返回 CodeWhale
tool_result_retrieval.rs
根目录 / crates / engine / src / tools / tool_result_retrieval.rs
1 //! `retrieve_tool_result` - selective retrieval for spilled tool outputs.
2 //!
3 //! Exact tool evidence is retained under its origin session. Historical
4 //! payloads in the global `tool_outputs/` compatibility directory are readable
5 //! only when a digest-bound ownership sidecar proves they belong to the active
6 //! session.
7
8 use std::path::PathBuf;
9
10 use async_trait::async_trait;
11 use serde_json::{Value, json};
12
13 use super::spec::{
14 ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec, optional_str, optional_u64,
15 required_str,
16 };
17
18 const DEFAULT_MAX_BYTES: usize = 8 * 1024;
19 const HARD_MAX_BYTES: usize = 128 * 1024;
20 const DEFAULT_LINE_COUNT: usize = 40;
21 const HARD_LINE_COUNT: usize = 500;
22 const DEFAULT_MAX_MATCHES: usize = 20;
23 const HARD_MAX_MATCHES: usize = 100;
24 const DEFAULT_CONTEXT_LINES: usize = 1;
25 const HARD_CONTEXT_LINES: usize = 5;
26 const MAX_SCAN_BYTES: u64 = 512 * 1024 * 1024;
27 const WRAP_LINE_BYTES: usize = 2 * 1024;
28 const MAX_JSON_BYTES: u64 = 32 * 1024 * 1024;
29 const MAX_SELECTION_BYTES: usize = 8 * 1024 * 1024;
30 const MAX_QUERY_BYTES: usize = 4 * 1024;
31 pub const MAX_REFERENCE_BYTES: usize = 32 * 1024;
32 const MAX_JSON_SUMMARY_KEYS: usize = 40;
33 const MAX_JSON_SUMMARY_CHILD_KEYS: usize = 16;
34 const MAX_JSON_SUMMARY_DEPTH: usize = 3;
35 const MAX_JSON_STRING_PREVIEW_CHARS: usize = 120;
36 const MAX_JSON_ARRAY_SAMPLE_ITEMS: usize = 3;
37 const MAX_JSON_SUGGESTED_QUERIES: usize = 6;
38 const MAX_JSON_EXPAND_DEPTH: usize = 4;
39
40 /// Retrieve summaries or slices of a prior spilled tool result.
41 pub struct RetrieveToolResultTool;
42
43 #[async_trait]
44 impl ToolSpec for RetrieveToolResultTool {
45 fn name(&self) -> &'static str {
46 "retrieve_tool_result"
47 }
48
49 fn description(&self) -> &'static str {
50 "Inspect retained tool evidence with strict session ownership and bounds. Accepts an artifact id, validated session-relative path, or an ownership-proven legacy call/SHA reference. Unowned legacy-global evidence fails closed. Modes: metadata, summary, head, tail, lines, query, json, bytes. Lines longer than 2 KiB are split into numbered segments. json parses the evidence (JSON text inside it, such as an MCP text block, included) and returns the `jsonpath` selection, cut to max_bytes as valid JSON. bytes returns a bounded base64 slice for exact text or binary recovery."
51 }
52
53 fn input_schema(&self) -> Value {
54 json!({
55 "type": "object",
56 "properties": {
57 "ref": {
58 "type": "string",
59 "description": "Session-owned artifact id (`art_<id>`) or validated artifact-relative path. Legacy call-id/SHA references work only when origin-session ownership was recorded."
60 },
61 "mode": {
62 "type": "string",
63 "enum": ["metadata", "summary", "head", "tail", "lines", "query", "json", "bytes"],
64 "description": "Retrieval mode. Defaults to summary."
65 },
66 "query": {
67 "type": "string",
68 "description": "Case-insensitive substring to search for when mode=query."
69 },
70 "jsonpath": {
71 "type": "string",
72 "description": "JSONPath subset for mode=json: $, .field, [index], [*], and ['field']. Defaults to $."
73 },
74 "lines": {
75 "type": "string",
76 "description": "Line selector for mode=lines, e.g. \"10\" or \"10-40\"."
77 },
78 "start_line": {
79 "type": "integer",
80 "description": "1-based first line for mode=lines."
81 },
82 "end_line": {
83 "type": "integer",
84 "description": "1-based final line for mode=lines."
85 },
86 "line_count": {
87 "type": "integer",
88 "description": "Number of lines for head/tail modes. Default 40, hard cap 500."
89 },
90 "max_bytes": {
91 "type": "integer",
92 "description": "Maximum bytes of excerpt text returned. Default 8192, hard cap 131072."
93 },
94 "max_matches": {
95 "type": "integer",
96 "description": "Maximum query matches or signal lines returned. Default 20, hard cap 100."
97 },
98 "context_lines": {
99 "type": "integer",
100 "description": "Extra lines around each query match. Default 1, hard cap 5."
101 },
102 "generation": {
103 "type": "integer",
104 "minimum": 1,
105 "description": "Optional expected evidence generation; mismatches fail closed."
106 },
107 "expected_sha256": {
108 "type": "string",
109 "description": "Expected SHA256 from an earlier verified window; a changed snapshot is refused."
110 },
111 "offset": {
112 "type": "integer",
113 "minimum": 0,
114 "description": "Zero-based byte offset for mode=bytes."
115 },
116 "length": {
117 "type": "integer",
118 "minimum": 1,
119 "description": "Byte count for mode=bytes, capped at max_bytes."
120 }
121 },
122 "required": ["ref"]
123 })
124 }
125
126 fn capabilities(&self) -> Vec<ToolCapability> {
127 vec![ToolCapability::ReadOnly]
128 }
129
130 fn supports_parallel(&self) -> bool {
131 true
132 }
133
134 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
135 let reference = required_str(&input, "ref")?;
136 if reference.len() > MAX_REFERENCE_BYTES {
137 return Err(ToolError::invalid_input(
138 "ref exceeds the 32768-byte inspection limit",
139 ));
140 }
141 let reference = reference.trim();
142 if reference.is_empty() {
143 return Err(ToolError::invalid_input("ref cannot be empty"));
144 }
145
146 let mode = optional_str(&input, "mode")?.unwrap_or("summary");
147 if mode.len() > 16 {
148 return Err(ToolError::invalid_input(
149 "mode exceeds the inspection limit",
150 ));
151 }
152 let mode = mode.trim().to_ascii_lowercase();
153 if !matches!(
154 mode.as_str(),
155 "metadata" | "summary" | "head" | "tail" | "lines" | "query" | "json" | "bytes"
156 ) {
157 return Err(ToolError::invalid_input(format!(
158 "unsupported mode `{mode}` (expected metadata, summary, head, tail, lines, query, json, or bytes)"
159 )));
160 }
161 let max_bytes = clamp_u64(
162 optional_u64(&input, "max_bytes", DEFAULT_MAX_BYTES as u64)?,
163 1,
164 HARD_MAX_BYTES,
165 );
166 let expected_digest = optional_str(&input, "expected_sha256")?
167 .map(|digest| {
168 if digest.len() != 64 || !digest.bytes().all(|byte| byte.is_ascii_hexdigit()) {
169 return Err(ToolError::invalid_input(
170 "expected_sha256 must be a SHA256 digest",
171 ));
172 }
173 Ok(digest.to_ascii_lowercase())
174 })
175 .transpose()?;
176 let jsonpath = optional_str(&input, "jsonpath")?
177 .map(str::trim)
178 .filter(|path| !path.is_empty())
179 .unwrap_or("$")
180 .to_string();
181 if jsonpath.len() > crate::tools::handle::JSONPATH_MAX_PATH_BYTES {
182 return Err(ToolError::invalid_input(
183 "jsonpath exceeds the 4096-byte inspection limit",
184 ));
185 }
186 let inspection = if matches!(mode.as_str(), "metadata" | "bytes" | "json") {
187 None
188 } else {
189 Some(TextInspection::new(&mode, &input, max_bytes)?)
190 };
191 let owned_reference = reference.to_string();
192 let session_id = context.state_namespace.clone();
193 let (resolved, legacy_ownership, file, initial_size) =
194 evidence_owner_work(context, move |cancel| {
195 let resolved = resolve_spillover_reference(&owned_reference, &session_id)?;
196 check_evidence_cancelled(cancel)?;
197 let legacy_ownership = if resolved.kind == ResolvedReferenceKind::LegacyGlobal {
198 Some(authorize_legacy_spillover(&resolved.path, &session_id)?)
199 } else {
200 None
201 };
202 check_evidence_cancelled(cancel)?;
203 let relative = resolved.path.strip_prefix(&resolved.root).map_err(|_| {
204 ToolError::permission_denied("evidence path is not owned by the active session")
205 })?;
206 let file = match resolved.kind {
207 ResolvedReferenceKind::ActiveSession => {
208 codewhale_runtime::artifacts::open_session_relative(
209 &session_id,
210 &std::path::Path::new(codewhale_runtime::artifacts::ARTIFACTS_DIR_NAME)
211 .join(relative),
212 false,
213 )
214 }
215 ResolvedReferenceKind::LegacyGlobal => {
216 codewhale_util::files::WorkspaceFile::open_delivery(
217 &resolved.root,
218 relative,
219 )
220 }
221 }
222 .and_then(|file| file.open_file())
223 .map_err(|_| {
224 ToolError::execution_failed("evidence is missing or no longer retained")
225 })?;
226 check_evidence_cancelled(cancel)?;
227 let initial_size = file
228 .metadata()
229 .map_err(|_| {
230 ToolError::execution_failed("evidence is missing or no longer retained")
231 })?
232 .len();
233 Ok((resolved, legacy_ownership, file, initial_size))
234 })
235 .await?;
236 let snapshot = stream_evidence(
237 file,
238 initial_size,
239 &input,
240 &mode,
241 max_bytes,
242 inspection,
243 context,
244 )
245 .await?;
246 if expected_digest
247 .as_ref()
248 .is_some_and(|digest| digest != &snapshot.digest)
249 {
250 return Err(ToolError::execution_failed(
251 "evidence changed since the previous window",
252 ));
253 }
254 if let Some(ownership) = legacy_ownership
255 && (ownership.size_bytes != snapshot.size_bytes || ownership.digest != snapshot.digest)
256 {
257 return Err(ToolError::execution_failed(
258 "legacy evidence content is corrupt",
259 ));
260 }
261 let owned_reference = reference.to_string();
262 let session_id = context.state_namespace.clone();
263 let size_bytes = snapshot.size_bytes;
264 let digest = snapshot.digest.clone();
265 let generation = input.get("generation").and_then(Value::as_u64);
266 let evidence = evidence_owner_work(context, move |_| {
267 validate_evidence_if_present(
268 &owned_reference,
269 &resolved.path,
270 size_bytes,
271 &digest,
272 &session_id,
273 generation,
274 )
275 })
276 .await?;
277 if mode == "metadata" {
278 return ToolResult::json(&json!({
279 "ref": reference,
280 "available": true,
281 "total_bytes": snapshot.size_bytes,
282 "sha256": snapshot.digest,
283 "evidence": evidence,
284 }))
285 .map_err(|err| ToolError::execution_failed(err.to_string()));
286 }
287 if mode == "bytes" {
288 use base64::Engine as _;
289 let offset = input.get("offset").and_then(Value::as_u64).unwrap_or(0);
290 let slice = &snapshot.byte_slice;
291 return ToolResult::json(&json!({
292 "ref": reference,
293 "mode": "bytes",
294 "offset": offset,
295 "returned_bytes": slice.len(),
296 "total_bytes": snapshot.size_bytes,
297 "encoding": "base64",
298 "sha256": snapshot.digest,
299 "data": base64::engine::general_purpose::STANDARD.encode(slice),
300 }))
301 .map_err(|err| ToolError::execution_failed(err.to_string()));
302 }
303 if mode == "json" {
304 let bytes = snapshot.byte_slice;
305 let total_bytes = snapshot.size_bytes;
306 let path = jsonpath.clone();
307 let owned_reference = reference.to_string();
308 let payload = evidence_owner_work(context, move |cancel| {
309 check_evidence_cancelled(cancel)?;
310 let (selection, match_cap_hit) = select_json(&bytes, &path)?;
311 check_evidence_cancelled(cancel)?;
312 let matches = selection.len();
313 let (values, omitted) =
314 crate::tools::truncate::shrink_json(Value::Array(selection), max_bytes);
315 let truncated = omitted > 0 || match_cap_hit;
316 let mut payload = json!({
317 "ref": owned_reference,
318 "mode": "json",
319 "jsonpath": path,
320 "total_bytes": total_bytes,
321 "matches": matches,
322 "values": values,
323 "truncated": truncated,
324 });
325 if truncated {
326 payload["hint"] = json!(
327 "values keep their leading elements; narrow jsonpath (for example $.items[10] or $.items[*].id) or raise max_bytes (up to 131072)"
328 );
329 }
330 Ok(payload)
331 })
332 .await?;
333 return ToolResult::json(&payload)
334 .map_err(|err| ToolError::execution_failed(err.to_string()));
335 }
336 if mode == "summary" && !snapshot.byte_slice.is_empty() {
337 let bytes = snapshot.byte_slice;
338 let total_bytes = snapshot.size_bytes;
339 let owned_reference = reference.to_string();
340 if let Some(payload) = evidence_owner_work(context, move |cancel| {
341 check_evidence_cancelled(cancel)?;
342 summarize_json_artifact(&owned_reference, &bytes, total_bytes, max_bytes, cancel)
343 })
344 .await?
345 {
346 return ToolResult::json(&payload).map_err(|err| {
347 ToolError::execution_failed(format!("failed to serialize result: {err}"))
348 });
349 }
350 }
351 let inspection = snapshot
352 .inspection?
353 .ok_or_else(|| ToolError::execution_failed("text inspection was unavailable"))?;
354 let payload = inspection.payload(reference, snapshot.size_bytes);
355
356 ToolResult::json(&payload).map_err(|err| {
357 ToolError::execution_failed(format!("failed to serialize result: {err}"))
358 })
359 }
360 }
361
362 async fn evidence_owner_work<T: Send + 'static>(
363 context: &ToolContext,
364 work: impl FnOnce(&tokio_util::sync::CancellationToken) -> Result<T, ToolError> + Send + 'static,
365 ) -> Result<T, ToolError> {
366 let cancel = context
367 .cancel_token
368 .as_ref()
369 .map(tokio_util::sync::CancellationToken::child_token)
370 .unwrap_or_default();
371 let _cancel_on_drop = cancel.clone().drop_guard();
372 let worker_cancel = cancel.clone();
373 #[cfg(any(test, feature = "test-support"))]
374 let ticket = crate::test_support::env_scope_ticket();
375 let worker = codewhale_runtime::runtime_control::owner_work(move || {
376 #[cfg(any(test, feature = "test-support"))]
377 let _membership = crate::test_support::join_env_scope(ticket);
378 let result = (|| {
379 check_evidence_cancelled(&worker_cancel)?;
380 let result = work(&worker_cancel);
381 check_evidence_cancelled(&worker_cancel)?;
382 result
383 })();
384 Ok(result)
385 });
386 tokio::select! {
387 biased;
388 () = cancel.cancelled() => Err(ToolError::cancelled("Evidence inspection cancelled")),
389 result = worker => result.map_err(|_| ToolError::execution_failed("evidence inspection preparation failed"))?,
390 }
391 }
392
393 fn check_evidence_cancelled(cancel: &tokio_util::sync::CancellationToken) -> Result<(), ToolError> {
394 if cancel.is_cancelled() {
395 return Err(ToolError::cancelled("Evidence inspection cancelled"));
396 }
397 Ok(())
398 }
399
400 fn validate_evidence_if_present(
401 reference: &str,
402 path: &std::path::Path,
403 size_bytes: u64,
404 digest: &str,
405 session_id: &str,
406 generation: Option<u64>,
407 ) -> Result<Option<crate::tools::large_output_router::EvidenceArtifact>, ToolError> {
408 let handle = path
409 .file_stem()
410 .and_then(|stem| stem.to_str())
411 .filter(|stem| stem.starts_with("art_"))
412 .or_else(|| {
413 reference
414 .trim()
415 .starts_with("art_")
416 .then(|| reference.trim())
417 });
418 let Some(handle) = handle else {
419 return Ok(None);
420 };
421 let metadata =
422 match crate::tools::large_output_router::read_evidence_metadata(session_id, handle) {
423 Ok(metadata) => metadata,
424 Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
425 Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => {
426 return Err(ToolError::permission_denied(
427 "evidence belongs to another session",
428 ));
429 }
430 Err(_) => return Err(ToolError::execution_failed("evidence metadata is corrupt")),
431 };
432 if metadata.origin_session != session_id || metadata.handle != handle {
433 return Err(ToolError::permission_denied(
434 "evidence belongs to another session",
435 ));
436 }
437 if metadata.redacted {
438 return Err(ToolError::permission_denied("evidence has been redacted"));
439 }
440 if crate::tools::large_output_router::evidence_is_expired(
441 &metadata,
442 crate::tools::large_output_router::unix_millis_now(),
443 ) {
444 return Err(ToolError::execution_failed(
445 "evidence retention has expired",
446 ));
447 }
448 if generation.is_some_and(|generation| generation != u64::from(metadata.generation)) {
449 return Err(ToolError::execution_failed(
450 "evidence generation does not match",
451 ));
452 }
453 if metadata.size_bytes != size_bytes || metadata.digest != digest {
454 return Err(ToolError::execution_failed("evidence content is corrupt"));
455 }
456 Ok(Some(metadata))
457 }
458
459 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
460 enum ResolvedReferenceKind {
461 ActiveSession,
462 LegacyGlobal,
463 }
464
465 #[derive(Debug, Clone, PartialEq, Eq)]
466 struct ResolvedSpilloverReference {
467 path: PathBuf,
468 root: PathBuf,
469 kind: ResolvedReferenceKind,
470 }
471
472 fn authorize_legacy_spillover(
473 path: &std::path::Path,
474 session_id: &str,
475 ) -> Result<crate::tools::truncate::LegacySpilloverOwnership, ToolError> {
476 if session_id.trim().is_empty() {
477 return Err(ToolError::permission_denied(
478 "legacy evidence has no verifiable session owner",
479 ));
480 }
481 let ownership = match crate::tools::truncate::read_legacy_spillover_ownership(path) {
482 Ok(ownership) => ownership,
483 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
484 return Err(ToolError::permission_denied(
485 "legacy evidence has no verifiable session owner",
486 ));
487 }
488 Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => {
489 return Err(ToolError::permission_denied(
490 "legacy evidence ownership proof is invalid",
491 ));
492 }
493 Err(_) => {
494 return Err(ToolError::execution_failed(
495 "legacy evidence ownership metadata is corrupt",
496 ));
497 }
498 };
499 if ownership.origin_session != session_id {
500 return Err(ToolError::permission_denied(
501 "legacy evidence belongs to another session",
502 ));
503 }
504 Ok(ownership)
505 }
506
507 /// Resolve a tool-result ref without weakening its ownership boundary.
508 ///
509 /// Current-session artifacts always win over same-named global compatibility
510 /// files. A legacy call-id, SHA, relative path, or absolute path can resolve,
511 /// but the caller must validate its ownership sidecar before reading bytes.
512 fn resolve_spillover_reference(
513 reference: &str,
514 session_id: &str,
515 ) -> Result<ResolvedSpilloverReference, ToolError> {
516 let root = crate::tools::truncate::spillover_root()
517 .ok_or_else(|| ToolError::execution_failed("retained evidence storage is unavailable"))?;
518 let root_canonical = root.canonicalize().ok();
519
520 // Resolve the session's `artifacts/` directory.
521 // `session_artifact_absolute_path(sid, p)` returns
522 // `~/.codewhale/sessions/<sid>/<p>` — so passing the literal
523 // `ARTIFACTS_DIR_NAME` ("artifacts") gets us the real artifacts
524 // root. An earlier draft passed `Path::new(".")` and took
525 // `.parent()`, which landed one directory too high (`<sid>` instead
526 // of `<sid>/artifacts`) and silently broke every bare `art_<id>`
527 // ref — only the legacy-spillover fallback survived. The test
528 // `resolves_art_prefix_to_legacy_spillover_id` masked it because
529 // it ONLY wrote a legacy spillover file. The new test
530 // `resolves_art_prefix_via_session_artifacts` exercises the real
531 // path.
532 let session_artifacts_root = if !session_id.is_empty() {
533 codewhale_runtime::artifacts::session_artifact_absolute_path(
534 session_id,
535 std::path::Path::new(codewhale_runtime::artifacts::ARTIFACTS_DIR_NAME),
536 )
537 } else {
538 None
539 };
540 let session_artifacts_root_canonical = session_artifacts_root
541 .as_ref()
542 .and_then(|p| p.canonicalize().ok());
543
544 let trimmed = reference.trim();
545 let stripped = trimmed
546 .strip_prefix("tool_result:")
547 .unwrap_or(trimmed)
548 .trim();
549
550 let mut tried = 0_usize;
551 let try_path = |candidate: PathBuf, tried: &mut usize| -> Option<ResolvedSpilloverReference> {
552 *tried = (*tried).saturating_add(1);
553
554 // Reject symlinks at the leaf BEFORE canonicalizing so an
555 // attacker who can write under `<sid>/artifacts/` cannot
556 // plant a symlink to `/etc/passwd` and read it back through
557 // `retrieve_tool_result`. canonicalize() would happily
558 // follow such a link and then pass the `starts_with(root)`
559 // check because of the resolved-then-compare order. Both session and
560 // compatibility roots reject leaf symlinks. Legacy
561 // compatibility files also need a separate ownership sidecar below.
562 if let Ok(meta) = std::fs::symlink_metadata(&candidate)
563 && meta.file_type().is_symlink()
564 {
565 return None;
566 }
567
568 let canonical = candidate.canonicalize().ok()?;
569 if !canonical.is_file() {
570 return None;
571 }
572 let inside_legacy = root_canonical
573 .as_ref()
574 .is_some_and(|root| canonical.starts_with(root));
575 let inside_session = session_artifacts_root_canonical
576 .as_ref()
577 .is_some_and(|root| canonical.starts_with(root));
578 if inside_session {
579 Some(ResolvedSpilloverReference {
580 path: canonical,
581 root: session_artifacts_root_canonical.as_ref()?.clone(),
582 kind: ResolvedReferenceKind::ActiveSession,
583 })
584 } else if inside_legacy {
585 Some(ResolvedSpilloverReference {
586 path: canonical,
587 root: root_canonical.as_ref()?.clone(),
588 kind: ResolvedReferenceKind::LegacyGlobal,
589 })
590 } else {
591 None
592 }
593 };
594
595 // Form 1/3: absolute path. Validate it lives under one of the allowed roots.
596 let raw_path = PathBuf::from(stripped);
597 if raw_path.is_absolute() {
598 if let Some(found) = try_path(raw_path, &mut tried) {
599 return Ok(found);
600 }
601 return Err(ToolError::permission_denied(
602 "evidence path is not owned by the active session",
603 ));
604 }
605
606 // Session artifact paths take priority over legacy-global lookups.
607 let looks_like_path = stripped.ends_with(".txt")
608 || stripped.contains('/')
609 || (std::path::MAIN_SEPARATOR != '/' && stripped.contains(std::path::MAIN_SEPARATOR));
610 if looks_like_path {
611 if let Some(sa_root) = session_artifacts_root.as_ref() {
612 let rel = stripped.strip_prefix("artifacts/").unwrap_or(stripped);
613 if let Some(found) = try_path(sa_root.join(rel), &mut tried) {
614 return Ok(found);
615 }
616 }
617 if let Some(found) = try_path(root.join(stripped), &mut tried) {
618 return Ok(found);
619 }
620 return Err(not_found(reference, tried));
621 }
622
623 if let Some(sa_root) = session_artifacts_root.as_ref() {
624 let file_name = if stripped.starts_with("art_") {
625 format!("{stripped}.txt")
626 } else {
627 format!("art_{stripped}.txt")
628 };
629 if let Some(found) = try_path(sa_root.join(file_name), &mut tried) {
630 return Ok(found);
631 }
632 }
633
634 // `sha:<hex>` or bare 64-hex resolves only as legacy-global evidence and
635 // therefore still requires an ownership sidecar in the caller.
636 let sha_candidate = stripped
637 .strip_prefix("sha:")
638 .or_else(|| stripped.strip_prefix("sha_"))
639 .unwrap_or(stripped)
640 .trim();
641 if crate::tools::truncate::is_valid_sha256(&sha_candidate.to_ascii_lowercase())
642 && let Some(p) = crate::tools::truncate::sha_spillover_path(sha_candidate)
643 && let Some(found) = try_path(p, &mut tried)
644 {
645 return Ok(found);
646 }
647
648 // Compatibility lookup: `art_<id>` may name the historical `<id>.txt`.
649 if let Some(stripped_art) = stripped.strip_prefix("art_")
650 && let Some(p) = crate::tools::truncate::spillover_path(stripped_art)
651 && let Some(found) = try_path(p, &mut tried)
652 {
653 return Ok(found);
654 }
655
656 if let Some(path) = crate::tools::truncate::spillover_path(stripped)
657 && let Some(found) = try_path(path, &mut tried)
658 {
659 return Ok(found);
660 }
661
662 Err(not_found(reference, tried))
663 }
664
665 /// Missing evidence is distinct without revealing storage roots or generated
666 /// session identifiers to the model.
667 fn not_found(reference: &str, tried: usize) -> ToolError {
668 ToolError::execution_failed(format!(
669 "retained evidence `{reference}` was not found for the active session \
670 ({tried} bounded candidate forms checked). Use the session-owned \
671 `art_<id>` handle from the original receipt."
672 ))
673 }
674
675 #[derive(Default)]
676 struct TextInspection {
677 mode: String,
678 max_bytes: usize,
679 line_count: usize,
680 max_matches: usize,
681 context_lines: usize,
682 range: (usize, usize),
683 query: String,
684 query_lower: String,
685 wrap_tail: String,
686 total_lines: usize,
687 wrapped_segments: usize,
688 non_empty_lines: usize,
689 matched_lines: usize,
690 retained_bytes: usize,
691 leading_bytes: usize,
692 leading: Vec<(usize, String)>,
693 trailing: std::collections::VecDeque<(usize, String)>,
694 signal_lines: Vec<Value>,
695 previous: std::collections::VecDeque<(usize, String)>,
696 matches: Vec<(usize, Vec<(usize, String)>)>,
697 active_matches: std::collections::VecDeque<(usize, usize)>,
698 }
699
700 impl TextInspection {
701 fn new(mode: &str, input: &Value, max_bytes: usize) -> Result<Self, ToolError> {
702 let mut state = Self {
703 mode: mode.to_string(),
704 max_bytes,
705 ..Self::default()
706 };
707 match mode {
708 "summary" | "query" => {
709 state.max_matches = clamp_u64(
710 optional_u64(input, "max_matches", DEFAULT_MAX_MATCHES as u64)?,
711 1,
712 HARD_MAX_MATCHES,
713 );
714 if mode == "summary" {
715 state.line_count = DEFAULT_LINE_COUNT;
716 } else {
717 let raw = optional_str(input, "query")?.ok_or_else(|| {
718 ToolError::invalid_input("query is required when mode=query")
719 })?;
720 if raw.len() > MAX_QUERY_BYTES {
721 return Err(ToolError::invalid_input(
722 "query exceeds the 4096-byte inspection limit; use a shorter substring",
723 ));
724 }
725 let query = raw.trim();
726 if query.is_empty() {
727 return Err(ToolError::invalid_input(
728 "query is required when mode=query",
729 ));
730 }
731 state.query = query.to_string();
732 state.query_lower = query.to_lowercase();
733 state.context_lines = clamp_u64(
734 optional_u64(input, "context_lines", DEFAULT_CONTEXT_LINES as u64)?,
735 0,
736 HARD_CONTEXT_LINES,
737 );
738 }
739 }
740 "head" | "tail" => {
741 state.line_count = clamp_u64(
742 optional_u64(input, "line_count", DEFAULT_LINE_COUNT as u64)?,
743 1,
744 HARD_LINE_COUNT,
745 );
746 }
747 "lines" => state.range = parse_line_selector(input)?,
748 _ => return Err(ToolError::invalid_input("unsupported text inspection mode")),
749 }
750 Ok(state)
751 }
752
753 fn retain(
754 &mut self,
755 line_no: usize,
756 line: &str,
757 limit: usize,
758 ) -> Result<(usize, String), ToolError> {
759 let mut end = line.len().min(limit.saturating_add(4));
760 while !line.is_char_boundary(end) {
761 end -= 1;
762 }
763 let size = end.saturating_add(std::mem::size_of::<(usize, String)>());
764 if self.retained_bytes.saturating_add(size) > MAX_SELECTION_BYTES {
765 return Err(ToolError::execution_failed(
766 "text selection exceeds the 8 MiB inspection memory limit; reduce line_count, context_lines or max_bytes, or use mode=bytes",
767 ));
768 }
769 self.retained_bytes += size;
770 Ok((line_no, line[..end].to_string()))
771 }
772
773 fn retain_tail(
774 &mut self,
775 line_no: usize,
776 line: &str,
777 limit: usize,
778 ) -> Result<(usize, String), ToolError> {
779 let keep = limit.saturating_add(4);
780 let start = if line.len() <= keep {
781 0
782 } else {
783 let mut idx = line.len() - keep;
784 while idx < line.len() && !line.is_char_boundary(idx) {
785 idx += 1;
786 }
787 idx
788 };
789 let slice = &line[start..];
790 let size = slice
791 .len()
792 .saturating_add(std::mem::size_of::<(usize, String)>());
793 if self.retained_bytes.saturating_add(size) > MAX_SELECTION_BYTES {
794 return Err(ToolError::execution_failed(
795 "text selection exceeds the 8 MiB inspection memory limit; reduce line_count, context_lines or max_bytes, or use mode=bytes",
796 ));
797 }
798 self.retained_bytes += size;
799 Ok((line_no, slice.to_string()))
800 }
801
802 fn release(&mut self, record: &(usize, String)) {
803 self.retained_bytes = self.retained_bytes.saturating_sub(
804 record
805 .1
806 .len()
807 .saturating_add(std::mem::size_of::<(usize, String)>()),
808 );
809 }
810
811 fn push_line(&mut self, line: &str, wrapped: bool) -> Result<(), ToolError> {
812 self.total_lines += 1;
813 let line_no = self.total_lines;
814 if !line.trim().is_empty() {
815 self.non_empty_lines += 1;
816 }
817 let budget = if self.mode == "summary" {
818 self.max_bytes / 2
819 } else {
820 self.max_bytes
821 };
822 if (self.mode == "summary" || self.mode == "head")
823 && self.leading.len() < self.line_count
824 && self.leading_bytes <= budget
825 || self.mode == "lines"
826 && line_no >= self.range.0
827 && line_no <= self.range.1
828 && self.leading_bytes <= budget
829 {
830 let record = self.retain(line_no, line, budget)?;
831 self.leading_bytes = self
832 .leading_bytes
833 .saturating_add(line_no.to_string().len())
834 .saturating_add(record.1.len())
835 .saturating_add(3);
836 self.leading.push(record);
837 }
838 if self.mode == "summary" || self.mode == "tail" {
839 if self.trailing.len() == self.line_count
840 && let Some(record) = self.trailing.pop_front()
841 {
842 self.release(&record);
843 }
844 let record = self.retain_tail(line_no, line, budget)?;
845 self.trailing.push_back(record);
846 }
847 if self.mode == "summary"
848 && self.signal_lines.len() < self.max_matches
849 && is_signal_line(line)
850 {
851 self.signal_lines.push(json!({
852 "line": line_no,
853 "text": truncate_line(line.trim(), 300),
854 }));
855 }
856 if self.mode != "query" {
857 return Ok(());
858 }
859 let budget = self.max_bytes / self.max_matches;
860 while self
861 .active_matches
862 .front()
863 .is_some_and(|(_, end)| *end < line_no)
864 {
865 self.active_matches.pop_front();
866 }
867 for position in 0..self.active_matches.len() {
868 let index = self.active_matches[position].0;
869 let record = self.retain(line_no, line, budget)?;
870 self.matches[index].1.push(record);
871 }
872 let mut matched = line.to_lowercase().contains(&self.query_lower);
873 if !matched && !self.wrap_tail.is_empty() {
874 let combined = format!("{}{}", self.wrap_tail, line);
875 let combined_lower = combined.to_lowercase();
876 let boundary = self.wrap_tail.to_lowercase().len();
877 matched = combined_lower
878 .rfind(&self.query_lower)
879 .is_some_and(|pos| pos + self.query_lower.len() > boundary);
880 }
881 if matched {
882 self.matched_lines += 1;
883 if self.matches.len() < self.max_matches {
884 let mut window = Vec::new();
885 let before: Vec<(usize, String)> = self.previous.iter().cloned().collect();
886 for (number, text) in before {
887 window.push(self.retain(number, &text, budget)?);
888 }
889 window.push(self.retain(line_no, line, budget)?);
890 let index = self.matches.len();
891 self.matches.push((line_no, window));
892 self.active_matches
893 .push_back((index, line_no.saturating_add(self.context_lines)));
894 }
895 }
896 if wrapped {
897 let keep_chars = self.query_lower.chars().count().saturating_sub(1);
898 if keep_chars == 0 {
899 self.wrap_tail.clear();
900 } else {
901 let line_chars = line.chars().count();
902 if line_chars >= keep_chars {
903 let start = line
904 .char_indices()
905 .nth(line_chars - keep_chars)
906 .map_or(line.len(), |(idx, _)| idx);
907 self.wrap_tail = line[start..].to_string();
908 } else {
909 let tail_need = keep_chars - line_chars;
910 let tail_chars = self.wrap_tail.chars().count();
911 let skip = tail_chars.saturating_sub(tail_need);
912 let start = self
913 .wrap_tail
914 .char_indices()
915 .nth(skip)
916 .map_or(self.wrap_tail.len(), |(idx, _)| idx);
917 self.wrap_tail = format!("{}{}", &self.wrap_tail[start..], line);
918 }
919 }
920 } else {
921 self.wrap_tail.clear();
922 }
923 if self.context_lines > 0 && self.matches.len() < self.max_matches {
924 if self.previous.len() == self.context_lines
925 && let Some(record) = self.previous.pop_front()
926 {
927 self.release(&record);
928 }
929 let record = self.retain(line_no, line, budget)?;
930 self.previous.push_back(record);
931 }
932 Ok(())
933 }
934
935 fn payload(self, reference: &str, total_bytes: u64) -> Value {
936 let numbered = |records: &[(usize, String)], budget| {
937 render_numbered_lines(
938 records
939 .iter()
940 .map(|(number, text)| (*number, text.as_str())),
941 budget,
942 )
943 };
944 let wrapped_segments = self.wrapped_segments;
945 let mut payload = match self.mode.as_str() {
946 "summary" => json!({
947 "ref": reference,
948 "mode": "summary",
949 "total_bytes": total_bytes,
950 "total_lines": self.total_lines,
951 "non_empty_lines": self.non_empty_lines,
952 "signal_lines": self.signal_lines,
953 "head": numbered(&self.leading, self.max_bytes / 2),
954 "tail": render_tail_numbered_lines(&self.trailing, self.max_bytes / 2),
955 "hint": "Use mode=head, tail, lines, or query to retrieve a narrower slice."
956 }),
957 "head" | "tail" => json!({
958 "ref": reference,
959 "mode": self.mode,
960 "total_lines": self.total_lines,
961 "line_count": self.line_count,
962 "excerpt": if self.mode == "head" { numbered(&self.leading, self.max_bytes) } else { render_tail_numbered_lines(&self.trailing, self.max_bytes) },
963 }),
964 "lines" => json!({
965 "ref": reference,
966 "mode": "lines",
967 "total_lines": self.total_lines,
968 "start_line": self.range.0,
969 "end_line": self.range.1.min(self.total_lines),
970 "excerpt": numbered(&self.leading, self.max_bytes),
971 }),
972 "query" => json!({
973 "ref": reference,
974 "mode": "query",
975 "query": self.query,
976 "total_lines": self.total_lines,
977 "matched_lines": self.matched_lines,
978 "matches_returned": self.matches.len(),
979 "results": self.matches.iter().map(|(line, window)| {
980 let budget = self.max_bytes / self.max_matches;
981 let fits = window.iter().map(|(_, text)| text.len() + 16).sum::<usize>() <= budget;
982 let shown: Vec<(usize, String)> = if fits {
983 window.clone()
984 } else {
985 window.iter().filter(|(number, _)| number == line).cloned().collect()
986 };
987 json!({
988 "line": line,
989 "excerpt": numbered(&shown, budget),
990 })
991 }).collect::<Vec<_>>(),
992 }),
993 _ => unreachable!(),
994 };
995 if wrapped_segments > 0 {
996 payload["long_lines_split_at_bytes"] = json!(WRAP_LINE_BYTES);
997 payload["split_segments"] = json!(wrapped_segments);
998 }
999 payload
1000 }
1001 }
1002
1003 struct EvidenceSnapshot {
1004 size_bytes: u64,
1005 digest: String,
1006 byte_slice: Vec<u8>,
1007 inspection: Result<Option<TextInspection>, ToolError>,
1008 }
1009
1010 async fn stream_evidence(
1011 source: std::fs::File,
1012 initial_size: u64,
1013 input: &Value,
1014 mode: &str,
1015 max_bytes: usize,
1016 inspection: Option<TextInspection>,
1017 context: &ToolContext,
1018 ) -> Result<EvidenceSnapshot, ToolError> {
1019 use sha2::{Digest, Sha256};
1020 use tokio::io::AsyncReadExt;
1021 let limit_error = || {
1022 ToolError::execution_failed(
1023 "evidence exceeds the 512 MiB verification scan limit; export a smaller artifact through the owning session",
1024 )
1025 };
1026 if initial_size > MAX_SCAN_BYTES {
1027 return Err(limit_error());
1028 }
1029 let mut file = tokio::fs::File::from_std(source);
1030 let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(20);
1031 let offset = input.get("offset").and_then(Value::as_u64).unwrap_or(0);
1032 let length = input
1033 .get("length")
1034 .and_then(Value::as_u64)
1035 .unwrap_or(max_bytes as u64)
1036 .min(max_bytes as u64);
1037 let slice_end = offset.saturating_add(length);
1038 let mut state = inspection;
1039 let mut text_error = None;
1040 let mut hasher = Sha256::new();
1041 let mut total = 0u64;
1042 let mut chunk = [0u8; 64 * 1024];
1043 let mut line = Vec::new();
1044 let mut byte_slice = Vec::new();
1045 let mut json_candidate = mode == "summary" && initial_size <= MAX_JSON_BYTES;
1046 let mut json_leading_checked = false;
1047 loop {
1048 if context
1049 .cancel_token
1050 .as_ref()
1051 .is_some_and(|token| token.is_cancelled())
1052 {
1053 return Err(ToolError::cancelled("Evidence inspection cancelled"));
1054 }
1055 if tokio::time::Instant::now() >= deadline {
1056 return Err(ToolError::execution_failed(
1057 "evidence verification exceeded the 20-second scan limit; export a smaller artifact through the owning session",
1058 ));
1059 }
1060 let read = async {
1061 loop {
1062 let result = match context.cancel_token.as_ref() {
1063 Some(token) => tokio::select! {
1064 biased;
1065 () = token.cancelled() => return Err(ToolError::cancelled("Evidence inspection cancelled")),
1066 result = file.read(&mut chunk) => result,
1067 },
1068 None => file.read(&mut chunk).await,
1069 };
1070 match result {
1071 Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
1072 result => {
1073 return result.map_err(|_| {
1074 ToolError::execution_failed("evidence is missing or no longer retained")
1075 });
1076 }
1077 }
1078 }
1079 };
1080 let n = tokio::time::timeout_at(deadline, read).await
1081 .map_err(|_| ToolError::execution_failed("evidence verification exceeded the 20-second scan limit; export a smaller artifact through the owning session"))??;
1082 if n == 0 {
1083 break;
1084 }
1085 let start = total;
1086 total = total.saturating_add(n as u64);
1087 if total > MAX_SCAN_BYTES {
1088 return Err(limit_error());
1089 }
1090 hasher.update(&chunk[..n]);
1091 if mode == "json" {
1092 if total > MAX_JSON_BYTES {
1093 return Err(ToolError::execution_failed(
1094 "evidence exceeds the 32 MiB json inspection limit; use mode=query or mode=lines",
1095 ));
1096 }
1097 byte_slice.extend_from_slice(&chunk[..n]);
1098 } else if mode == "summary" && json_candidate {
1099 if !json_leading_checked
1100 && let Some(&first) = chunk[..n]
1101 .iter()
1102 .find(|byte| !matches!(byte, b' ' | b'\t' | b'\r' | b'\n'))
1103 {
1104 json_leading_checked = true;
1105 if !matches!(first, b'{' | b'[') {
1106 json_candidate = false;
1107 byte_slice.clear();
1108 byte_slice.shrink_to_fit();
1109 }
1110 }
1111 if json_candidate {
1112 if total > MAX_JSON_BYTES {
1113 json_candidate = false;
1114 byte_slice.clear();
1115 byte_slice.shrink_to_fit();
1116 } else {
1117 byte_slice.extend_from_slice(&chunk[..n]);
1118 }
1119 }
1120 }
1121 if mode == "bytes" {
1122 let first = offset.max(start);
1123 let last = slice_end.min(total);
1124 if first < last {
1125 byte_slice
1126 .extend_from_slice(&chunk[(first - start) as usize..(last - start) as usize]);
1127 }
1128 }
1129 if state.is_some() {
1130 for piece in chunk[..n].split_inclusive(|byte| *byte == b'\n') {
1131 line.extend_from_slice(piece);
1132 let terminated = piece.ends_with(b"\n");
1133 let mut result = Ok(());
1134 loop {
1135 let body = if terminated {
1136 let raw = line.strip_suffix(b"\n").unwrap_or(&line);
1137 raw.strip_suffix(b"\r").unwrap_or(raw)
1138 } else {
1139 line.strip_suffix(b"\r").unwrap_or(&line)
1140 };
1141 if body.len() <= WRAP_LINE_BYTES {
1142 if terminated {
1143 result = feed_line(state.as_mut().unwrap(), body, false);
1144 line.clear();
1145 }
1146 break;
1147 }
1148 let mut cut = WRAP_LINE_BYTES;
1149 while cut > 0 && body[cut] & 0xC0 == 0x80 {
1150 cut -= 1;
1151 }
1152 let cut = if cut == 0 { WRAP_LINE_BYTES } else { cut };
1153 result = feed_line(state.as_mut().unwrap(), &body[..cut], true);
1154 if result.is_err() {
1155 break;
1156 }
1157 line.drain(..cut);
1158 }
1159 if let Err(error) = result {
1160 text_error = Some(error);
1161 state = None;
1162 line.clear();
1163 break;
1164 }
1165 }
1166 }
1167 }
1168 if let Some(state) = state.as_mut()
1169 && !line.is_empty()
1170 && let Err(error) = feed_line(state, &line, false)
1171 {
1172 text_error = Some(error);
1173 }
1174 if tokio::time::Instant::now() >= deadline {
1175 return Err(ToolError::execution_failed(
1176 "evidence verification exceeded the 20-second scan limit; export a smaller artifact through the owning session",
1177 ));
1178 }
1179 Ok(EvidenceSnapshot {
1180 size_bytes: total,
1181 digest: codewhale_runtime::hashing::hex_bytes(hasher.finalize()),
1182 byte_slice,
1183 inspection: match text_error {
1184 Some(error) => Err(error),
1185 None => Ok(state),
1186 },
1187 })
1188 }
1189
1190 fn feed_line(state: &mut TextInspection, raw: &[u8], wrapped: bool) -> Result<(), ToolError> {
1191 let text = std::str::from_utf8(raw).map_err(|_| {
1192 ToolError::execution_failed(
1193 "evidence encoding is binary; bounded text inspection is unavailable",
1194 )
1195 })?;
1196 if wrapped {
1197 state.wrapped_segments += 1;
1198 }
1199 state.push_line(text, wrapped)
1200 }
1201
1202 fn select_json(bytes: &[u8], path: &str) -> Result<(Vec<Value>, bool), ToolError> {
1203 fn expand(value: &mut Value) {
1204 match value {
1205 Value::String(text) => {
1206 let trimmed = text.trim_start();
1207 if (trimmed.starts_with('{') || trimmed.starts_with('['))
1208 && let Ok(mut parsed) = serde_json::from_str::<Value>(text)
1209 {
1210 expand(&mut parsed);
1211 *value = parsed;
1212 }
1213 }
1214 Value::Array(items) => items.iter_mut().for_each(expand),
1215 Value::Object(map) => map.values_mut().for_each(expand),
1216 _ => {}
1217 }
1218 }
1219 let mut root: Value = serde_json::from_slice(bytes).map_err(|error| {
1220 ToolError::execution_failed(format!(
1221 "evidence is not JSON ({error}); use mode=summary, query or lines"
1222 ))
1223 })?;
1224 expand(&mut root);
1225 crate::tools::handle::query_jsonpath_capped(&root, path).map_err(ToolError::invalid_input)
1226 }
1227
1228 fn parse_line_selector(input: &Value) -> Result<(usize, usize), ToolError> {
1229 let explicit_start = input.get("start_line").and_then(Value::as_u64);
1230 let explicit_end = input.get("end_line").and_then(Value::as_u64);
1231 if explicit_start.is_some() || explicit_end.is_some() {
1232 let start = explicit_start.ok_or_else(|| {
1233 ToolError::invalid_input("start_line is required when end_line is supplied")
1234 })?;
1235 let end = explicit_end.unwrap_or(start);
1236 let start = usize::try_from(start)
1237 .map_err(|_| ToolError::invalid_input("start_line exceeds the platform range"))?;
1238 let end = usize::try_from(end)
1239 .map_err(|_| ToolError::invalid_input("end_line exceeds the platform range"))?;
1240 return validate_line_range(start, end);
1241 }
1242
1243 let raw = optional_str(input, "lines")?;
1244 if raw.is_some_and(|value| value.len() > 64) {
1245 return Err(ToolError::invalid_input(
1246 "lines selector exceeds the 64-byte inspection limit",
1247 ));
1248 }
1249 let spec = raw
1250 .map(str::trim)
1251 .filter(|s| !s.is_empty())
1252 .ok_or_else(|| {
1253 ToolError::invalid_input(
1254 "mode=lines requires `lines` (for example \"10-40\") or start_line/end_line",
1255 )
1256 })?;
1257
1258 if let Some((start, end)) = spec.split_once('-') {
1259 let start = parse_positive_line(start.trim(), "lines start")?;
1260 let end = parse_positive_line(end.trim(), "lines end")?;
1261 validate_line_range(start, end)
1262 } else {
1263 let line = parse_positive_line(spec, "lines")?;
1264 validate_line_range(line, line)
1265 }
1266 }
1267
1268 fn validate_line_range(start: usize, end: usize) -> Result<(usize, usize), ToolError> {
1269 if start == 0 || end == 0 {
1270 return Err(ToolError::invalid_input("line numbers are 1-based"));
1271 }
1272 if end < start {
1273 return Err(ToolError::invalid_input(
1274 "end_line must be greater than or equal to start_line",
1275 ));
1276 }
1277 Ok((start, end))
1278 }
1279
1280 fn parse_positive_line(raw: &str, field: &str) -> Result<usize, ToolError> {
1281 raw.parse::<usize>().map_err(|_| {
1282 ToolError::invalid_input(format!("{field} must be a positive integer line number"))
1283 })
1284 }
1285
1286 fn expand_embedded_json(value: &mut Value, depth: usize) {
1287 if depth >= MAX_JSON_EXPAND_DEPTH {
1288 return;
1289 }
1290 match value {
1291 Value::String(text) => {
1292 let trimmed = text.trim_start();
1293 if (trimmed.starts_with('{') || trimmed.starts_with('['))
1294 && let Ok(mut parsed) = serde_json::from_str::<Value>(text)
1295 {
1296 expand_embedded_json(&mut parsed, depth + 1);
1297 *value = parsed;
1298 }
1299 }
1300 Value::Array(items) => {
1301 for item in items.iter_mut().take(32) {
1302 expand_embedded_json(item, depth + 1);
1303 }
1304 }
1305 Value::Object(map) => {
1306 for val in map.values_mut().take(MAX_JSON_SUMMARY_KEYS) {
1307 expand_embedded_json(val, depth + 1);
1308 }
1309 }
1310 _ => {}
1311 }
1312 }
1313
1314 fn looks_like_base64_blob(s: &str) -> bool {
1315 if s.len() >= 128
1316 && s.starts_with("data:")
1317 && s.split_once(',')
1318 .is_some_and(|(head, _)| head.contains(";base64"))
1319 {
1320 return true;
1321 }
1322 if s.len() < 256 || s.starts_with("http://") || s.starts_with("https://") || s.starts_with('/')
1323 {
1324 return false;
1325 }
1326 let mut has_upper = false;
1327 let mut has_lower = false;
1328 let mut has_digit_or_sym = false;
1329 for b in s.bytes() {
1330 match b {
1331 b'A'..=b'Z' => has_upper = true,
1332 b'a'..=b'z' => has_lower = true,
1333 b'0'..=b'9' | b'+' | b'/' | b'=' | b'-' | b'_' => has_digit_or_sym = true,
1334 _ => return false,
1335 }
1336 }
1337 has_upper && has_lower && has_digit_or_sym
1338 }
1339
1340 fn json_type_name(value: &Value) -> &'static str {
1341 match value {
1342 Value::Null => "null",
1343 Value::Bool(_) => "boolean",
1344 Value::Number(_) => "number",
1345 Value::String(_) => "string",
1346 Value::Array(_) => "array",
1347 Value::Object(_) => "object",
1348 }
1349 }
1350
1351 fn jsonpath_key_segment(key: &str) -> Option<String> {
1352 if !key.is_empty() && key.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
1353 Some(format!(".{key}"))
1354 } else if !key.contains(']') && !key.contains('\'') {
1355 Some(format!("['{key}']"))
1356 } else {
1357 None
1358 }
1359 }
1360
1361 fn describe_json_scalar_sample(value: &Value) -> Value {
1362 match value {
1363 Value::Null => Value::Null,
1364 Value::Bool(b) => json!(b),
1365 Value::Number(n) => json!(n),
1366 Value::String(s) => {
1367 if looks_like_base64_blob(s) {
1368 json!(format!("<base64 omitted ({} bytes)>", s.len()))
1369 } else {
1370 json!(truncate_line(s, 60))
1371 }
1372 }
1373 Value::Array(items) => json!(format!("[array({})]", items.len())),
1374 Value::Object(map) => json!(format!("{{object({} keys)}}", map.len())),
1375 }
1376 }
1377
1378 fn describe_json_value(value: &Value, depth: usize) -> Value {
1379 match value {
1380 Value::Null => json!({ "type": "null" }),
1381 Value::Bool(b) => json!({ "type": "boolean", "preview": b }),
1382 Value::Number(n) => json!({ "type": "number", "preview": n }),
1383 Value::String(s) => {
1384 if looks_like_base64_blob(s) {
1385 json!({
1386 "type": "string",
1387 "bytes": s.len(),
1388 "format": "base64",
1389 "preview": format!("<base64 omitted ({} bytes)>", s.len()),
1390 })
1391 } else {
1392 json!({
1393 "type": "string",
1394 "bytes": s.len(),
1395 "preview": truncate_line(s, MAX_JSON_STRING_PREVIEW_CHARS),
1396 })
1397 }
1398 }
1399 Value::Array(items) => {
1400 let mut element_types = Vec::new();
1401 for item in items.iter().take(100) {
1402 let kind = json_type_name(item);
1403 if !element_types.contains(&kind) {
1404 element_types.push(kind);
1405 }
1406 }
1407 let mut desc = serde_json::Map::new();
1408 desc.insert("type".to_string(), json!("array"));
1409 desc.insert("length".to_string(), json!(items.len()));
1410 if !element_types.is_empty() {
1411 desc.insert("element_types".to_string(), json!(element_types));
1412 }
1413 if let Some(first) = items.first()
1414 && depth < MAX_JSON_SUMMARY_DEPTH
1415 {
1416 match first {
1417 Value::Object(obj) => {
1418 if depth == 0 {
1419 desc.insert(
1420 "first_element".to_string(),
1421 describe_json_value(first, depth + 1),
1422 );
1423 } else {
1424 let elem_keys: Vec<String> = obj.keys().take(12).cloned().collect();
1425 desc.insert("element_keys".to_string(), json!(elem_keys));
1426 if obj.len() > 12 {
1427 desc.insert(
1428 "omitted_element_keys".to_string(),
1429 json!(obj.len() - 12),
1430 );
1431 }
1432 }
1433 }
1434 Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {
1435 let sample: Vec<Value> = items
1436 .iter()
1437 .take(MAX_JSON_ARRAY_SAMPLE_ITEMS)
1438 .map(describe_json_scalar_sample)
1439 .collect();
1440 desc.insert("sample".to_string(), json!(sample));
1441 }
1442 Value::Array(_) => {}
1443 }
1444 }
1445 Value::Object(desc)
1446 }
1447 Value::Object(map) => {
1448 let mut desc = serde_json::Map::new();
1449 desc.insert("type".to_string(), json!("object"));
1450 desc.insert("key_count".to_string(), json!(map.len()));
1451 if depth < MAX_JSON_SUMMARY_DEPTH {
1452 let limit = if depth == 0 {
1453 MAX_JSON_SUMMARY_CHILD_KEYS
1454 } else {
1455 8
1456 };
1457 let mut children = serde_json::Map::new();
1458 for (k, v) in map.iter().take(limit) {
1459 children.insert(k.clone(), describe_json_value(v, depth + 1));
1460 }
1461 desc.insert("keys".to_string(), Value::Object(children));
1462 if map.len() > limit {
1463 desc.insert("omitted_keys".to_string(), json!(map.len() - limit));
1464 }
1465 } else {
1466 let names: Vec<String> = map.keys().take(12).cloned().collect();
1467 desc.insert("keys".to_string(), json!(names));
1468 if map.len() > 12 {
1469 desc.insert("omitted_keys".to_string(), json!(map.len() - 12));
1470 }
1471 }
1472 Value::Object(desc)
1473 }
1474 }
1475 }
1476
1477 fn push_unique_query(out: &mut Vec<String>, query: String) {
1478 if out.len() < MAX_JSON_SUGGESTED_QUERIES && !out.contains(&query) {
1479 out.push(query);
1480 }
1481 }
1482
1483 fn collect_suggested_queries(root: &Value) -> Vec<String> {
1484 let mut queries = Vec::new();
1485 match root {
1486 Value::Object(map) => {
1487 for (key, value) in map.iter().take(MAX_JSON_SUMMARY_KEYS) {
1488 if queries.len() >= MAX_JSON_SUGGESTED_QUERIES {
1489 break;
1490 }
1491 let Some(seg) = jsonpath_key_segment(key) else {
1492 continue;
1493 };
1494 let base = format!("${seg}");
1495 match value {
1496 Value::String(s) if looks_like_base64_blob(s) => continue,
1497 Value::Array(items) if !items.is_empty() => {
1498 if let Some(Value::Object(first_obj)) = items.first() {
1499 if let Some(Value::Object(inner)) = first_obj.get("text") {
1500 for (inner_k, inner_v) in inner.iter().take(2) {
1501 if let Some(inner_seg) = jsonpath_key_segment(inner_k) {
1502 let inner_path = format!("{base}[0].text{inner_seg}");
1503 if matches!(inner_v, Value::Array(arr) if !arr.is_empty()) {
1504 push_unique_query(
1505 &mut queries,
1506 format!("{inner_path}[0]"),
1507 );
1508 } else {
1509 push_unique_query(&mut queries, inner_path);
1510 }
1511 }
1512 }
1513 } else {
1514 push_unique_query(&mut queries, format!("{base}[0]"));
1515 if let Some((first_k, _)) = first_obj.iter().next()
1516 && let Some(k_seg) = jsonpath_key_segment(first_k)
1517 {
1518 push_unique_query(&mut queries, format!("{base}[*]{k_seg}"));
1519 }
1520 }
1521 } else {
1522 push_unique_query(&mut queries, format!("{base}[0]"));
1523 }
1524 }
1525 Value::Object(child) => {
1526 push_unique_query(&mut queries, base.clone());
1527 if let Some((child_k, _)) = child.iter().next()
1528 && let Some(c_seg) = jsonpath_key_segment(child_k)
1529 {
1530 push_unique_query(&mut queries, format!("{base}{c_seg}"));
1531 }
1532 }
1533 _ => push_unique_query(&mut queries, base),
1534 }
1535 }
1536 if queries.is_empty() {
1537 for key in map.keys().take(2) {
1538 if let Some(seg) = jsonpath_key_segment(key) {
1539 push_unique_query(&mut queries, format!("${seg}"));
1540 }
1541 }
1542 }
1543 }
1544 Value::Array(items) => {
1545 if let Some(first) = items.first() {
1546 push_unique_query(&mut queries, "$[0]".to_string());
1547 if let Value::Object(obj) = first {
1548 for key in obj.keys().take(3) {
1549 if let Some(seg) = jsonpath_key_segment(key) {
1550 push_unique_query(&mut queries, format!("$[*]{seg}"));
1551 }
1552 }
1553 }
1554 } else {
1555 push_unique_query(&mut queries, "$".to_string());
1556 }
1557 }
1558 _ => push_unique_query(&mut queries, "$".to_string()),
1559 }
1560 queries
1561 }
1562
1563 fn bound_json_summary(mut payload: Value, max_bytes: usize) -> Value {
1564 if serde_json::to_string(&payload).map_or(usize::MAX, |s| s.len()) <= max_bytes {
1565 return payload;
1566 }
1567 if let Some(obj) = payload.as_object_mut() {
1568 let mut dropped = obj.get("omitted_keys").and_then(Value::as_u64).unwrap_or(0);
1569 while serde_json::to_string(&Value::Object(obj.clone())).map_or(usize::MAX, |s| s.len())
1570 > max_bytes
1571 {
1572 let removed = obj
1573 .get_mut("keys")
1574 .and_then(Value::as_object_mut)
1575 .and_then(|keys| {
1576 let last = keys.keys().next_back()?.clone();
1577 keys.remove(&last)
1578 });
1579 if removed.is_none() {
1580 break;
1581 }
1582 dropped += 1;
1583 obj.insert("omitted_keys".to_string(), json!(dropped));
1584 }
1585 }
1586 if serde_json::to_string(&payload).map_or(usize::MAX, |s| s.len()) <= max_bytes {
1587 return payload;
1588 }
1589 crate::tools::truncate::shrink_json(payload, max_bytes).0
1590 }
1591
1592 fn summarize_json_artifact(
1593 reference: &str,
1594 bytes: &[u8],
1595 total_bytes: u64,
1596 max_bytes: usize,
1597 cancel: &tokio_util::sync::CancellationToken,
1598 ) -> Result<Option<Value>, ToolError> {
1599 let Ok(mut root) = serde_json::from_slice::<Value>(bytes) else {
1600 return Ok(None);
1601 };
1602 if !matches!(root, Value::Object(_) | Value::Array(_)) {
1603 return Ok(None);
1604 }
1605 check_evidence_cancelled(cancel)?;
1606 expand_embedded_json(&mut root, 0);
1607 check_evidence_cancelled(cancel)?;
1608 let suggested_queries = collect_suggested_queries(&root);
1609 let hint = if suggested_queries.is_empty() {
1610 "Use mode=\"json\" with jsonpath=\"$\" to inspect structured values, or mode=\"query\" to search text.".to_string()
1611 } else {
1612 let examples = suggested_queries
1613 .iter()
1614 .take(3)
1615 .map(|q| format!("\"{q}\""))
1616 .collect::<Vec<_>>()
1617 .join(", ");
1618 format!(
1619 "Use mode=\"json\" with jsonpath (for example {examples}) to fetch specific fields without loading the full artifact."
1620 )
1621 };
1622 let payload = match &root {
1623 Value::Object(map) => {
1624 let mut keys = serde_json::Map::new();
1625 for (k, v) in map.iter().take(MAX_JSON_SUMMARY_KEYS) {
1626 keys.insert(k.clone(), describe_json_value(v, 0));
1627 }
1628 let mut obj = serde_json::Map::new();
1629 obj.insert("ref".to_string(), json!(reference));
1630 obj.insert("mode".to_string(), json!("summary"));
1631 obj.insert("format".to_string(), json!("json"));
1632 obj.insert("root_type".to_string(), json!("object"));
1633 obj.insert("total_bytes".to_string(), json!(total_bytes));
1634 obj.insert("key_count".to_string(), json!(map.len()));
1635 obj.insert("keys".to_string(), Value::Object(keys));
1636 if map.len() > MAX_JSON_SUMMARY_KEYS {
1637 obj.insert(
1638 "omitted_keys".to_string(),
1639 json!(map.len() - MAX_JSON_SUMMARY_KEYS),
1640 );
1641 }
1642 obj.insert("suggested_queries".to_string(), json!(suggested_queries));
1643 obj.insert("hint".to_string(), json!(hint));
1644 Value::Object(obj)
1645 }
1646 Value::Array(items) => {
1647 let mut element_types = Vec::new();
1648 for item in items.iter().take(100) {
1649 let kind = json_type_name(item);
1650 if !element_types.contains(&kind) {
1651 element_types.push(kind);
1652 }
1653 }
1654 let mut obj = serde_json::Map::new();
1655 obj.insert("ref".to_string(), json!(reference));
1656 obj.insert("mode".to_string(), json!("summary"));
1657 obj.insert("format".to_string(), json!("json"));
1658 obj.insert("root_type".to_string(), json!("array"));
1659 obj.insert("total_bytes".to_string(), json!(total_bytes));
1660 obj.insert("length".to_string(), json!(items.len()));
1661 obj.insert("element_types".to_string(), json!(element_types));
1662 if let Some(first) = items.first() {
1663 obj.insert("sample_element".to_string(), describe_json_value(first, 0));
1664 }
1665 obj.insert("suggested_queries".to_string(), json!(suggested_queries));
1666 obj.insert("hint".to_string(), json!(hint));
1667 Value::Object(obj)
1668 }
1669 _ => unreachable!(),
1670 };
1671 Ok(Some(bound_json_summary(payload, max_bytes)))
1672 }
1673
1674 fn is_signal_line(line: &str) -> bool {
1675 if looks_like_base64_blob(line.trim()) {
1676 return false;
1677 }
1678 let lower = line.to_lowercase();
1679 [
1680 "error",
1681 "failed",
1682 "failure",
1683 "panic",
1684 "warning",
1685 "exception",
1686 "traceback",
1687 "assertion",
1688 "exit code",
1689 "test result",
1690 "thread '",
1691 ]
1692 .iter()
1693 .any(|needle| lower.contains(needle))
1694 }
1695
1696 fn render_numbered_lines<'a>(
1697 lines: impl IntoIterator<Item = (usize, &'a str)>,
1698 max_bytes: usize,
1699 ) -> String {
1700 let mut rendered = String::new();
1701 for (line_no, line) in lines {
1702 rendered.push_str(&format!("{line_no}: {line}\n"));
1703 if rendered.len() > max_bytes {
1704 break;
1705 }
1706 }
1707 truncate_text(&rendered, max_bytes)
1708 }
1709
1710 fn render_tail_numbered_lines(
1711 lines: &std::collections::VecDeque<(usize, String)>,
1712 max_bytes: usize,
1713 ) -> String {
1714 let mut selected: Vec<String> = Vec::new();
1715 let mut used = 0usize;
1716 for (line_no, text) in lines.iter().rev() {
1717 let entry = format!("{line_no}: {text}");
1718 if selected.is_empty() && entry.len() > max_bytes {
1719 let prefix = format!("{line_no}: [truncated to max_bytes] ");
1720 if prefix.len() >= max_bytes {
1721 return truncate_text(&entry, max_bytes);
1722 }
1723 let keep = max_bytes - prefix.len();
1724 let raw_start = text.len().saturating_sub(keep);
1725 let start = (raw_start..=text.len())
1726 .find(|idx| text.is_char_boundary(*idx))
1727 .unwrap_or(text.len());
1728 return format!("{prefix}{}", &text[start..]);
1729 }
1730 let sep = usize::from(!selected.is_empty());
1731 if used + sep + entry.len() > max_bytes {
1732 break;
1733 }
1734 used += sep + entry.len();
1735 selected.push(entry);
1736 }
1737 selected.reverse();
1738 selected.join("\n")
1739 }
1740
1741 fn truncate_text(text: &str, max_bytes: usize) -> String {
1742 if text.len() <= max_bytes {
1743 return text.trim_end_matches('\n').to_string();
1744 }
1745 let note = "\n[truncated to max_bytes]";
1746 let budget = max_bytes.saturating_sub(note.len()).max(1);
1747 let cut = (0..=budget)
1748 .rev()
1749 .find(|idx| text.is_char_boundary(*idx))
1750 .unwrap_or(0);
1751 format!("{}{}", text[..cut].trim_end_matches('\n'), note)
1752 }
1753
1754 fn truncate_line(line: &str, max_chars: usize) -> String {
1755 if line.chars().count() <= max_chars {
1756 return line.to_string();
1757 }
1758 let mut out: String = line.chars().take(max_chars.saturating_sub(3)).collect();
1759 out.push_str("...");
1760 out
1761 }
1762
1763 fn clamp_u64(value: u64, min: usize, max: usize) -> usize {
1764 usize::try_from(value).unwrap_or(usize::MAX).clamp(min, max)
1765 }
1766
1767 #[cfg(test)]
1768 mod tests {
1769 use super::*;
1770 use std::fs;
1771 use std::sync::MutexGuard;
1772 use tempfile::tempdir;
1773
1774 struct SpilloverRootGuard {
1775 prior: Option<PathBuf>,
1776 }
1777
1778 impl Drop for SpilloverRootGuard {
1779 fn drop(&mut self) {
1780 crate::tools::truncate::set_test_spillover_root(self.prior.take());
1781 }
1782 }
1783
1784 fn set_spillover_root(path: PathBuf) -> SpilloverRootGuard {
1785 let prior = crate::tools::truncate::set_test_spillover_root(Some(path));
1786 SpilloverRootGuard { prior }
1787 }
1788
1789 fn context() -> ToolContext {
1790 let tmp = tempdir().unwrap();
1791 ToolContext::new(tmp.path())
1792 }
1793
1794 fn test_lock() -> MutexGuard<'static, ()> {
1795 crate::tools::truncate::TEST_SPILLOVER_GUARD
1796 .lock()
1797 .unwrap_or_else(|err| err.into_inner())
1798 }
1799
1800 fn execute_tool(input: Value) -> Result<ToolResult, ToolError> {
1801 let runtime = tokio::runtime::Builder::new_current_thread()
1802 .enable_all()
1803 .build()
1804 .unwrap();
1805 runtime.block_on(RetrieveToolResultTool.execute(input, &context()))
1806 }
1807
1808 fn execute_tool_in_session(input: Value, session_id: &str) -> Result<ToolResult, ToolError> {
1809 let runtime = tokio::runtime::Builder::new_current_thread()
1810 .enable_all()
1811 .build()
1812 .unwrap();
1813 let mut context = context();
1814 context.state_namespace = session_id.to_string();
1815 runtime.block_on(RetrieveToolResultTool.execute(input, &context))
1816 }
1817
1818 fn publish_test_evidence(
1819 session_id: &str,
1820 handle: &str,
1821 bytes: &[u8],
1822 expired: bool,
1823 ) -> crate::tools::large_output_router::EvidenceArtifact {
1824 let relative = codewhale_runtime::artifacts::session_artifact_relative_path(handle);
1825 codewhale_runtime::artifacts::write_session_relative_immutable(
1826 session_id, &relative, bytes,
1827 )
1828 .unwrap();
1829 let now = crate::tools::large_output_router::unix_millis_now();
1830 let artifact = crate::tools::large_output_router::EvidenceArtifact {
1831 handle: handle.to_string(),
1832 digest: codewhale_runtime::hashing::sha256_hex(bytes),
1833 size_bytes: bytes.len() as u64,
1834 content_type: "application/octet-stream".to_string(),
1835 tool_name: "exec_shell".to_string(),
1836 call_id: handle.trim_start_matches("art_").to_string(),
1837 origin_session: session_id.to_string(),
1838 generation: 1,
1839 redacted: false,
1840 encoding: "binary".to_string(),
1841 retention_state: if expired {
1842 crate::tools::large_output_router::EvidenceRetentionState::Expired
1843 } else {
1844 crate::tools::large_output_router::EvidenceRetentionState::Live
1845 },
1846 created_at_unix_ms: now,
1847 retain_until_unix_ms: now.saturating_add(60_000),
1848 storage_path: relative,
1849 };
1850 crate::tools::large_output_router::publish_evidence_metadata(session_id, &artifact)
1851 .unwrap();
1852 artifact
1853 }
1854
1855 fn write_owned_legacy(id: &str, content: &str, session_id: &str) -> PathBuf {
1856 let path = crate::tools::truncate::write_spillover(id, content).unwrap();
1857 crate::tools::truncate::publish_legacy_spillover_ownership(
1858 &path,
1859 session_id,
1860 content.as_bytes(),
1861 )
1862 .unwrap();
1863 path
1864 }
1865
1866 fn write_owned_sha(content: &str, session_id: &str) -> (String, PathBuf) {
1867 let sha = codewhale_runtime::hashing::sha256_hex(content.as_bytes());
1868 let path = crate::tools::truncate::write_sha_spillover(&sha, content).unwrap();
1869 crate::tools::truncate::publish_legacy_spillover_ownership(
1870 &path,
1871 session_id,
1872 content.as_bytes(),
1873 )
1874 .unwrap();
1875 (sha, path)
1876 }
1877
1878 #[test]
1879 fn summary_reads_spillover_by_tool_call_id() {
1880 let _lock = test_lock();
1881 let tmp = tempdir().unwrap();
1882 let _guard = set_spillover_root(tmp.path().join("tool_outputs"));
1883 let session_id = "session-legacy-summary";
1884 write_owned_legacy(
1885 "call-abc",
1886 "checking crate\nerror[E0425]: missing value\nwarning: unused import\nfinished",
1887 session_id,
1888 );
1889
1890 let result = execute_tool_in_session(json!({"ref": "call-abc"}), session_id).unwrap();
1891
1892 assert!(result.success);
1893 let body: Value = serde_json::from_str(&result.content).unwrap();
1894 assert_eq!(body["mode"], "summary");
1895 assert!(body["signal_lines"].to_string().contains("error[E0425]"));
1896 assert!(body["signal_lines"].to_string().contains("warning"));
1897 }
1898
1899 #[test]
1900 fn adaptive_evidence_binary_bytes_are_exact_and_bounded() {
1901 let _spill = test_lock();
1902 let _artifact = codewhale_runtime::artifacts::TEST_ARTIFACT_SESSIONS_GUARD
1903 .lock()
1904 .unwrap_or_else(|err| err.into_inner());
1905 let tmp = tempdir().unwrap();
1906 let _root = set_spillover_root(tmp.path().join("tool_outputs"));
1907 let prior = codewhale_runtime::artifacts::set_test_artifact_sessions_root(Some(
1908 tmp.path().join("sessions"),
1909 ));
1910 struct Restore(Option<PathBuf>);
1911 impl Drop for Restore {
1912 fn drop(&mut self) {
1913 codewhale_runtime::artifacts::set_test_artifact_sessions_root(self.0.take());
1914 }
1915 }
1916 let _restore = Restore(prior);
1917 let bytes = b"\0\xffbinary\nDEEP_SENTINEL\x80tail";
1918 publish_test_evidence("session-a", "art_call-binary", bytes, false);
1919
1920 let result = execute_tool_in_session(
1921 json!({"ref": "art_call-binary", "mode": "bytes", "offset": 0, "length": 1024}),
1922 "session-a",
1923 )
1924 .unwrap();
1925 let body: Value = serde_json::from_str(&result.content).unwrap();
1926 use base64::Engine as _;
1927 let decoded = base64::engine::general_purpose::STANDARD
1928 .decode(body["data"].as_str().unwrap())
1929 .unwrap();
1930 assert_eq!(decoded, bytes);
1931 assert_eq!(body["total_bytes"], bytes.len());
1932 }
1933
1934 #[test]
1935 fn adaptive_evidence_retrieves_after_restart_without_memory_state() {
1936 let _spill = test_lock();
1937 let _artifact = codewhale_runtime::artifacts::TEST_ARTIFACT_SESSIONS_GUARD
1938 .lock()
1939 .unwrap_or_else(|err| err.into_inner());
1940 let tmp = tempdir().unwrap();
1941 let _root = set_spillover_root(tmp.path().join("tool_outputs"));
1942 let prior = codewhale_runtime::artifacts::set_test_artifact_sessions_root(Some(
1943 tmp.path().join("sessions"),
1944 ));
1945 struct Restore(Option<PathBuf>);
1946 impl Drop for Restore {
1947 fn drop(&mut self) {
1948 codewhale_runtime::artifacts::set_test_artifact_sessions_root(self.0.take());
1949 }
1950 }
1951 let _restore = Restore(prior);
1952
1953 let bytes = b"restart-proof\nDEEP_RESTART_SENTINEL\nend";
1954 publish_test_evidence("session-restart", "art_call-restart", bytes, false);
1955
1956 // Construct two independent contexts to model process teardown and
1957 // resume. Retrieval must depend only on the sealed session artifact
1958 // and metadata, never an in-memory routing table from publication.
1959 let first = execute_tool_in_session(
1960 json!({"ref": "art_call-restart", "mode": "metadata"}),
1961 "session-restart",
1962 )
1963 .unwrap();
1964 drop(first);
1965 let resumed = execute_tool_in_session(
1966 json!({"ref": "art_call-restart", "mode": "bytes", "length": 4096}),
1967 "session-restart",
1968 )
1969 .unwrap();
1970 let body: Value = serde_json::from_str(&resumed.content).unwrap();
1971 use base64::Engine as _;
1972 let decoded = base64::engine::general_purpose::STANDARD
1973 .decode(body["data"].as_str().unwrap())
1974 .unwrap();
1975 assert_eq!(decoded, bytes);
1976 assert_eq!(body["total_bytes"], bytes.len());
1977 }
1978
1979 #[test]
1980 fn adaptive_evidence_distinguishes_corrupt_expired_and_generation_mismatch() {
1981 let _spill = test_lock();
1982 let _artifact = codewhale_runtime::artifacts::TEST_ARTIFACT_SESSIONS_GUARD
1983 .lock()
1984 .unwrap_or_else(|err| err.into_inner());
1985 let tmp = tempdir().unwrap();
1986 let _root = set_spillover_root(tmp.path().join("tool_outputs"));
1987 let prior = codewhale_runtime::artifacts::set_test_artifact_sessions_root(Some(
1988 tmp.path().join("sessions"),
1989 ));
1990 struct Restore(Option<PathBuf>);
1991 impl Drop for Restore {
1992 fn drop(&mut self) {
1993 codewhale_runtime::artifacts::set_test_artifact_sessions_root(self.0.take());
1994 }
1995 }
1996 let _restore = Restore(prior);
1997
1998 publish_test_evidence("session-a", "art_call-expired", b"expired", true);
1999 let expired = execute_tool_in_session(json!({"ref": "art_call-expired"}), "session-a")
2000 .unwrap_err()
2001 .to_string();
2002 assert!(expired.contains("expired"), "{expired}");
2003
2004 let artifact = publish_test_evidence("session-a", "art_call-corrupt", b"original", false);
2005 let absolute = codewhale_runtime::artifacts::session_artifact_absolute_path(
2006 "session-a",
2007 &artifact.storage_path,
2008 )
2009 .unwrap();
2010 std::fs::write(absolute, b"changed").unwrap();
2011 let corrupt = execute_tool_in_session(json!({"ref": "art_call-corrupt"}), "session-a")
2012 .unwrap_err()
2013 .to_string();
2014 assert!(corrupt.contains("corrupt"), "{corrupt}");
2015
2016 publish_test_evidence("session-a", "art_call-generation", b"stable", false);
2017 let mismatch = execute_tool_in_session(
2018 json!({"ref": "art_call-generation", "generation": 2}),
2019 "session-a",
2020 )
2021 .unwrap_err()
2022 .to_string();
2023 assert!(mismatch.contains("generation"), "{mismatch}");
2024 }
2025
2026 #[test]
2027 fn query_returns_matching_line_with_context() {
2028 let _lock = test_lock();
2029 let tmp = tempdir().unwrap();
2030 let _guard = set_spillover_root(tmp.path().join("tool_outputs"));
2031 let session_id = "session-legacy-query";
2032 write_owned_legacy(
2033 "call-query",
2034 "one\ntwo before\nneedle here\nafter\nlast",
2035 session_id,
2036 );
2037
2038 let result = execute_tool_in_session(
2039 json!({
2040 "ref": "tool_result:call-query",
2041 "mode": "query",
2042 "query": "needle",
2043 "context_lines": 1
2044 }),
2045 session_id,
2046 )
2047 .unwrap();
2048
2049 let body: Value = serde_json::from_str(&result.content).unwrap();
2050 assert_eq!(body["matched_lines"], 1);
2051 let rendered = body["results"].to_string();
2052 assert!(rendered.contains("2: two before"));
2053 assert!(rendered.contains("3: needle here"));
2054 assert!(rendered.contains("4: after"));
2055 }
2056
2057 #[test]
2058 fn single_line_mcp_json_pages_by_segment_and_jsonpath() {
2059 let _lock = test_lock();
2060 let tmp = tempdir().unwrap();
2061 let _guard = set_spillover_root(tmp.path().join("tool_outputs"));
2062 let session_id = "session-legacy-json";
2063 let runs: Vec<Value> = (0..30)
2064 .map(|id| json!({"id": id, "conclusion": "success", "repository": {"description": "r".repeat(12_000)}}))
2065 .collect();
2066 let inner = json!({"total_count": 40_000, "workflow_runs": runs}).to_string();
2067 let envelope = json!({"content": [{"type": "text", "text": inner}]}).to_string();
2068 assert!(envelope.len() > 300_000 && !envelope.contains('\n'));
2069 write_owned_legacy("call-json", &envelope, session_id);
2070
2071 let summary_result =
2072 execute_tool_in_session(json!({"ref": "call-json", "mode": "summary"}), session_id)
2073 .unwrap();
2074 assert!(
2075 summary_result.content.len() <= DEFAULT_MAX_BYTES,
2076 "{}",
2077 summary_result.content.len()
2078 );
2079 let summary: Value = serde_json::from_str(&summary_result.content).unwrap();
2080 assert_eq!(summary["format"], "json", "{summary}");
2081 assert_eq!(summary["root_type"], "object", "{summary}");
2082 assert_eq!(summary["total_bytes"], envelope.len(), "{summary}");
2083 assert_eq!(summary["keys"]["content"]["type"], "array", "{summary}");
2084 assert_eq!(
2085 summary["keys"]["content"]["first_element"]["keys"]["text"]["keys"]["workflow_runs"]["length"],
2086 30,
2087 "{summary}"
2088 );
2089 assert!(
2090 summary["hint"].as_str().unwrap().contains("mode=\"json\""),
2091 "{summary}"
2092 );
2093 assert!(summary.get("head").is_none(), "{summary}");
2094 assert!(summary.get("tail").is_none(), "{summary}");
2095
2096 let head_res =
2097 execute_tool_in_session(json!({"ref": "call-json", "mode": "head"}), session_id)
2098 .unwrap();
2099 let head_body: Value = serde_json::from_str(&head_res.content).unwrap();
2100 assert!(
2101 head_body["total_lines"].as_u64().unwrap() > 100,
2102 "{head_body}"
2103 );
2104 assert_eq!(head_body["long_lines_split_at_bytes"], WRAP_LINE_BYTES);
2105
2106 let ids = execute_tool_in_session(
2107 json!({"ref": "call-json", "mode": "json", "jsonpath": "$.content[0].text.workflow_runs[*].id"}),
2108 session_id,
2109 )
2110 .unwrap();
2111 let ids: Value = serde_json::from_str(&ids.content).unwrap();
2112 assert_eq!(ids["matches"], 30);
2113 assert_eq!(ids["values"], json!((0..30).collect::<Vec<_>>()));
2114 assert_eq!(ids["truncated"], false);
2115
2116 let whole =
2117 execute_tool_in_session(json!({"ref": "call-json", "mode": "json"}), session_id)
2118 .unwrap();
2119 assert!(
2120 whole.content.len() < 2 * DEFAULT_MAX_BYTES,
2121 "{}",
2122 whole.content.len()
2123 );
2124 let whole: Value = serde_json::from_str(&whole.content).unwrap();
2125 assert_eq!(whole["truncated"], true);
2126 assert_eq!(
2127 whole["values"][0]["content"][0]["text"]["total_count"],
2128 40_000
2129 );
2130
2131 let large_runs: Vec<Value> = (0..1_050)
2132 .map(|id| json!({"id": id, "repository": {"description": "r".repeat(1_100)}}))
2133 .collect();
2134 let large_body = json!({"total_count": 1_050, "workflow_runs": large_runs}).to_string();
2135 assert!(large_body.len() > 1_100_000);
2136 write_owned_legacy("call-json-large", &large_body, session_id);
2137 let large_whole = execute_tool_in_session(
2138 json!({"ref": "call-json-large", "mode": "json"}),
2139 session_id,
2140 )
2141 .unwrap();
2142 let large_whole: Value = serde_json::from_str(&large_whole.content).unwrap();
2143 assert_eq!(large_whole["truncated"], true);
2144 assert_eq!(large_whole["values"][0]["total_count"], 1_050);
2145
2146 let capped = execute_tool_in_session(
2147 json!({"ref": "call-json-large", "mode": "json", "jsonpath": "$.workflow_runs[*].id"}),
2148 session_id,
2149 )
2150 .unwrap();
2151 let capped: Value = serde_json::from_str(&capped.content).unwrap();
2152 assert_eq!(capped["matches"], 1_024);
2153 assert_eq!(capped["truncated"], true);
2154 }
2155
2156 #[test]
2157 fn query_matches_needle_straddling_split_boundary() {
2158 let _lock = test_lock();
2159 let tmp = tempdir().unwrap();
2160 let _guard = set_spillover_root(tmp.path().join("tool_outputs"));
2161 let session_id = "session-query-straddle";
2162 let body = format!("{}NEEDLE_XYZ{}\n", "a".repeat(2_040), "b".repeat(3_000));
2163 write_owned_legacy("call-straddle", &body, session_id);
2164
2165 let out = execute_tool_in_session(
2166 json!({"ref": "call-straddle", "mode": "query", "query": "needle_xyz"}),
2167 session_id,
2168 )
2169 .unwrap();
2170 let out: Value = serde_json::from_str(&out.content).unwrap();
2171 assert_eq!(out["matched_lines"], 1, "{out}");
2172
2173 let long_query = format!("{}NEEDLE_XYZ{}", "a".repeat(1_500), "b".repeat(1_500));
2174 let long_out = execute_tool_in_session(
2175 json!({"ref": "call-straddle", "mode": "query", "query": long_query}),
2176 session_id,
2177 )
2178 .unwrap();
2179 let long_out: Value = serde_json::from_str(&long_out.content).unwrap();
2180 assert_eq!(long_out["matched_lines"], 1, "{long_out}");
2181 }
2182
2183 #[test]
2184 fn lines_mode_accepts_filename_inside_spillover_root() {
2185 let _lock = test_lock();
2186 let tmp = tempdir().unwrap();
2187 let root = tmp.path().join("tool_outputs");
2188 let _guard = set_spillover_root(root.clone());
2189 let session_id = "session-legacy-lines";
2190 write_owned_legacy("call-lines", "a\nb\nc\nd", session_id);
2191
2192 let result = execute_tool_in_session(
2193 json!({
2194 "ref": "call-lines.txt",
2195 "mode": "lines",
2196 "lines": "2-3"
2197 }),
2198 session_id,
2199 )
2200 .unwrap();
2201
2202 let body: Value = serde_json::from_str(&result.content).unwrap();
2203 let excerpt = body["excerpt"].as_str().unwrap();
2204 assert!(excerpt.contains("2: b"));
2205 assert!(excerpt.contains("3: c"));
2206 assert!(!excerpt.contains("1: a"));
2207 assert!(!excerpt.contains("4: d"));
2208 }
2209
2210 #[test]
2211 fn rejects_path_outside_spillover_root() {
2212 let _lock = test_lock();
2213 let tmp = tempdir().unwrap();
2214 let root = tmp.path().join("tool_outputs");
2215 fs::create_dir_all(&root).unwrap();
2216 let outside = tmp.path().join("outside.txt");
2217 fs::write(&outside, "secret").unwrap();
2218 let _guard = set_spillover_root(root);
2219
2220 let err = execute_tool(json!({"ref": outside.display().to_string()})).unwrap_err();
2221
2222 // Unauthorized is distinct but non-leaking: no outside path detail is
2223 // echoed beyond the caller-supplied ref.
2224 let msg = err.to_string();
2225 assert!(
2226 msg.contains("authorize") && msg.contains("active session"),
2227 "expected non-leaking authorization diagnostic, got: {msg}"
2228 );
2229 }
2230
2231 #[test]
2232 fn resolves_sha_reference_from_wire_dedup() {
2233 // A SHA-keyed lookup — emulates what happens when the model
2234 // sees a `<TOOL_RESULT_REF sha="..." />` block and passes the
2235 // SHA to retrieve_tool_result.
2236 let _lock = test_lock();
2237 let tmp = tempdir().unwrap();
2238 let _guard = set_spillover_root(tmp.path().join("tool_outputs"));
2239 let body = "checking crate ... error[E0425]: cannot find value\n".repeat(80);
2240 let session_id = "session-legacy-sha";
2241 let (sha, _) = write_owned_sha(&body, session_id);
2242
2243 // Form: `sha:<hex>`
2244 let result =
2245 execute_tool_in_session(json!({"ref": format!("sha:{sha}")}), session_id).unwrap();
2246 assert!(result.success, "sha:<hex> form should resolve");
2247
2248 // Form: bare 64-hex
2249 let result = execute_tool_in_session(json!({"ref": &sha}), session_id).unwrap();
2250 assert!(result.success, "bare 64-hex form should resolve");
2251 }
2252
2253 #[test]
2254 fn resolves_art_prefix_to_legacy_spillover_id() {
2255 // The model commonly sees `id: art_call_xyz` in artifact
2256 // ref blocks. retrieve_tool_result should strip the `art_`
2257 // prefix and find the legacy `<id>.txt` file if no
2258 // session-artifact equivalent exists.
2259 let _lock = test_lock();
2260 let tmp = tempdir().unwrap();
2261 let _guard = set_spillover_root(tmp.path().join("tool_outputs"));
2262 let session_id = "session-legacy-art-prefix";
2263 write_owned_legacy("call_xyz", "line1\nline2\nline3", session_id);
2264
2265 let result = execute_tool_in_session(json!({"ref": "art_call_xyz"}), session_id).unwrap();
2266 assert!(result.success, "art_ prefix should resolve to legacy id");
2267 }
2268
2269 #[test]
2270 fn unowned_and_foreign_legacy_spillovers_fail_closed_without_leaking_content() {
2271 let _lock = test_lock();
2272 let tmp = tempdir().unwrap();
2273 let _guard = set_spillover_root(tmp.path().join("tool_outputs"));
2274 let sentinel = "SESSION_A_PRIVATE_SENTINEL";
2275
2276 crate::tools::truncate::write_spillover("call-unowned", sentinel).unwrap();
2277 let unowned =
2278 execute_tool_in_session(json!({"ref": "call-unowned", "mode": "bytes"}), "session-b")
2279 .unwrap_err()
2280 .to_string();
2281 assert!(unowned.contains("no verifiable session owner"), "{unowned}");
2282 assert!(!unowned.contains(sentinel), "{unowned}");
2283 assert!(
2284 !unowned.contains(tmp.path().to_string_lossy().as_ref()),
2285 "{unowned}"
2286 );
2287
2288 write_owned_legacy("call-foreign", sentinel, "session-a");
2289 let foreign =
2290 execute_tool_in_session(json!({"ref": "call-foreign", "mode": "bytes"}), "session-b")
2291 .unwrap_err()
2292 .to_string();
2293 assert!(foreign.contains("another session"), "{foreign}");
2294 assert!(!foreign.contains(sentinel), "{foreign}");
2295 assert!(
2296 !foreign.contains(tmp.path().to_string_lossy().as_ref()),
2297 "{foreign}"
2298 );
2299 }
2300
2301 #[test]
2302 fn owned_legacy_digest_mismatch_is_distinct_from_unauthorized() {
2303 let _lock = test_lock();
2304 let tmp = tempdir().unwrap();
2305 let _guard = set_spillover_root(tmp.path().join("tool_outputs"));
2306 let path = write_owned_legacy("call-corrupt-owned", "original", "session-a");
2307 std::fs::write(path, "changed").unwrap();
2308
2309 let error = execute_tool_in_session(json!({"ref": "call-corrupt-owned"}), "session-a")
2310 .unwrap_err()
2311 .to_string();
2312 assert!(error.contains("content is corrupt"), "{error}");
2313 assert!(!error.contains("another session"), "{error}");
2314 }
2315
2316 #[test]
2317 fn not_found_error_lists_tried_candidates_and_accepted_forms() {
2318 let _lock = test_lock();
2319 let tmp = tempdir().unwrap();
2320 let _guard = set_spillover_root(tmp.path().join("tool_outputs"));
2321 fs::create_dir_all(tmp.path().join("tool_outputs")).unwrap();
2322
2323 let err = execute_tool(json!({"ref": "definitely_missing_id"})).unwrap_err();
2324 let msg = err.to_string();
2325 assert!(msg.contains("not found"), "got: {msg}");
2326 assert!(msg.contains("active session"), "got: {msg}");
2327 assert!(msg.contains("art_<id>"), "got: {msg}");
2328 assert!(!msg.contains("tool_outputs"), "storage root leaked: {msg}");
2329 assert!(
2330 !msg.contains(tmp.path().to_string_lossy().as_ref()),
2331 "path leaked: {msg}"
2332 );
2333 }
2334
2335 #[test]
2336 fn resolves_art_prefix_via_session_artifacts() {
2337 let _lock = test_lock();
2338 let tmp = tempdir().unwrap();
2339 let _spill_guard = set_spillover_root(tmp.path().join("tool_outputs"));
2340 let _art_guard = {
2341 let prior = codewhale_runtime::artifacts::set_test_artifact_sessions_root(Some(
2342 tmp.path().join("sessions"),
2343 ));
2344 scopeguard_for_test(prior)
2345 };
2346 let session_id = "session-abc";
2347 let body = "this is the canonical session artifact body, not a legacy file";
2348 codewhale_runtime::artifacts::write_session_artifact(session_id, "art_call_real", body)
2349 .unwrap();
2350
2351 let runtime = tokio::runtime::Builder::new_current_thread()
2352 .enable_all()
2353 .build()
2354 .unwrap();
2355 let workspace_tmp = tempdir().unwrap();
2356 let ctx = ToolContext::new(workspace_tmp.path()).with_state_namespace(session_id);
2357 let result = runtime
2358 .block_on(RetrieveToolResultTool.execute(json!({"ref": "art_call_real"}), &ctx))
2359 .expect("art_<id> should resolve via session artifacts");
2360 assert!(result.success);
2361 let payload: Value = serde_json::from_str(&result.content).unwrap();
2362 assert!(
2363 payload
2364 .to_string()
2365 .contains("canonical session artifact body"),
2366 "summary should pull from session artifact, got: {payload}"
2367 );
2368 }
2369
2370 #[cfg(unix)]
2371 #[test]
2372 fn rejects_symlink_inside_session_artifacts() {
2373 let _lock = test_lock();
2374 let tmp = tempdir().unwrap();
2375 let _spill_guard = set_spillover_root(tmp.path().join("tool_outputs"));
2376 let _art_guard = {
2377 let prior = codewhale_runtime::artifacts::set_test_artifact_sessions_root(Some(
2378 tmp.path().join("sessions"),
2379 ));
2380 scopeguard_for_test(prior)
2381 };
2382 let session_id = "session-xyz";
2383 // Plant a sensitive file outside the artifact dir.
2384 let secret = tmp.path().join("secret.txt");
2385 fs::write(&secret, "do not leak").unwrap();
2386 // Create the artifact dir, then drop a symlink inside it
2387 // pointing at the secret.
2388 let art_dir = tmp
2389 .path()
2390 .join("sessions")
2391 .join(session_id)
2392 .join("artifacts");
2393 fs::create_dir_all(&art_dir).unwrap();
2394 std::os::unix::fs::symlink(&secret, art_dir.join("art_evil.txt")).unwrap();
2395
2396 let runtime = tokio::runtime::Builder::new_current_thread()
2397 .enable_all()
2398 .build()
2399 .unwrap();
2400 let workspace_tmp = tempdir().unwrap();
2401 let ctx = ToolContext::new(workspace_tmp.path()).with_state_namespace(session_id);
2402 let result =
2403 runtime.block_on(RetrieveToolResultTool.execute(json!({"ref": "art_evil"}), &ctx));
2404 let err = result.expect_err("symlink artifact must not resolve");
2405 assert!(
2406 err.to_string().contains("not found"),
2407 "expected `not found`, got: {err}"
2408 );
2409 }
2410
2411 struct ArtifactRootGuard {
2412 prior: Option<PathBuf>,
2413 }
2414 impl Drop for ArtifactRootGuard {
2415 fn drop(&mut self) {
2416 codewhale_runtime::artifacts::set_test_artifact_sessions_root(self.prior.take());
2417 }
2418 }
2419 fn scopeguard_for_test(prior: Option<PathBuf>) -> ArtifactRootGuard {
2420 ArtifactRootGuard { prior }
2421 }
2422
2423 #[test]
2424 fn summary_returns_smart_json_schema_skipping_base64_and_distinct_text_tail() {
2425 let _lock = test_lock();
2426 let tmp = tempdir().unwrap();
2427 let _guard = set_spillover_root(tmp.path().join("tool_outputs"));
2428 let session_id = "session-smart-summary";
2429
2430 let fake_b64 = format!(
2431 "iVBORw0KGgoAAAANSUhEUgAA{}ErRoR{}FaIlEd{}",
2432 "AbCdEfGh01234567+/".repeat(400),
2433 "ZyXwVuTs98765432+/".repeat(400),
2434 "MnOpQrSt11223344=="
2435 );
2436 let json_doc = json!({
2437 "status": "ok",
2438 "count": 42,
2439 "items": [
2440 {"id": "a1", "title": "first"},
2441 {"id": "a2", "title": "second"}
2442 ],
2443 "screenshot_base64": fake_b64,
2444 })
2445 .to_string();
2446 assert!(!json_doc.contains('\n'));
2447 write_owned_legacy("call-b64-json", &json_doc, session_id);
2448
2449 let res = execute_tool_in_session(
2450 json!({"ref": "call-b64-json", "mode": "summary"}),
2451 session_id,
2452 )
2453 .unwrap();
2454 assert!(res.content.len() <= DEFAULT_MAX_BYTES);
2455 let body: Value = serde_json::from_str(&res.content).unwrap();
2456 assert_eq!(body["format"], "json");
2457 assert_eq!(body["root_type"], "object");
2458 assert_eq!(body["total_bytes"], json_doc.len());
2459 assert_eq!(body["key_count"], 4);
2460 assert_eq!(body["keys"]["status"]["preview"], "ok");
2461 assert_eq!(body["keys"]["count"]["preview"], 42);
2462 assert_eq!(body["keys"]["items"]["type"], "array");
2463 assert_eq!(body["keys"]["items"]["length"], 2);
2464 assert_eq!(body["keys"]["screenshot_base64"]["format"], "base64");
2465 assert!(
2466 !res.content.contains("iVBORw0KGgo"),
2467 "base64 payload leaked into summary: {}",
2468 res.content
2469 );
2470 assert!(body.get("signal_lines").is_none());
2471 let hint = body["hint"].as_str().unwrap();
2472 assert!(hint.contains("mode=\"json\""), "{hint}");
2473 assert!(
2474 body["suggested_queries"]
2475 .as_array()
2476 .unwrap()
2477 .iter()
2478 .any(|q| q.as_str().is_some_and(|s| s.starts_with("$.items"))),
2479 "{body}"
2480 );
2481
2482 let array_doc = json!([{"id": 1, "name": "alpha"}, {"id": 2, "name": "beta"}]).to_string();
2483 write_owned_legacy("call-array-json", &array_doc, session_id);
2484 let arr_res = execute_tool_in_session(
2485 json!({"ref": "call-array-json", "mode": "summary"}),
2486 session_id,
2487 )
2488 .unwrap();
2489 let arr_body: Value = serde_json::from_str(&arr_res.content).unwrap();
2490 assert_eq!(arr_body["root_type"], "array");
2491 assert_eq!(arr_body["length"], 2);
2492 assert!(
2493 arr_body["suggested_queries"]
2494 .as_array()
2495 .unwrap()
2496 .contains(&json!("$[0]")),
2497 "{arr_body}"
2498 );
2499
2500 let long_non_json = format!(
2501 "HEAD_START_{}_MIDDLE_{}_TAIL_END",
2502 "x".repeat(4_000),
2503 "y".repeat(12_000)
2504 );
2505 assert!(!long_non_json.contains('\n'));
2506 write_owned_legacy("call-long-text", &long_non_json, session_id);
2507 let text_res = execute_tool_in_session(
2508 json!({"ref": "call-long-text", "mode": "summary"}),
2509 session_id,
2510 )
2511 .unwrap();
2512 let text_body: Value = serde_json::from_str(&text_res.content).unwrap();
2513 let head = text_body["head"].as_str().unwrap();
2514 let tail = text_body["tail"].as_str().unwrap();
2515 assert!(head.contains("HEAD_START_"), "{head}");
2516 assert!(!head.contains("TAIL_END"), "{head}");
2517 assert!(tail.contains("TAIL_END"), "{tail}");
2518 assert!(!tail.contains("HEAD_START_"), "{tail}");
2519 assert_ne!(head, tail);
2520 }
2521 }
2522
2522 lines RUST