diff --git a/.crumb b/.crumb index 5d4d3822..f8c53eb4 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:2773d5ada0e6ae8b446499314f4a704361ab91a14a35259a62607b7c731d0ab9", - "compiled_at": "2026-10-08T06:17:09Z", + "compiled_at": "2026-10-08T07:09:52Z", "compiler": "crumb-compile/1", - "digest": "sha256:b638673eea730af338429e079bad5c5c346a4b1e71e9ffeae4e28f5ea81a3d40", + "digest": "sha256:bd0a783a67322a7dff55098b23e5c40b92319f80220d29ccfaa7e1aea0f80aef", "evidence_files": 187, "evidence_root": "sha256:27ee0353cb4d4aae2b7dbce2bfe0d9f4ef2a94cd7a4555b84684d59372503280", - "files": 1359, - "generated_at_commit": "a720af06dd282faeaf4e549a6f39d556a7ccfb72", - "source_tree": "sha256:98fd8c938ef1e74410f167ed3c35d2ea34ae22eb3c7db53ea40ddc5bcb6fb0ee" + "files": 1360, + "generated_at_commit": "47a05e71c440970b1539e2bf1256b2950a973435", + "source_tree": "sha256:bd6748a40fdb373aa29fd6058b1fa9ff35a4ddc8eb33f173a6f13b6e37896cf5" } }, "history": [], diff --git a/crates/aien-runtime/src/requirements.rs b/crates/aien-runtime/src/requirements.rs index 60d1c073..5cb8e718 100644 --- a/crates/aien-runtime/src/requirements.rs +++ b/crates/aien-runtime/src/requirements.rs @@ -25,7 +25,8 @@ //! 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. +//! of sentences in every section; and a markdown heading as the first line +//! (`start with a Markdown heading line that begins with "# "`). //! //! ## What a requirement is judged on //! @@ -135,6 +136,12 @@ pub enum Requirement { level: usize, titles: Vec, }, + /// The first line of the file is a markdown ATX heading: 1 to 6 `#` at the very start of + /// the line, then a space or tab, then title text. `level`: exactly that many `#`; + /// None: any of 1 to 6. + FirstLineHeading { + level: Option, + }, } fn quoted(items: &[String]) -> String { @@ -175,6 +182,13 @@ impl Requirement { Requirement::LevelHeadings { level, titles } => { format!("the level-{level} headings {}", quoted(titles)) } + Requirement::FirstLineHeading { level } => match level { + Some(l) => format!( + "a level-{l} markdown heading (\"{} \") as the first line", + "#".repeat(*l) + ), + None => "a markdown heading as the first line".to_string(), + }, } } @@ -306,6 +320,24 @@ impl Requirement { ) }) } + Requirement::FirstLineHeading { level } => { + let first = content.split('\n').next().unwrap_or(""); + let first = first.strip_suffix('\r').unwrap_or(first); + let hashes = first.bytes().take_while(|&b| b == b'#').count(); + let has_title = first[hashes..] + .strip_prefix([' ', '\t']) + .is_some_and(|t| !t.trim().trim_end_matches('#').trim().is_empty()); + let ok = + (1..=6).contains(&hashes) && level.is_none_or(|l| l == hashes) && has_title; + (!ok).then(|| { + let shown: String = first.chars().take(60).collect(); + if shown.is_empty() { + format!("{label}, found an empty first line") + } else { + format!("{label}, found \"{shown}\"") + } + }) + } Requirement::MinSentencesPerSection(n) => { let secs = parse_sections(content); if secs.is_empty() { diff --git a/crates/aien-runtime/src/requirements_extract.rs b/crates/aien-runtime/src/requirements_extract.rs index 432a1529..8cdfbd47 100644 --- a/crates/aien-runtime/src/requirements_extract.rs +++ b/crates/aien-runtime/src/requirements_extract.rs @@ -25,6 +25,7 @@ //! | ` 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) | +//! | `start|begin|open with a [markdown] [level-N] heading [line]`, then the end of the clause or `that begins|starts with "# "` (quoted, 1 to 6 `#` and one space) | `FirstLineHeading` (the first line of the file is that heading; a marker fixes the level). Negated, emphasised, qualified or unquoted forms, and any other heading wording after `start with a`, are UNCERTAIN | //! | `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 @@ -1347,6 +1348,99 @@ pub fn analyze(goal: &str) -> Extraction { } } + // ---- first-line heading: "start with a [markdown] [level-N] heading [line] + // [that begins with "# "]" ---- + let mut first_heading: Option> = None; + for v in 0..n { + let w = |i: usize| toks.get(i).map(|t| t.word.as_str()); + if handled.contains(&v) + || !matches!( + w(v), + Some("start" | "starts" | "begin" | "begins" | "open" | "opens") + ) + || w(v + 1) != Some("with") + || w(v + 2) != Some("a") + || (v..v + 2).any(|i| ends_clause(&toks[i].raw)) + { + continue; + } + let mut k = v + 3; + if w(k) == Some("markdown") && !ends_clause(&toks[k].raw) { + k += 1; + } + let adj = w(k).and_then(level_adj); + if adj.is_some() && !ends_clause(&toks[k].raw) { + k += 1; + } + if w(k) != Some("heading") { + // "start with a **heading**", "start with a short heading": a heading + // wording this recognizer does not read is uncertain, never silent. + if (v + 3..=v + 5).any(|i| toks.get(i).is_some_and(|t| t.norm.starts_with("heading"))) { + bad(&mut unsure, v, false); + } + continue; + } + if w(k + 1) == Some("line") && !ends_clause(&toks[k].raw) { + k += 1; + } + if negated_before(&toks, v) { + bad(&mut unsure, v, false); + continue; + } + // The heading clause must END its sentence: anything after it in the same + // sentence ("and keep it brief", ", then a table") is left to the refusal below, + // so no sibling constraint is swallowed unchecked. + let sentence_end = |raw: &str| raw.ends_with(['.', '!', '?']); + let found = if sentence_end(&toks[k].raw) || k + 1 == n { + Some((adj, k)) + } else if matches!(w(k + 1), Some("that" | "which")) + && matches!(w(k + 2), Some("begins" | "starts" | "begin" | "start")) + && w(k + 3) == Some("with") + && (k..k + 3).all(|i| !ends_clause(&toks[i].raw)) + { + // The marker: a quoted run of 1 to 6 `#` and one space, then the end of + // the clause. Anything else ("#" alone, "a hash", a qualifier) is uncertain. + let from = toks[k + 3].end; + let rest = &goal[from..]; + let lead = rest.len() - rest.trim_start().len(); + let mut cs = rest[lead..].char_indices(); + let marker = cs.next().and_then(|(_, q)| { + let close: &[char] = match q { + '"' => &['"'], + '\u{201C}' => &['\u{201D}', '"'], + '\'' => &['\''], + '`' => &['`'], + _ => return None, + }; + let body = &rest[lead + q.len_utf8()..]; + let h = body.bytes().take_while(|&b| b == b'#').count(); + let after_space = body[h..].strip_prefix(' ')?; + let c = after_space.chars().next().filter(|c| close.contains(c))?; + let end = from + rest.len() - after_space.len() + c.len_utf8(); + let tail_ok = + goal[end..].trim_end().is_empty() || goal[end..].starts_with(['.', '!', '?']); + ((1..=6).contains(&h) && tail_ok).then_some((h, end)) + }); + match marker { + Some((h, end)) if adj.is_none_or(|a| a == h) => { + mark_bytes(&mut handled, &toks, from, end); + let last = (0..n).rev().find(|&i| toks[i].start < end).unwrap_or(k + 3); + Some((Some(h), last)) + } + _ => None, + } + } else { + None + }; + match found { + Some((level, last)) if first_heading.is_none_or(|f| f == level) => { + first_heading = Some(level); + handled.extend(v..=last.max(k)); + } + _ => bad(&mut unsure, v, false), + } + } + // ---- candidates the recognizers above did not claim ---- for s in 0..n { if handled.contains(&s) { @@ -1531,6 +1625,9 @@ pub fn analyze(goal: &str) -> Extraction { if !words.is_empty() { requirements.push(Requirement::RequiredWords(words)); } + if let Some(level) = first_heading { + requirements.push(Requirement::FirstLineHeading { level }); + } unsure.sort_by_key(|u| u.0); let mut uncertain: Vec = Vec::new(); let all: Vec = unsure.into_iter().map(|u| u.1).collect(); diff --git a/crates/aien-runtime/tests/requirements_first_heading_test.rs b/crates/aien-runtime/tests/requirements_first_heading_test.rs new file mode 100644 index 00000000..7f4a5eab --- /dev/null +++ b/crates/aien-runtime/tests/requirements_first_heading_test.rs @@ -0,0 +1,200 @@ +//! A goal that asks the document to start with a markdown heading +//! (Requirement::FirstLineHeading). The ALLEN end-to-end demo v2 request was +//! refused as uncertain because no recognizer read this wording (arch#162). +//! Recognizing it must not loosen any other uncertain wording. +use aien_runtime::requirements::{analyze, refusal_reason, Requirement}; +use aien_runtime::spine::{ + check_file_proposal, propose_task_checked, Generation, COMPOSE_MAX_ATTEMPTS, +}; +use std::sync::Mutex; +use std::time::Duration; + +use Requirement::*; + +/// The S3 request of docs/campaigns/allen-e2e/DEMO-v2.md, verbatim. +const DEMO_V2_GOAL: &str = "Write garden.md in the workspace, a garden plan. Start with a Markdown heading line that begins with \"# \". Use at most 200 words."; + +fn gen(text: &str) -> Result { + Ok(Generation { + text: text.to_string(), + tokens: 5, + finish_reason: Some("eos".into()), + ..Default::default() + }) +} + +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) +} + +const NO_HEADING: &str = + "filename: garden.md\nGarden plan\n\nPlant tomatoes in May and water them weekly.\n"; +const GOOD: &str = + "filename: garden.md\n# Garden plan\n\nPlant tomatoes in May and water them weekly.\n"; + +#[test] +fn demo_v2_goal_is_fully_recognized() { + let ex = analyze(DEMO_V2_GOAL); + assert!(ex.uncertain.is_empty(), "{:?}", ex.uncertain); + assert_eq!( + ex.requirements, + [MaxWords(200), FirstLineHeading { level: Some(1) }] + ); + // The S8 request differs only in the file name. + let s8 = DEMO_V2_GOAL.replace("garden.md", "garden-b.md"); + assert_eq!(analyze(&s8), ex); +} + +#[test] +fn first_heading_phrasings() { + for (g, want) in [ + ( + "Start with a Markdown heading line that begins with \"# \".", + Some(1), + ), + ( + "start with a markdown heading line that starts with \"## \"", + Some(2), + ), + ("Begin with a heading.", None), + ("Start with a Markdown heading.", None), + ("It must start with a level-two heading.", Some(2)), + ("Open with a markdown heading line.", None), + ( + "Start with a heading that begins with \u{201C}# \u{201D}.", + Some(1), + ), + ] { + let ex = analyze(g); + assert!(ex.uncertain.is_empty(), "{g}: {:?}", ex.uncertain); + assert_eq!(ex.requirements, [FirstLineHeading { level: want }], "{g}"); + } +} + +#[test] +fn near_misses_stay_uncertain() { + for g in [ + // negated: never inverted + "Don't start with a Markdown heading.", + // a marker that is not a heading marker on its own + "Start with a Markdown heading line that begins with \"#\".", + // the level adjective and the marker disagree + "Start with a level-one heading line that begins with \"## \".", + // seven hashes is not a heading + "Start with a heading line that begins with \"####### \".", + // emphasis around the wording + "Start with a **Markdown heading**.", + "Start with a **heading**.", + // another word before "heading" + "Begin with a short heading.", + // a qualifier after the heading + "Start with a Markdown heading about tomatoes.", + "Start with a Markdown heading line that begins with \"# \" in bold.", + // no marker after "begins with" + "Start with a Markdown heading line that begins with a hash.", + // a sibling constraint in the same sentence is never swallowed (R319 MUST 1) + "Begin with a markdown heading and keep it brief", + "Begin with a markdown heading and lowercase only", + "Begin with a markdown heading and end with a signature", + "Begin with a markdown heading, then a table", + "Begin with a markdown heading and a few sections", + "Open with a level-2 heading line and a short list", + "Open with a markdown heading line, and keep it short.", + "Start with a heading line that begins with \"# \" and at most 5 items.", + "Start with a heading, ####### markdown.", + // other heading cues the safety net already refused + "The page needs a Summary heading.", + "Include headings for setup and use.", + ] { + let ex = analyze(g); + assert!(!ex.uncertain.is_empty(), "{g}: should be uncertain"); + assert!( + !ex.requirements + .iter() + .any(|r| matches!(r, FirstLineHeading { .. })), + "{g}: {:?}", + ex.requirements + ); + } +} + +#[test] +fn the_first_line_is_checked() { + let one = FirstLineHeading { level: Some(1) }; + let any = FirstLineHeading { level: None }; + for (doc, ok1, ok_any) in [ + ("# Garden plan\nbody\n", true, true), + ("# Garden plan\r\nbody\r\n", true, true), + ("# Garden plan", true, true), + ("## Garden plan\n", false, true), + ("###### Six\n", false, true), + ("####### Seven\n", false, false), + ("Garden plan\n# Later\n", false, false), + ("\n# Garden plan\n", false, false), + (" # Indented\n", false, false), + ("#Garden\n", false, false), + ("# \nbody\n", false, false), + ("#\n", false, false), + ("", false, false), + ("\u{feff}# Garden plan\n", false, false), + ] { + assert_eq!(one.check(doc).is_none(), ok1, "level 1 on {doc:?}"); + assert_eq!(any.check(doc).is_none(), ok_any, "any level on {doc:?}"); + } + let why = one.check("Garden plan\n").unwrap(); + assert!(why.contains("first line"), "{why}"); +} + +#[test] +fn a_reply_without_the_heading_is_refused_then_a_good_one_passes() { + let ex = analyze(DEMO_V2_GOAL); + let content = check_file_proposal(NO_HEADING).unwrap().content; + let why = refusal_reason(&ex.requirements, &content).unwrap(); + assert!(why.contains("first line"), "{why}"); + let (out, a, prompts) = run(DEMO_V2_GOAL, vec![NO_HEADING.into(), GOOD.into()]); + assert_eq!(out.unwrap(), GOOD); + assert_eq!(a[0].outcome, "refused"); + assert_eq!(a[1].outcome, "parsed"); + // the retry prompt names what was missed + assert!(prompts[1].contains("first line"), "{}", prompts[1]); +} + +#[test] +fn a_reply_that_never_has_the_heading_exhausts_with_nothing_approved() { + let (out, a, _) = run(DEMO_V2_GOAL, vec![NO_HEADING.into()]); + assert!(out.unwrap_err().contains("first line")); + assert_eq!(a.len(), COMPOSE_MAX_ATTEMPTS as usize); + assert!(a + .iter() + .all(|x| x.outcome == "refused" && x.aegis.is_none())); +}