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.
Safe tool calls run side by side; oversized tool output is saved to a file
merged1ec0d89208beccb8 #670 · opened 2026-10-18 20:41 UTC · closed 2026-10-31 02:33 UTC · merged 2026-10-31 02:33 UTC
Imported from GitHub aien-dev/aien-sovereign-core-mv#670, by drakestapleton
Base 0998462ede94a92570457262a478cade49ea6816 · Head 44e015baba1ba1ca0f649c5f2d4e4c6b010af860
Merged on GitHub as 9612b7787fcca2463b1b9737a7faebe91a72552a; reachable from main 007ac4ac5ee5edc6f79f411b1706752293604044 (observed 2026-11-18T16:35:49Z)
drakestapleton wrote on 2026-10-18 20:41 UTC
Part of the Allen program (aien-dev/aien-architecture#269), phase 1. Refs #666. Its stack bases #668 and #669 are on main (7a258a0a); this branch now carries only the #666 change, merged with main 0998462e.
What changes for Allen
One reply's tool calls are planned before they run:
reads (view, list, search) run together, up to 8, even on the same file;
a write never runs beside a call on an overlapping path;
shell commands, unknown tools and any call the safety engine would ask the operator about run alone, so approval prompts never interleave.
Conflicting calls keep the order Allen asked for. Results come back in call order. Every request of a step is in the journal (#665) before any of them runs.
A tool result bigger than its share of the model's window is written whole to basecamp/sessions/<id>-spill/, and Allen gets a 40/60 head-and-tail preview plus the path:
per result: 15 percent of the window (floor 8,000, cap 100,000 characters);
per reply: 30 percent (floor 16,000, cap 200,000), largest first.
File reads are never spilled.
diff --git a/.crumb b/.crumb
index 5416ba49..482b4b95 100644
--- a/.crumb
+++ b/.crumb
@@ -65,49 +65,49 @@
"children": [
{
"digest": "e5a81587d398cafcc737337c51428c09697768967eea61386a6ab34f7f871903",
- "last_commit": "e8cc3aa0",
+ "last_commit": "6bbe2ec2",
"name": "crates/aien-allen",
"purpose": "ALLEN identity gate: resolve-only subject check, host pin record, deployment record (ADR 0035). "
},
{
"digest": "a6f60499665540ddd49ad3122d016232b15d9cc878cb68febb725cd711dfbb6d",
- "last_commit": "e8cc3aa0",
+ "last_commit": "b9b52f9c",
"name": "crates/aien-allen-memory",
"purpose": "ALLEN scoped memory store: scopes enforced at recall, inspect/correct/export, key-destroying for"
},
{
"digest": "3b65ec8698bac001b1d2aef39c1fce13a3475280186147af40a319212ed76d42",
- "last_commit": "e8cc3aa0",
+ "last_commit": "b9b52f9c",
"name": "crates/aien-allen-profile",
"purpose": "ALLEN persona profile v1: versioned, user-editable profile bound to the engaged ALLEN identity; "
},
{
- "digest": "a2ac5edc339c6011aafd47acc096584165fa05af1c164d464c77d928add1ecc4",
- "last_commit": "966d09f2",
+ "digest": "37d0e652616039490bbcd5e1b958d2001414fee63642859f16cad4b0a1df615a",
+ "last_commit": "2539fb55",
"name": "crates/aien-cli",
"purpose": ""
},
{
"digest": "3a331fee49e858953c344a75e26558ac2288bca4b335eed2f2702dfd77379e8e",
- "last_commit": "e728371b",
+ "last_commit": "",
"name": "crates/aien-heartbeat",
"purpose": "Expert Heartbeat H1 (aienix#4): fixed-slot versioned ring streaming MoE expert weights from NVMe"
},
{
"digest": "246e54412a28d811dc38af14bb943890fbafd85f55864c2468a04e6ea698062e",
- "last_commit": "e8cc3aa0",
+ "last_commit": "8cca8020",
"name": "crates/aien-scheduler/src/bin",
"purpose": ""
},
{
"digest": "a684b3e7bb1d356b05a499af3962db5b12b37d565bf9bfdf31de6188af457131",
- "last_commit": "53beb962",
+ "last_commit": "afbbd804",
"name": "crates/spark-cockpit-rs",
"purpose": ""
},
{
"digest": "f84780fa891f458ab56b40432a7ca3666e01783639585cdd282b73d508c1a038",
- "last_commit": "0a4e42b1",
+ "last_commit": "fe3677c3",
"name": "scripts",
"purpose": ""
},
@@ -119,20 +119,20 @@
},
{
"digest": "f3c208d8b9bdd9ad5382af5f1fe9bb2ed9c971a831a017d636c13aaf0e7e1b9e",
- "last_commit": "6f25b2bb",
+ "last_commit": "1db20d44",
"name": "tools/aien-local-ci",
"purpose": "Local CI sandbox exec contract (C8), aien-run user/caches install, Forgejo trigger hook, health "
}
],
- "children_root": "sha256:11667569f33ec3ce2a92661f04fa07e1e1757b2b1d83787eb82fe3aa44a73a00",
- "compiled_at": "2026-10-30T23:24:42Z",
+ "children_root": "sha256:9336db0a6669d32e68cee16900dfe9fc9e27304c00dc48daee6578317bf57d2c",
+ "compiled_at": "2026-10-31T02:10:57Z",
"compiler": "crumb-compile/1",
- "digest": "sha256:a1d9f37a63cca2ef7bef92fcce27a0b148bfe762509335291af68d04342b7753",
+ "digest": "sha256:6e1f332adae0996a056dffef7aa64b9fe31122183eef22ba9ec5f22798e3a417",
"evidence_files": 3602,
"evidence_root": "sha256:1b8069934a4cc67803874ebd2ad5de32671fae5ccce1a3ea70aeb532fe8ea86b",
- "files": 8114,
- "generated_at_commit": "843092c805a32c135abfe955f735af0c39a3e285",
- "source_tree": "sha256:efc3b4611596268608d8b1c6d7501026b5d3fa111d2a1736403fca178e61e109"
+ "files": 8117,
+ "generated_at_commit": "84ff89f7229a85628fdc7be5c30bb91cab039b10",
+ "source_tree": "sha256:23e8f4e4c64c7b3b4485effccd7fcf0ae368029fae4434c3634b091960b52487"
}
},
"history": [],
diff --git a/crates/aien-cli/.crumb b/crates/aien-cli/.crumb
index 8122513a..b6aa5bc4 100644
--- a/crates/aien-cli/.crumb
+++ b/crates/aien-cli/.crumb
@@ -34,21 +34,21 @@
"generated": {
"children": [
{
- "digest": "e3eb2b311e33b4191bcf709dc56c71c4c98bca33271dfd7b2683bc5855f4536a",
- "last_commit": "b91f018a",
+ "digest": "f2a696fda66f200dae534b5880cf13cb6f621cc6ff7f340d6fedfd40bc260132",
+ "last_commit": "2539fb55",
"name": "src",
"purpose": ""
}
],
- "children_root": "sha256:50e9d9153352363e0f19b0c6ef3dd3ac9033e485961f20234184ebb1c5ab689f",
- "compiled_at": "2026-10-30T14:49:12Z",
+ "children_root": "sha256:1eaa0fe902763b6926f0de26d1e9df0b150e780aab2542c467bf6e4ace91f501",
+ "compiled_at": "2026-10-31T02:10:57Z",
"compiler": "crumb-compile/1",
- "digest": "sha256:a2ac5edc339c6011aafd47acc096584165fa05af1c164d464c77d928add1ecc4",
+ "digest": "sha256:37d0e652616039490bbcd5e1b958d2001414fee63642859f16cad4b0a1df615a",
"evidence_files": 0,
"evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
- "files": 49,
- "generated_at_commit": "b91f018a2ea80fc1e9002a2a98a702c88a4a845a",
- "source_tree": "sha256:50ca02527a185c20d8f0f390bfa994076000ebbf6e24ce1cfacedb0e922c2869"
+ "files": 52,
+ "generated_at_commit": "84ff89f7229a85628fdc7be5c30bb91cab039b10",
+ "source_tree": "sha256:08b705b69471447a92b26d016f8c552da71da94bc0111564e029d305708eb8e9"
}
},
"history": [
diff --git a/crates/aien-cli/README.md b/crates/aien-cli/README.md
index e0348280..48c336b7 100644
--- a/crates/aien-cli/README.md
+++ b/crates/aien-cli/README.md
@@ -25,11 +25,22 @@ When a conversation gets too long for the model, older material is folded into a
- **Per-turn folding (opt-in):** `AIEN_MICRO_COMPACT=1` folds one exchange (Allen's part of one turn) after every turn, so the cost of each pass stays small. It is off by default because every pass changes the start of the prompt the model sees. A resumed session continues after the last recap and never folds an exchange twice.
- **The trade-off:** because the operator's messages are never folded, very long operator messages stay in the conversation. When that alone is over the limit, the loop says so instead of cutting them.
-The code is in `src/turn_journal.rs` (the journal), `src/turn_recovery.rs` (failure classes) and `src/compaction.rs` (folding). The mechanisms follow Hermes Agent (Nous Research, MIT licence, commit 5480918). It was re-implemented from reading; no code was copied.
+## Tools: side by side when safe, large output kept aside
+
+When Allen asks for several tools in one reply, the loop plans them before running them (sovereign-core #666):
+
+- **Reads run together:** viewing, listing and searching run side by side, up to eight at once, even on the same file.
+- **Writes are kept apart:** a write never runs at the same time as another call on the same path or a folder that holds it.
+- **Some tools always run alone:** shell commands, tools the planner does not know, and any call that would ask the operator for approval run alone, so two approval questions never share the screen.
+- **Order is kept:** two calls that touch the same path run in the order Allen asked for them, and results come back in that order however they finish. Every request of a step is recorded in the journal before any of them runs.
+- **Large output is saved to a file:** a result bigger than its share of the model's window (15 percent per result, 30 percent per reply, at least 8,000 and 16,000 characters, at most 100,000 and 200,000) is written whole to `basecamp/sessions/<session-id>-spill/`. Allen gets the start and the end of it (40 and 60 percent of 1,500 characters) and the file's path, so he can read the rest a page at a time instead of running the tool again. File reads are never saved aside this way, so a saved file can always be read back.
+
+The code is in `src/turn_journal.rs` (the journal), `src/turn_recovery.rs` (failure classes), `src/compaction.rs` (folding), and `src/tool_plan.rs`, `src/tool_batch.rs` and `src/tool_spill.rs` (tool batches). The mechanisms follow Hermes Agent (Nous Research, MIT licence, commit 5480918). It was re-implemented from reading; no code was copied.
### Not covered yet
- The recap is built by rule (the first line of each message), not by a language model. A model-written summary, with its own failure pacing (skip an exchange after three failures, wait 60 s, then 300 s, then 900 s), is the next part of #664.
- Token counts are still estimated locally. Using the counts the model server reports (#664) is not built yet.
-- `aien-cli goal auto` does not use the interactive loop's one-shot model-call recovery.
+- `aien-cli goal auto` does not use the interactive loop's one-shot model-call recovery, and it still runs tools one at a time (no tool batches).
+- Tool batches have no time limit yet: a tool that hangs holds its step. Paths are compared by spelling, so a symlink that gives one file two names is not detected.
- Trying another credential or provider before a fallback model (part of #665) is not built: the loop has one model seat and no fallback chain.
diff --git a/crates/aien-cli/src/.crumb b/crates/aien-cli/src/.crumb
index e8b6f25e..8f232897 100644
--- a/crates/aien-cli/src/.crumb
+++ b/crates/aien-cli/src/.crumb
@@ -64,14 +64,14 @@
"generated": {
"children": [],
"children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
- "compiled_at": "2026-10-30T14:49:12Z",
+ "compiled_at": "2026-10-31T02:10:57Z",
"compiler": "crumb-compile/1",
- "digest": "sha256:e3eb2b311e33b4191bcf709dc56c71c4c98bca33271dfd7b2683bc5855f4536a",
+ "digest": "sha256:f2a696fda66f200dae534b5880cf13cb6f621cc6ff7f340d6fedfd40bc260132",
"evidence_files": 0,
"evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
- "files": 36,
- "generated_at_commit": "b91f018a2ea80fc1e9002a2a98a702c88a4a845a",
- "source_tree": "sha256:7d8464b6909fa85e621c1b920d359fffa3473d283771afd7ad07161082b32575"
+ "files": 39,
+ "generated_at_commit": "84ff89f7229a85628fdc7be5c30bb91cab039b10",
+ "source_tree": "sha256:5afe3307b36bf6f80066fa499b8c68a00a00627db6ee045c50290f9fd3c9ca63"
}
},
"history": [
diff --git a/crates/aien-cli/src/main.rs b/crates/aien-cli/src/main.rs
index c3ac0e08..e20e83be 100644
--- a/crates/aien-cli/src/main.rs
+++ b/crates/aien-cli/src/main.rs
@@ -38,6 +38,9 @@ pub mod science_context;
pub mod skills;
pub mod subagents;
mod telemetry;
+pub mod tool_batch;
+pub mod tool_plan;
+pub mod tool_spill;
mod tools;
pub mod turn_journal;
pub mod turn_recovery;
@@ -440,6 +443,11 @@ async fn main() {
.with_redactor(crate::vault::redact_secrets)
.with_counter_from_env();
let micro_compact = crate::compaction::micro_compact_enabled_from_env();
+ // sc#666: tool batches; large results spill into the session's own folder.
+ let batch = tool_batch::BatchConfig::new(
+ compactor.max_tokens,
+ Some(sessions_dir.join(format!("{}-spill", session_id))),
+ );
loop {
let prompt_str = format!("{}{}", "AIEN".magenta().bold(), " ❯ ".cyan().bold());
@@ -484,6 +492,7 @@ async fn main() {
Some(&compactor),
&hook_registry,
true,
+ &batch,
)
.await
{
@@ -578,6 +587,10 @@ async fn run_single_prompt(prompt: &str) {
return;
}
};
+ let batch = tool_batch::BatchConfig::new(
+ crate::compaction::ContextCompactor::default().max_tokens,
+ Some(sessions_dir.join(format!("{}-spill", session_id))),
+ );
let opening = [
json!({"role": "system", "content": full_system_prompt}),
json!({"role": "user", "content": format!("<system_grounding>\n{}\n</system_grounding>\n{}", nesting.grounding_context, turn_prompt)}),
@@ -596,6 +609,7 @@ async fn run_single_prompt(prompt: &str) {
None,
&hook_registry,
false,
+ &batch,
)
.await
{
@@ -633,6 +647,7 @@ async fn run_model_steps(
compactor: Option<&crate::compaction::ContextCompactor>,
hook_registry: &crate::hooks::HookRegistry,
label: bool,
+ batch: &tool_batch::BatchConfig,
) -> Option<turn_journal::TurnStop> {
use turn_journal::TurnStop;
use turn_recovery::{
@@ -737,10 +752,9 @@ async fn run_model_steps(
// Completed turn
return None;
}
- if let Err(stop) =
- turn_journal::run_tool_calls(journal, messages, tool_calls, dispatch_tool)
- {
- return Some(stop);
+ match run_tools(journal, messages, tool_calls, batch) {
+ Ok(r) => report_batch(&r),
+ Err(stop) => return Some(stop),
}
}
None
@@ -788,6 +802,56 @@ where
Ok(AutonomousStep::Acted { milestone_done })
}
+/// sc#666: one reply's tool calls as a planned batch. Reads of the same or
+/// different paths run together; a write never runs beside a call on an
+/// overlapping path; shell commands, unknown tools and any call that would ask
+/// the operator run alone, so two approval prompts never share the screen.
+fn run_tools(
+ journal: &mut turn_journal::Journal,
+ messages: &mut Vec<Value>,
+ calls: Vec<(String, Value)>,
+ batch: &tool_batch::BatchConfig,
+) -> Result<tool_batch::BatchReport, turn_journal::TurnStop> {
+ let cwd = std::env::current_dir().unwrap_or_default();
+ let safety = crate::safety::SafetyEngine::default_sovereign_engine();
+ let access = |name: &str, args: &Value| match safety.evaluate(name, args) {
+ crate::safety::SafetyDecision::AskUser(_) => tool_plan::Access::Barrier,
+ _ => tool_plan::access_of(name, args, &cwd),
+ };
+ // Tools reach the async runtime from their own threads through the handle.
+ let handle = tokio::runtime::Handle::current();
+ let dispatch = move |name: &str, args: &Value| {
+ let _runtime = handle.enter();
+ dispatch_tool(name, args)
+ };
+ tool_batch::run_batch(journal, messages, calls, batch, access, dispatch)
+}
+
+fn report_batch(r: &tool_batch::BatchReport) {
+ if r.ran_together > 0 {
+ println!(
+ "{}",
+ format!(
+ " ⚡ tools: {} ran side by side ({} steps)",
+ r.ran_together, r.segments
+ )
+ .cyan()
+ .dimmed()
+ );
+ }
+ for p in &r.spilled {
+ println!(
+ "{}",
+ format!(
+ " ⚡ tools: a large result was saved to {} (Allen sees a preview)",
+ p.display()
+ )
+ .cyan()
+ .dimmed()
+ );
+ }
+}
+
pub async fn run_autonomous_goal(goal_id: &str) {
let manifest = goals::load_goals();
let goal = match manifest
@@ -1312,3 +1376,47 @@ mod autonomous_journal_tests {
assert!(rep.in_doubt.is_empty());
}
}
+
+#[cfg(test)]
+mod tool_batch_runtime_tests {
+ use super::*;
+
+ /// sc#666: the real tools, run side by side from plain threads inside the
+ /// real multi-threaded runtime. `dispatch_tool` reaches the runtime
+ /// (`block_in_place`, `Handle::current`) for its hooks; the batch runner
+ /// must hand each thread the runtime handle or this panics.
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn real_reads_run_side_by_side_inside_the_runtime() {
+ let d = tempfile::Builder::new()
+ .prefix("aien-666-")
+ .tempdir_in("/tmp")
+ .unwrap();
+ let a = d.path().join("a.txt");
+ let b = d.path().join("b.txt");
+ std::fs::write(&a, "alpha\n").unwrap();
+ std::fs::write(&b, "beta\n").unwrap();
+ let mut journal = turn_journal::Journal::create(&d.path().join("s.journal.jsonl")).unwrap();
+ let mut messages = Vec::new();
+ let batch = tool_batch::BatchConfig::new(24_000, Some(d.path().join("spill")));
+ let calls = vec![
+ (
+ "view_file".to_string(),
+ json!({"path": a.display().to_string()}),
+ ),
+ (
+ "view_file".to_string(),
+ json!({"path": b.display().to_string()}),
+ ),
+ ];
+ let report = run_tools(&mut journal, &mut messages, calls, &batch).unwrap();
+ assert_eq!((report.segments, report.ran_together), (1, 2));
+ assert_eq!(messages.len(), 2);
+ let first = messages[0]["content"].as_str().unwrap();
+ let second = messages[1]["content"].as_str().unwrap();
+ assert!(
+ first.contains("alpha") && !first.contains("CONFINEMENT"),
+ "{first}"
+ );
+ assert!(second.contains("beta"), "{second}");
+ }
+}
diff --git a/crates/aien-cli/src/tool_batch.rs b/crates/aien-cli/src/tool_batch.rs
new file mode 100644
index 00000000..82eb4517
--- /dev/null
+++ b/crates/aien-cli/src/tool_batch.rs
@@ -0,0 +1,396 @@
+// SPDX-License-Identifier: Apache-2.0
+// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! sovereign-core #666: run one reply's tool calls as a planned batch.
+//!
+//! Mechanism after Hermes Agent (Nous Research, MIT, commit 5480918),
+//! re-implemented; no code copied.
+//!
+//! For each segment of the plan (`tool_plan`), in order:
+//! 1. every request of the segment is written to the session journal first
+//! (persist-before-act, #665), so a crash mid-segment leaves each one
+//! recorded as in doubt and none half-known;
+//! 2. the calls run: one alone, or up to eight together on scoped threads;
+//! 3. oversized results spill to files (`tool_spill`), file before journal;
+//! 4. the results are journaled and added to the conversation in the order
+//! the model asked for them, whatever order they finished in.
+
+use crate::tool_plan::{plan, Access, MAX_PARALLEL};
+use crate::tool_spill::{self, SpillBudget};
+use crate::turn_journal::{tool_response_message, Journal, TurnStop};
+use serde_json::{json, Value};
+use std::path::PathBuf;
+
+pub struct BatchConfig {
+ pub max_parallel: usize,
+ pub budget: SpillBudget,
+ /// Folder for spilled results; `None` keeps an inline preview only.
+ pub spill_dir: Option<PathBuf>,
+}
+
+impl BatchConfig {
+ pub fn new(window_tokens: usize, spill_dir: Option<PathBuf>) -> Self {
+ Self {
+ max_parallel: MAX_PARALLEL,
+ budget: SpillBudget::for_window(window_tokens),
+ spill_dir,
+ }
+ }
+}
+
+/// What a batch did, for the operator's screen.
+#[derive(Debug, Default, Clone, PartialEq)]
+pub struct BatchReport {
+ pub segments: usize,
+ /// Calls that ran together with at least one other call.
+ pub ran_together: usize,
+ pub spilled: Vec<PathBuf>,
+}
+
+fn persist(e: crate::turn_journal::JournalError) -> TurnStop {
+ TurnStop::PersistFailed(e.to_string())
+}
+
+/// Runs `calls` under the plan. `access` says what each call touches;
+/// `dispatch` runs one call and must be safe to call from several threads.
+pub fn run_batch<A, D>(
+ journal: &mut Journal,
+ messages: &mut Vec<Value>,
+ calls: Vec<(String, Value)>,
+ cfg: &BatchConfig,
+ access: A,
+ dispatch: D,
+) -> Result<BatchReport, TurnStop>
+where
+ A: Fn(&str, &Value) -> Access,
+ D: Fn(&str, &Value) -> Value + Sync,
+{
+ let accesses: Vec<Access> = calls.iter().map(|(n, a)| access(n, a)).collect();
+ let segments = plan(&accesses, cfg.max_parallel);
+ let mut report = BatchReport {
+ segments: segments.len(),
+ ..BatchReport::default()
+ };
+ let mut turn_used = 0usize;
+ for seg in &segments {
+ // 1. Every request of the segment is on disk before any of them runs.
+ let mut intents = Vec::with_capacity(seg.calls.len());
+ for &i in &seg.calls {
+ intents.push(journal.intent(&calls[i].0, &calls[i].1).map_err(persist)?);
+ }
+ // 2. Run.
+ let results: Vec<Value> = if seg.calls.len() == 1 {
+ let (n, a) = &calls[seg.calls[0]];
+ vec![dispatch(n, a)]
+ } else {
+ report.ran_together += seg.calls.len();
+ let d = &dispatch;
+ std::thread::scope(|s| {
+ let handles: Vec<_> = seg
+ .calls
+ .iter()
+ .map(|&i| {
+ let (n, a) = &calls[i];
+ s.spawn(move || d(n, a))
+ })
+ .collect();
+ handles
+ .into_iter()
+ .map(|h| {
+ h.join().unwrap_or_else(
+ |_| json!({"error": "the tool stopped with an internal fault (panic)"}),
+ )
+ })
+ .collect()
+ })
+ };
+ // 3. Spill what is too large, file before journal.
+ let texts: Vec<String> = results
+ .iter()
+ .map(|r| serde_json::to_string(r).unwrap_or_default())
+ .collect();
+ let sizes: Vec<usize> = texts.iter().map(|t| t.chars().count()).collect();
+ let exempt: Vec<bool> = seg
+ .calls
+ .iter()
+ .map(|&i| tool_spill::exempt(&calls[i].0))
+ .collect();
+ let room = cfg.budget.per_turn.saturating_sub(turn_used);
+ let spill = tool_spill::choose(&sizes, &exempt, &cfg.budget, room);
+ // 4. Results in call order.
+ for (k, &i) in seg.calls.iter().enumerate() {
+ let name = &calls[i].0;
+ let shown = if spill[k] {
+ let full = tool_spill::render_full(name, &intents[k].call_id, &results[k]);
+ let path = cfg
+ .spill_dir
+ .as_ref()
+ .and_then(|d| tool_spill::write_spill(d, &full).ok());
+ if let Some(p) = &path {
+ report.spilled.push(p.clone());
+ }
+ tool_spill::stub(&results[k], sizes[k], path.as_deref(), &cfg.budget)
+ } else {
+ results[k].clone()
+ };
+ let message = tool_response_message(name, &shown);
+ turn_used += message["content"].as_str().map_or(0, |c| c.chars().count());
+ journal.outcome(messages, &intents[k], message)?;
+ }
+ }
+ Ok(report)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::tool_plan::access_of;
+ use crate::turn_journal::replay;
+ use std::path::Path;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ use std::sync::Mutex;
+ use std::time::Duration;
+
+ fn journal() -> (tempfile::TempDir, Journal, PathBuf) {
+ let d = tempfile::tempdir().unwrap();
+ let p = d.path().join("s.journal.jsonl");
+ let j = Journal::create(&p).unwrap();
+ (d, j, p)
+ }
+
+ fn cfg(spill: Option<PathBuf>) -> BatchConfig {
+ BatchConfig::new(24_000, spill)
+ }
+
+ fn acc(n: &str, a: &Value) -> Access {
+ access_of(n, a, Path::new("/w"))
+ }
+
+ fn body(message: &Value) -> Value {
+ let c = message["content"].as_str().unwrap();
+ let start = c.find('\n').unwrap() + 1;
+ let end = c.rfind("\n</tool_response>").unwrap();
+ serde_json::from_str(&c[start..end]).unwrap()
+ }
+
+ /// Counts how many calls run at the same moment.
+ struct Overlap {
+ now: AtomicUsize,
+ max: AtomicUsize,
+ }
+ impl Overlap {
+ fn new() -> Self {
+ Self {
+ now: AtomicUsize::new(0),
+ max: AtomicUsize::new(0),
+ }
+ }
+ fn run(&self) -> Value {
+ let n = self.now.fetch_add(1, Ordering::SeqCst) + 1;
+ self.max.fetch_max(n, Ordering::SeqCst);
+ std::thread::sleep(Duration::from_millis(150));
+ self.now.fetch_sub(1, Ordering::SeqCst);
+ json!({"ok": true})
+ }
+ }
+
+ #[test]
+ fn two_readers_of_one_path_run_together() {
+ let (_d, mut j, _p) = journal();
+ let mut msgs = Vec::new();
+ let o = Overlap::new();
+ let calls = vec![
+ ("view_file".to_string(), json!({"path": "/w/a"})),
+ ("view_file".to_string(), json!({"path": "/w/a"})),
+ ];
+ let r = run_batch(&mut j, &mut msgs, calls, &cfg(None), acc, |_, _| o.run()).unwrap();
+ assert_eq!(o.max.load(Ordering::SeqCst), 2);
+ assert_eq!((r.segments, r.ran_together), (1, 2));
+ assert_eq!(msgs.len(), 2);
+ }
+
+ #[test]
+ fn two_writers_on_one_path_never_run_together() {
+ let (_d, mut j, _p) = journal();
+ let mut msgs = Vec::new();
+ let o = Overlap::new();
+ let calls = vec![
+ (
+ "write_to_file".to_string(),
+ json!({"path": "/w/a", "content": "1"}),
+ ),
+ (
+ "write_to_file".to_string(),
+ json!({"path": "/w/a", "content": "2"}),
+ ),
+ ("view_file".to_string(), json!({"path": "/w/a"})),
+ ];
+ let r = run_batch(&mut j, &mut msgs, calls, &cfg(None), acc, |_, _| o.run()).unwrap();
+ assert_eq!(o.max.load(Ordering::SeqCst), 1);
+ assert_eq!((r.segments, r.ran_together), (3, 0));
+ }
+
+ #[test]
+ fn a_shell_command_never_runs_beside_anything() {
+ let (_d, mut j, _p) = journal();
+ let mut msgs = Vec::new();
+ let o = Overlap::new();
+ let calls = vec![
+ ("view_file".to_string(), json!({"path": "/w/a"})),
+ ("run_command".to_string(), json!({"command": "ls"})),
+ ("view_file".to_string(), json!({"path": "/w/b"})),
+ ];
+ run_batch(&mut j, &mut msgs, calls, &cfg(None), acc, |_, _| o.run()).unwrap();
+ assert_eq!(o.max.load(Ordering::SeqCst), 1);
+ }
+
+ #[test]
+ fn every_request_of_a_segment_is_on_disk_before_any_runs() {
+ let (_d, mut j, p) = journal();
+ let mut msgs = Vec::new();
+ let seen = Mutex::new(Vec::new());
+ let calls = vec![
+ ("view_file".to_string(), json!({"path": "/w/a"})),
+ ("view_file".to_string(), json!({"path": "/w/b"})),
+ ("view_file".to_string(), json!({"path": "/w/c"})),
+ ];
+ run_batch(&mut j, &mut msgs, calls, &cfg(None), acc, |_, _| {
+ let rep = replay(&std::fs::read_to_string(&p).unwrap()).unwrap();
+ seen.lock().unwrap().push(rep.in_doubt.len());
+ json!({"ok": true})
+ })
+ .unwrap();
+ assert_eq!(*seen.lock().unwrap(), vec![3, 3, 3]);
+ let rep = replay(&std::fs::read_to_string(&p).unwrap()).unwrap();
+ assert!(rep.in_doubt.is_empty());
+ assert_eq!(rep.messages, msgs);
+ }
+
+ #[test]
+ fn results_come_back_in_call_order_whatever_finishes_first() {
+ let (_d, mut j, _p) = journal();
+ let mut msgs = Vec::new();
+ let calls: Vec<(String, Value)> = (0..4)
+ .map(|i| ("view_file".to_string(), json!({"path": format!("/w/{i}")})))
+ .collect();
+ run_batch(&mut j, &mut msgs, calls, &cfg(None), acc, |_, a| {
+ let i: u64 = a["path"].as_str().unwrap()[3..].parse().unwrap();
+ std::thread::sleep(Duration::from_millis(40 * (4 - i)));
+ json!({"i": i})
+ })
+ .unwrap();
+ let order: Vec<u64> = msgs
+ .iter()
+ .map(|m| body(m)["i"].as_u64().unwrap())
+ .collect();
+ assert_eq!(order, vec![0, 1, 2, 3]);
+ }
+
+ #[test]
+ fn a_one_megabyte_result_spills_and_the_file_is_addressable() {
+ let (d, mut j, _p) = journal();
+ let spill = d.path().join("spill");
+ let mut msgs = Vec::new();
+ let big: String = (0..45_000)
+ .map(|i| format!("line {i:05} of the output\n"))
+ .collect();
+ assert!(big.len() >= 1_000_000);
+ let c = cfg(Some(spill.clone()));
+ let r = run_batch(
+ &mut j,
+ &mut msgs,
+ vec![("run_command".to_string(), json!({"command": "big"}))],
+ &c,
+ acc,
+ |_, _| json!({"stdout": big, "exit_code": 0}),
+ )
+ .unwrap();
+ let content = msgs[0]["content"].as_str().unwrap();
+ assert!(
+ content.chars().count() < c.budget.per_result,
+ "{} chars",
+ content.len()
+ );
+ let b = body(&msgs[0]);
+ assert_eq!(b["spilled"], json!(true));
+ let path = PathBuf::from(b["path"].as_str().unwrap());
+ assert_eq!(r.spilled, vec![path.clone()]);
+ assert!(path.starts_with(&spill));
+ let file = std::fs::read_to_string(&path).unwrap();
+ assert!(
+ file.contains(&format!("## stdout\n{big}")),
+ "the spill file holds the whole output"
+ );
+ assert!(b["preview"].as_str().unwrap().contains("TRUNCATED"));
+ }
+
+ #[test]
+ fn a_large_file_read_is_never_spilled() {
+ let (d, mut j, _p) = journal();
+ let mut msgs = Vec::new();
+ let big = "x".repeat(200_000);
+ run_batch(
+ &mut j,
+ &mut msgs,
+ vec![("view_file".to_string(), json!({"path": "/w/a"}))],
+ &cfg(Some(d.path().join("spill"))),
+ acc,
+ |_, _| json!({"content": big}),
+ )
+ .unwrap();
+ assert_eq!(body(&msgs[0])["content"].as_str().unwrap().len(), 200_000);
+ assert!(!d.path().join("spill").exists());
+ }
+
+ #[test]
+ fn when_the_spill_file_cannot_be_written_a_preview_is_still_kept() {
+ let (d, mut j, _p) = journal();
+ let blocker = d.path().join("not-a-dir");
+ std::fs::write(&blocker, b"x").unwrap();
+ let mut msgs = Vec::new();
+ run_batch(
+ &mut j,
+ &mut msgs,
+ vec![("run_command".to_string(), json!({"command": "big"}))],
+ &cfg(Some(blocker)),
+ acc,
+ |_, _| json!({"stdout": "y".repeat(50_000), "status": "ok"}),
+ )
+ .unwrap();
+ let b = body(&msgs[0]);
+ assert_eq!(b["spilled"], json!(false));
+ assert!(b["note"].as_str().unwrap().contains("could not be saved"));
+ assert_eq!(b["status"], json!("ok"), "the status is carried over");
+ }
+
+ #[test]
+ fn a_panicking_tool_in_a_parallel_segment_does_not_lose_the_others() {
+ let (_d, mut j, _p) = journal();
+ let mut msgs = Vec::new();
+ let calls = vec![
+ ("view_file".to_string(), json!({"path": "/w/a"})),
+ ("view_file".to_string(), json!({"path": "/w/boom"})),
+ ];
+ run_batch(&mut j, &mut msgs, calls, &cfg(None), acc, |_, a| {
+ if a["path"] == "/w/boom" {
+ panic!("tool fault");
+ }
+ json!({"ok": true})
+ })
+ .unwrap();
+ assert_eq!(body(&msgs[0]), json!({"ok": true}));
+ assert!(body(&msgs[1])["error"].as_str().unwrap().contains("panic"));
+ }
+}
diff --git a/crates/aien-cli/src/tool_plan.rs b/crates/aien-cli/src/tool_plan.rs
new file mode 100644
index 00000000..453a17e3
--- /dev/null
+++ b/crates/aien-cli/src/tool_plan.rs
@@ -0,0 +1,280 @@
+// SPDX-License-Identifier: Apache-2.0
+// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! sovereign-core #666: plan a batch of tool calls into ordered segments.
+//!
+//! Mechanism after Hermes Agent (Nous Research, MIT, commit 5480918),
+//! re-implemented; no code copied.
+//!
+//! The model often asks for several tools in one reply. Running them one after
+//! another is always safe; running them together is faster but only safe when
+//! they cannot step on each other. This module decides, without doing any I/O,
+//! which calls may run together:
+//!
+//! - **Readers share, writers exclude.** A reader (view, list, search) and a
+//! writer (write, replace, create) reserve a path. Two calls conflict when
+//! their paths overlap (one is the other or lies inside it) and at least one
+//! of them writes. Readers on the same path never conflict.
+//! - **Everything else is a barrier.** A shell command, a call that would ask
+//! the operator, a call with no path, or a tool this module does not know runs
+//! alone, so it never overlaps anything and approval prompts never interleave.
+//! - **Order is kept.** Segments run in call order. A call joins the current
+//! segment only if it conflicts with nothing in it; otherwise it starts the
+//! next one, so two conflicting calls always run in the order the model asked.
+//! - **Bounded.** At most `max_parallel` calls (8) run at once.
+//!
+//! Paths are compared lexically after making them absolute against the working
+//! directory and removing `.` and `..`. A symlink that gives one file two
+//! different spellings is not detected (known limit).
+
+use serde_json::Value;
+use std::path::{Component, Path, PathBuf};
+
+/// Most calls that run at once (Hermes uses the same bound).
+pub const MAX_PARALLEL: usize = 8;
+
+/// What one call touches.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Access {
+ Read(PathBuf),
+ Write(PathBuf),
+ /// Runs alone: unknown scope, a shell, an operator prompt, any other tool.
+ Barrier,
+}
+
+/// One step of the plan: indices into the batch, in call order. More than one
+/// index means the calls run together.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Segment {
+ pub calls: Vec<usize>,
+}
+
+/// Lexical normal form: absolute against `cwd`, no `.`, `..` folded.
+pub fn normalize(path: &str, cwd: &Path) -> PathBuf {
+ let p = Path::new(path);
+ let joined = if p.is_absolute() {
+ p.to_path_buf()
+ } else {
+ cwd.join(p)
+ };
+ let mut out = PathBuf::new();
+ for c in joined.components() {
+ match c {
+ Component::CurDir => {}
+ Component::ParentDir => {
+ out.pop();
+ }
+ other => out.push(other.as_os_str()),
+ }
+ }
+ out
+}
+
+fn path_arg(args: &Value) -> Option<&str> {
+ ["path", "Path", "directory", "dir"]
+ .iter()
+ .find_map(|k| args.get(*k).and_then(Value::as_str))
+ .filter(|p| !p.trim().is_empty())
+}
+
+/// What a call touches, from its name and arguments alone.
+pub fn access_of(name: &str, args: &Value, cwd: &Path) -> Access {
+ match name {
+ "view_file" | "list_dir" | "list_directory" => match path_arg(args) {
+ Some(p) => Access::Read(normalize(p, cwd)),
+ None => Access::Barrier,
+ },
+ // A search with no path searches the working directory.
+ "grep_search" | "search_directory" | "find_by_name" | "find_file" => {
+ Access::Read(normalize(path_arg(args).unwrap_or("."), cwd))
+ }
+ "write_to_file" | "create_file" | "replace_file_content" | "edit_file" | "create_dir" => {
+ match path_arg(args) {
+ Some(p) => Access::Write(normalize(p, cwd)),
+ None => Access::Barrier,
+ }
+ }
+ _ => Access::Barrier,
+ }
+}
+
+fn overlaps(a: &Path, b: &Path) -> bool {
+ a.starts_with(b) || b.starts_with(a)
+}
+
+fn conflicts(a: &Access, b: &Access) -> bool {
+ match (a, b) {
+ (Access::Barrier, _) | (_, Access::Barrier) => true,
+ (Access::Read(_), Access::Read(_)) => false,
+ (Access::Read(x) | Access::Write(x), Access::Read(y) | Access::Write(y)) => overlaps(x, y),
+ }
+}
+
+/// Plans the batch. Pure.
+pub fn plan(accesses: &[Access], max_parallel: usize) -> Vec<Segment> {
+ let max_parallel = max_parallel.max(1);
+ let mut segments: Vec<Segment> = Vec::new();
+ for (i, a) in accesses.iter().enumerate() {
+ let joins = match segments.last() {
+ Some(seg) => {
+ !matches!(a, Access::Barrier)
+ && seg.calls.len() < max_parallel
+ && seg.calls.iter().all(|&j| !conflicts(&accesses[j], a))
+ }
+ None => false,
+ };
+ if joins {
+ if let Some(seg) = segments.last_mut() {
+ seg.calls.push(i);
+ }
+ } else {
+ segments.push(Segment { calls: vec![i] });
+ }
+ }
+ segments
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn cwd() -> PathBuf {
+ PathBuf::from("/w")
+ }
+ fn r(p: &str) -> Access {
+ Access::Read(PathBuf::from(p))
+ }
+ fn w(p: &str) -> Access {
+ Access::Write(PathBuf::from(p))
+ }
+ fn segs(s: &[Segment]) -> Vec<Vec<usize>> {
+ s.iter().map(|x| x.calls.clone()).collect()
+ }
+
+ #[test]
+ fn readers_share_even_on_the_same_path() {
+ let p = plan(&[r("/w/a"), r("/w/a"), r("/w"), r("/w/b/c")], MAX_PARALLEL);
+ assert_eq!(segs(&p), vec![vec![0, 1, 2, 3]]);
+ }
+
+ #[test]
+ fn two_writers_on_one_path_never_share_a_segment() {
+ let p = plan(&[w("/w/a"), w("/w/a")], MAX_PARALLEL);
+ assert_eq!(segs(&p), vec![vec![0], vec![1]]);
+ }
+
+ #[test]
+ fn a_writer_excludes_readers_of_overlapping_paths_but_not_others() {
+ // Reading the folder overlaps writing a file inside it.
+ let p = plan(
+ &[
+ r("/w/src"),
+ w("/w/src/main.rs"),
+ r("/w/docs"),
+ w("/w/out.txt"),
+ ],
+ MAX_PARALLEL,
+ );
+ assert_eq!(segs(&p), vec![vec![0], vec![1, 2, 3]]);
+ // A prefix that is not a path component does not overlap.
+ assert!(!overlaps(Path::new("/w/ab"), Path::new("/w/a")));
+ }
+
+ #[test]
+ fn order_is_kept_across_conflicts() {
+ // write a, read b, read a: the read of a must come after the write.
+ let p = plan(&[w("/w/a"), r("/w/b"), r("/w/a")], MAX_PARALLEL);
+ assert_eq!(segs(&p), vec![vec![0, 1], vec![2]]);
+ }
+
+ #[test]
+ fn barriers_run_alone() {
+ let p = plan(
+ &[r("/w/a"), Access::Barrier, r("/w/b"), r("/w/c")],
+ MAX_PARALLEL,
+ );
+ assert_eq!(segs(&p), vec![vec![0], vec![1], vec![2, 3]]);
+ }
+
+ #[test]
+ fn at_most_max_parallel_run_at_once() {
+ let many: Vec<Access> = (0..20).map(|i| r(&format!("/w/{i}"))).collect();
+ let p = plan(&many, MAX_PARALLEL);
+ assert_eq!(
+ p.iter().map(|s| s.calls.len()).collect::<Vec<_>>(),
+ vec![8, 8, 4]
+ );
+ assert_eq!(p.concat_indices(), (0..20).collect::<Vec<_>>());
+ }
+
+ trait Concat {
+ fn concat_indices(&self) -> Vec<usize>;
+ }
+ impl Concat for Vec<Segment> {
+ fn concat_indices(&self) -> Vec<usize> {
+ self.iter().flat_map(|s| s.calls.clone()).collect()
+ }
+ }
+
+ #[test]
+ fn access_comes_from_the_tool_and_its_path() {
+ let c = cwd();
+ assert_eq!(
+ access_of("view_file", &json!({"path": "src/../a.rs"}), &c),
+ r("/w/a.rs")
+ );
+ assert_eq!(
+ access_of("grep_search", &json!({"query": "x"}), &c),
+ r("/w")
+ );
+ assert_eq!(
+ access_of("write_to_file", &json!({"path": "/w/./o"}), &c),
+ w("/w/o")
+ );
+ assert_eq!(
+ access_of("write_to_file", &json!({"content": "x"}), &c),
+ Access::Barrier
+ );
+ assert_eq!(
+ access_of("run_command", &json!({"command": "ls"}), &c),
+ Access::Barrier
+ );
+ assert_eq!(
+ access_of("brand_new_tool", &json!({"path": "a"}), &c),
+ Access::Barrier
+ );
+ }
+
+ /// The planner runs a call beside others as a reader only when the journal
+ /// says it is read-only, so a new alias in the dispatcher cannot become a
+ /// shared reader by mistake.
+ #[test]
+ fn readers_are_exactly_the_read_only_tools() {
+ use crate::turn_journal::{Effect, TOOL_EFFECTS};
+ let c = cwd();
+ for (name, effect) in TOOL_EFFECTS {
+ let reads = matches!(access_of(name, &json!({"path": "a"}), &c), Access::Read(_));
+ assert_eq!(reads, *effect == Effect::ReadOnly, "{name}");
+ }
+ assert_eq!(
+ access_of("list_directory", &json!({"path": "a"}), &c),
+ r("/w/a")
+ );
+ for name in ["create_file", "edit_file"] {
+ assert_eq!(access_of(name, &json!({"path": "a"}), &c), w("/w/a"));
+ }
+ }
+}
diff --git a/crates/aien-cli/src/tool_spill.rs b/crates/aien-cli/src/tool_spill.rs
new file mode 100644
index 00000000..4f7e4c66
--- /dev/null
+++ b/crates/aien-cli/src/tool_spill.rs
@@ -0,0 +1,298 @@
+// SPDX-License-Identifier: Apache-2.0
+// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! sovereign-core #666: oversized tool results spill to files.
+//!
+//! Mechanism after Hermes Agent (Nous Research, MIT, commit 5480918),
+//! re-implemented; no code copied.
+//!
+//! A tool can return far more text than the model can use (a 1 MB command
+//! output, a huge search). Such a result is written whole to a file in the
+//! session's spill folder, and the conversation gets a short preview (the first
+//! 40 percent and the last 60 percent of a fixed size, with one marker line)
+//! plus the file's path, so the model can page the rest instead of running the
+//! tool again. Three budgets decide what spills:
+//!
+//! - **per result:** any single result larger than this spills;
+//! - **per turn:** if the results of one model reply together are still
+//! larger, the largest remaining ones spill first until they fit;
+//! - **window-scaled:** both budgets are a share of the model's context window
+//! (15 and 30 percent at 4 characters a token), with floors and caps.
+//!
+//! Reading a file (`view_file`) never spills: a spilled read would be read
+//! back and spilled again in a loop. The pure part ([`SpillBudget`],
+//! [`choose`], [`preview`], [`render_full`], [`stub`]) does no I/O;
+//! [`write_spill`] is the only edge.
+
+use serde_json::{json, Value};
+use sha2::{Digest, Sha256};
+use std::path::{Path, PathBuf};
+
+pub const DEFAULT_PER_RESULT_CHARS: usize = 100_000;
+pub const DEFAULT_PER_TURN_CHARS: usize = 200_000;
+pub const PREVIEW_CHARS: usize = 1_500;
+const FLOOR_PER_RESULT_CHARS: usize = 8_000;
+const FLOOR_PER_TURN_CHARS: usize = 16_000;
+/// Room the stub takes besides its preview (path, counts, field names).
+const STUB_OVERHEAD_CHARS: usize = 400;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct SpillBudget {
+ pub per_result: usize,
+ pub per_turn: usize,
+ pub preview: usize,
+}
+
+impl SpillBudget {
+ /// Budgets for a model window of `window_tokens`.
+ pub fn for_window(window_tokens: usize) -> Self {
+ let chars = window_tokens.saturating_mul(4);
+ Self {
+ per_result: (chars * 15 / 100).clamp(FLOOR_PER_RESULT_CHARS, DEFAULT_PER_RESULT_CHARS),
+ per_turn: (chars * 30 / 100).clamp(FLOOR_PER_TURN_CHARS, DEFAULT_PER_TURN_CHARS),
+ preview: PREVIEW_CHARS,
+ }
+ }
+
+ fn stub_chars(&self) -> usize {
+ self.preview + STUB_OVERHEAD_CHARS
+ }
+}
+
+/// Tools whose results never spill.
+pub fn exempt(tool: &str) -> bool {
+ matches!(tool, "view_file")
+}
+
+/// Which results spill. `sizes[i]` is result `i`'s size in characters as it
+/// would enter the conversation; `exempt[i]` marks results that never spill;
+/// `turn_room` is what is left of the per-turn budget. Pure.
+pub fn choose(
+ sizes: &[usize],
+ exempt: &[bool],
+ budget: &SpillBudget,
+ turn_room: usize,
+) -> Vec<bool> {
+ let shrinks = |i: usize| !exempt[i] && sizes[i] > budget.stub_chars();
+ let mut spill: Vec<bool> = (0..sizes.len())
+ .map(|i| shrinks(i) && sizes[i] > budget.per_result)
+ .collect();
+ let kept = |spill: &[bool]| -> usize {
+ (0..sizes.len())
+ .map(|i| {
+ if spill[i] {
+ budget.stub_chars()
+ } else {
+ sizes[i]
+ }
+ })
+ .sum()
+ };
+ let mut order: Vec<usize> = (0..sizes.len()).filter(|&i| shrinks(i)).collect();
+ order.sort_by(|&a, &b| sizes[b].cmp(&sizes[a]).then(a.cmp(&b)));
+ for i in order {
+ if kept(&spill) <= turn_room {
+ break;
+ }
+ spill[i] = true;
+ }
+ spill
+}
+
+/// The first 40 percent and the last 60 percent of `keep` characters, with
+/// one marker line between them. Text that already fits is returned as is.
+pub fn preview(full: &str, keep: usize) -> String {
+ let total = full.chars().count();
+ if total <= keep {
+ return full.to_string();
+ }
+ let head_n = keep * 40 / 100;
+ let tail_n = keep - head_n;
+ let head: String = full.chars().take(head_n).collect();
+ let tail: String = full.chars().skip(total - tail_n).collect();
+ format!(
+ "{head}\n... [TOOL OUTPUT TRUNCATED - {} chars omitted out of {total} total] ...\n{tail}",
+ total - head_n - tail_n
+ )
+}
+
+/// The whole result as a file a person or `view_file` can page: string
+/// fields with their real line breaks, one heading each; other fields as JSON.
+pub fn render_full(tool: &str, call_id: &str, result: &Value) -> String {
+ let mut out =
+ format!("# Full result of {tool} ({call_id}). The conversation holds only a preview.\n");
+ match result {
+ Value::Object(map) => {
+ for (k, v) in map {
+ match v {
+ Value::String(s) => {
+ out.push_str(&format!("## {k}\n{s}\n"));
+ }
+ other => out.push_str(&format!("## {k}: {other}\n")),
+ }
+ }
+ }
+ other => {
+ out.push_str(&serde_json::to_string_pretty(other).unwrap_or_default());
+ out.push('\n');
+ }
+ }
+ out
+}
+
+/// What the conversation gets instead of a spilled result. A top-level
+/// `status` is carried over so readers of the status still see it.
+pub fn stub(result: &Value, full_chars: usize, path: Option<&Path>, budget: &SpillBudget) -> Value {
+ let text = serde_json::to_string(result).unwrap_or_default();
+ let mut v = json!({
+ "spilled": path.is_some(),
+ "original_chars": full_chars,
+ "preview": preview(&text, budget.preview),
+ });
+ match path {
+ Some(p) => {
+ v["path"] = json!(p.display().to_string());
+ v["read_with"] = json!("view_file with start_line and end_line, a page at a time; do not run the tool again");
+ }
+ None => {
+ v["note"] =
+ json!("the full result could not be saved to a file; only this preview is left");
+ }
+ }
+ if let Some(status) = result.get("status") {
+ v["status"] = status.clone();
+ }
+ v
+}
+
+/// Writes `text` into `dir` under a name taken from its digest, so the same
+/// output twice is one file. Whole or not at all; owner-only permissions.
+pub fn write_spill(dir: &Path, text: &str) -> std::io::Result<PathBuf> {
+ std::fs::create_dir_all(dir)?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
+ }
+ let digest = hex::encode(Sha256::digest(text.as_bytes()));
+ let path = dir.join(format!("{}.txt", &digest[..16]));
+ if path.is_file() {
+ return Ok(path);
+ }
+ let tmp = dir.join(format!("{}.txt.tmp", &digest[..16]));
+ {
+ let mut opts = std::fs::OpenOptions::new();
+ opts.write(true).create(true).truncate(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ opts.mode(0o600);
+ }
+ use std::io::Write;
+ let mut f = opts.open(&tmp)?;
+ f.write_all(text.as_bytes())?;
+ f.sync_all()?;
+ }
+ std::fs::rename(&tmp, &path)?;
+ Ok(path)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn budgets_scale_with_the_window_inside_floors_and_caps() {
+ let small = SpillBudget::for_window(8_000);
+ assert_eq!((small.per_result, small.per_turn), (8_000, 16_000));
+ let mid = SpillBudget::for_window(24_000);
+ assert_eq!((mid.per_result, mid.per_turn), (14_400, 28_800));
+ let big = SpillBudget::for_window(1_000_000);
+ assert_eq!((big.per_result, big.per_turn), (100_000, 200_000));
+ }
+
+ #[test]
+ fn a_result_over_the_per_result_budget_spills() {
+ let b = SpillBudget::for_window(24_000);
+ assert_eq!(
+ choose(&[20_000, 100], &[false, false], &b, b.per_turn),
+ vec![true, false]
+ );
+ }
+
+ #[test]
+ fn the_turn_budget_spills_the_largest_first() {
+ let b = SpillBudget {
+ per_result: 50_000,
+ per_turn: 15_000,
+ preview: 1_500,
+ };
+ // 10k + 9k + 2k = 21k > 15k: spilling the 10k alone brings it to ~12.9k.
+ assert_eq!(
+ choose(
+ &[9_000, 10_000, 2_000],
+ &[false, false, false],
+ &b,
+ b.per_turn
+ ),
+ vec![false, true, false]
+ );
+ }
+
+ #[test]
+ fn file_reads_never_spill() {
+ let b = SpillBudget::for_window(24_000);
+ assert_eq!(choose(&[1_000_000], &[true], &b, b.per_turn), vec![false]);
+ assert!(exempt("view_file") && !exempt("run_command"));
+ }
+
+ #[test]
+ fn preview_keeps_40_percent_head_and_60_percent_tail() {
+ let text: String = (0..1000)
+ .map(|i| char::from(b'a' + (i % 26) as u8))
+ .collect();
+ let p = preview(&text, 100);
+ let (head, rest) = p.split_once('\n').unwrap();
+ let (marker, tail) = rest.split_once('\n').unwrap();
+ assert_eq!(head, &text[..40]);
+ assert_eq!(tail, &text[940..]);
+ assert!(
+ marker.contains("900 chars omitted out of 1000 total"),
+ "{marker}"
+ );
+ assert_eq!(preview("short", 100), "short");
+ // Multibyte text is cut on character boundaries.
+ assert!(preview(&"\u{1F30A}".repeat(500), 10)
+ .starts_with("\u{1F30A}\u{1F30A}\u{1F30A}\u{1F30A}\n"));
+ }
+
+ #[test]
+ fn the_same_output_twice_is_one_file() {
+ let d = tempfile::tempdir().unwrap();
+ let a = write_spill(d.path(), "same").unwrap();
+ let b = write_spill(d.path(), "same").unwrap();
+ assert_eq!(a, b);
+ assert_eq!(std::fs::read_to_string(&a).unwrap(), "same");
+ assert_eq!(std::fs::read_dir(d.path()).unwrap().count(), 1);
+ }
+
+ #[test]
+ fn the_full_file_keeps_real_line_breaks() {
+ let r = json!({"stdout": "one\ntwo\n", "exit_code": 0});
+ let f = render_full("run_command", "call-3", &r);
+ assert!(f.contains("## stdout\none\ntwo\n"), "{f}");
+ assert!(f.contains("## exit_code: 0"), "{f}");
+ }
+}