返回 CodeWhale
adaptive_evidence_acceptance.rs
根目录 / crates / tui / tests / integration / adaptive_evidence_acceptance.rs
1 //! Process-level acceptance for adaptive exact-evidence routing (#4619).
2
3 use std::io::Read;
4 use std::path::{Path, PathBuf};
5 use std::process::{Command, Stdio};
6 use std::sync::Arc;
7 use std::sync::atomic::{AtomicUsize, Ordering};
8 use std::time::Duration;
9
10 use serde_json::{Value, json};
11 use sha2::{Digest, Sha256};
12 use tempfile::TempDir;
13 use wait_timeout::ChildExt;
14 use wiremock::matchers::{method, path};
15 use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate};
16
17 const MODEL: &str = "adaptive-evidence-test";
18 const SUCCESS_CALL_ID: &str = "call_bash_success";
19 const FAILURE_CALL_ID: &str = "call_bash_failure";
20 const RETRIEVE_CALL_ID: &str = "call_retrieve_omitted_range";
21 const SUCCESS_SENTINEL: &str = "DEEP_SUCCESS_EVIDENCE_SENTINEL_4619";
22 const FAILURE_SENTINEL: &str = "DEEP_FAILURE_EVIDENCE_SENTINEL_4619";
23 const BASH_STEP_TIMEOUT_SECS: u64 = 30;
24
25 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
26 async fn headless_bash_success_and_failure_are_distinct_bounded_exact_evidence() {
27 let workspace = TempDir::new().expect("workspace");
28 let home = TempDir::new().expect("home");
29
30 let server = mock_llm().await;
31 let output = run_exec(workspace.path(), home.path(), &server);
32 assert!(
33 output.status.success(),
34 "exec failed\nstdout:\n{}\nstderr:\n{}",
35 String::from_utf8_lossy(&output.stdout),
36 String::from_utf8_lossy(&output.stderr)
37 );
38 let events: Vec<Value> = std::str::from_utf8(&output.stdout)
39 .expect("UTF-8 stream events")
40 .lines()
41 .filter(|line| !line.trim().is_empty())
42 .map(|line| serde_json::from_str(line).expect("valid stream event"))
43 .collect();
44
45 let requests = server.received_requests().await.expect("recorded requests");
46 let success_receipt =
47 receipt_for(&requests, SUCCESS_CALL_ID).expect("model-visible Bash success receipt");
48 let failure_receipt =
49 receipt_for(&requests, FAILURE_CALL_ID).expect("model-visible Bash failure receipt");
50 for (outcome, receipt, sentinel) in [
51 ("success", &success_receipt, SUCCESS_SENTINEL),
52 ("failure", &failure_receipt, FAILURE_SENTINEL),
53 ] {
54 let has_truncate_footer = receipt.contains("of output omitted")
55 && receipt.contains("full output at")
56 && receipt.replace('\\', "/").contains("/artifacts/");
57 let has_shell_artifact_footer = receipt.contains("saved as artifact art_");
58 assert!(
59 has_truncate_footer || has_shell_artifact_footer,
60 "the {outcome} receipt must state how much was omitted or name its saved artifact ({} bytes, starts with {:?})",
61 receipt.len(),
62 receipt.chars().take(180).collect::<String>()
63 );
64 // The receipt must name a route the model can take *from this
65 // receipt*. It previously asserted the opposite — that the footer must
66 // NOT name `retrieve_tool_result` — which came from #5018's
67 // "no storage language" pass, not from any shell-vs-tool-result
68 // distinction: #4619 shipped the footer naming
69 // `retrieve_tool_result ref=art_<call>`, #5018 replaced the whole
70 // recovery line with "view full output in the tool details view" (a
71 // view the model cannot open) and froze that removal as a negative
72 // assertion, and #5212 restored the artifact path but left the stale
73 // negative in place. The follow-up probe below settles it empirically
74 // for *this* receipt: the scripted model reads the ref out of the
75 // receipt text it was handed, calls `retrieve_tool_result` with it,
76 // and gets back the exact line the receipt omitted.
77 assert!(
78 receipt.contains("retrieve_tool_result"),
79 "the footer must name the recovery route the model can actually take"
80 );
81 assert!(!receipt.contains("[Exact evidence retained"));
82 assert!(!receipt.contains(sentinel));
83 assert!(
84 receipt.len() <= 42_000,
85 "bounded preview must stay within the hybrid 32 KiB head + 8 KiB tail receipt budget, got {} bytes",
86 receipt.len()
87 );
88 }
89 assert_ne!(success_receipt, failure_receipt);
90
91 // The model followed the `ref=` the failure receipt named and got the byte
92 // range the receipt omitted. The mock parsed that ref out of the receipt
93 // text itself, so this only passes when the footer hands over a ref the
94 // retrieval tool can resolve in the origin session.
95 let retrieve_receipt = receipt_for(&requests, RETRIEVE_CALL_ID)
96 .expect("model-visible retrieve_tool_result receipt");
97 assert!(
98 retrieve_receipt.contains(FAILURE_SENTINEL),
99 "retrieve_tool_result must return the range the receipt omitted, got: {retrieve_receipt}"
100 );
101
102 let artifact_dir = find_artifact_dir(home.path()).expect("origin-session artifacts");
103 let payloads = std::fs::read_dir(&artifact_dir)
104 .expect("artifact directory")
105 .filter_map(Result::ok)
106 .map(|entry| entry.path())
107 .filter(|path| path.extension().and_then(|ext| ext.to_str()) == Some("txt"))
108 .count();
109 assert_eq!(payloads, 2, "exactly one evidence payload per result");
110
111 assert_ne!(
112 quoted_after(&success_receipt, "ref=\""),
113 quoted_after(&failure_receipt, "ref=\""),
114 "separate executions retain separate evidence handles"
115 );
116 let success = assert_exact_artifact(
117 &artifact_dir,
118 SUCCESS_CALL_ID,
119 &success_receipt,
120 &events,
121 SUCCESS_SENTINEL,
122 "success",
123 );
124 let failure = assert_exact_artifact(
125 &artifact_dir,
126 FAILURE_CALL_ID,
127 &failure_receipt,
128 &events,
129 FAILURE_SENTINEL,
130 "error",
131 );
132 assert_ne!(
133 success, failure,
134 "success and failure bytes must stay distinct"
135 );
136 }
137
138 fn assert_exact_artifact(
139 artifact_dir: &Path,
140 provider_id: &str,
141 receipt: &str,
142 events: &[Value],
143 sentinel: &str,
144 status: &str,
145 ) -> Vec<u8> {
146 let handle = quoted_after(receipt, "ref=\"").expect("model-visible artifact handle");
147 let result = events
148 .iter()
149 .find(|event| {
150 event["type"] == "tool_result"
151 && event["artifact"]["artifact_id"].as_str() == Some(handle)
152 })
153 .expect("stream result for the model-visible artifact");
154 let exec_id = result["id"].as_str().expect("host execution id");
155 uuid::Uuid::parse_str(exec_id).expect("artifact belongs to a host execution");
156 assert_ne!(exec_id, provider_id);
157 for kind in ["tool_use", "tool_result"] {
158 let matching = events
159 .iter()
160 .filter(|event| event["type"] == kind && event["id"] == exec_id)
161 .collect::<Vec<_>>();
162 assert_eq!(matching.len(), 1, "one {kind} for this exact execution");
163 let event = matching[0];
164 assert_eq!(event["name"], "bash");
165 if kind == "tool_use" {
166 assert!(
167 event["input"]["command"]
168 .as_str()
169 .unwrap()
170 .contains(sentinel)
171 );
172 } else {
173 let stream_output = event["output"].as_str().expect("stream output");
174 assert_eq!(quoted_after(stream_output, "ref=\""), Some(handle));
175 assert!(!stream_output.contains(sentinel));
176 let row = receipt
177 .lines()
178 .find(|line| {
179 line.starts_with("BASH-")
180 && line.contains("-ERR-")
181 && line.ends_with("xxxxxxxx")
182 })
183 .expect("a retained stderr line");
184 assert!(stream_output.contains(row));
185 assert_eq!(event["truncated"], true);
186 assert_eq!(
187 event["result_metadata"]["artifact_origin_tool_call_id"],
188 exec_id
189 );
190 assert_eq!(event["status"], status);
191 }
192 }
193 let exact =
194 std::fs::read(artifact_dir.join(format!("{handle}.txt"))).expect("exact evidence bytes");
195 assert!(
196 String::from_utf8_lossy(&exact).contains(sentinel),
197 "deep content omitted from context must remain retrievable"
198 );
199 let metadata: Value = serde_json::from_slice(
200 &std::fs::read(artifact_dir.join(format!("{handle}.evidence.json")))
201 .expect("evidence metadata"),
202 )
203 .expect("valid evidence metadata");
204 let digest = Sha256::digest(&exact)
205 .iter()
206 .map(|byte| format!("{byte:02x}"))
207 .collect::<String>();
208 assert_eq!(metadata["handle"], handle);
209 assert_eq!(metadata["call_id"], exec_id);
210 assert_eq!(
211 result["artifact"]["content_digest"],
212 format!("sha256:{digest}")
213 );
214 assert_eq!(result["artifact"]["artifact_byte_size"], exact.len() as u64);
215 assert_eq!(metadata["tool_name"], "bash");
216 assert_eq!(metadata["digest"], digest);
217 assert_eq!(metadata["size_bytes"], exact.len() as u64);
218 assert_eq!(metadata["generation"], 1);
219 assert_eq!(metadata["redacted"], false);
220 assert_eq!(metadata["encoding"], "utf-8");
221 assert_eq!(metadata["retention_state"], "live");
222 assert_eq!(
223 metadata["origin_session"].as_str(),
224 artifact_dir.parent().unwrap().file_name().unwrap().to_str()
225 );
226 exact
227 }
228
229 async fn mock_llm() -> MockServer {
230 let server = MockServer::start().await;
231 Mock::given(method("GET"))
232 .and(path("/v1/models"))
233 .respond_with(json_response(json!({
234 "object": "list",
235 "data": [{"id": MODEL, "object": "model"}]
236 })))
237 .mount(&server)
238 .await;
239 Mock::given(method("POST"))
240 .and(path("/v1/chat/completions"))
241 .respond_with(EvidenceScenario {
242 requests: Arc::new(AtomicUsize::new(0)),
243 })
244 .mount(&server)
245 .await;
246 server
247 }
248
249 #[derive(Clone)]
250 struct EvidenceScenario {
251 requests: Arc<AtomicUsize>,
252 }
253
254 /// Scripted four-turn scenario. Turn 3 is the empirical half of the design
255 /// question this test settles: rather than asserting from the outside which
256 /// recovery route a Bash receipt *should* name, the scripted model reads the
257 /// route out of the receipt it was actually handed and takes it, so the
258 /// assertion in the test body observes whether that route returns the bytes
259 /// the receipt omitted.
260 impl Respond for EvidenceScenario {
261 fn respond(&self, request: &Request) -> ResponseTemplate {
262 let sequence = self.requests.fetch_add(1, Ordering::SeqCst);
263 let body = request.body_json::<Value>().unwrap_or(Value::Null);
264 let response = match sequence {
265 0 => bash_tool_sse(SUCCESS_CALL_ID, true),
266 1 => bash_tool_sse(FAILURE_CALL_ID, false),
267 2 => {
268 let receipt = tool_result_content_for(&body, FAILURE_CALL_ID)
269 .expect("Bash failure receipt on the third request");
270 let reference = quoted_after(receipt, "ref=\"")
271 .expect("failure receipt must hand over a retrieval ref");
272 retrieve_tool_sse(reference, FAILURE_SENTINEL)
273 }
274 _ => final_sse(),
275 };
276 assert!(
277 sequence < 4,
278 "unexpected extra model request #{sequence}: {body}"
279 );
280 sse_response(response)
281 }
282 }
283
284 /// Read the recovery ref the truncation footer hands the model, e.g. the
285 /// `art_<execution-id>` inside `… call retrieve_tool_result with ref="…"`.
286 fn quoted_after<'a>(receipt: &'a str, marker: &str) -> Option<&'a str> {
287 let rest = &receipt[receipt.find(marker)? + marker.len()..];
288 rest.get(..rest.find('"')?)
289 }
290
291 fn run_exec(workspace: &Path, home: &Path, server: &MockServer) -> std::process::Output {
292 std::fs::create_dir_all(home.join(".codewhale")).expect("config directory");
293 std::fs::create_dir_all(home.join(".deepseek")).expect("legacy config directory");
294 std::fs::write(
295 home.join(".codewhale/config.toml"),
296 "allow_shell = true\n\n[retry]\nenabled = false\n",
297 )
298 .expect("headless test config");
299 let mut command = Command::new(crate::binary::codewhale());
300 preserve_host_env(&mut command);
301 command
302 .current_dir(workspace)
303 .args(["--workspace", workspace.to_str().expect("workspace utf8")])
304 .arg("--no-project-config")
305 .args([
306 "exec",
307 "--auto",
308 "--model",
309 MODEL,
310 "--output-format",
311 "stream-json",
312 ])
313 .arg("run both provider-fixtured Bash evidence probes")
314 .env("HOME", home)
315 .env("USERPROFILE", home)
316 .env("XDG_CONFIG_HOME", home.join(".config"))
317 .env("XDG_DATA_HOME", home.join(".local/share"))
318 .env("XDG_CACHE_HOME", home.join(".cache"))
319 .env("CODEWHALE_CONFIG_PATH", home.join(".codewhale/config.toml"))
320 .env("DEEPSEEK_CONFIG_PATH", home.join(".deepseek/config.toml"))
321 .env("DEEPSEEK_API_KEY", "ci-test-key-not-real")
322 .env("DEEPSEEK_BASE_URL", server.uri())
323 .env("CODEWHALE_BASE_URL", server.uri())
324 .env("DEEPSEEK_MODEL", MODEL)
325 .env("CODEWHALE_MODEL", MODEL)
326 // The adaptive evidence lane is an explicit opt-in; this test exists
327 // to prove it end to end, so the spawned binary runs opted in.
328 .env("CODEWHALE_ADAPTIVE_OUTPUT_ROUTING", "1")
329 .env("RUST_LOG", "warn")
330 .stdout(Stdio::piped())
331 .stderr(Stdio::piped());
332 run_with_timeout(
333 command,
334 Duration::from_secs(2 * BASH_STEP_TIMEOUT_SECS + 15),
335 )
336 }
337
338 fn find_artifact_dir(home: &Path) -> Option<PathBuf> {
339 let sessions = home.join(".codewhale/sessions");
340 std::fs::read_dir(sessions)
341 .ok()?
342 .filter_map(Result::ok)
343 .find_map(|entry| {
344 let path = entry.path().join("artifacts");
345 path.is_dir().then_some(path)
346 })
347 }
348
349 fn receipt_for(requests: &[Request], call_id: &str) -> Option<String> {
350 requests
351 .iter()
352 .filter_map(|request| request.body_json::<Value>().ok())
353 .find_map(|body| tool_result_content_for(&body, call_id).map(str::to_owned))
354 }
355
356 fn tool_result_content_for<'a>(body: &'a Value, call_id: &str) -> Option<&'a str> {
357 body.get("messages")?
358 .as_array()?
359 .iter()
360 .find(|message| {
361 message.get("role").and_then(Value::as_str) == Some("tool")
362 && message.get("tool_call_id").and_then(Value::as_str) == Some(call_id)
363 })?
364 .get("content")?
365 .as_str()
366 }
367
368 fn bash_tool_sse(call_id: &str, success: bool) -> String {
369 let (sentinel, prefix) = if success {
370 (SUCCESS_SENTINEL, "BASH-SUCCESS")
371 } else {
372 (FAILURE_SENTINEL, "BASH-FAILURE")
373 };
374 let command = probe_command(sentinel, prefix, success);
375 tool_call_sse(
376 call_id,
377 "bash",
378 &json!({"command": command, "timeout": BASH_STEP_TIMEOUT_SECS}),
379 )
380 }
381
382 /// Take the recovery route the receipt named, asking for the omitted range by
383 /// the sentinel that rides in it.
384 fn retrieve_tool_sse(reference: &str, query: &str) -> String {
385 tool_call_sse(
386 RETRIEVE_CALL_ID,
387 "retrieve_tool_result",
388 &json!({"ref": reference, "mode": "query", "query": query}),
389 )
390 }
391
392 fn tool_call_sse(call_id: &str, name: &str, arguments: &Value) -> String {
393 let arguments = serde_json::to_string(arguments).expect("tool arguments");
394 [
395 chunk(json!({"id":"tool","object":"chat.completion.chunk","model":MODEL,"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":call_id,"type":"function","function":{"name":name,"arguments":arguments}}]},"finish_reason":null}]})),
396 chunk(json!({"id":"tool","object":"chat.completion.chunk","model":MODEL,"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":10,"completion_tokens":2,"total_tokens":12}})),
397 "data: [DONE]\n\n".to_string(),
398 ].join("")
399 }
400
401 const SENTINEL_LINE: usize = 50;
402
403 #[cfg(not(windows))]
404 fn probe_command(sentinel: &str, prefix: &str, success: bool) -> String {
405 let trailer = if success { "" } else { "; exit 7" };
406 let stdout_loop = format!(
407 "i=0; while [ \"$i\" -lt 2800 ]; do printf '{prefix}-%04d-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\\n' \"$i\"; i=$((i + 1)); done"
408 );
409 let stderr_loop = format!(
410 "j=0; while [ \"$j\" -lt 2800 ]; do if [ \"$j\" -eq {SENTINEL_LINE} ]; then printf '%s\\n' '{sentinel}'; fi; printf '{prefix}-ERR-%04d-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\\n' \"$j\"; j=$((j + 1)); done"
411 );
412 format!("{stdout_loop}; {{ {stderr_loop}; }} >&2{trailer}")
413 }
414
415 /// PowerShell syntax: on Windows the shell dispatcher prefers `pwsh.exe`,
416 /// then in-box `powershell.exe`, only falling back to `cmd.exe` when no
417 /// PowerShell exists at all. Single quotes only — the payload is passed to
418 /// `-Command` as one argv string, and four or more double quotes would push
419 /// it onto the temp-`-File` path for no benefit. The failure variant mirrors
420 /// the Unix `{ ...; } >&2; exit 7` shape by writing every line to the OS
421 /// stderr handle and exiting 7 after the loop.
422 #[cfg(windows)]
423 fn probe_command(sentinel: &str, prefix: &str, success: bool) -> String {
424 let stdout_line = format!(
425 "'{prefix}-{{0}}-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'"
426 );
427 let stderr_line = format!(
428 "'{prefix}-ERR-{{0}}-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'"
429 );
430 let trailer = if success { "" } else { "; exit 7" };
431 format!(
432 "$out = [Text.StringBuilder]::new(); $err = [Text.StringBuilder]::new(); \
433 for ($i = 0; $i -lt 2800; $i++) {{ \
434 [void]$out.AppendLine(({stdout_line} -f $i)); \
435 if ($i -eq {SENTINEL_LINE}) {{ [void]$err.AppendLine('{sentinel}') }}; \
436 [void]$err.AppendLine(({stderr_line} -f $i)) \
437 }}; [Console]::Out.Write($out.ToString()); [Console]::Error.Write($err.ToString()){trailer}"
438 )
439 }
440
441 fn final_sse() -> String {
442 [
443 chunk(json!({"id":"final","object":"chat.completion.chunk","model":MODEL,"choices":[{"index":0,"delta":{"content":"evidence retained"},"finish_reason":null}]})),
444 chunk(json!({"id":"final","object":"chat.completion.chunk","model":MODEL,"choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":20,"completion_tokens":2,"total_tokens":22}})),
445 "data: [DONE]\n\n".to_string(),
446 ].join("")
447 }
448
449 fn chunk(value: Value) -> String {
450 format!(
451 "data: {}\n\n",
452 serde_json::to_string(&value).expect("SSE JSON")
453 )
454 }
455
456 fn sse_response(body: String) -> ResponseTemplate {
457 ResponseTemplate::new(200)
458 .insert_header("content-type", "text/event-stream")
459 .set_body_string(body)
460 }
461
462 fn json_response(value: Value) -> ResponseTemplate {
463 ResponseTemplate::new(200).set_body_json(value)
464 }
465
466 fn preserve_host_env(command: &mut Command) {
467 command.env_clear();
468 for key in [
469 "PATH",
470 "PATHEXT",
471 "SystemRoot",
472 "SystemDrive",
473 "WINDIR",
474 "COMSPEC",
475 "TEMP",
476 "TMP",
477 "TERM",
478 "LANG",
479 "LC_ALL",
480 ] {
481 if let Some(value) = std::env::var_os(key) {
482 command.env(key, value);
483 }
484 }
485 }
486
487 fn run_with_timeout(mut command: Command, timeout: Duration) -> std::process::Output {
488 let mut child = command.spawn().expect("spawn codewhale exec");
489 let stdout = read_in_background(child.stdout.take().expect("stdout"));
490 let stderr = read_in_background(child.stderr.take().expect("stderr"));
491 let status = child.wait_timeout(timeout).expect("wait");
492 if status.is_none() {
493 let _ = child.kill();
494 let _ = child.wait();
495 }
496 let stdout = stdout.join().expect("stdout thread").expect("read stdout");
497 let stderr = stderr.join().expect("stderr thread").expect("read stderr");
498 let status = status.unwrap_or_else(|| {
499 panic!(
500 "codewhale exec timed out after {timeout:?}\nstdout:\n{}\nstderr:\n{}",
501 String::from_utf8_lossy(&stdout),
502 String::from_utf8_lossy(&stderr)
503 )
504 });
505 std::process::Output {
506 status,
507 stdout,
508 stderr,
509 }
510 }
511
512 fn read_in_background<R: Read + Send + 'static>(
513 mut reader: R,
514 ) -> std::thread::JoinHandle<std::io::Result<Vec<u8>>> {
515 std::thread::spawn(move || {
516 let mut bytes = Vec::new();
517 reader.read_to_end(&mut bytes).map(|_| bytes)
518 })
519 }
520
520 lines RUST