Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/patches/3f4f872b64bf31b5 # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#807 (code only) closed derived `3f4f872b64bf31b5` #807 Imported from GitHub aien-dev/aien-sovereign-core-mv#807 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `2ef3e06c2a7b6c7498d7550cb0de6133129ed49a` · Head `4d2a1ee4f9d859f12bb928c4688720cf07f8f5a3` ### Fetch it A git bundle of the pull request's head, 38688 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/3f4f872b64bf31b5.bundle -o 3f4f872b64bf31b5.bundle git fetch 3f4f872b64bf31b5.bundle refs/pull/807/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 807 4d2a1ee4f9d859f12bb928c4688720cf07f8f5a3 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":807,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/807","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:38:04Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/README.md b/README.md index 8a6ad3ad..a0cda3c3 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,19 @@ Every file the agent writes in a chat session is recorded: one snapshot of the d Mechanism after Hermes Agent (Nous Research, MIT licence, commit 5480918), re-implemented from reading; no code copied. +Recursive subagent results and transcripts distinguish `completed` (a nonempty final model reply without tool calls, after a terminal stream event and successful transcript persistence), `failed` (inference error, interrupted or token-limited stream, empty reply, malformed tool markup, or transcript persistence failure), and `exhausted` (ten tool-bearing turns without a final reply). Only `completed` sets the tool success flag and emits a completion comb. A persistence failure returns `failed`, preserves the inference summary, reports the storage error separately as `transcript_error`, and sets `transcript_path: null`. The remote adapter requires `[DONE]` and refuses non-completing finish reasons such as `length`. The native server reserves `TurnFinished` for `StopToken`; token limits, aborts and preemption return a reason-bearing `Error` after recording generation evidence. The native client also refuses disconnected sockets without a terminal response. Malformed tool JSON, incomplete tool tags and unclosed named-tool fences (including whitespace-prefixed fences) are rejected, not repaired into calls or treated as final synthesis. These labels describe the agent loop, not independent verification of the assigned work. Host regressions use fake chat, isolated transcript storage, and test-owned loopback/Unix sockets, without model or GPU access: + +```sh +cargo test -p aien-cli --bin aien-cli subagents::tests:: +``` + +Autonomous goal execution marks an active milestone accomplished only after a successful `goal` tool `milestone_done`/`advance` request with the exact active goal id and milestone id. A whole-goal `done` request, mismatched identity, policy denial, storage error, empty/final-text reply without a completion request, or exhaustion of fifteen tool-bearing turns refuses completion and stops execution. Completion persistence errors propagate through the goal tool status and success flag; there is no unconditional fallback completion write. + +Goal selection and both completion mutations resolve an exact goal id across the entire manifest before trying the existing case-insensitive title-substring fallback. A different goal's title containing that id cannot intercept completion. The persisted-dispatch collision regressions exercise all four completion action names against an isolated `.goals.json`, using the real goal dispatcher and writer: + +```sh +cargo test -p aien-cli --bin aien-cli goals::completion_tests::round4_ +``` ## Human-Directed Agentic Engineering Development follows Human-Directed Agentic Engineering (HDAE): humans define goals, architecture, constraints, acceptance criteria, and stopping points; agents implement, execute checks, diagnose failures, and revise within those boundaries. Human review retains responsibility for claims, acceptance, and release decisions. diff --git a/crates/aien-cli/src/client.rs b/crates/aien-cli/src/client.rs index 32e96def..520a7531 100644 --- a/crates/aien-cli/src/client.rs +++ b/crates/aien-cli/src/client.rs @@ -308,6 +308,16 @@ impl ChatClient { if let Ok(val) = serde_json::from_str::(data) { if let Some(choices) = val.get("choices").and_then(Value::as_array) { if let Some(choice) = choices.first() { + if let Some(reason) = + choice.get("finish_reason").and_then(Value::as_str) + { + if !matches!(reason, "stop" | "tool_calls" | "function_call") { + return Err(format!( + "Model turn did not complete: finish_reason {}", + reason + )); + } + } if let Some(delta) = choice.get("delta") { if let Some(reasoning) = delta .get("reasoning") @@ -357,84 +367,82 @@ impl ChatClient { if stream_to_stdout { println!(); } + if !is_done { + return Err("Model stream ended before [DONE]".into()); + } Ok(full_text) } } -fn parse_tool_call_json(raw: &str) -> Option { - let trimmed = raw.trim(); - if let Ok(parsed) = serde_json::from_str::(trimmed) { - return Some(parsed); - } - // Delimiter repair: trailing "]" instead of "}" - if let Some(stripped) = trimmed.strip_suffix("]") { - let mut fixed = stripped.to_string(); - fixed.push('}'); - if let Ok(parsed) = serde_json::from_str::(&fixed) { - return Some(parsed); - } - } - // Truncated boundary repair: unclosed curlies - let open_c = trimmed.chars().filter(|&c| c == '{').count(); - let close_c = trimmed.chars().filter(|&c| c == '}').count(); - if open_c > close_c { - let mut candidate = trimmed.to_string(); - if candidate.chars().filter(|&c| c == '"').count() % 2 != 0 { - candidate.push('"'); - } - for _ in 0..(open_c - close_c) { - candidate.push('}'); - } - if let Ok(parsed) = serde_json::from_str::(&candidate) { - return Some(parsed); - } +fn parse_tool_call_json(raw: &str) -> Result<(String, Value), String> { + let parsed: Value = serde_json::from_str(raw.trim()) + .map_err(|error| format!("Malformed tool call: {}", error))?; + let name = parsed + .get("name") + .and_then(Value::as_str) + .filter(|name| !name.trim().is_empty() && *name != "tool_name") + .ok_or_else(|| "Malformed tool call: missing or invalid name".to_string())?; + let args = parsed + .get("arguments") + .cloned() + .unwrap_or_else(|| json!({})); + if !args.is_object() { + return Err("Malformed tool call: arguments must be an object".into()); } - None + Ok((name.to_string(), args)) } -pub fn extract_tool_calls(text: &str) -> Vec<(String, Value)> { - let mut calls = Vec::new(); - let pattern = match regex::Regex::new(r"(?s)\s*(.*?)\s*(?:|$)") { - Ok(p) => p, - Err(_) => return calls, +fn fenced_tool_call(block: &str) -> Option<&str> { + let block = block.trim(); + let (explicit, raw) = if let Some(raw) = block.strip_prefix("tool_call") { + (true, raw) + } else { + (false, block.strip_prefix("json").unwrap_or(block)) }; - for caps in pattern.captures_iter(text) { - if let Some(json_match) = caps.get(1) { - if let Some(parsed) = parse_tool_call_json(json_match.as_str()) { - if let Some(name) = parsed.get("name").and_then(Value::as_str) { - if name != "tool_name" { - let args = parsed.get("arguments").cloned().unwrap_or(json!({})); - calls.push((name.to_string(), args)); - } - } - } + (explicit || (raw.trim_start().starts_with('{') && raw.contains("\"name\""))).then_some(raw) +} + +/// Parse tool requests without treating malformed markup as final synthesis. +pub fn extract_tool_calls(text: &str) -> Result, String> { + let mut calls = Vec::new(); + let mut remaining = text; + while let Some((prefix, after)) = remaining.split_once("') + .ok_or_else(|| "Malformed tool call: invalid opening tag".to_string())?; + let (raw, rest) = after + .split_once("") + .ok_or_else(|| "Malformed tool call: missing closing tag".to_string())?; + calls.push(parse_tool_call_json(raw)?); + remaining = rest; } - if calls.is_empty() { - if let Ok(json_pat) = regex::Regex::new( - r#"(?s)```(?:json|tool_call)?\s*(\{\s*"name"\s*:\s*"[^"]+".*?\})\s*```"#, - ) { - for caps in json_pat.captures_iter(text) { - if let Some(json_match) = caps.get(1) { - if let Some(parsed) = parse_tool_call_json(json_match.as_str()) { - if let Some(name) = parsed.get("name").and_then(Value::as_str) { - if name != "tool_name" { - let args = parsed.get("arguments").cloned().unwrap_or(json!({})); - calls.push((name.to_string(), args)); - } - } - } - } + if remaining.contains(" Option<(String, Value)> { - extract_tool_calls(text).into_iter().last() + Ok(calls) } #[cfg(test)] @@ -446,26 +454,21 @@ mod tests { let valid = r#" {"name": "run_command", "arguments": {"command": "git status"}} "#; - let calls = extract_tool_calls(valid); + let calls = extract_tool_calls(valid).unwrap(); assert_eq!(calls.len(), 1); assert_eq!(calls[0].0, "run_command"); assert_eq!(calls[0].1["command"], "git status"); - // Trailing bracket repair + // Malformed JSON is evidence of an invalid request, not repairable success. let bracket_glitch = r#" {"name": "invoke_subagent", "arguments": {"role": "Auditor", "prompt": "check crates"}] "#; - let calls2 = extract_tool_calls(bracket_glitch); - assert_eq!(calls2.len(), 1); - assert_eq!(calls2[0].0, "invoke_subagent"); - assert_eq!(calls2[0].1["role"], "Auditor"); + assert!(extract_tool_calls(bracket_glitch).is_err()); - // Truncated tool call (no closing tag) + // An incomplete tag must not be executed or treated as final synthesis. let truncated = r#" {"name": "run_command", "arguments": {"command": "ls -la"}}"#; - let calls3 = extract_tool_calls(truncated); - assert_eq!(calls3.len(), 1); - assert_eq!(calls3[0].0, "run_command"); + assert!(extract_tool_calls(truncated).is_err()); } #[tokio::test] diff --git a/crates/aien-cli/src/compaction.rs b/crates/aien-cli/src/compaction.rs index dba22c35..149e548d 100644 --- a/crates/aien-cli/src/compaction.rs +++ b/crates/aien-cli/src/compaction.rs @@ -541,7 +541,12 @@ fn classify(index: usize, m: &Value) -> MessageClass { return MessageClass::ToolResult; } if role == "assistant" { - let calls = crate::client::extract_tool_calls(&text).len(); + // Invalid requests are not executable calls. Their original assistant + // text remains in the transcript; the execution loop reports the error. + let calls = match crate::client::extract_tool_calls(&text) { + Ok(calls) => calls.len(), + Err(_) => return MessageClass::Assistant, + }; if calls > 0 { return MessageClass::AssistantToolRequest(calls); } diff --git a/crates/aien-cli/src/goals.rs b/crates/aien-cli/src/goals.rs index eb8b226b..7d9034c2 100644 --- a/crates/aien-cli/src/goals.rs +++ b/crates/aien-cli/src/goals.rs @@ -123,72 +123,76 @@ pub fn add_goal(title: &str, description: &str, milestones_raw: Vec) -> goal } +pub(crate) fn goal_index(goals: &[Goal], target: &str) -> Option { + goals.iter().position(|goal| goal.id == target).or_else(|| { + let title = target.to_lowercase(); + goals + .iter() + .position(|goal| goal.title.to_lowercase().contains(&title)) + }) +} + pub fn complete_goal(target_id: &str) -> Result { - let mut manifest = load_goals(); - let mut found = false; - let mut title = String::new(); - - for g in manifest.goals.iter_mut() { - if g.id == target_id || g.title.to_lowercase().contains(&target_id.to_lowercase()) { - g.status = GoalStatus::Completed; - for m in g.milestones.iter_mut() { - m.completed = true; - } - g.updated_at = Utc::now().to_rfc3339(); - title = g.title.clone(); - found = true; - break; - } - } + complete_goal_with(target_id, load_goals(), save_goals) +} - if found { - let _ = save_goals(&manifest); - Ok(format!( - "Goal '{}' ({}) marked as Completed.", - title, target_id - )) - } else { - Err(format!("Goal '{}' not found in manifest.", target_id)) +fn complete_goal_with( + target_id: &str, + mut manifest: GoalManifest, + save: impl FnOnce(&GoalManifest) -> Result, +) -> Result { + let index = goal_index(&manifest.goals, target_id) + .ok_or_else(|| format!("Goal '{}' not found in manifest.", target_id))?; + let goal = &mut manifest.goals[index]; + goal.status = GoalStatus::Completed; + for milestone in &mut goal.milestones { + milestone.completed = true; } + goal.updated_at = Utc::now().to_rfc3339(); + save(&manifest)?; + Ok(format!( + "Goal '{}' ({}) marked as Completed.", + manifest.goals[index].title, target_id + )) } pub fn complete_milestone(target_id: &str, milestone_id: usize) -> Result { - let mut manifest = load_goals(); - let mut found = false; - let mut all_completed = false; - - for g in manifest.goals.iter_mut() { - if g.id == target_id || g.title.to_lowercase().contains(&target_id.to_lowercase()) { - for m in g.milestones.iter_mut() { - if m.id == milestone_id { - m.completed = true; - found = true; - } - } - g.updated_at = Utc::now().to_rfc3339(); - if g.milestones.iter().all(|m| m.completed) { - g.status = GoalStatus::Completed; - all_completed = true; - } - break; - } - } + complete_milestone_with(target_id, milestone_id, load_goals(), save_goals) +} - if found { - let _ = save_goals(&manifest); - if all_completed { - Ok(format!( - "Milestone {} completed. All milestones finished! Goal is now Completed.", - milestone_id - )) - } else { - Ok(format!("Milestone {} completed.", milestone_id)) - } - } else { - Err(format!( +fn complete_milestone_with( + target_id: &str, + milestone_id: usize, + mut manifest: GoalManifest, + save: impl FnOnce(&GoalManifest) -> Result, +) -> Result { + let missing = || { + format!( "Milestone {} for goal '{}' not found.", milestone_id, target_id + ) + }; + let index = goal_index(&manifest.goals, target_id).ok_or_else(missing)?; + let goal = &mut manifest.goals[index]; + let milestone = goal + .milestones + .iter_mut() + .find(|milestone| milestone.id == milestone_id) + .ok_or_else(missing)?; + milestone.completed = true; + goal.updated_at = Utc::now().to_rfc3339(); + let all_completed = goal.milestones.iter().all(|milestone| milestone.completed); + if all_completed { + goal.status = GoalStatus::Completed; + } + save(&manifest)?; + if all_completed { + Ok(format!( + "Milestone {} completed. All milestones finished! Goal is now Completed.", + milestone_id )) + } else { + Ok(format!("Milestone {} completed.", milestone_id)) } } @@ -303,3 +307,151 @@ pub fn goals_dispatch_tool(args: &Value) -> Value { _ => json!({"error": format!("Unknown goal action '{}'", action)}), } } + +#[cfg(test)] +mod completion_tests { + use super::*; + fn manifest() -> GoalManifest { + GoalManifest { + project_name: "isolated".into(), + goals: vec![Goal { + id: "active".into(), + title: "active".into(), + description: "test".into(), + status: GoalStatus::Active, + created_at: "test".into(), + updated_at: "test".into(), + milestones: vec![Milestone { + id: 7, + description: "test".into(), + completed: false, + }], + }], + } + } + #[test] + fn round3_milestone_persistence_failure_is_error() { + let scratch = tempfile::tempdir().unwrap(); + let blocked = scratch.path().join("goals.json"); + std::fs::create_dir(&blocked).unwrap(); + let result = complete_milestone_with("active", 7, manifest(), |m| { + std::fs::write(&blocked, serde_json::to_vec(m).unwrap()) + .map(|_| blocked.clone()) + .map_err(|e| format!("write goals: {e}")) + }); + assert!(result.unwrap_err().contains("write goals")); + } + #[test] + fn round3_goal_persistence_failure_is_error() { + let result = + complete_goal_with("active", manifest(), |_| Err("storage unavailable".into())); + assert!(result.unwrap_err().contains("storage unavailable")); + } + #[test] + fn round3_milestone_persistence_success() { + let scratch = tempfile::tempdir().unwrap(); + let path = scratch.path().join("goals.json"); + complete_milestone_with("active", 7, manifest(), |m| { + std::fs::write(&path, serde_json::to_vec(m).unwrap()) + .map(|_| path.clone()) + .map_err(|e| e.to_string()) + }) + .unwrap(); + let saved: GoalManifest = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); + assert!(saved.goals[0].milestones[0].completed); + assert_eq!(saved.goals[0].status, GoalStatus::Completed); + } + + fn collision_manifest() -> GoalManifest { + let mut manifest = manifest(); + let mut goal_a = manifest.goals.remove(0); + goal_a.id = "goal-A".into(); + goal_a.title = "Support goal-B".into(); + goal_a.milestones[0].id = 1; + let mut goal_b = goal_a.clone(); + goal_b.id = "goal-B".into(); + goal_b.title = "Actual task".into(); + manifest.goals = vec![goal_a, goal_b]; + manifest + } + + #[test] + fn round4_exact_goal_resolution_precedes_title() { + let manifest = collision_manifest(); + assert_eq!(goal_index(&manifest.goals, "goal-B"), Some(1)); + assert_eq!(goal_index(&manifest.goals, "Actual task"), Some(1)); + assert_eq!(goal_index(&manifest.goals, "ACTUAL"), Some(1)); + assert_eq!(goal_index(&manifest.goals, "Support"), Some(0)); + assert_eq!(goal_index(&manifest.goals, "missing"), None); + } + + fn persisted_dispatch_collision(test_name: &str, actions: &[&str]) { + const CHILD_ACTION: &str = "AIEN_TEST_ROUND4_GOAL_DISPATCH_ACTION"; + if let Ok(action) = std::env::var(CHILD_ACTION) { + assert!(actions.contains(&action.as_str())); + let before = load_goals(); + // This is the same resolver used by autonomous mode. Resolving + // the title selects goal-B; its id must stay authoritative when + // the real tool dispatcher persists the completion. + let selected = goal_index(&before.goals, "Actual task").unwrap(); + let id = &before.goals[selected].id; + assert_eq!(id, "goal-B"); + let result = goals_dispatch_tool(&json!({ + "action": action, "id": id, "milestone_id": 1, + })); + assert_eq!(result["status"], "ok", "{result}"); + let saved: GoalManifest = + serde_json::from_slice(&fs::read(".goals.json").unwrap()).unwrap(); + assert!( + saved.goals[1].milestones[0].completed, + "{action}: goal-B not persisted" + ); + assert_eq!(saved.goals[1].status, GoalStatus::Completed); + assert_eq!( + serde_json::to_value(&saved.goals[0]).unwrap(), + serde_json::to_value(&before.goals[0]).unwrap(), + "{action}: unrelated goal-A changed", + ); + return; + } + for action in actions { + let scratch = tempfile::tempdir().unwrap(); + fs::write( + scratch.path().join(".goals.json"), + serde_json::to_vec(&collision_manifest()).unwrap(), + ) + .unwrap(); + // Isolate the real path resolver and writer without changing the + // unit-test process's cwd or using synthetic dispatch success. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .current_dir(scratch.path()) + .env(CHILD_ACTION, action) + .args(["--exact", test_name, "--nocapture"]) + .output() + .unwrap(); + assert!( + output.status.success(), + "{action}: child failed ({:?})\n{}\n{}", + output.status.code(), + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); + } + } + + #[test] + fn round4_milestone_dispatch_persists_exact_goal() { + persisted_dispatch_collision( + "goals::completion_tests::round4_milestone_dispatch_persists_exact_goal", + &["milestone_done", "advance"], + ); + } + + #[test] + fn round4_goal_dispatch_persists_exact_goal() { + persisted_dispatch_collision( + "goals::completion_tests::round4_goal_dispatch_persists_exact_goal", + &["done", "complete"], + ); + } +} diff --git a/crates/aien-cli/src/main.rs b/crates/aien-cli/src/main.rs index e20e83be..a8de8846 100644 --- a/crates/aien-cli/src/main.rs +++ b/crates/aien-cli/src/main.rs @@ -747,7 +747,13 @@ async fn run_model_steps( } } - let tool_calls = extract_tool_calls(&assistant_resp); + let tool_calls = match extract_tool_calls(&assistant_resp) { + Ok(calls) => calls, + Err(error) => { + eprintln!("{}", error); + return Some(TurnStop::Recovery("malformed-tool-markup")); + } + }; if tool_calls.is_empty() { // Completed turn return None; @@ -763,22 +769,31 @@ async fn run_model_steps( /// What one autonomous assistant reply did, after it was recorded. #[derive(Debug)] enum AutonomousStep { - /// The reply had no tool call. - StoppedTalking, - /// Tools ran. `milestone_done` is the goal tool's signal. - Acted { milestone_done: bool }, + /// The reply had no tool call, or its tool markup was malformed. + StoppedTalking(String), + /// Tools ran; none of them asked to complete the milestone. + Acted, + /// The goal tool accepted a completion request for the active milestone. + Completed, + /// A completion request named the wrong goal/milestone (not dispatched) + /// or the goal tool refused it. + Refused(String), } /// One autonomous assistant reply under persist-before-act. /// /// The reply is on disk before any tool runs. Each tool request is on disk /// before that tool runs. A failed journal write returns `Err` and does not -/// call `dispatch`. +/// call `dispatch`. Only a `goal` `milestone_done`/`advance` request naming +/// exactly `goal_id` and `milestone_id`, answered with `status: ok`, completes +/// the milestone; any other completion request is refused before dispatch. fn apply_autonomous_reply( journal: &mut turn_journal::Journal, messages: &mut Vec, assistant_resp: &str, - dispatch: F, + goal_id: &str, + milestone_id: usize, + mut dispatch: F, ) -> Result where F: FnMut(&str, &Value) -> Value, @@ -787,19 +802,47 @@ where messages, json!({"role": "assistant", "content": assistant_resp}), )?; - let tool_calls = extract_tool_calls(assistant_resp); + let tool_calls = match extract_tool_calls(assistant_resp) { + Ok(calls) => calls, + Err(error) => return Ok(AutonomousStep::StoppedTalking(error)), + }; if tool_calls.is_empty() { - return Ok(AutonomousStep::StoppedTalking); + return Ok(AutonomousStep::StoppedTalking( + "reply did not request milestone completion".into(), + )); } - let milestone_done = tool_calls.iter().any(|(name, args)| { - name == "goal" + for (name, args) in tool_calls { + let action = args["action"].as_str(); + let completion_request = name == "goal" && matches!( - args.get("action").and_then(Value::as_str), - Some("milestone_done") | Some("done") - ) - }); - turn_journal::run_tool_calls(journal, messages, tool_calls, dispatch)?; - Ok(AutonomousStep::Acted { milestone_done }) + action, + Some("milestone_done" | "advance" | "done" | "complete") + ); + if completion_request + && (!matches!(action, Some("milestone_done" | "advance")) + || args["id"].as_str() != Some(goal_id) + || args["milestone_id"].as_u64() != Some(milestone_id as u64)) + { + return Ok(AutonomousStep::Refused( + "completion request does not identify the active goal/milestone".into(), + )); + } + let mut result = Value::Null; + turn_journal::run_tool_calls(journal, messages, vec![(name, args)], |n, a| { + result = dispatch(n, a); + result.clone() + })?; + if completion_request { + if result["status"].as_str() == Some("ok") { + return Ok(AutonomousStep::Completed); + } + return Ok(AutonomousStep::Refused(format!( + "milestone completion refused: {}", + result + ))); + } + } + Ok(AutonomousStep::Acted) } /// sc#666: one reply's tool calls as a planned batch. Reads of the same or @@ -854,10 +897,7 @@ fn report_batch(r: &tool_batch::BatchReport) { pub async fn run_autonomous_goal(goal_id: &str) { let manifest = goals::load_goals(); - let goal = match manifest - .goals - .iter() - .find(|g| g.id == goal_id || g.title.to_lowercase().contains(&goal_id.to_lowercase())) + let goal = match goals::goal_index(&manifest.goals, goal_id).map(|index| &manifest.goals[index]) { Some(g) => g.clone(), None => { @@ -968,43 +1008,21 @@ pub async fn run_autonomous_goal(goal_id: &str) { } } - let mut max_tool_steps = 15; - let mut milestone_done = false; - - while max_tool_steps > 0 && !milestone_done { - max_tool_steps -= 1; - print!( - "\n{}", - format!("AIEN [Milestone {}]: ", m.id).magenta().bold() - ); - let mut assistant_resp = match client.stream_turn(&messages, true).await { - Ok(text) => text, - Err(e) => { - eprintln!("Inference error: {}", e); - break; - } - }; - - hook_registry.run_post_turn(&mut assistant_resp).await; - match apply_autonomous_reply( - &mut journal, - &mut messages, - &assistant_resp, - dispatch_tool, - ) { - Ok(AutonomousStep::StoppedTalking) => break, - Ok(AutonomousStep::Acted { - milestone_done: done, - }) => milestone_done = done, - Err(stop) => { - eprintln!("{}", stop.describe().red().bold()); - journal.stop(&stop); - return; - } - } + if let Err(error) = execute_autonomous_milestone( + &client, + &mut journal, + &mut messages, + &goal.id, + m.id, + &hook_registry, + dispatch_tool, + ) + .await + { + eprintln!("Milestone {} not completed: {}", m.id, error); + return; } - let _ = goals::complete_milestone(&goal.id, m.id); println!( "{}", format!(" ✓ Milestone {} accomplished: {}", m.id, m.description) @@ -1024,6 +1042,171 @@ pub async fn run_autonomous_goal(goal_id: &str) { ); } +trait MilestoneChat { + async fn reply(&self, messages: &[Value]) -> Result; +} + +impl MilestoneChat for ChatClient { + async fn reply(&self, messages: &[Value]) -> Result { + self.stream_turn(messages, true).await + } +} + +/// Runs one milestone: at most fifteen tool-bearing replies, each applied +/// under persist-before-act by `apply_autonomous_reply`. Anything but an +/// accepted completion request for exactly this goal/milestone is `Err`. +/// A journal failure is recorded with `journal.stop` before returning. +async fn execute_autonomous_milestone( + client: &impl MilestoneChat, + journal: &mut turn_journal::Journal, + messages: &mut Vec, + goal_id: &str, + milestone_id: usize, + hook_registry: &crate::hooks::HookRegistry, + mut dispatch: impl FnMut(&str, &Value) -> Value, +) -> Result<(), String> { + for _ in 0..15 { + print!( + "\n{}", + format!("AIEN [Milestone {}]: ", milestone_id) + .magenta() + .bold() + ); + let mut response = client.reply(messages).await?; + hook_registry.run_post_turn(&mut response).await; + match apply_autonomous_reply( + journal, + messages, + &response, + goal_id, + milestone_id, + &mut dispatch, + ) { + Ok(AutonomousStep::Acted) => {} + Ok(AutonomousStep::Completed) => return Ok(()), + Ok(AutonomousStep::StoppedTalking(why) | AutonomousStep::Refused(why)) => { + return Err(why) + } + Err(stop) => { + journal.stop(&stop); + return Err(stop.describe()); + } + } + } + Err("milestone exhausted its 15 tool-bearing turns without completion".into()) +} + +#[cfg(test)] +mod autonomous_tests { + use super::*; + struct FakeChat(std::cell::RefCell>); + impl MilestoneChat for FakeChat { + async fn reply(&self, _: &[Value]) -> Result { + Ok(self + .0 + .borrow_mut() + .pop_front() + .expect("unexpected inference")) + } + } + fn request(args: Value) -> String { + format!( + "{}", + json!({"name":"goal","arguments":args}) + ) + } + async fn run( + replies: Vec, + dispatch: impl FnMut(&str, &Value) -> Value, + ) -> Result<(), String> { + let d = tempfile::tempdir().unwrap(); + let mut journal = turn_journal::Journal::create(&d.path().join("s.journal.jsonl")).unwrap(); + execute_autonomous_milestone( + &FakeChat(std::cell::RefCell::new(replies.into())), + &mut journal, + &mut Vec::new(), + "active", + 7, + &crate::hooks::HookRegistry::default_sovereign_registry(), + dispatch, + ) + .await + } + #[tokio::test] + async fn round3_milestone_exhaustion_refuses_completion() { + let reply = request(json!({"action":"list"})); + let mut count = 0; + let result = run(vec![reply; 15], |_, _| { + count += 1; + json!({"status":"ok"}) + }) + .await; + assert!(result.is_err(), "exhaustion completed"); + assert_eq!(count, 15); + } + #[tokio::test] + async fn round3_milestone_empty_and_final_text_refuse_completion() { + for reply in ["", "I think the milestone is done."] { + assert!(run(vec![reply.into()], |_, _| panic!("no dispatch")) + .await + .is_err()); + } + } + #[tokio::test] + async fn round3_milestone_denied_request_refuses_completion() { + for refusal in [ + json!({"error":"SECURITY DENIAL: policy refused"}), + json!({"status":"error","error":"write goals failed"}), + ] { + let result = run( + vec![request( + json!({"action":"milestone_done","id":"active","milestone_id":7}), + )], + |_, _| refusal.clone(), + ) + .await; + assert!( + result.is_err(), + "denied/failed completion request succeeded" + ); + } + } + #[tokio::test] + async fn round3_milestone_invalid_request_refuses_completion() { + for args in [ + json!({"action":"milestone_done","id":"other","milestone_id":7}), + json!({"action":"milestone_done","id":"active","milestone_id":8}), + json!({"action":"milestone_done","id":"active"}), + json!({"action":"done","id":"active"}), + ] { + let mut dispatched = false; + assert!(run(vec![request(args)], |_, _| { + dispatched = true; + json!({"status":"ok"}) + }) + .await + .is_err()); + assert!(!dispatched, "invalid completion request reached its effect"); + } + } + #[tokio::test] + async fn round3_milestone_valid_request_completes() { + let mut count = 0; + run( + vec![request( + json!({"action":"milestone_done","id":"active","milestone_id":7}), + )], + |_, _| { + count += 1; + json!({"status":"ok"}) + }, + ) + .await + .unwrap(); + assert_eq!(count, 1); + } +} + /// Prints the outcome of a compaction pass. Skips are reported too, so a /// refusal (detached tool result, store failure) is never silent. /// sc#664: prints the compaction report and, when the history changed, records @@ -1303,10 +1486,11 @@ mod autonomous_journal_tests { journal.accept_only_n_writes_for_test(1); let assistant = reply_with("run_command", json!({"command": "rm x"})); let mut ran = false; - let result = apply_autonomous_reply(&mut journal, &mut messages, &assistant, |_, _| { - ran = true; - json!({}) - }); + let result = + apply_autonomous_reply(&mut journal, &mut messages, &assistant, "g", 1, |_, _| { + ran = true; + json!({}) + }); assert!( matches!(result, Err(turn_journal::TurnStop::PersistFailed(_))), "{result:?}" @@ -1346,26 +1530,29 @@ mod autonomous_journal_tests { json!({"action": "milestone_done", "id": "g", "milestone_id": 1}), ); let path_for_dispatch = path.clone(); - let step = apply_autonomous_reply(&mut journal, &mut messages, &assistant, |name, args| { - let rep = turn_journal::replay(&std::fs::read_to_string(&path_for_dispatch).unwrap()) - .unwrap(); - assert_eq!( - rep.in_doubt.len(), - 1, - "the request must be durable before dispatch" - ); - assert_eq!(rep.in_doubt[0].name, name); - assert_eq!(rep.in_doubt[0].effect, turn_journal::Effect::Effectful); - assert_eq!(args["action"], "milestone_done"); - json!({"ok": true}) - }) + let step = apply_autonomous_reply( + &mut journal, + &mut messages, + &assistant, + "g", + 1, + |name, args| { + let rep = + turn_journal::replay(&std::fs::read_to_string(&path_for_dispatch).unwrap()) + .unwrap(); + assert_eq!( + rep.in_doubt.len(), + 1, + "the request must be durable before dispatch" + ); + assert_eq!(rep.in_doubt[0].name, name); + assert_eq!(rep.in_doubt[0].effect, turn_journal::Effect::Effectful); + assert_eq!(args["action"], "milestone_done"); + json!({"status": "ok"}) + }, + ) .unwrap(); - assert!(matches!( - step, - AutonomousStep::Acted { - milestone_done: true - } - )); + assert!(matches!(step, AutonomousStep::Completed), "{step:?}"); assert!(messages.iter().any(|m| { m["content"] .as_str() diff --git a/crates/aien-cli/src/subagents.rs b/crates/aien-cli/src/subagents.rs index cf65a1d6..736750f1 100644 --- a/crates/aien-cli/src/subagents.rs +++ b/crates/aien-cli/src/subagents.rs @@ -19,6 +19,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::fs; use std::future::Future; +use std::path::Path; use std::pin::Pin; use std::time::SystemTime; @@ -42,7 +43,8 @@ pub struct SubagentResult { pub parent_id: Option, pub status: String, pub summary: String, - pub transcript_path: String, + pub transcript_path: Option, + pub transcript_error: Option, pub steps_executed: usize, pub children_spawned: Vec, } @@ -66,6 +68,23 @@ pub struct SubagentTranscript { pub children: Vec, } +#[derive(Clone, Copy, PartialEq, Eq)] +enum SubagentOutcome { + Completed, + Failed, + Exhausted, +} + +impl SubagentOutcome { + fn status(self) -> &'static str { + match self { + Self::Completed => "completed", + Self::Failed => "failed", + Self::Exhausted => "exhausted", + } + } +} + pub fn get_subagent_system_prompt(spec: &SubagentSpec) -> String { let mut p = String::new(); p.push_str(&format!( @@ -132,191 +151,245 @@ fn generate_short_id() -> String { format!("{:04x}", nanos % 0xffff) } +trait SubagentChat: Sync { + fn reply(&self, messages: &[Value]) -> impl Future> + Send; +} + +impl SubagentChat for ChatClient { + async fn reply(&self, messages: &[Value]) -> Result { + self.stream_turn_with_limit(messages, false, 1024).await + } +} + pub fn execute_subagent( spec: SubagentSpec, ) -> Pin + Send>> { Box::pin(async move { - let start_time = Utc::now().to_rfc3339(); - let indent = " ".repeat(spec.depth); - println!( - "{}", - format!( - "{}┌─ [Subagent Spawning: '{}' | Depth: {} | ID: {}]", - indent, spec.role, spec.depth, spec.id - ) - .cyan() - .bold() - ); - println!( - "{}", - format!("{}│ Directive: {}", indent, spec.prompt).dimmed() - ); - let client = ChatClient::new(None, None); - let mut messages = vec![ - json!({"role": "system", "content": get_subagent_system_prompt(&spec)}), - json!({"role": "user", "content": format!("TASK ASSIGNMENT:\nRole: {}\nPrompt: {}\n\nExecute all necessary steps using tools, verify outcomes, and provide your distilled technical summary when complete.", spec.role, spec.prompt)}), - ]; - - let mut steps_log = Vec::new(); - let mut children_spawned = Vec::new(); - let mut max_steps = 10; - let mut step_count = 0; - let mut final_summary = String::new(); - - while max_steps > 0 { - max_steps -= 1; - step_count += 1; - - let assistant_resp = match client.stream_turn_with_limit(&messages, false, 1024).await { - Ok(text) => text, - Err(e) => { - let err_msg = format!("Subagent inference failed: {}", e); - println!("{}", format!("{}│ [Error] {}", indent, err_msg).red()); - final_summary = err_msg; - break; - } - }; + let platform = crate::platform::PlatformContext::detect(); + let transcript_dir = platform.home_dir.join("basecamp/sessions/subagents"); + execute_subagent_with(spec, &client, &transcript_dir, emit_completion_comb).await + }) +} - messages.push(json!({"role": "assistant", "content": assistant_resp.clone()})); +async fn execute_subagent_with( + spec: SubagentSpec, + client: &impl SubagentChat, + transcript_dir: &Path, + emit_comb: impl Fn(&SubagentSpec, &str), +) -> SubagentResult { + let start_time = Utc::now().to_rfc3339(); + let indent = " ".repeat(spec.depth); + println!( + "{}", + format!( + "{}┌─ [Subagent Spawning: '{}' | Depth: {} | ID: {}]", + indent, spec.role, spec.depth, spec.id + ) + .cyan() + .bold() + ); + println!( + "{}", + format!("{}│ Directive: {}", indent, spec.prompt).dimmed() + ); - let tool_calls = extract_tool_calls(&assistant_resp); - if tool_calls.is_empty() { - // Done! Assistant provided its final synthesis without tool calls. - final_summary = assistant_resp; + let mut messages = vec![ + json!({"role": "system", "content": get_subagent_system_prompt(&spec)}), + json!({"role": "user", "content": format!("TASK ASSIGNMENT:\nRole: {}\nPrompt: {}\n\nExecute all necessary steps using tools, verify outcomes, and provide your distilled technical summary when complete.", spec.role, spec.prompt)}), + ]; + + let mut steps_log = Vec::new(); + let mut children_spawned = Vec::new(); + let mut max_steps = 10; + let mut step_count = 0; + let mut final_summary = String::new(); + let mut outcome = SubagentOutcome::Exhausted; + + while max_steps > 0 { + max_steps -= 1; + step_count += 1; + + let assistant_resp = match client.reply(&messages).await { + Ok(text) => text, + Err(e) => { + let err_msg = format!("Subagent inference failed: {}", e); + println!("{}", format!("{}│ [Error] {}", indent, err_msg).red()); + final_summary = err_msg; + outcome = SubagentOutcome::Failed; break; } + }; - let mut step_results = Vec::new(); - for (tool_name, tool_args) in &tool_calls { - println!( - "{}", - format!( - "{}│ [Step {}] Executing tool: {}", - indent, step_count, tool_name - ) - .yellow() - ); - - let tool_result = if tool_name == "invoke_subagent" { - if spec.depth >= 3 { - json!({"error": "Maximum subagent recursion depth (3) reached. You must complete the task directly without further delegation."}) - } else { - let child_role = tool_args - .get("role") - .and_then(Value::as_str) - .unwrap_or("Child Subagent"); - let child_prompt = tool_args - .get("prompt") - .and_then(Value::as_str) - .unwrap_or(""); - let child_spec = SubagentSpec { - id: format!("sub-{}-{}", Utc::now().timestamp(), generate_short_id()), - role: child_role.to_string(), - prompt: child_prompt.to_string(), - depth: spec.depth + 1, - parent_id: Some(spec.id.clone()), - }; - children_spawned.push(child_spec.id.clone()); - let child_res = execute_subagent(child_spec).await; - serde_json::to_value(&child_res).unwrap_or_default() - } + messages.push(json!({"role": "assistant", "content": assistant_resp.clone()})); + + let tool_calls = match extract_tool_calls(&assistant_resp) { + Ok(calls) => calls, + Err(error) => { + final_summary = error; + outcome = SubagentOutcome::Failed; + break; + } + }; + if tool_calls.is_empty() { + // Only a real, nonempty model reply is a final synthesis. + if assistant_resp.trim().is_empty() { + outcome = SubagentOutcome::Failed; + final_summary = "Subagent inference returned an empty reply.".to_string(); + } else { + outcome = SubagentOutcome::Completed; + final_summary = assistant_resp; + } + break; + } + + let mut step_results = Vec::new(); + for (tool_name, tool_args) in &tool_calls { + println!( + "{}", + format!( + "{}│ [Step {}] Executing tool: {}", + indent, step_count, tool_name + ) + .yellow() + ); + + let tool_result = if tool_name == "invoke_subagent" { + if spec.depth >= 3 { + json!({"error": "Maximum subagent recursion depth (3) reached. You must complete the task directly without further delegation."}) } else { - dispatch_tool(tool_name, tool_args) - }; + let child_role = tool_args + .get("role") + .and_then(Value::as_str) + .unwrap_or("Child Subagent"); + let child_prompt = tool_args + .get("prompt") + .and_then(Value::as_str) + .unwrap_or(""); + let child_spec = SubagentSpec { + id: format!("sub-{}-{}", Utc::now().timestamp(), generate_short_id()), + role: child_role.to_string(), + prompt: child_prompt.to_string(), + depth: spec.depth + 1, + parent_id: Some(spec.id.clone()), + }; + children_spawned.push(child_spec.id.clone()); + let child_res = execute_subagent(child_spec).await; + serde_json::to_value(&child_res).unwrap_or_default() + } + } else { + dispatch_tool(tool_name, tool_args) + }; - let result_str = serde_json::to_string(&tool_result).unwrap_or_default(); - messages.push(json!({ + let result_str = serde_json::to_string(&tool_result).unwrap_or_default(); + messages.push(json!({ "role": "user", "content": format!("\n{}\n", tool_name, result_str) })); - step_results.push(tool_result); - } - - steps_log.push(SubagentStepLog { - step: step_count, - assistant_response: assistant_resp, - tool_calls: tool_calls.clone(), - tool_results: step_results, - }); + step_results.push(tool_result); } - if final_summary.is_empty() { - final_summary = "Subagent completed execution loop (reached step limit).".to_string(); - } + steps_log.push(SubagentStepLog { + step: step_count, + assistant_response: assistant_resp, + tool_calls: tool_calls.clone(), + tool_results: step_results, + }); + } - let end_time = Utc::now().to_rfc3339(); - let platform = crate::platform::PlatformContext::detect(); - let transcript_dir = platform.home_dir.join("basecamp/sessions/subagents"); - let _ = fs::create_dir_all(&transcript_dir); - let transcript_path = transcript_dir.join(format!("{}.json", spec.id)); - - let transcript = SubagentTranscript { - spec: spec.clone(), - start_time, - end_time, - status: "completed".to_string(), - summary: final_summary.clone(), - steps: steps_log, - children: children_spawned.clone(), - }; + if outcome == SubagentOutcome::Exhausted { + final_summary = "Subagent exhausted its step limit without a final reply.".to_string(); + } - let _ = fs::write( - &transcript_path, - serde_json::to_string_pretty(&transcript).unwrap_or_default(), - ); + let end_time = Utc::now().to_rfc3339(); + let transcript_path = transcript_dir.join(format!("{}.json", spec.id)); + + let transcript = SubagentTranscript { + spec: spec.clone(), + start_time, + end_time, + status: outcome.status().to_string(), + summary: final_summary.clone(), + steps: steps_log, + children: children_spawned.clone(), + }; - // Emit comb onto the native hexagonal honeycomb message wall - if let Ok(store) = spark_hive::CombStore::open_default() { - let summary_text = if final_summary.chars().count() > 280 { - let trimmed: String = final_summary.chars().take(280).collect(); - format!("{}...", trimmed) - } else { - final_summary.clone() - }; - if let Ok(comb) = spark_hive::emit_subagent_comb( - &store, - &spec.role, - &summary_text, - spec.parent_id.as_deref(), - ) { - println!( - "{}", - format!( - "{} [Hive Lattice] Comb placed at ({}, {}) [id: {}]", - indent, comb.q, comb.r, comb.id - ) - .yellow() - ); - } + let persisted = serde_json::to_vec_pretty(&transcript) + .map_err(|e| e.to_string()) + .and_then(|bytes| { + fs::create_dir_all(transcript_dir) + .and_then(|_| fs::write(&transcript_path, bytes)) + .map_err(|e| e.to_string()) + }); + let (transcript_path, transcript_error) = match persisted { + Ok(()) => (Some(transcript_path.to_string_lossy().to_string()), None), + Err(error) => { + outcome = SubagentOutcome::Failed; + let message = format!("Subagent transcript write failed: {}", error); + eprintln!("{}", format!("{}│ [Error] {}", indent, message).red()); + (None, Some(message)) } + }; - println!( - "{}", - format!( - "{}└─ [Subagent {} Finished (depth: {}, steps: {}, children: {})]", - indent, - spec.id, - spec.depth, - step_count, - children_spawned.len() - ) - .green() - .bold() - ); + if outcome == SubagentOutcome::Completed { + emit_comb(&spec, &final_summary); + } + + let terminal_line = format!( + "{}└─ [Subagent {} {} (depth: {}, steps: {}, children: {})]", + indent, + spec.id, + outcome.status(), + spec.depth, + step_count, + children_spawned.len() + ); + let terminal_line = if outcome == SubagentOutcome::Completed { + terminal_line.green() + } else { + terminal_line.red() + }; + println!("{}", terminal_line.bold()); + + SubagentResult { + id: spec.id, + role: spec.role, + depth: spec.depth, + parent_id: spec.parent_id, + status: outcome.status().to_string(), + summary: final_summary, + transcript_path, + transcript_error, + steps_executed: step_count, + children_spawned, + } +} - SubagentResult { - id: spec.id, - role: spec.role, - depth: spec.depth, - parent_id: spec.parent_id, - status: "completed".to_string(), - summary: final_summary, - transcript_path: transcript_path.to_string_lossy().to_string(), - steps_executed: step_count, - children_spawned, +fn emit_completion_comb(spec: &SubagentSpec, final_summary: &str) { + let indent = " ".repeat(spec.depth); + if let Ok(store) = spark_hive::CombStore::open_default() { + let summary_text = if final_summary.chars().count() > 280 { + let trimmed: String = final_summary.chars().take(280).collect(); + format!("{}...", trimmed) + } else { + final_summary.to_string() + }; + if let Ok(comb) = spark_hive::emit_subagent_comb( + &store, + &spec.role, + &summary_text, + spec.parent_id.as_deref(), + ) { + println!( + "{}", + format!( + "{} [Hive Lattice] Comb placed at ({}, {}) [id: {}]", + indent, comb.q, comb.r, comb.id + ) + .yellow() + ); } - }) + } } pub async fn invoke_subagent_from_root(role: &str, prompt: &str) -> Value { @@ -401,6 +474,10 @@ pub fn format_subagents_tui() -> String { let role = item.get("role").and_then(Value::as_str).unwrap_or("?"); let depth = item.get("depth").and_then(Value::as_u64).unwrap_or(1); let steps = item.get("steps").and_then(Value::as_u64).unwrap_or(0); + let status = item + .get("status") + .and_then(Value::as_str) + .unwrap_or("unknown"); let parent = item .get("parent_id") .and_then(Value::as_str) @@ -419,8 +496,9 @@ pub fn format_subagents_tui() -> String { parent.dimmed() )); out.push_str(&format!( - "{} Steps: {} | Summary: {}\n", + "{} Status: {} | Steps: {} | Summary: {}\n", indent, + status, steps, preview.dimmed() )); @@ -433,6 +511,377 @@ pub fn format_subagents_tui() -> String { #[cfg(test)] mod tests { use super::*; + struct FakeChat(std::sync::Mutex>>); + + impl SubagentChat for FakeChat { + async fn reply(&self, _messages: &[Value]) -> Result { + self.0 + .lock() + .unwrap() + .pop_front() + .expect("unexpected model call") + } + } + + async fn run_replies( + replies: Vec>, + expected: &str, + steps: usize, + summary: &str, + ) { + let client = FakeChat(std::sync::Mutex::new(replies.into())); + run_chat(&client, expected, steps, summary).await; + } + + async fn run_chat(client: &impl SubagentChat, expected: &str, steps: usize, summary: &str) { + let scratch = tempfile::tempdir().unwrap(); + let emissions = std::cell::RefCell::new(Vec::new()); + let result = execute_subagent_with( + SubagentSpec { + id: "outcome-test".into(), + role: "Verifier".into(), + prompt: "Test outcome classification".into(), + depth: 3, + parent_id: Some("test-parent".into()), + }, + client, + scratch.path(), + |_, summary| emissions.borrow_mut().push(summary.to_string()), + ) + .await; + let transcript: SubagentTranscript = serde_json::from_str( + &fs::read_to_string(result.transcript_path.as_ref().unwrap()).unwrap(), + ) + .unwrap(); + let (tool_result, success) = + crate::tools::subagent_tool_result(serde_json::to_value(&result).unwrap()); + assert_eq!(result.status, expected); + assert_eq!(transcript.status, expected); + assert_eq!(tool_result["status"], expected); + assert_eq!(success, expected == "completed"); + assert_eq!( + emissions.borrow().len(), + usize::from(expected == "completed") + ); + assert_eq!(result.steps_executed, steps); + assert!(result.transcript_error.is_none()); + assert!(result.summary.contains(summary)); + assert_eq!(transcript.summary, result.summary); + } + + #[tokio::test] + async fn inference_error_is_failed() { + run_replies( + vec![Err("injected inference error".into())], + "failed", + 1, + "injected inference error", + ) + .await; + } + + #[tokio::test] + async fn ten_tool_replies_are_exhausted() { + let tool_reply = "{\"name\":\"invoke_subagent\",\"arguments\":{}}"; + run_replies( + vec![Ok(tool_reply.into()); 10], + "exhausted", + 10, + "step limit", + ) + .await; + } + + #[tokio::test] + async fn final_reply_is_completed() { + run_replies( + vec![Ok("Verified final synthesis.".into())], + "completed", + 1, + "Verified final synthesis.", + ) + .await; + } + + #[tokio::test] + async fn empty_reply_is_failed() { + run_replies(vec![Ok(" \n\t".into())], "failed", 1, "empty reply").await; + } + + #[tokio::test] + async fn error_after_tool_reply_is_failed() { + run_replies( + vec![ + Ok("{\"name\":\"invoke_subagent\",\"arguments\":{}}".into()), + Err("injected inference error after tools".into()), + ], + "failed", + 2, + "injected inference error after tools", + ) + .await; + } + + #[tokio::test] + async fn final_reply_on_last_turn_is_completed() { + let tool_reply = "{\"name\":\"invoke_subagent\",\"arguments\":{}}"; + let mut replies = vec![Ok(tool_reply.into()); 9]; + replies.push(Ok("Final synthesis on the last permitted turn.".into())); + run_replies(replies, "completed", 10, "last permitted turn").await; + } + + async fn persistence_failure(fail_directory_creation: bool) { + for reply in [ + Ok::("Final synthesis.".into()), + Err("injected inference error".into()), + ] { + let scratch = tempfile::tempdir().unwrap(); + let transcript_dir = scratch.path().join("transcripts"); + if fail_directory_creation { + fs::write(&transcript_dir, "not a directory").unwrap(); + } else { + fs::create_dir_all(transcript_dir.join("outcome-test.json")).unwrap(); + } + let summary = match &reply { + Ok(text) => text.clone(), + Err(error) => error.clone(), + }; + let client = FakeChat(std::sync::Mutex::new(vec![reply].into())); + let emissions = std::cell::Cell::new(0); + let result = execute_subagent_with( + SubagentSpec { + id: "outcome-test".into(), + role: "Verifier".into(), + prompt: "Test persistence failure".into(), + depth: 3, + parent_id: None, + }, + &client, + &transcript_dir, + |_, _| emissions.set(emissions.get() + 1), + ) + .await; + assert_eq!(result.status, "failed"); + assert!(result.transcript_path.is_none()); + assert!(result + .transcript_error + .as_ref() + .unwrap() + .contains("transcript write failed")); + assert!(result.summary.contains(&summary)); + let (value, success) = + crate::tools::subagent_tool_result(serde_json::to_value(&result).unwrap()); + assert!(value["transcript_path"].is_null()); + assert!(!success); + assert_eq!(emissions.get(), 0); + } + } + + #[tokio::test] + async fn round2_persistence_directory_failure() { + persistence_failure(true).await; + } + + #[tokio::test] + async fn round2_persistence_file_failure() { + persistence_failure(false).await; + } + + #[tokio::test] + async fn round2_malformed_tool_call_is_failed() { + run_replies( + vec![Ok("{\"name\":".into())], + "failed", + 1, + "Malformed tool call", + ) + .await; + } + + #[tokio::test] + async fn round3_unclosed_named_json_fence_is_failed() { + run_replies( + vec![Ok( + "```json\n{\"name\":\"goal\",\"arguments\":{\"action\":\"list\"}}".into(), + )], + "failed", + 1, + "Malformed tool call", + ) + .await; + } + + #[tokio::test] + async fn round3_unclosed_spaced_tool_fence_is_failed() { + for prefix in [" tool_call", "\n tool_call", "\njson"] { + run_replies( + vec![Ok(format!( + "```{prefix}\n{{\"name\":\"goal\",\"arguments\":{{}}}}" + ))], + "failed", + 1, + "Malformed tool call", + ) + .await; + } + } + + async fn remote_fixture(body: String) -> (ChatClient, tokio::task::JoinHandle<()>) { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)) + .await + .unwrap(); + let endpoint = format!( + "http://{}/v1/chat/completions", + listener.local_addr().unwrap() + ); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + let mut bytes = [0; 1024]; + loop { + let count = socket.read(&mut bytes).await.unwrap(); + assert_ne!(count, 0); + request.extend_from_slice(&bytes[..count]); + if let Some(pos) = request.windows(4).position(|w| w == b"\r\n\r\n") { + let headers = std::str::from_utf8(&request[..pos]).unwrap(); + let length: usize = headers + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse().unwrap()) + }) + .unwrap(); + if request.len() >= pos + 4 + length { + break; + } + } + } + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), body + ); + socket.write_all(response.as_bytes()).await.unwrap(); + socket.shutdown().await.unwrap(); + }); + ( + ChatClient::new(Some(endpoint), Some("test-model".into())), + server, + ) + } + + fn remote_body(reason: Option<&str>, done: bool) -> String { + let mut body = format!( + "data: {}\n\n", + json!({"choices":[{"delta":{"content":"Partial final synthesis."}}]}) + ); + if let Some(reason) = reason { + body.push_str(&format!( + "data: {}\n\n", + json!({"choices":[{"delta":{},"finish_reason":reason}]}) + )); + } + if done { + body.push_str("data: [DONE]\n\n"); + } + body + } + + #[tokio::test] + async fn round2_remote_eof_is_failed() { + let (client, server) = remote_fixture(remote_body(None, false)).await; + run_chat(&client, "failed", 1, "before [DONE]").await; + server.await.unwrap(); + } + + #[tokio::test] + async fn round2_remote_length_is_failed() { + let (client, server) = remote_fixture(remote_body(Some("length"), true)).await; + run_chat(&client, "failed", 1, "length").await; + server.await.unwrap(); + } + + #[tokio::test] + async fn remote_stop_is_completed() { + let (client, server) = remote_fixture(remote_body(Some("stop"), true)).await; + run_chat(&client, "completed", 1, "Partial final synthesis.").await; + server.await.unwrap(); + } + + struct NativeChat(aien_runtime::client::AienRuntimeClient); + impl SubagentChat for NativeChat { + async fn reply(&self, _messages: &[Value]) -> Result { + self.0.stream_turn(Vec::new(), 1024, 0.2).await + } + } + + async fn native_fixture( + finish: bool, + ) -> (tempfile::TempDir, NativeChat, tokio::task::JoinHandle<()>) { + use aien_runtime::control::ControlResponse; + use tokio::io::{AsyncBufReadExt, AsyncWriteExt}; + let scratch = tempfile::tempdir().unwrap(); + let path = scratch.path().join("runtime.sock"); + let listener = tokio::net::UnixListener::bind(&path).unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = String::new(); + tokio::io::BufReader::new(&mut socket) + .read_line(&mut request) + .await + .unwrap(); + serde_json::from_str::(&request).unwrap(); + let delta = ControlResponse::TurnDelta { + text: "Partial final synthesis.".into(), + }; + socket + .write_all(format!("{}\n", serde_json::to_string(&delta).unwrap()).as_bytes()) + .await + .unwrap(); + if finish { + let terminal = ControlResponse::TurnFinished { + text: "Complete native synthesis.".into(), + total_tokens: 4, + generation_record: Some(9), + }; + socket + .write_all( + format!("{}\n", serde_json::to_string(&terminal).unwrap()).as_bytes(), + ) + .await + .unwrap(); + } + socket.shutdown().await.unwrap(); + }); + let client = NativeChat(aien_runtime::client::AienRuntimeClient::new(&path)); + (scratch, client, server) + } + + #[tokio::test] + async fn round2_native_eof_is_failed() { + let (_scratch, client, server) = native_fixture(false).await; + run_chat(&client, "failed", 1, "before the turn finished").await; + server.await.unwrap(); + } + + #[tokio::test] + async fn native_finished_is_completed() { + let (_scratch, client, server) = native_fixture(true).await; + run_chat(&client, "completed", 1, "Complete native synthesis.").await; + server.await.unwrap(); + } + + #[test] + fn tool_flag_rejects_missing_and_unknown_status() { + for value in [ + json!({}), + json!({"status": "unknown"}), + json!({"error": "serialization failed"}), + ] { + assert!(!crate::tools::subagent_tool_result(value).1); + } + } #[test] fn test_subagent_spec_serialization() { diff --git a/crates/aien-cli/src/tools.rs b/crates/aien-cli/src/tools.rs index 1c104e8a..2b03a6a7 100644 --- a/crates/aien-cli/src/tools.rs +++ b/crates/aien-cli/src/tools.rs @@ -294,7 +294,7 @@ pub fn dispatch_tool_with(name: &str, args: &Value, ctx: &crate::approval::GateC let ok = res.get("status").and_then(Value::as_str) == Some("ok"); (res, ok) } - "goal" => (crate::goals::goals_dispatch_tool(args), true), + "goal" => goal_tool_result(crate::goals::goals_dispatch_tool(args)), "cortex" => { let res = tokio::task::block_in_place(|| { tokio::runtime::Handle::current() @@ -377,7 +377,7 @@ pub fn dispatch_tool_with(name: &str, args: &Value, ctx: &crate::approval::GateC tokio::runtime::Handle::current() .block_on(crate::subagents::invoke_subagent_from_root(role, prompt)) }); - (res, true) + subagent_tool_result(res) } "subagent" | "subagents" => { let action = args.get("action").and_then(Value::as_str).unwrap_or("list"); @@ -427,6 +427,16 @@ pub fn dispatch_tool_with(name: &str, args: &Value, ctx: &crate::approval::GateC final_res } +fn goal_tool_result(result: Value) -> (Value, bool) { + let success = result["status"].as_str() == Some("ok"); + (result, success) +} + +pub(crate) fn subagent_tool_result(res: Value) -> (Value, bool) { + let success = res.get("status").and_then(Value::as_str) == Some("completed"); + (res, success) +} + /// Persist a content-addressed, secret-free receipt for every tool effect. /// Arguments and results are hashed, never copied into the receipt. /// Writes one effect receipt under `$AIEN_PROVENANCE_DIR` and returns its path @@ -1133,6 +1143,17 @@ fn exec_ask_question(question: &str, options: Option<&Vec>) -> (Value, bo mod tests { use super::*; + #[test] + fn round3_goal_tool_failure_flag_is_false() { + for result in [ + json!({"status":"error","error":"write goals failed"}), + json!({"error":"denied"}), + ] { + assert!(!goal_tool_result(result).1); + } + assert!(goal_tool_result(json!({"status":"ok"})).1); + } + // Tests that install the process-wide checkpoint session must serialize. static CHECKPOINT_SESSION_TEST: std::sync::Mutex<()> = std::sync::Mutex::new(()); struct StopCheckpointSession; diff --git a/crates/aien-cli/tests/recovery_matrix_test.rs b/crates/aien-cli/tests/recovery_matrix_test.rs index d3bd4664..0bb67d86 100644 --- a/crates/aien-cli/tests/recovery_matrix_test.rs +++ b/crates/aien-cli/tests/recovery_matrix_test.rs @@ -1083,17 +1083,43 @@ fn home_lineage(r: &Rig) -> [u8; 32] { /// One generation by the daemon; returns its generation record id. fn generate(r: &Rig) -> u64 { let client = AienRuntimeClient::new(r.sock()); - let (_, rec) = - r.rt.block_on(client.stream_turn_recorded( - vec![ChatTurn { - role: "user".into(), - content: "hi".into(), - }], - 4, - 0.0, - )) - .expect("turn"); - rec.expect("the daemon wrote a generation record") + let result = r.rt.block_on(client.stream_turn_recorded( + vec![ChatTurn { + role: "user".into(), + content: "hi".into(), + }], + 4, + 0.0, + )); + match result { + Ok((_, Some(id))) => id, + Ok((_, None)) => panic!("the daemon wrote no generation record"), + Err(error) => { + // This fixture deliberately caps its generation. Incomplete output + // is not a successful turn, but its daemon-owned record still exists. + assert!(error.contains("max_tokens"), "{error}"); + let report = + r.rt.block_on(client.send_command( + aien_runtime::control::ControlCommand::ComposeRecall { + ids: vec![], + prefix: None, + }, + )) + .expect("recall evidence"); + let aien_runtime::control::ControlResponse::ComposeRecalled(report) = report else { + panic!("recall response") + }; + report + .host + .iter() + .rev() + .find_map(|record| { + let value: Value = serde_json::from_str(record.text.as_deref()?).ok()?; + (record.verified && value["generation"] == 1).then_some(record.id) + }) + .expect("the daemon retained generation evidence") + } + } } fn record_text(r: &Rig, id: u64) -> Value { diff --git a/crates/aien-runtime/src/client.rs b/crates/aien-runtime/src/client.rs index d09fec7f..a7bdd615 100644 --- a/crates/aien-runtime/src/client.rs +++ b/crates/aien-runtime/src/client.rs @@ -156,6 +156,9 @@ impl AienRuntimeClient { /// [`Self::stream_turn`] plus the compose ledger id of the daemon's /// generation record for the turn (`None` = the daemon wrote no record). + /// Only a normal StopToken finish succeeds. Updated servers return Error + /// for limited/aborted/preempted turns after recording generation evidence; + /// callers needing that evidence must use ComposeRecall, not infer success. pub async fn stream_turn_recorded( &self, messages: Vec, @@ -232,11 +235,7 @@ impl AienRuntimeClient { } } } - if finished.is_empty() { - Err("native runtime closed the socket before the turn finished".into()) - } else { - Ok((finished, None)) - } + Err("native runtime closed the socket before the turn finished".into()) } pub async fn shutdown(&self) -> Result<(), String> { diff --git a/crates/aien-runtime/src/control.rs b/crates/aien-runtime/src/control.rs index 20a858ae..8726ba30 100644 --- a/crates/aien-runtime/src/control.rs +++ b/crates/aien-runtime/src/control.rs @@ -90,7 +90,8 @@ pub enum ControlCommand { GetRuntimeStatus, Shutdown, /// One operator turn on the in-process PR #68 spine. The server streams - /// `TurnDelta` lines and finishes with `TurnFinished`. + /// `TurnDelta` lines, then `TurnFinished` only for StopToken; token limits, + /// aborts and preemption terminate with a reason-bearing `Error`. StreamTurn { messages: Vec, max_tokens: usize, @@ -379,6 +380,7 @@ pub enum ControlResponse { TurnDelta { text: String, }, + /// A normally stopped answer, never a token-limited/aborted/preempted turn. TurnFinished { text: String, total_tokens: usize, diff --git a/crates/aien-runtime/src/server.rs b/crates/aien-runtime/src/server.rs index d297fcd7..6b3844b9 100644 --- a/crates/aien-runtime/src/server.rs +++ b/crates/aien-runtime/src/server.rs @@ -854,14 +854,7 @@ async fn stream_turn( temperature: f32, rec: RecordCtx, ) { - let RecordCtx { - compose, - identity, - started, - request_id, - operation_id, - } = rec; - let (tokenizer, mut events, prompt_ids) = + let (tokenizer, events, prompt_ids) = match submit_turn(spine, tokenizer, messages, max_tokens, temperature, "").await { Ok(x) => x, Err(error) => { @@ -870,6 +863,25 @@ async fn stream_turn( } }; + forward_turn(writer, tokenizer, events, prompt_ids, rec).await; +} + +// Shared production event-to-wire path. Tests inject scheduler events, never +// fabricated terminal responses, so they exercise the producer and client. +async fn forward_turn( + writer: &mut tokio::net::unix::OwnedWriteHalf, + tokenizer: ChatTokenizer, + mut events: tokio::sync::mpsc::UnboundedReceiver, + prompt_ids: Vec, + rec: RecordCtx, +) { + let RecordCtx { + compose, + identity, + started, + request_id, + operation_id, + } = rec; let mut produced = Vec::new(); let mut text = String::new(); loop { @@ -917,6 +929,19 @@ async fn stream_turn( }, ) .await; + // Retain the generation evidence even for an incomplete answer. + // Existing clients already fail closed on the Error response. + if !matches!(finish_reason, aien_inference_abi::FinishReason::StopToken) { + let _ = write_response( + writer, + &ControlResponse::Error(format!( + "native turn did not complete: {}", + finish_reason_label(&finish_reason) + )), + ) + .await; + return; + } let _ = write_response( writer, &ControlResponse::TurnFinished { @@ -1287,3 +1312,93 @@ mod generation_record_tests { assert_eq!(got, None); } } + +#[cfg(test)] +mod completion_tests { + use super::*; + use aien_inference_abi::FinishReason; + + async fn event_to_client(reason: FinishReason) -> Result<(String, Option), String> { + let scratch = tempfile::tempdir().unwrap(); + let path = scratch.path().join("finish.sock"); + let listener = UnixListener::bind(&path).unwrap(); + let server = tokio::spawn(async move { + let (socket, _) = listener.accept().await.unwrap(); + let (reader, mut writer) = socket.into_split(); + let mut request = String::new(); + BufReader::new(reader) + .read_line(&mut request) + .await + .unwrap(); + serde_json::from_str::(&request).unwrap(); + let tokenizer = ChatTokenizer::from_bytes(br#"{"version":"1.0","truncation":null,"padding":null,"added_tokens":[],"normalizer":null,"pre_tokenizer":{"type":"Whitespace"},"post_processor":null,"decoder":null,"model":{"type":"WordLevel","unk_token":"","vocab":{"":0,"partial":100}}}"#).unwrap(); + let (sender, events) = tokio::sync::mpsc::unbounded_channel(); + let seq_id = aien_scheduler::SequenceId { + slot: 0, + generation: 1, + }; + sender + .send(CompletionEvent::Token { seq_id, token: 100 }) + .unwrap(); + sender + .send(CompletionEvent::Finished { + seq_id, + finish_reason: reason, + total_tokens: 1, + decoding: None, + ops: None, + }) + .unwrap(); + forward_turn( + &mut writer, + tokenizer, + events, + vec![0], + RecordCtx { + compose: None, + identity: None, + started: DaemonStart::now(), + request_id: 1, + operation_id: 1, + }, + ) + .await; + }); + let result = crate::client::AienRuntimeClient::new(&path) + .stream_turn_recorded(Vec::new(), 10, 0.0) + .await; + server.await.unwrap(); + result + } + + #[tokio::test] + async fn round3_length_limit_is_not_complete() { + let error = event_to_client(FinishReason::LengthLimit) + .await + .expect_err("limited turn"); + assert!(error.contains("max_tokens"), "{error}"); + } + + #[tokio::test] + async fn round3_aborted_is_not_complete() { + let error = event_to_client(FinishReason::Aborted) + .await + .expect_err("aborted turn"); + assert!(error.contains("aborted"), "{error}"); + } + + #[tokio::test] + async fn round3_preempted_is_not_complete() { + let error = event_to_client(FinishReason::Preempted) + .await + .expect_err("preempted turn"); + assert!(error.contains("preempted"), "{error}"); + } + + #[tokio::test] + async fn round3_stop_token_is_complete() { + let (text, record) = event_to_client(FinishReason::StopToken).await.unwrap(); + assert_eq!(text, "partial"); + assert_eq!(record, None); + } +} diff --git a/crates/aien-runtime/tests/generation_record_test.rs b/crates/aien-runtime/tests/generation_record_test.rs index 02d9e60f..f36a9da0 100644 --- a/crates/aien-runtime/tests/generation_record_test.rs +++ b/crates/aien-runtime/tests/generation_record_test.rs @@ -88,6 +88,32 @@ async fn start_with(identity: Option, tokenizer: ChatTokenizer) - start_on(identity, tokenizer, MockInferenceBackend::new(1)).await } +// Success-path evidence fixtures must actually stop, not merely reach a cap. +struct EosBackend(B); +#[async_trait::async_trait] +impl AienInferenceBackend for EosBackend { + async fn load_model(&mut self, config: &ModelConfig) -> Result<(), String> { + self.0.load_model(config).await + } + async fn execute_step( + &mut self, + batch: &ScheduledBatch, + ) -> Result<(Vec, StepMetrics), String> { + let (mut outputs, metrics) = self.0.execute_step(batch).await?; + for output in &mut outputs { + if let DecodeOutput::Token { token_id, .. } = output { + if *token_id == 101 { + *token_id = 2; + } + } + } + Ok((outputs, metrics)) + } + fn take_decode_observation(&mut self, request_id: u64) -> Option { + self.0.take_decode_observation(request_id) + } +} + async fn start_on( identity: Option, tokenizer: ChatTokenizer, @@ -122,7 +148,7 @@ async fn start_on( if let Some(id) = identity { server.set_model_identity(id); } - let handle = tokio::spawn(async move { server.run(backend).await }); + let handle = tokio::spawn(async move { server.run(EosBackend(backend)).await }); let client = AienRuntimeClient::new(&socket); for _ in 0..200 { if client.is_alive().await { @@ -192,13 +218,13 @@ fn sha(b: &[u8]) -> String { hex(&Sha256::digest(b)) } -/// The mock backend only emits tokens 100 and 101, which the toy vocabulary -/// spells x100 and x101. +/// The stopping mock emits ordinary x100 (100), then EOS (2). +/// This toy tokenizer does not register special added tokens, so both decode. fn ids_of(text: &str) -> Vec { text.split_whitespace() .map(|w| match w { "x100" => 100, - "x101" => 101, + "" => 2, other => panic!("unexpected word {other:?} in {text:?}"), }) .collect() @@ -233,10 +259,7 @@ async fn record_carries_the_digests_of_the_turn() { assert_eq!(r["output_token_ids_sha256"], token_ids_sha256(&out)); assert_eq!(r["output_tokens"], out.len()); assert!(r["total_tokens"].as_u64().unwrap() > 0); - assert!(matches!( - r["finish_reason"].as_str(), - Some("eos" | "max_tokens") - )); + assert_eq!(r["finish_reason"], "eos"); assert_eq!(r["daemon"]["pid"], std::process::id()); assert!(r["daemon"]["started_unix_ms"].as_str().unwrap().len() > 8); // sc#294: the mock backend observes nothing, so the record makes no @@ -419,3 +442,39 @@ async fn record_states_the_decoding_the_backend_reported() { ); d.stop().await; } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] +async fn capped_turn_is_refused_but_its_evidence_is_retained() { + let _home = home_guard::home_slot(); + let _g = ONE_HOME.lock().await; + let d = start(Some(identity())).await; + let before = d.records().await; + let error = d + .client + .stream_turn_recorded(user("hello"), 1, 0.0) + .await + .expect_err("a token cap is not completion"); + assert!(error.contains("max_tokens"), "{error}"); + assert_eq!(d.records().await, before + 1); + let ControlResponse::ComposeRecalled(report) = d.recall(vec![]).await else { + panic!("recall") + }; + let record = report + .host + .iter() + .rev() + .find_map(|record| { + let value: Value = serde_json::from_str(record.text.as_deref()?).ok()?; + (value["generation"] == 1).then_some((record, value)) + }) + .expect("generation evidence"); + assert!(record.0.verified); + assert_eq!(record.1["finish_reason"], "max_tokens"); + assert_eq!(record.1["output_text_sha256"], sha(b"x100")); + assert_eq!( + record.1["output_token_ids_sha256"], + token_ids_sha256(&[100]) + ); + d.stop().await; +} diff --git a/crates/aien-runtime/tests/warm_up_before_serving_test.rs b/crates/aien-runtime/tests/warm_up_before_serving_test.rs index 3fed34da..6fc8bf40 100644 --- a/crates/aien-runtime/tests/warm_up_before_serving_test.rs +++ b/crates/aien-runtime/tests/warm_up_before_serving_test.rs @@ -45,7 +45,8 @@ use std::time::{Duration, Instant}; /// first step the backend runs. const FIRST_STEP_COST: Duration = Duration::from_millis(600); -/// Word-level tokenizer: the mock emits ids 100 and 101, decoded as x100/x101. +/// Word-level tokenizer: RecordingBackend maps mock id 101 to EOS (2), so +/// served turns stop normally rather than masquerading as successful caps. fn toy_tokenizer() -> ChatTokenizer { let json = r#"{"version":"1.0","truncation":null,"padding":null,"added_tokens":[], "normalizer":null,"pre_tokenizer":{"type":"Whitespace"},"post_processor":null, @@ -82,7 +83,18 @@ impl AienInferenceBackend for RecordingBackend { if self.log.lock().unwrap().is_empty() { std::thread::sleep(FIRST_STEP_COST); } - let out = self.inner.execute_step(batch).await; + let mut out = self.inner.execute_step(batch).await; + // A served success must stop normally; the original never-ending mock + // reached its cap and must now be refused by StreamTurn. + if let Ok((outputs, _)) = &mut out { + for output in outputs { + if let DecodeOutput::Token { token_id, .. } = output { + if *token_id == 101 { + *token_id = 2; + } + } + } + } self.log.lock().unwrap().push(StepRecord { prefill: batch .prefill_requests diff --git a/docs/DAEMON_GENERATION_RECORD.md b/docs/DAEMON_GENERATION_RECORD.md index fe5ba7f8..0bb6bb22 100644 --- a/docs/DAEMON_GENERATION_RECORD.md +++ b/docs/DAEMON_GENERATION_RECORD.md @@ -12,10 +12,16 @@ have to take the run driver's word for "this text came from this model". daemon passes both to the server (`set_model_identity`). The same digests are in the "checkpoint loaded" log line; a sharded checkpoint also logs a `CHECKPOINT_SHARDS` line (below). -2. When a `StreamTurn` finishes, and the compose ledger is open, the daemon - appends one record to the ledger and returns its id in - `TurnFinished.generation_record` (optional field; absent when there is no - record, so older clients keep working). +2. On every `StreamTurn` Finished event, and when the compose ledger is open, + the daemon appends one record **before classifying completion**. Only + `StopToken` sends `TurnFinished`, whose optional `generation_record` id is + absent when no record was written. `LengthLimit`, `Aborted` and `Preempted` + send the existing `Error` response with `max_tokens`, `aborted` or `preempted` + in its text. Their records remain in the ledger and can be retrieved with + `ComposeRecall`; the Error response does not contain a structured record id. + No wire field was added: older clients already treat Error as failure. + An unchanged older daemon can still misclassify these reasons; this source + change is not a deployment claim. ## The record @@ -29,7 +35,7 @@ An `effect`-class host note whose JSON has the marker field `generation`: | `tokenizer_sha256`, `tokenizer_path` | the loaded tokenizer file's digest and path | | `prompt_ids_sha256` | `token_ids_sha256` of the submitted prompt token ids | | `output_token_ids_sha256` | same hash over the generated token ids | -| `output_text_sha256` | sha256 of the exact `text` returned in `TurnFinished` | +| `output_text_sha256` | sha256 of the exact accumulated text (returned in `TurnFinished` for a normal stop, or emitted as deltas before an incomplete-turn Error) | | `total_tokens`, `output_tokens` | token count the engine reported; generated tokens | | `finish_reason` | `eos`, `max_tokens`, `aborted` or `preempted` | | `decoding` | how the backend chose the output tokens (below); ABSENT when the backend did not report it | @@ -193,15 +199,15 @@ operation_id as the client's claims. ## Timing -The record is written before `TurnFinished` is sent, and the write waits for -the compose home lock. A running compose task holds that lock, so a turn that -finishes meanwhile can have its `TurnFinished` delayed until the task releases -it. There is no deadlock: the compose task's own model calls (`generate_text`) -write no record and take no home lock. +The record is written before either terminal response (`TurnFinished` or an +incomplete-turn `Error`), and the write waits for the compose home lock. A +running compose task holds that lock, so either response can be delayed until +the task releases it. There is no deadlock: the compose task's own model calls +(`generate_text`) write no record and take no home lock. ## No record means no claim -The turn still succeeds, with `generation_record` absent, when: +A normally stopped turn still succeeds, with `generation_record` absent, when: - there is no compose ledger; - the daemon has no model identity (a stub run, or the reference-weights ```