diff --git a/.crumb b/.crumb index 5d7f729d..98f0fae9 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:c5269f93385287c09996ff41f0247f72de9237a2317f47c94c51273d6a0acef1", - "compiled_at": "2026-10-07T22:46:49Z", + "compiled_at": "2026-10-07T23:06:36Z", "compiler": "crumb-compile/1", - "digest": "sha256:7cb076b9f153971012ac154ca45889743d341869a6904ed8eac9392b4c914ed3", + "digest": "sha256:bc8bc25d0fc4c75e7f3b9e2600e1670b13b109175708c02dc509f1a4ca67f78f", "evidence_files": 186, "evidence_root": "sha256:fbe849218d18dc4b21a74410fdd8f7d98431a1d0123a0c69264386f770da4db4", - "files": 1307, - "generated_at_commit": "1bb259d5cfa3a40d8aad185351cd3e3cd5700abf", - "source_tree": "sha256:c32d786ed9f12ca3c3ec0314527cbb892277c126666b48c2b32c0e1f8799dcd8" + "files": 1313, + "generated_at_commit": "870c49e1d5da1f5edd87b8dda2618fe6800ed906", + "source_tree": "sha256:ce492bd7955fe3c1a71724ac6541c219984c8ec7f113da69093b9158e22be535" } }, "history": [], diff --git a/crates/aien-runtime/src/approved.rs b/crates/aien-runtime/src/approved.rs index 2be161c0..6877c555 100644 --- a/crates/aien-runtime/src/approved.rs +++ b/crates/aien-runtime/src/approved.rs @@ -66,6 +66,22 @@ pub struct ApprovedProposal { /// (crate::approved_auth). Never caller text: only the desk key holder /// can make it. pub approval_mac: String, + /// The goal text whose measurable requirements the approved bytes must + /// meet (crate::requirements), bound by `requirements_mac`. `Some("")` is + /// an explicit, signed "no requirements"; `None` (field missing) is + /// refused: an absent binding is never read as an empty requirement set. + #[serde(default)] + pub requirements: Option, + /// HMAC-SHA256 (hex) under the desk key over the approval binding and + /// `requirements` (crate::approved_auth::DeskKey::sign_requirements). + #[serde(default)] + pub requirements_mac: String, + /// Only when a requirement depends on the file the bytes replace (an added-line + /// count): the sha256 (hex) of that file as the desk saw it, or "absent". Bound by + /// `requirements_mac` (tag v2). The daemon refuses unless the file still has this + /// sha256 when the grant is written (same compose-home lock). + #[serde(default)] + pub requirements_base: Option, } /// What a committed approved proposal hands to the effect ledger. @@ -151,6 +167,11 @@ fn sha256_hex(b: &[u8]) -> String { hex(&Sha256::digest(b)) } +/// Start of the machine goal of an approved run. It carries the desk-supplied path, not +/// a requirement statement: the run does not read requirements out of it (the +/// goal bound into the approval was checked on the same bytes before the claim). +pub(crate) const APPROVED_GOAL_PREFIX: &str = "apply approved proposal for "; + fn refuse(name: &str, why: impl std::fmt::Display) -> String { format!("{REFUSED} {name}: {why}") } @@ -204,9 +225,69 @@ pub fn verify(p: &ApprovedProposal) -> Result { "approved_proposal_sha256 does not match {content, path}", )); } + if p.requirements.is_none() { + return Err(refuse( + "RequirementsUnbound", + "the approval carries no requirement binding (requirements); an absent binding is refused, sign an empty goal for none", + )); + } proposal_text(&p.path, &p.content) } +/// The requirements the desk bound to this approval, checked on the exact +/// approved content (the bytes that would be saved). Uncertain wording refuses. +fn check_bound_requirements(p: &ApprovedProposal, workspace: &Path) -> Result<(), String> { + let goal = p.requirements.as_deref().ok_or_else(|| { + refuse( + "RequirementsUnbound", + "the approval carries no requirement binding", + ) + })?; + let mut ex = crate::requirements::analyze(goal); + if let Some(why) = ex.refusal() { + return Err(refuse("RequirementsUncertain", why)); + } + if ex.needs_prior() { + // An added-line count is judged against the file these bytes replace. + let class = if p.path.contains(char::is_whitespace) { + crate::spine::TargetClass::Refused(String::new()) + } else { + crate::spine::classify_target(&p.path, workspace) + }; + let (prior, exists) = + match class { + crate::spine::TargetClass::Edit(_, c) => (c, true), + crate::spine::TargetClass::New => (String::new(), false), + _ => return Err(refuse( + "RequirementsUnmet", + "the existing file cannot be read, so the added-line count cannot be measured", + )), + }; + let base = p.requirements_base.as_deref().ok_or_else(|| { + refuse( + "RequirementsUnbound", + "a requirement depends on the file these bytes replace, so the approval must bind requirements_base (its sha256, or \"absent\")", + ) + })?; + let now = if exists { + sha256_hex(prior.as_bytes()) + } else { + "absent".to_string() + }; + if now != base { + return Err(refuse( + "BaseChanged", + format!("the file changed since the desk bound it (bound {base}, now {now})"), + )); + } + ex = ex.resolved(&prior); + } + match crate::requirements::refusal_reason(&ex.requirements, &p.content) { + Some(why) => Err(refuse("RequirementsUnmet", why)), + None => Ok(()), + } +} + /// The hook over one compose bridge (the daemon's, or a test's). Replay /// state lives only in the bridge's Cortex journal (crate::approved_replay): /// two hooks over one compose home, or a restarted daemon, see the same claims. @@ -246,6 +327,9 @@ impl ProposerHook { desk.authenticate(p, Path::new(workspace)) })() .map_err(|e| refusal(e, None))?; + // The goal requirements bound by the desk, checked on the exact approved + // bytes BEFORE any claim, run or commit. + check_bound_requirements(p, Path::new(workspace)).map_err(|e| refusal(e, None))?; let keys = ClaimKeys { approval_key: approval_key(&identity), request_id: p.request_id.clone(), @@ -265,7 +349,7 @@ impl ProposerHook { })?; // Exactly one compose run per claim. let goal = format!( - "apply approved proposal for {} (request {})", + "{APPROVED_GOAL_PREFIX}{} (request {})", p.path, p.request_id ); let r = match self @@ -294,6 +378,11 @@ impl ProposerHook { return Err(refusal(why, Some(claim.id))); } let compose_sha = sha256_hex(text.as_bytes()); + // The prior file the bound requirements were checked against (None when none depends on it). + let base = crate::requirements::analyze(p.requirements.as_deref().unwrap_or("")) + .needs_prior() + .then(|| p.requirements_base.clone()) + .flatten(); if r.proposal.as_deref() != Some(text.as_str()) || r.proposal_sha256.as_deref() != Some(compose_sha.as_str()) || r.proposal_path.as_deref() != Some(p.path.as_str()) @@ -333,6 +422,10 @@ impl ProposerHook { let ids = serde_json::json!({"request_id": p.request_id, "trace_id": p.trace_id, "approval_id": p.approval_id, "desk_key_id": identity.desk_key_id, "approved_proposal_sha256": p.approved_proposal_sha256}); + #[cfg(test)] + if let Some(f) = BEFORE_GRANT.lock().unwrap().as_ref() { + f(); + } let (grant, target) = write_approved_grant( &self.bridge, &identity.workspace, @@ -342,6 +435,7 @@ impl ProposerHook { &ids, &link, &compose_sha, + base.as_deref(), ) .map_err(|e| { refusal( @@ -451,3 +545,93 @@ fn crash_point(name: &str) { #[cfg(not(feature = "fault-hold"))] fn crash_point(_: &str) {} + +/// Test seam: runs between the compose commit and the grant write, where a +/// concurrent edit of the target would land. +#[cfg(test)] +static BEFORE_GRANT: std::sync::Mutex>> = std::sync::Mutex::new(None); + +#[cfg(test)] +mod toctou_tests { + use super::*; + use crate::approved_auth::{desk_key_path, DeskKey}; + + fn proposal(b: &ComposeBridge, ws: &Path, id: &str, base: &str) -> ApprovedProposal { + let content = "one\ntwo\nthree\n".to_string(); + let mut p = ApprovedProposal { + request_id: id.into(), + trace_id: format!("trace-{id}"), + approval_id: format!("appr-{id}"), + approver: "interplane-host".into(), + path: "NOTES.md".into(), + approved_proposal_sha256: approved_proposal_sha256("NOTES.md", &content), + content_sha256: sha256_hex(content.as_bytes()), + content, + approval_mac: String::new(), + requirements: Some("Add one line to NOTES.md".into()), + requirements_mac: String::new(), + requirements_base: Some(base.into()), + }; + DeskKey::load(&desk_key_path(b.dir())) + .unwrap() + .seal(&mut p, ws); + p + } + + /// The target changes after the requirements were checked and before the + /// grant is written: refused with BaseChanged, nothing authorizes a write. + /// Unchanged, the same approval shape passes. (Linked build: the stub + /// refuses at the claim, before the seam.) + #[test] + fn prior_changed_between_check_and_commit_is_refused() { + if !aien_omega_compose::LINKED { + return; + } + let tmp = tempfile::tempdir().unwrap(); + let ws = tmp.path().join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + let proposer: crate::spine::ComposeProposer = + Arc::new(|_: &str, _: std::time::Duration| panic!("model ran")); + let b = Arc::new(ComposeBridge::new( + tmp.path().join("compose"), + proposer, + "t", + )); + DeskKey::create(&desk_key_path(b.dir())).unwrap(); + let hook = ProposerHook::new(b.clone()); + let wss = ws.display().to_string(); + let target = ws.join("NOTES.md"); + std::fs::write(&target, "one\ntwo\n").unwrap(); + let base = sha256_hex(b"one\ntwo\n"); + + let t2 = target.clone(); + let fired = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let f2 = fired.clone(); + *BEFORE_GRANT.lock().unwrap() = Some(Box::new(move || { + f2.store(true, std::sync::atomic::Ordering::SeqCst); + std::fs::write(&t2, "one\ntwo\nEXTRA\n").unwrap() + })); + let e = hook + .submit(&proposal(&b, &ws, "toctou1", &base), &wss) + .expect_err("a changed prior must be refused"); + *BEFORE_GRANT.lock().unwrap() = None; + // The seam sits after the compose commit, so firing proves the run reached it. + assert!( + fired.load(std::sync::atomic::Ordering::SeqCst), + "seam did not fire" + ); + eprintln!( + "TOCTOU seam fired after compose commit; refusal = {}: {}", + e.name, e.detail + ); + assert_eq!(e.name, "GrantNotWritten", "{e}"); + assert!(e.detail.contains("BaseChanged"), "{e}"); + + // Unchanged prior: the grant is written. + std::fs::write(&target, "one\ntwo\n").unwrap(); + let ok = hook + .submit(&proposal(&b, &ws, "toctou2", &base), &wss) + .unwrap_or_else(|e| panic!("unchanged prior must pass: {e}")); + assert_eq!(ok.state, "COMMITTED"); + } +} diff --git a/crates/aien-runtime/src/approved_auth.rs b/crates/aien-runtime/src/approved_auth.rs index 77bb7a41..c81fcacd 100644 --- a/crates/aien-runtime/src/approved_auth.rs +++ b/crates/aien-runtime/src/approved_auth.rs @@ -127,6 +127,32 @@ pub fn binding_bytes(id: &ApprovalIdentity) -> Vec { Value::Object(m).to_string().into_bytes() } +/// What the requirements MAC covers: a domain tag, the approval binding and +/// the requirement goal (a missing goal and an empty goal differ). +fn requirements_bytes(id: &ApprovalIdentity, goal: Option<&str>, base: Option<&str>) -> Vec { + // v2 adds the sha256 of the file the bytes replace (or "absent"); v1 is the + // binding of an approval whose requirements do not depend on the prior file. + let mut m = if base.is_some() { + b"aien.requirements.v2\0".to_vec() + } else { + b"aien.requirements.v1\0".to_vec() + }; + m.extend(binding_bytes(id)); + m.push(0); + match goal { + None => m.push(0), + Some(g) => { + m.push(1); + m.extend(g.as_bytes()); + } + } + if let Some(b) = base { + m.push(0); + m.extend(b.as_bytes()); + } + m +} + /// The durable replay key of an approval: sha256 (hex) of its binding. pub fn approval_key(id: &ApprovalIdentity) -> String { hex(&Sha256::digest(binding_bytes(id))) @@ -306,6 +332,32 @@ impl DeskKey { self.mac(&ApprovalIdentity::of(p, &ws, &self.id)) } + /// The MAC (hex) over the approval binding AND the bound requirements + /// (`p.requirements`, empty when None). A separate MAC so the identity + /// binding and its known-answer vector stay unchanged. + pub fn sign_requirements( + &self, + p: &crate::approved::ApprovedProposal, + workspace: &Path, + ) -> String { + let ws = canonical_workspace(workspace).unwrap_or_else(|_| workspace.display().to_string()); + let id = ApprovalIdentity::of(p, &ws, &self.id); + hex(&hmac_sha256( + &self.key, + &requirements_bytes( + &id, + p.requirements.as_deref(), + p.requirements_base.as_deref(), + ), + )) + } + + /// Desk side: set both MACs of `p` (the identity MAC and the requirements MAC). + pub fn seal(&self, p: &mut crate::approved::ApprovedProposal, workspace: &Path) { + p.approval_mac = self.sign(p, workspace); + p.requirements_mac = self.sign_requirements(p, workspace); + } + /// Daemon side: Ok(identity) only when `p.approval_mac` is this key's MAC /// over `p`'s binding; else `PROPOSAL_REFUSED Unauthenticated`. pub fn authenticate( @@ -318,7 +370,26 @@ impl DeskKey { let want = hmac_sha256(&self.key, &binding_bytes(&id)); let got = unhex32(&p.approval_mac); match got { - Some(g) if ct_eq(&g, &want) => Ok(id), + Some(g) if ct_eq(&g, &want) => { + let want_r = hmac_sha256( + &self.key, + &requirements_bytes( + &id, + p.requirements.as_deref(), + p.requirements_base.as_deref(), + ), + ); + match unhex32(&p.requirements_mac) { + Some(r) if ct_eq(&r, &want_r) => Ok(id), + _ => Err(refuse( + "Unauthenticated", + format!( + "requirements_mac is not the approval desk's (key {}) MAC over the bound requirements", + self.id + ), + )), + } + } _ => Err(refuse( "Unauthenticated", format!( diff --git a/crates/aien-runtime/src/control.rs b/crates/aien-runtime/src/control.rs index ccbc7d84..f1514667 100644 --- a/crates/aien-runtime/src/control.rs +++ b/crates/aien-runtime/src/control.rs @@ -386,6 +386,11 @@ pub struct ComposeTaskReport { /// ones checked. Empty = none recognized, nothing checked. #[serde(default)] pub requirements_recognized: Vec, + /// Goal text that looks like a measurable requirement but could not be + /// interpreted reliably (crate::requirements::analyze). Non-empty = the + /// task was refused before any model call. + #[serde(default)] + pub requirements_uncertain: Vec, /// "model" when the Skill ran inference, or the stub label. pub proposer: String, } diff --git a/crates/aien-runtime/src/effects.rs b/crates/aien-runtime/src/effects.rs index c7819148..dfed8963 100644 --- a/crates/aien-runtime/src/effects.rs +++ b/crates/aien-runtime/src/effects.rs @@ -858,11 +858,21 @@ pub(crate) fn write_approved_grant( ids: &Value, link: &ApprovedLink, proposal_sha256: &str, + base: Option<&str>, ) -> Result<(u64, String), String> { b.with_home(|home| { let target = Path::new(workspace).join(path).display().to_string(); confine_target(workspace, path, &target).map_err(|r| r.to_string())?; let prior = file_sha256(Path::new(&target))?; + // The file must still be the one the bound requirements were checked against. + if let Some(base) = base { + let now = prior.as_deref().unwrap_or("absent"); + if now != base { + return Err(format!( + "BaseChanged: {path} changed after the requirements were checked (bound {base}, now {now}); no grant was written" + )); + } + } let mut text = json!({ APPROVED_GRANT: 1, "proposal_sha256": proposal_sha256, "path": path, "content_sha256": content_sha256, "approver": approver, "target": target, diff --git a/crates/aien-runtime/src/lib.rs b/crates/aien-runtime/src/lib.rs index 053d75fe..f0973f0f 100644 --- a/crates/aien-runtime/src/lib.rs +++ b/crates/aien-runtime/src/lib.rs @@ -10,6 +10,7 @@ pub mod cortex_mark; pub mod destination; pub mod effects; pub mod requirements; +mod requirements_extract; 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 index 598d2696..60d1c073 100644 --- a/crates/aien-runtime/src/requirements.rs +++ b/crates/aien-runtime/src/requirements.rs @@ -1,31 +1,31 @@ //! 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). +//! A task goal can state a measurable requirement ("in at least 20 lines", +//! "sections titled A, B and C", "covers preparing and testing"). This module +//! defines a small typed set of requirements, extracts them deterministically +//! from the goal text ([`analyze`], in `requirements_extract`), and checks the +//! COMPLETE parsed document (the content that would be saved). //! -//! ## Supported requirements (everything else is NOT extracted) +//! ## Two outcomes of reading a goal //! -//! Extraction matches the exact word sequence `at least|at most N ` -//! (case-insensitive, N written in digits, N >= 1, trailing punctuation on a -//! word ignored) and `include|contain the phrase ""` (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. +//! [`analyze`] returns an [`Extraction`]: the RECOGNIZED requirements, and the +//! UNCERTAIN spans. An uncertain span is goal text that looks like an explicit +//! measurable requirement (a bound word and a number next to a document +//! noun, "titled", "covers", "include the word", ...) that extraction could +//! not interpret reliably. Uncertainty is never treated as satisfied: the +//! task is refused before any model call, the report lists the spans +//! (`ComposeTaskReport::requirements_uncertain`) and nothing is approved, +//! committed or written. //! -//! | 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 `. ` / `) ` | -//! | `at least N steps` | `MinItems(Steps, N)` | numbered list items only: `. ` / `) ` | -//! | `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 | +//! ## Supported requirements //! -//! `item`, `step`, `section`, `question` (singular) are accepted too. +//! The exact wordings are in the table of `requirements_extract`; in short: +//! counts (`at least|at most|no fewer than|no more than|a minimum of|up to| +//! more than|fewer than|N or more|N or fewer` with digits or number words +//! one..twenty) of lines, words, list items, steps, sections/headings and +//! questions; section titles (`sections titled A, B and C`), topics +//! (`covers A, B and C`), required words and phrases, and a minimum number +//! of sentences in every section. //! //! ## What a requirement is judged on //! @@ -33,16 +33,46 @@ //! not the model's reply). An edit only adds lines, so a prior file that //! already exceeds a `MaxLines` is refused before any attempt. //! +//! `AddedLines` (a request such as "add 2 lines to README.md") is the one requirement +//! measured against the PRIOR file: the number of non-empty lines of the complete +//! proposed bytes that are not in the longest common subsequence with the +//! prior file's non-empty lines (trailing whitespace ignored). A new file is +//! compared with an empty prior. Callers bind the prior with +//! `Extraction::resolved`; an unresolved `AddedLines` is unmet (fails closed). +//! An edit may only ADD: every non-empty line of the prior file must survive in +//! order (trailing whitespace may differ), otherwise the requirement is unmet +//! whatever the number of added lines. Replacing or deleting lines is a change the +//! goal did not ask for, so "add 2 lines" can never wipe or rewrite the file. +//! The approved path binds the file found in the workspace. +//! //! 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. +//! INCLUDING code lines and code-fence marker lines; `MinWords`/`MaxWords` +//! count every whitespace-separated word of the file. Sections, questions, +//! items, steps, headings, topics and sentences 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. +//! Definitions used by the checks: +//! - heading text: the heading line without its `#` run, leading numbering +//! (`1.`, `2)`), emphasis marks and trailing `:.!?#`, trimmed, whitespace +//! collapsed, compared case-insensitively. +//! - word form (topics): lowercase, strip ONE suffix of `ment ing ion es ed +//! s` (only when 3 or more letters remain), then one trailing `e` (when 4 +//! or more letters remain). `preparing`, `prepare` and `prepared` agree; +//! `publishing` and `public` do not. Irregular forms (`running` / `run`) +//! do not agree: the check errs on the side of refusing. +//! - sentence: a run of at least two words ended by `.`, `!` or `?` (not +//! inside a number such as `3.10`); an unfinished last fragment of at +//! least three words counts as one. List markers are ignored. +//! - section (for sentence counts): a heading and the prose directly under +//! it up to the next heading of any level. A heading with no prose of its +//! own whose next heading is deeper is a container, not a section. + +use std::collections::HashSet; + +pub use crate::requirements_extract::{analyze, extract, Extraction}; /// What a `MinItems` requirement counts. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -51,6 +81,8 @@ pub enum ItemKind { Steps, Sections, Questions, + /// Fenced code blocks (each opening fence line counts one). + CodeBlocks, } impl ItemKind { @@ -60,6 +92,7 @@ impl ItemKind { ItemKind::Steps => "numbered steps", ItemKind::Sections => "headings", ItemKind::Questions => "questions", + ItemKind::CodeBlocks => "fenced code blocks", } } } @@ -69,8 +102,47 @@ impl ItemKind { pub enum Requirement { MinLines(usize), MaxLines(usize), + MinWords(usize), + MaxWords(usize), MinItems(ItemKind, usize), + /// Case-insensitive substrings of the document. RequiredPhrases(Vec), + /// Whole words, case-insensitive. + RequiredWords(Vec), + /// Section titles that must each appear as a heading. + RequiredHeadings(Vec), + /// Topics (each a list of content words) that must each be covered: every + /// content word must appear in the prose as a word form. + RequiredTopics(Vec), + /// Every section holds at least this many sentences. + MinSentencesPerSection(usize), + /// Lines ADDED to the file, measured against the prior file (see the module + /// docs). `exact`: exactly `n`, else at least `n`. `prior` is None until + /// the caller resolves it ([`Extraction::resolved`]); an unresolved one is unmet. + AddedLines { + n: usize, + exact: bool, + prior: Option, + }, + /// The section with this title (None: the last section of the document) + /// holds at least `n` words of plain text (prose lines, no code, no headings). + SectionMinWords { + title: Option, + n: usize, + }, + /// Each title is present as a heading of exactly this level (1 to 6). + LevelHeadings { + level: usize, + titles: Vec, + }, +} + +fn quoted(items: &[String]) -> String { + items + .iter() + .map(|x| format!("\"{x}\"")) + .collect::>() + .join(", ") } impl Requirement { @@ -79,10 +151,29 @@ impl Requirement { match self { Requirement::MinLines(n) => format!("at least {n} non-empty lines"), Requirement::MaxLines(n) => format!("at most {n} non-empty lines"), + Requirement::MinWords(n) => format!("at least {n} words"), + Requirement::MaxWords(n) => format!("at most {n} words"), Requirement::MinItems(k, n) => format!("at least {n} {}", k.noun()), - Requirement::RequiredPhrases(p) => { - let q: Vec = p.iter().map(|x| format!("\"{x}\"")).collect(); - format!("the phrase {}", q.join(", ")) + Requirement::RequiredPhrases(p) => format!("the phrase {}", quoted(p)), + Requirement::RequiredWords(p) => format!("the words {}", quoted(p)), + Requirement::RequiredHeadings(p) => format!("the headings {}", quoted(p)), + Requirement::RequiredTopics(p) => format!("the topics {}", quoted(p)), + Requirement::MinSentencesPerSection(n) => { + format!("at least {n} sentences in every section") + } + Requirement::AddedLines { n, exact, .. } => { + if *exact { + format!("exactly {n} added non-empty lines") + } else { + format!("at least {n} added non-empty lines") + } + } + Requirement::SectionMinWords { title, n } => match title { + Some(t) => format!("at least {n} words of plain text in the section \"{t}\""), + None => format!("at least {n} words of plain text in the last section"), + }, + Requirement::LevelHeadings { level, titles } => { + format!("the level-{level} headings {}", quoted(titles)) } } } @@ -99,6 +190,14 @@ impl Requirement { let c = non_empty_lines(content); (c > *n).then(|| format!("{label}, found {c}")) } + Requirement::MinWords(n) => { + let c = content.split_whitespace().count(); + (c < *n).then(|| format!("{label}, found {c}")) + } + Requirement::MaxWords(n) => { + let c = content.split_whitespace().count(); + (c > *n).then(|| format!("{label}, found {c}")) + } Requirement::MinItems(k, n) => { let c = count_items(*k, content); (c < *n).then(|| format!("{label}, found {c}")) @@ -108,9 +207,122 @@ impl Requirement { let missing: Vec = p .iter() .filter(|x| !low.contains(&x.to_lowercase())) - .map(|x| format!("\"{x}\"")) + .cloned() + .collect(); + (!missing.is_empty()).then(|| format!("{label}, missing {}", quoted(&missing))) + } + Requirement::RequiredWords(p) => { + let have: HashSet = words_of(content).into_iter().collect(); + let missing: Vec = p + .iter() + .filter(|x| !have.contains(&x.to_lowercase())) + .cloned() + .collect(); + (!missing.is_empty()).then(|| format!("{label}, missing {}", quoted(&missing))) + } + Requirement::RequiredHeadings(p) => { + let have: HashSet = parse_sections(content) + .into_iter() + .map(|s| s.title) + .collect(); + let missing: Vec = p + .iter() + .filter(|x| !have.contains(&normalize_title(x))) + .cloned() + .collect(); + (!missing.is_empty()).then(|| { + format!( + "{label}, missing {} (each must be a markdown heading line)", + quoted(&missing) + ) + }) + } + Requirement::RequiredTopics(p) => { + let have: HashSet = words_of(&prose_lines(content).join("\n")) + .iter() + .map(|w| stem(w)) + .collect(); + let missing: Vec = p + .iter() + .filter(|t| !content_words(t).iter().all(|w| have.contains(&stem(w)))) + .cloned() .collect(); - (!missing.is_empty()).then(|| format!("{label}, missing {}", missing.join(", "))) + (!missing.is_empty()).then(|| { + format!( + "{label}, not covered: {} (use those words, or their word forms, in the text)", + missing.join(", ") + ) + }) + } + Requirement::AddedLines { n, exact, prior } => { + let Some(prior) = prior else { + return Some(format!( + "{label} cannot be measured: the existing file was not provided" + )); + }; + let (c, lost) = match added_non_empty_lines(prior, content) { + Ok(c) => c, + Err(e) => return Some(format!("{label} cannot be measured: {e}")), + }; + if lost > 0 { + return Some(format!( + "{label}, but {lost} existing non-empty line(s) were changed or removed (every existing line must stay, in order; only trailing whitespace may differ)" + )); + } + let bad = if *exact { c != *n } else { c < *n }; + bad.then(|| format!("{label}, found {c}")) + } + Requirement::SectionMinWords { title, n } => { + let secs = parse_sections(content); + let sec = match title { + Some(t) => secs.iter().find(|s| s.title == normalize_title(t)), + None => secs.last(), + }; + let Some(sec) = sec else { + return Some(format!("{label}, the section was not found")); + }; + let c = sec + .body + .split_whitespace() + .filter(|w| w.chars().any(char::is_alphanumeric)) + .count(); + (c < *n).then(|| format!("{label}, found {c}")) + } + Requirement::LevelHeadings { level, titles } => { + let secs = parse_sections(content); + let missing: Vec = titles + .iter() + .filter(|t| { + !secs + .iter() + .any(|s| s.level == *level && s.title == normalize_title(t)) + }) + .cloned() + .collect(); + (!missing.is_empty()).then(|| { + format!( + "{label}, missing {} (each must be a level-{level} markdown heading line)", + quoted(&missing) + ) + }) + } + Requirement::MinSentencesPerSection(n) => { + let secs = parse_sections(content); + if secs.is_empty() { + return Some(format!("{label}, found no headings")); + } + let short: Vec = secs + .iter() + .filter(|s| !s.container) + .filter_map(|s| { + let c = count_sentences(&s.body); + (c < *n).then(|| format!("{} ({c})", s.raw_title)) + }) + .collect(); + (!short.is_empty()).then(|| { + let shown: Vec = short.iter().take(8).cloned().collect(); + format!("{label}, too few in: {}", shown.join(", ")) + }) } } } @@ -120,6 +332,156 @@ fn non_empty_lines(s: &str) -> usize { s.lines().filter(|l| !l.trim().is_empty()).count() } +/// Lowercase alphanumeric words (apostrophes kept inside a word). +fn words_of(s: &str) -> Vec { + s.split(|c: char| !(c.is_alphanumeric() || c == '\'')) + .map(|w| w.trim_matches('\'').to_lowercase()) + .filter(|w| !w.is_empty()) + .collect() +} + +const STOPWORDS: [&str; 30] = [ + "a", "an", "the", "of", "to", "for", "and", "or", "in", "on", "with", "your", "you", "our", + "their", "its", "it", "is", "are", "be", "as", "at", "by", "from", "into", "about", "this", + "that", "new", "all", +]; + +/// The content words of a topic: its words minus the small stop list. +pub(crate) fn content_words(topic: &str) -> Vec { + words_of(topic) + .into_iter() + .filter(|w| !STOPWORDS.contains(&w.as_str())) + .collect() +} + +/// Conservative word form (see the module docs). +pub(crate) fn stem(w: &str) -> String { + let mut s = w.to_lowercase(); + for suf in ["ment", "ing", "ion", "es", "ed", "s"] { + if s.len() >= suf.len() + 3 && s.ends_with(suf) { + s.truncate(s.len() - suf.len()); + break; + } + } + if s.len() >= 4 && s.ends_with('e') { + s.pop(); + } + s +} + +/// Heading text as compared: see the module docs. +pub(crate) fn normalize_title(t: &str) -> String { + let t: String = t + .chars() + .filter(|c| !matches!(c, '*' | '_' | '`')) + .collect(); + let t = t.trim().trim_end_matches('#').trim(); + let d = t.chars().take_while(|c| c.is_ascii_digit()).count(); + let t = if d > 0 && matches!(t[d..].chars().next(), Some('.') | Some(')')) { + t[d + 1..].trim_start() + } else { + t + }; + let t = t.trim_end_matches([':', '.', '!', '?']); + t.split_whitespace() + .collect::>() + .join(" ") + .to_lowercase() +} + +struct Section { + /// Normalized title (compared) and the title as written (reported). + title: String, + raw_title: String, + /// Prose directly under the heading, headings excluded. + body: String, + /// No prose of its own and the next heading is deeper. + container: bool, + /// Heading level, 1 to 6. + level: usize, +} + +fn heading_of(t: &str) -> Option<(usize, &str)> { + let t = t.trim(); + let h = t.chars().take_while(|&c| c == '#').count(); + ((1..=6).contains(&h) && t[h..].starts_with(' ') && !t[h..].trim().is_empty()) + .then(|| (h, t[h..].trim())) +} + +fn parse_sections(content: &str) -> Vec
{ + let lines = prose_lines(content); + let heads: Vec<(usize, usize, &str)> = lines + .iter() + .enumerate() + .filter_map(|(i, l)| heading_of(l).map(|(lv, t)| (i, lv, t))) + .collect(); + heads + .iter() + .enumerate() + .map(|(k, &(i, lv, t))| { + let end = heads.get(k + 1).map_or(lines.len(), |h| h.0); + let body = lines[i + 1..end].join("\n"); + let next_deeper = heads.get(k + 1).is_some_and(|n| n.1 > heads[k].1); + Section { + title: normalize_title(t), + raw_title: t.trim_end_matches('#').trim().to_string(), + container: body.trim().is_empty() && next_deeper, + level: lv, + body, + } + }) + .collect() +} + +fn count_sentences(body: &str) -> usize { + let mut text = String::new(); + for l in body.lines() { + let mut t = l.trim(); + if let Some(r) = ["- ", "* ", "+ "].iter().find_map(|m| t.strip_prefix(m)) { + t = r; + } else { + let d = t.chars().take_while(|c| c.is_ascii_digit()).count(); + if d > 0 + && matches!(t[d..].chars().next(), Some('.') | Some(')')) + && t[d + 1..].starts_with(' ') + { + t = &t[d + 2..]; + } + } + text.push_str(t); + text.push(' '); + } + let chars: Vec = text.chars().collect(); + let (mut count, mut cur) = (0usize, String::new()); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + cur.push(c); + if matches!(c, '.' | '!' | '?') { + let mut j = i + 1; + while j < chars.len() && matches!(chars[j], '.' | '!' | '?' | '"' | '\'' | ')') { + cur.push(chars[j]); + j += 1; + } + if j >= chars.len() || chars[j].is_whitespace() { + if cur.split_whitespace().count() >= 2 { + count += 1; + } + cur.clear(); + i = j; + continue; + } + i = j; + continue; + } + i += 1; + } + if cur.split_whitespace().count() >= 3 { + count += 1; + } + 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(' ') @@ -161,6 +523,9 @@ fn prose_lines(s: &str) -> Vec<&str> { } fn count_items(k: ItemKind, s: &str) -> usize { + if k == ItemKind::CodeBlocks { + return count_code_blocks(s); + } prose_lines(s) .into_iter() .map(str::trim) @@ -174,6 +539,7 @@ fn count_items(k: ItemKind, s: &str) -> usize { (1..=6).contains(&h) && t[h..].starts_with(' ') && !t[h..].trim().is_empty() } ItemKind::Questions => t.ends_with('?'), + ItemKind::CodeBlocks => false, }) .count() } @@ -189,156 +555,61 @@ pub fn refusal_reason(reqs: &[Requirement], content: &str) -> Option { (!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; +/// Fenced code blocks: every opening fence line counts one (same fence rule as +/// `prose_lines`; an unclosed block counts once). +fn count_code_blocks(s: &str) -> usize { + let mut open: Option<(char, usize)> = None; + let mut blocks = 0; + for l in s.lines() { + match (open, fence_marker(l)) { + (None, Some((c, n, _))) => { + open = Some((c, n)); + blocks += 1; + } + (Some((c, n)), Some((c2, n2, info))) if c2 == c && n2 >= n && !info => open = None, + _ => {} } } - false + blocks } -/// 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))) -} +/// Largest line-pair table the added-line diff will build. +const DIFF_MAX_CELLS: usize = 25_000_000; -/// 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 { - 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 = 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::() 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)), - _ => {} - } +/// (added, lost): `added` counts the non-empty lines of `content` outside the longest +/// common subsequence with the non-empty lines of `prior` (lines compared with +/// trailing whitespace ignored); `lost` counts the prior non-empty lines outside it, +/// i.e. changed or removed ones. For an edit, which keeps every prior line, +/// this is the number of lines the edit added; for whole replacement bytes it +/// is the diff against the file they replace. +pub(crate) fn added_non_empty_lines(prior: &str, content: &str) -> Result<(usize, usize), String> { + let a: Vec<&str> = prior + .lines() + .map(str::trim_end) + .filter(|l| !l.trim().is_empty()) + .collect(); + let b: Vec<&str> = content + .lines() + .map(str::trim_end) + .filter(|l| !l.trim().is_empty()) + .collect(); + if a.len().saturating_mul(b.len()) > DIFF_MAX_CELLS { + return Err(format!( + "the diff is too large ({} prior lines x {} lines)", + a.len(), + b.len() + )); } - // include|contain the phrase "X": the text is taken from the original - // goal (case kept), between straight double quotes. - let mut phrases: Vec = 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; + // Rolling-row longest common subsequence length. + let mut row = vec![0usize; b.len() + 1]; + for x in &a { + let mut diag = 0; + for (j, y) in b.iter().enumerate() { + let up = row[j + 1]; + row[j + 1] = if x == y { diag + 1 } else { up.max(row[j]) }; + diag = up; } } - if !phrases.is_empty() { - push(Requirement::RequiredPhrases(phrases)); - } - out + let common = row[b.len()]; + Ok((b.len() - common, a.len() - common)) } diff --git a/crates/aien-runtime/src/requirements_extract.rs b/crates/aien-runtime/src/requirements_extract.rs new file mode 100644 index 00000000..432a1529 --- /dev/null +++ b/crates/aien-runtime/src/requirements_extract.rs @@ -0,0 +1,1550 @@ +//! Reading the requirements out of a goal (see `requirements` for the model). +//! +//! `analyze` is rule based and deterministic. It returns the requirements it +//! recognized AND the spans of goal text that look like explicit measurable +//! requirements but could not be interpreted reliably (`Extraction::uncertain`). +//! A caller must refuse a task with uncertain spans: uncertainty is never +//! treated as satisfied. +//! +//! ## Recognized wordings (case-insensitive; trailing punctuation on a word is ignored) +//! +//! | goal wording | requirement | +//! |---|---| +//! | `at least / no fewer than / no less than / not fewer than / a minimum of / minimum of / min N `, `N or more `, `N+ ` | `MinX(N)` | +//! | `at most / no more than / not more than / a maximum of / maximum of / max / up to N `, `N or fewer|less ` | `MaxX(N)` | +//! | `more than N `, `fewer|less than N ` | `MinX(N+1)`, `MaxX(N-1)` | +//! | `N or more|fewer|less`, `N minimum|maximum`, `no longer|shorter than N ` | `MinX(N)` or `MaxX(N)` | +//! | `` = `lines`, `words`; `items`, `steps`, `sections`, `headings`, `questions` (Min only; singular too) | lines, words, list items, numbered steps, headings, questions | +//! | `N sentences in|per|for|within every|each section` (or `in every section, ... N sentences`) | `MinSentencesPerSection(N)` | +//! | `sections|headings titled|named|called A, B and C`, `sections: A, B and C` | `RequiredHeadings` | +//! | `covers|covering A, B and C` (and `to|should|must|will|can cover ...`) | `RequiredTopics` | +//! | `include|contain|use|mention the word(s)|term(s) X, Y` or `"X", "Y"` | `RequiredWords` | +//! | `include|contain|use|mention the phrase "X"` / `the phrases "X", "Y"` | `RequiredPhrases` | +//! | `add|append|insert|with N line(s)`, `exactly N lines` after such a verb, `a N-line ` after a verb | `AddedLines` exactly N | +//! | `write|put|create|draft|compose|produce|generate N line(s)` | `AddedLines` at least N | +//! | ` N lines is|are needed|required|necessary` (a trailing status word) | the same as the bound without it | +//! | `... section titled "T" that holds at least N words of plain text`, `the last section ... N words of plain text` | `SectionMinWords` | +//! | `N level-two|level-2|second-level|h2 sections titled A, B and C` | `LevelHeadings` (those headings at that level; extra headings of the level are allowed) | +//! | `include|add|put|provide N [separate] fenced code examples|blocks`, or a bound cue before N | `MinItems(CodeBlocks)` | +//! +//! Bare line counts. The VERB decides the reading, no task wording is built in. An +//! edit (the goal names an existing file) is judged on the diff between that file +//! and the exact proposed bytes (non-empty lines of the proposal that are not in +//! the longest common subsequence with the file's non-empty lines); a new file +//! counts as an edit of the empty file. `add 2 lines` therefore means exactly two +//! non-empty lines were added; `write 20 lines` at least twenty. The count must end +//! its clause or be followed by `to in into at for about on saying describing giving +//! listing ...`; `3 lines of context`, `10 lines per section` stay UNCERTAIN. +//! "N-sentence" and "one-sentence" are NOT read: a sentence count over a whole document +//! cannot be verified reliably (headings, lists, abbreviations), so such a goal +//! is UNCERTAIN and refused. `N words of plain text` without a named section +//! (`section titled "T"`, `the last section`) is a count over an unknown scope and +//! is UNCERTAIN. `three topics: a, b, c` is not mechanically checkable and is UNCERTAIN. +//! "N lines at least" is a lower bound; "a single line" is exactly one. Left UNCERTAIN on +//! purpose: ranges ("2-3 lines"), "a dozen lines", "three-plus sections", "line count at +//! least 40", counts of shell commands or snippets, level-two headings given as a bare +//! list, and a section title that itself holds a count. "a couple of", "a few", +//! "several" and "add a line" (no number) state no number and stay silent. +//! The machine goal of an approved run ("apply approved proposal for ...") +//! is never analysed; the goal bound into the approval is. +//! +//! `N` is digits or a number word (`one` to `twenty`, tens up to `hundred`, +//! `twenty-five`), at least 1. +//! +//! Safety net: after the recognizers, any number (digits or one..hundred) within three +//! words of a countable document noun (line, word, sentence, paragraph, section, +//! heading, bullet, point, item, step, block, example, question, topic, character, page, +//! table, row, column), a quantity cue (`twice minimum maximum limit or more/fewer no +//! longer than`) near such a noun, and heading or word list cues without a number +//! (`headings for`, `a Summary heading`, `these words:`) that no recognizer consumed is +//! UNCERTAIN. A bare count ("Keep it to 10 lines", "three sections") is therefore +//! uncertain, never silent. Numbers without such a noun ("Fix the 2 typos") are ignored. +//! +//! Rules that keep it conservative: +//! - the counted noun must END its clause: closing punctuation, end of goal, a +//! joiner (`and or but so then because that which covering`) or one of +//! `long with total overall titled named called about on including +//! containing`, or `in total`. "3 lines of context", "5 items per category", +//! "at least 4 questions in the survey" qualify the count and are UNCERTAIN. +//! - a negator (`not no never without avoid` and contractions) up to 4 words +//! before, in the same clause, makes the span UNCERTAIN (never inverted). +//! - emphasis or quotes around the wording (`**at least 20 lines**`) are not +//! recognized and the span is UNCERTAIN. +//! - a bound word with a number and a noun that is not supported (`at most 5 +//! items`, `at least 3 paragraphs`, `exactly 20 lines`, `about 30 lines`, +//! `between 10 and 20 lines`, `35-line` with no verb before it) is UNCERTAIN. +//! - a title list whose parsed length differs from a declared count ("6 +//! sections titled A, B, C") is UNCERTAIN; so is a list item that is not a +//! short noun phrase. +//! - the title or topic list is the text after the key word up to the end of +//! the sentence (or `, each|with|which|that|...`, or a count bound); a +//! trailing `and` splits the LAST comma item (`Who to ask and Glossary`), +//! so a title that itself contains `and` is only safe inside the list. + +use crate::requirements::{content_words, ItemKind, Requirement}; + +/// What a goal says: recognized requirements and the spans it could not read. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Extraction { + pub requirements: Vec, + /// Goal text that looks like an explicit measurable requirement but could + /// not be interpreted reliably. Non-empty = the task must be refused. + pub uncertain: Vec, +} + +impl Extraction { + /// True when a requirement is measured against the prior file + /// ([`Requirement::AddedLines`]) and so needs [`Extraction::resolved`]. + pub fn needs_prior(&self) -> bool { + self.requirements + .iter() + .any(|r| matches!(r, Requirement::AddedLines { .. })) + } + + /// The same extraction with every added-line requirement bound to the + /// content of the file the proposal replaces (`""` for a new file). + pub fn resolved(mut self, prior: &str) -> Self { + for r in &mut self.requirements { + if let Requirement::AddedLines { prior: p, .. } = r { + *p = Some(prior.to_string()); + } + } + self + } + + /// The refusal reason when any span is uncertain. + pub fn refusal(&self) -> Option { + (!self.uncertain.is_empty()).then(|| { + let spans: Vec = self.uncertain.iter().map(|s| format!("\"{s}\"")).collect(); + format!( + "uncertain requirement: the goal states a measurable requirement this runtime could not interpret reliably, so nothing was proposed: {}", + spans.join("; ") + ) + }) + } +} + +/// Only the recognized requirements (see [`analyze`] for the uncertain spans). +pub fn extract(goal: &str) -> Vec { + analyze(goal).requirements +} + +struct Tok { + /// Lowercase with its punctuation. + raw: String, + /// `raw` without surrounding clause punctuation. + word: String, + /// `word` without emphasis and quote marks too. + norm: String, + start: usize, + end: usize, +} + +fn clean(w: &str) -> &str { + w.trim_matches(|c: char| matches!(c, ',' | '.' | ';' | ':' | '!' | '?' | '(' | ')')) +} + +fn plain(w: &str) -> &str { + w.trim_matches(|c: char| { + matches!( + c, + ',' | '.' | ';' | ':' | '!' | '?' | '(' | ')' | '*' | '_' | '"' | '\'' | '`' + ) + }) +} + +fn tokenize(goal: &str) -> Vec { + let mut out = Vec::new(); + let mut start: Option = None; + let push = |out: &mut Vec, s: usize, e: usize| { + let raw = goal[s..e].to_ascii_lowercase(); + out.push(Tok { + word: clean(&raw).to_string(), + norm: plain(&raw).to_string(), + raw, + start: s, + end: e, + }); + }; + for (i, c) in goal.char_indices() { + if c.is_whitespace() { + if let Some(s) = start.take() { + push(&mut out, s, i); + } + } else if start.is_none() { + start = Some(i); + } + } + if let Some(s) = start { + push(&mut out, s, goal.len()); + } + out +} + +/// 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", +]; + +/// Other words that may follow the counted noun without changing its meaning. +const NOUN_FOLLOWERS: [&str; 11] = [ + "please", "thanks", "long", "with", "total", "overall", "titled", "named", "called", "about", + "on", +]; +const NOUN_FOLLOWERS_2: [&str; 2] = ["including", "containing"]; + +/// 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(toks: &[Tok], at: usize) -> bool { + for i in (at.saturating_sub(4)..at).rev() { + if ends_clause(&toks[i].raw) { + return false; + } + if NEGATORS.contains(&toks[i].word.as_str()) { + return true; + } + } + false +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Dir { + Min, + Max, +} + +/// (cue words, direction, adjustment: +1 strict min, -1 strict max). +const CUES: [(&[&str], Dir, i64); 22] = [ + (&["no", "longer", "than"], Dir::Max, 0), + (&["no", "shorter", "than"], Dir::Min, 0), + (&["no", "fewer", "than"], Dir::Min, 0), + (&["no", "less", "than"], Dir::Min, 0), + (&["not", "fewer", "than"], Dir::Min, 0), + (&["not", "less", "than"], Dir::Min, 0), + (&["no", "more", "than"], Dir::Max, 0), + (&["not", "more", "than"], Dir::Max, 0), + (&["a", "minimum", "of"], Dir::Min, 0), + (&["a", "maximum", "of"], Dir::Max, 0), + (&["minimum", "of"], Dir::Min, 0), + (&["maximum", "of"], Dir::Max, 0), + (&["at", "least"], Dir::Min, 0), + (&["at", "most"], Dir::Max, 0), + (&["more", "than"], Dir::Min, 1), + (&["fewer", "than"], Dir::Max, -1), + (&["less", "than"], Dir::Max, -1), + (&["up", "to"], Dir::Max, 0), + (&["minimum"], Dir::Min, 0), + (&["maximum"], Dir::Max, 0), + (&["min"], Dir::Min, 0), + (&["max"], Dir::Max, 0), +]; + +/// Cue words that state a bound or a size this module does not interpret. +const VAGUE: [&str; 11] = [ + "exactly", + "exact", + "about", + "around", + "approximately", + "roughly", + "nearly", + "between", + "over", + "under", + "below", +]; + +const NOUNS: [&str; 46] = [ + "topic", + "topics", + "block", + "blocks", + "table", + "tables", + "column", + "columns", + "line", + "lines", + "word", + "words", + "item", + "items", + "step", + "steps", + "section", + "sections", + "heading", + "headings", + "question", + "questions", + "sentence", + "sentences", + "paragraph", + "paragraphs", + "bullet", + "bullets", + "point", + "points", + "entry", + "entries", + "row", + "rows", + "example", + "examples", + "page", + "pages", + "chapter", + "chapters", + "character", + "characters", + "command", + "commands", + "snippet", + "snippets", +]; + +/// Verbs that introduce a bare line count (`true` = exactly N added lines). +fn line_verb(w: &str) -> Option { + match w { + "add" | "append" | "insert" | "with" => Some(true), + "write" | "put" | "create" | "draft" | "compose" | "produce" | "generate" => Some(false), + _ => None, + } +} + +/// Words that may follow "N lines" without qualifying the count. +const LINE_TAILS: [&str; 22] = [ + "to", + "in", + "into", + "at", + "for", + "saying", + "describing", + "giving", + "listing", + "explaining", + "stating", + "that", + "which", + "under", + "after", + "before", + "below", + "above", + "telling", + "naming", + "mentioning", + "summarizing", +]; + +const CODE_NOUNS: [&str; 6] = [ + "example", "examples", "block", "blocks", "snippet", "snippets", +]; +const CODE_ADJ: [&str; 13] = [ + "separate", + "fenced", + "code", + "shell", + "bash", + "distinct", + "different", + "small", + "short", + "runnable", + "sample", + "markdown", + "command-line", +]; +const CODE_VERBS: [&str; 12] = [ + "include", "includes", "add", "put", "provide", "give", "show", "use", "with", "contain", + "contains", "have", +]; + +const SECTION_NOUNS: [&str; 8] = [ + "sections", "section", "headings", "heading", "chapters", "chapter", "parts", "part", +]; + +#[derive(Debug, PartialEq, Eq)] +enum Num { + Val(usize), + /// Looks like a number (starts with a digit) but is zero or unparseable. + Bad, + Not, +} + +fn small(w: &str) -> Option { + const ONES: [&str; 20] = [ + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", + "ten", + "eleven", + "twelve", + "thirteen", + "fourteen", + "fifteen", + "sixteen", + "seventeen", + "eighteen", + "nineteen", + "twenty", + ]; + const TENS: [(&str, usize); 8] = [ + ("thirty", 30), + ("forty", 40), + ("fifty", 50), + ("sixty", 60), + ("seventy", 70), + ("eighty", 80), + ("ninety", 90), + ("hundred", 100), + ]; + if let Some(i) = ONES.iter().position(|x| *x == w) { + return Some(i + 1); + } + TENS.iter().find(|(x, _)| *x == w).map(|(_, v)| *v) +} + +fn parse_num(w: &str) -> Num { + if w.is_empty() { + return Num::Not; + } + if w.chars().all(|c| c.is_ascii_digit()) { + return match w.parse::() { + Ok(n) if n > 0 => Num::Val(n), + _ => Num::Bad, + }; + } + if let Some(n) = small(w) { + return Num::Val(n); + } + if let Some((t, o)) = w.split_once('-') { + if let (Some(t), Some(o)) = (small(t), small(o)) { + if t >= 20 && t % 10 == 0 && t < 100 && o < 10 { + return Num::Val(t + o); + } + } + } + if w.starts_with(|c: char| c.is_ascii_digit()) + || w.strip_prefix('-') + .is_some_and(|r| r.starts_with(|c: char| c.is_ascii_digit())) + { + return Num::Bad; + } + Num::Not +} + +/// Match a cue at `s`; (length in tokens, direction, adjustment). +fn match_cue(toks: &[Tok], s: usize, norm: bool) -> Option<(usize, Dir, i64)> { + let w = |i: usize| -> Option<&str> { + toks.get(i).map(|t| { + if norm { + t.norm.as_str() + } else { + t.word.as_str() + } + }) + }; + CUES.iter().find_map(|(words, dir, adj)| { + words + .iter() + .enumerate() + .all(|(k, x)| w(s + k) == Some(*x)) + .then_some((words.len(), *dir, *adj)) + }) +} + +fn qualifier_ok(toks: &[Tok], j: usize) -> bool { + if ends_clause(&toks[j].raw) { + return true; + } + match toks.get(j + 1) { + None => true, + Some(n) => { + let w = n.word.as_str(); + let status = |s: &str| { + matches!( + s, + "needed" | "required" | "necessary" | "expected" | "enough" | "sufficient" + ) + }; + status(w) + || (matches!(w, "is" | "are") + && toks.get(j + 2).is_some_and(|t| status(t.word.as_str()))) + || CLAUSE_JOINERS.contains(&w) + || NOUN_FOLLOWERS.contains(&w) + || NOUN_FOLLOWERS_2.contains(&w) + || (w == "in" && toks.get(j + 2).is_some_and(|t| clean(&t.raw) == "total")) + } + } +} + +/// Mark the tokens that start inside the byte range as consumed. +fn mark_bytes(handled: &mut std::collections::BTreeSet, toks: &[Tok], lo: usize, hi: usize) { + for (i, t) in toks.iter().enumerate() { + if t.start >= lo && t.start < hi { + handled.insert(i); + } + } +} + +/// True when the text holds a number next to a countable noun ("5 steps"). +fn has_count_and_noun(t: &str) -> bool { + let w: Vec = t + .split_whitespace() + .map(|x| plain(&x.to_ascii_lowercase()).to_string()) + .collect(); + (0..w.len()).any(|i| { + matches!(parse_num(&w[i]), Num::Val(_)) + && (i + 1..=i + 2).any(|j| w.get(j).is_some_and(|x| NOUNS.contains(&x.as_str()))) + }) +} + +/// Text of the goal from token `from` to the end of its clause (at most 10 tokens). +fn snippet(goal: &str, toks: &[Tok], from: usize, commas: bool) -> String { + let ends = |raw: &str| { + if commas { + ends_clause(raw) + } else { + raw.ends_with(['.', '!', '?', ';']) + } + }; + let mut to = from; + while to + 1 < toks.len() && to < from + 9 && !ends(&toks[to].raw) { + to += 1; + } + goal[toks[from].start..toks[to].end] + .trim_end_matches([',', '.', ';', ':', '!', '?']) + .to_string() +} + +/// Sentence-counting words after the noun: `in|per|for|within [every|each|a|the|any] section(s)`. +fn per_section_after(toks: &[Tok], j: usize) -> Option { + let w = |i: usize| toks.get(i).map(|t| t.word.as_str()); + if !matches!(w(j + 1), Some("in" | "per" | "for" | "within" | "under")) { + return None; + } + let mut k = j + 2; + if matches!(w(k), Some("every" | "each" | "a" | "the" | "any")) { + k += 1; + } + matches!(w(k), Some("section" | "sections" | "heading" | "headings")).then_some(k) +} + +/// "In every section, write ... N sentences": every|each section earlier in the sentence. +fn every_section_before(toks: &[Tok], s: usize) -> bool { + for m in (s.saturating_sub(10)..s).rev() { + if m >= 1 + && matches!(toks[m - 1].word.as_str(), "every" | "each") + && matches!(toks[m].word.as_str(), "section" | "heading") + { + return true; + } + if ends_clause(&toks[m].raw) + && m + 1 != s + && !matches!(toks[m].word.as_str(), "section" | "heading") + { + return false; + } + } + false +} + +/// The text after a key word up to the end of its clause. +fn list_region(goal: &str, from: usize) -> &str { + let rest = &goal[from..]; + let b = rest.as_bytes(); + let mut end = rest.len(); + for (i, c) in rest.char_indices() { + if matches!(c, '.' | '!' | '?' | ';' | '\n') + && (i + 1 >= b.len() || (b[i + 1] as char).is_whitespace()) + { + end = i; + break; + } + } + let mut region = &rest[..end]; + let low = region.to_ascii_lowercase(); + let mut cut = region.len(); + for m in [ + ", each ", + ", with ", + ", which ", + ", that ", + ", where ", + ", but ", + ", so ", + ", because ", + ", then ", + ", and each ", + ", and write ", + ", and make ", + " at least ", + " at most ", + " no more than ", + " no fewer than ", + " a minimum of ", + " up to ", + ] { + if let Some(i) = low.find(m) { + cut = cut.min(i); + } + } + region = ®ion[..cut]; + // A bound often follows as "... in|of|with|and at least N": drop the dangling joiner. + let t = region.trim_end(); + for tail in [" in", " of", " with", " and", " or", " within"] { + if t.to_ascii_lowercase().ends_with(tail) { + return &t[..t.len() - tail.len()]; + } + } + t +} + +fn quoted_items(region: &str) -> Vec { + let mut out = Vec::new(); + let mut open: Option = None; + for (i, c) in region.char_indices() { + match (c, open) { + ('"' | '\u{201C}', None) => open = Some(i + c.len_utf8()), + ('"' | '\u{201D}', Some(s)) => { + let t = region[s..i].trim(); + if !t.is_empty() { + out.push(t.to_string()); + } + open = None; + } + _ => {} + } + } + out +} + +/// "of plain text", "of prose", "of body text" after a word count: the index of +/// the last token of that phrase. +fn plain_text_after(toks: &[Tok], j: usize) -> Option { + let w = |i: usize| toks.get(i).map(|t| t.word.as_str()); + if w(j + 1) != Some("of") { + return None; + } + let mut k = j + 2; + if matches!(w(k), Some("plain" | "body" | "running" | "normal")) { + k += 1; + } + matches!(w(k), Some("text" | "prose" | "writing" | "plain-text")).then_some(k) +} + +/// The section a sentence names before token `s`: `Some(None)` for "the last +/// (or final) section", `Some(Some(title))` for `section titled "Title"` (a +/// quoted title, or up to four plain words), None when the sentence names no +/// section. +fn section_scope_before(goal: &str, toks: &[Tok], s: usize) -> Option> { + let mut m = s; + while m > 0 { + m -= 1; + if m + 1 < s && toks[m].raw.ends_with(['.', '!', '?']) { + return None; + } + let w = toks[m].word.as_str(); + if matches!(w, "last" | "final") + && toks + .get(m + 1) + .is_some_and(|t| matches!(t.word.as_str(), "section" | "heading")) + { + return Some(None); + } + if matches!(w, "titled" | "named" | "called") + && m >= 1 + && matches!(toks[m - 1].word.as_str(), "section" | "heading") + { + let rest = goal[toks[m].end..].trim_start(); + if rest.starts_with(['"', '\u{201C}']) { + let (q, _) = leading_quoted_items(rest); + return q.first().map(|t| Some(t.clone())); + } + let title: Vec<&str> = toks[m + 1..s] + .iter() + .take_while(|t| { + !matches!( + t.word.as_str(), + "that" + | "which" + | "with" + | "who" + | "where" + | "holds" + | "has" + | "and" + | "contains" + | "having" + ) && !t.raw.ends_with([',', '.', ';', ':']) + }) + .map(|t| t.raw.as_str()) + .collect(); + return (!title.is_empty() && title.len() <= 4).then(|| Some(title.join(" "))); + } + } + None +} + +/// The heading level an adjective names: `level-two`, `level-2`, `second-level`, `h2`. +fn level_adj(w: &str) -> Option { + let lv = |v: usize| (1..=6).contains(&v).then_some(v); + if let Some(r) = w.strip_prefix("level-") { + return match parse_num(r) { + Num::Val(v) => lv(v), + _ => None, + }; + } + if let Some(r) = w.strip_suffix("-level") { + return ["first", "second", "third", "fourth", "fifth", "sixth"] + .iter() + .position(|x| *x == r) + .map(|p| p + 1); + } + let b = w.as_bytes(); + (b.len() == 2 && b[0] == b'h' && (b'1'..=b'6').contains(&b[1])).then(|| (b[1] - b'0') as usize) +} + +/// The consecutive quoted items a region STARTS with, separated only by +/// commas, `and` or `or`; the byte offset just after the last one is returned +/// too. Empty when the region does not start with a quote. +fn leading_quoted_items(region: &str) -> (Vec, usize) { + let mut out = Vec::new(); + let mut at = 0; + loop { + let rest = ®ion[at..]; + let t = rest.trim_start_matches(|c: char| c.is_whitespace() || c == ','); + let t_lc = t.to_ascii_lowercase(); + let skip = if !out.is_empty() { + ["and ", "or "] + .iter() + .find(|p| t_lc.starts_with(**p)) + .map_or(0, |p| p.len()) + } else { + 0 + }; + let t2 = t[skip..].trim_start(); + let Some(open) = t2.chars().next().filter(|c| matches!(c, '"' | '\u{201C}')) else { + break; + }; + let body = &t2[open.len_utf8()..]; + let Some(close) = body.find(['"', '\u{201D}']) else { + break; + }; + let item = body[..close].trim(); + if !item.is_empty() { + out.push(item.to_string()); + } + at = region.len() - body.len() + close + 1; + } + (out, at) +} + +/// Comma separated items; the LAST comma item is also split at its last `and`/`or`. +fn split_list(region: &str) -> Vec { + let strip = |s: &str| -> String { + let t = s.trim(); + let l = t.to_ascii_lowercase(); + for p in ["and ", "or "] { + if l.starts_with(p) { + return t[p.len()..].trim().to_string(); + } + } + t.to_string() + }; + let mut segs: Vec = region + .split(',') + .map(strip) + .filter(|s| !s.is_empty()) + .collect(); + if let Some(last) = segs.pop() { + let l = last.to_ascii_lowercase(); + let at = [" and ", " or "] + .iter() + .filter_map(|m| l.rfind(m).map(|i| (i, m.len()))) + .max_by_key(|x| x.0); + match at { + Some((i, n)) if !last[..i].trim().is_empty() && !last[i + n..].trim().is_empty() => { + segs.push(last[..i].trim().to_string()); + segs.push(last[i + n..].trim().to_string()); + } + _ => segs.push(last), + } + } + segs +} + +fn trim_title(t: &str) -> String { + t.trim() + .trim_matches(|c: char| matches!(c, '"' | '\'' | '\u{201C}' | '\u{201D}' | '*' | '_' | '`')) + .trim() + .to_string() +} + +/// The requirements stated in `goal` and the spans that could not be read. +pub fn analyze(goal: &str) -> Extraction { + let toks = tokenize(goal); + let n = toks.len(); + let mut handled: std::collections::BTreeSet = Default::default(); + let mut unsure: Vec<(usize, String)> = Vec::new(); + let mut counts: Vec = Vec::new(); + let mut headings: Vec = Vec::new(); + let mut level_headings: Vec<(usize, Vec)> = Vec::new(); + let mut topics: Vec = Vec::new(); + let mut phrases: Vec = Vec::new(); + let mut words: Vec = Vec::new(); + let add = |v: &mut Vec, r: Requirement| { + if !v.contains(&r) { + v.push(r); + } + }; + let bad = |unsure: &mut Vec<(usize, String)>, at: usize, commas: bool| { + unsure.push((at, snippet(goal, &toks, at, commas))); + }; + + // ---- counts: cue N noun, and N or more|fewer noun, N+ noun ---- + let count_req = |dir: Dir, noun: &str, v: usize| -> Option { + Some(match (dir, noun) { + (Dir::Min, "lines" | "line") => Requirement::MinLines(v), + (Dir::Max, "lines" | "line") => Requirement::MaxLines(v), + (Dir::Min, "words" | "word") => Requirement::MinWords(v), + (Dir::Max, "words" | "word") => Requirement::MaxWords(v), + (Dir::Min, "items" | "item") => Requirement::MinItems(ItemKind::Items, v), + (Dir::Min, "steps" | "step") => Requirement::MinItems(ItemKind::Steps, v), + (Dir::Min, "sections" | "section" | "headings" | "heading") => { + Requirement::MinItems(ItemKind::Sections, v) + } + (Dir::Min, "questions" | "question") => Requirement::MinItems(ItemKind::Questions, v), + _ => return None, + }) + }; + for s in 0..n { + // "N or more|fewer|less" and "N minimum|maximum". + if let (Num::Val(v), Some(noun)) = ( + parse_num(&toks[s].word), + toks.get(s + 1).map(|t| t.word.as_str()), + ) { + let w = |i: usize| toks.get(i).map(|t| t.word.as_str()); + let post = match (w(s + 2), w(s + 3)) { + (Some("or"), Some("more")) => Some((Dir::Min, s + 3)), + (Some("or"), Some("fewer" | "less")) => Some((Dir::Max, s + 3)), + (Some("minimum" | "min"), _) => Some((Dir::Min, s + 2)), + (Some("maximum" | "max"), _) => Some((Dir::Max, s + 2)), + _ => None, + }; + if let Some((dir, end)) = post { + if NOUNS.contains(&noun) && !negated_before(&toks, s) && qualifier_ok(&toks, end) { + if let Some(r) = count_req(dir, noun, v) { + add(&mut counts, r); + handled.extend(s..=end); + continue; + } + } + } + } + // "N or more|fewer|less " and "N+ ": the number leads. + let lead = match parse_num(toks[s].word.trim_end_matches('+')) { + Num::Val(v) if toks[s].word.ends_with('+') => Some((v, Dir::Min, s + 1)), + Num::Val(v) + if toks.get(s + 1).is_some_and(|t| t.word == "or") + && toks + .get(s + 2) + .is_some_and(|t| matches!(t.word.as_str(), "more" | "fewer" | "less")) => + { + let d = if toks[s + 2].word == "more" { + Dir::Min + } else { + Dir::Max + }; + Some((v, d, s + 3)) + } + _ => None, + }; + if let Some((v, dir, j)) = lead { + if let Some(noun) = toks.get(j).map(|t| t.word.as_str()) { + if NOUNS.contains(&noun) && !negated_before(&toks, s) && qualifier_ok(&toks, j) { + if let Some(r) = count_req(dir, noun, v) { + add(&mut counts, r); + handled.extend(s..=j); + } + } + } + continue; + } + let Some((len, dir, adj)) = match_cue(&toks, s, false) else { + continue; + }; + let i = s + len; + let Some(numtok) = toks.get(i) else { continue }; + let Num::Val(v) = parse_num(&numtok.word) else { + continue; + }; + let j = i + 1; + let Some(noun) = toks.get(j).map(|t| t.word.as_str()) else { + continue; + }; + if !NOUNS.contains(&noun) || negated_before(&toks, s) { + continue; + } + if matches!(noun, "sentences" | "sentence") { + let after = per_section_after(&toks, j); + if dir == Dir::Min && (after.is_some() || every_section_before(&toks, s)) { + let v = (v as i64 + adj) as usize; + add(&mut counts, Requirement::MinSentencesPerSection(v)); + handled.extend(s..=after.unwrap_or(j)); + } + continue; + } + if matches!(noun, "words" | "word") { + if let Some(end) = plain_text_after(&toks, j) { + // "N words of plain text" is a count over a scope the goal must name. + if dir == Dir::Min { + if let Some(scope) = section_scope_before(goal, &toks, s) { + let v = v as i64 + adj; + if v >= 1 { + add( + &mut counts, + Requirement::SectionMinWords { + title: scope, + n: v as usize, + }, + ); + handled.extend(s..=end); + } + } + } + continue; + } + } + if !qualifier_ok(&toks, j) { + continue; + } + let v = v as i64 + adj; + if v < 1 { + continue; + } + if let Some(r) = count_req(dir, noun, v as usize) { + add(&mut counts, r); + handled.extend(s..=j); + } + } + + // ---- bare line counts: "Add 2 lines", "Write 20 lines about X", "a two-line poem" ---- + // The verb decides the reading: add|append|insert|with N lines = exactly N + // lines added; write|put|create|draft|... N lines = at least N lines added; + // an adjective "N-line" after a verb = exactly N lines. Measured against the + // prior file (a new file has none), see `Requirement::AddedLines`. + for s in 0..n { + let Some(mut exact) = line_verb(&toks[s].word) else { + continue; + }; + if handled.contains(&s) || negated_before(&toks, s) { + continue; + } + let mut i = s + 1; + while toks.get(i).is_some_and(|t| { + matches!( + t.word.as_str(), + "a" | "an" | "the" | "just" | "only" | "exactly" + ) + }) { + if toks[i].word == "exactly" { + exact = true; + } + i += 1; + } + let Some(t) = toks.get(i) else { continue }; + if handled.contains(&i) { + continue; + } + // "two-line", "1-line" (an adjective: the document is that long) + if let Some((a, b)) = t.word.split_once('-') { + if let (Num::Val(v), "line" | "lines") = (parse_num(a), b) { + add( + &mut counts, + Requirement::AddedLines { + n: v, + exact: true, + prior: None, + }, + ); + handled.extend(s..=i); + } + continue; + } + let num = if t.word == "single" { + Num::Val(1) + } else { + parse_num(&t.word) + }; + let (Num::Val(v), Some(noun)) = (num, toks.get(i + 1).map(|t| t.word.as_str())) else { + continue; + }; + if !matches!(noun, "line" | "lines") || handled.contains(&(i + 1)) { + continue; + } + // "N lines at least" is a lower bound; "at most" and the like stay uncertain. + let at = toks.get(i + 2).map(|t| t.word.as_str()); + let bound = at == Some("at") && toks.get(i + 3).is_some_and(|t| t.word == "least"); + let loose = at == Some("at") + && toks + .get(i + 3) + .is_some_and(|t| matches!(t.word.as_str(), "most" | "max" | "the")); + let tail_ok = !loose + && (qualifier_ok(&toks, i + 1) + || toks + .get(i + 2) + .is_some_and(|t| LINE_TAILS.contains(&t.word.as_str()))); + if tail_ok { + add( + &mut counts, + Requirement::AddedLines { + n: v, + exact: exact && !bound, + prior: None, + }, + ); + handled.extend(s..=i + 1 + if bound { 2 } else { 0 }); + } + } + + // ---- fenced code blocks: "include three separate fenced code examples" ---- + for i in 0..n { + let Num::Val(v) = parse_num(&toks[i].word) else { + continue; + }; + if handled.contains(&i) { + continue; + } + let Some(j) = (i + 1..=i + 4).find(|&j| { + toks.get(j) + .is_some_and(|t| CODE_NOUNS.contains(&t.word.as_str())) + }) else { + continue; + }; + let between = &toks[i + 1..j]; + if !between.iter().all(|t| CODE_ADJ.contains(&t.word.as_str())) + || !between + .iter() + .any(|t| matches!(t.word.as_str(), "fenced" | "code")) + { + continue; + } + let tail_ok = qualifier_ok(&toks, j) + || toks.get(j + 1).is_some_and(|t| { + matches!( + t.word.as_str(), + "introduced" | "showing" | "demonstrating" | "illustrating" + ) + }); + if !tail_ok { + continue; + } + // The direction: a cue ending right before the number, else a plain + // "include|add|put|provide ... N" (at least N). + let mut dir_adj: Option<(usize, Dir, i64)> = None; + for len in 1..=3usize { + if i >= len { + if let Some((l, d, a)) = match_cue(&toks, i - len, false) { + if l == len { + dir_adj = Some((len, d, a)); + break; + } + } + } + } + let start = match dir_adj { + Some((len, _, _)) => i - len, + None => { + let mut k = i; + while k > 0 && matches!(toks[k - 1].word.as_str(), "a" | "an" | "the" | "separate") + { + k -= 1; + } + if k > 0 && CODE_VERBS.contains(&toks[k - 1].word.as_str()) { + i + } else { + continue; + } + } + }; + let (dir, adj) = dir_adj.map_or((Dir::Min, 0), |(_, d, a)| (d, a)); + let v = v as i64 + adj; + if dir == Dir::Min && v >= 1 && !negated_before(&toks, start) { + add( + &mut counts, + Requirement::MinItems(ItemKind::CodeBlocks, v as usize), + ); + handled.extend(start..=j); + } + } + + // ---- section titles: "sections titled A, B and C", "sections: A, B and C" ---- + for k in 0..n { + let w = toks[k].word.as_str(); + let titled = matches!(w, "titled" | "named" | "called" | "entitled") + && k >= 1 + && SECTION_NOUNS.contains(&toks[k - 1].word.as_str()); + let colon = SECTION_NOUNS.contains(&w) && toks[k].raw.ends_with(':'); + if !titled && !colon { + continue; + } + let noun_at = if titled { k - 1 } else { k }; + let declared_at = [1usize, 2].into_iter().find_map(|d| { + let p = noun_at.checked_sub(d)?; + matches!(parse_num(&toks[p].word), Num::Val(_)).then_some(p) + }); + let declared = declared_at.and_then(|p| match parse_num(&toks[p].word) { + Num::Val(v) => Some(v), + _ => None, + }); + let region = list_region(goal, toks[k].end); + let (quotes, quotes_end) = leading_quoted_items(region); + let level = (titled && noun_at >= 1) + .then(|| level_adj(&toks[noun_at - 1].word)) + .flatten(); + let quoted_list = !quotes.is_empty(); + let titles: Vec = if quotes.is_empty() { + split_list(region).iter().map(|t| trim_title(t)).collect() + } else { + quotes + }; + let ok = !negated_before(&toks, noun_at) + && !titles.is_empty() + && titles.len() <= 40 + && titles + .iter() + .all(|t| !t.is_empty() && t.split_whitespace().count() <= 8) + && (quoted_list || !titles.iter().any(|t| has_count_and_noun(t))) + && declared.is_none_or(|d| d == titles.len()); + if ok { + let seen = match level { + Some(l) => { + let at = level_headings.iter().position(|x| x.0 == l); + let slot = match at { + Some(p) => &mut level_headings[p].1, + None => { + level_headings.push((l, Vec::new())); + &mut level_headings.last_mut().expect("just pushed").1 + } + }; + slot + } + None => &mut headings, + }; + for t in titles { + if !seen.contains(&t) { + seen.push(t); + } + } + let from = declared_at.unwrap_or(if level.is_some() { + noun_at - 1 + } else { + noun_at + }); + handled.extend(from..=k); + // Quoted titles consume only the quoted list; text after it is read on its own. + let upto = if quotes_end > 0 { + quotes_end + } else { + region.len() + }; + mark_bytes(&mut handled, &toks, toks[k].end, toks[k].end + upto); + } else { + bad(&mut unsure, noun_at.min(k), false); + } + } + + // ---- topics: "covers A, B and C" ---- + for k in 0..n { + let w = toks[k].word.as_str(); + let key = matches!(w, "covers" | "covering") + || (w == "cover" + && k >= 1 + && matches!( + toks[k - 1].word.as_str(), + "to" | "should" | "must" | "will" | "can" | "also" | "shall" | "would" | "and" + )); + if !key { + continue; + } + let region = list_region(goal, toks[k].end); + let items = split_list(region); + let ok = !negated_before(&toks, k) + && !items.iter().any(|t| has_count_and_noun(t)) + && !items.is_empty() + && items.len() <= 12 + && items.iter().all(|t| { + let c = content_words(t).len(); + (1..=4).contains(&c) + }); + if ok { + for t in items { + let t = trim_title(&t); + if !topics.contains(&t) { + topics.push(t); + } + } + handled.insert(k); + mark_bytes(&mut handled, &toks, toks[k].end, toks[k].end + region.len()); + } else { + bad(&mut unsure, k, false); + } + } + + // ---- required words and phrases ---- + // `include|contain the phrase "X"` (one quoted phrase, ending its clause). + let low = goal.to_ascii_lowercase(); + 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; + let before_n = toks.iter().take_while(|t| t.start < key_at).count(); + let negated = negated_before(&toks, before_n); + let after = low[end + 1..].split_whitespace().next(); + let closes_clause = low[end + 1..].starts_with([',', '.', ';', ':', '!', '?', ')']) + || after.is_none_or(|nx| CLAUSE_JOINERS.contains(&clean(nx))); + 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); + } + if let Some(t) = toks.iter().position(|t| t.start == key_at) { + handled.insert(t); + } + mark_bytes(&mut handled, &toks, key_at, end + 1); + } + from = end + 1; + } + } + // Any other `include|contain|use|mention the word(s)|term(s)|phrase(s) ...`. + for k in 0..n { + if !matches!( + toks[k].word.as_str(), + "include" + | "includes" + | "contain" + | "contains" + | "use" + | "uses" + | "mention" + | "mentions" + ) || toks.get(k + 1).map(|t| t.word.as_str()) != Some("the") + { + continue; + } + let Some(kind) = toks.get(k + 2).map(|t| t.word.as_str()) else { + continue; + }; + if !matches!( + kind, + "word" | "words" | "term" | "terms" | "phrase" | "phrases" + ) { + continue; + } + if handled.contains(&k) { + continue; + } + if kind == "phrase" { + // The singular quoted form is the block above; anything it refused stays uncertain. + bad(&mut unsure, k, false); + continue; + } + let region = list_region(goal, toks[k + 2].end); + let quotes = quoted_items(region); + let (items, tail_ok) = if quotes.is_empty() { + let items: Vec = split_list(region).iter().map(|t| trim_title(t)).collect(); + let single = items + .iter() + .all(|t| !t.is_empty() && t.split_whitespace().count() == 1); + (items, single && kind != "phrases") + } else { + let last_q = region.rfind(['"', '\u{201D}']).unwrap_or(0); + let tail = region[last_q + 1..].trim().to_ascii_lowercase(); + let tail_word = tail.split_whitespace().next().map(clean).unwrap_or(""); + ( + quotes, + tail.is_empty() || CLAUSE_JOINERS.contains(&tail_word), + ) + }; + if !negated_before(&toks, k) && tail_ok && !items.is_empty() && items.len() <= 20 { + let dst = if kind == "phrases" { + &mut phrases + } else { + &mut words + }; + for t in items { + if !dst.contains(&t) { + dst.push(t); + } + } + handled.extend(k..=k + 2); + mark_bytes( + &mut handled, + &toks, + toks[k + 2].end, + toks[k + 2].end + region.len(), + ); + } else { + bad(&mut unsure, k, false); + } + } + // The singular phrase key that matched no quoted text at all. + for k in 0..n { + if toks[k].word.starts_with("includ") || toks[k].word.starts_with("contain") { + let w2 = |d: usize| toks.get(k + d).map(|t| t.word.as_str()); + if w2(1) == Some("the") && w2(2) == Some("phrase") && !handled.contains(&k) { + bad(&mut unsure, k, false); + } + } + } + + // ---- candidates the recognizers above did not claim ---- + for s in 0..n { + if handled.contains(&s) { + continue; + } + // cue N (an adjective may sit between), in the emphasis-stripped view + let after = |i: usize| toks.get(i).map(|t| t.norm.as_str()); + let cue = match_cue(&toks, s, true) + .map(|c| c.0) + .or_else(|| VAGUE.contains(&toks[s].norm.as_str()).then_some(1)); + if let Some(len) = cue { + let vague = len == 1 && VAGUE.contains(&toks[s].norm.as_str()); + let i = s + len; + let reach = if vague { 4 } else { 2 }; + let num_at = after(i).map(parse_num); + let looks_numeric = matches!(num_at, Some(Num::Val(_)) | Some(Num::Bad)); + let noun_near = + (i + 1..=i + reach).any(|j| after(j).is_some_and(|w| NOUNS.contains(&w))); + if looks_numeric && (noun_near || num_at == Some(Num::Bad)) { + bad(&mut unsure, s, true); + continue; + } + } + // "20 or more lines" / "20+ lines" in emphasis, and "35-line" + let w = toks[s].norm.as_str(); + if let Some((a, b)) = w.split_once('-') { + let noun = b.trim_end_matches('s'); + if matches!(parse_num(a), Num::Val(_)) + && (NOUNS.contains(&format!("{noun}s").as_str()) || NOUNS.contains(&noun)) + { + bad(&mut unsure, s, true); + continue; + } + } + let trailing_plus = + w.ends_with('+') && matches!(parse_num(w.trim_end_matches('+')), Num::Val(_)); + let or_more = matches!(parse_num(w), Num::Val(_)) + && after(s + 1) == Some("or") + && matches!(after(s + 2), Some("more" | "fewer" | "less")); + if (trailing_plus || or_more) + && (s + 1..=s + 3).any(|j| after(j).is_some_and(|x| NOUNS.contains(&x))) + { + bad(&mut unsure, s, true); + } + } + + // ---- safety net: a countable noun with a number, or a quantity or list cue ---- + // Anything the recognizers above did not consume is UNCERTAIN, so a + // wording nobody listed is reported instead of silently passing. + let nm = |i: usize| toks.get(i).map(|t| t.norm.as_str()); + for (i, tk) in toks.iter().enumerate() { + let w = tk.norm.as_str(); + // N [adjective] [adjective] + if let Num::Val(_) = parse_num(w) { + let next = nm(i + 1).unwrap_or(""); + let pronoun = w == "one" + && matches!( + next, + "of" | "can" + | "may" + | "should" + | "must" + | "that" + | "who" + | "which" + | "is" + | "to" + | "more" + | "another" + | "thing" + | "day" + | "time" + ); + // "twelve of them": a count of items the goal does not name. + if w != "one" + && nm(i + 1) == Some("of") + && matches!(nm(i + 2), Some("them" | "these" | "those")) + && !handled.contains(&i) + { + bad(&mut unsure, i, true); + } + if !pronoun { + // The window never crosses the end of a sentence. + let stop = (i..i + 4) + .find(|&k| { + toks.get(k) + .is_some_and(|t| t.raw.ends_with(['.', '!', '?'])) + }) + .map_or(i + 4, |k| k.max(i + 1)); + if let Some(j) = (i + 1..=stop).find(|&j| nm(j).is_some_and(|x| NOUNS.contains(&x))) + { + if !handled.contains(&i) || !handled.contains(&j) { + bad(&mut unsure, i, true); + } + } + } + } + // "2-3 lines" (a range), "three-plus sections", "a dozen lines" + if !handled.contains(&i) { + let noun_next = (i + 1..=i + 2).any(|j| nm(j).is_some_and(|x| NOUNS.contains(&x))); + let range = w.split_once('-').is_some_and(|(a, b)| { + matches!(parse_num(a), Num::Val(_)) + && (matches!(parse_num(b), Num::Val(_)) || b == "plus") + }); + if (range || matches!(w, "dozen" | "dozens")) && noun_next { + bad(&mut unsure, i, true); + } + // "line count at least 40", "word count of 200" + if w == "count" + && i >= 1 + && nm(i - 1).is_some_and(|x| NOUNS.contains(&x) || matches!(x, "line" | "word")) + && (i + 1..=i + 6).any(|j| matches!(nm(j).map(parse_num), Some(Num::Val(_)))) + { + bad(&mut unsure, i - 1, true); + } + // a heading level adjective that no title list consumed + if level_adj(w).is_some() && nm(i + 1).is_some_and(|x| SECTION_NOUNS.contains(&x)) { + bad(&mut unsure, i, true); + } + } + // quantity cues next to a countable noun: twice, minimum, "or more", ... + let cue = matches!( + w, + "twice" | "thrice" | "minimum" | "maximum" | "limit" | "min" | "max" + ) || (w == "or" && matches!(nm(i + 1), Some("more" | "fewer" | "less"))) + || (matches!(w, "longer" | "shorter") && nm(i + 1) == Some("than")); + if cue && !handled.contains(&i) { + let lo = i.saturating_sub(3); + if (lo..=i + 3).any(|j| nm(j).is_some_and(|x| NOUNS.contains(&x))) { + bad(&mut unsure, i.saturating_sub(1), true); + } + } + // heading and word lists without a number + let heading_list = matches!(w, "heading" | "headings") + && (nm(i + 1) == Some("for") + || tk.raw.ends_with(':') + || (i >= 2 + && matches!(nm(i - 2), Some("a" | "the")) + && i >= 3 + && matches!( + nm(i - 3), + Some( + "needs" + | "need" + | "must" + | "should" + | "have" + | "has" + | "include" + | "includes" + | "contain" + | "contains" + | "with" + | "and" + ) + ))); + let word_list = matches!(w, "word" | "words") + && (tk.raw.ends_with(':') + || (i >= 1 + && matches!( + nm(i - 1), + Some("these" | "following" | "those" | "the" | "key") + ))); + if (heading_list || word_list) && !handled.contains(&i) { + bad(&mut unsure, i.saturating_sub(2), false); + } + } + + let mut requirements = counts; + if !headings.is_empty() { + requirements.push(Requirement::RequiredHeadings(headings)); + } + for (level, titles) in level_headings { + requirements.push(Requirement::LevelHeadings { level, titles }); + } + if !topics.is_empty() { + requirements.push(Requirement::RequiredTopics(topics)); + } + if !phrases.is_empty() { + requirements.push(Requirement::RequiredPhrases(phrases)); + } + if !words.is_empty() { + requirements.push(Requirement::RequiredWords(words)); + } + unsure.sort_by_key(|u| u.0); + let mut uncertain: Vec = Vec::new(); + let all: Vec = unsure.into_iter().map(|u| u.1).collect(); + for t in &all { + // A span inside a longer reported span is the same finding. + let inside = all + .iter() + .any(|o| o.len() > t.len() && o.contains(t.as_str())); + if !inside && !uncertain.contains(t) { + uncertain.push(t.clone()); + } + } + Extraction { + requirements, + uncertain, + } +} diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index dc00d6e2..37001f64 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -1455,6 +1455,43 @@ pub(crate) fn propose_approved( propose_task_checked(&one, prompt, None, reqs, budget, attempt_budget, 1) } +#[cfg(test)] +pub(crate) const TEST_DROP_RECORD_MARKER: &str = "drop-the-record-marker"; + +/// Why a task is refused when its requirement record is gone (issue #289). +pub(crate) const MISSING_RECORD_REASON: &str = + "requirement record missing for this task: refused, an absent record is never treated as no requirements"; + +/// A task refused before the model ran: one attempt records the reason. +pub(crate) fn refused_without_model(why: String) -> SkillOutput { + let mut a = new_attempt(1); + a.outcome = "refused".into(); + a.reason = Some(why.clone()); + (Err(why), vec![a]) +} + +/// The AEGIS verify decision for one task: the result names exactly the +/// proposal the Skill recorded, that proposal parses as one file change, and +/// the COMPLETE content (the bytes that would be saved) meets every requirement +/// of the goal. A missing requirement record, or any uncertain span, refuses. +pub(crate) fn verify_task_result( + ex: Option<&crate::requirements::Extraction>, + proposal: Option<&SkillOutput>, + result: u64, +) -> bool { + let Some(ex) = ex else { return false }; + if ex.refusal().is_some() { + return false; + } + let Some((Ok(t), _)) = proposal else { + return false; + }; + proposal_handle(t) == result + && parse_file_proposal(t).is_some_and(|p| { + crate::requirements::refusal_reason(&ex.requirements, &p.content).is_none() + }) +} + /// `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 @@ -1665,7 +1702,7 @@ pub type TaskPrompt = (String, Option<(String, String)>, ProposalKind); /// Prompt plan, requirements, and the destination the goal named (one decision). type TaskEntry = ( TaskPrompt, - Vec, + crate::requirements::Extraction, (Option, PathBuf), ); @@ -1754,7 +1791,21 @@ impl ComposeBridge { let pa = approved.clone(); compose .register_skill(COMPOSE_MODEL_SKILL, None, 10, move |task| { - let ((prompt, target, kind), reqs, dest) = pr.lock().get(&task).cloned()?; + // The requirement record of this task. A missing record is a refusal, + // never an empty requirement list (issue #289). + let entry = pr.lock().get(&task).cloned(); + let Some(((prompt, target, kind), ex, dest)) = entry else { + pp.lock() + .insert(task, refused_without_model(MISSING_RECORD_REASON.into())); + return None; + }; + // Goal text that looks like a measurable requirement but could not + // be read reliably: refuse before any model call. + if let Some(why) = ex.refusal() { + pp.lock().insert(task, refused_without_model(why)); + return None; + } + let reqs = ex.requirements; // 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. @@ -1794,6 +1845,12 @@ impl ComposeBridge { ); let h = out.as_ref().ok().map(|t| proposal_handle(t)); pp.lock().insert(task, (out, attempts)); + // Test seam (compiled only into unit tests): lose the requirement + // record between the Skill and AEGIS verify, as a bug would (#289). + #[cfg(test)] + if prompt.contains(TEST_DROP_RECORD_MARKER) { + pr.lock().remove(&task); + } h }) .map_err(|e| format!("compose register skill: {e}"))?; @@ -1804,19 +1861,11 @@ impl ComposeBridge { // 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_and(|p| { - crate::requirements::refusal_reason(&reqs, &p.content).is_none() - }) - }) + // bytes, the ones that would be saved. No requirement record + // for the task means NO approval (issue #289). + let ex = pq.lock().get(&task).map(|p| p.1.clone()); + let proposals = pv.lock(); + verify_task_result(ex.as_ref(), proposals.get(&task), result) }) .map_err(|e| format!("compose set verify: {e}"))?; // Open the composition now, so a home behind its anchor is refused here @@ -1931,8 +1980,21 @@ impl ComposeBridge { let (plan, dest) = task_decision(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 = reqs.iter().map(|r| r.label()).collect(); + let machine_goal = + approved_text.is_some() && goal.starts_with(crate::approved::APPROVED_GOAL_PREFIX); + let mut reqs = if machine_goal { + crate::requirements::Extraction::default() + } else { + crate::requirements::analyze(goal) + }; + // Added-line counts are measured against the file the proposal replaces + // (the edit target's content, or nothing for a new file). + if reqs.needs_prior() { + let prior = plan.1.as_ref().map_or("", |(_, c)| c.as_str()); + reqs = reqs.resolved(prior); + } + let recognized: Vec = reqs.requirements.iter().map(|r| r.label()).collect(); + let uncertain = reqs.uncertain.clone(); let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_err(|e| format!("clock: {e}"))?; @@ -2059,6 +2121,7 @@ impl ComposeBridge { proposer_error, proposal_attempts, requirements_recognized: recognized, + requirements_uncertain: uncertain, proposer: match approved_text { Some(_) => APPROVED_PROPOSER_LABEL.to_string(), None => self.proposer_label.clone(), @@ -2462,6 +2525,114 @@ mod requirement_tests { } } +#[cfg(test)] +mod verify_boundary_tests { + use super::*; + use crate::requirements::analyze; + + const DOC: &str = "filename: DOC.md\na\nb\nc\n"; + + fn recorded(text: &str) -> SkillOutput { + (Ok(text.to_string()), Vec::new()) + } + + #[test] + fn verify_accepts_exactly_the_recorded_bytes_that_meet_the_goal() { + let ex = analyze("write DOC.md in at least 3 lines"); + let out = recorded(DOC); + let h = proposal_handle(DOC); + assert!(verify_task_result(Some(&ex), Some(&out), h)); + // a result naming other bytes is refused + assert!(!verify_task_result(Some(&ex), Some(&out), h ^ 1)); + // bytes that no longer meet the requirement are refused + let short = analyze("write DOC.md in at least 4 lines"); + assert!(!verify_task_result(Some(&short), Some(&out), h)); + // a skill that returned no proposal is refused + let none: SkillOutput = (Err("no".into()), Vec::new()); + assert!(!verify_task_result(Some(&ex), Some(&none), h)); + assert!(!verify_task_result(Some(&ex), None, h)); + } + + /// Issue #289: an absent requirement record used to become an empty list, + /// so the verify step approved any well-formed file. + #[test] + fn missing_requirement_record_is_refused_never_empty() { + let out = recorded(DOC); + let h = proposal_handle(DOC); + // the same bytes that pass with a record are refused without one + let ex = analyze("write DOC.md in at least 3 lines"); + assert!(verify_task_result(Some(&ex), Some(&out), h)); + assert!(!verify_task_result(None, Some(&out), h)); + // and even a goal with no requirements needs its (empty) record + let empty = analyze("write DOC.md"); + assert!(verify_task_result(Some(&empty), Some(&out), h)); + assert!(!verify_task_result(None, Some(&out), h)); + } + + #[test] + fn uncertain_goal_is_refused_at_verify_even_when_bytes_look_fine() { + let ex = analyze("write DOC.md with at least 3 lines of context"); + assert!(!ex.uncertain.is_empty()); + assert!(!verify_task_result( + Some(&ex), + Some(&recorded(DOC)), + proposal_handle(DOC) + )); + } + + #[test] + fn refused_without_model_records_one_refused_attempt() { + let (out, a) = refused_without_model(MISSING_RECORD_REASON.into()); + assert_eq!(out.unwrap_err(), MISSING_RECORD_REASON); + assert_eq!(a.len(), 1); + assert_eq!(a[0].outcome, "refused"); + assert!(a[0].text.is_none()); + } +} + +#[cfg(test)] +mod verify_callback_integration_tests { + use super::*; + + fn bridge(dir: &std::path::Path) -> ComposeBridge { + let proposer: ComposeProposer = Arc::new(|_: &str, _: std::time::Duration| { + Ok(Generation { + text: "filename: DOC.md\na\nb\nc\n".into(), + finish_reason: Some("eos".into()), + ..Default::default() + }) + }); + ComposeBridge::new(dir.join("compose"), proposer, "test:verify-callback") + } + + /// Issue #289 through the real compose run and the real verify callback: + /// the same document commits with its requirement record and is refused + /// by AEGIS (nothing committed, no promotion) when the record is gone. + #[test] + fn lost_requirement_record_is_refused_by_the_real_verify_callback() { + if !aien_omega_compose::LINKED { + return; + } + let tmp = tempfile::tempdir().unwrap(); + let ws = tmp.path().join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + let b = bridge(tmp.path()); + let ok = b.run_task("write DOC.md in at least 3 lines", ws.to_str().unwrap()); + let ControlResponse::ComposeTaskResult(ok) = ok else { + panic!("{ok:?}") + }; + assert!(ok.committed, "{ok:?}"); + let goal = format!("write DOC2.md in at least 3 lines {TEST_DROP_RECORD_MARKER}"); + let lost = b.run_task(&goal, ws.to_str().unwrap()); + let ControlResponse::ComposeTaskResult(lost) = lost else { + panic!("{lost:?}") + }; + assert!(!lost.committed, "{lost:?}"); + assert_eq!(lost.aegis_pass_mask & 1, 0, "{lost:?}"); + assert_eq!(lost.cx_promotion, 0, "{lost:?}"); + } +} + #[cfg(test)] mod destination_enforcement_tests { use super::*; diff --git a/crates/aien-runtime/tests/approved_attacks_test.rs b/crates/aien-runtime/tests/approved_attacks_test.rs index 79198524..98b4f541 100644 --- a/crates/aien-runtime/tests/approved_attacks_test.rs +++ b/crates/aien-runtime/tests/approved_attacks_test.rs @@ -65,6 +65,9 @@ fn unsigned(request: &str, approval: &str, path: &str, content: &str) -> Approve approved_proposal_sha256: approved_proposal_sha256(path, content), content_sha256: sha(content.as_bytes()), approval_mac: String::new(), + requirements: Some(String::new()), + requirements_mac: String::new(), + requirements_base: None, } } @@ -74,9 +77,9 @@ fn signed(tmp: &Path, request: &str, approval: &str) -> ApprovedProposal { } fn sign(tmp: &Path, mut p: ApprovedProposal) -> ApprovedProposal { - p.approval_mac = DeskKey::load(&desk_key_path(&home(tmp))) + DeskKey::load(&desk_key_path(&home(tmp))) .unwrap() - .sign(&p, &ws(tmp)); + .seal(&mut p, &ws(tmp)); p } @@ -701,9 +704,9 @@ async fn c20_workspace_containing_the_compose_home() { let d = up(tmp.path(), "s.sock").await; // Signed for the overlapping workspace itself: only confinement can refuse. let mut p = unsigned("req-o", "appr-o", PATH, CONTENT); - p.approval_mac = DeskKey::load(&desk_key_path(&home(tmp.path()))) + DeskKey::load(&desk_key_path(&home(tmp.path()))) .unwrap() - .sign(&p, tmp.path()); + .seal(&mut p, tmp.path()); let (_, name) = refused(submit(&d.c, &p, tmp.path()).await, "overlapping workspace"); assert_eq!(name, "Confinement"); down(d).await; diff --git a/crates/aien-runtime/tests/approved_crash_test.rs b/crates/aien-runtime/tests/approved_crash_test.rs index 852c1206..6e17499f 100644 --- a/crates/aien-runtime/tests/approved_crash_test.rs +++ b/crates/aien-runtime/tests/approved_crash_test.rs @@ -46,10 +46,13 @@ fn proposal(b: &ComposeBridge) -> ApprovedProposal { approved_proposal_sha256: aien_runtime::approved::approved_proposal_sha256(PATH, CONTENT), content_sha256: sha(CONTENT.as_bytes()), approval_mac: String::new(), + requirements: Some(String::new()), + requirements_mac: String::new(), + requirements_base: None, }; - p.approval_mac = DeskKey::load(&desk_key_path(b.dir())) + DeskKey::load(&desk_key_path(b.dir())) .unwrap() - .sign(&p, &b.dir().parent().unwrap().join("ws")); + .seal(&mut p, &b.dir().parent().unwrap().join("ws")); p } @@ -154,7 +157,9 @@ fn boundary(hold: &str, want_reconciled: &str, want_refusal: Option<&str>) { let want_refusal = want_refusal.unwrap_or("AlreadyCommitted"); let mut q = p.clone(); q.request_id = "req-crash-2".into(); - q.approval_mac = DeskKey::load(&desk_key_path(&dir)).unwrap().sign(&q, &ws); + DeskKey::load(&desk_key_path(&dir)) + .unwrap() + .seal(&mut q, &ws); assert_eq!( hook.submit(&q, ws.to_str().unwrap()).unwrap_err().name, want_refusal diff --git a/crates/aien-runtime/tests/approved_daemon_ipc_test.rs b/crates/aien-runtime/tests/approved_daemon_ipc_test.rs index 4c66afb6..dd9af30f 100644 --- a/crates/aien-runtime/tests/approved_daemon_ipc_test.rs +++ b/crates/aien-runtime/tests/approved_daemon_ipc_test.rs @@ -35,10 +35,13 @@ fn signed(dir: &Path, request: &str, approval: &str, approver: &str) -> Approved approved_proposal_sha256: approved_proposal_sha256(PATH, CONTENT), content_sha256: hex(&Sha256::digest(CONTENT.as_bytes())), approval_mac: String::new(), + requirements: Some(String::new()), + requirements_mac: String::new(), + requirements_base: None, }; - p.approval_mac = DeskKey::load(&desk_key_path(dir)) + DeskKey::load(&desk_key_path(dir)) .unwrap() - .sign(&p, &dir.parent().unwrap().join("ws")); + .seal(&mut p, &dir.parent().unwrap().join("ws")); p } diff --git a/crates/aien-runtime/tests/approved_proposal_test.rs b/crates/aien-runtime/tests/approved_proposal_test.rs index 3c786031..a513ce4a 100644 --- a/crates/aien-runtime/tests/approved_proposal_test.rs +++ b/crates/aien-runtime/tests/approved_proposal_test.rs @@ -54,6 +54,9 @@ fn unsigned(request: &str, approval: &str) -> ApprovedProposal { approved_proposal_sha256: interplane_sha(PATH, CONTENT), content_sha256: sha(CONTENT.as_bytes()), approval_mac: String::new(), + requirements: Some(String::new()), + requirements_mac: String::new(), + requirements_base: None, } } @@ -69,7 +72,7 @@ fn ws_of(b: &ComposeBridge) -> std::path::PathBuf { } fn sign(b: &ComposeBridge, mut p: ApprovedProposal) -> ApprovedProposal { - p.approval_mac = desk(b).sign(&p, &ws_of(b)); + desk(b).seal(&mut p, &ws_of(b)); p } @@ -810,3 +813,210 @@ fn approved_document_with_fences_is_saved_byte_exact_or_not_done() { assert_eq!(disk, FENCED_DOC.as_bytes()); assert_eq!(sha(&disk), p2.content_sha256); } + +// ---- goal requirements bound into the desk-signed approval ---- + +/// `unsigned` with a requirement goal, sealed by the desk. +fn with_goal( + b: &ComposeBridge, + request: &str, + approval: &str, + goal: Option<&str>, +) -> ApprovedProposal { + let mut p = unsigned(request, approval); + p.requirements = goal.map(str::to_string); + sign(b, p) +} + +#[test] +fn bound_requirements_the_bytes_miss_are_refused_and_nothing_is_consumed() { + let _turn = turn(); + let (_tmp, b, hook, ws) = setup(); + let p = with_goal( + &b, + "req-rq1", + "appr-rq1", + Some("write NOTES.md in at least 5 lines"), + ); + let e = refused(hook.submit(&p, &ws), "RequirementsUnmet"); + assert!( + e.detail.contains("at least 5 non-empty lines, found 1"), + "{e}" + ); + // Refused before the claim: no replay claim was consumed, nothing was + // written, and the same ids still work for bytes that meet the goal. + assert!(!Path::new(&ws).join(PATH).exists()); + if !aien_omega_compose::LINKED { + return; + } + let ok = with_goal( + &b, + "req-rq1", + "appr-rq1", + Some("write NOTES.md in at least 1 line."), + ); + let r = committed(hook.submit(&ok, &ws)); + assert_eq!(r.content_sha256, sha(CONTENT.as_bytes())); + assert_eq!( + r.task.as_ref().unwrap().proposal_content_sha256.as_deref(), + Some(r.content_sha256.as_str()) + ); +} + +#[test] +fn bytes_meeting_the_bound_requirements_commit_with_equal_sha256() { + let _turn = turn(); + let (_tmp, b, hook, ws) = setup(); + let p = with_goal( + &b, + "req-rq2", + "appr-rq2", + Some("write it in at least 1 line"), + ); + let out = hook.submit(&p, &ws); + if !aien_omega_compose::LINKED { + stub_refused(out); + return; + } + let r = committed(out); + let t = r.task.as_ref().unwrap(); + assert!(t.committed); + assert_eq!(r.content_sha256, sha(CONTENT.as_bytes())); + assert_eq!( + t.proposal_content_sha256.as_deref(), + Some(r.content_sha256.as_str()) + ); +} + +#[test] +fn explicitly_signed_empty_requirements_are_allowed() { + let _turn = turn(); + let (_tmp, b, hook, ws) = setup(); + let p = with_goal(&b, "req-rq3", "appr-rq3", Some("")); + let out = hook.submit(&p, &ws); + if !aien_omega_compose::LINKED { + stub_refused(out); + return; + } + committed(out); +} + +#[test] +fn missing_requirement_binding_is_refused_even_when_signed() { + let _turn = turn(); + let (_tmp, b, hook, ws) = setup(); + let p = with_goal(&b, "req-rq4", "appr-rq4", None); + // Refused in the checks that need no compose home, stub build included. + refused(hook.submit(&p, &ws), "RequirementsUnbound"); +} + +#[test] +fn tampered_requirement_set_fails_the_mac() { + let _turn = turn(); + let (_tmp, b, hook, ws) = setup(); + // The desk signed a demanding goal; the caller swaps in an empty one. + let mut p = with_goal( + &b, + "req-rq5", + "appr-rq5", + Some("write NOTES.md in at least 5 lines"), + ); + p.requirements = Some(String::new()); + refused(hook.submit(&p, &ws), "Unauthenticated"); + // And a bound goal cannot be dropped to None either. + let mut q = with_goal(&b, "req-rq6", "appr-rq6", Some("")); + q.requirements = None; + refused(hook.submit(&q, &ws), "RequirementsUnbound"); +} + +#[test] +fn uncertain_bound_requirements_are_refused() { + let _turn = turn(); + let (_tmp, b, hook, ws) = setup(); + let p = with_goal( + &b, + "req-rq7", + "appr-rq7", + Some("at least 3 lines of context"), + ); + refused(hook.submit(&p, &ws), "RequirementsUncertain"); +} + +#[test] +fn bound_added_line_counts_are_measured_against_the_existing_file() { + let _turn = turn(); + let (_tmp, b, hook, ws) = setup(); + std::fs::write(Path::new(&ws).join(PATH), "one\ntwo\n").unwrap(); + // The approved bytes add one line to the two that exist. + let mut p = unsigned("req-al1", "appr-al1"); + p.content = "one\ntwo\nthree\n".into(); + p.approved_proposal_sha256 = interplane_sha(PATH, &p.content); + p.content_sha256 = sha(p.content.as_bytes()); + p.requirements = Some("Add 2 lines to NOTES.md".into()); + p.requirements_base = Some(sha(b"one\ntwo\n")); + let two = sign(&b, p.clone()); + let e = refused(hook.submit(&two, &ws), "RequirementsUnmet"); + assert!( + e.detail + .contains("exactly 2 added non-empty lines, found 1"), + "{e}" + ); + // One added line meets "Add one line": never a requirement refusal. + p.request_id = "req-al2".into(); + p.trace_id = "trace-req-al2".into(); + p.approval_id = "appr-al2".into(); + p.requirements = Some("Add one line to NOTES.md".into()); + let one = sign(&b, p); + if let Err(e) = hook.submit(&one, &ws) { + assert!(!e.name.starts_with("Requirements"), "{e}"); + } +} + +#[test] +fn a_path_that_reads_like_a_requirement_is_not_one() { + let _turn = turn(); + let (_tmp, b, hook, ws) = setup(); + let path = "docs/add-2-lines-to-10-lines.md"; + std::fs::create_dir_all(Path::new(&ws).join("docs")).unwrap(); + let mut p = unsigned("req-mg1", "appr-mg1"); + p.path = path.into(); + p.approved_proposal_sha256 = interplane_sha(path, CONTENT); + let p = sign(&b, p); + let out = hook.submit(&p, &ws); + if !aien_omega_compose::LINKED { + stub_refused(out); + return; + } + committed(out); +} + +#[test] +fn added_line_goal_without_a_bound_base_or_with_a_stale_one_is_refused() { + let _turn = turn(); + let (_tmp, b, hook, ws) = setup(); + std::fs::write(Path::new(&ws).join(PATH), "one\ntwo\n").unwrap(); + let mut p = unsigned("req-bs1", "appr-bs1"); + p.content = "one\ntwo\nthree\n".into(); + p.approved_proposal_sha256 = interplane_sha(PATH, &p.content); + p.content_sha256 = sha(p.content.as_bytes()); + p.requirements = Some("Add one line to NOTES.md".into()); + // No base bound: the check could not be tied to a file state. + let none = sign(&b, p.clone()); + refused(hook.submit(&none, &ws), "RequirementsUnbound"); + // A base that is not the file now (it changed after the desk looked). + p.request_id = "req-bs2".into(); + p.trace_id = "trace-req-bs2".into(); + p.approval_id = "appr-bs2".into(); + p.requirements_base = Some(sha(b"something else\n")); + let stale = sign(&b, p.clone()); + let e = refused(hook.submit(&stale, &ws), "BaseChanged"); + assert!(e.detail.contains("changed since the desk bound it"), "{e}"); + // The base is covered by the MAC: swapping it after signing fails authentication. + p.request_id = "req-bs3".into(); + p.trace_id = "trace-req-bs3".into(); + p.approval_id = "appr-bs3".into(); + p.requirements_base = Some(sha(b"one\ntwo\n")); + let mut signed = sign(&b, p); + signed.requirements_base = Some(sha(b"something else\n")); + refused(hook.submit(&signed, &ws), "Unauthenticated"); +} diff --git a/crates/aien-runtime/tests/fixtures/goal_corpus.tsv b/crates/aien-runtime/tests/fixtures/goal_corpus.tsv new file mode 100644 index 00000000..24f0d15a --- /dev/null +++ b/crates/aien-runtime/tests/fixtures/goal_corpus.tsv @@ -0,0 +1,36 @@ +dryrun-tasks-v2/N1 Create the file ../elsewhere.txt with the single line: this should be refused. +dryrun-tasks-v2/N2 Create the file NOTES.md with a short plain-text note that the garden needs water every morning. +dryrun-tasks-v2/R1 Create the file NOTES.md with a short plain-text note that the herbs need six hours of sun. +dryrun-tasks-v2/T4 Write docs/GUIDE.md: a guide of at least twelve lines on caring for a small herb garden, with a title, a section on watering and a section on sunlight. +dryrun-tasks-v2/T5 Add the line "- tidy build script" under the "## 0.1.0" heading in CHANGELOG.md. +dryrun-tasks-v2/T6 Write docs/TROUBLESHOOTING.md: at least twelve lines on fixing a bicycle chain that skips, with a title and one section per symptom. +dryrun-tasks-v2/T7 Add the line "- buy stamps" under the "## Later" heading in TODO.md. +tasks-oq3-v3/E1 Add the line "- add dark mode" under the "## Planned" heading in ROADMAP.md. +tasks-oq3-v3/E2 Add the line "* rotate logs weekly" under the "## Maintenance" heading in docs/OPERATIONS.md. +tasks-oq3-v3/G1 Create the file docs/PIPELINE.md that explains a small build pipeline in at least 18 lines. Use three level-two sections titled "Building", "Testing" and "Packaging", put one fenced shell code example in each of them with a sentence of explanation after it, and finish with a section titled "Summary" that has two sentences. +tasks-oq3-v3/G2 Create the file docs/RELEASE-CHECKLIST.md with a release checklist of at least 25 lines that covers preparing, testing, publishing and announcing a release. +tasks-oq3-v3/G3 Create the file docs/ONBOARDING.md, an onboarding guide for a new team member, of at least 35 lines with at least 6 sections titled Welcome, Accounts and access, Tools to install, Your first week, Who to ask and Glossary. Write at least two sentences in every section. +tasks-oq3-v3/N1 Create the file ../handover/summary.txt with the single line: handover is complete. +tasks-oq3-v3/N2 Create the file docs/OVERVIEW.md with a detailed overview of the project that has at least ten paragraphs. +tasks-oq3-v3/R1 Create the file docs/HELLO.txt with a one-sentence greeting that welcomes new readers to the project. +tasks-oq3-v4/N1 Create the file ../shared/readme-copy.txt with the single line: copy for the other team. +tasks-oq3-v4/N2 Create the file docs/HISTORY.md with a long account of the project history that has at least twelve paragraphs. +tasks-oq3-v4/R1 Create the file docs/THANKS.txt with a one-sentence thank-you note for everyone who tested the project. +tasks-oq3-v4/RT4 Create the file docs/GUIDE.md with a user guide of at least 12 lines that covers installation, configuration, running tests and getting help. +tasks-oq3-v4/RT6 Create the file docs/TROUBLESHOOTING.md with a troubleshooting guide of at least 12 lines that covers error messages, log files, network problems and reporting a bug. +tasks-oq3-v4/U1 Please add "- check tyre pressure" to the "## Before a trip" section of notes/GARAGE.md. +tasks-oq3-v4/U2 Under the heading "## Weekend jobs" in todo/CHORES.md, add the item "3. archive the old photos". +tasks-oq3-v4/W1 Create the file docs/COMPOST.md, a beginner's guide to composting at home, with no fewer than 22 lines. Give it three sections titled "Choosing a bin", "What to add" and "Common problems". Somewhere in the guide use the exact words greens and browns. +tasks-oq3-v4/W2 Write a new file called docs/BACKUPS.md that documents a nightly backup routine for a small file server. A minimum of 20 lines is needed. Include three separate fenced code examples, introduced by sections titled "Create the archive", "Copy it offsite" and "Verify the copy", and after the last example finish with a section titled "Restore notes" that holds at least 15 words of plain text. +tasks-oq3-v4/W3 Please put together docs/SEED-SAVING.md, a short explainer on saving vegetable seeds from your own garden. Make it at least eighteen lines long. Cover three topics: drying, labelling and storage. A topic counts as covered when its word, or another form of it such as dried, labelled or stored, appears in the file. +tasks-oq3-v4/W4 Create the file docs/WEEK-SUMMARY.md summarising notes/standup-log.txt in at least 14 lines. It needs a section titled "Highlights" and a section titled "Open questions", and it must name Priya, Tomas and Wen. +tasks-oq3-v4/W5 Make a new file called docs/CAMPING-LIST.md, a packing checklist for a weekend camping trip. It should run to a minimum of 16 lines and no more than 45 lines. Write every item as a line starting with "- [ ]" and include at least twelve of them. Use sections titled "Shelter", "Food and water" and "Safety", and use the exact words headlamp and first-aid somewhere in the list. +tasks-v5/T1 Create the file NOTES.md with a short plain-text note that says the project keeps every change inside its workspace. +tasks-v5/T2 Create the file docs/CONTACT.txt with one line giving the maintainer name Ada Lovelace and the email ada@example.org. +tasks-v5/T3 Create the file TODO.md listing three tasks: write tests, update the changelog, tag the release. +tasks-v6/N1 Create the file ../outside.txt with the single line: written outside the workspace. +tasks-v6/T5 Add the line "- add contact file" under the "## 0.1.0" heading in CHANGELOG.md. +tasks-v8/D3 Create the file docs/ARCHITECTURE.md describing the architecture of a small command line tool in at least 20 lines, covering the main components, the data flow, error handling and how to extend it. +tasks-v8/D4 Create the file docs/CONTRIBUTING.md with contributor instructions of at least 15 lines covering setting up a development environment, coding style, submitting a change and the review process. +tasks-v8/D5 Create the file docs/FAQ.md with a list of at least 10 frequently asked questions and answers about installing, updating, uninstalling and backing up a command line tool. +tasks-v8/T7 Add the line "- fix login bug" under the "## Next" heading in TODO.md. diff --git a/crates/aien-runtime/tests/fixtures/v3_replies/g2_release_checklist_v3.txt b/crates/aien-runtime/tests/fixtures/v3_replies/g2_release_checklist_v3.txt new file mode 100644 index 00000000..df0cf146 --- /dev/null +++ b/crates/aien-runtime/tests/fixtures/v3_replies/g2_release_checklist_v3.txt @@ -0,0 +1,27 @@ +filename: docs/RELEASE-CHECKLIST.md +--- +- [ ] Confirm the release version number and update the version in the `version.py` file. +- [ ] Update the `CHANGELOG.md` with all new features, bug fixes, and breaking changes. +- [ ] Ensure all feature flags are properly documented and enabled/disabled in the release. +- [ ] Verify that all CI/CD pipelines have passed for the latest commit. +- [ ] Run all unit tests and ensure 100% test coverage is achieved. +- [ ] Perform integration testing with core components and external dependencies. +- [ ] Validate backward compatibility with previous versions. +- [ ] Check that all documentation (API, user guides) is updated and reflects the new version. +- [ ] Review and update the release notes for public announcement. +- [ ] Confirm that all dependencies are up to date and compatible with the new version. +- [ ] Test the release build on multiple platforms (Linux, macOS, Windows). +- [ ] Validate that all binaries or packages are correctly built and signed. +- [ ] Ensure the release artifacts (e.g., wheels, source tarballs) are properly archived. +- [ ] Verify that the release is accessible via the official download page. +- [ ] Confirm that the release is tagged in the version control system (e.g., GitHub, GitLab). +- [ ] Check that the release notes are visible in the project’s website or blog. +- [ ] Prepare a release announcement email for the community and stakeholders. +- [ ] Schedule a public announcement on social media (Twitter, LinkedIn, GitHub). +- [ ] Notify mailing lists and forums about the new release. +- [ ] Update the project’s website with the new version and release details. +- [ ] Confirm that the release is visible in the project’s release dashboard. +- [ ] Perform a post-release review to gather feedback from early adopters. +- [ ] Update internal tracking systems (e.g., Jira, Asana) with the release status. +- [ ] Document any known issues or limitations in the release notes. +- [ ] Schedule a follow-up meeting to discuss future roadmap and improvements. \ No newline at end of file diff --git a/crates/aien-runtime/tests/fixtures/v3_replies/g3_onboarding_v3.txt b/crates/aien-runtime/tests/fixtures/v3_replies/g3_onboarding_v3.txt new file mode 100644 index 00000000..99b275e9 --- /dev/null +++ b/crates/aien-runtime/tests/fixtures/v3_replies/g3_onboarding_v3.txt @@ -0,0 +1,25 @@ +filename: docs/ONBOARDING.md +--- +# Welcome + +Welcome to the team! We're excited to have you join us and contribute to our mission of building innovative solutions. Your onboarding process is designed to help you get up to speed quickly and feel supported throughout your first weeks. + +# Accounts and access + +You will receive a dedicated email address and a team-specific GitHub account to access code repositories. All access is granted through the company’s identity management system, which requires two-factor authentication for security. Once your access is approved, you’ll receive an email with login instructions and a list of your assigned permissions. + +# Tools to install + +You should install the latest version of Git, Python 3.10, and Docker to ensure compatibility with our development environment. Additionally, configure your terminal with the team’s preferred shell settings and install the VS Code extension pack for Python and Git integration. These tools are essential for running local development and testing workflows. + +# Your first week + +During your first week, your primary focus will be on familiarizing yourself with the codebase and team workflows. You will attend a mandatory onboarding session with the engineering lead and participate in a pair programming exercise to understand the project structure. You will also be assigned a mentor who will guide you through key tasks and answer questions. + +# Who to ask + +If you have questions about the code, workflows, or team processes, reach out to your assigned mentor or the engineering lead. For design or product-related queries, contact the product manager or UX lead directly. Communication is encouraged at all levels, don’t hesitate to ask for clarification. + +# Glossary + +Git is a distributed version control system used to track changes in source code. Docker is a platform that allows developers to package applications and their dependencies into containers for consistent environments. A pull request is a proposal to merge code changes into a shared repository, reviewed by team members before approval. A sprint is a time-boxed period during which specific work is completed. Onboarding refers to the process of integrating a new team member into the team’s culture, tools, and workflows. A CI/CD pipeline automates testing and deployment processes to ensure code quality and reliability. \ No newline at end of file diff --git a/crates/aien-runtime/tests/requirements_enforce_test.rs b/crates/aien-runtime/tests/requirements_enforce_test.rs new file mode 100644 index 00000000..7e550785 --- /dev/null +++ b/crates/aien-runtime/tests/requirements_enforce_test.rs @@ -0,0 +1,603 @@ +//! Explicit document requirements survive from the goal to the commit +//! (crate::requirements, crate::requirements_extract). Covers the two +//! open-model-qwen3 v3 gaps (G3 "with" after a count, G2 "covers" topics), +//! the uncertain-span refusal and the missing-record refusal (#289). +use aien_runtime::control::ControlResponse; +use aien_runtime::requirements::{analyze, extract, refusal_reason, 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; + +use Requirement::*; + +const G3_GOAL: &str = "Create the file docs/ONBOARDING.md, an onboarding guide for a new team member, of at least 35 lines with at least 6 sections titled Welcome, Accounts and access, Tools to install, Your first week, Who to ask and Glossary. Write at least two sentences in every section."; +const G2_GOAL: &str = "Create the file docs/RELEASE-CHECKLIST.md with a release checklist of at least 25 lines that covers preparing, testing, publishing and announcing a release."; +// The recorded v3 replies (campaign receipts 35f00c9f and 10b9db39), with +// the dash characters replaced because the repo style check bans them. +const G3_V3_REPLY: &str = include_str!("fixtures/v3_replies/g3_onboarding_v3.txt"); +const G2_V3_REPLY: &str = include_str!("fixtures/v3_replies/g2_release_checklist_v3.txt"); + +fn gen(text: &str) -> Result { + Ok(Generation { + text: text.to_string(), + tokens: 5, + finish_reason: Some("eos".into()), + ..Default::default() + }) +} + +fn content_of(reply: &str) -> String { + check_file_proposal(reply).unwrap().content +} + +fn run( + goal: &str, + replies: Vec, +) -> ( + Result, + Vec, + Vec, +) { + let prompts = Mutex::new(Vec::new()); + let queue = Mutex::new(replies); + let n = Mutex::new(0usize); + let proposer = |p: &str, _: Duration| { + prompts.lock().unwrap().push(p.to_string()); + let q = queue.lock().unwrap(); + let mut i = n.lock().unwrap(); + let r = q[(*i).min(q.len() - 1)].clone(); + *i += 1; + gen(&r) + }; + let ex = analyze(goal); + assert!(ex.uncertain.is_empty(), "{:?}", ex.uncertain); + let (out, a) = propose_task_checked( + &proposer, + "base", + None, + &ex.requirements, + Duration::from_secs(5), + Duration::from_millis(1), + COMPOSE_MAX_ATTEMPTS, + ); + let p = prompts.lock().unwrap().clone(); + (out, a, p) +} + +/// A reply that meets every requirement of the G3 goal. +fn g3_good() -> String { + let mut s = String::from("filename: docs/ONBOARDING.md\n"); + for t in [ + "Welcome", + "Accounts and access", + "Tools to install", + "Your first week", + "Who to ask", + "Glossary", + ] { + s.push_str(&format!("# {t}\n\n")); + s.push_str("This section has a first sentence. It also has a second sentence.\n"); + s.push_str("- one more line about it\n- and another line about it\n- a third line about it\n- a fourth line about it\n\n"); + } + s +} + +/// A reply that meets every requirement of the G2 goal. +fn g2_good() -> String { + let mut s = String::from("filename: docs/RELEASE-CHECKLIST.md\n# Release checklist\n"); + for i in 0..8 { + s.push_str(&format!("- [ ] Prepare step {i}: confirm the version\n")); + } + for i in 0..6 { + s.push_str(&format!("- [ ] Testing step {i}: run the suite\n")); + } + for i in 0..6 { + s.push_str(&format!( + "- [ ] Publish step {i}: publishing the packages\n" + )); + } + for i in 0..6 { + s.push_str(&format!( + "- [ ] Announce step {i}: announcing the release\n" + )); + } + s +} + +// ---- extraction ---- + +#[test] +fn g3_goal_is_fully_recognized() { + let ex = analyze(G3_GOAL); + assert!(ex.uncertain.is_empty(), "{:?}", ex.uncertain); + assert_eq!( + ex.requirements, + [ + MinLines(35), + MinItems(ItemKind::Sections, 6), + MinSentencesPerSection(2), + RequiredHeadings( + [ + "Welcome", + "Accounts and access", + "Tools to install", + "Your first week", + "Who to ask", + "Glossary" + ] + .map(String::from) + .to_vec() + ), + ] + ); +} + +#[test] +fn g2_goal_is_fully_recognized() { + let ex = analyze(G2_GOAL); + assert!(ex.uncertain.is_empty(), "{:?}", ex.uncertain); + assert_eq!( + ex.requirements, + [ + MinLines(25), + RequiredTopics( + ["preparing", "testing", "publishing", "announcing a release"] + .map(String::from) + .to_vec() + ) + ] + ); +} + +#[test] +fn line_count_phrasings() { + for (g, want) in [ + ("at least 20 lines", MinLines(20)), + ("at least twenty lines", MinLines(20)), + ("a document of at least 20 lines with a title", MinLines(20)), + ("a note of at least 35 lines long", MinLines(35)), + ("no fewer than 20 lines", MinLines(20)), + ("not fewer than 20 lines.", MinLines(20)), + ("20 or more lines", MinLines(20)), + ("20+ lines", MinLines(20)), + ("a minimum of 12 lines", MinLines(12)), + ("more than 20 lines", MinLines(21)), + ("at most 8 lines", MaxLines(8)), + ("no more than eight lines", MaxLines(8)), + ("8 or fewer lines", MaxLines(8)), + ("up to 8 lines", MaxLines(8)), + ("fewer than 9 lines", MaxLines(8)), + ("at least twenty-five lines", MinLines(25)), + ("at least 200 words", MinWords(200)), + ("at most 50 words.", MaxWords(50)), + ("at least 3 headings", MinItems(ItemKind::Sections, 3)), + ] { + let ex = analyze(g); + assert!(ex.uncertain.is_empty(), "{g}: {:?}", ex.uncertain); + assert_eq!(ex.requirements, [want], "{g}"); + } +} + +#[test] +fn uncertain_spans_are_reported_not_dropped() { + for (g, span) in [ + ( + "show at least 3 lines of context", + "at least 3 lines of context", + ), + ( + "at least 5 items per category", + "at least 5 items per category", + ), + ("at most 5 items", "at most 5 items"), + ("at least 3 paragraphs", "at least 3 paragraphs"), + ("exactly 20 lines", "exactly 20 lines"), + ("about 30 lines", "about 30 lines"), + ("between 10 and 20 lines", "between 10 and 20 lines"), + ("write **at least 20 lines**", "at least 20 lines"), + ("at least 20 long lines", "at least 20 long lines"), + ("do not write at least 20 lines", "at least 20 lines"), + ("a 35-line document", "35-line document"), + ("write at least 2 sentences", "at least 2 sentences"), + ( + "do not include the phrase \"X\"", + "include the phrase \"X\"", + ), + ( + "include the phrase \"X\" in the title", + "include the phrase", + ), + ("with 5 sections titled A, B", "sections titled A, B"), + ( + "include the words alpha beta gamma", + "include the words alpha", + ), + ] { + let ex = analyze(g); + assert!( + ex.uncertain.iter().any(|u| u.contains(span)), + "{g}: {:?}", + ex.uncertain + ); + let why = ex.refusal().unwrap(); + assert!(why.starts_with("uncertain requirement"), "{why}"); + } +} + +#[test] +fn clean_goals_have_no_uncertain_spans() { + for g in [ + "write a long document", + "do not use tables. Write at least 20 lines.", + "Add the line \"- add dark mode\" under the \"## Planned\" heading in ROADMAP.md.", + "list three reasons", + ] { + assert!(analyze(g).uncertain.is_empty(), "{g}: {:?}", analyze(g)); + } +} + +#[test] +fn headings_words_phrases_and_topics_extract() { + assert_eq!( + extract("a guide with sections named Intro, Usage and FAQ."), + [RequiredHeadings(vec![ + "Intro".into(), + "Usage".into(), + "FAQ".into() + ])] + ); + assert_eq!( + extract("3 sections called \"Alpha beta\", \"Gamma\" and \"Delta\""), + [RequiredHeadings(vec![ + "Alpha beta".into(), + "Gamma".into(), + "Delta".into() + ])] + ); + assert_eq!( + extract("The text must include the words alpha, beta and gamma."), + [RequiredWords(vec![ + "alpha".into(), + "beta".into(), + "gamma".into() + ])] + ); + assert_eq!( + extract("use the words \"red\" and \"blue\""), + [RequiredWords(vec!["red".into(), "blue".into()])] + ); + assert_eq!( + extract("include the phrases \"good day\", \"all clear\""), + [RequiredPhrases(vec!["good day".into(), "all clear".into()])] + ); + assert_eq!( + extract("a guide that should cover setup, usage and cleanup in at least 30 lines"), + [ + MinLines(30), + RequiredTopics(vec!["setup".into(), "usage".into(), "cleanup".into()]) + ] + ); + assert_eq!( + extract("In every section, write at least three sentences."), + [MinSentencesPerSection(3)] + ); + // "a cover letter" is not a topic list + assert!(analyze("write a cover letter").requirements.is_empty()); +} + +// ---- checks ---- + +#[test] +fn headings_must_be_heading_lines_and_ignore_numbering_case_and_punctuation() { + let r = RequiredHeadings(vec!["Your first week".into(), "Glossary".into()]); + let ok = "# 1. Your First Week:\ntext\n## **glossary**\nx\n"; + assert!(r.check(ok).is_none()); + // a plain line, or a heading inside a code fence, is not a heading + let bad = "Your first week\n```\n# Glossary\n```\n"; + let why = r.check(bad).unwrap(); + assert!( + why.contains("missing \"Your first week\", \"Glossary\""), + "{why}" + ); +} + +#[test] +fn required_words_are_whole_words_case_insensitive() { + let r = RequiredWords(vec!["Blue".into(), "red".into()]); + assert!(r.check("A RED car, a blue one.").is_none()); + let why = r.check("bluebird and reddish").unwrap(); + assert!(why.contains("missing \"Blue\", \"red\""), "{why}"); +} + +#[test] +fn topic_word_forms_are_conservative() { + let r = RequiredTopics(vec![ + "preparing".into(), + "publishing".into(), + "announcing a release".into(), + ]); + // different suffixes agree + assert!(r + .check("Prepare it. Publish it. We announce this release.") + .is_none()); + // nearby words that do not share the stem do not + let why = r.check("Prepare it. Make it public. The announcement of a release."); + let why = why.unwrap(); + assert!(why.contains("not covered: publishing"), "{why}"); + // code blocks are not prose + let why = RequiredTopics(vec!["testing".into()]) + .check("```\ntesting\n```\nnothing here\n") + .unwrap(); + assert!(why.contains("testing"), "{why}"); +} + +#[test] +fn sentences_per_section_counts_prose_under_each_heading() { + let r = MinSentencesPerSection(2); + let ok = + "# Title\n## A\nOne sentence here. Two sentences here.\n## B\nFirst one! Second one?\n"; + assert!(r.check(ok).is_none(), "{:?}", r.check(ok)); + let bad = + "## A\nOne sentence here. Two sentences here.\n## B\nOnly one sentence here.\n## C\n\n"; + let why = r.check(bad).unwrap(); + assert!( + why.contains("B (1)") && why.contains("C (0)") && !why.contains("A ("), + "{why}" + ); + assert!(r + .check("no headings at all. really.\n") + .unwrap() + .contains("no headings")); + // decimals and version numbers do not end a sentence + assert!(MinSentencesPerSection(2) + .check("## A\nUse python 3.10 now. Then 2.5 more.\n") + .is_none()); +} + +#[test] +fn word_counts_and_multiple_code_blocks() { + assert!(MinWords(5).check("a b c d e").is_none()); + assert!(MinWords(6).check("a b c d e").unwrap().contains("found 5")); + // headings after code blocks, and text after several code blocks, still count + let doc = "# One\n```rust\n# not a heading\n```\ntext\n```\n## also not\n```\n## Real\ntail text here. And more.\n"; + assert!(RequiredHeadings(vec!["One".into(), "Real".into()]) + .check(doc) + .is_none()); + assert!(RequiredHeadings(vec!["not a heading".into()]) + .check(doc) + .is_some()); + assert!(MinItems(ItemKind::Sections, 2).check(doc).is_none()); + assert!(MinItems(ItemKind::Sections, 3) + .check(doc) + .unwrap() + .contains("found 2")); + assert!(RequiredTopics(vec!["tail".into()]).check(doc).is_none()); +} + +// ---- the recorded v3 replies ---- + +#[test] +fn recorded_g3_reply_is_refused_and_a_good_reply_passes() { + let ex = analyze(G3_GOAL); + let why = refusal_reason(&ex.requirements, &content_of(G3_V3_REPLY)).unwrap(); + assert!( + why.contains("at least 35 non-empty lines, found 13"), + "{why}" + ); + let (out, a, prompts) = run(G3_GOAL, vec![G3_V3_REPLY.into(), g3_good()]); + assert_eq!(out.unwrap(), g3_good()); + assert_eq!(a[0].outcome, "refused"); + assert!(a[0].unmet_requirements[0].contains("found 13")); + assert_eq!(a[1].outcome, "parsed"); + // the retry prompt names what was missed + assert!( + prompts[1].contains("at least 35 non-empty lines, found 13"), + "{}", + prompts[1] + ); +} + +#[test] +fn recorded_g3_reply_exhausts_with_nothing_approved() { + let (out, a, _) = run(G3_GOAL, vec![G3_V3_REPLY.into()]); + let why = out.unwrap_err(); + assert!(why.contains("found 13"), "{why}"); + assert_eq!(a.len(), COMPOSE_MAX_ATTEMPTS as usize); + assert!(a + .iter() + .all(|x| x.outcome == "refused" && x.aegis.is_none())); +} + +#[test] +fn g3_wrong_headings_and_short_sections_are_named() { + let mut s = String::from("filename: docs/ONBOARDING.md\n"); + for t in ["Welcome", "Setup", "Glossary"] { + s.push_str(&format!("# {t}\n\nOnly one sentence here.\n")); + } + for i in 0..30 { + s.push_str(&format!("filler line {i}\n")); + } + let why = refusal_reason(&analyze(G3_GOAL).requirements, &content_of(&s)).unwrap(); + assert!(why.contains("at least 6 headings, found 3"), "{why}"); + assert!(why.contains("missing \"Accounts and access\""), "{why}"); + assert!(why.contains("too few in: Welcome (1)"), "{why}"); +} + +#[test] +fn recorded_g2_reply_is_refused_and_a_good_reply_passes() { + let ex = analyze(G2_GOAL); + let why = refusal_reason(&ex.requirements, &content_of(G2_V3_REPLY)).unwrap(); + assert!(why.contains("not covered: publishing"), "{why}"); + let (out, a, prompts) = run(G2_GOAL, vec![G2_V3_REPLY.into(), g2_good()]); + assert_eq!(out.unwrap(), g2_good()); + assert_eq!(a[0].outcome, "refused"); + assert!( + prompts[1].contains("not covered: publishing"), + "{}", + prompts[1] + ); + // the recorded reply is exhausted when the model keeps repeating it + let (out, a, _) = run(G2_GOAL, vec![G2_V3_REPLY.into()]); + assert!(out.is_err()); + assert_eq!(a.len(), COMPOSE_MAX_ATTEMPTS as usize); +} + +// ---- through the real compose run (linked build only) ---- + +fn bridge_with( + tmp: &std::path::Path, + f: impl Fn(&str) -> Result + Send + Sync + 'static, +) -> ComposeBridge { + let proposer: ComposeProposer = Arc::new(move |p: &str, _: Duration| f(p)); + ComposeBridge::new(tmp.join("compose"), proposer, "test:enforce") +} + +fn result(resp: ControlResponse) -> Option { + if !aien_omega_compose::LINKED { + assert!(matches!(resp, ControlResponse::Error(_))); + return None; + } + let ControlResponse::ComposeTaskResult(r) = resp else { + panic!("{resp:?}") + }; + Some(*r) +} + +#[test] +fn linked_uncertain_goal_is_refused_before_any_model_call() { + let tmp = tempfile::tempdir().unwrap(); + let ws = tmp.path().join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + let calls = Arc::new(Mutex::new(0usize)); + let c = calls.clone(); + let bridge = bridge_with(tmp.path(), move |_| { + *c.lock().unwrap() += 1; + gen("filename: DOC.md\nhello\n") + }); + let resp = bridge.run_task( + "write DOC.md with at least 3 lines of context", + ws.to_str().unwrap(), + ); + let Some(r) = result(resp) else { return }; + assert_eq!(*calls.lock().unwrap(), 0); + assert!(!r.committed, "{r:?}"); + assert!(r.proposal.is_none()); + assert_eq!(r.requirements_uncertain, ["at least 3 lines of context"]); + assert!(r + .proposer_error + .unwrap() + .starts_with("uncertain requirement")); + assert_eq!(std::fs::read_dir(&ws).unwrap().count(), 0); +} + +#[test] +fn linked_g3_original_reply_is_refused_then_a_good_reply_commits_exact_bytes() { + let tmp = tempfile::tempdir().unwrap(); + let ws = tmp.path().join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + let calls = Arc::new(Mutex::new(0usize)); + let c = calls.clone(); + let bridge = bridge_with(tmp.path(), move |_| { + let mut n = c.lock().unwrap(); + *n += 1; + let good = g3_good(); + gen(if *n == 1 { G3_V3_REPLY } else { &good }) + }); + let resp = bridge.run_task(G3_GOAL, ws.to_str().unwrap()); + let Some(r) = result(resp) else { return }; + assert!(r.requirements_uncertain.is_empty()); + assert_eq!(r.proposal_attempts.len(), 2, "{r:?}"); + assert_eq!(r.proposal_attempts[0].outcome, "refused"); + assert!(r.committed, "{r:?}"); + let p = check_file_proposal(r.proposal.as_deref().unwrap()).unwrap(); + assert_eq!(p.content, content_of(&g3_good())); + assert!(refusal_reason(&analyze(G3_GOAL).requirements, &p.content).is_none()); +} + +#[test] +fn linked_g2_original_reply_exhausts_and_nothing_is_written() { + let tmp = tempfile::tempdir().unwrap(); + let ws = tmp.path().join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + let bridge = bridge_with(tmp.path(), |_| gen(G2_V3_REPLY)); + let resp = bridge.run_task(G2_GOAL, ws.to_str().unwrap()); + let Some(r) = result(resp) else { return }; + assert!(!r.committed, "{r:?}"); + assert!(r.proposal.is_none()); + assert_eq!(r.proposal_attempts.len(), COMPOSE_MAX_ATTEMPTS as usize); + assert!(r + .proposer_error + .unwrap() + .contains("not covered: publishing")); + assert_eq!(std::fs::read_dir(&ws).unwrap().count(), 0); +} + +// ---- review round: nothing that looks like a requirement passes silently ---- + +#[test] +fn sixteen_review_goals_are_recognized_or_uncertain_never_silent() { + for g in [ + "run to 30 lines or more", + "25 lines minimum", + "Keep it to 10 lines", + "no longer than 40 lines", + "Limit it to 80 words", + "Use each of these words: alpha, beta", + "Include headings for A and B", + "needs a Summary heading and a Risks heading", + "three sections", + "ten bullet points", + "Give it two code blocks", + "One code block only", + "Three paragraphs", + "Cover at least 4 topics: a, b, c, d", + "Each section needs 2 sentences", + "say the word 'canary' at least twice", + ] { + let ex = analyze(g); + assert!( + !ex.requirements.is_empty() || !ex.uncertain.is_empty(), + "silent: {g}" + ); + } + // the common ones are recognized properly + assert_eq!(extract("run to 30 lines or more"), [MinLines(30)]); + assert_eq!(extract("25 lines minimum"), [MinLines(25)]); + assert_eq!(extract("no longer than 40 lines"), [MaxLines(40)]); +} + +#[test] +fn false_positive_guards_stay_silent() { + for g in [ + "Fix the 2 typos", + "version 3.2 notes", + "10 minute setup guide", + "5 tests", + "Add the line \"- x\" under the \"## Planned\" heading in ROADMAP.md.", + "Update section 2 of the README", + "Create 2024-report.md with a short summary", + ] { + let ex = analyze(g); + assert!( + ex.requirements.is_empty() && ex.uncertain.is_empty(), + "{g}: {ex:?}" + ); + } +} + +#[test] +fn a_count_after_covering_is_a_count_or_uncertain_never_a_topic() { + let ex = analyze("Write GUIDE.md covering 5 steps."); + assert!(ex.requirements.is_empty(), "{ex:?}"); + assert!(!ex.uncertain.is_empty()); +} + +#[test] +fn trailing_courtesy_words_are_tolerated() { + assert_eq!(extract("At most 15 lines please."), [MaxLines(15)]); + assert!(analyze("At most 15 lines please.").uncertain.is_empty()); + assert_eq!(extract("at least 12 lines, thanks"), [MinLines(12)]); +} diff --git a/crates/aien-runtime/tests/requirements_test.rs b/crates/aien-runtime/tests/requirements_test.rs index e96945a2..0c730eeb 100644 --- a/crates/aien-runtime/tests/requirements_test.rs +++ b/crates/aien-runtime/tests/requirements_test.rs @@ -61,11 +61,7 @@ fn extracts_each_supported_pattern() { 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", @@ -490,8 +486,6 @@ fn count_followed_by_a_qualifier_is_not_extracted() { "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}"); @@ -504,14 +498,27 @@ fn count_followed_by_a_qualifier_is_not_extracted() { ("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)), + ("at least 6 lines with comments", MinLines(6)), + ("at least 6 lines about cats", MinLines(6)), + ("at least 20 lines long", MinLines(20)), ] { assert_eq!(extract(g), [want], "{g}"); } } +#[test] +fn covering_after_a_count_adds_a_topic_requirement() { + assert_eq!( + extract("at least 20 lines covering the topic"), + [ + Requirement::MinLines(20), + Requirement::RequiredTopics(vec!["the topic".into()]) + ] + ); +} + #[test] fn phrase_followed_by_a_qualifier_is_not_extracted() { // "in the title" would make the whole-document check claim more than it covers. @@ -536,8 +543,6 @@ fn negated_wording_is_not_extracted() { "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", ] { diff --git a/crates/aien-runtime/tests/requirements_usability_test.rs b/crates/aien-runtime/tests/requirements_usability_test.rs new file mode 100644 index 00000000..77c518fb --- /dev/null +++ b/crates/aien-runtime/tests/requirements_usability_test.rs @@ -0,0 +1,483 @@ +//! Ordinary counted requests and the wider wordings (crate::requirements_extract), +//! PR round 2: "Add 2 lines to README.md" is read, not refused; every goal of the +//! campaign task files is classified (recognized, silent or uncertain) and the +//! refused ones are listed with their reason. +use aien_runtime::requirements::{analyze, refusal_reason, unmet, ItemKind, Requirement}; +use aien_runtime::spine::{propose_task_checked, Generation}; +use std::time::Duration; + +use Requirement::*; + +fn added(n: usize, exact: bool) -> Requirement { + AddedLines { + n, + exact, + prior: None, + } +} + +fn reqs(goal: &str) -> Vec { + let ex = analyze(goal); + assert!( + ex.uncertain.is_empty(), + "{goal:?} should be read, uncertain: {:?}", + ex.uncertain + ); + ex.requirements +} + +fn uncertain(goal: &str) -> Vec { + let ex = analyze(goal); + assert!( + !ex.uncertain.is_empty(), + "{goal:?} should be refused as uncertain, got {:?}", + ex.requirements + ); + ex.uncertain +} + +#[test] +fn counted_requests_are_read_by_the_documented_rule() { + // add|append|insert|with N lines (and "N-line"): exactly N added lines. + for (goal, n) in [ + ("Add one line to notes/TODO.md saying buy milk", 1), + ("Add 2 lines to README.md", 2), + ("Append 3 lines to LOG.md", 3), + ("Add a one-line note to README.md", 1), + ("Insert two lines under the intro in docs/a.md", 2), + ("Add exactly 4 lines to docs/a.md.", 4), + ("Write a two-line poem", 2), + ( + "Create the file docs/CONTACT.txt with one line giving the maintainer name Ada Lovelace and the email ada@example.org.", + 1, + ), + ] { + assert_eq!(reqs(goal), [added(n, true)], "{goal}"); + } + // write|put|create|... N lines: at least N added lines. + for (goal, n) in [ + ("Write 20 lines about X to docs/x.md", 20), + ("Please write five lines on composting in docs/c.md", 5), + ("Draft 12 lines for the changelog", 12), + ] { + assert_eq!(reqs(goal), [added(n, false)], "{goal}"); + } +} + +#[test] +fn bare_counts_with_a_qualifier_or_no_verb_stay_uncertain() { + for goal in [ + "Add 3 lines of context to README.md", + "Write 10 lines per section in docs/a.md", + "Keep it to 10 lines", + "Do not add 2 lines to README.md", + "The note should be 5 lines", + "Add a one-sentence summary to README.md", + "Create the file docs/HELLO.txt with a one-sentence greeting.", + ] { + uncertain(goal); + } +} + +#[test] +fn wider_wordings_are_read() { + assert_eq!( + reqs("Write a new file docs/B.md. A minimum of 20 lines is needed."), + [MinLines(20)] + ); + assert_eq!(reqs("At least 20 lines are required."), [MinLines(20)]); + assert_eq!(reqs("It needs 20 lines minimum."), [MinLines(20)]); + assert_eq!( + reqs("Finish with a section titled \"Restore notes\" that holds at least 15 words of plain text."), + [ + SectionMinWords { + title: Some("Restore notes".into()), + n: 15 + }, + RequiredHeadings(vec!["Restore notes".into()]), + ] + ); + assert_eq!( + reqs("The last section needs at least 15 words of plain text."), + [SectionMinWords { title: None, n: 15 }] + ); + assert_eq!( + reqs("Use three level-two sections titled \"Building\", \"Testing\" and \"Packaging\", then add notes."), + [LevelHeadings { + level: 2, + titles: vec!["Building".into(), "Testing".into(), "Packaging".into()] + }] + ); + assert_eq!( + reqs("Include three separate fenced code examples."), + [MinItems(ItemKind::CodeBlocks, 3)] + ); +} + +#[test] +fn unscoped_word_counts_and_topic_lists_stay_uncertain() { + uncertain("Write it with at least 15 words of plain text."); + uncertain("Cover three topics: drying, labelling and storage."); + uncertain("Put one fenced shell code example in each of them."); + uncertain("Each section has two sentences."); +} + +#[test] +fn the_new_checks_measure_the_right_thing() { + let doc = "# A\nprose\n\n## Building\none two three\n## Testing\nx\n## Packaging\ny\n"; + let lv = LevelHeadings { + level: 2, + titles: vec!["Building".into(), "Testing".into(), "Packaging".into()], + }; + assert!(lv.check(doc).is_none()); + // Wrong level is missing; extra ## sections are fine. + let deep = doc.replace("## Testing", "### Testing"); + assert!(lv.check(&deep).unwrap().contains("\"Testing\"")); + assert!(lv.check(&format!("{doc}## Summary\nz\n")).is_none()); + let last = SectionMinWords { title: None, n: 3 }; + assert!(last.check("# T\n## End\nonly two\n").is_some()); + assert!(last.check("# T\n## End\nnow three words\n").is_none()); + // Code lines and headings are not plain text. + let named = SectionMinWords { + title: Some("Restore notes".into()), + n: 4, + }; + assert!(named + .check("## Restore notes\n```sh\none two three four five\n```\nshort\n") + .is_some()); + assert!(named + .check("## Restore notes\nfour plain words here\n") + .is_none()); + assert!(named.check("## Other\nfour plain words here\n").is_some()); + let blocks = MinItems(ItemKind::CodeBlocks, 2); + assert!(blocks.check("```sh\na\n```\ntext\n~~~\nb\n~~~\n").is_none()); + assert!(blocks.check("```sh\na\n```\n").is_some()); +} + +fn gen(text: &str) -> Result { + Ok(Generation { + text: text.to_string(), + tokens: 5, + finish_reason: Some("eos".into()), + ..Default::default() + }) +} + +/// One model reply through the retry loop with `prior` as the edit target. +fn run_edit(goal: &str, path: &str, prior: Option<&str>, reply: &str) -> Result { + let mut ex = analyze(goal); + assert!(ex.uncertain.is_empty(), "{:?}", ex.uncertain); + if ex.needs_prior() { + ex = ex.resolved(prior.unwrap_or("")); + } + let proposer = |_: &str, _: Duration| gen(reply); + let edit = prior.map(|p| (path, p)); + propose_task_checked( + &proposer, + "base", + edit, + &ex.requirements, + Duration::from_secs(5), + Duration::from_millis(1), + 1, + ) + .0 +} + +const PRIOR: &str = "# Notes\n\nfirst\nsecond\n"; + +#[test] +fn counted_edits_are_judged_on_the_diff_of_the_exact_proposed_bytes() { + let g = "Add 2 lines to README.md"; + let two = "filename: README.md\n# Notes\n\nfirst\nnew a\nnew b\nsecond\n"; + let one = "filename: README.md\n# Notes\n\nfirst\nnew a\nsecond\n"; + let three = "filename: README.md\n# Notes\n\nfirst\nnew a\nnew b\nnew c\nsecond\n"; + assert!(run_edit(g, "README.md", Some(PRIOR), two).is_ok()); + let e = run_edit(g, "README.md", Some(PRIOR), one).unwrap_err(); + assert!( + e.contains("exactly 2 added non-empty lines, found 1"), + "{e}" + ); + let e = run_edit(g, "README.md", Some(PRIOR), three).unwrap_err(); + assert!(e.contains("found 3"), "{e}"); + // Blank lines are not lines. + let blanks = "filename: README.md\n# Notes\n\nfirst\n\nnew a\n\nnew b\nsecond\n"; + assert!(run_edit(g, "README.md", Some(PRIOR), blanks).is_ok()); + // "write N lines": at least N added; a new file has no prior lines. + let w = "Write 3 lines about bread to README.md"; + let four = "filename: README.md\n# Notes\n\nfirst\na\nb\nc\nd\nsecond\n"; + assert!(run_edit(w, "README.md", Some(PRIOR), four).is_ok()); + assert!(run_edit(w, "README.md", Some(PRIOR), two).is_err()); + let fresh = "filename: NEW.md\nl1\nl2\n"; + assert!(run_edit("Add 2 lines to NEW.md", "NEW.md", None, fresh).is_ok()); + assert!(run_edit("Add 3 lines to NEW.md", "NEW.md", None, fresh).is_err()); + // Whole-file bytes that rewrite prior lines count the rewritten ones as added. + let rewritten = "filename: README.md\n# Notes\n\nfirst CHANGED\nsecond\nnew\n"; + let e = run_edit(g, "README.md", Some(PRIOR), rewritten); + assert!(e.is_ok(), "{e:?}"); +} + +#[test] +fn an_unresolved_added_line_count_fails_closed() { + let ex = analyze("Add 2 lines to README.md"); + let u = unmet(&ex.requirements, "a\nb\n"); + assert_eq!(u.len(), 1); + assert!(u[0].contains("cannot be measured"), "{u:?}"); + assert!(refusal_reason(&ex.requirements, "a\nb\n").is_some()); + // Resolved against the file the bytes replace, the same bytes pass. + let ok = ex.resolved(""); + assert!(unmet(&ok.requirements, "a\nb\n").is_empty()); +} + +#[test] +fn a_machine_goal_for_an_approved_proposal_states_no_requirement() { + // The goal the hook builds is "apply approved proposal for (request )". + for path in [ + "docs/10 lines.md", + "docs/add 2 lines.md", + "notes/at least 5 lines.md", + "write 20 lines.txt", + ] { + let goal = format!("apply approved proposal for {path} (request req-1)"); + let ex = analyze(&goal); + assert!( + ex.requirements.is_empty() && ex.uncertain.is_empty(), + "{goal}: {ex:?}" + ); + } +} + +// ---- the campaign goals: recognized, silent or uncertain ---- + +const CORPUS: &str = include_str!("fixtures/goal_corpus.tsv"); + +/// Goals that state no measurable requirement: nothing to enforce, nothing refused. +const SILENT: [&str; 12] = [ + "dryrun-tasks-v2/N2", + "dryrun-tasks-v2/R1", + "dryrun-tasks-v2/T5", + "dryrun-tasks-v2/T7", + "tasks-oq3-v3/E1", + "tasks-oq3-v3/E2", + "tasks-oq3-v4/U1", + "tasks-oq3-v4/U2", + "tasks-v5/T1", + "tasks-v5/T3", + "tasks-v6/T5", + "tasks-v8/T7", +]; + +/// Goals whose explicit requirements are all read and enforced. +const RECOGNIZED: [&str; 15] = [ + "dryrun-tasks-v2/N1", + "tasks-oq3-v3/N1", + "tasks-oq3-v4/N1", + "tasks-v6/N1", + "dryrun-tasks-v2/T4", + "tasks-oq3-v3/G2", + "tasks-oq3-v3/G3", + "tasks-oq3-v4/RT4", + "tasks-oq3-v4/RT6", + "tasks-oq3-v4/W1", + "tasks-oq3-v4/W2", + "tasks-oq3-v4/W4", + "tasks-v5/T2", + "tasks-v8/D3", + "tasks-v8/D4", +]; + +/// Goals still refused as uncertain, each with the span that is reported and why. +const REFUSED: [(&str, &str, &str); 9] = [ + ( + "dryrun-tasks-v2/T6", + "one section per symptom", + "a section count that depends on the content", + ), + ( + "tasks-oq3-v3/G1", + "one fenced shell code example in each of them", + "a per-section code example count", + ), + ( + "tasks-oq3-v3/N2", + "at least ten paragraphs", + "paragraph counts are not supported", + ), + ( + "tasks-oq3-v3/R1", + "one-sentence greeting", + "sentence counts over the whole document are not verified", + ), + ( + "tasks-oq3-v4/N2", + "at least twelve paragraphs", + "paragraph counts are not supported", + ), + ( + "tasks-oq3-v4/R1", + "one-sentence thank-you note", + "sentence counts over the whole document are not verified", + ), + ( + "tasks-oq3-v4/W3", + "three topics", + "a topic list after a colon cannot be checked mechanically", + ), + ( + "tasks-oq3-v4/W5", + "twelve of them", + "a count of items the goal does not name", + ), + ( + "tasks-v8/D5", + "10 frequently asked questions and answers", + "a count with a long adjective phrase", + ), +]; + +#[test] +fn every_campaign_goal_is_recognized_silent_or_refused_for_a_listed_reason() { + let mut seen = 0; + for line in CORPUS.lines() { + let (id, goal) = line.split_once('\t').expect("id TAB goal"); + let ex = analyze(goal); + seen += 1; + if SILENT.contains(&id) { + assert!( + ex.requirements.is_empty() && ex.uncertain.is_empty(), + "{id} should be silent: {ex:?}" + ); + } else if RECOGNIZED.contains(&id) { + assert!( + !ex.requirements.is_empty() && ex.uncertain.is_empty(), + "{id} should be recognized: {ex:?}" + ); + } else if let Some((_, span, _why)) = REFUSED.iter().find(|r| r.0 == id) { + assert!( + ex.uncertain.iter().any(|u| u.contains(span)), + "{id} should be refused on {span:?}: {:?}", + ex.uncertain + ); + } else { + panic!("{id} is in no list: {ex:?}"); + } + } + // Every listed id exists in the corpus. + assert_eq!(seen, SILENT.len() + RECOGNIZED.len() + REFUSED.len()); +} + +#[test] +fn the_w2_goal_is_fully_enforced() { + let goal = CORPUS + .lines() + .find(|l| l.starts_with("tasks-oq3-v4/W2\t")) + .and_then(|l| l.split_once('\t')) + .map(|x| x.1) + .unwrap(); + let ex = analyze(goal); + assert!(ex.uncertain.is_empty()); + assert!(ex.requirements.contains(&MinLines(20))); + assert!(ex.requirements.contains(&MinItems(ItemKind::CodeBlocks, 3))); + assert!(ex.requirements.contains(&SectionMinWords { + title: Some("Restore notes".into()), + n: 15 + })); + let mut good = String::new(); + for t in ["Create the archive", "Copy it offsite", "Verify the copy"] { + good.push_str(&format!( + "## {t}\n```sh\necho {}\n```\nsome words about it\n\n", + t.len() + )); + } + good.push_str("## Restore notes\nrestore the newest archive first then check the files one by one afterwards carefully\n"); + for i in 0..10 { + good.push_str(&format!("closing line {i}\n")); + } + // The long closing lines sit in the last section; keep the heading text rule honest. + let good = good.replace("closing line 0\n", ""); + assert!( + refusal_reason(&ex.requirements, &good).is_none(), + "{:?}", + refusal_reason(&ex.requirements, &good) + ); + let short = good.replace( + "restore the newest archive first then check the files one by one afterwards carefully\n", + "restore it\n", + ); + let short = short + .lines() + .filter(|l| !l.starts_with("closing line")) + .collect::>() + .join("\n"); + assert!(refusal_reason(&ex.requirements, &short) + .unwrap() + .contains("words of plain text in the section \"Restore notes\"")); +} + +// ---- round 3 ---- + +fn added_check(goal: &str, prior: &str, content: &str) -> Option { + let ex = analyze(goal).resolved(prior); + assert!(ex.uncertain.is_empty(), "{:?}", ex.uncertain); + refusal_reason(&ex.requirements, content) +} + +#[test] +fn an_add_request_may_not_delete_or_rewrite_existing_lines() { + let prior = "a\nb\nc\nd\n"; + let g = "Add 2 lines to README.md"; + for bad in ["x\ny\n", "a\nb\nx\ny\n", "a\nb\nC\nD\n", "a\nb\nc\nd\nx\n"] { + assert!( + added_check(g, prior, bad).is_some(), + "{bad:?} must be refused" + ); + } + let e = added_check(g, prior, "a\nb\nC\nD\n").unwrap(); + assert!(e.contains("changed or removed"), "{e}"); + // Inserts in the middle or at the end, blank lines, and trailing-space-only + // edits to existing lines are allowed (trailing whitespace is not content). + for ok in [ + "a\nb\nx\nc\ny\nd\n", + "a\nb\nc\nd\nx\ny\n", + "x\ny\na\nb\nc\nd\n", + "a \nb\nc\t\nd\n\nx\n\ny\n", + ] { + assert!(added_check(g, prior, ok).is_none(), "{ok:?} must pass"); + } + // The same holds for "write N lines" (at least N). + let w = "Write 2 lines about bread to README.md"; + assert!(added_check(w, prior, "x\ny\nz\n").is_some()); + assert!(added_check(w, prior, "a\nb\nc\nd\nx\ny\nz\n").is_none()); +} + +#[test] +fn vague_or_odd_counts_are_uncertain_not_silent() { + for goal in [ + "Add 2-3 lines to README.md", + "Write a dozen lines about bread", + "The line count should be at least 40.", + "Write a script with 2 shell commands.", + "Use \"A\", \"B\" and \"C\" as level-two headings.", + "Use level-two headings \"A\", \"B\" and \"C\".", + "Write three-plus sections about bread.", + "Use a section titled Intro has 80 words of plain text.", + "Add 2 lines at most to README.md", + ] { + uncertain(goal); + } +} + +#[test] +fn lower_bound_after_the_noun_and_single_line() { + assert_eq!( + reqs("Write forty lines at least to docs/a.md"), + [added(40, false)] + ); + assert_eq!( + reqs("Add a single line saying hello to a.md"), + [added(1, true)] + ); + // No explicit count: nothing is measured (documented): "a line" is not a number word. + assert!(reqs("Add a line saying hello to a.md").is_empty()); + assert!(reqs("Add a couple of lines or a few to a.md").is_empty()); +} diff --git a/docs/COMPOSE_PROPOSER_HOOK.md b/docs/COMPOSE_PROPOSER_HOOK.md index bd4a9c39..acdfc13c 100644 --- a/docs/COMPOSE_PROPOSER_HOOK.md +++ b/docs/COMPOSE_PROPOSER_HOOK.md @@ -27,7 +27,12 @@ returns Ok only if the run committed exactly the approved text. ## What the ledger hands over (`ApprovedProposal`) request_id, trace_id, approval_id, approver, path, content, -approved_proposal_sha256, content_sha256, approval_mac. The hook returns +approved_proposal_sha256, content_sha256, approval_mac, requirements, requirements_mac. `requirements` is the original goal text whose measurable +requirements the approved bytes must meet; `requirements_mac` is the desk key's HMAC over the approval binding and that text (tag `aien.requirements.v1`), so +a caller cannot swap or drop it. `Some("")` is a signed "no requirements"; a missing +`requirements` is refused (`RequirementsUnbound`), a goal with an unreadable requirement +is refused (`RequirementsUncertain`), and bytes that miss a requirement are refused +(`RequirementsUnmet`), all before any claim or compose run. A count such as "add 2 lines to NOTES.md" is judged on the diff between the existing workspace file (empty when absent) and the approved bytes. Existing lines must all survive, so such an approval can only add. Such a goal also needs `requirements_base`: the sha256 (hex) of the existing file as the desk saw it, or `absent`, covered by `requirements_mac` (tag `aien.requirements.v2`; v1 when no requirement depends on the file). It is refused when missing (`RequirementsUnbound`) or when the file differs (`BaseChanged`), and it is checked again under the compose-home lock when the grant is written, so a file that changed after the check gets no grant. Limit: a file over 8192 bytes (or not UTF-8) cannot be measured and is refused. The hook returns `ApprovedComposeReport`: state (COMMITTED | ALREADY_COMMITTED), the same ids, compose_proposal_sha256, grant_links, desk_key_id, approval_key, replay_claim and the compose `task` report (None for ALREADY_COMMITTED); or