diff --git a/.crumb b/.crumb index fd0db261..91e8f069 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:c5269f93385287c09996ff41f0247f72de9237a2317f47c94c51273d6a0acef1", - "compiled_at": "2026-10-07T21:22:43Z", + "compiled_at": "2026-10-07T22:16:47Z", "compiler": "crumb-compile/1", - "digest": "sha256:75e041a194612f5809fd25b39925ed0424a6acd3e53ae2641a38d4a95886958e", + "digest": "sha256:13e4b128a6a9660899f874a62d5311172a09e30bc5965ec4c5eb04e79960abf1", "evidence_files": 186, "evidence_root": "sha256:fbe849218d18dc4b21a74410fdd8f7d98431a1d0123a0c69264386f770da4db4", - "files": 1302, - "generated_at_commit": "2bf56d0f98ede765e6c83c226a9af7727a6628b5", - "source_tree": "sha256:daa2cb1b706f0695a8edc532f353c0965e8ade49bb18526eb263f90000a3779f" + "files": 1304, + "generated_at_commit": "a7533566439ec4cc6745f872b49f1906bc6b21a2", + "source_tree": "sha256:7fa9e5efcec034e5ff6f7b272cfc5e2952f2196e1a3c60a6977b2de1c8874e92" } }, "history": [], diff --git a/crates/aien-runtime/src/destination.rs b/crates/aien-runtime/src/destination.rs new file mode 100644 index 00000000..780b3d77 --- /dev/null +++ b/crates/aien-runtime/src/destination.rs @@ -0,0 +1,450 @@ +//! Which path does a compose goal ask to WRITE? (issue #288) +//! +//! A goal mentions paths in two roles: the DESTINATION (the file the task +//! creates or changes) and SOURCES (material it reads: "about README.md"). +//! Only the destination decides the task kind, the budget, the prompt and the +//! merge. This module is a small rule-based parser with two tables: +//! +//! * `DESTINATION_VERBS`: a verb that introduces the destination ("create", +//! "update", "append", "save", ...). The first path after it is the target. +//! * `SOURCE_MARKERS`: a word that marks the next path as source material +//! ("about", "from", "using", "based on", "summarising", ...). Paths joined +//! to a source by "and" or a comma are sources too. +//! +//! Rules, in order: +//! 1. A path-like word is one with a `/`, a file extension, or a name that +//! exists as a file (`Makefile`). Absolute, `~` and `..` paths are path-like +//! and unsafe. +//! 2. Paths marked as sources are set aside. +//! 3. No destination left: `Ok(None)` (a new document, the model names it). +//! 4. One destination: it. +//! 5. Several destinations: the first is taken only when a destination verb +//! comes before it and no later path is joined to it by "and"/"," or +//! introduced by a second destination verb. Otherwise `Err(Ambiguous)` +//! naming every candidate. Never a silent pick. +//! +//! The words of a goal are untrusted text; nothing here touches the disk +//! except through the `is_file` callback. + +/// Verbs that introduce the destination of a task. +pub const DESTINATION_VERBS: &[&str] = &[ + "create", "write", "make", "generate", "produce", "draft", "compose", "update", "edit", + "modify", "append", "add", "insert", "rewrite", "change", "fix", "extend", "revise", "save", + "put", "store", "place", "prepend", "replace", +]; + +/// Words that mark the path after them as source material. +pub const SOURCE_MARKERS: &[&str] = &[ + "about", + "from", + "using", + "use", + "of", + "reading", + "read", + "summarising", + "summarizing", + "summarise", + "summarize", + "describing", + "covering", + "per", + "following", + "reference", + "referencing", + "given", +]; + +/// Words that may sit between a destination verb and the path it governs +/// ("Edit the given README.md"): a verb reaching the path through these wins +/// over a source marker. +pub const FILLERS: &[&str] = &[ + "the", + "a", + "an", + "this", + "that", + "my", + "our", + "your", + "file", + "document", + "doc", + "new", + "existing", + "given", + "reference", + "referenced", + "called", + "named", + "same", + "current", +]; + +/// Nouns that place a position INSIDE a file: in "the end of X" or "the Intro +/// section of X", the word "of" points at the file being changed, so it is not +/// a source marker. Other "of" phrases ("summary of X", "list of X", "copy of +/// X") still mark X as material to read. +pub const LOCATIONAL: &[&str] = &[ + "section", + "sections", + "part", + "end", + "top", + "bottom", + "start", + "beginning", + "body", + "contents", + "content", + "heading", + "line", + "lines", + "row", + "block", + "footer", + "header", + "middle", + "rest", + "bit", +]; + +/// Top-level domains that make a bare `name.tld` token a host name, not a file. +pub const HOST_TLDS: &[&str] = &[ + "org", "com", "net", "io", "dev", "edu", "gov", "ai", "co", "app", "me", "info", "xyz", +]; + +/// Words after which a `name.tld` token is a web address. +pub const HOST_LEAD: &[&str] = &["visit", "see", "at", "http", "https", "www", "url", "site"]; + +/// A path-like word of the goal. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Cand { + path: String, + idx: usize, + source: bool, + /// Joined to the previous path-like word by "and", "or" or a comma. + conj: bool, + /// A destination verb stands between the previous path-like word and this one. + verb_before: bool, +} + +/// The destination could not be chosen. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum DestinationError { + /// Several candidate destinations and no rule picks one. + Ambiguous(Vec), + /// The goal only mentions paths as source material; nothing is named to write. + NoDestination(Vec), + /// The goal asks for an operation this parser does not support. + Unsupported(String), +} + +impl std::fmt::Display for DestinationError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::NoDestination(c) => write!( + f, + "no destination named: the goal only mentions {} as material to read; name the file to write", + c.join(", ") + ), + Self::Unsupported(w) => write!(f, "{w} is not supported: name the file to create or edit"), + Self::Ambiguous(c) => write!( + f, + "ambiguous destination: the goal names several files to write ({}); name one", + c.join(", ") + ), + } + } +} + +fn clean(w: &str) -> &str { + const Q: fn(char) -> bool = |c| matches!(c, '"' | '\'' | '`' | '(' | ')' | '[' | ']'); + w.trim_matches(Q) + .trim_end_matches(['.', ',', ';', ':', '!', '?']) + .trim_matches(Q) +} + +fn has_extension(w: &str) -> bool { + let last = w.rsplit('/').next().unwrap_or(w); + match last.rsplit_once('.') { + Some((stem, ext)) => { + !stem.is_empty() + && !ext.is_empty() + && ext.len() <= 10 + && ext.starts_with(|c: char| c.is_ascii_alphabetic()) + && ext.chars().all(|c| c.is_ascii_alphanumeric()) + && !matches!(w, "e.g" | "i.e" | "etc") + && !(ext.len() == 1 && stem.contains('.')) + } + None => false, + } +} + +/// True for a word that names a path, safe or not. +fn path_like(w: &str, is_file: &dyn Fn(&str) -> bool) -> bool { + if w.is_empty() || w.contains('@') || w.contains("://") { + return false; + } + let unsafe_form = + w.starts_with('/') || w.starts_with("~/") || w == "~" || w.split('/').any(|c| c == ".."); + if unsafe_form { + return w.contains('/') || w.starts_with('~'); + } + let ok_chars = w + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '/')); + ok_chars && (w.contains('/') && has_extension(w) || has_extension(w) || is_file(w)) +} + +/// 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, DestinationError> { + let raw: Vec<&str> = goal.split_whitespace().collect(); + let words: Vec = raw.iter().map(|w| clean(w).to_ascii_lowercase()).collect(); + if let Some(v) = words + .iter() + .find(|w| matches!(w.as_str(), "rename" | "move" | "delete" | "remove")) + { + return Err(DestinationError::Unsupported(v.clone())); + } + let mut cands: Vec = Vec::new(); + let mut verb_since_last = false; + let mut first_verb: Option = None; + for (i, w) in raw.iter().enumerate() { + let c = clean(w); + let lw = &words[i]; + if DESTINATION_VERBS.contains(&lw.as_str()) { + verb_since_last = true; + first_verb.get_or_insert(i); + } + if !path_like(c, is_file) { + continue; + } + let governed = { + let mut j = i; + while j > 0 && FILLERS.contains(&words[j - 1].as_str()) { + j -= 1; + } + j > 0 && DESTINATION_VERBS.contains(&words[j - 1].as_str()) + }; + let host_like = !c.contains('/') + && !is_file(c) + && (c + .rsplit('.') + .next() + .is_some_and(|t| HOST_TLDS.contains(&t.to_ascii_lowercase().as_str())) + || (i > 0 && HOST_LEAD.contains(&words[i - 1].as_str()))); + if host_like && !governed { + continue; + } + let prev = (i > 0).then(|| words[i - 1].as_str()); + let prev2 = (i > 1).then(|| words[i - 2].as_str()); + let location_of = prev == Some("of") && prev2.is_some_and(|p| LOCATIONAL.contains(&p)); + let marked = !governed + && (prev.is_some_and(|p| SOURCE_MARKERS.contains(&p) && !location_of) + || (prev == Some("on") && prev2 == Some("based")) + || (prev == Some("on") && prev2 == Some("relying"))); + // Joined to the previous path-like word: "A and B", "A, B", "A or B", "A B". + let joined = cands.last().is_some_and(|l| { + (prev == Some("and") || prev == Some("or") || prev == Some("&")) && l.idx + 2 == i + || l.idx + 1 == i + }); + let source = marked || (joined && cands.last().is_some_and(|l| l.source)); + cands.push(Cand { + path: c.to_string(), + idx: i, + source, + conj: joined, + verb_before: verb_since_last && !cands.is_empty(), + }); + verb_since_last = false; + } + let dests: Vec<&Cand> = cands.iter().filter(|c| !c.source).collect(); + let Some(first) = dests.first() else { + if cands.is_empty() { + return Ok(None); + } + let mut names: Vec = Vec::new(); + for c in &cands { + if !names.contains(&c.path) { + names.push(c.path.clone()); + } + } + return Err(DestinationError::NoDestination(names)); + }; + if dests.len() > 1 { + let verb_leads = first_verb.is_some_and(|v| v < first.idx); + let clash = dests[1..].iter().any(|d| d.conj || d.verb_before); + if !verb_leads || clash { + let mut names: Vec = Vec::new(); + for d in &dests { + if !names.contains(&d.path) { + names.push(d.path.clone()); + } + } + if names.len() > 1 { + return Err(DestinationError::Ambiguous(names)); + } + } + } + Ok(Some(first.path.clone())) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn d(g: &str) -> Result, DestinationError> { + named_destination(g, &|w| w == "Makefile") + } + + #[test] + fn source_is_not_the_destination() { + assert_eq!( + d("Create docs/SUMMARY.md about README.md"), + Ok(Some("docs/SUMMARY.md".into())) + ); + assert_eq!( + d("Update README.md using docs/NOTES.md"), + Ok(Some("README.md".into())) + ); + assert_eq!( + d("Add a summary of README.md and LICENSE to docs/S.md"), + Ok(Some("docs/S.md".into())) + ); + } + + #[test] + fn single_and_extensionless() { + assert_eq!(d("write faq.md"), Ok(Some("faq.md".into()))); + assert_eq!(d("Edit Makefile please"), Ok(Some("Makefile".into()))); + assert_eq!(d("Edit docs now"), Ok(None)); + assert_eq!(d("say hi, e.g. twice"), Ok(None)); + assert_eq!(d("under the ## 0.1.0 heading"), Ok(None)); + } + + #[test] + fn several_destinations_are_ambiguous() { + assert!(matches!( + d("Create a.md and b.md"), + Err(DestinationError::Ambiguous(c)) if c == ["a.md", "b.md"] + )); + assert!(d("Create a.md. Then update b.md").is_err()); + assert!(d("put a.md b.md together").is_err()); + assert_eq!( + d("Edit `docs/plan.txt`, then README.md"), + Ok(Some("docs/plan.txt".into())) + ); + } + + #[test] + fn source_only_goals_name_no_destination() { + for g in [ + "Summarise README.md", + "Summarise README.md and docs/A.md", + "Create a note summarising README.md", + ] { + assert!( + matches!(d(g), Err(DestinationError::NoDestination(_))), + "{g}" + ); + } + let Err(e) = d("Summarise README.md") else { + panic!() + }; + assert!(e.to_string().contains("README.md") && e.to_string().contains("no destination")); + } + + #[test] + fn verb_governing_the_path_beats_a_marker_adjective() { + assert_eq!(d("Edit the given README.md"), Ok(Some("README.md".into()))); + assert_eq!( + d("Update the reference README.md"), + Ok(Some("README.md".into())) + ); + assert_eq!( + d("Create docs/S.md from the given README.md"), + Ok(Some("docs/S.md".into())) + ); + } + + #[test] + fn host_names_are_not_files_unless_governed() { + assert_eq!( + d("Visit example.org and write out.md"), + Ok(Some("out.md".into())) + ); + assert_eq!( + d("See docs.example.com then create out.md"), + Ok(Some("out.md".into())) + ); + assert_eq!(d("Create example.org"), Ok(Some("example.org".into()))); + } + + #[test] + fn of_phrases_resolve_by_what_they_point_at() { + let one = |g: &str| d(g).unwrap().unwrap(); + // A position inside the file being changed: the file is the destination. + for (g, want) in [ + ("Add a line to the Intro section of README.md", "README.md"), + ("Append a note to the end of README.md", "README.md"), + ("Insert a badge at the top of README.md", "README.md"), + ( + "Add \"x\" to the \"## Before a trip\" section of notes/GARAGE.md.", + "notes/GARAGE.md", + ), + ] { + assert_eq!(one(g), want, "{g}"); + } + // Material to read: the file is a source, the destination is named elsewhere. + for (g, want) in [ + ("Write a list of README.md into docs/L.md", "docs/L.md"), + ("Create docs/C.md as a copy of README.md", "docs/C.md"), + ( + "Write a summary of README.md into docs/SUMMARY.md", + "docs/SUMMARY.md", + ), + // Location word in the source role: the later file is not demoted, + // the first file after the verb still wins (documented limit). + ("Create docs/S.md from the top of README.md", "docs/S.md"), + ( + "Create docs/S.md summarising the section of README.md", + "docs/S.md", + ), + ("Create docs/S.md about the end of README.md", "docs/S.md"), + ] { + assert_eq!(one(g), want, "{g}"); + } + for g in [ + "Make a list of README.md", + "Summarise README.md", + "Make a copy of README.md", + ] { + assert!( + matches!(d(g), Err(DestinationError::NoDestination(_))), + "{g}" + ); + } + } + + #[test] + fn rename_is_unsupported() { + assert!( + matches!(d("Rename a.md to b.md"), Err(DestinationError::Unsupported(w)) if w == "rename") + ); + } + + #[test] + fn unsafe_paths_are_named_not_skipped() { + assert_eq!( + d("Create the file ../outside.txt"), + Ok(Some("../outside.txt".into())) + ); + assert_eq!(d("Edit /etc/passwd"), Ok(Some("/etc/passwd".into()))); + assert_eq!(d("Edit ~/secret.txt"), Ok(Some("~/secret.txt".into()))); + } +} diff --git a/crates/aien-runtime/src/lib.rs b/crates/aien-runtime/src/lib.rs index 5ceea682..053d75fe 100644 --- a/crates/aien-runtime/src/lib.rs +++ b/crates/aien-runtime/src/lib.rs @@ -7,6 +7,7 @@ pub mod client; pub mod context; pub mod control; pub mod cortex_mark; +pub mod destination; pub mod effects; pub mod requirements; pub mod rsi; diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index 46585d0a..a9ecdbd1 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -1068,12 +1068,12 @@ pub fn proposal_prompt(goal: &str, workspace: &str) -> String { /// (NEXT-PHASE-1 v6 T5); a larger file gets no block. pub const COMPOSE_EDIT_MAX_BYTES: u64 = 8192; -/// NEXT-PHASE-1 v6 edit mode: the first whitespace-separated word of the goal -/// that (after stripping surrounding quotes, backticks, brackets and trailing -/// `.,;:!?`) is a plain relative path naming an existing regular UTF-8 file -/// of at most `COMPOSE_EDIT_MAX_BYTES` inside the canonical workspace `ws`. -/// Returns that path and the file's content. None when the goal names no -/// existing file, so a new-file goal keeps the v5 prompt byte for byte. +/// NEXT-PHASE-1 v6 edit mode: the goal's DESTINATION (see `destination.rs`, +/// issue #288; paths the goal only reads are ignored) when it is a plain +/// relative path naming an existing regular UTF-8 file of at most +/// `COMPOSE_EDIT_MAX_BYTES` inside the canonical workspace `ws`. Returns that +/// path and the file's content. None when the destination is missing, unsafe +/// or ambiguous, so a new-file goal keeps the v5 prompt byte for byte. pub fn existing_target(goal: &str, ws: &Path) -> Option<(String, String)> { match classify_target(goal, ws) { TargetClass::Edit(p, c) => Some((p, c)), @@ -1081,67 +1081,109 @@ pub fn existing_target(goal: &str, ws: &Path) -> Option<(String, String)> { } } -/// Decide the task kind from whether the named target path EXISTS in the -/// workspace (same word scan and `check_relative_path` as `existing_target`). -/// A word that names an existing file or symlink decides the class: small -/// UTF-8 file inside the workspace is `Edit`; any other existing file -/// (over `COMPOSE_EDIT_MAX_BYTES`, non-UTF-8, unreadable, dangling or -/// resolving outside the workspace) is `Refused`. Words naming nothing, or -/// only a directory, are skipped; no word names a file means `New`. +/// Decide the task kind from the goal's DESTINATION only (issue #288): the +/// path the goal asks to create or change, found by +/// `crate::destination::named_destination`; paths it merely reads ("about +/// README.md") are never classified. The destination is then judged by the disk: +/// a small UTF-8 file inside the workspace is `Edit`; a missing path inside the +/// workspace is `New`; everything else is `Refused` with the reason: an +/// absolute, `~`, `..` or non-plain path, a symlink or parent resolving outside +/// the workspace, a directory, a file over `COMPOSE_EDIT_MAX_BYTES`, non-UTF-8 +/// or unreadable content, and an ambiguous destination (several candidates). +/// A goal naming no destination is `New` (the model names the file). pub fn classify_target(goal: &str, ws: &Path) -> TargetClass { + classify_destination(goal, ws).0 +} + +/// `classify_target` plus the destination path it judged (None when the goal +/// 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) { let Ok(ws) = std::fs::canonicalize(ws) else { - return TargetClass::New; + return (TargetClass::New, None); }; - for w in goal.split_whitespace() { - let w = w - .trim_matches(|c| matches!(c, '"' | '\'' | '`' | '(' | ')' | '[' | ']')) - .trim_end_matches(['.', ',', ';', ':', '!', '?']) - .trim_matches(|c| matches!(c, '"' | '\'' | '`' | '(' | ')' | '[' | ']')); - if check_relative_path(w).is_err() { - continue; - } - let joined = ws.join(w); - // symlink_metadata: a dangling or outward symlink still EXISTS. - let Ok(lmeta) = std::fs::symlink_metadata(&joined) else { - continue; - }; - let refuse = |why: &str| { - TargetClass::Refused(format!( - "target {w} already exists but cannot be edited safely ({why}); refusing instead of treating it as a new document" - )) - }; - let full = match std::fs::canonicalize(&joined) { - Ok(f) => f, - Err(_) if lmeta.file_type().is_symlink() => return refuse("unresolvable symlink"), - Err(_) => return refuse("unresolvable path"), - }; - if !full.starts_with(&ws) { - return refuse("resolves outside the workspace"); - } - let Ok(meta) = std::fs::metadata(&full) else { - return refuse("unreadable"); - }; - if meta.is_dir() { - continue; - } - if !meta.is_file() { - return refuse("not a regular file"); - } - if meta.len() > COMPOSE_EDIT_MAX_BYTES { - return refuse(&format!( - "{} bytes is over the {COMPOSE_EDIT_MAX_BYTES}-byte edit limit", - meta.len() - )); + 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 class = classify_named(&w, &ws); + (class, Some(w)) +} + +fn classify_named(w: &str, ws: &Path) -> TargetClass { + let refuse = |why: &str| { + TargetClass::Refused(format!( + "destination {w} cannot be written safely ({why}); refusing" + )) + }; + if check_relative_path(w).is_err() { + return refuse("not a plain relative path inside the workspace"); + } + let joined = ws.join(w); + // symlink_metadata: a dangling or outward symlink still EXISTS. + let Ok(lmeta) = std::fs::symlink_metadata(&joined) else { + // Missing: a new document, if its nearest existing parent is a + // directory inside the workspace (no symlinked parent leaving it). + let mut anc = joined.parent(); + while let Some(a) = anc { + if std::fs::symlink_metadata(a).is_ok() { + break; + } + anc = a.parent(); } - let Ok(bytes) = std::fs::read(&full) else { - return refuse("unreadable"); - }; - return match String::from_utf8(bytes) { - Ok(content) => TargetClass::Edit(w.to_string(), content), - Err(_) => refuse("not UTF-8 text"), + return match anc.map(std::fs::canonicalize) { + Some(Ok(p)) if p.starts_with(ws) && p.is_dir() => TargetClass::New, + Some(Ok(p)) if p.starts_with(ws) => refuse("a parent is not a directory"), + Some(Ok(_)) => refuse("a parent resolves outside the workspace"), + _ => refuse("unresolvable parent"), }; + }; + let refuse = |why: &str| { + TargetClass::Refused(format!( + "destination {w} already exists but cannot be edited safely ({why}); refusing instead of treating it as a new document" + )) + }; + let full = match std::fs::canonicalize(&joined) { + Ok(f) => f, + Err(_) if lmeta.file_type().is_symlink() => return refuse("unresolvable symlink"), + Err(_) => return refuse("unresolvable path"), + }; + if !full.starts_with(ws) { + return refuse("resolves outside the workspace"); + } + let Ok(meta) = std::fs::metadata(&full) else { + return refuse("unreadable"); + }; + if meta.is_dir() { + return refuse("it is a directory"); } - TargetClass::New + if !meta.is_file() { + return refuse("not a regular file"); + } + if meta.len() > COMPOSE_EDIT_MAX_BYTES { + return refuse(&format!( + "{} bytes is over the {COMPOSE_EDIT_MAX_BYTES}-byte edit limit", + meta.len() + )); + } + let Ok(bytes) = std::fs::read(&full) else { + return refuse("unreadable"); + }; + match String::from_utf8(bytes) { + Ok(content) => TargetClass::Edit(w.to_string(), content), + Err(_) => refuse("not UTF-8 text"), + } +} + +/// The additive new-document block, appended when the goal names a destination +/// that does not exist yet: the model is told which file to write and must +/// answer with that `filename:` line (issue #288). +pub fn new_document_block(path: &str) -> String { + format!("\nWrite the new file {path}. The filename line of your answer must be exactly: filename: {path}") } /// The additive edit-mode block (NEXT-PHASE-1 v6 T5), appended to the fixed @@ -1179,16 +1221,28 @@ pub fn task_prompt_and_target(goal: &str, ws: &Path) -> (String, Option<(String, /// Prompt, edit target and kind of a task, or the refusal when the goal names /// an existing file that no edit block can be built for. pub fn task_plan(goal: &str, ws: &Path) -> Result { + task_decision(goal, ws).map(|(plan, _)| plan) +} + +/// `task_plan` plus the destination path the goal named (None when it names +/// 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> { let mut prompt = proposal_prompt(goal, &ws.display().to_string()); - let class = classify_target(goal, ws); + let (class, dest) = classify_destination(goal, ws); let kind = class.kind(); match class { TargetClass::Refused(why) => Err(format!("RunComposeTask: {why}")), TargetClass::Edit(path, content) => { prompt.push_str(&edit_block(&path, &content)); - Ok((prompt, Some((path, content)), kind)) + Ok(((prompt, Some((path, content)), kind), dest)) + } + TargetClass::New => { + if let Some(d) = &dest { + prompt.push_str(&new_document_block(d)); + } + Ok(((prompt, None, kind), dest)) } - TargetClass::New => Ok((prompt, None, kind)), } } @@ -1607,7 +1661,12 @@ type SkillOutput = (Result, Vec); /// The prompt of one task, its edit target and its kind (`task_plan`). pub type TaskPrompt = (String, Option<(String, String)>, ProposalKind); /// A task's plan plus the requirements its goal states (`requirements::extract`). -type TaskEntry = (TaskPrompt, Vec); +/// Prompt plan, requirements, and the destination the goal named (one decision). +type TaskEntry = ( + TaskPrompt, + Vec, + (Option, PathBuf), +); /// Owns the composition home of this process. pub struct ComposeBridge { @@ -1694,7 +1753,7 @@ impl ComposeBridge { let pa = approved.clone(); compose .register_skill(COMPOSE_MODEL_SKILL, None, 10, move |task| { - let ((prompt, target, kind), reqs) = pr.lock().get(&task).cloned()?; + let ((prompt, target, kind), reqs, dest) = pr.lock().get(&task).cloned()?; // Proposer hook (crate::approved): an approved proposal for this // task replaces the model's reply. One attempt, the same // template check, the same AEGIS contract and commit below. @@ -1726,6 +1785,12 @@ impl ComposeBridge { ) } }; + let (out, attempts) = enforce_destination( + (out, attempts), + dest.0.as_deref(), + &dest.1, + kind == ProposalKind::Edit, + ); let h = out.as_ref().ok().map(|t| proposal_handle(t)); pp.lock().insert(task, (out, attempts)); h @@ -1862,7 +1927,7 @@ impl ComposeBridge { ws.display() )); } - let plan = task_plan(goal, &ws)?; + 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); @@ -1903,7 +1968,9 @@ impl ComposeBridge { if let Some(t) = approved_text { home.approved.lock().insert(task, t.to_string()); } - home.prompts.lock().insert(task, (plan, reqs)); + home.prompts + .lock() + .insert(task, (plan, reqs, (dest, ws.clone()))); let run = home.compose.run(task, now.as_micros() as u64); home.prompts.lock().remove(&task); home.approved.lock().remove(&task); @@ -2219,6 +2286,39 @@ impl ComposeBridge { } } +/// The reply must write the destination the goal named (issue #288): the +/// approved proposal and a model reply are both held to the same path, so the +/// save and the commit land on the file the prompt and budget were chosen for. +/// A goal that named no destination leaves the model free to name the file. +fn enforce_destination( + out: SkillOutput, + dest: Option<&str>, + ws: &Path, + is_edit: bool, +) -> SkillOutput { + let (res, attempts) = out; + let res = match res { + Ok(t) => match parse_file_proposal(&t) { + Some(p) if dest.is_some_and(|d| p.path != d) => Err(format!( + "the proposal writes {} but the goal named the destination {}", + p.path, + dest.unwrap_or_default() + )), + // Defence in depth: a new-document task never replaces a file + // that exists (symlinks and dangling links count as existing). + Some(p) if !is_edit && std::fs::symlink_metadata(ws.join(&p.path)).is_ok() => { + Err(format!( + "the proposal writes {} which already exists; refusing to overwrite it as a new document", + p.path + )) + } + _ => Ok(t), + }, + r => r, + }; + (res, attempts) +} + #[cfg(test)] mod requirement_tests { use super::*; @@ -2304,3 +2404,50 @@ mod requirement_tests { assert_eq!(r.proposal.as_deref(), Some(SHORT)); } } + +#[cfg(test)] +mod destination_enforcement_tests { + use super::*; + + #[test] + fn reply_must_write_the_named_destination() { + let ok = "filename: docs/SUMMARY.md\n# s\n".to_string(); + let tmp = tempfile::tempdir().unwrap(); + let ws = tmp.path().to_path_buf(); + let run = |d: Option<&str>, t: &str| { + enforce_destination((Ok(t.to_string()), vec![]), d, &ws, false).0 + }; + assert_eq!(run(Some("docs/SUMMARY.md"), &ok), Ok(ok.clone())); + let e = run(Some("README.md"), &ok).unwrap_err(); + assert!( + e.contains("docs/SUMMARY.md") && e.contains("README.md"), + "{e}" + ); + assert_eq!(run(None, &ok), Ok(ok)); + } +} + +#[cfg(test)] +mod new_document_overwrite_tests { + use super::*; + + #[test] + fn new_kind_proposal_never_replaces_an_existing_file() { + let tmp = tempfile::tempdir().unwrap(); + let ws = tmp.path(); + std::fs::write(ws.join("README.md"), "# r\n").unwrap(); + std::os::unix::fs::symlink("nowhere", ws.join("dangling.md")).unwrap(); + let run = |dest: Option<&str>, path: &str, edit: bool| { + let t = format!("filename: {path}\nbody\n"); + enforce_destination((Ok(t), vec![]), dest, ws, edit).0 + }; + for dest in [None, Some("README.md")] { + let e = run(dest, "README.md", false).unwrap_err(); + assert!(e.contains("already exists"), "{e}"); + } + assert!(run(None, "dangling.md", false).is_err()); + assert!(run(None, "fresh.md", false).is_ok()); + // An edit-kind task may write its own (existing) target. + assert!(run(Some("README.md"), "README.md", true).is_ok()); + } +} diff --git a/crates/aien-runtime/tests/destination_test.rs b/crates/aien-runtime/tests/destination_test.rs new file mode 100644 index 00000000..d1552cd9 --- /dev/null +++ b/crates/aien-runtime/tests/destination_test.rs @@ -0,0 +1,156 @@ +//! Issue #288: the task kind, prompt and budget follow the DESTINATION the +//! goal names, not the first path that happens to exist. + +use aien_runtime::spine::{classify_target, task_decision, task_plan, ProposalKind, TargetClass}; +use std::path::PathBuf; + +fn ws_with(files: &[(&str, &str)]) -> (tempfile::TempDir, PathBuf) { + let d = tempfile::tempdir().unwrap(); + let ws = d.path().join("ws"); + std::fs::create_dir_all(ws.join("docs")).unwrap(); + for (n, c) in files { + std::fs::write(ws.join(n), c).unwrap(); + } + let ws = std::fs::canonicalize(ws).unwrap(); + (d, ws) +} + +#[test] +fn create_new_file_about_an_existing_one_is_a_new_document() { + let (_d, ws) = ws_with(&[("README.md", "# readme\n")]); + let goal = "Create docs/SUMMARY.md about README.md"; + assert_eq!(classify_target(goal, &ws), TargetClass::New); + let ((prompt, target, kind), dest) = task_decision(goal, &ws).unwrap(); + assert_eq!((target, kind), (None, ProposalKind::Document)); + assert_eq!(dest.as_deref(), Some("docs/SUMMARY.md")); + assert!(!prompt.contains("already exists")); +} + +#[test] +fn update_destination_using_a_source_is_an_edit_of_the_destination() { + let (_d, ws) = ws_with(&[("README.md", "# readme\n"), ("docs/NOTES.md", "n\n")]); + let (p, t, k) = task_plan("Update README.md using docs/NOTES.md", &ws).unwrap(); + assert_eq!(k, ProposalKind::Edit); + assert_eq!(t, Some(("README.md".into(), "# readme\n".into()))); + assert!(p.contains("The file README.md already exists")); +} + +#[test] +fn append_to_existing_guide_is_an_edit() { + let (_d, ws) = ws_with(&[("docs/GUIDE.md", "# guide\n")]); + let (_, t, k) = task_plan("Append a section to docs/GUIDE.md", &ws).unwrap(); + assert_eq!( + (t.map(|t| t.0), k), + (Some("docs/GUIDE.md".into()), ProposalKind::Edit) + ); +} + +#[test] +fn missing_destination_with_existing_source_is_new() { + let (_d, ws) = ws_with(&[("src.txt", "s\n")]); + let (_, t, k) = task_plan("Write out.md based on src.txt", &ws).unwrap(); + assert_eq!((t, k), (None, ProposalKind::Document)); +} + +#[test] +fn unsafe_destinations_are_refused_with_a_reason() { + let d = tempfile::tempdir().unwrap(); + let outside = d.path().join("outside"); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("s.txt"), "s\n").unwrap(); + let ws = d.path().join("ws"); + std::fs::create_dir_all(ws.join("docs")).unwrap(); + std::os::unix::fs::symlink(outside.join("s.txt"), ws.join("link.md")).unwrap(); + std::os::unix::fs::symlink(&outside, ws.join("linkdir")).unwrap(); + std::fs::write(ws.join("README.md"), "r\n").unwrap(); + let ws = std::fs::canonicalize(ws).unwrap(); + let abs = format!("Create {} about README.md", outside.join("n.md").display()); + for goal in [ + "Create ../x.md about README.md", + abs.as_str(), + "Create ~/x.md about README.md", + "Update link.md using README.md", + "Create linkdir/new.md about README.md", + ] { + let TargetClass::Refused(why) = classify_target(goal, &ws) else { + panic!("not refused: {goal}"); + }; + assert!(why.contains("destination"), "{goal}: {why}"); + assert!(task_plan(goal, &ws).is_err(), "{goal}"); + } +} + +#[test] +fn two_destinations_are_an_ambiguous_refusal_naming_both() { + let (_d, ws) = ws_with(&[("a.md", "a\n")]); + for goal in ["Create a.md and b.md", "Update a.md. Then create b.md"] { + let e = task_plan(goal, &ws).unwrap_err(); + assert!( + e.contains("ambiguous destination") && e.contains("a.md") && e.contains("b.md"), + "{e}" + ); + } +} + +#[test] +fn source_only_goal_is_refused_with_candidates() { + let (_d, ws) = ws_with(&[("README.md", "# r\n")]); + for goal in ["Summarise README.md", "Edit the given README.md "] { + let r = task_plan(goal, &ws); + if goal.starts_with("Edit") { + let (_, t, k) = r.unwrap(); + assert_eq!( + (t.map(|t| t.0), k), + (Some("README.md".into()), ProposalKind::Edit) + ); + } else { + let e = r.unwrap_err(); + assert!( + e.contains("no destination named") && e.contains("README.md"), + "{e}" + ); + } + } + let (_, t, _) = task_plan("Update the reference README.md", &ws).unwrap(); + assert_eq!(t.map(|t| t.0), Some("README.md".into())); +} + +#[test] +fn new_document_prompt_states_the_destination() { + let (_d, ws) = ws_with(&[("README.md", "# r\n")]); + let (p, _, _) = task_plan("Create docs/SUMMARY.md about README.md", &ws).unwrap(); + assert!(p.contains("filename: docs/SUMMARY.md"), "{p}"); +} + +#[test] +fn rename_is_refused() { + let (_d, ws) = ws_with(&[("a.md", "a\n")]); + assert!(task_plan("Rename a.md to b.md", &ws) + .unwrap_err() + .contains("rename is not supported")); +} + +#[test] +fn u1_garage_goal_is_an_edit_of_the_named_file() { + let (_d, ws) = ws_with(&[]); + std::fs::create_dir_all(ws.join("notes")).unwrap(); + std::fs::write( + ws.join("notes/GARAGE.md"), + "# Garage\n\n## Before a trip\n- check oil\n", + ) + .unwrap(); + let goal = r###"Please add "- check tyre pressure" to the "## Before a trip" section of notes/GARAGE.md."###; + let ((_, t, k), dest) = task_decision(goal, &ws).unwrap(); + assert_eq!(k, ProposalKind::Edit); + assert_eq!(t.map(|t| t.0), Some("notes/GARAGE.md".into())); + assert_eq!(dest.as_deref(), Some("notes/GARAGE.md")); +} + +#[test] +fn summary_of_source_into_destination_is_a_document() { + let (_d, ws) = ws_with(&[("README.md", "# r\n")]); + let ((_, t, k), dest) = + task_decision("Write a summary of README.md into docs/SUMMARY.md", &ws).unwrap(); + assert_eq!((t, k), (None, ProposalKind::Document)); + assert_eq!(dest.as_deref(), Some("docs/SUMMARY.md")); +} diff --git a/crates/aien-runtime/tests/np1_v6_test.rs b/crates/aien-runtime/tests/np1_v6_test.rs index 1ee08301..b36c0e10 100644 --- a/crates/aien-runtime/tests/np1_v6_test.rs +++ b/crates/aien-runtime/tests/np1_v6_test.rs @@ -119,6 +119,8 @@ fn token_ids_reach_the_attempt_record() { fn edit_block_only_when_the_goal_names_an_existing_file() { let (_d, ws) = ws(); let w = ws.display().to_string(); + // A new-document goal keeps the v5 prompt and gains the destination line + // (issue #288); an unsafe destination is refused and keeps the plain prompt. for goal in [ "Create the file NOTES.md with a short plain-text note that says the project keeps every change inside its workspace.", "Create the file docs/CONTACT.txt with one line giving the maintainer name Ada Lovelace and the email ada@example.org.", @@ -127,7 +129,14 @@ fn edit_block_only_when_the_goal_names_an_existing_file() { "Create the file docs/GUIDE.md about docs and plan.txt.", ] { assert_eq!(existing_target(goal, &ws), None, "{goal}"); - assert_eq!(task_prompt(goal, &ws), proposal_prompt(goal, &w), "{goal}"); + let dest = aien_runtime::spine::task_decision(goal, &ws) + .ok() + .and_then(|(_, d)| d); + let want = match dest { + Some(d) => format!("{}{}", proposal_prompt(goal, &w), aien_runtime::spine::new_document_block(&d)), + None => proposal_prompt(goal, &w), + }; + assert_eq!(task_prompt(goal, &ws), want, "{goal}"); } let log = "# Changelog\n\n## 0.1.0\n- initial release\n"; std::fs::write(ws.join("CHANGELOG.md"), log).unwrap();