返回 CodeWhale
truncate.rs
根目录 / crates / engine / src / tools / truncate.rs
1 //! Tool-output spillover writer (#422).
2 //!
3 //! When a tool produces output that's too large to land in the model's
4 //! context budget, we want two things at once:
5 //!
6 //! 1. The transcript / tool-cell renders a bounded preview so the UI
7 //! stays scannable.
8 //! 2. The full router input is preserved under its origin session so bounded
9 //! retrieval and the raw-detail pager can inspect it without leaking a
10 //! process-global filesystem path.
11 //!
12 //! The opt-in adaptive path writes immutable artifacts under
13 //! `~/.codewhale/sessions/<session>/artifacts/`. The historical
14 //! `~/.codewhale/tool_outputs/<sanitised-id>.txt` directory remains only for
15 //! classic-routing compatibility, protected by a digest-bound origin sidecar.
16 //!
17 //! Boot prune drops files whose mtime is older than [`SPILLOVER_MAX_AGE`]
18 //! (7 days). Prune failures are logged and never fatal — the user
19 //! shouldn't see startup wedge because of a stale tool-output file.
20 //!
21 //! ## Live callers
22 //!
23 //! * [`apply_spillover`] — invoked from the engine's tool-execution
24 //! path (`turn_loop.rs`) so any successful tool result over
25 //! [`SPILLOVER_THRESHOLD_BYTES`] spills to disk and the model
26 //! receives a bounded plain preview: a [`SPILLOVER_HEAD_BYTES`] head,
27 //! a short retained tail, and an honest footer naming the on-disk
28 //! path of the full output plus a one-line recovery instruction.
29 //! * Boot prune in `main.rs` deletes files older than
30 //! [`SPILLOVER_MAX_AGE`].
31 //!
32 //! UI-side rendering is owned by `tui/history.rs::render_spillover_annotation`;
33 //! it exposes a calm expand affordance and the tool-details shortcut opens the
34 //! full retained output.
35
36 use codewhale_tools::names::SPILLOVER_RECOVERY_HINT;
37 use std::fs;
38 use std::io;
39 use std::path::{Path, PathBuf};
40 use std::time::{Duration, SystemTime};
41
42 use crate::tools::spec::ToolResult;
43
44 /// Name of the spillover directory under the CodeWhale home.
45 pub const SPILLOVER_DIR_NAME: &str = "tool_outputs";
46
47 const LEGACY_SPILLOVER_OWNER_SCHEMA_VERSION: u32 = 1;
48
49 /// Session proof for compatibility payloads kept in the historical global
50 /// `tool_outputs/` directory.
51 ///
52 /// The payload remains in its legacy location so classic-routing rollback and
53 /// existing detail pagers keep working, but model retrieval is authorized only
54 /// when this sidecar names the active origin session and still matches the
55 /// immutable bytes being returned.
56 #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
57 pub struct LegacySpilloverOwnership {
58 pub schema_version: u32,
59 pub origin_session: String,
60 pub digest: String,
61 pub size_bytes: u64,
62 }
63
64 /// Default threshold above which a tool result is a candidate for
65 /// spillover. Mirrors the `MAX_MEMORY_SIZE` ceiling we use elsewhere
66 /// for "too large to inline" so the rules feel consistent. Wired
67 /// callers can pass a different value if a tool family has different
68 /// economics.
69 pub const SPILLOVER_THRESHOLD_BYTES: usize = 100 * 1024; // 100 KiB
70
71 /// Default boot-prune age. Older spillover files are deleted on
72 /// startup to keep `~/.codewhale/tool_outputs/` from growing without
73 /// bound. Mirrors the workspace-snapshot 7-day default.
74 pub const SPILLOVER_MAX_AGE: Duration = Duration::from_secs(7 * 24 * 60 * 60);
75
76 #[cfg(any(test, feature = "test-support"))]
77 static TEST_SPILLOVER_ROOT: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
78
79 #[cfg(any(test, feature = "test-support"))]
80 pub static TEST_SPILLOVER_GUARD: std::sync::Mutex<()> = std::sync::Mutex::new(());
81
82 /// Resolve `~/.codewhale/tool_outputs/`. Returns `None` if the home
83 /// directory can't be determined (CI containers occasionally hit
84 /// this). Callers should treat `None` as "spillover unavailable" and
85 /// degrade gracefully rather than fail the tool call.
86 #[must_use]
87 pub fn spillover_root() -> Option<PathBuf> {
88 #[cfg(any(test, feature = "test-support"))]
89 if let Some(root) = TEST_SPILLOVER_ROOT
90 .lock()
91 .unwrap_or_else(|err| err.into_inner())
92 .clone()
93 {
94 return Some(root);
95 }
96
97 let home = codewhale_paths::user_home()?;
98 let primary = home.join(".codewhale").join(SPILLOVER_DIR_NAME);
99 let legacy = home.join(".deepseek").join(SPILLOVER_DIR_NAME);
100 if primary.exists() || !legacy.exists() {
101 return Some(primary);
102 }
103 Some(legacy)
104 }
105
106 /// Override the spillover root for tests without mutating `$HOME`.
107 #[cfg(any(test, feature = "test-support"))]
108 pub fn set_test_spillover_root(root: Option<PathBuf>) -> Option<PathBuf> {
109 let mut guard = TEST_SPILLOVER_ROOT
110 .lock()
111 .unwrap_or_else(|err| err.into_inner());
112 std::mem::replace(&mut *guard, root)
113 }
114
115 /// Resolve the spillover-file path for a tool call id. Sanitises the
116 /// id so that a hostile value can't escape the storage directory.
117 /// Returns `None` for empty / fully-invalid ids; the caller should
118 /// treat that as "spillover unavailable" and skip the write.
119 #[must_use]
120 pub fn spillover_path(id: &str) -> Option<PathBuf> {
121 let sanitised = sanitise_id(id)?;
122 Some(spillover_root()?.join(format!("{sanitised}.txt")))
123 }
124
125 #[must_use]
126 pub fn legacy_spillover_ownership_path(payload_path: &Path) -> PathBuf {
127 payload_path.with_extension("owner.json")
128 }
129
130 /// Publish the proof needed to retrieve a legacy-global spillover safely.
131 ///
132 /// Payload publication happens first. If this atomic sidecar write fails, the
133 /// payload is deliberately left unowned and therefore inaccessible through
134 /// `retrieve_tool_result`; callers must not advertise a retrieval hint.
135 pub fn publish_legacy_spillover_ownership(
136 payload_path: &Path,
137 session_id: &str,
138 bytes: &[u8],
139 ) -> io::Result<PathBuf> {
140 if session_id.trim().is_empty() {
141 return Err(io::Error::new(
142 io::ErrorKind::InvalidInput,
143 "legacy spillover ownership requires a session id",
144 ));
145 }
146 let ownership = LegacySpilloverOwnership {
147 schema_version: LEGACY_SPILLOVER_OWNER_SCHEMA_VERSION,
148 origin_session: session_id.to_string(),
149 digest: codewhale_runtime::hashing::sha256_hex(bytes),
150 size_bytes: bytes.len().try_into().unwrap_or(u64::MAX),
151 };
152 let sidecar = legacy_spillover_ownership_path(payload_path);
153 let encoded = serde_json::to_vec_pretty(&ownership)
154 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
155 codewhale_util::utils::write_atomic(&sidecar, &encoded)?;
156 Ok(sidecar)
157 }
158
159 pub fn read_legacy_spillover_ownership(
160 payload_path: &Path,
161 ) -> io::Result<LegacySpilloverOwnership> {
162 let sidecar = legacy_spillover_ownership_path(payload_path);
163 if std::fs::symlink_metadata(&sidecar)?
164 .file_type()
165 .is_symlink()
166 {
167 return Err(io::Error::new(
168 io::ErrorKind::PermissionDenied,
169 "legacy spillover ownership sidecar must not be a symlink",
170 ));
171 }
172 use std::io::Read;
173 const MAX_OWNERSHIP_BYTES: u64 = 64 * 1024;
174 let parent = sidecar
175 .parent()
176 .ok_or_else(|| io::Error::other("missing ownership parent"))?;
177 let filename = sidecar
178 .file_name()
179 .ok_or_else(|| io::Error::other("missing ownership filename"))?;
180 let file = codewhale_util::files::WorkspaceFile::open_delivery(parent, Path::new(filename))?;
181 let mut raw = Vec::new();
182 file.open_file()?
183 .take(MAX_OWNERSHIP_BYTES + 1)
184 .read_to_end(&mut raw)?;
185 if raw.len() as u64 > MAX_OWNERSHIP_BYTES {
186 return Err(io::Error::new(
187 io::ErrorKind::InvalidData,
188 "legacy ownership metadata exceeds limit",
189 ));
190 }
191 let ownership = serde_json::from_slice::<LegacySpilloverOwnership>(&raw)
192 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
193 if ownership.schema_version != LEGACY_SPILLOVER_OWNER_SCHEMA_VERSION {
194 return Err(io::Error::new(
195 io::ErrorKind::InvalidData,
196 "unsupported legacy spillover ownership schema",
197 ));
198 }
199 Ok(ownership)
200 }
201
202 /// Resolve the spillover-file path for a SHA256 content hash. Separate
203 /// namespace (`sha_<hex>.txt`) from the tool-call-id files so legacy
204 /// SHA-addressed evidence can be recognized without colliding with
205 /// tool-call references. Retrieval still requires matching ownership
206 /// metadata. `sha` must be the raw 64-char lowercase hex digest —
207 /// case-insensitive matching is done by the caller.
208 #[must_use]
209 pub fn sha_spillover_path(sha: &str) -> Option<PathBuf> {
210 let sha = sha.trim().to_ascii_lowercase();
211 if !is_valid_sha256(&sha) {
212 return None;
213 }
214 Some(spillover_root()?.join(format!("sha_{sha}.txt")))
215 }
216
217 /// True when `s` is a 64-character lowercase ASCII hex string. Used
218 /// to detect bare SHA refs the model might pass to retrieval and to
219 /// validate input to [`sha_spillover_path`].
220 #[must_use]
221 pub fn is_valid_sha256(s: &str) -> bool {
222 s.len() == 64
223 && s.chars()
224 .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
225 }
226
227 /// Write a legacy SHA-addressed spillover fixture for ownership tests.
228 #[cfg(any(test, feature = "test-support"))]
229 pub fn write_sha_spillover(sha: &str, content: &str) -> io::Result<PathBuf> {
230 let path = sha_spillover_path(sha).ok_or_else(|| {
231 io::Error::new(
232 io::ErrorKind::InvalidInput,
233 "sha must be a 64-char lowercase hex digest",
234 )
235 })?;
236 if path.exists() {
237 return Ok(path);
238 }
239 if let Some(parent) = path.parent() {
240 fs::create_dir_all(parent)?;
241 }
242 codewhale_util::utils::write_atomic(&path, content.as_bytes())?;
243 Ok(path)
244 }
245
246 /// Write `content` to the spillover file for `id`. Creates the
247 /// parent directory if needed. Returns the resolved path on success.
248 ///
249 /// Atomic via `write` + filesystem rename guarantees from the
250 /// underlying OS — the file is created at a temp name first and
251 /// then renamed into place. Failures bubble up as `io::Error` so the
252 /// caller can decide whether to surface them.
253 pub fn write_spillover(id: &str, content: &str) -> io::Result<PathBuf> {
254 let path = spillover_path(id).ok_or_else(|| {
255 io::Error::new(
256 io::ErrorKind::InvalidInput,
257 "could not resolve spillover path (empty/invalid id or missing home directory)",
258 )
259 })?;
260 if let Some(parent) = path.parent() {
261 fs::create_dir_all(parent)?;
262 }
263 codewhale_util::utils::write_atomic(&path, content.as_bytes())?;
264 Ok(path)
265 }
266
267 /// Drop spillover files older than `max_age`. Returns the number of
268 /// files removed. Non-fatal: directory-missing returns 0; per-file
269 /// errors are logged and skipped. Mirrors
270 /// [`crate::session_manager::prune_workspace_snapshots`].
271 pub fn prune_older_than(max_age: Duration) -> io::Result<usize> {
272 let Some(root) = spillover_root() else {
273 return Ok(0);
274 };
275 if !root.exists() {
276 return Ok(0);
277 }
278 let cutoff = SystemTime::now()
279 .checked_sub(max_age)
280 .unwrap_or(SystemTime::UNIX_EPOCH);
281 let mut pruned = 0usize;
282 for entry in fs::read_dir(&root)? {
283 let entry = match entry {
284 Ok(e) => e,
285 Err(err) => {
286 tracing::warn!(target: "spillover", ?err, "skipping unreadable dir entry");
287 continue;
288 }
289 };
290 let path = entry.path();
291 if !path.is_file() {
292 continue;
293 }
294 let modified = match entry.metadata().and_then(|m| m.modified()) {
295 Ok(t) => t,
296 Err(err) => {
297 tracing::warn!(target: "spillover", ?err, ?path, "skipping unreadable mtime");
298 continue;
299 }
300 };
301 if modified < cutoff {
302 if let Err(err) = fs::remove_file(&path) {
303 tracing::warn!(target: "spillover", ?err, ?path, "spillover prune skipped a file");
304 continue;
305 }
306 pruned += 1;
307 }
308 }
309 Ok(pruned)
310 }
311
312 /// Convenience for the common "too long? spill it." pattern. If
313 /// `content` is at or below `threshold` bytes, returns `None` and the
314 /// caller keeps the inline content. Above the threshold, writes the
315 /// full content to the spillover file and returns
316 /// `Some((head, path))` where `head` is the leading slice the caller
317 /// can show inline. The trailing tail isn't returned — `path` is the
318 /// canonical reference.
319 ///
320 /// `head_bytes` controls how much inline content the caller wants to
321 /// keep. Pass `threshold` for "preserve as much as fits inline" or
322 /// a smaller value (e.g. `4 * 1024`) for "show a peek".
323 pub fn maybe_spillover(
324 id: &str,
325 content: &str,
326 threshold: usize,
327 head_bytes: usize,
328 ) -> io::Result<Option<(String, PathBuf)>> {
329 if content.len() <= threshold {
330 return Ok(None);
331 }
332 let path = write_spillover(id, content)?;
333 // Don't slice mid-utf8: walk back to a char boundary if needed.
334 let cut = head_bytes.min(content.len());
335 let cut = (0..=cut)
336 .rev()
337 .find(|&i| content.is_char_boundary(i))
338 .unwrap_or(0);
339 Ok(Some((content[..cut].to_string(), path)))
340 }
341
342 /// Inline head retained when [`apply_spillover`] truncates a tool
343 /// result. 32 KiB is large enough for the model to keep meaningful
344 /// context (a long stack trace, a `git diff` head, a directory
345 /// listing of typical depth) without consuming the lion's share of
346 /// the per-turn context budget. The full output is preserved
347 /// internally and opens in the tool details view.
348 pub const SPILLOVER_HEAD_BYTES: usize = 32 * 1024;
349 /// Inline tail retained alongside the head so compiler summaries and final
350 /// test failures are not systematically hidden by truncation.
351 pub const SPILLOVER_TAIL_BYTES: usize = 8 * 1024;
352
353 /// Inline head/tail budgets for the adaptive evidence bands. Hybrid results
354 /// keep a generous 32 KiB head + 8 KiB tail so mid-size outputs stay mostly
355 /// readable; handle-only results keep a 16 KiB head + 4 KiB tail. The head
356 /// and tail windows never overlap ([`head_tail_windows`]).
357 const HYBRID_HEAD_BYTES: usize = 32 * 1024;
358 const HYBRID_TAIL_BYTES: usize = 8 * 1024;
359 const HANDLE_ONLY_HEAD_BYTES: usize = 16 * 1024;
360 const HANDLE_ONLY_TAIL_BYTES: usize = 4 * 1024;
361
362 /// Phrase used only by the TUI expand affordance and the UI-side detection of
363 /// historical truncated previews. Never emitted into model-facing content:
364 /// the model cannot open the tool details view, so the model-facing footer
365 /// carries the artifact path and a recovery instruction instead.
366 pub const SPILLOVER_PREVIEW_HINT: &str = "view full output in the tool details view";
367
368 /// Model-facing recovery instruction for a truncated tool result.
369 ///
370 /// The previous text — "read it back with the read_file tool or with sed line
371 /// ranges" — named `read_file`, which is not model-visible at all (only `File`
372 /// is), and otherwise leaned on reaching the artifact by path. Reaching it by
373 /// path is *conditional*: `ToolContext::resolve_path` short-circuits under
374 /// trust mode, so `File action="read"` on an artifact under
375 /// `~/.codewhale/sessions/` succeeds in a trusted/auto session and is refused
376 /// as a path escape otherwise — and even when it succeeds it pages the file
377 /// rather than seeking the omitted range. Meanwhile `retrieve_tool_result` —
378 /// model-visible, purpose-built, unconditional, and already named correctly by
379 /// the web overflow path in `tools/web/overflow.rs` — went unmentioned.
380 /// `tests/adaptive_evidence_acceptance.rs` proves end to end that a model
381 /// handed one of these receipts can take the named ref and get the omitted
382 /// bytes back.
383 ///
384 /// The distinction that matters is retrievability, not tidiness. An adaptive
385 /// session artifact carries an `art_<id>` the retrieval tool resolves, so name
386 /// it. A legacy global spillover is authorized by an ownership sidecar whose
387 /// write is allowed to fail (see [`publish_legacy_spillover_ownership`]), so
388 /// promising retrieval there would just be a fourth dead route; say plainly
389 /// that there is no tool call for it and name what does work instead.
390 pub fn spillover_recovery_instruction(retrieval_ref: Option<&str>) -> String {
391 spillover_recovery_instruction_for(retrieval_ref, None)
392 }
393
394 fn spillover_recovery_instruction_for(
395 retrieval_ref: Option<&str>,
396 omitted_lines: Option<usize>,
397 ) -> String {
398 match retrieval_ref {
399 Some(reference) if omitted_lines.is_some_and(|lines| lines <= 3) => format!(
400 "{SPILLOVER_RECOVERY_HINT} call retrieve_tool_result with ref=\"{reference}\" \
401 (it is one or a few long lines: mode=\"summary\" for its structure, \
402 mode=\"json\" with jsonpath=\"$.field\" for part of a JSON value, \
403 mode=\"query\" with query=\"…\" to search it)"
404 ),
405 Some(reference) => format!(
406 "{SPILLOVER_RECOVERY_HINT} call retrieve_tool_result with ref=\"{reference}\" \
407 (mode=\"tail\" for the end, mode=\"lines\" with lines=\"A-B\" for a line range, \
408 mode=\"query\" with query=\"…\" to search it, mode=\"json\" for JSON)"
409 ),
410 None => format!(
411 "{SPILLOVER_RECOVERY_HINT} no tool call reaches this copy — re-run the command \
412 with narrower output (a tighter filter, or head/tail) if you need the rest"
413 ),
414 }
415 }
416
417 /// Model-facing footer for a truncated tool result. Names how much was
418 /// omitted (bytes and lines), where the complete output lives on disk, and
419 /// how the model can read the omitted range back.
420 fn spillover_preview_footer(
421 omitted_bytes: usize,
422 omitted_lines: usize,
423 recovery_path: &str,
424 retrieval_ref: Option<&str>,
425 ) -> String {
426 format!(
427 "… {} of output omitted ({omitted_lines} lines) — full output at {recovery_path}; {}",
428 codewhale_runtime::artifacts::format_byte_size(
429 omitted_bytes.try_into().unwrap_or(u64::MAX)
430 ),
431 spillover_recovery_instruction_for(retrieval_ref, Some(omitted_lines))
432 )
433 }
434
435 /// Split `content` into a head of at most `head_bytes` and a tail of at most
436 /// `tail_bytes` that never overlap: the tail window always starts at or after
437 /// the head window ends, so no byte of the output appears twice and the
438 /// omitted count is exact.
439 fn head_tail_windows(content: &str, head_bytes: usize, tail_bytes: usize) -> (&str, &str) {
440 let head_end = (0..=head_bytes.min(content.len()))
441 .rev()
442 .find(|&index| content.is_char_boundary(index))
443 .unwrap_or(0);
444 let tail_floor = content.len().saturating_sub(tail_bytes).max(head_end);
445 let tail_start = (tail_floor..=content.len())
446 .find(|&index| content.is_char_boundary(index))
447 .unwrap_or(content.len());
448 (&content[..head_end], &content[tail_start..])
449 }
450
451 /// Build the model-facing preview for a truncated tool result: the head, an
452 /// honest footer naming how much was omitted and where the full output can be
453 /// read back, and a short retained tail. When the head and tail windows cover
454 /// the whole output (nothing was actually omitted), the content is returned
455 /// unchanged — the preview never claims a truncation that did not happen.
456 fn truncated_preview(
457 head: &str,
458 tail: &str,
459 original: &str,
460 recovery_path: &str,
461 retrieval_ref: Option<&str>,
462 ) -> String {
463 let omitted = original.len().saturating_sub(head.len() + tail.len());
464 if omitted == 0 {
465 return original.to_string();
466 }
467 let omitted_lines = original[head.len()..original.len() - tail.len()]
468 .lines()
469 .count();
470 format!(
471 "{head}\n\n{}\n\n…\n{tail}",
472 spillover_preview_footer(omitted, omitted_lines, recovery_path, retrieval_ref)
473 )
474 }
475
476 /// Apply spillover to a tool result in place. If the result's
477 /// content exceeds [`SPILLOVER_THRESHOLD_BYTES`], writes the full
478 /// content to a sibling file under `~/.codewhale/tool_outputs/`,
479 /// replaces `result.content` with a [`SPILLOVER_HEAD_BYTES`] head
480 /// plus a footer naming the spillover path and how to read the
481 /// omitted range back, and stamps `metadata.spillover_path` so the
482 /// UI can render its expand annotation.
483 ///
484 /// Returns the spillover path on success, `None` if no spillover
485 /// happened (content small enough, error result, write failure).
486 /// Failures are logged but never bubble up — a tool that produced a
487 /// result shouldn't be marked failed because the spillover writer
488 /// couldn't reach disk; a bounded preview then says the full output could
489 /// not be saved, without advertising a recovery path or artifact.
490 ///
491 /// Error results (`success == false`) are skipped: error messages
492 /// are typically short, and turning them into a truncated preview
493 /// would just hide the error from the model's reasoning.
494 pub fn apply_spillover(result: &mut ToolResult, tool_id: &str) -> Option<PathBuf> {
495 apply_spillover_inner(result, tool_id, None, false)
496 }
497
498 /// Apply spillover and publish session-scoped exact evidence.
499 ///
500 /// The default (classic) path writes the full bytes under the origin session
501 /// and replaces oversized content with a bounded head/tail preview whose
502 /// footer names the artifact path and how to read the omitted range back.
503 /// The adaptive evidence lane is reachable only through the explicit
504 /// `CODEWHALE_ADAPTIVE_OUTPUT_ROUTING` opt-in.
505 pub fn apply_spillover_with_artifact(
506 result: &mut ToolResult,
507 tool_id: &str,
508 tool_name: &str,
509 session_id: &str,
510 ) -> Option<PathBuf> {
511 apply_spillover_inner(
512 result,
513 tool_id,
514 Some(ArtifactSpilloverContext {
515 tool_name,
516 session_id,
517 }),
518 false,
519 )
520 }
521
522 /// [`apply_spillover_with_artifact`] for callers whose error payloads are
523 /// routinely as large as their successes — sub-agent tool output is often a
524 /// full build log, so the root loop's pass-errors-through rationale does not
525 /// hold there.
526 pub fn apply_spillover_with_artifact_including_errors(
527 result: &mut ToolResult,
528 tool_id: &str,
529 tool_name: &str,
530 session_id: &str,
531 ) -> Option<PathBuf> {
532 apply_spillover_inner(
533 result,
534 tool_id,
535 Some(ArtifactSpilloverContext {
536 tool_name,
537 session_id,
538 }),
539 true,
540 )
541 }
542
543 #[derive(Clone, Copy)]
544 struct ArtifactSpilloverContext<'a> {
545 tool_name: &'a str,
546 session_id: &'a str,
547 }
548
549 fn apply_spillover_inner(
550 result: &mut ToolResult,
551 tool_id: &str,
552 artifact_context: Option<ArtifactSpilloverContext<'_>>,
553 bound_errors: bool,
554 ) -> Option<PathBuf> {
555 if crate::tools::large_output_router::adaptive_output_routing_enabled()
556 && let Some(context) = artifact_context
557 {
558 return apply_adaptive_evidence_inner(result, tool_id, context);
559 }
560 if !result.success && !bound_errors {
561 return None;
562 }
563 if result.content.len() <= SPILLOVER_THRESHOLD_BYTES {
564 return None;
565 }
566 let original_content = result.content.clone();
567 let outcome = match maybe_spillover(
568 tool_id,
569 &original_content,
570 SPILLOVER_THRESHOLD_BYTES,
571 SPILLOVER_HEAD_BYTES,
572 ) {
573 Ok(Some(pair)) => pair,
574 Ok(None) => return None,
575 Err(err) => {
576 tracing::warn!(
577 target: "spillover",
578 ?err,
579 tool_id,
580 "spillover write failed; retaining a bounded unsaved preview"
581 );
582 bound_unpersisted_output(result, SPILLOVER_HEAD_BYTES, SPILLOVER_TAIL_BYTES);
583 return None;
584 }
585 };
586 let (_head, path) = outcome;
587 let (head, tail) = head_tail_windows(
588 &original_content,
589 SPILLOVER_HEAD_BYTES,
590 SPILLOVER_TAIL_BYTES,
591 );
592 let digest = codewhale_runtime::hashing::sha256_hex(original_content.as_bytes());
593 let path_str = path.display().to_string();
594
595 // Keep publishing the legacy ownership proof even though the model-facing
596 // footer no longer mentions retrieval: the tool-details pager authorizes
597 // legacy spillover reads through this sidecar.
598 if let Some(context) = artifact_context
599 && let Err(err) = publish_legacy_spillover_ownership(
600 &path,
601 context.session_id,
602 original_content.as_bytes(),
603 )
604 {
605 tracing::warn!(
606 target: "spillover",
607 ?err,
608 tool_id,
609 "legacy spillover ownership publication failed"
610 );
611 }
612
613 let mut artifact_path = None;
614 if let Some(context) = artifact_context {
615 let artifact_id = codewhale_runtime::artifacts::artifact_id_for_tool_call(tool_id);
616 let persisted = if let Some(existing) =
617 pre_persisted_session_artifact(result, &artifact_id, context.session_id)
618 {
619 Ok((
620 existing.absolute_path,
621 existing.relative_path,
622 Some(existing.byte_size),
623 ))
624 } else {
625 codewhale_runtime::artifacts::write_session_artifact_immutable(
626 context.session_id,
627 &artifact_id,
628 original_content.as_bytes(),
629 )
630 .map(|(absolute_path, relative_path)| (absolute_path, relative_path, None))
631 };
632 match persisted {
633 Ok((absolute_path, relative_path, existing_byte_size)) => {
634 let record = match existing_byte_size {
635 Some(byte_size) => {
636 codewhale_runtime::artifacts::record_tool_output_artifact_with_size(
637 context.session_id,
638 tool_id,
639 context.tool_name,
640 relative_path.clone(),
641 byte_size,
642 &original_content,
643 )
644 }
645 None => codewhale_runtime::artifacts::record_tool_output_artifact(
646 context.session_id,
647 tool_id,
648 context.tool_name,
649 relative_path.clone(),
650 &original_content,
651 ),
652 };
653 result.content = truncated_preview(
654 head,
655 tail,
656 &original_content,
657 &codewhale_runtime::artifacts::format_artifact_relative_path(&absolute_path),
658 Some(artifact_id.as_str()),
659 );
660 artifact_path = Some((absolute_path, relative_path, record));
661 }
662 Err(err) => {
663 tracing::warn!(
664 target: "spillover",
665 ?err,
666 tool_id,
667 "session artifact write failed; falling back to legacy spillover footer"
668 );
669 }
670 }
671 }
672
673 if artifact_path.is_none() {
674 // Legacy fallback: no session artifact was written, so there is no
675 // `art_<id>` ref to hand over — only the on-disk path.
676 result.content = truncated_preview(head, tail, &original_content, &path_str, None);
677 }
678
679 let obj = metadata_object_mut(result);
680 if let Some((absolute_path, relative_path, record)) = artifact_path.as_ref() {
681 stamp_artifact_metadata(obj, absolute_path, relative_path, record);
682 obj.insert(
683 "legacy_spillover_path".into(),
684 serde_json::Value::String(path_str),
685 );
686 } else {
687 obj.insert("spillover_path".into(), serde_json::Value::String(path_str));
688 }
689 if let Some(obj) = result
690 .metadata
691 .as_mut()
692 .and_then(serde_json::Value::as_object_mut)
693 {
694 obj.insert("truncated".into(), serde_json::Value::Bool(true));
695 obj.insert(
696 "content_digest".into(),
697 serde_json::Value::String(format!("sha256:{digest}")),
698 );
699 if artifact_path.is_some() {
700 // Plain hex, the same form the adaptive path and the workspace
701 // read `revision` use; the turn artifact ref carries it verbatim.
702 obj.insert(
703 "artifact_digest".into(),
704 serde_json::Value::String(digest.clone()),
705 );
706 }
707 obj.insert(
708 "original_byte_count".into(),
709 serde_json::Value::Number(serde_json::Number::from(original_content.len() as u64)),
710 );
711 obj.insert(
712 "retained_head_bytes".into(),
713 serde_json::Value::Number(serde_json::Number::from(head.len() as u64)),
714 );
715 obj.insert(
716 "retained_tail_bytes".into(),
717 serde_json::Value::Number(serde_json::Number::from(tail.len() as u64)),
718 );
719 obj.insert(
720 "original_line_count".into(),
721 serde_json::Value::Number(serde_json::Number::from(
722 original_content.lines().count() as u64
723 )),
724 );
725 }
726 artifact_path
727 .map(|(absolute_path, _, _)| absolute_path)
728 .or(Some(path))
729 }
730
731 /// The result's metadata as a JSON object, created when absent. Metadata that
732 /// is not an object is kept under `_prior` rather than dropped.
733 fn metadata_object_mut(result: &mut ToolResult) -> &mut serde_json::Map<String, serde_json::Value> {
734 let metadata = result.metadata.get_or_insert_with(|| serde_json::json!({}));
735 if !metadata.is_object() {
736 let prior = std::mem::replace(metadata, serde_json::json!({}));
737 if let Some(obj) = metadata.as_object_mut() {
738 obj.insert("_prior".into(), prior);
739 }
740 }
741 metadata
742 .as_object_mut()
743 .expect("metadata was just made an object")
744 }
745
746 /// Bound a failed persistence attempt without turning its preview into exact
747 /// evidence. The same windows and footer authority serve both routing modes.
748 fn bound_unpersisted_output(result: &mut ToolResult, head_bytes: usize, tail_bytes: usize) {
749 let original = &result.content;
750 let (head, tail) = head_tail_windows(original, head_bytes, tail_bytes);
751 let omitted = original.len().saturating_sub(head.len() + tail.len());
752 if omitted == 0 {
753 return;
754 }
755 let original_bytes = original.len();
756 let original_lines = original.lines().count();
757 let head_len = head.len();
758 let tail_len = tail.len();
759 let omitted_lines = original[head_len..original_bytes - tail_len]
760 .lines()
761 .count();
762 let digest = codewhale_runtime::hashing::sha256_hex(original.as_bytes());
763 result.content = format!(
764 "{head}\n\n{}\n\n…\n{tail}",
765 preview_footer(omitted, omitted_lines, None, None)
766 );
767 let object = metadata_object_mut(result);
768 // A prior metadata envelope cannot claim that it retained these bytes.
769 for key in [
770 "spillover_path",
771 "legacy_spillover_path",
772 "artifact_path",
773 "artifact_id",
774 "artifact_session_id",
775 "artifact_relative_path",
776 "artifact_byte_size",
777 "artifact_digest",
778 "artifact_generation",
779 "artifact_encoding",
780 "artifact_retention_state",
781 "artifact_preview",
782 "artifact_record",
783 ] {
784 object.remove(key);
785 }
786 object.insert("evidence_available".into(), false.into());
787 object.insert("output_persistence_failed".into(), true.into());
788 object.insert("truncated".into(), true.into());
789 object.insert("content_digest".into(), format!("sha256:{digest}").into());
790 object.insert("original_byte_count".into(), original_bytes.into());
791 object.insert("original_line_count".into(), original_lines.into());
792 object.insert("retained_head_bytes".into(), head_len.into());
793 object.insert("retained_tail_bytes".into(), tail_len.into());
794 }
795
796 /// Stamp the keys the TUI, receipts and `retrieve_tool_result` use to find a
797 /// session artifact that holds a tool call's full output.
798 fn stamp_artifact_metadata(
799 obj: &mut serde_json::Map<String, serde_json::Value>,
800 absolute_path: &Path,
801 relative_path: &Path,
802 record: &codewhale_runtime::artifacts::ArtifactRecord,
803 ) {
804 let absolute = serde_json::Value::String(absolute_path.display().to_string());
805 obj.insert("spillover_path".into(), absolute.clone());
806 obj.insert("artifact_path".into(), absolute);
807 obj.insert("artifact_id".into(), record.id.clone().into());
808 obj.insert(
809 "artifact_session_id".into(),
810 record.session_id.clone().into(),
811 );
812 obj.insert(
813 "artifact_relative_path".into(),
814 codewhale_runtime::artifacts::format_artifact_relative_path(relative_path).into(),
815 );
816 obj.insert("artifact_byte_size".into(), record.byte_size.into());
817 obj.insert("artifact_preview".into(), record.preview.clone().into());
818 }
819
820 /// Save a tool call's full output as a session artifact before the model's
821 /// view of it is cut to the inline budget (#6508).
822 ///
823 /// The result's content is left as it is, so the UI cell still shows it; only
824 /// the metadata gains the artifact keys, so the model-context view can name a
825 /// ref `retrieve_tool_result` resolves. A result that already has an artifact
826 /// (spillover wrote one) is left alone. Returns whether an artifact exists
827 /// afterwards. Publication is immutable: a reused ID may name the same bytes,
828 /// but never replace earlier output. A failed write is logged and reported as
829 /// `false`; the caller's footer then says no tool call reaches the rest instead
830 /// of promising a ref.
831 pub fn preserve_full_output_for_model_context(
832 result: &mut ToolResult,
833 tool_id: &str,
834 tool_name: &str,
835 session_id: &str,
836 ) -> bool {
837 if result
838 .metadata
839 .as_ref()
840 .and_then(|metadata| metadata.get("output_persistence_failed"))
841 .and_then(serde_json::Value::as_bool)
842 == Some(true)
843 {
844 // Persistence already lost the omitted bytes. Saving this preview as
845 // the full output would manufacture an exact-evidence receipt.
846 return false;
847 }
848 if result
849 .metadata
850 .as_ref()
851 .and_then(|metadata| metadata.get("artifact_id"))
852 .is_some()
853 {
854 return true;
855 }
856 let artifact_id = codewhale_runtime::artifacts::artifact_id_for_tool_call(tool_id);
857 match codewhale_runtime::artifacts::write_session_artifact_immutable(
858 session_id,
859 &artifact_id,
860 result.content.as_bytes(),
861 ) {
862 Ok((absolute_path, relative_path)) => {
863 let record = codewhale_runtime::artifacts::record_tool_output_artifact(
864 session_id,
865 tool_id,
866 tool_name,
867 relative_path.clone(),
868 &result.content,
869 );
870 let digest = codewhale_runtime::hashing::sha256_hex(result.content.as_bytes());
871 let obj = metadata_object_mut(result);
872 stamp_artifact_metadata(obj, &absolute_path, &relative_path, &record);
873 obj.insert("content_digest".into(), format!("sha256:{digest}").into());
874 true
875 }
876 Err(err) => {
877 tracing::warn!(
878 target: "spillover",
879 ?err,
880 tool_id,
881 "could not save full tool output before cutting it for model context"
882 );
883 false
884 }
885 }
886 }
887
888 /// Bytes reserved beside the footer for the preview's blank lines and the
889 /// `…` separator, plus slack for the omitted-size text changing length.
890 const PREVIEW_FRAME_BYTES: usize = 32;
891
892 /// Footer for a preview whose full output lives at `recovery_path`, or, when
893 /// it is `None`, one that says plainly the full output could not be saved.
894 fn preview_footer(
895 omitted_bytes: usize,
896 omitted_lines: usize,
897 recovery_path: Option<&str>,
898 retrieval_ref: Option<&str>,
899 ) -> String {
900 match recovery_path {
901 Some(path) => spillover_preview_footer(omitted_bytes, omitted_lines, path, retrieval_ref),
902 None => format!(
903 "… {} of output omitted ({omitted_lines} lines) — the full output could not be saved; {}",
904 codewhale_runtime::artifacts::format_byte_size(
905 omitted_bytes.try_into().unwrap_or(u64::MAX)
906 ),
907 spillover_recovery_instruction(None)
908 ),
909 }
910 }
911
912 /// Drop the path and preview before sacrificing the retrieval reference.
913 /// Budgets smaller than this complete instruction cannot contain a usable
914 /// receipt: keep it intact and let the wire's recovery-marker guard preserve it.
915 fn compact_recovery_footer(retrieval_ref: Option<&str>) -> String {
916 match retrieval_ref {
917 Some(reference) => {
918 format!("{SPILLOVER_RECOVERY_HINT} retrieve_tool_result ref=\"{reference}\"")
919 }
920 None => format!("{SPILLOVER_RECOVERY_HINT} re-run with narrower output"),
921 }
922 }
923
924 /// Fit `content` into `budget` characters for the model: nothing changes when
925 /// it already fits; otherwise a head (two thirds) and a tail (one third)
926 /// around one recovery footer. The cut is measured in bytes, so the result
927 /// never exceeds `budget` characters either, unless the budget cannot hold
928 /// even a compact recovery instruction (which must remain intact).
929 pub fn fit_to_inline_budget(
930 content: &str,
931 budget: usize,
932 recovery_path: Option<&str>,
933 retrieval_ref: Option<&str>,
934 ) -> String {
935 if content.chars().count() <= budget {
936 return content.to_string();
937 }
938 let footer = preview_footer(
939 content.len(),
940 content.lines().count(),
941 recovery_path,
942 retrieval_ref,
943 );
944 if footer.len() + PREVIEW_FRAME_BYTES > budget {
945 return compact_recovery_footer(retrieval_ref);
946 }
947 let room = budget.saturating_sub(footer.len() + PREVIEW_FRAME_BYTES);
948 let head_bytes = room * 2 / 3;
949 let (head, tail) = head_tail_windows(content, head_bytes, room - head_bytes);
950 let omitted = content.len().saturating_sub(head.len() + tail.len());
951 let omitted_lines = content[head.len()..content.len() - tail.len()]
952 .lines()
953 .count();
954 format!(
955 "{head}\n\n{}\n\n…\n{tail}",
956 preview_footer(omitted, omitted_lines, recovery_path, retrieval_ref)
957 )
958 }
959
960 /// Re-fit a spillover preview (head, footer, tail) to `budget` characters.
961 ///
962 /// Spillover already saved the full output, so this writes nothing: it keeps
963 /// a shorter head and tail from the preview's own windows (found through the
964 /// `retained_head_bytes`/`retained_tail_bytes` metadata spillover stamped) and
965 /// re-emits one footer that names the same recovery ref. Returns `None` when
966 /// the metadata does not describe this preview, so the caller can fall back.
967 pub fn refit_spilled_preview(
968 preview: &str,
969 metadata: &serde_json::Value,
970 budget: usize,
971 recovery_path: Option<&str>,
972 retrieval_ref: Option<&str>,
973 ) -> Option<String> {
974 if preview.chars().count() <= budget {
975 return Some(preview.to_string());
976 }
977 let field = |key: &str| {
978 metadata
979 .get(key)
980 .and_then(serde_json::Value::as_u64)
981 .and_then(|value| usize::try_from(value).ok())
982 };
983 let head_len = field("retained_head_bytes")?;
984 let tail_len = field("retained_tail_bytes")?;
985 let original_len = field("original_byte_count")?;
986 if head_len + tail_len > preview.len()
987 || !preview.is_char_boundary(head_len)
988 || !preview.is_char_boundary(preview.len() - tail_len)
989 {
990 return None;
991 }
992 let head_window = &preview[..head_len];
993 let tail_window = &preview[preview.len() - tail_len..];
994
995 let footer = preview_footer(
996 original_len,
997 field("original_line_count").unwrap_or(0),
998 recovery_path,
999 retrieval_ref,
1000 );
1001 if footer.len() + PREVIEW_FRAME_BYTES > budget {
1002 return Some(compact_recovery_footer(retrieval_ref));
1003 }
1004 let room = budget.saturating_sub(footer.len() + PREVIEW_FRAME_BYTES);
1005 let head_bytes = (room * 2 / 3).min(head_len);
1006 let tail_bytes = (room - head_bytes).min(tail_len);
1007 let (head, _) = head_tail_windows(head_window, head_bytes, 0);
1008 let (_, tail) = head_tail_windows(tail_window, 0, tail_bytes);
1009 let omitted = original_len.saturating_sub(head.len() + tail.len());
1010 let kept_lines = head.lines().count() + tail.lines().count();
1011 let omitted_lines = match field("original_line_count") {
1012 Some(total) => total.saturating_sub(kept_lines),
1013 // Older spills did not record a line count; count only the lines this
1014 // preview can see, which understates rather than invents.
1015 None => {
1016 head_window[head.len()..].lines().count()
1017 + tail_window[..tail_window.len() - tail.len()]
1018 .lines()
1019 .count()
1020 }
1021 };
1022 Some(format!(
1023 "{head}\n\n{}\n\n…\n{tail}",
1024 preview_footer(omitted, omitted_lines, recovery_path, retrieval_ref)
1025 ))
1026 }
1027
1028 struct PrePersistedSessionArtifact {
1029 absolute_path: PathBuf,
1030 relative_path: PathBuf,
1031 byte_size: u64,
1032 digest: String,
1033 }
1034
1035 fn pre_persisted_session_artifact(
1036 result: &ToolResult,
1037 expected_artifact_id: &str,
1038 expected_session_id: &str,
1039 ) -> Option<PrePersistedSessionArtifact> {
1040 let metadata = result.metadata.as_ref()?.as_object()?;
1041 if metadata
1042 .get("artifact_id")
1043 .and_then(serde_json::Value::as_str)?
1044 != expected_artifact_id
1045 {
1046 return None;
1047 }
1048 if metadata
1049 .get("artifact_session_id")
1050 .and_then(serde_json::Value::as_str)?
1051 != expected_session_id
1052 {
1053 return None;
1054 }
1055 let absolute_path = PathBuf::from(
1056 metadata
1057 .get("artifact_path")
1058 .and_then(serde_json::Value::as_str)?,
1059 );
1060 let relative_path = PathBuf::from(
1061 metadata
1062 .get("artifact_relative_path")
1063 .and_then(serde_json::Value::as_str)?,
1064 );
1065 let byte_size = metadata
1066 .get("artifact_byte_size")
1067 .and_then(serde_json::Value::as_u64)?;
1068 let digest = metadata
1069 .get("artifact_digest")
1070 .and_then(serde_json::Value::as_str)?
1071 .to_string();
1072 Some(PrePersistedSessionArtifact {
1073 absolute_path,
1074 relative_path,
1075 byte_size,
1076 digest,
1077 })
1078 }
1079
1080 fn apply_adaptive_evidence_inner(
1081 result: &mut ToolResult,
1082 tool_id: &str,
1083 context: ArtifactSpilloverContext<'_>,
1084 ) -> Option<PathBuf> {
1085 use crate::tools::large_output_router::{
1086 DEFAULT_LARGE_OUTPUT_THRESHOLD_TOKENS, EVIDENCE_RETENTION_SECS, EvidenceArtifact,
1087 EvidenceRetentionState, EvidenceRouting, estimate_tokens, publish_evidence_metadata,
1088 unix_millis_now,
1089 };
1090
1091 let artifact_id = result
1092 .metadata
1093 .as_ref()
1094 .and_then(|metadata| {
1095 crate::tools::shell::completed_bash_artifact_handle(
1096 metadata,
1097 context.tool_name,
1098 tool_id,
1099 context.session_id,
1100 )
1101 })
1102 .map(str::to_owned)
1103 .unwrap_or_else(|| codewhale_runtime::artifacts::artifact_id_for_tool_call(tool_id));
1104 let pre_persisted = pre_persisted_session_artifact(result, &artifact_id, context.session_id);
1105
1106 let estimated_tokens = estimate_tokens(&result.content);
1107 let threshold = result
1108 .metadata
1109 .as_ref()
1110 .and_then(|metadata| metadata.get("evidence_threshold_tokens"))
1111 .and_then(serde_json::Value::as_u64)
1112 .and_then(|value| usize::try_from(value).ok())
1113 .unwrap_or(DEFAULT_LARGE_OUTPUT_THRESHOLD_TOKENS);
1114 let routing = result
1115 .metadata
1116 .as_ref()
1117 .and_then(|metadata| metadata.get("evidence_routing"))
1118 .cloned()
1119 .and_then(|value| serde_json::from_value::<EvidenceRouting>(value).ok())
1120 .unwrap_or_else(|| EvidenceRouting::from_token_estimate(estimated_tokens, threshold));
1121 if routing == EvidenceRouting::Inline && pre_persisted.is_none() {
1122 return None;
1123 }
1124
1125 let original = result.content.clone();
1126 let (head_bytes, tail_bytes) = if routing == EvidenceRouting::Hybrid {
1127 (HYBRID_HEAD_BYTES, HYBRID_TAIL_BYTES)
1128 } else {
1129 (HANDLE_ONLY_HEAD_BYTES, HANDLE_ONLY_TAIL_BYTES)
1130 };
1131 let (head, tail) = head_tail_windows(&original, head_bytes, tail_bytes);
1132 let omitted = if routing == EvidenceRouting::Inline {
1133 0
1134 } else {
1135 original.len().saturating_sub(head.len() + tail.len())
1136 };
1137 if omitted == 0 && pre_persisted.is_none() {
1138 return None;
1139 }
1140 let head_len = head.len();
1141 let tail_len = tail.len();
1142
1143 let (relative_path, digest, size_bytes, content_type) = match pre_persisted.as_ref() {
1144 Some(existing) => (
1145 existing.relative_path.clone(),
1146 existing.digest.clone(),
1147 existing.byte_size,
1148 "text/plain".to_string(),
1149 ),
1150 None => (
1151 codewhale_runtime::artifacts::session_artifact_relative_path(&artifact_id),
1152 codewhale_runtime::hashing::sha256_hex(original.as_bytes()),
1153 original.len().try_into().unwrap_or(u64::MAX),
1154 if serde_json::from_str::<serde_json::Value>(&original).is_ok() {
1155 "application/json".to_string()
1156 } else {
1157 "text/plain".to_string()
1158 },
1159 ),
1160 };
1161 let now_ms = unix_millis_now();
1162 let proposed_artifact = EvidenceArtifact {
1163 handle: artifact_id.clone(),
1164 digest: digest.clone(),
1165 size_bytes,
1166 content_type,
1167 tool_name: context.tool_name.to_string(),
1168 call_id: tool_id.to_string(),
1169 origin_session: context.session_id.to_string(),
1170 generation: 1,
1171 redacted: false,
1172 encoding: "utf-8".to_string(),
1173 retention_state: EvidenceRetentionState::Live,
1174 created_at_unix_ms: now_ms,
1175 retain_until_unix_ms: now_ms.saturating_add(EVIDENCE_RETENTION_SECS * 1_000),
1176 storage_path: relative_path.clone(),
1177 };
1178 let artifact = match crate::tools::large_output_router::read_evidence_metadata(
1179 context.session_id,
1180 &artifact_id,
1181 ) {
1182 Ok(existing)
1183 if existing.digest == proposed_artifact.digest
1184 && existing.size_bytes == proposed_artifact.size_bytes
1185 && existing.call_id == proposed_artifact.call_id
1186 && existing.origin_session == proposed_artifact.origin_session =>
1187 {
1188 existing
1189 }
1190 Ok(_) => {
1191 tracing::warn!(target: "evidence", tool_id, "adaptive evidence replay conflicts with immutable metadata");
1192 if omitted > 0 {
1193 bound_unpersisted_output(result, head_bytes, tail_bytes);
1194 }
1195 return None;
1196 }
1197 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
1198 if let Err(err) = publish_evidence_metadata(context.session_id, &proposed_artifact) {
1199 tracing::warn!(target: "evidence", ?err, tool_id, "adaptive evidence metadata publication failed");
1200 if omitted > 0 {
1201 bound_unpersisted_output(result, head_bytes, tail_bytes);
1202 }
1203 return None;
1204 }
1205 proposed_artifact
1206 }
1207 Err(err) => {
1208 tracing::warn!(target: "evidence", ?err, tool_id, "adaptive evidence metadata validation failed");
1209 if omitted > 0 {
1210 bound_unpersisted_output(result, head_bytes, tail_bytes);
1211 }
1212 return None;
1213 }
1214 };
1215
1216 let (absolute_path, relative_path) = match pre_persisted {
1217 Some(existing) => (existing.absolute_path, existing.relative_path),
1218 None => match codewhale_runtime::artifacts::write_session_artifact_immutable(
1219 context.session_id,
1220 &artifact_id,
1221 original.as_bytes(),
1222 ) {
1223 Ok(paths) => paths,
1224 Err(err) => {
1225 tracing::warn!(target: "evidence", ?err, tool_id, "adaptive evidence content publication failed");
1226 bound_unpersisted_output(result, head_bytes, tail_bytes);
1227 return None;
1228 }
1229 },
1230 };
1231
1232 let mut record = codewhale_runtime::artifacts::record_tool_output_artifact_with_size(
1233 context.session_id,
1234 tool_id,
1235 context.tool_name,
1236 relative_path.clone(),
1237 artifact.size_bytes,
1238 &original,
1239 );
1240 record.id.clone_from(&artifact_id);
1241 if omitted > 0 {
1242 result.content = truncated_preview(
1243 head,
1244 tail,
1245 &original,
1246 &codewhale_runtime::artifacts::format_artifact_relative_path(&absolute_path),
1247 Some(artifact_id.as_str()),
1248 );
1249 }
1250 let metadata = result.metadata.get_or_insert_with(|| serde_json::json!({}));
1251 if let Some(object) = metadata.as_object_mut() {
1252 object.insert(
1253 "spillover_path".into(),
1254 absolute_path.display().to_string().into(),
1255 );
1256 object.insert("artifact_id".into(), artifact_id.into());
1257 object.insert("artifact_session_id".into(), context.session_id.into());
1258 object.insert(
1259 "artifact_relative_path".into(),
1260 codewhale_runtime::artifacts::format_artifact_relative_path(&relative_path).into(),
1261 );
1262 object.insert("artifact_byte_size".into(), artifact.size_bytes.into());
1263 object.insert("artifact_digest".into(), digest.into());
1264 object.insert("artifact_generation".into(), artifact.generation.into());
1265 object.insert("artifact_encoding".into(), artifact.encoding.into());
1266 object.insert("artifact_retention_state".into(), "live".into());
1267 object.insert("evidence_available".into(), true.into());
1268 object.insert("truncated".into(), true.into());
1269 object.insert("original_byte_count".into(), artifact.size_bytes.into());
1270 if omitted > 0 {
1271 object.insert("retained_head_bytes".into(), head_len.into());
1272 object.insert("retained_tail_bytes".into(), tail_len.into());
1273 }
1274 object.insert(
1275 "artifact_preview".into(),
1276 original.chars().take(200).collect::<String>().into(),
1277 );
1278 object.insert(
1279 "artifact_record".into(),
1280 serde_json::to_value(record).unwrap_or(serde_json::Value::Null),
1281 );
1282 }
1283 Some(absolute_path)
1284 }
1285
1286 /// Sanitise a tool call id for use as a filename. Keeps ASCII
1287 /// alphanumerics, `-`, and `_`; rejects `.` to keep `..` traversal
1288 /// out, rejects empty results. Returns `None` if the input contains
1289 /// no acceptable characters.
1290 fn sanitise_id(id: &str) -> Option<String> {
1291 let cleaned: String = id
1292 .chars()
1293 .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_')
1294 .collect();
1295 if cleaned.is_empty() {
1296 None
1297 } else {
1298 Some(cleaned)
1299 }
1300 }
1301
1302 #[must_use]
1303 pub fn json_len(value: &serde_json::Value) -> usize {
1304 struct Count(usize);
1305 impl io::Write for Count {
1306 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1307 self.0 += buf.len();
1308 Ok(buf.len())
1309 }
1310 fn flush(&mut self) -> io::Result<()> {
1311 Ok(())
1312 }
1313 }
1314 let mut count = Count(0);
1315 let _ = serde_json::to_writer(&mut count, value);
1316 count.0
1317 }
1318
1319 #[must_use]
1320 pub fn shrink_json(value: serde_json::Value, budget: usize) -> (serde_json::Value, usize) {
1321 if json_len(&value) <= budget {
1322 return (value, 0);
1323 }
1324 let mut omitted = 0;
1325 let value = shrink_json_inner(value, budget, &mut omitted);
1326 (value, omitted.max(1))
1327 }
1328
1329 fn shrink_json_inner(
1330 value: serde_json::Value,
1331 budget: usize,
1332 omitted: &mut usize,
1333 ) -> serde_json::Value {
1334 use serde_json::Value;
1335 const MIN_ENTRY_BYTES: usize = 8;
1336 match value {
1337 Value::String(text) => {
1338 let mut keep = budget.saturating_sub(5).min(text.len());
1339 loop {
1340 while !text.is_char_boundary(keep) {
1341 keep -= 1;
1342 }
1343 let cut = Value::String(format!("{}…", &text[..keep]));
1344 if keep == 0 || json_len(&cut) <= budget {
1345 *omitted += 1;
1346 return cut;
1347 }
1348 keep /= 2;
1349 }
1350 }
1351 Value::Array(items) => {
1352 let total = items.len();
1353 let mut kept = Vec::new();
1354 let mut used = 2;
1355 for item in items {
1356 let remaining = budget.saturating_sub(used + 1);
1357 if remaining < MIN_ENTRY_BYTES {
1358 break;
1359 }
1360 let fits = json_len(&item) <= remaining;
1361 let item = if fits {
1362 item
1363 } else {
1364 shrink_json_inner(item, remaining, omitted)
1365 };
1366 let len = json_len(&item);
1367 if len > remaining {
1368 break;
1369 }
1370 used += len + 1;
1371 kept.push(item);
1372 if !fits {
1373 break;
1374 }
1375 }
1376 *omitted += total - kept.len();
1377 Value::Array(kept)
1378 }
1379 Value::Object(map) => {
1380 let total = map.len();
1381 let mut kept = serde_json::Map::new();
1382 let mut used = 2;
1383 for (key, item) in map {
1384 if budget.saturating_sub(used) < MIN_ENTRY_BYTES {
1385 break;
1386 }
1387 let key_len = json_len(&Value::String(key.clone())) + 2;
1388 let remaining = budget.saturating_sub(used + key_len);
1389 if remaining < MIN_ENTRY_BYTES {
1390 continue;
1391 }
1392 let fits = json_len(&item) <= remaining;
1393 let item = if fits {
1394 item
1395 } else {
1396 shrink_json_inner(item, remaining, omitted)
1397 };
1398 let len = json_len(&item);
1399 if len > remaining {
1400 continue;
1401 }
1402 used += key_len + len;
1403 kept.insert(key, item);
1404 }
1405 *omitted += total - kept.len();
1406 Value::Object(kept)
1407 }
1408 other => other,
1409 }
1410 }
1411
1412 /// Override the storage roots for tests so they don't pollute the
1413 /// user's real `~/.codewhale/` directory. This uses explicit test hooks instead
1414 /// of `$HOME` because Windows home-dir resolution can ignore environment
1415 /// overrides and return the runner profile directory.
1416 #[cfg(any(test, feature = "test-support"))]
1417 pub fn with_test_home<F, R>(home: &Path, f: F) -> R
1418 where
1419 F: FnOnce() -> R,
1420 {
1421 let _artifact_guard = codewhale_runtime::artifacts::TEST_ARTIFACT_SESSIONS_GUARD
1422 .lock()
1423 .unwrap_or_else(|err| err.into_inner());
1424
1425 struct StorageRootOverride {
1426 prior_spillover: Option<PathBuf>,
1427 prior_artifacts: Option<PathBuf>,
1428 }
1429
1430 impl Drop for StorageRootOverride {
1431 fn drop(&mut self) {
1432 set_test_spillover_root(self.prior_spillover.take());
1433 codewhale_runtime::artifacts::set_test_artifact_sessions_root(
1434 self.prior_artifacts.take(),
1435 );
1436 }
1437 }
1438
1439 // Tests in this module serialize spillover through `TEST_GUARD`; the
1440 // artifact guard above protects the session-artifact root shared with
1441 // artifacts.rs tests.
1442 let prior_spillover =
1443 set_test_spillover_root(Some(home.join(".codewhale").join(SPILLOVER_DIR_NAME)));
1444 let prior_artifacts = codewhale_runtime::artifacts::set_test_artifact_sessions_root(Some(
1445 home.join(".codewhale").join("sessions"),
1446 ));
1447 let _restore = StorageRootOverride {
1448 prior_spillover,
1449 prior_artifacts,
1450 };
1451 f()
1452 }
1453
1454 #[cfg(test)]
1455 mod tests {
1456 use super::*;
1457 use tempfile::tempdir;
1458
1459 #[test]
1460 fn tiny_inline_budgets_keep_the_complete_retrieval_reference() {
1461 let content = "你好 output\n".repeat(500);
1462 let path = format!(
1463 "/very-long-workspace/{}/art_call-1.txt",
1464 "nested/".repeat(100)
1465 );
1466 let reference = "art_12345678-1234-1234-1234-123456789abc";
1467 let metadata = serde_json::json!({
1468 "retained_head_bytes": 1000,
1469 "retained_tail_bytes": 1000,
1470 "original_byte_count": content.len(),
1471 "original_line_count": content.lines().count(),
1472 });
1473 let preview = format!(
1474 "{}\n\n{}\n\n…\n{}",
1475 "h".repeat(1000),
1476 spillover_preview_footer(content.len() - 2000, 300, &path, Some(reference)),
1477 "t".repeat(1000),
1478 );
1479 for budget in [120, 160, 200, 1200] {
1480 for fitted in [
1481 fit_to_inline_budget(&content, budget, Some(&path), Some(reference)),
1482 refit_spilled_preview(&preview, &metadata, budget, Some(&path), Some(reference))
1483 .unwrap(),
1484 ] {
1485 assert!(fitted.len() <= budget, "{budget}: {fitted}");
1486 assert!(fitted.contains(&format!("ref=\"{reference}\"")), "{fitted}");
1487 assert!(fitted.contains("retrieve_tool_result"), "{fitted}");
1488 assert!(fitted.contains(SPILLOVER_RECOVERY_HINT), "{fitted}");
1489 }
1490 }
1491 // Even an impossible allowance must not amputate a reference. The
1492 // marker tells the wire backstop to preserve this complete receipt.
1493 let fitted = fit_to_inline_budget(&content, 1, Some(&path), Some(reference));
1494 assert!(fitted.contains(reference));
1495 assert!(fitted.contains(SPILLOVER_RECOVERY_HINT));
1496 let unsaved = fit_to_inline_budget(&content, 120, None, None);
1497 assert!(unsaved.len() <= 120);
1498 assert!(!unsaved.contains("retrieve_tool_result"));
1499 }
1500
1501 #[test]
1502 fn model_context_archive_reuse_keeps_original_bytes_and_reports_conflicts() {
1503 let _guard = setup();
1504 let home = tempdir().unwrap();
1505 with_test_home(home.path(), || {
1506 let provider = codewhale_config::ProviderKind::Deepseek;
1507 let model = "deepseek-v3.2-128k";
1508 let budget =
1509 crate::route_budget::route_inline_char_budget_for_route(provider, model, None);
1510 let original = "a".repeat(budget + 1_000);
1511 let prior = serde_json::json!({"prior_key": "prior_value"});
1512 let mut first = ToolResult::success(original.clone()).with_metadata(prior.clone());
1513 assert!(preserve_full_output_for_model_context(
1514 &mut first,
1515 "reused-call",
1516 "exec_shell",
1517 "session-inline",
1518 ));
1519 let metadata = first.metadata.clone().unwrap();
1520 let path = PathBuf::from(metadata["artifact_path"].as_str().unwrap());
1521 assert_eq!(fs::read(&path).unwrap(), original.as_bytes());
1522 assert_eq!(first.content, original);
1523 assert_eq!(metadata["prior_key"], prior["prior_key"]);
1524
1525 // An identical replay still names the original immutable bytes.
1526 let mut identical = ToolResult::success(original.clone()).with_metadata(prior.clone());
1527 assert!(preserve_full_output_for_model_context(
1528 &mut identical,
1529 "reused-call",
1530 "exec_shell",
1531 "session-inline",
1532 ));
1533 assert_eq!(identical.metadata.as_ref(), Some(&metadata));
1534
1535 let changed = "b".repeat(original.len());
1536 let mut conflict = ToolResult::success(changed.clone()).with_metadata(prior.clone());
1537 assert!(!preserve_full_output_for_model_context(
1538 &mut conflict,
1539 "reused-call",
1540 "exec_shell",
1541 "session-inline",
1542 ));
1543 assert_eq!(fs::read(&path).unwrap(), original.as_bytes());
1544 assert_eq!(first.metadata.as_ref(), Some(&metadata));
1545 assert_eq!(conflict.content, changed);
1546 assert_eq!(conflict.metadata.as_ref(), Some(&prior));
1547
1548 // Use the real model-context projection, not a fabricated footer.
1549 let view = crate::core::engine::compact_tool_result_for_route(
1550 provider,
1551 model,
1552 None,
1553 "exec_shell",
1554 &conflict,
1555 );
1556 assert!(view.contains("the full output could not be saved"));
1557 assert!(view.contains("no tool call reaches this copy"));
1558 assert!(!view.contains("retrieve_tool_result"));
1559 assert!(!view.contains("art_reused-call"));
1560 });
1561 }
1562
1563 /// Tests in this module serialize through this guard because they mutate
1564 /// process-global test storage roots. Without it, cargo's parallel runner
1565 /// would observe interleaved overrides.
1566 fn setup() -> std::sync::MutexGuard<'static, ()> {
1567 super::TEST_SPILLOVER_GUARD
1568 .lock()
1569 .unwrap_or_else(|e| e.into_inner())
1570 }
1571
1572 /// Run the adaptive evidence lane directly. These cases exercise it
1573 /// without the `CODEWHALE_ADAPTIVE_OUTPUT_ROUTING` process opt-in so
1574 /// parallel tests keep a deterministic routing decision.
1575 fn adaptive_spillover(
1576 result: &mut ToolResult,
1577 tool_id: &str,
1578 tool_name: &str,
1579 session_id: &str,
1580 ) -> Option<PathBuf> {
1581 apply_adaptive_evidence_inner(
1582 result,
1583 tool_id,
1584 ArtifactSpilloverContext {
1585 tool_name,
1586 session_id,
1587 },
1588 )
1589 }
1590
1591 fn assert_unsaved_preview(result: &mut ToolResult, original: &str, success: bool) {
1592 assert_eq!(result.success, success);
1593 assert!(result.content.len() < SPILLOVER_HEAD_BYTES + SPILLOVER_TAIL_BYTES + 1024);
1594 assert!(result.content.starts_with("first 🐳\n"));
1595 assert!(result.content.ends_with("last 🐳\n"));
1596 assert!(
1597 result
1598 .content
1599 .contains("the full output could not be saved")
1600 );
1601 assert!(
1602 result
1603 .content
1604 .contains("re-run the command with narrower output")
1605 );
1606 assert!(!result.content.contains("full output at"));
1607 assert!(!result.content.contains("retrieve_tool_result"));
1608 let metadata = result.metadata.as_ref().unwrap();
1609 assert_eq!(metadata["original_byte_count"], original.len());
1610 assert_eq!(metadata["evidence_available"], false);
1611 assert_eq!(metadata["output_persistence_failed"], true);
1612 assert_eq!(metadata["truncated"], true);
1613 assert_eq!(metadata["fixture"], "preserved");
1614 assert_eq!(
1615 metadata["content_digest"],
1616 format!(
1617 "sha256:{}",
1618 codewhale_runtime::hashing::sha256_hex(original.as_bytes())
1619 )
1620 );
1621 assert!(metadata.get("artifact_id").is_none());
1622 assert!(metadata.get("spillover_path").is_none());
1623 assert!(!preserve_full_output_for_model_context(
1624 result,
1625 "retry",
1626 "exec_shell",
1627 "retry-session"
1628 ));
1629 }
1630
1631 #[test]
1632 fn classic_spillover_write_failure_bounds_success_and_error_without_fake_evidence() {
1633 let _g = setup();
1634 let tmp = tempdir().unwrap();
1635 with_test_home(tmp.path(), || {
1636 let root = spillover_root().unwrap();
1637 fs::create_dir_all(root.parent().unwrap()).unwrap();
1638 fs::write(&root, "keep this file").unwrap();
1639 let original = format!("first 🐳\n{}last 🐳\n", "middle 🐳\n".repeat(20_000));
1640 for success in [true, false] {
1641 let mut result = ToolResult::success(original.clone());
1642 result.success = success;
1643 result.metadata = Some(serde_json::json!({"fixture": "preserved"}));
1644 assert!(apply_spillover_inner(&mut result, "call-failed", None, true).is_none());
1645 assert_unsaved_preview(&mut result, &original, success);
1646 }
1647 assert_eq!(fs::read_to_string(root).unwrap(), "keep this file");
1648 });
1649 }
1650
1651 #[test]
1652 fn adaptive_persistence_failures_bound_output_and_keep_existing_evidence_immutable() {
1653 let _g = setup();
1654 let tmp = tempdir().unwrap();
1655 with_test_home(tmp.path(), || {
1656 let original = format!("first 🐳\n{}last 🐳\n", "middle 🐳\n".repeat(20_000));
1657 for failure in [
1658 "metadata-write",
1659 "metadata-invalid",
1660 "metadata-conflict",
1661 "content-conflict",
1662 ] {
1663 for success in [true, false] {
1664 let session = format!("{failure}-{success}");
1665 let directory = tmp
1666 .path()
1667 .join(".codewhale/sessions")
1668 .join(&session)
1669 .join("artifacts");
1670 fs::create_dir_all(directory.parent().unwrap()).unwrap();
1671 let canary = match failure {
1672 "metadata-write" => directory.clone(),
1673 "metadata-invalid" | "metadata-conflict" => {
1674 directory.join("art_call-failed.evidence.json")
1675 }
1676 _ => directory.join("art_call-failed.txt"),
1677 };
1678 if failure != "metadata-write" {
1679 fs::create_dir_all(&directory).unwrap();
1680 }
1681 if failure == "metadata-conflict" {
1682 let mut retained =
1683 ToolResult::success("retained evidence\n".repeat(10_000));
1684 adaptive_spillover(&mut retained, "call-failed", "exec_shell", &session)
1685 .unwrap();
1686 } else {
1687 fs::write(&canary, "keep this file").unwrap();
1688 }
1689 let canary_before = fs::read(&canary).unwrap();
1690 let mut result = ToolResult::success(original.clone());
1691 result.success = success;
1692 result.metadata = Some(serde_json::json!({
1693 "fixture": "preserved",
1694 "artifact_id": "stale",
1695 "spillover_path": "/stale",
1696 "evidence_available": true,
1697 }));
1698 assert!(
1699 adaptive_spillover(&mut result, "call-failed", "exec_shell", &session)
1700 .is_none()
1701 );
1702 assert_unsaved_preview(&mut result, &original, success);
1703 assert_eq!(fs::read(&canary).unwrap(), canary_before);
1704 if failure == "metadata-conflict" {
1705 assert_eq!(
1706 fs::read_to_string(directory.join("art_call-failed.txt")).unwrap(),
1707 "retained evidence\n".repeat(10_000)
1708 );
1709 }
1710 }
1711 }
1712 assert!(
1713 !tmp.path()
1714 .join(".codewhale/sessions/retry-session")
1715 .exists()
1716 );
1717 });
1718 }
1719
1720 /// The old hint named `read_file`, which is not registered for the model
1721 /// at all, and otherwise pointed at routes that only reach the artifact
1722 /// under trust mode (see [`spillover_recovery_instruction`]), while never
1723 /// naming `retrieve_tool_result` — model-visible, unconditional, and built
1724 /// for exactly this.
1725 #[test]
1726 fn truncation_footer_names_a_recovery_route_that_works() {
1727 let footer = spillover_preview_footer(
1728 4096,
1729 120,
1730 "/tmp/artifacts/art_call-1.txt",
1731 Some("art_call-1"),
1732 );
1733
1734 assert!(footer.contains("retrieve_tool_result"), "{footer}");
1735 assert!(footer.contains("ref=\"art_call-1\""), "{footer}");
1736 assert!(!footer.contains("read_file"), "{footer}");
1737 assert!(!footer.contains("sed"), "{footer}");
1738 }
1739
1740 /// The legacy global copy has no guaranteed authorization sidecar, so the
1741 /// footer must not invent a fourth dead route — but it still must not name
1742 /// the three it used to.
1743 #[test]
1744 fn truncation_footer_without_an_artifact_promises_nothing_it_cannot_deliver() {
1745 let footer = spillover_preview_footer(4096, 120, "/tmp/tool_outputs/call-1.txt", None);
1746
1747 assert!(
1748 footer.contains("no tool call reaches this copy"),
1749 "{footer}"
1750 );
1751 assert!(!footer.contains("retrieve_tool_result"), "{footer}");
1752 assert!(!footer.contains("read_file"), "{footer}");
1753 assert!(!footer.contains("sed"), "{footer}");
1754 }
1755
1756 /// The TUI keys its "this preview was truncated" detection off the shared
1757 /// constant, so it has to stay a literal substring of every variant.
1758 #[test]
1759 fn every_footer_variant_carries_the_ui_detection_marker() {
1760 for reference in [Some("art_call-1"), None] {
1761 let footer = spillover_preview_footer(4096, 120, "/tmp/x.txt", reference);
1762 assert!(footer.contains(SPILLOVER_RECOVERY_HINT), "{footer}");
1763 }
1764 }
1765
1766 #[test]
1767 fn single_line_spillover_footer_points_to_json_and_query_not_a_line_range() {
1768 let footer = spillover_preview_footer(319_744, 1, "/tmp/x.txt", Some("art_1"));
1769 assert!(footer.contains("mode=\"json\""), "{footer}");
1770 assert!(footer.contains("mode=\"query\""), "{footer}");
1771 assert!(!footer.contains("mode=\"lines\""), "{footer}");
1772 }
1773
1774 #[test]
1775 fn with_test_home_overrides_storage_roots_without_home_resolution() {
1776 let _g = setup();
1777 let tmp = tempdir().unwrap();
1778
1779 with_test_home(tmp.path(), || {
1780 assert_eq!(
1781 spillover_root().as_deref(),
1782 Some(tmp.path().join(".codewhale").join("tool_outputs").as_path())
1783 );
1784 assert_eq!(
1785 codewhale_runtime::artifacts::session_artifact_absolute_path(
1786 "session-123",
1787 &PathBuf::from("artifacts").join("art_call-big.txt")
1788 )
1789 .as_deref(),
1790 Some(
1791 tmp.path()
1792 .join(".codewhale")
1793 .join("sessions")
1794 .join("session-123")
1795 .join("artifacts")
1796 .join("art_call-big.txt")
1797 .as_path()
1798 )
1799 );
1800 });
1801 }
1802
1803 #[test]
1804 fn sanitise_id_keeps_safe_chars_and_drops_dangerous() {
1805 assert_eq!(super::sanitise_id("abc-123_x"), Some("abc-123_x".into()));
1806 // `.` is dropped to keep `..` out of the path.
1807 assert_eq!(super::sanitise_id("../etc"), Some("etc".into()));
1808 assert_eq!(super::sanitise_id("/etc/passwd"), Some("etcpasswd".into()));
1809 // Empty-after-sanitise → None.
1810 assert!(super::sanitise_id("...").is_none());
1811 assert!(super::sanitise_id("").is_none());
1812 }
1813
1814 #[test]
1815 fn write_spillover_creates_directory_and_writes_file() {
1816 let _g = setup();
1817 let tmp = tempdir().unwrap();
1818 with_test_home(tmp.path(), || {
1819 let path = write_spillover("call-abc", "hello world").expect("write");
1820 assert!(path.exists(), "{path:?} missing");
1821 let body = fs::read_to_string(&path).unwrap();
1822 assert_eq!(body, "hello world");
1823 // Directory landed under `<HOME>/.codewhale/tool_outputs/`.
1824 // Compare components instead of a substring on `to_string_lossy`
1825 // — Windows uses `\` as the separator so a `/` substring match
1826 // would falsely fail there.
1827 let components: Vec<&str> = path
1828 .components()
1829 .filter_map(|c| c.as_os_str().to_str())
1830 .collect();
1831 assert!(
1832 components.contains(&".codewhale") && components.contains(&"tool_outputs"),
1833 "spillover path missing expected `.codewhale/tool_outputs/...` segments: {path:?}"
1834 );
1835 });
1836 }
1837
1838 #[test]
1839 fn write_spillover_rejects_empty_id() {
1840 let _g = setup();
1841 let tmp = tempdir().unwrap();
1842 with_test_home(tmp.path(), || {
1843 let err = write_spillover("...", "x").unwrap_err();
1844 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1845 });
1846 }
1847
1848 #[test]
1849 fn maybe_spillover_returns_none_below_threshold() {
1850 let _g = setup();
1851 let tmp = tempdir().unwrap();
1852 with_test_home(tmp.path(), || {
1853 let out = maybe_spillover("call-1", "tiny content", 100 * 1024, 4 * 1024).expect("ok");
1854 assert!(out.is_none());
1855 });
1856 }
1857
1858 #[test]
1859 fn maybe_spillover_writes_and_returns_head_above_threshold() {
1860 let _g = setup();
1861 let tmp = tempdir().unwrap();
1862 with_test_home(tmp.path(), || {
1863 // Content larger than the threshold.
1864 let big = "A".repeat(2_000);
1865 let (head, path) = maybe_spillover("call-2", &big, 1_000, 256)
1866 .expect("ok")
1867 .expect("should have spilled");
1868 // Head is bounded.
1869 assert_eq!(head.len(), 256);
1870 // Full content on disk.
1871 let body = fs::read_to_string(&path).unwrap();
1872 assert_eq!(body.len(), 2_000);
1873 });
1874 }
1875
1876 #[test]
1877 fn maybe_spillover_does_not_split_inside_a_codepoint() {
1878 let _g = setup();
1879 let tmp = tempdir().unwrap();
1880 with_test_home(tmp.path(), || {
1881 // 4 byte chars; ask for 3 bytes of head → walks back to
1882 // the previous char boundary (0).
1883 let s = "🐳🐳🐳🐳"; // 4 × 4-byte codepoints
1884 assert_eq!(s.len(), 16);
1885 let (head, _) = maybe_spillover("call-3", s, 1, 3)
1886 .expect("ok")
1887 .expect("spilled");
1888 // 3 isn't a char boundary in this string; walk back → 0.
1889 assert_eq!(head, "");
1890 // Asking for 4 bytes lands on the first char boundary.
1891 let (head, _) = maybe_spillover("call-3b", s, 1, 4)
1892 .expect("ok")
1893 .expect("spilled");
1894 assert_eq!(head, "🐳");
1895 });
1896 }
1897
1898 #[test]
1899 fn prune_older_than_handles_missing_root() {
1900 let _g = setup();
1901 let tmp = tempdir().unwrap();
1902 with_test_home(tmp.path(), || {
1903 // Nothing has ever written; root doesn't exist; that's fine.
1904 let count = prune_older_than(SPILLOVER_MAX_AGE).expect("ok");
1905 assert_eq!(count, 0);
1906 });
1907 }
1908
1909 // The mtime backdate uses utimensat (Unix-only). On Windows the
1910 // filetime_set_modified helper is a no-op, so the prune wouldn't see
1911 // any stale files. Gate the whole test on `cfg(unix)` instead of
1912 // testing a no-op path that can't fail meaningfully.
1913 #[test]
1914 #[cfg(unix)]
1915 fn prune_older_than_keeps_fresh_files_drops_stale_ones() {
1916 let _g = setup();
1917 let tmp = tempdir().unwrap();
1918 with_test_home(tmp.path(), || {
1919 let fresh = write_spillover("fresh", "x").unwrap();
1920 let stale = write_spillover("stale", "y").unwrap();
1921
1922 // Backdate `stale` to 30 days ago.
1923 let thirty_days = SystemTime::now() - Duration::from_secs(30 * 24 * 60 * 60);
1924 filetime_set_modified(&stale, thirty_days);
1925
1926 let pruned = prune_older_than(SPILLOVER_MAX_AGE).unwrap();
1927 assert_eq!(pruned, 1);
1928 assert!(fresh.exists());
1929 assert!(!stale.exists());
1930 });
1931 }
1932
1933 /// Set the mtime on a file. The workspace doesn't pull the
1934 /// `filetime` crate, so we reach for `utimensat` directly on
1935 /// Unix. Windows is a no-op — the prune semantics are the same
1936 /// and the per-cycle stress test lives on the Unix path.
1937 #[cfg(unix)]
1938 fn filetime_set_modified(path: &Path, when: SystemTime) {
1939 let secs = when
1940 .duration_since(SystemTime::UNIX_EPOCH)
1941 .unwrap_or_default()
1942 .as_secs() as libc::time_t;
1943 let times = [
1944 libc::timespec {
1945 tv_sec: secs,
1946 tv_nsec: 0,
1947 },
1948 libc::timespec {
1949 tv_sec: secs,
1950 tv_nsec: 0,
1951 },
1952 ];
1953 let path_c = std::ffi::CString::new(path.as_os_str().as_encoded_bytes()).unwrap();
1954 // SAFETY: path_c is a valid CString; times is a 2-element array
1955 // matching utimensat's signature.
1956 let rc = unsafe { libc::utimensat(libc::AT_FDCWD, path_c.as_ptr(), times.as_ptr(), 0) };
1957 assert_eq!(
1958 rc,
1959 0,
1960 "utimensat failed: {}",
1961 std::io::Error::last_os_error()
1962 );
1963 }
1964
1965 // Windows stub removed in v0.8.8 — the only caller of
1966 // `filetime_set_modified` is `prune_older_than_keeps_fresh_files_drops_stale_ones`,
1967 // which is now `#[cfg(unix)]` because mtime backdating requires
1968 // `utimensat` and a Windows no-op stub can't make the assertion pass
1969 // anyway. Keeping the stub triggered `-D dead-code` on Windows builds
1970 // (the prune test was the only caller) and broke `Test (windows-latest)`.
1971
1972 #[test]
1973 fn apply_spillover_is_noop_below_threshold() {
1974 let _g = setup();
1975 let tmp = tempdir().unwrap();
1976 with_test_home(tmp.path(), || {
1977 let mut result = ToolResult::success("small payload");
1978 let path = apply_spillover(&mut result, "call-small");
1979 assert!(path.is_none());
1980 assert_eq!(result.content, "small payload");
1981 assert!(result.metadata.is_none());
1982 });
1983 }
1984
1985 #[test]
1986 fn apply_spillover_is_noop_for_error_results() {
1987 let _g = setup();
1988 let tmp = tempdir().unwrap();
1989 with_test_home(tmp.path(), || {
1990 // Even very large error messages are passed through —
1991 // truncating an error would hide it from the model.
1992 let big_err = "boom\n".repeat(50_000);
1993 let mut result = ToolResult::error(big_err.clone());
1994 let path = apply_spillover(&mut result, "call-err");
1995 assert!(path.is_none());
1996 assert_eq!(result.content, big_err);
1997 });
1998 }
1999
2000 #[test]
2001 fn apply_spillover_truncates_and_stamps_metadata_above_threshold() {
2002 let _g = setup();
2003 let tmp = tempdir().unwrap();
2004 with_test_home(tmp.path(), || {
2005 // 200 KiB body — well above the 100 KiB threshold.
2006 let big = "X".repeat(200 * 1024);
2007 let mut result = ToolResult::success(big.clone());
2008 let path = apply_spillover(&mut result, "call-big").expect("should spill");
2009
2010 // Inline content shrunk to head + honest preview footer.
2011 assert!(result.content.len() < big.len());
2012 assert!(
2013 !result.content.contains(SPILLOVER_PREVIEW_HINT),
2014 "the tool-details phrase is a UI affordance, not model-facing"
2015 );
2016 assert!(
2017 result.content.contains("of output omitted"),
2018 "footer missing: {}",
2019 &result.content[result.content.len().saturating_sub(200)..]
2020 );
2021 // The footer tells the model where the full output lives and how
2022 // to read the omitted range back.
2023 assert!(result.content.contains("full output at"));
2024 assert!(result.content.contains(&path.display().to_string()));
2025 assert!(result.content.contains(SPILLOVER_RECOVERY_HINT));
2026 assert!(
2027 !result.content.contains("retrieve_tool_result"),
2028 "legacy spillover ownership can fail to publish; promising \
2029 retrieval here would be another dead route"
2030 );
2031 assert!(!result.content.contains("read_file"));
2032 assert!(!result.content.contains("sed"));
2033
2034 // Full bytes are on disk at the returned path.
2035 assert!(path.exists(), "spillover file missing: {path:?}");
2036 let body = fs::read_to_string(&path).unwrap();
2037 assert_eq!(body.len(), 200 * 1024);
2038
2039 // metadata.spillover_path stamped for the UI to find.
2040 let metadata = result.metadata.expect("metadata stamped");
2041 let stamped = metadata
2042 .get("spillover_path")
2043 .and_then(serde_json::Value::as_str)
2044 .expect("spillover_path key present");
2045 assert_eq!(stamped, path.display().to_string());
2046 assert_eq!(metadata["truncated"], true);
2047 assert_eq!(metadata["original_byte_count"], 200 * 1024);
2048 assert_eq!(metadata["retained_head_bytes"], SPILLOVER_HEAD_BYTES);
2049 assert_eq!(metadata["retained_tail_bytes"], SPILLOVER_TAIL_BYTES);
2050 assert!(
2051 metadata["content_digest"]
2052 .as_str()
2053 .is_some_and(|digest| digest.starts_with("sha256:"))
2054 );
2055 });
2056 }
2057
2058 #[test]
2059 fn apply_spillover_with_artifact_writes_session_file_and_plain_preview() {
2060 let _g = setup();
2061 let tmp = tempdir().unwrap();
2062 with_test_home(tmp.path(), || {
2063 let big = "checking crate ... error[E0425]: cannot find value\n".repeat(4_000);
2064 let mut result = ToolResult::success(big.clone());
2065 let path = adaptive_spillover(&mut result, "call-big", "exec_shell", "session-123")
2066 .expect("should spill");
2067
2068 let session_artifact = tmp
2069 .path()
2070 .join(".codewhale")
2071 .join("sessions")
2072 .join("session-123")
2073 .join("artifacts")
2074 .join("art_call-big.txt");
2075 assert_eq!(path, session_artifact);
2076 assert_eq!(fs::read_to_string(&session_artifact).unwrap(), big);
2077 assert!(
2078 !tmp.path()
2079 .join(".codewhale/tool_outputs/call-big.txt")
2080 .exists(),
2081 "adaptive evidence stores one exact origin-session copy"
2082 );
2083 // The model sees a bounded preview with an honest footer: the
2084 // artifact path plus the retrieval call that actually resolves it.
2085 assert!(!result.content.contains(SPILLOVER_PREVIEW_HINT));
2086 assert!(result.content.contains("\n…\n"));
2087 assert!(result.content.contains("of output omitted"));
2088 assert!(result.content.contains("full output at"));
2089 assert!(result.content.contains(SPILLOVER_RECOVERY_HINT));
2090 assert!(
2091 result.content.contains("art_call-big.txt"),
2092 "footer must name the artifact path so the model can recover the output"
2093 );
2094 assert!(!result.content.contains("Exact evidence retained"));
2095 assert!(
2096 result.content.contains("retrieve_tool_result"),
2097 "a session artifact is retrievable; the footer must say so: {}",
2098 result.content
2099 );
2100 assert!(
2101 result.content.contains("ref=\"art_call-big\""),
2102 "the footer must hand over a ref that resolves: {}",
2103 result.content
2104 );
2105 assert!(
2106 session_artifact
2107 .with_file_name("art_call-big.evidence.json")
2108 .exists()
2109 );
2110
2111 let metadata = result.metadata.expect("metadata stamped");
2112 assert_eq!(
2113 metadata
2114 .get("artifact_id")
2115 .and_then(serde_json::Value::as_str),
2116 Some("art_call-big")
2117 );
2118 assert_eq!(
2119 metadata
2120 .get("artifact_relative_path")
2121 .and_then(serde_json::Value::as_str),
2122 Some("artifacts/art_call-big.txt")
2123 );
2124 assert_eq!(
2125 metadata
2126 .get("artifact_session_id")
2127 .and_then(serde_json::Value::as_str),
2128 Some("session-123")
2129 );
2130 assert_eq!(metadata["original_byte_count"], big.len());
2131 assert!(metadata["retained_head_bytes"].as_u64().unwrap_or(0) <= 16 * 1024);
2132 assert!(metadata["retained_tail_bytes"].as_u64().unwrap_or(0) <= 4 * 1024);
2133 });
2134 }
2135
2136 #[test]
2137 fn adaptive_evidence_keeps_success_and_failure_exact_distinct_and_out_of_context() {
2138 let _g = setup();
2139 let tmp = tempdir().unwrap();
2140 with_test_home(tmp.path(), || {
2141 let sentinel = "DEEP_RAW_SENTINEL";
2142 // Payloads must exceed the 32_768-token (≈96 KiB) handle-only
2143 // threshold so adaptive routing actually spills them.
2144 let success_raw = format!(
2145 "{}{}{}",
2146 "head\n".repeat(30_000),
2147 sentinel,
2148 "tail\n".repeat(30_000)
2149 );
2150 let failure_raw = format!("{}{}", "failure\n".repeat(30_000), "FAILURE_END");
2151 let mut success = ToolResult::success(success_raw.clone());
2152 let mut failure = ToolResult::error(failure_raw.clone());
2153
2154 let success_path =
2155 adaptive_spillover(&mut success, "call-success", "exec_shell", "session-a")
2156 .expect("success evidence");
2157 let failure_path =
2158 adaptive_spillover(&mut failure, "call-failure", "mcp_fixture", "session-a")
2159 .expect("failure evidence");
2160
2161 assert_ne!(success_path, failure_path);
2162 assert_eq!(
2163 std::fs::read(&success_path).unwrap(),
2164 success_raw.as_bytes()
2165 );
2166 assert_eq!(
2167 std::fs::read(&failure_path).unwrap(),
2168 failure_raw.as_bytes()
2169 );
2170 assert!(!success.content.contains(sentinel));
2171 // Handle-only preview: 16 KiB head + 4 KiB tail + footer.
2172 assert!(success.content.len() < 21 * 1024);
2173 let success_meta = success.metadata.as_ref().unwrap();
2174 let failure_meta = failure.metadata.as_ref().unwrap();
2175 assert_ne!(
2176 success_meta["artifact_digest"],
2177 failure_meta["artifact_digest"]
2178 );
2179 assert_eq!(success_meta["artifact_session_id"], "session-a");
2180 assert_eq!(failure_meta["artifact_session_id"], "session-a");
2181
2182 let mut replay = ToolResult::success(success_raw);
2183 let replay_path =
2184 adaptive_spillover(&mut replay, "call-success", "exec_shell", "session-a")
2185 .expect("idempotent replay");
2186 assert_eq!(replay_path, success_path);
2187 });
2188 }
2189
2190 #[test]
2191 fn adaptive_evidence_publication_failure_emits_no_handle_or_details_hint() {
2192 let _g = setup();
2193 let tmp = tempdir().unwrap();
2194 with_test_home(tmp.path(), || {
2195 let session_dir = tmp
2196 .path()
2197 .join(".codewhale")
2198 .join("sessions")
2199 .join("session-blocked");
2200 std::fs::create_dir_all(&session_dir).unwrap();
2201 std::fs::write(session_dir.join("artifacts"), b"block artifact directory").unwrap();
2202
2203 let raw = format!(
2204 "{}{}{}",
2205 "publication failure head\n".repeat(1_500),
2206 "DEEP_FAILURE_SENTINEL",
2207 "publication failure tail\n".repeat(1_500),
2208 );
2209 let mut result = ToolResult::error(raw.clone());
2210 let path = adaptive_spillover(
2211 &mut result,
2212 "call-failed-publish",
2213 "mcp_fixture",
2214 "session-blocked",
2215 );
2216
2217 assert!(path.is_none());
2218 assert!(!result.success);
2219 assert!(result.content.len() < SPILLOVER_HEAD_BYTES + SPILLOVER_TAIL_BYTES + 1024);
2220 assert!(!result.content.contains("DEEP_FAILURE_SENTINEL"));
2221 assert!(
2222 result
2223 .content
2224 .contains("the full output could not be saved")
2225 );
2226 assert!(!result.content.contains(SPILLOVER_PREVIEW_HINT));
2227 assert!(!result.content.contains("retrieve_tool_result"));
2228 assert_eq!(
2229 result
2230 .metadata
2231 .as_ref()
2232 .and_then(|metadata| metadata.get("evidence_available")),
2233 Some(&serde_json::Value::Bool(false))
2234 );
2235 assert!(
2236 !session_dir
2237 .join("artifacts/art_call-failed-publish.txt")
2238 .exists()
2239 );
2240 });
2241 }
2242
2243 #[test]
2244 fn adaptive_evidence_metadata_atomic_failure_leaves_payload_unadvertised() {
2245 let _g = setup();
2246 let tmp = tempdir().unwrap();
2247 with_test_home(tmp.path(), || {
2248 let artifact_dir = tmp
2249 .path()
2250 .join(".codewhale")
2251 .join("sessions")
2252 .join("session-metadata-blocked")
2253 .join("artifacts");
2254 std::fs::create_dir_all(artifact_dir.join("art_call-failed-metadata.evidence.json"))
2255 .unwrap();
2256
2257 let raw = format!(
2258 "{}{}{}",
2259 "metadata failure head\n".repeat(1_500),
2260 "DEEP_METADATA_FAILURE_SENTINEL",
2261 "metadata failure tail\n".repeat(1_500),
2262 );
2263 let mut result = ToolResult::success(raw.clone());
2264 let path = adaptive_spillover(
2265 &mut result,
2266 "call-failed-metadata",
2267 "exec_shell",
2268 "session-metadata-blocked",
2269 );
2270
2271 assert!(path.is_none());
2272 assert!(result.success);
2273 assert!(result.content.len() < SPILLOVER_HEAD_BYTES + SPILLOVER_TAIL_BYTES + 1024);
2274 assert!(!result.content.contains("DEEP_METADATA_FAILURE_SENTINEL"));
2275 assert!(
2276 result
2277 .content
2278 .contains("the full output could not be saved")
2279 );
2280 assert_eq!(
2281 result.metadata.as_ref().unwrap()["evidence_available"],
2282 false
2283 );
2284 assert!(!result.content.contains(SPILLOVER_PREVIEW_HINT));
2285 assert!(!result.content.contains("retrieve_tool_result"));
2286 assert!(
2287 !artifact_dir.join("art_call-failed-metadata.txt").exists(),
2288 "metadata failure must leave no payload behind a guessable handle"
2289 );
2290 });
2291 }
2292
2293 #[test]
2294 fn registry_results_spill_to_artifacts_like_every_other_tool() {
2295 // The Registry bypass is gone: an oversized payload (which today can
2296 // only be a bug, since the tool caps model-visible matches at eight)
2297 // takes the same artifact path as any other tool result.
2298 let _g = setup();
2299 let tmp = tempdir().unwrap();
2300 with_test_home(tmp.path(), || {
2301 let original = "registry-entry\n".repeat(10_000);
2302 assert!(original.len() > SPILLOVER_THRESHOLD_BYTES);
2303 let mut result = ToolResult::success(original);
2304
2305 let path = apply_spillover_with_artifact(
2306 &mut result,
2307 "call-registry",
2308 "registry_sync",
2309 "session-registry",
2310 );
2311
2312 assert!(path.is_some(), "oversized registry payload must spill");
2313 });
2314 }
2315
2316 #[test]
2317 fn apply_spillover_preserves_existing_metadata() {
2318 let _g = setup();
2319 let tmp = tempdir().unwrap();
2320 with_test_home(tmp.path(), || {
2321 let big = "Y".repeat(200 * 1024);
2322 let mut result = ToolResult::success(big)
2323 .with_metadata(serde_json::json!({"prior_key": "prior_value"}));
2324 let path = apply_spillover(&mut result, "call-meta").expect("should spill");
2325
2326 let metadata = result.metadata.expect("metadata present");
2327 // Prior keys survive.
2328 assert_eq!(
2329 metadata
2330 .get("prior_key")
2331 .and_then(serde_json::Value::as_str),
2332 Some("prior_value")
2333 );
2334 // New key added alongside.
2335 assert_eq!(
2336 metadata
2337 .get("spillover_path")
2338 .and_then(serde_json::Value::as_str),
2339 Some(path.display().to_string().as_str())
2340 );
2341 });
2342 }
2343
2344 #[test]
2345 fn apply_spillover_wraps_non_object_metadata_under_prior_key() {
2346 // Defends against a tool whose `metadata` is something
2347 // other than a JSON object (rare — most use the `json!({})`
2348 // pattern — but legal per `serde_json::Value`). The
2349 // spillover writer must add `spillover_path` without losing
2350 // the prior payload.
2351 let _g = setup();
2352 let tmp = tempdir().unwrap();
2353 with_test_home(tmp.path(), || {
2354 let big = "Z".repeat(200 * 1024);
2355 let mut result = ToolResult::success(big).with_metadata(serde_json::json!([
2356 "unexpected",
2357 "array",
2358 "payload"
2359 ]));
2360 let path = apply_spillover(&mut result, "call-arr").expect("should spill");
2361
2362 let metadata = result.metadata.expect("metadata stamped");
2363 // Prior payload re-homed under `_prior`.
2364 let prior = metadata.get("_prior").expect("_prior wrap key present");
2365 assert_eq!(
2366 prior,
2367 &serde_json::json!(["unexpected", "array", "payload"]),
2368 "prior array should round-trip under _prior"
2369 );
2370 // New key alongside.
2371 assert_eq!(
2372 metadata
2373 .get("spillover_path")
2374 .and_then(serde_json::Value::as_str),
2375 Some(path.display().to_string().as_str())
2376 );
2377 });
2378 }
2379
2380 // ── Honest-truncation regressions (v0.9.4) ─────────────────────────────
2381
2382 #[test]
2383 fn truncated_preview_returns_content_unchanged_when_nothing_omitted() {
2384 let original = "line one\nline two\nline three\n";
2385 let preview = truncated_preview(original, "", original, "/tmp/artifact.txt", None);
2386 assert_eq!(preview, original);
2387 assert!(
2388 !preview.contains("of output omitted"),
2389 "must never claim a truncation that did not happen"
2390 );
2391 }
2392
2393 #[test]
2394 fn head_tail_windows_never_overlap() {
2395 // Content smaller than head + tail budgets: the tail window shrinks
2396 // so it starts exactly where the head ends — no byte appears twice.
2397 let content = "x".repeat(10_000);
2398 let (head, tail) = head_tail_windows(&content, 8 * 1024, 4 * 1024);
2399 assert_eq!(head.len(), 8 * 1024);
2400 assert_eq!(tail.len(), 10_000 - 8 * 1024);
2401 assert!(head.len() + tail.len() <= content.len());
2402
2403 // Content larger than both budgets: full windows, exact omission.
2404 let big = "y".repeat(100_000);
2405 let (head, tail) = head_tail_windows(&big, 32 * 1024, 8 * 1024);
2406 assert_eq!(head.len(), 32 * 1024);
2407 assert_eq!(tail.len(), 8 * 1024);
2408
2409 // UTF-8 codepoints are never split at either window edge.
2410 let emoji = "🐳".repeat(5_000); // 20_000 bytes, 4 per codepoint
2411 let (head, tail) = head_tail_windows(&emoji, 8 * 1024 + 1, 4 * 1024 + 2);
2412 assert!(emoji.is_char_boundary(head.len()));
2413 assert!(emoji.is_char_boundary(emoji.len() - tail.len()));
2414 assert!(head.len() + tail.len() <= emoji.len());
2415 }
2416
2417 #[test]
2418 fn adaptive_evidence_passes_through_when_preview_budget_covers_output() {
2419 let _g = setup();
2420 let tmp = tempdir().unwrap();
2421 with_test_home(tmp.path(), || {
2422 // 30_000 bytes → 10_000 estimated tokens → Hybrid band under the
2423 // 32_768-token default, but the 32 KiB + 8 KiB preview budget
2424 // covers the whole output, so nothing is actually omitted.
2425 let raw = "mid\n".repeat(7_500);
2426 assert_eq!(raw.len(), 30_000);
2427 let mut result = ToolResult::success(raw.clone());
2428 let path =
2429 adaptive_spillover(&mut result, "call-covered", "exec_shell", "session-covered");
2430 assert!(path.is_none(), "no artifact when nothing is omitted");
2431 assert_eq!(result.content, raw);
2432 assert!(!result.content.contains("of output omitted"));
2433 assert!(
2434 !tmp.path()
2435 .join(".codewhale/sessions/session-covered/artifacts/art_call-covered.txt")
2436 .exists()
2437 );
2438 });
2439 }
2440
2441 #[test]
2442 fn adaptive_evidence_footer_names_artifact_path_and_recovery() {
2443 let _g = setup();
2444 let tmp = tempdir().unwrap();
2445 with_test_home(tmp.path(), || {
2446 // 120_000 bytes → 40_000 estimated tokens → handle-only band.
2447 let raw = "entry\n".repeat(20_000);
2448 assert_eq!(raw.len(), 120_000);
2449 let mut result = ToolResult::success(raw);
2450 let path =
2451 adaptive_spillover(&mut result, "call-honest", "exec_shell", "session-honest")
2452 .expect("should spill");
2453
2454 // Footer: omitted size + line count, artifact path, recovery line.
2455 assert!(result.content.contains("of output omitted ("));
2456 assert!(result.content.contains(" lines)"));
2457 assert!(result.content.contains("full output at"));
2458 assert!(
2459 result
2460 .content
2461 .contains(&codewhale_runtime::artifacts::format_artifact_relative_path(&path))
2462 );
2463 assert!(result.content.contains(SPILLOVER_RECOVERY_HINT));
2464 assert!(!result.content.contains(SPILLOVER_PREVIEW_HINT));
2465
2466 // Head and tail do not overlap: 16 KiB + 4 KiB handle-only
2467 // windows over a 120_000-byte output.
2468 let metadata = result.metadata.expect("metadata stamped");
2469 assert_eq!(metadata["retained_head_bytes"], 16 * 1024);
2470 assert_eq!(metadata["retained_tail_bytes"], 4 * 1024);
2471 });
2472 }
2473
2474 #[test]
2475 fn apply_spillover_with_artifact_defaults_to_classic_head_tail_spillover() {
2476 // 120_000 bytes exceeds the 100 KiB classic threshold. Without the
2477 // `CODEWHALE_ADAPTIVE_OUTPUT_ROUTING` opt-in the public entry point
2478 // keeps a 32 KiB head + 8 KiB tail and writes the session artifact —
2479 // the adaptive handle-only windows and evidence metadata are opt-in.
2480 let _g = setup();
2481 let tmp = tempdir().unwrap();
2482 with_test_home(tmp.path(), || {
2483 let raw = "entry\n".repeat(20_000);
2484 assert_eq!(raw.len(), 120_000);
2485 let mut result = ToolResult::success(raw.clone());
2486 let path = apply_spillover_with_artifact(
2487 &mut result,
2488 "call-classic",
2489 "exec_shell",
2490 "session-classic",
2491 )
2492 .expect("should spill");
2493
2494 let metadata = result.metadata.expect("metadata stamped");
2495 assert_eq!(metadata["retained_head_bytes"], 32 * 1024);
2496 assert_eq!(metadata["retained_tail_bytes"], 8 * 1024);
2497 assert!(result.content.contains(SPILLOVER_RECOVERY_HINT));
2498 assert!(
2499 !tmp.path()
2500 .join(
2501 ".codewhale/sessions/session-classic/artifacts/art_call-classic.evidence.json"
2502 )
2503 .exists(),
2504 "classic lane publishes no adaptive evidence metadata"
2505 );
2506 assert_eq!(std::fs::read_to_string(&path).unwrap(), raw);
2507 // The classic lane names its bytes by digest, like the adaptive
2508 // lane, so a turn artifact ref can carry a revision.
2509 assert_eq!(
2510 metadata["artifact_digest"],
2511 codewhale_runtime::hashing::sha256_hex(raw.as_bytes())
2512 );
2513 let artifact = tmp
2514 .path()
2515 .join(".codewhale/sessions/session-classic/artifacts/art_call-classic.txt");
2516 assert_eq!(std::fs::read_to_string(&artifact).unwrap(), raw);
2517
2518 // The published handle is immutable: a different payload under
2519 // the same call id never rewrites the bytes a ref names.
2520 let mut replay = ToolResult::success("other\n".repeat(20_000));
2521 apply_spillover_with_artifact(
2522 &mut replay,
2523 "call-classic",
2524 "exec_shell",
2525 "session-classic",
2526 )
2527 .expect("replay still spills to the legacy footer");
2528 assert_eq!(std::fs::read_to_string(&artifact).unwrap(), raw);
2529 let replay_metadata = replay.metadata.expect("metadata stamped");
2530 assert!(replay_metadata.get("artifact_id").is_none());
2531 assert!(replay_metadata.get("artifact_digest").is_none());
2532 });
2533 }
2534 }
2535
2535 lines RUST