aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
GitHub aien-dev/aien-sovereign-core-mv#392 (code only)
Apply it
git checkout -b patch-5686f8b4b6144bcb 65691512aca31b19d6b1cfe1fc9741f648b7db6e curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/5686f8b4b6144bcb.patch | git am
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
392
41993f96587a3be4d959911898b309985382f9bf
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":392,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/392","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:03Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.crumb b/.crumb index 5f34a686..47af2fd4 100644 --- a/.crumb +++ b/.crumb @@ -65,7 +65,7 @@ "children": [ { "digest": "2338fcb7d38b8603f52b70ad65751ab7cbcf633956e32fd223f7c40364de9f66", - "last_commit": "b222a2d", + "last_commit": "6569151", "name": "scripts", "purpose": "" }, @@ -77,14 +77,14 @@ } ], "children_root": "sha256:0a9888c4482972fc88ec2b2fd7c1f0a1833e714e49850d47058179b11f0772a1", - "compiled_at": "2026-10-10T15:01:02Z", + "compiled_at": "2026-10-10T15:10:37Z", "compiler": "crumb-compile/1", - "digest": "sha256:9eda446dbec5df7f5d43ef36b9c4b19e9127b70ed3dea46cec42b9c07c379040", + "digest": "sha256:8dd4cf803754d22be5554e67ecf361c4804f7f66acc5bb09a9dc211782f363e4", "evidence_files": 187, "evidence_root": "sha256:27ee0353cb4d4aae2b7dbce2bfe0d9f4ef2a94cd7a4555b84684d59372503280", - "files": 2166, - "generated_at_commit": "25cb4f62ba701ea5800d69e690beb69082cd7bf7", - "source_tree": "sha256:f820b5c3ee0a07aa34bb804ce36da12049da12ef1bfb058112fccbd42ca03541" + "files": 2168, + "generated_at_commit": "3e86c8010257b46ebacc501a1654b75b19829be4", + "source_tree": "sha256:31acafd6d35b30603634ccb8100e605f0fd588e8f94402e2abea0f3ee412e7eb" } }, "history": [], diff --git a/crates/aien-runtime/src/control.rs b/crates/aien-runtime/src/control.rs index d3d4cde6..79f8c1b7 100644 --- a/crates/aien-runtime/src/control.rs +++ b/crates/aien-runtime/src/control.rs @@ -704,6 +704,29 @@ pub struct ComposeTaskReport { /// ALLEN memory used for this task (arch#159). Old reports have none. #[serde(default)] pub memory: Option<MemoryReport>, + /// Workspace files whose text the proposal prompt carried (sc#382): name + /// relative to the workspace, sha256 and size of the bytes shown. Reading + /// inside the workspace is not an effect; this list is its record. + #[serde(default)] + pub inputs: Vec<InputRef>, + /// Input candidates that were not shown to the model, with the reason. + #[serde(default)] + pub inputs_omitted: Vec<InputOmitted>, +} + +/// One workspace file shown to the model as input (sc#382). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct InputRef { + pub name: String, + pub sha256: String, + pub bytes: usize, +} + +/// An input candidate that was not shown, and why. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct InputOmitted { + pub name: String, + pub reason: String, } /// One proposal the compose "model" Skill made (ACCEPTANCE-v2 3b). diff --git a/crates/aien-runtime/src/destination.rs b/crates/aien-runtime/src/destination.rs index 7e1f1ea6..660882e9 100644 --- a/crates/aien-runtime/src/destination.rs +++ b/crates/aien-runtime/src/destination.rs @@ -330,12 +330,136 @@ fn path_like(w: &str, is_file: &dyn Fn(&str) -> bool) -> bool { ok_chars && (w.contains('/') && has_extension(w) || has_extension(w) || is_file(w)) } +/// What a goal names: the one file to write (resolved into its folder when the +/// goal says "in the Y folder") and the other paths it mentions, in goal order. +/// The other paths are references: material to read, never written. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Named { + pub dest: Option<String>, + pub inputs: Vec<String>, +} + +#[derive(Default)] +struct Parsed { + /// Destination path as written in the goal, and its word index. + dest: Option<(String, usize)>, + others: Vec<String>, +} + +const FOLDER_NOUNS: &[&str] = &["folder", "directory", "dir"]; +const FOLDER_ARTICLES: &[&str] = &["the", "a", "an", "our", "my", "this"]; +/// Plural nouns and verbs that make a folder phrase a place to read from. +const READ_INTENT: &[&str] = &[ + "files", + "documents", + "docs", + "notes", + "texts", + "read", + "reading", + "from", + "about", + "using", + "summarise", + "summarize", + "of", +]; + +/// "in the Y folder" phrases of the goal: (folder name, index of "in"). +fn folder_phrases(raw: &[&str], words: &[String]) -> Vec<(String, usize)> { + let mut out = Vec::new(); + for (i, w) in words.iter().enumerate() { + if !matches!(w.as_str(), "in" | "inside" | "into") { + continue; + } + let mut j = i + 1; + while j < words.len() && FOLDER_ARTICLES.contains(&words[j].as_str()) { + j += 1; + } + if j + 1 >= words.len() || !FOLDER_NOUNS.contains(&words[j + 1].as_str()) { + continue; + } + let name = clean(raw[j]); + let plain = !name.is_empty() + && !name.starts_with('.') + && name + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.')); + if plain { + out.push((name.to_string(), i)); + } + } + out +} + +/// The destination written as "X ... in the Y folder" is `Y/X`. Only a bare +/// name directly followed by the phrase is moved. +fn resolve_in_folder(raw: &[&str], words: &[String], dest: String, idx: usize) -> String { + if dest.contains('/') { + return dest; + } + match folder_phrases(raw, words) + .into_iter() + .find(|(_, at)| *at == idx + 1) + { + Some((folder, _)) => format!("{folder}/{dest}"), + None => dest, + } +} + +/// Every folder the goal names with "the Y folder" (any role), in goal order. +pub fn goal_folders(goal: &str) -> Vec<String> { + let raw: Vec<&str> = goal.split_whitespace().collect(); + let words: Vec<String> = raw.iter().map(|w| clean(w).to_ascii_lowercase()).collect(); + let mut out: Vec<String> = Vec::new(); + for (n, _) in folder_phrases(&raw, &words) { + if !out.contains(&n) { + out.push(n); + } + } + out +} + +/// Folders the goal names as a place to READ from ("the three text files in the +/// inbox folder"): the phrase is not the folder of a file the goal names +/// (the word before "in" is not a path) and a reading word stands within the +/// five words before "in". +pub fn input_folders(goal: &str) -> Vec<String> { + let raw: Vec<&str> = goal.split_whitespace().collect(); + let words: Vec<String> = raw.iter().map(|w| clean(w).to_ascii_lowercase()).collect(); + let mut out: Vec<String> = Vec::new(); + for (n, at) in folder_phrases(&raw, &words) { + let after_path = at > 0 && { + let p = clean(raw[at - 1]); + p.contains('/') || has_extension(p) + }; + let reads = words[at.saturating_sub(5)..at] + .iter() + .any(|w| READ_INTENT.contains(&w.as_str())); + if !after_path && reads && !out.contains(&n) { + out.push(n); + } + } + out +} + /// The destination the goal names. `is_file(w)` says whether the plain /// relative word `w` is an existing file (for extension-less names). pub fn named_destination( goal: &str, is_file: &dyn Fn(&str) -> bool, ) -> Result<Option<String>, DestinationError> { + named_paths(goal, is_file, &|_| false).map(|n| n.dest) +} + +/// The destination and the input paths a goal names. `is_input(w)` says whether +/// the word `w` is an existing workspace file that is material to read: such a +/// name is never taken as a write target when the goal also names a new file. +pub fn named_paths( + goal: &str, + is_file: &dyn Fn(&str) -> bool, + is_input: &dyn Fn(&str) -> bool, +) -> Result<Named, DestinationError> { let raw: Vec<&str> = goal.split_whitespace().collect(); let words: Vec<String> = raw.iter().map(|w| clean(w).to_ascii_lowercase()).collect(); if let Some(op) = asked_file_op(&raw, &words, is_file) { @@ -344,10 +468,17 @@ pub fn named_destination( // A file-operation word that acts on nothing is subject matter only when // the goal names exactly one file to write; otherwise it is refused as before. let op_word = words.iter().find(|w| FILE_OPS.contains(&w.as_str())); - match (op_word, parse(&raw, &words, is_file)) { - (_, Ok(Some(dest))) => Ok(Some(dest)), + let finish = |p: Parsed| { + let dest = p.dest.map(|(d, i)| resolve_in_folder(&raw, &words, d, i)); + Named { + dest, + inputs: p.others, + } + }; + match (op_word, parse(&raw, &words, is_file, is_input)) { + (_, Ok(p)) if p.dest.is_some() => Ok(finish(p)), (Some(op), _) => Err(DestinationError::Unsupported(op.clone())), - (None, other) => other, + (None, other) => other.map(finish), } } @@ -355,7 +486,8 @@ fn parse( raw: &[&str], words: &[String], is_file: &dyn Fn(&str) -> bool, -) -> Result<Option<String>, DestinationError> { + is_input: &dyn Fn(&str) -> bool, +) -> Result<Parsed, DestinationError> { let mut cands: Vec<Cand> = Vec::new(); let mut verb_since_last = false; let mut first_verb: Option<usize> = None; @@ -433,9 +565,16 @@ fn parse( if demote { dests.retain(|c| !c.existing); } + // A name that already exists in the workspace and is not governed by a + // destination verb is material to read, never a write target, when another + // candidate remains that does not exist (the new file the goal asks for). + let input_like = |c: &Cand| !c.governed && is_input(&c.path); + if dests.iter().any(|c| !input_like(c) && !is_input(&c.path)) { + dests.retain(|c| !input_like(c)); + } let Some(first) = dests.first() else { if cands.is_empty() { - return Ok(None); + return Ok(Parsed::default()); } let mut names: Vec<String> = Vec::new(); for c in &cands { @@ -460,7 +599,16 @@ fn parse( } } } - Ok(Some(first.path.clone())) + let mut others: Vec<String> = Vec::new(); + for c in &cands { + if c.path != first.path && !others.contains(&c.path) { + others.push(c.path.clone()); + } + } + Ok(Parsed { + dest: Some((first.path.clone(), first.idx)), + others, + }) } #[cfg(test)] diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index f0aefb3d..3f724358 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -516,7 +516,7 @@ fn branch_sampling_params(config: &SwarmConfig) -> SamplingParams { use crate::control::{ ComposeNoteReport, ComposeRecallReport, ComposeRecordView, ComposeRecoverReport, - ComposeTaskReport, ProposalAttempt, + ComposeTaskReport, InputOmitted, InputRef, ProposalAttempt, }; use crate::cortex_mark::{self, Mark, MarkRefusal, Plan}; use aien_omega_compose::{hex, note_bytes, Compose, ComposeError, NoteKind, RootKind}; @@ -1196,19 +1196,188 @@ pub fn classify_target(goal: &str, ws: &Path) -> TargetClass { /// names none). This is the single decision of a task: the prompt, the budget, /// the merge target and the check of the reply's `filename:` all use it. pub fn classify_destination(goal: &str, ws: &Path) -> (TargetClass, Option<String>) { + let (class, dest, _) = classify_with_inputs(goal, ws); + (class, dest) +} + +/// Directories of the workspace the goal points at: every "Y folder" phrase and +/// every directory name used as a modifier ("the three inbox files"). +fn goal_dirs(goal: &str, ws: &Path) -> Vec<String> { + const NOUNS: &[&str] = &["files", "documents", "docs", "notes", "texts"]; + let mut out = crate::destination::goal_folders(goal); + let ws_words: Vec<&str> = goal.split_whitespace().collect(); + for pair in ws_words.windows(2) { + let trim = |c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '-'; + let (w, next) = (pair[0].trim_matches(trim), pair[1].trim_matches(trim)); + if !w.is_empty() + && NOUNS.contains(&next.to_ascii_lowercase().as_str()) + && !out.iter().any(|o| o == w) + && ws.join(w).is_dir() + { + out.push(w.to_string()); + } + } + out +} + +/// Where a named input word lives in the workspace: the word itself, else the +/// same name inside a directory the goal points at. None when it does not exist. +fn locate_input(word: &str, ws: &Path, dirs: &[String]) -> Option<String> { + let exists = |p: &str| std::fs::symlink_metadata(ws.join(p)).is_ok(); + if exists(word) { + return Some(word.to_string()); + } + if word.contains('/') { + return None; + } + dirs.iter() + .map(|d| format!("{d}/{word}")) + .find(|p| exists(p)) +} + +/// `classify_destination` plus the other paths the goal names (inputs, as the +/// goal wrote them). A name that exists in the workspace and is not the named +/// destination is an input, never a write target (sc#383). +fn classify_with_inputs(goal: &str, ws: &Path) -> (TargetClass, Option<String>, Vec<String>) { let Ok(ws) = std::fs::canonicalize(ws) else { - return (TargetClass::New, None); + return (TargetClass::New, None, Vec::new()); }; let is_file = |w: &str| { check_relative_path(w).is_ok() && std::fs::metadata(ws.join(w)).is_ok_and(|m| m.is_file()) }; - let w = match crate::destination::named_destination(goal, &is_file) { - Ok(Some(w)) => w, - Ok(None) => return (TargetClass::New, None), - Err(e) => return (TargetClass::Refused(format!("{e}")), None), + let dirs = goal_dirs(goal, &ws); + let is_input = |w: &str| { + check_relative_path(w).is_ok() && locate_input(w, &ws, &dirs).is_some_and(|p| is_file(&p)) + }; + let n = match crate::destination::named_paths(goal, &is_file, &is_input) { + Ok(n) => n, + Err(e) => return (TargetClass::Refused(format!("{e}")), None, Vec::new()), + }; + let Some(w) = n.dest else { + return (TargetClass::New, None, n.inputs); }; let class = classify_named(&w, &ws); - (class, Some(w)) + (class, Some(w), n.inputs) +} + +/// Input files for the prompt (sc#382): the paths the goal reads, plus the +/// regular files directly inside a folder the goal reads from. All resolved +/// strictly inside the canonical workspace, UTF-8 only, sorted by name, bounded +/// by `COMPOSE_INPUTS_MAX_FILES` and `COMPOSE_INPUTS_MAX_BYTES`. Returns the +/// prompt block ("" when nothing is shown), what was shown and what was left +/// out. A named input that leaves the workspace is refused. Never writes. +fn gather_inputs( + goal: &str, + ws: &Path, + named: &[String], + dest: Option<&str>, +) -> Result<(String, Vec<InputRef>, Vec<InputOmitted>), String> { + let none = (String::new(), Vec::new(), Vec::new()); + let Ok(ws) = std::fs::canonicalize(ws) else { + return Ok(none); + }; + let dirs = goal_dirs(goal, &ws); + let mut omitted: Vec<InputOmitted> = Vec::new(); + let mut cands: Vec<String> = Vec::new(); + let refuse = |w: &str, why: &str| format!("RunComposeTask: input {w} {why}; refusing"); + for w in named { + if check_relative_path(w).is_err() { + return Err(refuse( + w, + "is not a plain relative path inside the workspace", + )); + } + let Some(rel) = locate_input(w, &ws, &dirs) else { + continue; // does not exist: nothing to read, as before + }; + match std::fs::canonicalize(ws.join(&rel)) { + Ok(full) if full.starts_with(&ws) => { + if full.is_file() && Some(rel.as_str()) != dest && !cands.contains(&rel) { + cands.push(rel); + } + } + _ => return Err(refuse(w, "resolves outside the workspace")), + } + } + for d in crate::destination::input_folders(goal) { + let Ok(full) = std::fs::canonicalize(ws.join(&d)) else { + continue; + }; + if check_relative_path(&d).is_err() || !full.starts_with(&ws) || !full.is_dir() { + continue; + } + let Ok(rd) = std::fs::read_dir(&full) else { + continue; + }; + for e in rd.flatten() { + let rel = format!("{d}/{}", e.file_name().to_string_lossy()); + let ft = e.file_type(); + if ft.as_ref().is_ok_and(|t| t.is_file()) { + if Some(rel.as_str()) != dest && !cands.contains(&rel) { + cands.push(rel); + } + } else if ft.is_ok_and(|t| t.is_symlink()) { + omitted.push(InputOmitted { + name: rel, + reason: "symlink, not followed".into(), + }); + } + } + } + cands.sort(); + let mut included: Vec<InputRef> = Vec::new(); + let mut block = String::new(); + let mut used = 0usize; + for rel in cands { + let skip = |reason: String| InputOmitted { + name: rel.clone(), + reason, + }; + if included.len() >= COMPOSE_INPUTS_MAX_FILES { + omitted.push(skip(format!( + "over the {COMPOSE_INPUTS_MAX_FILES}-file input limit" + ))); + continue; + } + let Ok(meta) = std::fs::metadata(ws.join(&rel)) else { + omitted.push(skip("unreadable".into())); + continue; + }; + if meta.len() as usize > COMPOSE_INPUTS_MAX_BYTES - used { + omitted.push(skip(format!( + "{} bytes does not fit the {COMPOSE_INPUTS_MAX_BYTES}-byte input limit", + meta.len() + ))); + continue; + } + let Ok(bytes) = std::fs::read(ws.join(&rel)) else { + omitted.push(skip("unreadable".into())); + continue; + }; + let Ok(text) = String::from_utf8(bytes) else { + omitted.push(skip("not UTF-8 text".into())); + continue; + }; + if text.len() > COMPOSE_INPUTS_MAX_BYTES - used { + omitted.push(skip("does not fit the input byte limit".into())); + continue; + } + used += text.len(); + let nl = if text.ends_with('\n') { "" } else { "\n" }; + block.push_str(&format!("--- {rel} ---\n{text}{nl}--- end {rel} ---\n")); + included.push(InputRef { + sha256: hex(&Sha256::digest(text.as_bytes())), + bytes: text.len(), + name: rel, + }); + } + omitted.sort_by(|a, b| a.name.cmp(&b.name)); + if !block.is_empty() { + block = format!( + "\nInput files from the workspace (read only, material for the answer, not files to write):\n{block}" + ); + } + Ok((block, included, omitted)) } fn classify_named(w: &str, ws: &Path) -> TargetClass { @@ -1325,24 +1494,49 @@ pub fn task_plan(goal: &str, ws: &Path) -> Result<TaskPrompt, String> { /// none). The one decision of a task: a reply whose `filename:` differs from /// the destination is refused by the Skill. pub fn task_decision(goal: &str, ws: &Path) -> Result<(TaskPrompt, Option<String>), String> { + task_decision_with_inputs(goal, ws).map(|(plan, dest, _, _)| (plan, dest)) +} + +/// A task decision with the inputs its prompt carries and the candidates left out. +pub type TaskDecisionInputs = (TaskPrompt, Option<String>, Vec<InputRef>, Vec<InputOmitted>); + +/// `task_decision` plus the inputs its prompt carries and the candidates left +/// out (sc#382). The prompt is the fixed template, the input block when the +/// goal points at workspace files to read, then the edit or new-document block. +pub fn task_decision_with_inputs(goal: &str, ws: &Path) -> Result<TaskDecisionInputs, String> { let mut prompt = proposal_prompt(goal, &ws.display().to_string()); - let (class, dest) = classify_destination(goal, ws); + let (class, dest, named) = classify_with_inputs(goal, ws); let kind = class.kind(); + if let TargetClass::Refused(why) = class { + return Err(format!("RunComposeTask: {why}")); + } + let (block, included, omitted) = gather_inputs(goal, ws, &named, dest.as_deref())?; + prompt.push_str(&block); match class { - TargetClass::Refused(why) => Err(format!("RunComposeTask: {why}")), + TargetClass::Refused(_) => unreachable!("refused above"), TargetClass::Edit(path, content) => { prompt.push_str(&edit_block(&path, &content)); - Ok(((prompt, Some((path, content)), kind), dest)) + Ok(( + (prompt, Some((path, content)), kind), + dest, + included, + omitted, + )) } TargetClass::New => { if let Some(d) = &dest { prompt.push_str(&new_document_block(d)); } - Ok(((prompt, None, kind), dest)) + Ok(((prompt, None, kind), dest, included, omitted)) } } } +/// Total bytes of input text a proposal prompt carries (sc#382). +pub const COMPOSE_INPUTS_MAX_BYTES: usize = 16384; +/// Most input files a proposal prompt carries (sc#382). +pub const COMPOSE_INPUTS_MAX_FILES: usize = 16; + /// Largest prior-lines x reply-lines table `merge_edit_reply` builds. pub const COMPOSE_EDIT_MERGE_MAX_CELLS: usize = 4 << 20; @@ -2167,7 +2361,7 @@ impl ComposeBridge { ws.display() )); } - let (mut plan, dest) = task_decision(goal, &ws)?; + let (mut plan, dest, inputs, inputs_omitted) = task_decision_with_inputs(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 machine_goal = @@ -2347,6 +2541,8 @@ impl ComposeBridge { }, persona, memory, + inputs, + inputs_omitted, }) } @@ -2990,3 +3186,20 @@ mod new_document_overwrite_tests { assert!(run(Some("README.md"), "README.md", true).is_ok()); } } + +#[cfg(test)] +mod folder_destination_enforcement_tests { + use super::*; + + #[test] + fn proposal_in_the_folder_is_accepted_for_ctrl_goal() { + let tmp = tempfile::tempdir().unwrap(); + std::fs::create_dir(tmp.path().join("outbox")).unwrap(); + let ws = std::fs::canonicalize(tmp.path()).unwrap(); + let goal = "Write a file named ctrl.md in the outbox folder containing one line: control."; + let dest = task_decision(goal, &ws).unwrap().1; + let t = "filename: outbox/ctrl.md\ncontrol\n".to_string(); + let r = enforce_destination((Ok(t.clone()), vec![]), dest.as_deref(), &ws, false).0; + assert_eq!(r, Ok(t)); + } +} diff --git a/crates/aien-runtime/tests/allen_persona_test.rs b/crates/aien-runtime/tests/allen_persona_test.rs index 1aea764a..0a22d586 100644 --- a/crates/aien-runtime/tests/allen_persona_test.rs +++ b/crates/aien-runtime/tests/allen_persona_test.rs @@ -379,6 +379,8 @@ fn old_reports_without_persona_still_parse() { reason: None, }), memory: None, + inputs: vec![], + inputs_omitted: vec![], }; let mut v = serde_json::to_value(&report).unwrap(); assert_eq!(v["persona"]["display_name"], "Nova"); diff --git a/crates/aien-runtime/tests/inputs_test.rs b/crates/aien-runtime/tests/inputs_test.rs new file mode 100644 index 00000000..f334aef3 --- /dev/null +++ b/crates/aien-runtime/tests/inputs_test.rs @@ -0,0 +1,293 @@ +//! sc#382 and sc#383 items 2 and 3 (WHOLE-SYSTEM-E2E, arch#190): input files the +//! goal points at are shown to the model and never written, and "named X in the +//! Y folder" resolves to `Y/X`. Pre-registered in +//! `docs/campaigns/whole-system-e2e/REGRESSION-sc382-sc383.md`. +#[path = "support/home_guard.rs"] +mod home_guard; + +use aien_runtime::control::ControlResponse; +use aien_runtime::spine::{ + task_decision, task_decision_with_inputs, ComposeBridge, ComposeProposer, Generation, + COMPOSE_INPUTS_MAX_BYTES, +}; +use sha2::{Digest, Sha256}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +// The three objective texts of scripts/whole_system_e2e.sh, verbatim. +const OBJ: &str = "Read the three text files in the inbox folder and write a Markdown report named report.md in the outbox folder. Start with a Markdown heading line that begins with \"# \". Use at most 200 words. Mention each file by name."; +const OBJ6: &str = "Write a file named done.md in the outbox folder containing one line: finished."; +const OBJC: &str = "Write a file named ctrl.md in the outbox folder containing one line: control."; +// The first mechanics objective of harness v1 (sc#383 item 2). +const OBJ_NAMED: &str = "Write a Markdown report named report.md about the three inbox files named harbour-notes.txt, orchard-ledger.txt and windmill-log.txt. Start with a Markdown heading line that begins with \"# \". Use at most 200 words. Mention each file by name."; + +const FILES: [(&str, &str); 3] = [ + ( + "harbour-notes.txt", + "Harbour notes. Three boats came in before noon.\n", + ), + ("orchard-ledger.txt", "Orchard ledger. Forty apple trees.\n"), + ( + "windmill-log.txt", + "Windmill log. The brake band was replaced.\n", + ), +]; + +fn ws_with_inbox() -> (tempfile::TempDir, PathBuf) { + let d = tempfile::tempdir().unwrap(); + let ws = d.path().join("ws"); + std::fs::create_dir_all(ws.join("inbox")).unwrap(); + std::fs::create_dir_all(ws.join("outbox")).unwrap(); + // Written out of order on purpose: the order must come from the names. + for (n, c) in FILES.iter().rev() { + std::fs::write(ws.join("inbox").join(n), c).unwrap(); + } + let ws = std::fs::canonicalize(ws).unwrap(); + (d, ws) +} + +fn sha(s: &str) -> String { + Sha256::digest(s.as_bytes()) + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +fn dest_of(goal: &str, ws: &Path) -> Option<String> { + task_decision(goal, ws).unwrap().1 +} + +#[test] +fn folder_phrase_resolves_done_ctrl_and_report_destinations() { + let (_d, ws) = ws_with_inbox(); + assert_eq!(dest_of(OBJ6, &ws).as_deref(), Some("outbox/done.md")); + assert_eq!(dest_of(OBJC, &ws).as_deref(), Some("outbox/ctrl.md")); + assert_eq!(dest_of(OBJ, &ws).as_deref(), Some("outbox/report.md")); + // The model is shown the resolved path. + let ((prompt, _, _), _) = task_decision(OBJC, &ws).unwrap(); + assert!(prompt.contains("filename: outbox/ctrl.md"), "{prompt}"); +} + +#[test] +fn folder_phrase_works_without_the_article_and_for_directory() { + let (_d, ws) = ws_with_inbox(); + assert_eq!( + dest_of( + "Write a file named a.md in outbox folder containing x.", + &ws + ) + .as_deref(), + Some("outbox/a.md") + ); + assert_eq!( + dest_of( + "Write a file named b.md in the outbox directory containing x.", + &ws + ) + .as_deref(), + Some("outbox/b.md") + ); +} + +#[test] +fn input_names_are_not_write_targets() { + let (_d, ws) = ws_with_inbox(); + let (_, dest, _, _) = task_decision_with_inputs(OBJ_NAMED, &ws).unwrap(); + assert_eq!(dest.as_deref(), Some("report.md")); +} + +#[test] +fn two_distinct_write_targets_stay_ambiguous() { + let (_d, ws) = ws_with_inbox(); + let e = task_decision("Create alpha.md and beta.md about the weather.", &ws).unwrap_err(); + assert!(e.contains("ambiguous destination"), "{e}"); + // A name that does not exist is not an input: two new files are still two targets. + let e = task_decision( + "Write a report named one.md and write another named two.md about the inbox folder.", + &ws, + ) + .unwrap_err(); + assert!(e.contains("ambiguous destination"), "{e}"); +} + +#[test] +fn existing_destination_is_still_an_edit() { + let (_d, ws) = ws_with_inbox(); + std::fs::write(ws.join("README.md"), "# r\n").unwrap(); + let ((prompt, target, _), dest) = task_decision("Append a line to README.md", &ws).unwrap(); + assert_eq!(dest.as_deref(), Some("README.md")); + assert!(target.is_some() && prompt.contains("already exists")); +} + +#[test] +fn folder_source_phrase_includes_inputs_sorted_with_digests() { + let (_d, ws) = ws_with_inbox(); + let (((prompt, _, _), dest), inputs, omitted) = { + let (p, d, i, o) = task_decision_with_inputs(OBJ, &ws).unwrap(); + ((p, d), i, o) + }; + assert_eq!(dest.as_deref(), Some("outbox/report.md")); + assert!(omitted.is_empty(), "{omitted:?}"); + let names: Vec<&str> = inputs.iter().map(|i| i.name.as_str()).collect(); + assert_eq!( + names, + [ + "inbox/harbour-notes.txt", + "inbox/orchard-ledger.txt", + "inbox/windmill-log.txt" + ] + ); + let mut at = 0; + for ((n, c), i) in FILES.iter().zip(&inputs) { + assert_eq!((i.sha256.clone(), i.bytes), (sha(c), c.len())); + let p = prompt[at..] + .find(c) + .unwrap_or_else(|| panic!("{n} missing: {prompt}")); + at += p; + assert!(prompt.contains(&format!("inbox/{n}"))); + } + // The inputs are not the file to write. + assert!(prompt.contains("filename: outbox/report.md")); +} + +#[test] +fn named_files_become_inputs_but_destination_is_not() { + let (_d, ws) = ws_with_inbox(); + // The goal names the files bare and says where they live. + let goal = "Write a Markdown report named report.md in the outbox folder about harbour-notes.txt, orchard-ledger.txt and windmill-log.txt in the inbox folder."; + let (((prompt, _, _), dest), inputs, _) = { + let (p, d, i, o) = task_decision_with_inputs(goal, &ws).unwrap(); + ((p, d), i, o) + }; + assert_eq!(dest.as_deref(), Some("outbox/report.md")); + assert_eq!(inputs.len(), 3, "{inputs:?}"); + assert!(prompt.contains("Windmill log. The brake band was replaced.")); + // A bare name that exists at the workspace root is an input too. + std::fs::write(ws.join("facts.txt"), "Fact one.\n").unwrap(); + let (_, dest, inputs, _) = + task_decision_with_inputs("Write summary.md based on the notes named facts.txt", &ws) + .unwrap(); + assert_eq!(dest.as_deref(), Some("summary.md")); + assert_eq!( + inputs.iter().map(|i| i.name.as_str()).collect::<Vec<_>>(), + ["facts.txt"] + ); +} + +#[test] +fn inputs_are_capped_and_omissions_are_listed() { + let (_d, ws) = ws_with_inbox(); + let big = "x".repeat(COMPOSE_INPUTS_MAX_BYTES / 2 + 1); + std::fs::write(ws.join("inbox").join("big1.txt"), &big).unwrap(); + std::fs::write(ws.join("inbox").join("big2.txt"), &big).unwrap(); + let (_, _, inputs, omitted) = task_decision_with_inputs(OBJ, &ws).unwrap(); + let total: usize = inputs.iter().map(|i| i.bytes).sum(); + assert!(total <= COMPOSE_INPUTS_MAX_BYTES, "{total}"); + assert!(inputs.iter().any(|i| i.name == "inbox/big1.txt")); + assert!( + omitted.iter().any(|o| o.name == "inbox/big2.txt"), + "{omitted:?}" + ); + // Deterministic: the same goal gives the same lists. + let again = task_decision_with_inputs(OBJ, &ws).unwrap(); + assert_eq!((again.2, again.3), (inputs, omitted)); +} + +#[test] +fn non_utf8_and_non_regular_inputs_are_omitted_not_read() { + let (_d, ws) = ws_with_inbox(); + std::fs::write(ws.join("inbox").join("bin.dat"), [0xff, 0xfe, 0x00]).unwrap(); + std::fs::create_dir(ws.join("inbox").join("sub")).unwrap(); + let out = tempfile::tempdir().unwrap(); + std::fs::write(out.path().join("secret.txt"), "TOPSECRET").unwrap(); + std::os::unix::fs::symlink( + out.path().join("secret.txt"), + ws.join("inbox").join("leak.txt"), + ) + .unwrap(); + let ((prompt, _, _), _, inputs, omitted) = task_decision_with_inputs(OBJ, &ws).unwrap(); + assert!(!prompt.contains("TOPSECRET")); + assert!(inputs + .iter() + .all(|i| i.name != "inbox/bin.dat" && i.name != "inbox/leak.txt")); + for n in ["inbox/bin.dat", "inbox/leak.txt"] { + assert!(omitted.iter().any(|o| o.name == n), "{n}: {omitted:?}"); + } +} + +#[test] +fn named_input_escaping_workspace_is_refused_before_model() { + let (d, ws) = ws_with_inbox(); + std::fs::write(d.path().join("outside.txt"), "TOPSECRET").unwrap(); + std::os::unix::fs::symlink(d.path().join("outside.txt"), ws.join("link.txt")).unwrap(); + for goal in [ + "Write report.md about ../outside.txt", + "Write report.md about /etc/hostname", + "Write report.md about link.txt", + ] { + let e = task_decision_with_inputs(goal, &ws).unwrap_err(); + assert!( + e.contains("RunComposeTask") && e.contains("input"), + "{goal}: {e}" + ); + } +} + +#[test] +fn goal_without_inputs_keeps_prompt_byte_for_byte() { + let (_d, ws) = ws_with_inbox(); + let goal = "Write a file named notes.md containing one line: hello."; + let a = task_decision(goal, &ws).unwrap(); + let b = task_decision_with_inputs(goal, &ws).unwrap(); + assert_eq!(a.0, b.0); + assert!(b.2.is_empty() && b.3.is_empty()); + assert!(!a.0 .0.contains("Input files")); + let w = ws.display().to_string(); + let want = format!( + "{}{}", + aien_runtime::spine::proposal_prompt(goal, &w), + aien_runtime::spine::new_document_block("notes.md") + ); + assert_eq!(a.0 .0, want); +} + +fn scripted(seen: Arc<std::sync::Mutex<String>>) -> ComposeProposer { + Arc::new(move |prompt: &str, _l: std::time::Duration| { + *seen.lock().unwrap() = prompt.to_string(); + Ok(Generation { + text: "filename: outbox/report.md\n# Report\nharbour-notes.txt, orchard-ledger.txt, windmill-log.txt\n".into(), + tokens: 9, + finish_reason: None, + ..Default::default() + }) + }) +} + +#[test] +fn compose_propose_report_lists_inputs_with_digests() { + let _home = home_guard::home_slot(); + let (d, ws) = ws_with_inbox(); + let seen = Arc::new(std::sync::Mutex::new(String::new())); + let bridge = ComposeBridge::new( + d.path().join("compose"), + scripted(seen.clone()), + "test:scripted", + ); + let resp = bridge.run_task(OBJ, ws.to_str().unwrap()); + if !aien_omega_compose::LINKED { + match resp { + ControlResponse::Error(e) => assert!(e.contains("not linked"), "{e}"), + other => panic!("stub build must refuse, got {other:?}"), + } + return; + } + let ControlResponse::ComposeTaskResult(r) = resp else { + panic!("{resp:?}") + }; + assert!(seen.lock().unwrap().contains("Windmill log.")); + assert_eq!(r.inputs.len(), 3); + for ((n, c), i) in FILES.iter().zip(&r.inputs) { + assert_eq!(i.name, format!("inbox/{n}")); + assert_eq!(i.sha256, sha(c)); + } +} diff --git a/docs/campaigns/whole-system-e2e/REGRESSION-sc382-sc383.md b/docs/campaigns/whole-system-e2e/REGRESSION-sc382-sc383.md new file mode 100644 index 00000000..c2738519 --- /dev/null +++ b/docs/campaigns/whole-system-e2e/REGRESSION-sc382-sc383.md @@ -0,0 +1,77 @@ +# Regression pre-registration: sc#382 (inputs unreadable) and sc#383 items 2 and 3 (destination) + +Written before any test or fix. Program: aien-architecture#190. Branch `e2e/w1-input-reading`. +Evidence is under `runs/` and is not edited. + +## Failing behaviour on main, as observed + +1. sc#382. `RUN-1-dry-20261010T134202Z/artifacts/E3-propose.json`: for the contract objective the model + invented `ws-contract.txt` and `ws-contract.md` because the prompt carries only the goal text and the + workspace path. The three inbox files are never shown to the model. +2. sc#383 item 2. `RUN-1-dry-20261010T133749Z/artifacts/E3m-propose.json`: the goal "Write a Markdown report + named report.md about the three inbox files named harbour-notes.txt, orchard-ledger.txt and + windmill-log.txt ..." was refused: `ambiguous destination: the goal names several files to write + (report.md, harbour-notes.txt, orchard-ledger.txt, windmill-log.txt); name one`. +3. sc#383 item 3. `RUN-1-dry-20261010T134202Z/artifacts/CTRL-E3b-propose.json`: goal "Write a file named ctrl.md + in the outbox folder containing one line: control." was refused because the proposal wrote + `outbox/ctrl.md` but the goal-named destination was `ctrl.md`. + +## Design (constants, no new knobs) + +- Destination: "named X in the Y folder" (also "in Y folder", "in the Y directory") resolves to `Y/X` before the + model runs. The proposal filename line, the destination check and the written path all use `Y/X`. +- Inputs: paths the goal references but does not write. A bare name that exists in the workspace (or in a + folder the goal names with "the Y folder") and is not the destination is an input. A folder named as a + source ("files in the inbox folder") contributes its regular files, directly inside it, sorted by name. +- Bounds: `COMPOSE_INPUTS_MAX_BYTES` = 16384 total, `COMPOSE_INPUTS_MAX_FILES` = 16. Files are taken in + sorted order; a file that does not fit whole, a non-UTF-8 file or a non-regular entry is not included and + is listed under `inputs_omitted` with the reason. Never truncated silently. +- Confinement: a named input outside the workspace (absolute, `~`, `..`, or a symlink resolving outside) is + refused before the model runs. Folder entries that are symlinks leaving the workspace are omitted. +- Report: `compose propose` report gains `inputs` (name, sha256, bytes) and `inputs_omitted` (name, reason), + both default empty so old reports still parse. + +## Tests to add + +Unit and integration tests in `crates/aien-runtime/tests/inputs_test.rs` (new), plus a stub-aware +`compose propose` test in the same file. + +| Test | On main | After fix | +|---|---|---| +| folder_phrase_resolves_done_ctrl_and_report_destinations (OBJ6, OBJC, OBJ texts) | FAIL | PASS | +| proposal_in_the_folder_is_accepted_for_ctrl_goal (`outbox/ctrl.md` reply accepted) | FAIL | PASS | +| input_names_are_not_write_targets (sc#383 item 2 text, files exist) | FAIL | PASS | +| two_distinct_write_targets_stay_ambiguous (negative control) | PASS | PASS | +| existing_destination_is_still_an_edit (negative control) | PASS | PASS | +| folder_source_phrase_includes_inputs_sorted_with_digests (OBJ, three inbox files) | FAIL | PASS | +| named_files_become_inputs_but_destination_is_not (item 2 text) | FAIL | PASS | +| inputs_are_capped_and_omissions_are_listed | FAIL | PASS | +| non_utf8_and_non_regular_inputs_are_omitted_not_read | FAIL | PASS | +| named_input_escaping_workspace_is_refused_before_model (`..`, absolute, symlink) | FAIL | PASS | +| goal_without_inputs_keeps_prompt_byte_for_byte (negative control) | PASS | PASS | +| compose_propose_report_lists_inputs_with_digests (stub-aware) | FAIL | PASS | + +The tests commit adds only empty-returning stubs of the new API so the tests compile; a FAIL is an assertion +failure, not a compile error. + +## Must not change + +Desk requirement, grants, effect boundary refusals, `AlreadySpent`, requirement phrasing rules, the refusal +for two genuinely distinct write targets, the destination-probe corpus record +(`destination_corpus_test`), the model, token budgets, memory and ALLEN code, the harness script. + +## Limits (stated now) + +Input text is untrusted prompt content, the same as edit-mode content today. Folder reading is one level +deep. Reading only happens when the goal names the source; the model cannot ask for files. + +## Notes added with the fix (rows above unchanged) + +- `compose_propose_report_lists_inputs_with_digests` passes on a stub build before and after the fix, because + the stub refuses every run ("not linked"). The registered FAIL-before holds only with the linked compose + library; the assertions on `inputs` are exercised by CI's linked job. The same facts are asserted without + the library by `folder_source_phrase_includes_inputs_sorted_with_digests`, which failed before. +- Inputs found by a directory word: a goal word naming a top-level workspace directory counts only when a + plural noun follows it ("the three inbox files"), so "about docs and plan.txt" keeps its v5 prompt. +- A folder is read as input only when the goal puts a reading word (files, notes, from, about, ...) within + five words before "in the Y folder" and the phrase does not directly follow a named path.