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
GitHub aien-dev/aien-sovereign-core-mv#287 (code only)
Fetch it
curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/cfb0917491eb4507.bundle -o cfb0917491eb4507.bundle git fetch cfb0917491eb4507.bundle refs/pull/287/head
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
287
80bb0a76332304d8f46611f849f6eaac966308e2
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":287,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/287","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:41Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.crumb b/.crumb index 4d05553a..cb10a8ba 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:c5269f93385287c09996ff41f0247f72de9237a2317f47c94c51273d6a0acef1", - "compiled_at": "2026-10-07T17:04:52Z", + "compiled_at": "2026-10-07T18:10:03Z", "compiler": "crumb-compile/1", - "digest": "sha256:4d7842dd2a1b4b3edb2776d65b09db27e35cf7a75bc9955cdbf55b150d4112c8", + "digest": "sha256:67eac8376516a99bd28dccff7cc549b1a13ccb774a966b7ab25e63cdd7afca87", "evidence_files": 186, "evidence_root": "sha256:fbe849218d18dc4b21a74410fdd8f7d98431a1d0123a0c69264386f770da4db4", - "files": 1225, - "generated_at_commit": "5c303a0666d47e0ce4fa8111e8eb7fb8afaffb04", - "source_tree": "sha256:a2a8cd8ac5a06e1a2a26b170688042a27fd50acef4e008aa47870d4694faa1ca" + "files": 1230, + "generated_at_commit": "263f0e1b653711e53ce67eb8c70c96bafcf746b8", + "source_tree": "sha256:291f9dc69ed260ae285b27c32dbd7dcfb9b84dc08068e442bac91cb4c7dd0067" } }, "history": [], diff --git a/crates/aien-runtime/src/control.rs b/crates/aien-runtime/src/control.rs index 85c93095..791c3516 100644 --- a/crates/aien-runtime/src/control.rs +++ b/crates/aien-runtime/src/control.rs @@ -365,6 +365,10 @@ pub struct ComposeTaskReport { /// Every proposal the model Skill made for this task (ACCEPTANCE-v2 3b). #[serde(default)] pub proposal_attempts: Vec<ProposalAttempt>, + /// Requirements recognized in the goal (crate::requirements); the only + /// ones checked. Empty = none recognized, nothing checked. + #[serde(default)] + pub requirements_recognized: Vec<String>, /// "model" when the Skill ran inference, or the stub label. pub proposer: String, } @@ -400,6 +404,10 @@ pub struct ProposalAttempt { /// sha256 of the prompt ids, each 4 little-endian bytes (NEXT-PHASE-1 v6 R1). #[serde(default)] pub prompt_ids_sha256: Option<String>, + /// Requirements of the goal this attempt's complete document failed + /// (crate::requirements); empty when none failed or none were recognized. + #[serde(default)] + pub unmet_requirements: Vec<String>, } /// The record `ComposeNote` appended. diff --git a/crates/aien-runtime/src/lib.rs b/crates/aien-runtime/src/lib.rs index b52be6f0..5ceea682 100644 --- a/crates/aien-runtime/src/lib.rs +++ b/crates/aien-runtime/src/lib.rs @@ -8,6 +8,7 @@ pub mod context; pub mod control; pub mod cortex_mark; pub mod effects; +pub mod requirements; pub mod rsi; pub mod sequence; pub mod server; diff --git a/crates/aien-runtime/src/requirements.rs b/crates/aien-runtime/src/requirements.rs new file mode 100644 index 00000000..598d2696 --- /dev/null +++ b/crates/aien-runtime/src/requirements.rs @@ -0,0 +1,344 @@ +//! Requirement validation for composed documents. +//! +//! A task goal can state a measurable requirement ("in at least 20 lines"). +//! Before this module nothing checked it: a 13-line answer to such a goal was +//! approved and committed. This module defines a small typed set of +//! requirements, extracts them deterministically from the goal text, and +//! checks the COMPLETE parsed document (the content that would be saved). +//! +//! ## Supported requirements (everything else is NOT extracted) +//! +//! Extraction matches the exact word sequence `at least|at most N <noun>` +//! (case-insensitive, N written in digits, N >= 1, trailing punctuation on a +//! word ignored) and `include|contain the phrase "<text>"` (double quotes). +//! A goal that states a requirement in any other wording is not covered and +//! gets no check; `ComposeTaskReport::requirements_recognized` lists exactly +//! what was recognized. +//! +//! | goal wording | requirement | how it is counted | +//! |-----------------------------|------------------|-------------------| +//! | `at least N lines` | `MinLines(N)` | non-empty lines (a line with a non-whitespace character) | +//! | `at most N lines` | `MaxLines(N)` | non-empty lines | +//! | `at least N items` | `MinItems(Items, N)` | markdown list items: a line starting (after indentation) with `- `, `* `, `+ ` or `<digits>. ` / `<digits>) ` | +//! | `at least N steps` | `MinItems(Steps, N)` | numbered list items only: `<digits>. ` / `<digits>) ` | +//! | `at least N sections` | `MinItems(Sections, N)` | markdown headings: 1 to 6 `#` then a space then text | +//! | `at least N questions` | `MinItems(Questions, N)` | non-empty lines whose last character is `?` | +//! | `include the phrase "X"` | `RequiredPhrases([X])` | case-insensitive substring of the document | +//! +//! `item`, `step`, `section`, `question` (singular) are accepted too. +//! +//! ## What a requirement is judged on +//! +//! The COMPLETE document that would be saved (in edit mode the merged file, +//! not the model's reply). An edit only adds lines, so a prior file that +//! already exceeds a `MaxLines` is refused before any attempt. +//! +//! Counting: `MinLines`/`MaxLines` count every non-empty line of the file, +//! INCLUDING code lines and code-fence marker lines. Sections, questions, +//! items and steps skip fenced code blocks (``` or ~~~, CommonMark close +//! rule: same marker, at least as long, no info string; an unclosed fence +//! runs to the end) and the fence lines themselves, so a `# comment` or a +//! `- x` inside a code block is not a heading or an item. +//! +//! Wording rules (see [`extract`]): the noun must end its clause (no +//! "of/per/each/in/with ..." after it), negated wording is not extracted, +//! and emphasis or quotes around the wording are not recognized. + +/// What a `MinItems` requirement counts. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ItemKind { + Items, + Steps, + Sections, + Questions, +} + +impl ItemKind { + fn noun(self) -> &'static str { + match self { + ItemKind::Items => "list items", + ItemKind::Steps => "numbered steps", + ItemKind::Sections => "headings", + ItemKind::Questions => "questions", + } + } +} + +/// One measurable requirement on a document. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Requirement { + MinLines(usize), + MaxLines(usize), + MinItems(ItemKind, usize), + RequiredPhrases(Vec<String>), +} + +impl Requirement { + /// Short stable label, as recorded in the receipt. + pub fn label(&self) -> String { + match self { + Requirement::MinLines(n) => format!("at least {n} non-empty lines"), + Requirement::MaxLines(n) => format!("at most {n} non-empty lines"), + Requirement::MinItems(k, n) => format!("at least {n} {}", k.noun()), + Requirement::RequiredPhrases(p) => { + let q: Vec<String> = p.iter().map(|x| format!("\"{x}\"")).collect(); + format!("the phrase {}", q.join(", ")) + } + } + } + + /// None when met, else the unmet requirement with what was found. + pub fn check(&self, content: &str) -> Option<String> { + let label = self.label(); + match self { + Requirement::MinLines(n) => { + let c = non_empty_lines(content); + (c < *n).then(|| format!("{label}, found {c}")) + } + Requirement::MaxLines(n) => { + let c = non_empty_lines(content); + (c > *n).then(|| format!("{label}, found {c}")) + } + Requirement::MinItems(k, n) => { + let c = count_items(*k, content); + (c < *n).then(|| format!("{label}, found {c}")) + } + Requirement::RequiredPhrases(p) => { + let low = content.to_lowercase(); + let missing: Vec<String> = p + .iter() + .filter(|x| !low.contains(&x.to_lowercase())) + .map(|x| format!("\"{x}\"")) + .collect(); + (!missing.is_empty()).then(|| format!("{label}, missing {}", missing.join(", "))) + } + } + } +} + +fn non_empty_lines(s: &str) -> usize { + s.lines().filter(|l| !l.trim().is_empty()).count() +} + +fn numbered(t: &str) -> bool { + let d = t.chars().take_while(|c| c.is_ascii_digit()).count(); + d > 0 && matches!(t[d..].chars().next(), Some('.') | Some(')')) && t[d + 1..].starts_with(' ') +} + +/// A CommonMark code-fence line: its marker character (backtick or tilde), +/// run length (3 or more) and whether an info string follows the run. A +/// backtick fence whose info string holds a backtick is not a fence. +fn fence_marker(l: &str) -> Option<(char, usize, bool)> { + let t = l.trim_start(); + let c = t.chars().next().filter(|c| matches!(c, '`' | '~'))?; + let n = t.chars().take_while(|&x| x == c).count(); + if n < 3 { + return None; + } + let info = t[n..].trim(); + if c == '`' && info.contains('`') { + return None; + } + Some((c, n, !info.is_empty())) +} + +/// The lines of `s` that are NOT inside a fenced code block and are not a +/// fence marker line. A block opens at a fence line and closes at the first +/// later line with the same marker character, at least as long a run and no +/// info string (CommonMark); an unclosed block runs to the end. +fn prose_lines(s: &str) -> Vec<&str> { + let mut open: Option<(char, usize)> = None; + let mut out = Vec::new(); + for l in s.lines() { + match (open, fence_marker(l)) { + (None, Some((c, n, _))) => open = Some((c, n)), + (None, None) => out.push(l), + (Some((c, n)), Some((c2, n2, info))) if c2 == c && n2 >= n && !info => open = None, + (Some(_), _) => {} + } + } + out +} + +fn count_items(k: ItemKind, s: &str) -> usize { + prose_lines(s) + .into_iter() + .map(str::trim) + .filter(|t| match k { + ItemKind::Items => { + t.starts_with("- ") || t.starts_with("* ") || t.starts_with("+ ") || numbered(t) + } + ItemKind::Steps => numbered(t), + ItemKind::Sections => { + let h = t.chars().take_while(|&c| c == '#').count(); + (1..=6).contains(&h) && t[h..].starts_with(' ') && !t[h..].trim().is_empty() + } + ItemKind::Questions => t.ends_with('?'), + }) + .count() +} + +/// Every unmet requirement, each as a short sentence. Empty = all met. +pub fn unmet(reqs: &[Requirement], content: &str) -> Vec<String> { + reqs.iter().filter_map(|r| r.check(content)).collect() +} + +/// The refusal reason a retry prompt carries; None when all are met. +pub fn refusal_reason(reqs: &[Requirement], content: &str) -> Option<String> { + let u = unmet(reqs, content); + (!u.is_empty()).then(|| format!("unmet requirement: {}", u.join("; "))) +} + +fn clean(w: &str) -> &str { + w.trim_matches(|c: char| matches!(c, ',' | '.' | ';' | ':' | '!' | '?' | '(' | ')')) +} + +/// A word that ends its clause: it carries closing punctuation. +fn ends_clause(raw: &str) -> bool { + raw.ends_with([',', '.', ';', ':', '!', '?', ')']) +} + +/// Words allowed right after the counted noun or the quoted phrase: they +/// join a new clause instead of qualifying the count. +const CLAUSE_JOINERS: [&str; 9] = [ + "and", "or", "but", "so", "then", "because", "that", "which", "covering", +]; + +/// Words that turn a requirement into its opposite or into something else. +const NEGATORS: [&str; 20] = [ + "not", + "no", + "never", + "without", + "avoid", + "dont", + "don't", + "doesnt", + "doesn't", + "cant", + "can't", + "cannot", + "wont", + "won't", + "shouldnt", + "shouldn't", + "mustnt", + "mustn't", + "isnt", + "isn't", +]; + +/// True when one of the (at most 4) words before position `at` in the same +/// clause is a negator. `raw` are the whitespace-split lowercase words. +fn negated_before(raw: &[&str], at: usize) -> bool { + for i in (at.saturating_sub(4)..at).rev() { + if ends_clause(raw[i]) { + return false; + } + if NEGATORS.contains(&clean(raw[i])) { + return true; + } + } + false +} + +/// True when the clause ends right after word `at`: closing punctuation on +/// it, end of the goal, or a clause-joining word next. Anything else +/// ("of", "per", "each", "in", "with", ...) qualifies the count. +fn clause_ends_after(raw: &[&str], at: usize) -> bool { + ends_clause(raw[at]) + || raw + .get(at + 1) + .is_none_or(|n| CLAUSE_JOINERS.contains(&clean(n))) +} + +/// The requirements stated in `goal`, in the exact supported wordings only. +/// +/// Rules, all conservative (a requirement is extracted only when the +/// wording is certainly the supported claim; otherwise it is simply not +/// extracted and never appears in `requirements_recognized`): +/// - the count noun must END its clause: closing punctuation, end of goal, +/// or a joiner (`and or but so then because that which covering`). So +/// "3 lines of context", "5 items per category", "2 sections in the +/// file" are not extracted. +/// - a negator (`not no never without avoid` and the contractions) in the +/// same clause, up to 4 words before, cancels it: "do not include the +/// phrase "X"", "not at least 20 lines". No forbidden-phrase check exists, +/// so negated wording is reported unrecognized, not inverted. +/// - the quoted phrase must also end its clause ("... "X" in the title" is +/// not extracted). +/// - emphasis or quotes around the wording (`**at least 20 lines**`, +/// `"at least 20 lines"`, `at least **20** lines`) break the exact word +/// sequence and are not recognized (known limitation). +pub fn extract(goal: &str) -> Vec<Requirement> { + let low = goal.to_ascii_lowercase(); + let raw: Vec<&str> = low.split_whitespace().collect(); + let words: Vec<&str> = raw.iter().copied().map(clean).collect(); + let mut out: Vec<Requirement> = Vec::new(); + let mut push = |r: Requirement| { + if !out.contains(&r) { + out.push(r); + } + }; + for (i, w) in words.windows(4).enumerate() { + if w[0] != "at" || !(w[1] == "least" || w[1] == "most") { + continue; + } + if !w[2].chars().all(|c| c.is_ascii_digit()) || w[2].is_empty() { + continue; + } + let Ok(n) = w[2].parse::<usize>() else { + continue; + }; + if n == 0 || negated_before(&raw, i) || !clause_ends_after(&raw, i + 3) { + continue; + } + let least = w[1] == "least"; + match (least, w[3]) { + (true, "lines") => push(Requirement::MinLines(n)), + (false, "lines") => push(Requirement::MaxLines(n)), + (true, "items" | "item") => push(Requirement::MinItems(ItemKind::Items, n)), + (true, "steps" | "step") => push(Requirement::MinItems(ItemKind::Steps, n)), + (true, "sections" | "section") => push(Requirement::MinItems(ItemKind::Sections, n)), + (true, "questions" | "question") => push(Requirement::MinItems(ItemKind::Questions, n)), + _ => {} + } + } + // include|contain the phrase "X": the text is taken from the original + // goal (case kept), between straight double quotes. + let mut phrases: Vec<String> = Vec::new(); + for key in ["include the phrase \"", "contain the phrase \""] { + let mut from = 0; + while let Some(i) = low[from..].find(key) { + let key_at = from + i; + let start = key_at + key.len(); + let Some(len) = low[start..].find('"') else { + break; + }; + let end = start + len; + // Words before the key (negation) and the first word after the + // closing quote (qualifier), read from the same lowercase text. + let before: Vec<&str> = low[..key_at].split_whitespace().collect(); + let negated = negated_before(&before, before.len()); + let after = low[end + 1..].split_whitespace().next(); + let closes_clause = low[end + 1..].starts_with([',', '.', ';', ':', '!', '?', ')']) + || after.is_none_or(|n| CLAUSE_JOINERS.contains(&clean(n))); + if len > 0 + && !negated + && closes_clause + && goal.is_char_boundary(start) + && goal.is_char_boundary(end) + { + let p = goal[start..end].to_string(); + if !phrases.contains(&p) { + phrases.push(p); + } + } + from = end + 1; + } + } + if !phrases.is_empty() { + push(Requirement::RequiredPhrases(phrases)); + } + out +} diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index 28bd185b..46585d0a 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -1348,9 +1348,98 @@ pub fn propose_task_with_retries( budget: std::time::Duration, attempt_budget: std::time::Duration, max_attempts: u32, +) -> (Result<String, String>, Vec<ProposalAttempt>) { + propose_task_checked( + proposer, + base, + edit, + &[], + budget, + attempt_budget, + max_attempts, + ) +} + +fn new_attempt(k: u32) -> ProposalAttempt { + ProposalAttempt { + attempt: k, + ms: 0, + tokens: 0, + outcome: String::new(), + reason: None, + text_sha256: None, + text: None, + aegis: None, + finish_reason: None, + token_ids: None, + prompt_tokens: None, + prompt_ids_sha256: None, + unmet_requirements: Vec::new(), + } +} + +/// The approved-proposal path of the Skill: exactly one attempt that returns +/// `text` unchanged, through the same requirement check as a model reply (the +/// bytes a human approved are still refused, before any write, when the goal +/// states a requirement they do not meet). +pub(crate) fn propose_approved( + text: &str, + prompt: &str, + reqs: &[crate::requirements::Requirement], + budget: std::time::Duration, + attempt_budget: std::time::Duration, +) -> SkillOutput { + let text = text.to_string(); + let one = move |_: &str, _: std::time::Duration| { + Ok(Generation { + text: text.clone(), + finish_reason: Some("approved".into()), + ..Default::default() + }) + }; + propose_task_checked(&one, prompt, None, reqs, budget, attempt_budget, 1) +} + +/// `propose_task_with_retries` plus requirement validation: a parsed reply +/// whose COMPLETE content (the merged file in edit mode, i.e. the bytes that +/// would be saved) fails any of `reqs` is refused like a parse failure, the +/// unmet requirement(s) are recorded on the attempt, and the next attempt +/// gets them as its retry reason. `budget` is one deadline for the whole +/// task, started when this function starts and never reset per attempt. +/// Exhaustion returns Err: no proposal exists, so nothing is approved, +/// committed or written. +pub fn propose_task_checked( + proposer: &(dyn Fn(&str, std::time::Duration) -> Result<Generation, String> + Send + Sync), + base: &str, + edit: Option<(&str, &str)>, + reqs: &[crate::requirements::Requirement], + budget: std::time::Duration, + attempt_budget: std::time::Duration, + max_attempts: u32, ) -> (Result<String, String>, Vec<ProposalAttempt>) { let start = std::time::Instant::now(); let mut attempts: Vec<ProposalAttempt> = Vec::new(); + // An edit only adds lines (`merge_edit_reply` keeps every prior line), so a + // prior file that already breaks a MaxLines can never satisfy it: refuse + // now with a recorded reason instead of spending attempts. + if let Some((path, prior)) = edit { + let over: Vec<String> = reqs + .iter() + .filter(|r| matches!(r, crate::requirements::Requirement::MaxLines(_))) + .filter_map(|r| r.check(prior)) + .collect(); + if !over.is_empty() { + let why = format!( + "unmet requirement: the existing {path} already breaks it ({}) and an edit only adds lines", + over.join("; ") + ); + let mut a = new_attempt(1); + a.outcome = "refused".into(); + a.reason = Some(why.clone()); + a.unmet_requirements = over; + return (Err(why), vec![a]); + } + } let mut last_reason = "no attempt made".to_string(); let need_ms = (attempt_budget.as_millis() as u64).max(1); for k in 1..=max_attempts { @@ -1370,20 +1459,8 @@ pub fn propose_task_with_retries( let t0 = std::time::Instant::now(); let out = proposer(&prompt, remaining); let last_ms = t0.elapsed().as_millis() as u64; - let mut a = ProposalAttempt { - attempt: k, - ms: last_ms, - tokens: 0, - outcome: String::new(), - reason: None, - text_sha256: None, - text: None, - aegis: None, - finish_reason: None, - token_ids: None, - prompt_tokens: None, - prompt_ids_sha256: None, - }; + let mut a = new_attempt(k); + a.ms = last_ms; match out { Ok(g) => { a.tokens = g.tokens; @@ -1396,7 +1473,17 @@ pub fn propose_task_with_retries( // NEXT-PHASE-1 v6 N2: a length-cut reply is refused before parsing. let checked = match length_cut_refusal(&g) { Some(why) => Err(why), - None => edit_proposal(&g.text, edit), + None => edit_proposal(&g.text, edit).and_then(|p| { + // The complete content that would be saved. + let content = check_file_proposal(&p)?.content; + match crate::requirements::refusal_reason(reqs, &content) { + Some(why) => { + a.unmet_requirements = crate::requirements::unmet(reqs, &content); + Err(why) + } + None => Ok(p), + } + }), }; match checked { Ok(proposal) => { @@ -1465,7 +1552,7 @@ pub(crate) fn record_view( pub(crate) struct ComposeHome { pub(crate) compose: Compose, pub(crate) machine_id: String, - prompts: Arc<parking_lot::Mutex<HashMap<u64, TaskPrompt>>>, + prompts: Arc<parking_lot::Mutex<HashMap<u64, TaskEntry>>>, /// Proposer hook: task -> approved proposal text (crate::approved). approved: Arc<parking_lot::Mutex<HashMap<u64, String>>>, /// What the model Skill returned per task: the text, or why it gave @@ -1519,6 +1606,8 @@ impl ComposeHome { type SkillOutput = (Result<String, String>, Vec<ProposalAttempt>); /// The prompt of one task, its edit target and its kind (`task_plan`). pub type TaskPrompt = (String, Option<(String, String)>, ProposalKind); +/// A task's plan plus the requirements its goal states (`requirements::extract`). +type TaskEntry = (TaskPrompt, Vec<crate::requirements::Requirement>); /// Owns the composition home of this process. pub struct ComposeBridge { @@ -1594,7 +1683,7 @@ impl ComposeBridge { journal_present, ) .map_err(|r| mark_refusal(&self.dir, &r))?; - let prompts: Arc<parking_lot::Mutex<HashMap<u64, TaskPrompt>>> = Arc::default(); + let prompts: Arc<parking_lot::Mutex<HashMap<u64, TaskEntry>>> = Arc::default(); let proposals: Arc<parking_lot::Mutex<HashMap<u64, SkillOutput>>> = Arc::default(); let approved: Arc<parking_lot::Mutex<HashMap<u64, String>>> = Arc::default(); let (pr, pp, proposer) = (prompts.clone(), proposals.clone(), self.proposer.clone()); @@ -1605,7 +1694,7 @@ impl ComposeBridge { let pa = approved.clone(); compose .register_skill(COMPOSE_MODEL_SKILL, None, 10, move |task| { - let (prompt, target, kind) = pr.lock().get(&task).cloned()?; + let ((prompt, target, kind), reqs) = pr.lock().get(&task).cloned()?; // Proposer hook (crate::approved): an approved proposal for this // task replaces the model's reply. One attempt, the same // template check, the same AEGIS contract and commit below. @@ -1616,16 +1705,7 @@ impl ComposeBridge { let attempt_budget = compose_attempt_budget(kind, budget); let fixed = pa.lock().get(&task).cloned(); let (out, attempts) = match fixed { - Some(text) => { - let one = move |_: &str, _: std::time::Duration| { - Ok(Generation { - text: text.clone(), - finish_reason: Some("approved".into()), - ..Default::default() - }) - }; - propose_task_with_retries(&one, &prompt, None, budget, attempt_budget, 1) - } + Some(text) => propose_approved(&text, &prompt, &reqs, budget, attempt_budget), // Fixed template + bounded automatic retry (ACCEPTANCE-v2 3a, 3b), // measured per-attempt budget (ACCEPTANCE-v3 3b); an edit reply // is merged into the content the model was shown (v7 T5). @@ -1635,10 +1715,11 @@ impl ComposeBridge { ProposalKind::Edit => &proposer, ProposalKind::Document => &doc_proposer, }; - propose_task_with_retries( + propose_task_checked( p.as_ref(), &prompt, edit, + &reqs, budget, attempt_budget, COMPOSE_MAX_ATTEMPTS, @@ -1650,15 +1731,25 @@ impl ComposeBridge { h }) .map_err(|e| format!("compose register skill: {e}"))?; - let pv = proposals.clone(); + let (pv, pq) = (proposals.clone(), prompts.clone()); compose .set_verify(move |task, result| { // AEGIS contract: the result names exactly the proposal text // the Skill recorded for this task, and that text parses as one // file change (a relative path and nonempty content). + // The requirements of the goal are checked again on these same + // bytes, the ones that would be saved. + let reqs = pq + .lock() + .get(&task) + .map(|p| p.1.clone()) + .unwrap_or_default(); pv.lock().get(&task).is_some_and(|(t, _)| { let Ok(t) = t else { return false }; - proposal_handle(t) == result && parse_file_proposal(t).is_some() + proposal_handle(t) == result + && parse_file_proposal(t).is_some_and(|p| { + crate::requirements::refusal_reason(&reqs, &p.content).is_none() + }) }) }) .map_err(|e| format!("compose set verify: {e}"))?; @@ -1771,7 +1862,11 @@ impl ComposeBridge { ws.display() )); } - let prompt = task_plan(goal, &ws)?; + let plan = task_plan(goal, &ws)?; + // The requirements the goal states are checked on every path: the model + // path and an approved proposal (refused before any write when unmet). + let reqs = crate::requirements::extract(goal); + let recognized: Vec<String> = reqs.iter().map(|r| r.label()).collect(); let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_err(|e| format!("clock: {e}"))?; @@ -1795,7 +1890,7 @@ impl ComposeBridge { // starts, the Skill gives up at budget. Set only here, under the lock that // serializes runs, never while rx_compose_run is in flight. An omega without // rxc_host_set_wait_ms refuses a budget that needs a longer wait (no silent 30 s wait). - let kind = prompt.2; + let kind = plan.2; let wait = home.budgets.for_kind(kind) + COMPOSE_WAIT_MARGIN; home.compose .set_wait_ms(wait.as_millis() as u32) @@ -1808,7 +1903,7 @@ impl ComposeBridge { if let Some(t) = approved_text { home.approved.lock().insert(task, t.to_string()); } - home.prompts.lock().insert(task, prompt); + home.prompts.lock().insert(task, (plan, reqs)); let run = home.compose.run(task, now.as_micros() as u64); home.prompts.lock().remove(&task); home.approved.lock().remove(&task); @@ -1858,6 +1953,7 @@ impl ComposeBridge { uncommitted_proposal, proposer_error, proposal_attempts, + requirements_recognized: recognized, proposer: match approved_text { Some(_) => APPROVED_PROPOSER_LABEL.to_string(), None => self.proposer_label.clone(), @@ -2122,3 +2218,89 @@ impl ComposeBridge { .map_err(|e| format!("compose record {id}: {e}")) } } + +#[cfg(test)] +mod requirement_tests { + use super::*; + use crate::requirements::extract; + + const SHORT: &str = "filename: DOC.md\na\nb\nc\n"; + + #[test] + fn approved_text_is_checked_against_the_goal_requirements() { + let reqs = extract("write DOC.md in at least 10 lines"); + let (out, a) = propose_approved( + SHORT, + "base", + &reqs, + COMPOSE_SKILL_BUDGET, + COMPOSE_ATTEMPT_BUDGET, + ); + let why = out.unwrap_err(); + assert!( + why.contains("at least 10 non-empty lines, found 3"), + "{why}" + ); + assert_eq!(a.len(), 1); + assert_eq!(a[0].outcome, "refused"); + assert_eq!( + a[0].unmet_requirements, + ["at least 10 non-empty lines, found 3"] + ); + // Met, or none stated: the approved bytes pass through unchanged. + let (out, _) = propose_approved( + SHORT, + "base", + &extract("at least 3 lines"), + COMPOSE_SKILL_BUDGET, + COMPOSE_ATTEMPT_BUDGET, + ); + assert_eq!(out.unwrap(), SHORT); + let (out, a) = propose_approved( + SHORT, + "base", + &[], + COMPOSE_SKILL_BUDGET, + COMPOSE_ATTEMPT_BUDGET, + ); + assert_eq!(out.unwrap(), SHORT); + assert_eq!(a[0].finish_reason.as_deref(), Some("approved")); + } + + #[test] + fn approved_run_reports_recognized_and_refuses_unmet_before_any_write() { + let tmp = tempfile::tempdir().unwrap(); + let ws = tmp.path().join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + let proposer: ComposeProposer = Arc::new(|_: &str, _: std::time::Duration| { + panic!("the model proposer ran on the approved path") + }); + let bridge = ComposeBridge::new(tmp.path().join("compose"), proposer, "test:approved"); + let r = bridge.run_approved_task( + "write DOC.md in at least 10 lines", + ws.to_str().unwrap(), + SHORT, + ); + if !aien_omega_compose::LINKED { + assert!(r.is_err()); + return; + } + let r = r.unwrap(); + assert!(!r.committed, "{r:?}"); + assert!(r.proposal.is_none()); + assert_eq!(r.requirements_recognized, ["at least 10 non-empty lines"]); + assert!(r.proposer_error.unwrap().contains("found 3")); + assert_eq!(std::fs::read_dir(&ws).unwrap().count(), 0); + // The same bytes pass when the goal states a requirement they meet. + let r = bridge + .run_approved_task( + "write DOC.md in at least 3 lines", + ws.to_str().unwrap(), + SHORT, + ) + .unwrap(); + assert!(r.committed, "{r:?}"); + assert_eq!(r.requirements_recognized, ["at least 3 non-empty lines"]); + assert_eq!(r.proposal.as_deref(), Some(SHORT)); + } +} diff --git a/crates/aien-runtime/tests/requirements_deadline_test.rs b/crates/aien-runtime/tests/requirements_deadline_test.rs new file mode 100644 index 00000000..0ac987ed --- /dev/null +++ b/crates/aien-runtime/tests/requirements_deadline_test.rs @@ -0,0 +1,118 @@ +//! A document task whose first attempt fails a stated requirement and whose +//! second attempt passes: both attempts happen inside the ONE per-task document +//! deadline (a short injected budget), and the bytes saved are the bytes approved. +//! Own test binary: it sets a process-global environment variable. +use aien_runtime::control::ControlResponse; +use aien_runtime::requirements::extract; +use aien_runtime::spine::{ + check_file_proposal, compose_attempt_budget, compose_budgets_from_env, propose_task_checked, + ComposeBridge, ComposeProposer, Generation, ProposalKind, COMPOSE_DOC_BUDGET_ENV, + COMPOSE_MAX_ATTEMPTS, +}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +fn doc(n: usize) -> String { + let mut s = String::from("filename: DOC.md\n"); + for i in 0..n { + s.push_str(&format!("line {i}\n")); + } + s +} + +fn reply(text: String) -> Result<Generation, String> { + Ok(Generation { + text, + tokens: 5, + finish_reason: Some("eos".into()), + ..Default::default() + }) +} + +#[test] +fn requirement_retry_stays_inside_the_single_document_deadline_and_saves_approved_bytes() { + std::env::set_var(COMPOSE_DOC_BUDGET_ENV, "6000"); + let budget = compose_budgets_from_env().unwrap().doc; + assert_eq!(budget, Duration::from_millis(6000)); + let attempt_budget = compose_attempt_budget(ProposalKind::Document, budget); + let reqs = extract("write DOC.md in at least 20 lines"); + assert_eq!(reqs.len(), 1); + + // Part 1 (any build): the shared deadline, observed from the proposer. + let limits: Mutex<Vec<Duration>> = Mutex::default(); + let t0 = Instant::now(); + let proposer = |_: &str, limit: Duration| { + let mut l = limits.lock().unwrap(); + l.push(limit); + std::thread::sleep(Duration::from_millis(300)); + // First attempt: 5 lines (unmet). Second: 25 lines. + reply(doc(if l.len() == 1 { 5 } else { 25 })) + }; + let (out, attempts) = propose_task_checked( + &proposer, + "base", + None, + &reqs, + budget, + attempt_budget, + COMPOSE_MAX_ATTEMPTS, + ); + assert!(t0.elapsed() < budget, "both attempts inside one deadline"); + let limits = limits.lock().unwrap().clone(); + assert_eq!(limits.len(), 2); + assert!(limits[0] <= budget, "{limits:?}"); + assert!( + limits[1] < limits[0], + "retry gets what is left, not a fresh budget: {limits:?}" + ); + assert_eq!(attempts.len(), 2); + assert_eq!(attempts[0].outcome, "refused"); + assert_eq!(attempts[0].unmet_requirements.len(), 1); + assert_eq!(attempts[1].outcome, "parsed"); + assert!(out.is_ok()); + + // Part 2 (linked build): the same through the real run; saved == approved. + let tmp = tempfile::tempdir().unwrap(); + let ws = std::fs::canonicalize({ + std::fs::create_dir_all(tmp.path().join("ws")).unwrap(); + tmp.path().join("ws") + }) + .unwrap(); + let calls: Arc<Mutex<u32>> = Arc::default(); + let c = calls.clone(); + let doc_proposer: ComposeProposer = Arc::new(move |_: &str, _: Duration| { + let mut n = c.lock().unwrap(); + *n += 1; + std::thread::sleep(Duration::from_millis(300)); + reply(doc(if *n == 1 { 5 } else { 25 })) + }); + let unused: ComposeProposer = Arc::new(|_: &str, _: Duration| Err("edit path unused".into())); + let bridge = ComposeBridge::new(tmp.path().join("compose"), unused, "test:deadline") + .with_doc_proposer(doc_proposer); + let t0 = Instant::now(); + let resp = bridge.run_task("write DOC.md in at least 20 lines", ws.to_str().unwrap()); + if !aien_omega_compose::LINKED { + assert!(matches!(resp, ControlResponse::Error(_))); + return; + } + let ControlResponse::ComposeTaskResult(r) = resp else { + panic!("{resp:?}") + }; + assert!(t0.elapsed() < budget); + assert!(r.committed, "{r:?}"); + assert_eq!(*calls.lock().unwrap(), 2); + assert_eq!(r.proposal_attempts.len(), 2); + assert_eq!(r.proposal_attempts[0].unmet_requirements.len(), 1); + assert_eq!(r.proposal_attempts[1].aegis.as_deref(), Some("pass")); + let saved = check_file_proposal(&r.proposal.clone().unwrap()).unwrap(); + assert_eq!( + r.proposal_content_sha256.clone().unwrap(), + aien_omega_compose::hex(&<sha2::Sha256 as sha2::Digest>::digest( + saved.content.as_bytes() + )) + ); + assert_eq!( + saved.content, + doc(25).strip_prefix("filename: DOC.md\n").unwrap() + ); +} diff --git a/crates/aien-runtime/tests/requirements_test.rs b/crates/aien-runtime/tests/requirements_test.rs new file mode 100644 index 00000000..392aed3b --- /dev/null +++ b/crates/aien-runtime/tests/requirements_test.rs @@ -0,0 +1,651 @@ +//! Requirement validation for composed documents (crate::requirements). +use aien_runtime::approved::{approved_proposal_sha256, proposal_text}; +use aien_runtime::control::ControlResponse; +use aien_runtime::effects; +use aien_runtime::requirements::{extract, refusal_reason, unmet, ItemKind, Requirement}; +use aien_runtime::spine::{ + check_file_proposal, propose_task_checked, ComposeBridge, ComposeProposer, Generation, + COMPOSE_MAX_ATTEMPTS, +}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +fn doc(n: usize) -> String { + let mut s = String::from("filename: DOC.md\n"); + for i in 0..n { + s.push_str(&format!("line {i}\n")); + } + s +} + +fn gen(text: String) -> Result<Generation, String> { + Ok(Generation { + text, + tokens: 5, + finish_reason: Some("eos".into()), + ..Default::default() + }) +} + +#[test] +fn extracts_each_supported_pattern() { + use ItemKind::*; + use Requirement::*; + assert_eq!( + extract("Write a note in at least 20 lines."), + [MinLines(20)] + ); + assert_eq!(extract("keep it to AT MOST 8 lines"), [MaxLines(8)]); + assert_eq!(extract("give at least 5 items"), [MinItems(Items, 5)]); + assert_eq!(extract("give at least 1 item"), [MinItems(Items, 1)]); + assert_eq!( + extract("list at least 3 steps, please"), + [MinItems(Steps, 3)] + ); + assert_eq!(extract("with at least 4 sections"), [MinItems(Sections, 4)]); + assert_eq!( + extract("ask at least 6 questions."), + [MinItems(Questions, 6)] + ); + assert_eq!( + extract("include the phrase \"Hello World\" and contain the phrase \"x\""), + [RequiredPhrases(vec!["Hello World".into(), "x".into()])] + ); + assert_eq!( + extract("at least 20 lines and at most 40 lines"), + [MinLines(20), MaxLines(40)] + ); +} + +#[test] +fn unsupported_phrasing_is_not_extracted() { + for g in [ + "write a long document", + "at least twenty lines", + "no fewer than 20 lines", + "more than 20 lines", + "at least 20 long lines", + "at least 20 words", + "at least 20 paragraphs", + "at most 5 items", + "at least 0 lines", + "at least -3 lines", + "at least 2.5 lines", + "at least 99999999999999999999999 lines", + "include the phrase hello", + "include the phrase \"\"", + "mention hello in the text", + "exactly 20 lines", + ] { + assert_eq!(extract(g), vec![], "{g}"); + } +} + +#[test] +fn checks_pass_and_fail_with_exact_counts() { + use ItemKind::*; + use Requirement::*; + let thirteen: String = (0..13).map(|i| format!("l{i}\n\n")).collect(); + assert_eq!(non_empty_blank_safe(&thirteen), 13); + assert!(MinLines(13).check(&thirteen).is_none()); + assert_eq!( + MinLines(20).check(&thirteen).unwrap(), + "at least 20 non-empty lines, found 13" + ); + assert!(MaxLines(13).check(&thirteen).is_none()); + assert!(MaxLines(12).check(&thirteen).is_some()); + let md = "# One\n## Two\n#NoSpace\n####### seven\n- a\n * b\n+ c\n1. d\n2) e\n3.f\nWhy?\nreally ?\n"; + assert!(MinItems(Sections, 2).check(md).is_none()); + assert!(MinItems(Sections, 3).check(md).is_some()); + assert!(MinItems(Items, 5).check(md).is_none()); + assert!(MinItems(Items, 6).check(md).is_some()); + assert!(MinItems(Steps, 2).check(md).is_none()); + assert!(MinItems(Steps, 3).check(md).is_some()); + assert!(MinItems(Questions, 2).check(md).is_none()); + assert!(MinItems(Questions, 3).check(md).is_some()); + let p = RequiredPhrases(vec!["hello world".into(), "Bye".into()]); + assert_eq!( + p.check("HeLLo WoRLD only").unwrap(), + "the phrase \"hello world\", \"Bye\", missing \"Bye\"" + ); + assert!(p.check("Hello World and BYE").is_none()); + assert_eq!(unmet(&[], "x"), Vec::<String>::new()); + assert_eq!(refusal_reason(&[], "x"), None); +} + +fn non_empty_blank_safe(s: &str) -> usize { + s.lines().filter(|l| !l.trim().is_empty()).count() +} + +#[test] +fn retry_names_the_unmet_requirement_and_second_attempt_passes() { + let prompts: Mutex<Vec<String>> = Mutex::new(Vec::new()); + let replies = Mutex::new(vec![doc(25), doc(13)]); + let proposer = |p: &str, _: Duration| { + prompts.lock().unwrap().push(p.to_string()); + gen(replies.lock().unwrap().pop().unwrap()) + }; + let reqs = extract("write it in at least 20 lines"); + let (out, a) = propose_task_checked( + &proposer, + "base", + None, + &reqs, + Duration::from_secs(5), + Duration::from_millis(1), + COMPOSE_MAX_ATTEMPTS, + ); + assert_eq!(out.unwrap(), doc(25)); + assert_eq!(a.len(), 2); + assert_eq!(a[0].outcome, "refused"); + assert_eq!( + a[0].reason.as_deref(), + Some("unmet requirement: at least 20 non-empty lines, found 13") + ); + assert_eq!( + a[0].unmet_requirements, + ["at least 20 non-empty lines, found 13"] + ); + assert_eq!(a[1].outcome, "parsed"); + assert!(a[1].unmet_requirements.is_empty()); + let p = prompts.lock().unwrap(); + assert!(!p[0].contains("unmet requirement")); + assert!( + p[1].contains("refused (unmet requirement: at least 20 non-empty lines, found 13)"), + "{}", + p[1] + ); +} + +#[test] +fn exhaustion_returns_no_proposal() { + let proposer = |_: &str, _: Duration| gen(doc(13)); + let reqs = extract("in at least 20 lines"); + let (out, a) = propose_task_checked( + &proposer, + "base", + None, + &reqs, + Duration::from_secs(5), + Duration::from_millis(1), + COMPOSE_MAX_ATTEMPTS, + ); + let why = out.unwrap_err(); + assert!( + why.contains("at least 20 non-empty lines, found 13"), + "{why}" + ); + assert_eq!(a.len(), COMPOSE_MAX_ATTEMPTS as usize); + assert!(a + .iter() + .all(|x| x.outcome == "refused" && x.aegis.is_none())); + assert!(a.iter().all(|x| x.unmet_requirements.len() == 1)); +} + +#[test] +fn deadline_is_shared_across_attempts() { + // No tight margins: every assertion is a one-sided bound that sleeping + // longer than planned (a loaded machine) can only make easier to meet. + let seen: Mutex<Vec<Duration>> = Mutex::new(Vec::new()); + let proposer = |_: &str, limit: Duration| { + seen.lock().unwrap().push(limit); + std::thread::sleep(Duration::from_millis(300)); + gen(doc(1)) + }; + let reqs = extract("at least 20 lines"); + let budget = Duration::from_millis(2000); + let (out, a) = propose_task_checked( + &proposer, + "base", + None, + &reqs, + budget, + Duration::from_millis(100), + 100, + ); + assert!(out.is_err()); + let seen = seen.lock().unwrap(); + assert_eq!(seen.len(), a.len()); + // Per-attempt reset would allow all 100 attempts. One shared deadline + // stops attempt k > 1 unless 100 ms are left, and every earlier attempt + // took at least 300 ms, so k - 1 <= (2000 - 100) / 300 = 6: at most 7. + assert!(a.len() <= 7, "attempts {}", a.len()); + assert!(a.len() >= 2, "attempts {}", a.len()); + // Each attempt's limit is what is left of ONE budget: attempt k starts + // after k - 1 sleeps of at least 300 ms, so it is at least that far + // below the first limit. + for k in 1..seen.len() { + assert!( + seen[k] + Duration::from_millis(290 * k as u64) <= seen[0], + "attempt {} limit {:?} vs first {:?}", + k + 1, + seen[k], + seen[0] + ); + } + assert!(seen[0] <= budget); + assert!(out.unwrap_err().contains("per-attempt budget")); +} + +#[test] +fn validated_document_is_the_one_approval_binds() { + let reqs = extract("at least 4 lines"); + let proposer = |_: &str, _: Duration| gen("filename: DOC.md\na\nb\nc\nd\n".into()); + let (out, _) = propose_task_checked( + &proposer, + "base", + None, + &reqs, + Duration::from_secs(5), + Duration::from_millis(1), + 3, + ); + let text = out.unwrap(); + let saved = check_file_proposal(&text).unwrap(); + // The content that passed is the content that would be written ... + assert!(refusal_reason(&reqs, &saved.content).is_none()); + // ... and it reads back byte for byte through the approval template, so + // the digest an approval binds is the digest of the saved bytes. + assert_eq!(proposal_text(&saved.path, &saved.content).unwrap(), text); + let bound = approved_proposal_sha256(&saved.path, &saved.content); + let again = check_file_proposal(&proposal_text(&saved.path, &saved.content).unwrap()).unwrap(); + assert_eq!(approved_proposal_sha256(&again.path, &again.content), bound); +} + +#[test] +fn edit_mode_validates_the_merged_file_not_the_reply() { + // The prior file has 3 lines; the reply adds 2: the saved file has 5. + let prior = "# T\na\nb\n"; + let proposer = |_: &str, _: Duration| gen("filename: N.md\n# T\na\nnew1\nnew2\nb\n".into()); + let ok = |n: usize| { + propose_task_checked( + &proposer, + "base", + Some(("N.md", prior)), + &[Requirement::MinLines(n)], + Duration::from_secs(5), + Duration::from_millis(1), + 1, + ) + }; + let (out, _) = ok(5); + assert_eq!( + check_file_proposal(&out.unwrap()).unwrap().content, + "# T\na\nnew1\nnew2\nb\n" + ); + let (out, a) = ok(6); + assert!(out.is_err()); + assert_eq!( + a[0].unmet_requirements, + ["at least 6 non-empty lines, found 5"] + ); +} + +#[test] +fn unmet_requirement_leaves_nothing_committed_or_written() { + let tmp = tempfile::tempdir().unwrap(); + let ws = tmp.path().join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + let proposer: ComposeProposer = Arc::new(|_: &str, _: Duration| gen(doc(13))); + let bridge = ComposeBridge::new(tmp.path().join("compose"), proposer, "test:short"); + let resp = bridge.run_task("write DOC.md in at least 20 lines", ws.to_str().unwrap()); + if !aien_omega_compose::LINKED { + assert!(matches!(resp, ControlResponse::Error(_))); + return; + } + let ControlResponse::ComposeTaskResult(r) = resp else { + panic!("{resp:?}") + }; + assert!(!r.committed, "{r:?}"); + assert!(r.proposal.is_none()); + assert_eq!(r.requirements_recognized, ["at least 20 non-empty lines"]); + assert_eq!(r.proposal_attempts.len(), COMPOSE_MAX_ATTEMPTS as usize); + assert!(r.proposer_error.unwrap().contains("found 13")); + assert_eq!(std::fs::read_dir(&ws).unwrap().count(), 0); +} + +// ---- linked proofs (real omega compose library; skipped in the CPU stub) ---- + +fn sha256_hex(b: &[u8]) -> String { + aien_omega_compose::hex(&<sha2::Sha256 as sha2::Digest>::digest(b)) +} + +fn recalled(b: &ComposeBridge) -> aien_runtime::control::ComposeRecallReport { + match b.recall(&[], None) { + ControlResponse::ComposeRecalled(r) => *r, + other => panic!("recall: {other:?}"), + } +} + +fn dir_names(d: &std::path::Path) -> Vec<String> { + let mut v: Vec<String> = std::fs::read_dir(d) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + v.sort(); + v +} + +/// Every attempt of a real compose run fails the requirement: nothing is +/// proposed, approved, written, committed or recorded as an effect. +#[test] +fn linked_exhaustion_leaves_ledger_state_and_files_untouched() { + let tmp = tempfile::tempdir().unwrap(); + let ws = tmp.path().join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + let home = tmp.path().join("compose"); + let calls = Arc::new(Mutex::new(0usize)); + let c2 = calls.clone(); + let proposer: ComposeProposer = Arc::new(move |_: &str, _: Duration| { + *c2.lock().unwrap() += 1; + gen(doc(13)) + }); + let bridge = ComposeBridge::new(home.clone(), proposer, "test:short"); + let resp = bridge.run_task("write DOC.md in at least 20 lines", ws.to_str().unwrap()); + if !aien_omega_compose::LINKED { + assert!(matches!(resp, ControlResponse::Error(_))); + return; + } + let ControlResponse::ComposeTaskResult(r) = resp else { + panic!("{resp:?}") + }; + // The real model Skill ran COMPOSE_MAX_ATTEMPTS times, each refused. + assert_eq!(*calls.lock().unwrap(), COMPOSE_MAX_ATTEMPTS as usize); + assert!(r + .proposal_attempts + .iter() + .all(|a| a.outcome == "refused" && a.aegis.is_none())); + // No committed proposal, no winner, no AEGIS pass, no promotion record. + assert!(!r.committed, "{r:?}"); + assert_eq!(r.outcome, 2, "RXC_OUT_NO_WINNER: {r:?}"); + assert!(r.proposal.is_none() && r.proposal_sha256.is_none()); + assert!(r.proposal_path.is_none() && r.proposal_content_sha256.is_none()); + assert_eq!((r.winner, r.aegis_pass_mask), (None, 0), "{r:?}"); + assert_eq!(r.cx_promotion, 0, "{r:?}"); + // No approval request, no effect intent: the host ledger holds no + // authorization or effect note, and rebuilds to an empty ledger. + let rec = recalled(&bridge); + assert!( + rec.host + .iter() + .all(|h| !matches!(h.note.as_deref(), Some("authorization") | Some("effect"))), + "{:?}", + rec.host + ); + let ledger = effects::Ledger::from_records(&rec.host).unwrap(); + assert!(ledger.grants.is_empty() && ledger.intents.is_empty()); + assert!(ledger.approved_by_claim.is_empty() && ledger.spent.is_empty()); + // No file was written and the destination is absent. + assert!(!ws.join("DOC.md").exists()); + assert_eq!(dir_names(&ws), Vec::<String>::new()); + // The compose home holds only composition files. + for n in dir_names(&home) { + assert!( + n == "machine.id" || n == "cortex.cx" || n.starts_with("jspace"), + "{n}" + ); + } + // Compose state is unchanged by the failed task: a second identical task + // adds no promotion and the committed World has no new document. + let before = recalled(&bridge).records_total; + let again = bridge.run_task("write DOC.md in at least 20 lines", ws.to_str().unwrap()); + let ControlResponse::ComposeTaskResult(r2) = again else { + panic!("{again:?}") + }; + assert!(!r2.committed && r2.cx_promotion == 0, "{r2:?}"); + assert!(!ws.join("DOC.md").exists()); + let after = recalled(&bridge); + assert!(after.records_total >= before); + assert!(after + .host + .iter() + .all(|h| !matches!(h.note.as_deref(), Some("authorization") | Some("effect")))); +} + +/// A document that passes validation commits through the real compose run, +/// is approved by an authorization bound to its digest, and is saved with +/// sha256(disk) == the approved content sha256. +#[test] +fn linked_passing_document_is_approved_and_saved_byte_for_byte() { + let tmp = tempfile::tempdir().unwrap(); + let ws = tmp.path().join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + let ws = std::fs::canonicalize(&ws).unwrap(); + let proposer: ComposeProposer = Arc::new(|_: &str, _: Duration| gen(doc(25))); + let bridge = ComposeBridge::new(tmp.path().join("compose"), proposer, "test:long"); + let resp = bridge.run_task("write DOC.md in at least 20 lines", ws.to_str().unwrap()); + if !aien_omega_compose::LINKED { + assert!(matches!(resp, ControlResponse::Error(_))); + return; + } + let ControlResponse::ComposeTaskResult(r) = resp else { + panic!("{resp:?}") + }; + assert!(r.committed, "{r:?}"); + assert_eq!(r.proposal_attempts.len(), 1); + assert_eq!(r.proposal_attempts[0].aegis.as_deref(), Some("pass")); + let proposal = r.proposal.clone().unwrap(); + let saved = check_file_proposal(&proposal).unwrap(); + assert!(refusal_reason(&extract("at least 20 lines"), &saved.content).is_none()); + let content_sha = r.proposal_content_sha256.clone().unwrap(); + assert_eq!(content_sha, sha256_hex(saved.content.as_bytes())); + assert!(!ws.join("DOC.md").exists(), "composing writes nothing"); + // Approval (the authorization note) binds the digest; the effect writes. + let target = ws.join(&saved.path); + let grant = serde_json::json!({ + "proposal_sha256": r.proposal_sha256.clone().unwrap(), "path": saved.path, + "content_sha256": content_sha, "approver": "drake", + "target": target.display().to_string(), "prior_sha256": null, + "workspace": ws.display().to_string()}); + let a = match bridge.note("authorization", &grant.to_string(), &[]) { + ControlResponse::ComposeNoted(n) => n.id, + other => panic!("authorize: {other:?}"), + }; + let (pid, start) = effects::self_executor(); + let i = match effects::open_intent( + &bridge, + &effects::IntentRequest { + authorization: a, + proposal_sha256: r.proposal_sha256.clone().unwrap(), + path: saved.path.clone(), + target: target.display().to_string(), + content_sha256: content_sha.clone(), + executor_pid: pid, + executor_start: start, + }, + ) { + ControlResponse::ComposeNoted(n) => n.id, + other => panic!("intent: {other:?}"), + }; + std::fs::write(&target, &saved.content).unwrap(); + assert!(matches!( + effects::ack( + &bridge, + i, + &serde_json::json!({"written_sha256": content_sha}) + ), + ControlResponse::ComposeNoted(_) + )); + assert_eq!(sha256_hex(&std::fs::read(&target).unwrap()), content_sha); + let ledger = effects::Ledger::from_records(&recalled(&bridge).host).unwrap(); + assert_eq!(ledger.intents.len(), 1); +} + +// ---- review fixes (#287) ---- + +#[test] +fn count_followed_by_a_qualifier_is_not_extracted() { + // The noun must END the clause: "N lines of context" states something + // other than "the document has N lines", so it gets no check. + for g in [ + "show a diff with at least 3 lines of context", + "write at least 2 sections of the config", + "at least 5 items per category", + "at least 3 steps for each stage", + "at least 4 questions in the survey", + "at least 4 questions from the list", + "at least 6 lines for the intro", + "at least 6 lines with comments", + "at least 6 lines about cats", + "at most 10 lines in each file", + ] { + assert_eq!(extract(g), vec![], "{g}"); + } + use Requirement::*; + // Clause-ending punctuation, end of goal, and the joining words are fine. + for (g, want) in [ + ("at least 20 lines", MinLines(20)), + ("at least 20 lines.", MinLines(20)), + ("at least 20 lines, please", MinLines(20)), + ("at least 20 lines and a title", MinLines(20)), + ("at least 20 lines or more", MinLines(20)), + ("at least 20 lines covering the topic", MinLines(20)), + ("at least 20 lines that explain it", MinLines(20)), + ("at most 8 lines which are short", MaxLines(8)), + ] { + assert_eq!(extract(g), [want], "{g}"); + } +} + +#[test] +fn phrase_followed_by_a_qualifier_is_not_extracted() { + // "in the title" would make the whole-document check claim more than it covers. + assert_eq!(extract("include the phrase \"X\" in the title"), vec![]); + assert_eq!( + extract("include the phrase \"X\" in the title and contain the phrase \"Y\"."), + [Requirement::RequiredPhrases(vec!["Y".into()])] + ); +} + +#[test] +fn negated_wording_is_not_extracted() { + for g in [ + "do not include the phrase \"X\"", + "Do NOT include the phrase \"X\"", + "never contain the phrase \"X\"", + "the file must not include the phrase \"X\"", + "don't include the phrase \"X\"", + "it doesn't contain the phrase \"X\"", + "without ever including; never include the phrase \"X\"", + "not at least 20 lines", + "do not write at least 20 lines", + "never write at least 3 sections", + "it must not have at most 5 lines", + "no more than 20 lines", + "no fewer than 20 lines", + "not at most 10 lines", + "without at least 4 items", + ] { + assert_eq!(extract(g), vec![], "{g}"); + } + // A negation in an EARLIER clause does not poison a later requirement. + assert_eq!( + extract("do not use tables. Write at least 20 lines."), + [Requirement::MinLines(20)] + ); + assert_eq!( + extract("do not hedge, include the phrase \"X\""), + [Requirement::RequiredPhrases(vec!["X".into()])] + ); +} + +#[test] +fn emphasis_and_quoted_forms_are_unrecognized() { + // Documented limitation: markdown emphasis or quotes around the wording + // break the exact word sequence, so nothing is extracted (and nothing is + // claimed as covered). + for g in [ + "write **at least 20 lines**", + "write \"at least 20 lines\"", + "write 'at least 20 lines'", + "write at least **20** lines", + "write at least 20 *lines*", + "write at least 20 `lines`", + ] { + assert_eq!(extract(g), vec![], "{g}"); + } +} + +#[test] +fn fenced_code_is_not_counted_as_headings_questions_items_or_steps() { + use ItemKind::*; + let d = "# Real\n- a\n1. s\nWhy?\n```bash\n# not a heading\n- not an item\n1. not a step\nnot a question?\n```\n~~~\n## also not\n- nor this\nq?\n~~~\n"; + assert_eq!(count(Sections, d), 1); + assert_eq!(count(Items, d), 2); + assert_eq!(count(Steps, d), 1); + assert_eq!(count(Questions, d), 1); + // CommonMark close rule: a shorter or info-carrying fence does not close. + let d2 = "````\n```\n# inside\n```bash\n- inside\n````\n# outside\n"; + assert_eq!(count(Sections, d2), 1); + // ~~~ is not closed by ``` and vice versa. + let d3 = "~~~\n```\n# inside\n~~~\n# outside\n"; + assert_eq!(count(Sections, d3), 1); + // An unclosed fence runs to the end of the document. + assert_eq!(count(Sections, "# a\n```\n# b\n# c\n"), 1); + // A backtick fence whose info string holds a backtick is not a fence. + assert_eq!(count(Sections, "``` `x`\n# real\n"), 1); +} + +fn count(k: ItemKind, s: &str) -> usize { + // found N appears in the unmet sentence; ask for an impossible minimum. + let m = Requirement::MinItems(k, usize::MAX).check(s).unwrap(); + m.rsplit("found ").next().unwrap().parse().unwrap() +} + +#[test] +fn line_limits_count_every_non_empty_line_including_code_and_fences() { + // Documented: MinLines/MaxLines count lines of the file, so fence marker + // lines and code lines count; blank lines do not. + let d = "intro\n```rust\nlet x = 1;\n\nlet y = 2;\n```\nend\n"; + assert_eq!(Requirement::MinLines(6).check(d), None); + assert_eq!( + Requirement::MinLines(7).check(d).unwrap(), + "at least 7 non-empty lines, found 6" + ); + assert_eq!(Requirement::MaxLines(6).check(d), None); + assert!(Requirement::MaxLines(5).check(d).is_some()); +} + +#[test] +fn edit_whose_prior_file_already_breaks_a_max_is_refused_before_any_attempt() { + let prior: String = (0..10).map(|i| format!("l{i}\n")).collect(); + let calls = Mutex::new(0u32); + let proposer = |_: &str, _: Duration| { + *calls.lock().unwrap() += 1; + gen("filename: N.md\nl0\nnew\n".into()) + }; + let (out, a) = propose_task_checked( + &proposer, + "base", + Some(("N.md", &prior)), + &[Requirement::MaxLines(5)], + Duration::from_secs(5), + Duration::from_millis(1), + 3, + ); + assert_eq!(*calls.lock().unwrap(), 0, "no attempt may be spent"); + let why = out.unwrap_err(); + assert!( + why.contains("N.md") && why.contains("at most 5 non-empty lines, found 10"), + "{why}" + ); + assert!(why.contains("an edit only adds lines"), "{why}"); + assert_eq!(a.len(), 1); + assert_eq!(a[0].outcome, "refused"); + assert_eq!(a[0].reason.as_deref(), Some(why.as_str())); + assert_eq!( + a[0].unmet_requirements, + ["at most 5 non-empty lines, found 10"] + ); + // Min requirements and a prior file within the maximum are unaffected. + let (out, _) = propose_task_checked( + &proposer, + "base", + Some(("N.md", &prior)), + &[Requirement::MaxLines(12)], + Duration::from_secs(5), + Duration::from_millis(1), + 1, + ); + assert!(out.is_ok()); +}