interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-runtime / tests / compose_task_test.rs

775 lines · 27168 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! NEXT-PHASE-1 cut 1b + 2: RunComposeTask, ComposeNote, ComposeRecall and
17//! RecoverComposeHome through omega COMPOSITION-2.
18//!
19//! With librx_compose.a linked (aien-omega-compose built with
20//! AIEN_OMEGA_COMPOSE_DIR, see its README) these run the real composition;
21//! in a stub build they check that the bridge reports the missing library.
22//!
23//! The retry loop, the budgets and the task kind are observed through
24//! `ComposeBridge::run_task` (tests/support/compose_harness.rs): the prompt and
25//! time limit each model call is handed, which proposer was asked, and the
26//! report. The rules under a short injected budget are in
27//! compose_budget_test.rs; the budget settings themselves in compose_env_test.rs.
28#[path = "support/compose_harness.rs"]
29mod compose_harness;
30#[path = "support/home_guard.rs"]
31mod home_guard;
32
33use aien_runtime::control::{ComposeRecallReport, ComposeTaskReport, ControlResponse};
34use aien_runtime::{
35 check_file_proposal, parse_file_proposal, ComposeBridge, ComposeProposer, Generation,
36};
37use compose_harness::{reply, Asked, Harness};
38use std::sync::Arc;
39use std::time::Duration;
40
41/// A goal that names no destination: the model names the file.
42const NO_DEST_GOAL: &str = "remember the constraints and propose one change";
43
44fn proposer() -> ComposeProposer {
45 Arc::new(|prompt: &str, _limit: std::time::Duration| {
46 assert!(prompt.contains("Authorized workspace:"));
47 assert!(prompt.contains("filename: <relative path>"));
48 Ok(Generation {
49 text: "filename: NOTES.md\nconstraint: keep main green\n".to_string(),
50 tokens: 12,
51 finish_reason: None,
52 ..Default::default()
53 })
54 })
55}
56
57fn report(r: ControlResponse) -> ComposeTaskReport {
58 match r {
59 ControlResponse::ComposeTaskResult(r) => *r,
60 other => panic!("expected ComposeTaskResult, got {other:?}"),
61 }
62}
63
64fn recalled(r: ControlResponse) -> ComposeRecallReport {
65 match r {
66 ControlResponse::ComposeRecalled(r) => *r,
67 other => panic!("expected ComposeRecalled, got {other:?}"),
68 }
69}
70
71fn snapshot(dir: &std::path::Path) -> Vec<(String, Vec<u8>)> {
72 let mut v: Vec<(String, Vec<u8>)> = std::fs::read_dir(dir)
73 .unwrap()
74 .map(|e| {
75 let e = e.unwrap();
76 (
77 e.file_name().to_string_lossy().into_owned(),
78 std::fs::read(e.path()).unwrap_or_default(),
79 )
80 })
81 .collect();
82 v.sort();
83 v
84}
85
86#[test]
87fn compose_task_commits_and_survives_restart() {
88 let _home = home_guard::home_slot();
89 let tmp = tempfile::tempdir().unwrap();
90 let home = tmp.path().join("compose");
91 let ws = tmp.path().join("workspace");
92 std::fs::create_dir_all(&ws).unwrap();
93 std::fs::write(ws.join("README.md"), b"project\n").unwrap();
94 let ws_before = snapshot(&ws);
95
96 let bridge = ComposeBridge::new(home.clone(), proposer(), "test:fixed-proposer");
97 let resp = bridge.run_task(
98 "remember the constraints and propose one change",
99 ws.to_str().unwrap(),
100 );
101 if !aien_omega_compose::LINKED {
102 match resp {
103 ControlResponse::Error(e) => assert!(e.contains("not linked"), "{e}"),
104 other => panic!("stub build must refuse, got {other:?}"),
105 }
106 return;
107 }
108 let r1 = report(resp);
109 assert!(r1.committed, "{r1:?}");
110 assert_eq!(r1.outcome, 1);
111 assert_eq!(r1.branch_count, 1);
112 assert_eq!(r1.winner, Some(0));
113 assert_eq!(r1.aegis_pass_mask & 1, 1);
114 assert!(
115 r1.cx_goal != 0
116 && r1.cx_evidence != 0
117 && r1.cx_promotion != 0
118 && !r1.cx_candidates.is_empty()
119 );
120 assert_eq!(
121 r1.proposal.as_deref(),
122 Some("filename: NOTES.md\nconstraint: keep main green\n")
123 );
124 assert_eq!(r1.proposal_attempts.len(), 1, "{:?}", r1.proposal_attempts);
125 assert_eq!(r1.proposal_attempts[0].outcome, "parsed");
126 assert_eq!(r1.proposal_attempts[0].aegis.as_deref(), Some("pass"));
127 assert_eq!(r1.proposal_attempts[0].tokens, 12);
128 assert_eq!(r1.machine_id.len(), 64);
129 assert_eq!(r1.proposal_path.as_deref(), Some("NOTES.md"));
130 assert_eq!(
131 r1.proposal_content_sha256.as_deref(),
132 Some(aien_omega_compose::hex(
133 &<sha2::Sha256 as sha2::Digest>::digest(b"constraint: keep main green\n")
134 ))
135 .as_deref()
136 );
137 let c = match bridge.note("constraint", "keep main green", &[]) {
138 ControlResponse::ComposeNoted(n) => n,
139 other => panic!("note: {other:?}"),
140 };
141 assert!(c.id > r1.cx_promotion);
142 assert!(matches!(
143 bridge.note("effect", "x", &[1 << 40]),
144 ControlResponse::Error(_)
145 ));
146 assert!(matches!(
147 bridge.note("rumour", "x", &[]),
148 ControlResponse::Error(_)
149 ));
150 let before = recalled(bridge.recall(&[r1.cx_promotion], Some(c.id)));
151 let cited = [
152 r1.cx_goal,
153 r1.cx_candidates[0],
154 r1.cx_evidence,
155 r1.cx_promotion,
156 ];
157 let digests: Vec<String> = cited
158 .iter()
159 .map(|&id| bridge.record_digest(id).unwrap())
160 .collect();
161 drop(bridge);
162
163 // restart: same home, same machine, cited records unchanged
164 let bridge = ComposeBridge::new(home.clone(), proposer(), "test:fixed-proposer");
165 for (id, d) in cited.iter().zip(digests.iter()) {
166 assert_eq!(
167 &bridge.record_digest(*id).unwrap(),
168 d,
169 "record {id} after restart"
170 );
171 }
172 let r2 = report(bridge.run_task("second goal", ws.to_str().unwrap()));
173 assert!(r2.committed);
174 assert_eq!(
175 r2.machine_id, r1.machine_id,
176 "same AienMachineId across restart"
177 );
178 assert!(r2.cx_evidence > r1.cx_evidence);
179 let after = recalled(bridge.recall(&[r1.cx_promotion], Some(c.id)));
180 assert_eq!(after.machine_id, before.machine_id);
181 assert_eq!(
182 after.prefix_digest, before.prefix_digest,
183 "records 1..=S1 unchanged"
184 );
185 assert_eq!(after.cited, before.cited);
186 let k = after
187 .host
188 .iter()
189 .find(|h| h.id == c.id)
190 .expect("constraint recalled after restart");
191 assert_eq!(k.note.as_deref(), Some("constraint"));
192 assert_eq!(k.text.as_deref(), Some("keep main green"));
193 assert!(k.verified);
194
195 // containment: nothing in the workspace changed (this cut executes no effect)
196 assert_eq!(snapshot(&ws), ws_before);
197 // the home holds only the composition files (no staged-branch leftovers)
198 for (name, _) in snapshot(&home) {
199 assert!(
200 name == "machine.id" || name == "cortex.cx" || name.starts_with("jspace"),
201 "unexpected file in compose home: {name}"
202 );
203 }
204}
205
206#[test]
207fn failing_model_commits_nothing() {
208 let _home = home_guard::home_slot();
209 if !aien_omega_compose::LINKED {
210 return;
211 }
212 let tmp = tempfile::tempdir().unwrap();
213 let ws = tmp.path().join("ws");
214 std::fs::create_dir_all(&ws).unwrap();
215 let bridge = ComposeBridge::new(
216 tmp.path().join("compose"),
217 Arc::new(|_: &str, _: std::time::Duration| Err("model unavailable".to_string())),
218 "test:failing",
219 );
220 let r = report(bridge.run_task("goal", ws.to_str().unwrap()));
221 assert!(!r.committed, "{r:?}");
222 assert_eq!(r.winner, None);
223 assert_eq!(r.proposal, None);
224}
225
226#[test]
227fn bad_workspace_is_refused() {
228 let tmp = tempfile::tempdir().unwrap();
229 let bridge = ComposeBridge::new(tmp.path().join("compose"), proposer(), "test");
230 match bridge.run_task("goal", tmp.path().join("missing").to_str().unwrap()) {
231 ControlResponse::Error(e) => assert!(e.contains("workspace"), "{e}"),
232 other => panic!("expected Error, got {other:?}"),
233 }
234}
235
236#[test]
237fn proposal_template_parser() {
238 // filename line present
239 let p = check_file_proposal(
240 "filename: NOTES.md
241line one
242",
243 )
244 .unwrap();
245 assert_eq!(
246 (p.path.as_str(), p.content.as_str()),
247 (
248 "NOTES.md",
249 "line one
250"
251 )
252 );
253 let p = check_file_proposal(
254 "
255**Filename: `docs/plan.txt`**
256
257```
258step 1
259step 2
260```
261",
262 )
263 .unwrap();
264 assert_eq!(
265 (p.path.as_str(), p.content.as_str()),
266 (
267 "docs/plan.txt",
268 "step 1
269step 2
270"
271 )
272 );
273 // filename line absent: refused, even when a path appears later
274 for t in [
275 "Sure, I can help with that!",
276 "NOTES.md
277line one
278",
279 "To create NOTES.md:
280filename: NOTES.md
281x
282",
283 "",
284 ] {
285 assert!(check_file_proposal(t).is_err(), "{t:?}");
286 assert!(parse_file_proposal(t).is_none());
287 }
288 assert!(check_file_proposal(
289 "NOTES.md
290x"
291 )
292 .unwrap_err()
293 .contains("no filename line"));
294 // outside the workspace: refused before AEGIS
295 for t in [
296 "filename: /etc/passwd
297root
298",
299 "filename: ../escape.txt
300x
301",
302 "filename: docs/../../escape.txt
303x
304",
305 "filename: ~/.bashrc
306x
307",
308 ] {
309 let e = check_file_proposal(t).unwrap_err();
310 assert!(e.contains("outside the workspace"), "{t:?}: {e}");
311 }
312 assert!(check_file_proposal(
313 "filename: a b.txt
314x
315"
316 )
317 .is_err());
318 assert!(check_file_proposal(
319 "filename: NOTES.md
320
321
322"
323 )
324 .unwrap_err()
325 .contains("empty content"));
326 // deterministic
327 assert_eq!(
328 check_file_proposal(
329 "filename: a.txt
330z
331"
332 ),
333 check_file_proposal(
334 "filename: a.txt
335z
336"
337 )
338 );
339}
340
341#[test]
342#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
343fn retry_is_capped_and_recorded() {
344 let _home = home_guard::home_slot();
345 let chatty = |text: &'static str, tokens: usize| {
346 move |_: usize, _: &str, _: Duration| {
347 Ok(Generation {
348 text: text.into(),
349 tokens,
350 finish_reason: None,
351 ..Default::default()
352 })
353 }
354 };
355 // never parses: exactly 3 calls, all refused
356 {
357 let h = Harness::new(Arc::new(chatty("Sure!", 2)));
358 let r = h.run(NO_DEST_GOAL).unwrap();
359 assert!(r
360 .proposer_error
361 .as_deref()
362 .unwrap()
363 .contains("no filename line"));
364 assert!(r.proposal.is_none() && !r.committed, "{r:?}");
365 assert_eq!(h.calls().len(), 3);
366 let a = &r.proposal_attempts;
367 assert_eq!(a.len(), 3);
368 assert!(a
369 .iter()
370 .all(|x| x.outcome == "refused" && x.tokens == 2 && x.text_sha256.is_some()));
371 assert_eq!(
372 a.iter().map(|x| x.attempt).collect::<Vec<_>>(),
373 vec![1, 2, 3]
374 );
375 }
376 // second attempt parses: stops there, and the retry prompt names the refusal
377 {
378 let h = Harness::new(Arc::new(|n, _: &str, _: Duration| {
379 Ok(Generation {
380 text: if n == 1 {
381 "Sure!"
382 } else {
383 "filename: a.txt\nok\n"
384 }
385 .into(),
386 tokens: 3,
387 finish_reason: None,
388 ..Default::default()
389 })
390 }));
391 let r = h.run(NO_DEST_GOAL).unwrap();
392 assert_eq!(
393 r.proposal.as_deref(),
394 Some("filename: a.txt\nok\n"),
395 "{r:?}"
396 );
397 let a = &r.proposal_attempts;
398 assert_eq!(a.len(), 2);
399 assert_eq!(
400 (a[0].outcome.as_str(), a[1].outcome.as_str()),
401 ("refused", "parsed")
402 );
403 let p: Vec<String> = h.calls().into_iter().map(|c| c.prompt).collect();
404 assert_eq!(p.len(), 2);
405 assert!(!p[0].contains("previous answer was refused"), "{}", p[0]);
406 assert!(
407 p[1].starts_with(&format!("{}\n", p[0]))
408 && p[1].contains("previous answer was refused"),
409 "{}",
410 p[1]
411 );
412 }
413 // The budget rule (attempt 2 does not start when less than the per-attempt
414 // budget is left) needs a short budget: compose_budget_test.rs, same name.
415 // model errors are recorded, not retried past the cap
416 {
417 let h = Harness::new(Arc::new(|_, _: &str, _: Duration| {
418 Err::<Generation, _>("model proposal exceeded 25000 ms".to_string())
419 }));
420 let r = h.run(NO_DEST_GOAL).unwrap();
421 let a = &r.proposal_attempts;
422 assert_eq!(h.calls().len(), a.len());
423 assert!(
424 a.len() <= 3 && a.iter().all(|x| x.outcome == "timeout"),
425 "{a:?}"
426 );
427 }
428}
429
430/// ACCEPTANCE-v3 Section 3b at full scale, through the bridge with the default
431/// edit budget: a slow (cold) attempt 1 of 16.1 s no longer blocks attempt 2;
432/// attempt 2 of 11.6 s leaves too little for 3. Takes about 28 s.
433#[test]
434#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
435fn measured_attempt_budget_admits_a_second_attempt() {
436 let _home = home_guard::home_slot();
437 // 2 839 + 896 + 47 x 166.6 + 60 ms, the measured full retry attempt, fits
438 // the 12 000 ms per-attempt budget of an edit
439 let measured: [f64; 4] = [2_839.0, 896.0, 47.0 * 166.6, 60.0];
440 assert!(measured.iter().sum::<f64>() <= 12_000.0);
441 let h = Harness::new(Arc::new(|n, _: &str, _: Duration| {
442 std::thread::sleep(Duration::from_millis(if n == 1 { 16_100 } else { 11_600 }));
443 Ok(Generation {
444 text: "Goal: echo".into(),
445 tokens: 48,
446 finish_reason: None,
447 ..Default::default()
448 })
449 }));
450 h.write("notes.md", "# notes\n");
451 let r = h.run("add a line to notes.md").unwrap();
452 let c = h.calls();
453 assert_eq!(c.len(), 2, "{r:?}");
454 assert!(c.iter().all(|c| c.asked == Asked::Edit));
455 // the default (AIEN_COMPOSE_EDIT_BUDGET_MS unset): omega's 30 s wait less 1 s
456 assert!(c[0].limit <= Duration::from_secs(29), "{:?}", c[0].limit);
457 assert!(c[0].limit > Duration::from_secs(28), "{:?}", c[0].limit);
458 assert_eq!(r.proposal_attempts.len(), 2, "{r:?}");
459 let reason = r.proposer_error.unwrap();
460 assert!(
461 reason.contains("no attempt 3") && reason.contains("< 12000 ms per-attempt budget"),
462 "{reason}"
463 );
464}
465
466#[test]
467fn unparseable_proposal_fails_the_aegis_contract() {
468 let _home = home_guard::home_slot();
469 if !aien_omega_compose::LINKED {
470 return;
471 }
472 let tmp = tempfile::tempdir().unwrap();
473 let ws = tmp.path().join("ws");
474 std::fs::create_dir_all(&ws).unwrap();
475 let bridge = ComposeBridge::new(
476 tmp.path().join("compose"),
477 Arc::new(|_: &str, _: std::time::Duration| {
478 Ok(Generation {
479 text: "Sure, I can help with that!".to_string(),
480 tokens: 8,
481 finish_reason: None,
482 ..Default::default()
483 })
484 }),
485 "test:chatty",
486 );
487 let r = report(bridge.run_task("goal", ws.to_str().unwrap()));
488 assert!(!r.committed, "{r:?}");
489 assert_eq!(r.aegis_pass_mask & 1, 0);
490 assert_eq!(r.proposal_path, None);
491 // Refused by the template parser before AEGIS, retried up to the cap (3).
492 assert_eq!(r.proposal_attempts.len(), 3, "{r:?}");
493 assert!(r
494 .proposal_attempts
495 .iter()
496 .all(|a| a.outcome == "refused" && a.aegis.is_none()));
497 assert!(r
498 .proposer_error
499 .as_deref()
500 .unwrap_or("")
501 .contains("no filename line"));
502}
503
504#[test]
505fn torn_home_is_refused_by_name_then_recovered() {
506 let _home = home_guard::home_slot();
507 if !aien_omega_compose::LINKED {
508 return;
509 }
510 let tmp = tempfile::tempdir().unwrap();
511 let home = tmp.path().join("compose");
512 let ws = tmp.path().join("ws");
513 std::fs::create_dir_all(&ws).unwrap();
514 let bridge = ComposeBridge::new(home.clone(), proposer(), "test");
515 let r1 = report(bridge.run_task("goal", ws.to_str().unwrap()));
516 assert!(r1.committed);
517 let all = recalled(bridge.recall(&[], Some(r1.cx_promotion)));
518 drop(bridge);
519 let cx = home.join("cortex.cx");
520 let len = std::fs::metadata(&cx).unwrap().len();
521 std::fs::OpenOptions::new()
522 .write(true)
523 .open(&cx)
524 .unwrap()
525 .set_len(len - 5)
526 .unwrap();
527
528 let bridge = ComposeBridge::new(home.clone(), proposer(), "test");
529 for _ in 0..2 {
530 match bridge.note("constraint", "x", &[]) {
531 ControlResponse::Error(e) => {
532 assert!(e.contains("E_TORN") && e.contains("compose recover"), "{e}")
533 }
534 other => panic!("torn home must be refused, got {other:?}"),
535 }
536 assert_eq!(
537 std::fs::metadata(&cx).unwrap().len(),
538 len - 5,
539 "refusal wrote"
540 );
541 }
542 let rep = match bridge.recover() {
543 ControlResponse::ComposeRecovered(r) => *r,
544 other => panic!("recover: {other:?}"),
545 };
546 assert!(rep.repaired && rep.tail_torn && rep.opens, "{rep:?}");
547 assert_eq!((rep.cause, rep.cut_hi), (-8, len - 5));
548 assert!(rep.dropped_records >= 1 && rep.repair_record == rep.records_kept + 1);
549 let after = recalled(bridge.recall(&[], Some(r1.cx_promotion)));
550 assert_eq!(
551 after.prefix_digest, all.prefix_digest,
552 "old records unchanged"
553 );
554 assert_eq!(after.machine_id, all.machine_id);
555 assert!(after
556 .host
557 .iter()
558 .any(|h| h.id == rep.repair_record && h.note.as_deref() == Some("repair_tail")));
559 let r2 = report(bridge.run_task("goal after recover", ws.to_str().unwrap()));
560 assert!(r2.committed);
561}
562
563/// ACCEPTANCE-v5 Q3: the proposer's stop reason reaches every attempt record,
564/// so the receipt can tell end of sequence from the token limit.
565#[test]
566#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
567fn finish_reason_is_recorded_per_attempt() {
568 let _home = home_guard::home_slot();
569 let h = Harness::new(Arc::new(|n, _: &str, _: Duration| {
570 Ok(if n == 1 {
571 Generation {
572 text: "Goal: echo".into(),
573 tokens: 48,
574 finish_reason: Some("max_tokens".into()),
575 ..Default::default()
576 }
577 } else {
578 Generation {
579 text: "filename: NOTES.md\nkeep changes in the workspace\n".into(),
580 tokens: 11,
581 finish_reason: Some("eos".into()),
582 ..Default::default()
583 }
584 })
585 }));
586 let r = h.run("write a short note into NOTES.md").unwrap();
587 assert!(r.proposal.is_some(), "{r:?}");
588 let a = &r.proposal_attempts;
589 assert_eq!(a.len(), 2, "{a:?}");
590 assert_eq!(a[0].finish_reason.as_deref(), Some("max_tokens"));
591 assert_eq!(a[1].finish_reason.as_deref(), Some("eos"));
592 // An attempt record without the field (v1..v4 receipts) still reads.
593 let old = r#"{"attempt":1,"ms":1,"tokens":48,"outcome":"parsed","reason":null,
594 "text_sha256":null,"text":null,"aegis":null}"#;
595 let parsed: aien_runtime::ProposalAttempt = serde_json::from_str(old).unwrap();
596 assert_eq!(parsed.finish_reason, None);
597}
598
599#[test]
600fn finish_reason_labels_match_acceptance_v5() {
601 use aien_inference_abi::FinishReason;
602 assert_eq!(
603 aien_runtime::finish_reason_label(&FinishReason::StopToken),
604 "eos"
605 );
606 assert_eq!(
607 aien_runtime::finish_reason_label(&FinishReason::LengthLimit),
608 "max_tokens"
609 );
610 assert_eq!(
611 aien_runtime::finish_reason_label(&FinishReason::Aborted),
612 "aborted"
613 );
614 assert_eq!(
615 aien_runtime::finish_reason_label(&FinishReason::Preempted),
616 "preempted"
617 );
618}
619
620// A file whose own content holds fenced blocks must not be cut at the
621// first inner fence (DIAGNOSTIC-LONG-1 task D5: a 649-token FAQ was saved
622// as 4 lines).
623#[test]
624fn proposal_fence_inner_block_kept() {
625 let p = check_file_proposal(
626 "filename: docs/FAQ.md\n```markdown\n# FAQ\n\nRun:\n```bash\nls -l\n```\nDone.\n```\nTrailing prose.\n",
627 )
628 .unwrap();
629 assert_eq!(p.path, "docs/FAQ.md");
630 assert_eq!(p.content, "# FAQ\n\nRun:\n```bash\nls -l\n```\nDone.\n");
631}
632
633#[test]
634fn proposal_fence_d5_reply_shape() {
635 // D5 reply, trimmed to its first two blocks and closed by the outer fence.
636 let reply = include_str!("fixtures/d5_reply_trimmed.txt");
637 let reply = format!("{reply}```\n");
638 let p = check_file_proposal(&reply).unwrap();
639 assert_eq!(p.path, "docs/FAQ.md");
640 assert_eq!(p.content.matches("```bash").count(), 2, "{}", p.content);
641 assert_eq!(p.content.lines().count(), 14, "{}", p.content);
642 assert!(p.content.ends_with("```\n"));
643 assert!(p.content.contains("sudo curl"));
644 assert!(p.content.lines().count() > 4, "old parser kept 4 lines");
645}
646
647#[test]
648fn proposal_fence_unbalanced_takes_last_bare_fence() {
649 // Inner block opened and never closed: the last bare fence ends the file.
650 let p = check_file_proposal("filename: a.md\n```md\ntext\n```bash\nls\nmore\n```\n").unwrap();
651 assert_eq!(p.content, "text\n```bash\nls\nmore\n");
652 // No bare fence at all: nothing to close, whole body kept (as before).
653 let p = check_file_proposal("filename: a.md\n```md\ntext\n```bash\nls\n").unwrap();
654 assert_eq!(p.content, "text\n```bash\nls\n");
655}
656
657#[test]
658fn proposal_fence_four_backtick_outer() {
659 let p = check_file_proposal(
660 "filename: a.md\n````markdown\nintro\n```\nbare inner\n```\n```bash\nls\n```\n````\n",
661 )
662 .unwrap();
663 assert_eq!(p.content, "intro\n```\nbare inner\n```\n```bash\nls\n```\n");
664}
665
666#[test]
667fn proposal_fence_plain_replies_unchanged() {
668 let p = check_file_proposal("filename: a.txt\nx\ny\n").unwrap();
669 assert_eq!(p.content, "x\ny\n");
670 let p = check_file_proposal("filename: a.txt\n```\nx\n```\nthanks\n").unwrap();
671 assert_eq!(p.content, "x\n");
672 let p = check_file_proposal("filename: a.txt\n```text\nx\n").unwrap();
673 assert_eq!(p.content, "x\n");
674}
675
676// Several code examples in one document and normal prose after the last one:
677// every byte is kept, in the fenced reply shape and in the unfenced shape.
678#[test]
679fn proposal_fence_many_examples_and_trailing_text_keep_every_byte() {
680 let doc = "# Guide\n\nStep one:\n```bash\nls -l\n```\nStep two:\n```python\nprint(1)\n```\nStep three:\n```\nplain\n```\nNotes after the last example.\nAnd one more line.\n";
681 // Outer fence with a label: inner fences nest, nothing after is lost.
682 let p = check_file_proposal(&format!("filename: g.md\n```markdown\n{doc}```\n")).unwrap();
683 assert_eq!(p.content, doc);
684 // Longer outer fence: inner bare and labelled fences are all content.
685 let p = check_file_proposal(&format!("filename: g.md\n````markdown\n{doc}````\n")).unwrap();
686 assert_eq!(p.content, doc);
687 // No outer fence at all: the document is taken whole.
688 let p = check_file_proposal(&format!("filename: g.md\n{doc}")).unwrap();
689 assert_eq!(p.content, doc);
690}
691
692/// A task that names an existing file is an edit (29 s); a task with no
693/// existing target creates a new document (120 s). Omega's wait follows by +1 s.
694/// The per-attempt budgets (edit 12 s; document 30 s, capped at half a small
695/// custom budget) need short budgets: compose_budget_test.rs, same name.
696#[test]
697#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
698fn kind_selects_budget() {
699 use std::sync::atomic::Ordering;
700 let _home = home_guard::home_slot();
701 let waits: Arc<parking_lot::Mutex<Vec<u32>>> = Arc::default();
702 let w = waits.clone();
703 let h = Harness::new(Arc::new(move |_, p: &str, _: Duration| {
704 w.lock()
705 .push(aien_omega_compose::LAST_WAIT_MS.load(Ordering::SeqCst));
706 reply(if p.contains("The file notes.md already exists") {
707 "filename: notes.md\n# notes\nnew line\n"
708 } else {
709 "filename: faq.md\nq and a\n"
710 })
711 }));
712 h.write("notes.md", "# notes\n");
713 let edit = h.run("add a line to notes.md").unwrap();
714 let new = h.run("write a new file faq.md").unwrap();
715 assert!(
716 edit.proposal.is_some() && new.proposal.is_some(),
717 "{edit:?} {new:?}"
718 );
719 let c = h.calls();
720 assert_eq!(c.len(), 2, "{c:?}");
721 assert_eq!((c[0].asked, c[1].asked), (Asked::Edit, Asked::Document));
722 assert!(c[0].limit <= Duration::from_secs(29), "{:?}", c[0].limit);
723 assert!(c[0].limit > Duration::from_secs(28), "{:?}", c[0].limit);
724 assert!(c[1].limit <= Duration::from_secs(120), "{:?}", c[1].limit);
725 assert!(c[1].limit > Duration::from_secs(119), "{:?}", c[1].limit);
726 assert_eq!(*waits.lock(), vec![30_000, 121_000]);
727}
728
729/// The two ways a long reply can fail leave different, stable reasons: a cut
730/// at the token limit is refused ("reply cut at the token limit ...
731/// finish_reason max_tokens"), a slow model times out ("model proposal
732/// exceeded N ms"). Neither text contains the other's marker.
733#[test]
734#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
735fn token_cut_and_wall_clock_reasons_are_distinct() {
736 let _home = home_guard::home_slot();
737 let goal = "write a short note into a.md";
738 // token-limit cut
739 let h = Harness::new(Arc::new(|_, _: &str, _: Duration| {
740 Ok(Generation {
741 text: "filename: a.md\nline\n".into(),
742 tokens: 1024,
743 finish_reason: Some("max_tokens".into()),
744 ..Default::default()
745 })
746 }));
747 let r = h.run(goal).unwrap();
748 assert!(
749 r.proposal.is_none() && r.uncommitted_proposal.is_none(),
750 "a cut reply is never a proposal: {r:?}"
751 );
752 let why = r.proposer_error.unwrap();
753 assert_eq!(r.proposal_attempts[0].outcome, "refused");
754 assert!(
755 why.contains("reply cut at the token limit after 1024 tokens (finish_reason max_tokens)"),
756 "{why}"
757 );
758 assert!(!why.contains("exceeded"), "{why}");
759 drop(h);
760 // wall-clock timeout (the text the daemon proposer emits)
761 let h = Harness::new(Arc::new(|_, _: &str, limit: Duration| {
762 Err(format!("model proposal exceeded {} ms", limit.as_millis()))
763 }));
764 let r = h.run(goal).unwrap();
765 let why = r.proposer_error.expect("timed out");
766 assert_eq!(r.proposal_attempts[0].outcome, "timeout");
767 assert!(
768 why.starts_with("model proposal exceeded ") && why.ends_with(" ms"),
769 "{why}"
770 );
771 assert!(
772 !why.contains("token limit") && !why.contains("max_tokens"),
773 "{why}"
774 );
775}