| 1 | use super::tests::{chat_fixture_response, make_worker_spec, stub_runtime}; |
| 2 | use super::*; |
| 3 | use axum::{Json, Router, http::StatusCode, response::IntoResponse, routing::post}; |
| 4 | use tempfile::{TempDir, tempdir}; |
| 5 | use tokio::sync::Notify; |
| 6 | |
| 7 | const SCOUT_READS: usize = 26; |
| 8 | |
| 9 | struct Fixture { |
| 10 | _workspace: TempDir, |
| 11 | manager: SharedSubAgentManager, |
| 12 | task: Option<JoinHandle<()>>, |
| 13 | server: JoinHandle<()>, |
| 14 | requests: Arc<std::sync::Mutex<Vec<Value>>>, |
| 15 | request_count: tokio::sync::watch::Receiver<usize>, |
| 16 | report_started: Arc<Notify>, |
| 17 | release_report: Arc<Notify>, |
| 18 | cancel: CancellationToken, |
| 19 | completions: mpsc::Receiver<SubAgentCompletion>, |
| 20 | mailbox: MailboxReceiver, |
| 21 | } |
| 22 | |
| 23 | impl Fixture { |
| 24 | async fn finish(&mut self) -> SubAgentResult { |
| 25 | tokio::time::timeout(Duration::from_secs(30), self.task.take().unwrap()) |
| 26 | .await |
| 27 | .expect("bounded worker") |
| 28 | .expect("worker task"); |
| 29 | self.manager |
| 30 | .read() |
| 31 | .await |
| 32 | .get_result("report-worker") |
| 33 | .unwrap() |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | impl Drop for Fixture { |
| 38 | fn drop(&mut self) { |
| 39 | if let Some(task) = &self.task { |
| 40 | task.abort(); |
| 41 | } |
| 42 | self.server.abort(); |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | async fn fixture(mode: &'static str, first_tokens: u64, max_steps: u32) -> Fixture { |
| 47 | // Only these cases exercise wall/API timeouts. The other cases exercise |
| 48 | // budget and report semantics, so leave room for full-suite scheduling. |
| 49 | let timeout_case = matches!(mode, "timeout" | "work-timeout"); |
| 50 | let wall_time_secs = if mode == "timeout" { 5 } else { 30 }; |
| 51 | let workspace = tempdir().unwrap(); |
| 52 | fs::write( |
| 53 | workspace.path().join("README.md"), |
| 54 | "TOOL_EVIDENCE: checksum validation is still missing.\n", |
| 55 | ) |
| 56 | .unwrap(); |
| 57 | if mode == "uncapped-scout" { |
| 58 | for part in 1..=SCOUT_READS { |
| 59 | fs::write( |
| 60 | workspace.path().join(format!("part-{part}.md")), |
| 61 | format!("checked part {part}"), |
| 62 | ) |
| 63 | .unwrap(); |
| 64 | } |
| 65 | } |
| 66 | let requests = Arc::new(std::sync::Mutex::new(Vec::new())); |
| 67 | let (request_progress, request_count) = tokio::sync::watch::channel(0); |
| 68 | let report_started = Arc::new(Notify::new()); |
| 69 | let release_report = Arc::new(Notify::new()); |
| 70 | let app = Router::new().route("/{*path}", post({ |
| 71 | let requests = Arc::clone(&requests); |
| 72 | let report_started = Arc::clone(&report_started); |
| 73 | let release_report = Arc::clone(&release_report); |
| 74 | move |Json(body): Json<Value>| { |
| 75 | let requests = Arc::clone(&requests); |
| 76 | let request_progress = request_progress.clone(); |
| 77 | let report_started = Arc::clone(&report_started); |
| 78 | let release_report = Arc::clone(&release_report); |
| 79 | async move { |
| 80 | let call = { |
| 81 | let mut requests = requests.lock().unwrap(); |
| 82 | requests.push(body.clone()); |
| 83 | requests.len() |
| 84 | }; |
| 85 | request_progress.send_replace(call); |
| 86 | let choice = if call == 1 || mode == "tool-only" || (mode == "uncapped-scout" && call <= SCOUT_READS) { |
| 87 | let path = if mode == "uncapped-scout" { format!("part-{call}.md") } else { "README.md".to_string() }; |
| 88 | let content = match mode { |
| 89 | "tool-only" => Value::Null, |
| 90 | "truncated" => json!(format!("RECORDED_FINDING{}TAIL", "界".repeat(4_000))), |
| 91 | _ => json!("RECORDED_FINDING: checksum validation is missing."), |
| 92 | }; |
| 93 | json!({"index": 0, "message": {"role": "assistant", |
| 94 | "content": content, |
| 95 | "tool_calls": [{"id": format!("read-{call}"), "type": "function", "function": { |
| 96 | "name": "read", "arguments": json!({"path": path}).to_string() |
| 97 | }}]}, "finish_reason": "tool_calls"}) |
| 98 | } else { |
| 99 | report_started.notify_one(); |
| 100 | if matches!(mode, "hold" | "timeout" | "work-timeout") { release_report.notified().await; } |
| 101 | if mode == "failure" { |
| 102 | return (StatusCode::BAD_REQUEST, Json(json!({"error": {"message": "fixture rejection"}}))).into_response(); |
| 103 | } |
| 104 | if mode == "tool" { |
| 105 | json!({"index": 0, "message": {"role": "assistant", "content": "REJECTED_REPORT: I wrote report.md.", |
| 106 | "tool_calls": [{"id": "must-not-write", "type": "function", "function": { |
| 107 | "name": "write_file", "arguments": "{\"path\":\"report.md\",\"content\":\"must not execute\"}" |
| 108 | }}]}, "finish_reason": "tool_calls"}) |
| 109 | } else if mode == "truncated" { |
| 110 | json!({"index": 0, "message": {"role": "assistant", "content": "TRUNCATED_REPORT: README evid"}, "finish_reason": "length"}) |
| 111 | } else { |
| 112 | json!({"index": 0, "message": {"role": "assistant", "content": |
| 113 | "PARTIAL_REPORT: README evidence identifies missing checksum validation. No report file was produced. Next: implement and verify the checksum check."}, "finish_reason": "stop"}) |
| 114 | } |
| 115 | }; |
| 116 | let usage = if (call == 1 && matches!(mode, "unknown" | "resume-unknown")) || (call > 1 && mode == "report-unknown") { Value::Null } |
| 117 | else if call == 1 { json!({"prompt_tokens": first_tokens.saturating_sub(5), "completion_tokens": 5, "total_tokens": first_tokens}) } |
| 118 | else if mode == "resume-unknown" { json!({"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}) } |
| 119 | else { json!({"prompt_tokens": 20, "completion_tokens": 10, "total_tokens": 30}) }; |
| 120 | chat_fixture_response(body.get("stream").and_then(Value::as_bool).unwrap_or(false), json!({"id": format!("handback-{call}"), "model": "deepseek-v4-flash", "choices": [choice], "usage": usage})).into_response() |
| 121 | } |
| 122 | } |
| 123 | })); |
| 124 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 125 | let address = listener.local_addr().unwrap(); |
| 126 | let server = tokio::spawn(async move { |
| 127 | axum::serve(listener, app).await.unwrap(); |
| 128 | }); |
| 129 | let config = { |
| 130 | let __cw_config_init_0_0 = Some(codewhale_runtime::config::RetryConfig { |
| 131 | enabled: Some(false), |
| 132 | max_retries: Some(0), |
| 133 | initial_delay: Some(0.0), |
| 134 | max_delay: Some(0.0), |
| 135 | exponential_base: Some(1.0), |
| 136 | jitter: None, |
| 137 | jitter_factor: None, |
| 138 | respect_retry_after: None, |
| 139 | rate_limit: Default::default(), |
| 140 | }); |
| 141 | let mut __cw_config_init_0_value: codewhale_runtime::config::Config = Default::default(); |
| 142 | __cw_config_init_0_value.retry = __cw_config_init_0_0; |
| 143 | __cw_config_init_0_value |
| 144 | } |
| 145 | .with_legacy_root( |
| 146 | Some("fixture-key".to_string()), |
| 147 | Some(format!("http://{address}/v1")), |
| 148 | ); |
| 149 | let manager = Arc::new(RwLock::new( |
| 150 | SubAgentManager::new(workspace.path().to_path_buf(), 4) |
| 151 | .with_state_path(workspace.path().join(".codewhale/subagents/state.json")), |
| 152 | )); |
| 153 | let mut spec = make_worker_spec("report-worker", workspace.path().to_path_buf()); |
| 154 | spec.max_steps = max_steps; |
| 155 | spec.runtime_profile.max_steps = max_steps; |
| 156 | spec.runtime_profile.wall_time_secs = Some(wall_time_secs); |
| 157 | spec.runtime_profile.wall_deadline_ms = Some(epoch_millis_now() + wall_time_secs * 1_000); |
| 158 | if mode == "uncapped-scout" { |
| 159 | spec.runtime_profile.wall_time_secs = None; |
| 160 | spec.runtime_profile.wall_deadline_ms = None; |
| 161 | } |
| 162 | if mode == "work-timeout" { |
| 163 | spec.runtime_profile.wall_deadline_ms = Some(epoch_millis_now() + 9_000); |
| 164 | } |
| 165 | spec.launch_manifest = Some(serde_json::from_value(json!({ |
| 166 | "owner_session": "root", "child_id": "report-worker", "profile": spec.runtime_profile, |
| 167 | "prompt": "Read README.md and produce report.md", "cwd": workspace.path(), "worktree": false, |
| 168 | "writable_roots": [], "writable_files": [], "coordination_contracts": [], "deliverables": ["report.md"], |
| 169 | "resume_identity": null, "generation": 1, "resume_from_agent_id": null |
| 170 | })).unwrap()); |
| 171 | if matches!(mode, "resume-unknown" | "uncapped-scout") { |
| 172 | spec.launch_manifest.as_mut().unwrap().deliverables.clear(); |
| 173 | } |
| 174 | let mut runtime = stub_runtime(); |
| 175 | runtime.client = CodewhaleClient::new(&config).unwrap(); |
| 176 | runtime.api_config = Some(Arc::new(config)); |
| 177 | runtime.context = ToolContext::new(workspace.path().to_path_buf()); |
| 178 | runtime.accounting_origin = SubAgentAccountingOrigin::capture(&runtime.context); |
| 179 | runtime.manager = Arc::clone(&manager); |
| 180 | runtime.worker_profile = spec.runtime_profile.clone(); |
| 181 | runtime.spawn_depth = spec.spawn_depth; |
| 182 | runtime.allow_shell = false; |
| 183 | runtime.accept_edits = false; |
| 184 | runtime.step_api_timeout = if mode == "timeout" { |
| 185 | Duration::from_millis(100) |
| 186 | } else if mode == "work-timeout" { |
| 187 | Duration::from_secs(10) |
| 188 | } else if timeout_case { |
| 189 | Duration::from_secs(2) |
| 190 | } else { |
| 191 | Duration::from_secs(10) |
| 192 | }; |
| 193 | let cancel = runtime.cancel_token.clone(); |
| 194 | let (parent_tx, completions) = mpsc::channel(16); |
| 195 | runtime.parent_completion_tx = Some(parent_tx); |
| 196 | let (mailbox, mailbox_rx) = Mailbox::new(CancellationToken::new()); |
| 197 | runtime.mailbox = Some(mailbox); |
| 198 | let assignment = SubAgentAssignment::new( |
| 199 | "Read README.md, report findings and identify what remains.".to_string(), |
| 200 | None, |
| 201 | ); |
| 202 | let (input_tx, input_rx) = mpsc::unbounded_channel(); |
| 203 | let mut agent = SubAgent::new( |
| 204 | "report-worker".to_string(), |
| 205 | FleetRole::Scout, |
| 206 | assignment.objective.clone(), |
| 207 | assignment.clone(), |
| 208 | runtime.model.clone(), |
| 209 | None, |
| 210 | Some(vec!["read_file".to_string()]), |
| 211 | input_tx, |
| 212 | workspace.path().to_path_buf(), |
| 213 | manager.read().await.current_session_boot_id.clone(), |
| 214 | ); |
| 215 | agent.status = SubAgentStatus::Running; |
| 216 | { |
| 217 | let mut guard = manager.write().await; |
| 218 | guard |
| 219 | .with_store_transaction(|guard| { |
| 220 | guard.register_worker_for_session(spec, &runtime.context.state_namespace, None); |
| 221 | guard.agents.insert("report-worker".to_string(), agent); |
| 222 | guard.persist_state_synchronously() |
| 223 | }) |
| 224 | .unwrap(); |
| 225 | } |
| 226 | let task = tokio::spawn(run_subagent_task(SubAgentTask { |
| 227 | manager_handle: Arc::clone(&manager), |
| 228 | runtime, |
| 229 | agent_id: "report-worker".to_string(), |
| 230 | agent_type: FleetRole::Scout, |
| 231 | prompt: assignment.objective.clone(), |
| 232 | assignment, |
| 233 | allowed_tools: Some(vec!["read_file".to_string()]), |
| 234 | fork_context: false, |
| 235 | started_at: Instant::now(), |
| 236 | max_steps, |
| 237 | wall_time: (mode != "uncapped-scout").then(|| Duration::from_secs(wall_time_secs)), |
| 238 | wall_ceiling_ms: None, |
| 239 | input_rx, |
| 240 | launch_gate: None, |
| 241 | _foreground_child_registration: None, |
| 242 | })); |
| 243 | Fixture { |
| 244 | _workspace: workspace, |
| 245 | manager, |
| 246 | task: Some(task), |
| 247 | server, |
| 248 | requests, |
| 249 | request_count, |
| 250 | report_started, |
| 251 | release_report, |
| 252 | cancel, |
| 253 | completions, |
| 254 | mailbox: mailbox_rx, |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | #[tokio::test] |
| 259 | async fn scout_without_an_owner_limit_finishes_after_twenty_five_reads() { |
| 260 | let steps = resolve_max_steps(FleetRole::Scout, None, None); |
| 261 | let mut fixture = fixture("uncapped-scout", 15, steps).await; |
| 262 | for expected in 1..=SCOUT_READS + 1 { |
| 263 | tokio::time::timeout( |
| 264 | Duration::from_secs(30), |
| 265 | fixture.request_count.wait_for(|seen| *seen >= expected), |
| 266 | ) |
| 267 | .await |
| 268 | .unwrap_or_else(|_| panic!("scout stalled before provider request {expected}")) |
| 269 | .expect("fixture provider"); |
| 270 | } |
| 271 | let result = fixture.finish().await; |
| 272 | assert_eq!(result.status, SubAgentStatus::Completed); |
| 273 | assert_eq!(result.steps_taken as usize, SCOUT_READS + 1); |
| 274 | let requests = fixture.requests.lock().unwrap(); |
| 275 | assert_eq!(requests.len(), SCOUT_READS + 1); |
| 276 | for (part, request) in (1..=SCOUT_READS).zip(&requests[1..]) { |
| 277 | let evidence = format!("checked part {part}"); |
| 278 | assert!( |
| 279 | request["messages"] |
| 280 | .as_array() |
| 281 | .unwrap() |
| 282 | .iter() |
| 283 | .any(|message| { |
| 284 | message["role"] == "tool" |
| 285 | && message["content"] |
| 286 | .as_str() |
| 287 | .is_some_and(|text| text.contains(&evidence)) |
| 288 | }), |
| 289 | "missing read result for part {part}" |
| 290 | ); |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | #[tokio::test] |
| 295 | #[allow(clippy::await_holding_lock)] |
| 296 | async fn owner_step_limit_preserves_tool_only_work_without_an_extra_request() { |
| 297 | let _retry = codewhale_runtime::retry_status::test_guard(); |
| 298 | codewhale_runtime::retry_status::clear_rate_limit(); |
| 299 | let mut fixture = fixture("tool-only", 15, 2).await; |
| 300 | let result = fixture.finish().await; |
| 301 | assert_eq!(result.status, SubAgentStatus::BudgetExhausted); |
| 302 | assert_eq!(terminal_limit_kind(&result), Some(AgentLimitKind::Step)); |
| 303 | assert_eq!(result.steps_taken, 2); |
| 304 | assert_eq!(result.usage.as_ref().unwrap().total_tokens, Some(45)); |
| 305 | assert!(result.result.as_deref().unwrap().contains("README.md")); |
| 306 | assert!( |
| 307 | result |
| 308 | .checkpoint |
| 309 | .as_ref() |
| 310 | .unwrap() |
| 311 | .messages |
| 312 | .iter() |
| 313 | .flat_map(|message| &message.content) |
| 314 | .any( |
| 315 | |block| matches!(block, ContentBlock::ToolResult { tool_use_id, content, .. } |
| 316 | if tool_use_id == "read-1" && content.contains("TOOL_EVIDENCE")) |
| 317 | ), |
| 318 | "the read must execute successfully before reporting: {:?}", |
| 319 | result.checkpoint, |
| 320 | ); |
| 321 | let requests = fixture.requests.lock().unwrap(); |
| 322 | assert_eq!(requests.len(), 2); |
| 323 | assert_eq!(requests[0]["model"], "deepseek-v4-flash"); |
| 324 | assert!( |
| 325 | requests[0]["tools"] |
| 326 | .as_array() |
| 327 | .unwrap() |
| 328 | .iter() |
| 329 | .any(|tool| tool["function"]["name"] == "read") |
| 330 | ); |
| 331 | drop(requests); |
| 332 | let guard = fixture.manager.read().await; |
| 333 | let worker = &guard.worker_records["report-worker"]; |
| 334 | assert_eq!(worker.limit_kind, Some(AgentLimitKind::Step)); |
| 335 | let encoded = serde_json::to_value(worker).unwrap(); |
| 336 | assert_eq!(encoded["limit_kind"], "step"); |
| 337 | let mut legacy = encoded; |
| 338 | legacy.as_object_mut().unwrap().remove("limit_kind"); |
| 339 | assert_eq!( |
| 340 | serde_json::from_value::<AgentWorkerRecord>(legacy) |
| 341 | .unwrap() |
| 342 | .limit_kind, |
| 343 | None |
| 344 | ); |
| 345 | assert_eq!(worker.verification.status, "deliverable_missing"); |
| 346 | assert_eq!(worker.verification.deliverables[0].path, "report.md"); |
| 347 | assert!( |
| 348 | !worker.spec.runtime_profile.permissions.write, |
| 349 | "report did not widen the Scout's authority" |
| 350 | ); |
| 351 | drop(guard); |
| 352 | let completion = fixture.completions.try_recv().unwrap(); |
| 353 | assert!(completion.payload.contains("budget_exhausted")); |
| 354 | assert!( |
| 355 | completion |
| 356 | .payload |
| 357 | .contains(r#""failure_class":"step_budget""#) |
| 358 | ); |
| 359 | assert!(completion.payload.contains("deliverable_missing")); |
| 360 | assert!(fixture.completions.try_recv().is_err()); |
| 361 | } |
| 362 | |
| 363 | #[tokio::test] |
| 364 | #[allow(clippy::await_holding_lock)] |
| 365 | async fn owner_step_limit_keeps_the_digest_as_the_deliverable() { |
| 366 | let _retry = codewhale_runtime::retry_status::test_guard(); |
| 367 | codewhale_runtime::retry_status::clear_rate_limit(); |
| 368 | let mut fixture = fixture("truncated", 15, 1).await; |
| 369 | let result = fixture.finish().await; |
| 370 | assert_eq!(fixture.requests.lock().unwrap().len(), 1); |
| 371 | assert_eq!(result.status, SubAgentStatus::BudgetExhausted); |
| 372 | let text = result.result.as_deref().unwrap(); |
| 373 | assert!( |
| 374 | text.contains("RECORDED_FINDING"), |
| 375 | "digest is the result: {text}" |
| 376 | ); |
| 377 | assert!(!text.contains("TRUNCATED_REPORT"), "{text}"); |
| 378 | assert!(text.contains("this child's deliverable"), "{text}"); |
| 379 | assert!(text.contains("4000 of 4020 characters shown"), "{text}"); |
| 380 | assert!(text.contains("transcript_handle"), "{text}"); |
| 381 | assert!(text.ends_with(&"界".repeat(3_984))); |
| 382 | assert!( |
| 383 | result |
| 384 | .checkpoint |
| 385 | .as_ref() |
| 386 | .unwrap() |
| 387 | .messages |
| 388 | .iter() |
| 389 | .flat_map(|message| &message.content) |
| 390 | .any( |
| 391 | |block| matches!(block, ContentBlock::Text { text, .. } if text.ends_with("TAIL")) |
| 392 | ) |
| 393 | ); |
| 394 | let completion = fixture.completions.try_recv().unwrap(); |
| 395 | assert!(completion.payload.contains("4000 of 4020 characters shown")); |
| 396 | |
| 397 | let state_root = fixture.manager.read().await.state_root.clone(); |
| 398 | let artifact = checked_subagent_state_path( |
| 399 | &state_root, |
| 400 | &Path::new(".codewhale/state/subagent-results").join(format!( |
| 401 | "{}.md", |
| 402 | codewhale_runtime::hashing::sha256_hex(b"report-worker") |
| 403 | )), |
| 404 | ) |
| 405 | .unwrap(); |
| 406 | let saved = fs::read_to_string(&artifact).expect("digest artifact written"); |
| 407 | assert!(saved.contains("RECORDED_FINDING"), "{saved}"); |
| 408 | assert!(saved.contains("4000 of 4020 characters shown"), "{saved}"); |
| 409 | assert!(!saved.contains("TAIL"), "{saved}"); |
| 410 | assert!(!saved.contains("TRUNCATED_REPORT"), "{saved}"); |
| 411 | assert!(text.contains(&artifact.display().to_string()), "{text}"); |
| 412 | } |
| 413 | |
| 414 | #[tokio::test] |
| 415 | #[allow(clippy::await_holding_lock)] |
| 416 | async fn budget_handback_inflight_wall_timeout_persists_unreported_usage() { |
| 417 | let _retry = codewhale_runtime::retry_status::test_guard(); |
| 418 | codewhale_runtime::retry_status::clear_rate_limit(); |
| 419 | let mut fixture = fixture("work-timeout", 15, 4).await; |
| 420 | let result = fixture.finish().await; |
| 421 | assert_eq!(result.status, SubAgentStatus::BudgetExhausted); |
| 422 | assert_eq!(terminal_limit_kind(&result), Some(AgentLimitKind::WallTime)); |
| 423 | assert!( |
| 424 | result |
| 425 | .result |
| 426 | .as_deref() |
| 427 | .unwrap() |
| 428 | .contains("child wall-time work budget exhausted") |
| 429 | ); |
| 430 | assert_eq!( |
| 431 | fixture.requests.lock().unwrap().len(), |
| 432 | 2, |
| 433 | "the owner deadline does not admit another model request for reporting" |
| 434 | ); |
| 435 | let manager = fixture.manager.read().await; |
| 436 | assert_eq!( |
| 437 | manager.worker_records["report-worker"].limit_kind, |
| 438 | Some(AgentLimitKind::WallTime) |
| 439 | ); |
| 440 | assert!(manager.worker_records["report-worker"].has_unreported_usage); |
| 441 | assert_eq!( |
| 442 | manager.worker_records["report-worker"].usage.total_tokens, |
| 443 | Some(15) |
| 444 | ); |
| 445 | } |
| 446 | |
| 447 | #[test] |
| 448 | fn budget_handback_coverage_marker_is_sticky_without_reclassifying_legacy_or_measured_zero() { |
| 449 | let tmp = tempdir().unwrap(); |
| 450 | let mut manager = SubAgentManager::new(tmp.path().to_path_buf(), 4); |
| 451 | for id in ["worker", "unrelated"] { |
| 452 | let spec = make_worker_spec(id, tmp.path().to_path_buf()); |
| 453 | manager.register_worker(spec); |
| 454 | } |
| 455 | let measured_zero = Usage { |
| 456 | prompt_cache_hit_tokens: Some(0), |
| 457 | ..Usage::default() |
| 458 | }; |
| 459 | manager.record_worker_usage("worker", "zero", &measured_zero, None); |
| 460 | manager.record_worker_usage("unrelated", "unrelated-missing", &Usage::default(), None); |
| 461 | assert_eq!(manager.worker_records["worker"].usage.total_tokens, Some(0)); |
| 462 | assert!(!manager.worker_records["worker"].has_unreported_usage); |
| 463 | let mut legacy = serde_json::to_value(&manager.worker_records["worker"]).unwrap(); |
| 464 | legacy |
| 465 | .as_object_mut() |
| 466 | .unwrap() |
| 467 | .remove("has_unreported_usage"); |
| 468 | let legacy: AgentWorkerRecord = serde_json::from_value(legacy).unwrap(); |
| 469 | assert!(!legacy.has_unreported_usage); |
| 470 | manager.worker_records.insert("worker".to_string(), legacy); |
| 471 | manager.record_worker_usage("worker", "missing", &Usage::default(), None); |
| 472 | manager.record_worker_usage( |
| 473 | "worker", |
| 474 | "known-later", |
| 475 | &Usage { |
| 476 | input_tokens: 10, |
| 477 | output_tokens: 5, |
| 478 | ..Usage::default() |
| 479 | }, |
| 480 | None, |
| 481 | ); |
| 482 | let saved = serde_json::to_vec(&manager.worker_records).unwrap(); |
| 483 | manager.worker_records = serde_json::from_slice(&saved).unwrap(); |
| 484 | assert_eq!( |
| 485 | manager.worker_records["worker"].usage.total_tokens, |
| 486 | Some(15) |
| 487 | ); |
| 488 | assert!(manager.worker_records["worker"].has_unreported_usage); |
| 489 | } |
| 490 | |
| 491 | #[tokio::test] |
| 492 | #[allow(clippy::await_holding_lock)] |
| 493 | async fn child_work_cancellation_wins_once() { |
| 494 | let _retry = codewhale_runtime::retry_status::test_guard(); |
| 495 | codewhale_runtime::retry_status::clear_rate_limit(); |
| 496 | let mut fixture = fixture("hold", 15, 2).await; |
| 497 | tokio::time::timeout(Duration::from_secs(30), fixture.report_started.notified()) |
| 498 | .await |
| 499 | .unwrap(); |
| 500 | fixture.cancel.cancel(); |
| 501 | let result = fixture.finish().await; |
| 502 | assert_eq!( |
| 503 | result.status, |
| 504 | SubAgentStatus::Cancelled, |
| 505 | "{:?} / {:?}", |
| 506 | result.result, |
| 507 | fixture.manager.read().await.worker_records["report-worker"].error |
| 508 | ); |
| 509 | assert_eq!(result.usage.as_ref().unwrap().total_tokens, Some(15)); |
| 510 | assert!(fixture.manager.read().await.worker_records["report-worker"].has_unreported_usage); |
| 511 | assert!( |
| 512 | fixture |
| 513 | .completions |
| 514 | .try_recv() |
| 515 | .unwrap() |
| 516 | .payload |
| 517 | .contains("cancelled") |
| 518 | ); |
| 519 | assert!(fixture.completions.try_recv().is_err()); |
| 520 | } |
| 521 | |
| 522 | #[tokio::test] |
| 523 | #[allow(clippy::await_holding_lock)] |
| 524 | async fn child_work_cancellation_after_response_preserves_actual_usage() { |
| 525 | let _retry = codewhale_runtime::retry_status::test_guard(); |
| 526 | codewhale_runtime::retry_status::clear_rate_limit(); |
| 527 | let mut fixture = fixture("hold", 15, 2).await; |
| 528 | tokio::time::timeout(Duration::from_secs(30), fixture.report_started.notified()) |
| 529 | .await |
| 530 | .unwrap(); |
| 531 | let manager = Arc::clone(&fixture.manager); |
| 532 | let guard = manager.write().await; |
| 533 | fixture.release_report.notify_one(); |
| 534 | // Runtime billing publishes the decoded response before it waits for the |
| 535 | // worker ledger lock. This makes the cancellation seam deterministic. |
| 536 | tokio::time::timeout(Duration::from_secs(30), async { |
| 537 | loop { |
| 538 | let entry = fixture.mailbox.recv().await.unwrap(); |
| 539 | if let MailboxMessage::TokenUsage { |
| 540 | agent_id, |
| 541 | source_id, |
| 542 | usage, |
| 543 | .. |
| 544 | } = entry.message |
| 545 | && agent_id == "report-worker" |
| 546 | && usage_total_tokens(&usage) == 30 |
| 547 | { |
| 548 | assert!(source_id.starts_with("child:report-worker:turn:")); |
| 549 | assert!(source_id.contains(":request:2:dispatch:")); |
| 550 | break; |
| 551 | } |
| 552 | } |
| 553 | }) |
| 554 | .await |
| 555 | .unwrap(); |
| 556 | fixture.cancel.cancel(); |
| 557 | drop(guard); |
| 558 | let result = fixture.finish().await; |
| 559 | assert_eq!( |
| 560 | result.status, |
| 561 | SubAgentStatus::Cancelled, |
| 562 | "{:?} / {:?}", |
| 563 | result.result, |
| 564 | fixture.manager.read().await.worker_records["report-worker"].error |
| 565 | ); |
| 566 | assert_eq!(result.usage.as_ref().unwrap().total_tokens, Some(45)); |
| 567 | assert!(!fixture.manager.read().await.worker_records["report-worker"].has_unreported_usage); |
| 568 | assert!( |
| 569 | fixture |
| 570 | .completions |
| 571 | .try_recv() |
| 572 | .unwrap() |
| 573 | .payload |
| 574 | .contains("cancelled") |
| 575 | ); |
| 576 | assert!(fixture.completions.try_recv().is_err()); |
| 577 | } |
| 578 | |
| 579 | #[tokio::test] |
| 580 | async fn child_job_preserves_the_original_deadline_without_a_reserve() { |
| 581 | let tmp = tempdir().unwrap(); |
| 582 | let mut runtime = stub_runtime(); |
| 583 | runtime.context = ToolContext::new(tmp.path().to_path_buf()); |
| 584 | runtime.manager = Arc::new(RwLock::new(SubAgentManager::new( |
| 585 | tmp.path().to_path_buf(), |
| 586 | 1, |
| 587 | ))); |
| 588 | runtime |
| 589 | .manager |
| 590 | .write() |
| 591 | .await |
| 592 | .register_worker(make_worker_spec("expired", tmp.path().to_path_buf())); |
| 593 | runtime.worker_profile.wall_deadline_ms = Some(epoch_millis_now().saturating_sub(1)); |
| 594 | let authority = engine::ChildAuthority::capture( |
| 595 | runtime.clone(), |
| 596 | FleetRole::Worker, |
| 597 | "expired".into(), |
| 598 | "report".into(), |
| 599 | None, |
| 600 | ); |
| 601 | let job = engine::ChildJob::admitted( |
| 602 | authority, |
| 603 | SubAgentAssignment::new("report".into(), None), |
| 604 | Instant::now(), |
| 605 | 2, |
| 606 | false, |
| 607 | None, |
| 608 | ) |
| 609 | .await |
| 610 | .unwrap(); |
| 611 | assert!( |
| 612 | job.deadline |
| 613 | .is_some_and(|deadline| deadline <= Instant::now()) |
| 614 | ); |
| 615 | assert_eq!(job.steps(), 0, "no model turn was admitted"); |
| 616 | assert!(!runtime.manager.read().await.worker_records["expired"].has_unreported_usage); |
| 617 | } |
| 618 | |
| 619 | fn git(root: &Path, args: &[&str]) { |
| 620 | let output = std::process::Command::new("git") |
| 621 | .arg("-C") |
| 622 | .arg(root) |
| 623 | .args(args) |
| 624 | .output() |
| 625 | .expect("git"); |
| 626 | assert!( |
| 627 | output.status.success(), |
| 628 | "git {args:?}: {}", |
| 629 | String::from_utf8_lossy(&output.stderr) |
| 630 | ); |
| 631 | } |
| 632 | |
| 633 | /// Addendum F4 (fleet-5): cancelling keeps the work. A Stop on a |
| 634 | /// write-scoped child appends the same preservation receipt a budget death |
| 635 | /// gets, exactly once, and leaves a read-only child's result alone. |
| 636 | #[tokio::test] |
| 637 | async fn cancel_appends_work_preservation_note_once() { |
| 638 | let tmp = tempdir().unwrap(); |
| 639 | let root = tmp.path(); |
| 640 | git(root, &["init", "--quiet"]); |
| 641 | git(root, &["config", "user.name", "Budget test"]); |
| 642 | git(root, &["config", "user.email", "budget@example.invalid"]); |
| 643 | fs::write(root.join("src.rs"), "baseline\n").unwrap(); |
| 644 | git(root, &["add", "--", "src.rs"]); |
| 645 | git(root, &["commit", "--quiet", "-m", "baseline"]); |
| 646 | |
| 647 | let manager = Arc::new(RwLock::new(SubAgentManager::new(root.to_path_buf(), 2))); |
| 648 | for (agent_id, write) in [("cancel-writer", true), ("cancel-scout", false)] { |
| 649 | let mut spec = make_worker_spec(agent_id, root.to_path_buf()); |
| 650 | spec.runtime_profile.permissions.write = write; |
| 651 | let mut guard = manager.write().await; |
| 652 | guard.register_worker(spec); |
| 653 | let (input_tx, _input_rx) = mpsc::unbounded_channel(); |
| 654 | let mut agent = SubAgent::new( |
| 655 | agent_id.to_string(), |
| 656 | FleetRole::Worker, |
| 657 | "work that gets stopped".to_string(), |
| 658 | SubAgentAssignment { |
| 659 | native_preset: None, |
| 660 | objective: "edit".to_string(), |
| 661 | role: Some("worker".to_string()), |
| 662 | }, |
| 663 | "deepseek-v4-flash".to_string(), |
| 664 | None, |
| 665 | None, |
| 666 | input_tx, |
| 667 | root.to_path_buf(), |
| 668 | guard.current_session_boot_id.clone(), |
| 669 | ); |
| 670 | agent.task_handle = Some(tokio::spawn(async { |
| 671 | tokio::time::sleep(Duration::from_secs(60)).await; |
| 672 | })); |
| 673 | guard.agents.insert(agent_id.to_string(), agent); |
| 674 | } |
| 675 | fs::create_dir_all(root.join("scratch")).unwrap(); |
| 676 | fs::write(root.join("scratch/half-done.rs"), "wip\n").unwrap(); |
| 677 | |
| 678 | let stopped = manager.write().await.cancel_agent("cancel-writer").unwrap(); |
| 679 | let preserved = preserve_cancelled_work(&manager, stopped).await; |
| 680 | let text = preserved.result.as_deref().unwrap_or_default(); |
| 681 | assert!(text.starts_with(CANCELLED_BY_PARENT_RESULT), "{text}"); |
| 682 | assert!(text.contains("scratch/half-done.rs"), "{text}"); |
| 683 | let stored = manager.read().await.get_result("cancel-writer").unwrap(); |
| 684 | assert_eq!(stored.result, preserved.result, "the receipt is persisted"); |
| 685 | |
| 686 | // A repeated Stop does not stack a second receipt. |
| 687 | let again = manager.write().await.cancel_agent("cancel-writer").unwrap(); |
| 688 | let again = preserve_cancelled_work(&manager, again).await; |
| 689 | assert_eq!(again.result, preserved.result); |
| 690 | |
| 691 | // A read-only child has no baseline: its result stays the plain Stop. |
| 692 | let scout = manager.write().await.cancel_agent("cancel-scout").unwrap(); |
| 693 | let scout = preserve_cancelled_work(&manager, scout).await; |
| 694 | assert_eq!(scout.result.as_deref(), Some(CANCELLED_BY_PARENT_RESULT)); |
| 695 | } |
| 696 | |
| 697 | /// F4: a Stop cascades to descendants, and each write-scoped descendant |
| 698 | /// stopped with the parent gets its own receipt; a read-only one does not. |
| 699 | #[tokio::test] |
| 700 | async fn cancel_receipts_each_writing_descendant_stopped_with_its_parent() { |
| 701 | let tmp = tempdir().unwrap(); |
| 702 | let root = tmp.path(); |
| 703 | git(root, &["init", "--quiet"]); |
| 704 | git(root, &["config", "user.name", "Budget test"]); |
| 705 | git(root, &["config", "user.email", "budget@example.invalid"]); |
| 706 | fs::write(root.join("src.rs"), "baseline\n").unwrap(); |
| 707 | git(root, &["add", "--", "src.rs"]); |
| 708 | git(root, &["commit", "--quiet", "-m", "baseline"]); |
| 709 | |
| 710 | let manager = Arc::new(RwLock::new(SubAgentManager::new(root.to_path_buf(), 4))); |
| 711 | for (agent_id, write, parent) in [ |
| 712 | ("tree-parent", true, None), |
| 713 | ("tree-writer", true, Some("tree-parent")), |
| 714 | ("tree-scout", false, Some("tree-parent")), |
| 715 | ("tree-stranger", true, None), |
| 716 | ] { |
| 717 | let mut spec = make_worker_spec(agent_id, root.to_path_buf()); |
| 718 | spec.runtime_profile.permissions.write = write; |
| 719 | spec.parent_run_id = parent.map(str::to_string); |
| 720 | let mut guard = manager.write().await; |
| 721 | guard.register_worker(spec); |
| 722 | let (input_tx, _input_rx) = mpsc::unbounded_channel(); |
| 723 | let mut agent = SubAgent::new( |
| 724 | agent_id.to_string(), |
| 725 | FleetRole::Worker, |
| 726 | "work that gets stopped".to_string(), |
| 727 | SubAgentAssignment { |
| 728 | native_preset: None, |
| 729 | objective: "edit".to_string(), |
| 730 | role: Some("worker".to_string()), |
| 731 | }, |
| 732 | "deepseek-v4-flash".to_string(), |
| 733 | None, |
| 734 | None, |
| 735 | input_tx, |
| 736 | root.to_path_buf(), |
| 737 | guard.current_session_boot_id.clone(), |
| 738 | ); |
| 739 | agent.task_handle = Some(tokio::spawn(async { |
| 740 | tokio::time::sleep(Duration::from_secs(60)).await; |
| 741 | })); |
| 742 | guard.agents.insert(agent_id.to_string(), agent); |
| 743 | } |
| 744 | fs::create_dir_all(root.join("scratch")).unwrap(); |
| 745 | fs::write(root.join("scratch/half-done.rs"), "wip\n").unwrap(); |
| 746 | |
| 747 | // The cascade order of `cancel_agent_for_session`: descendants, then the |
| 748 | // target. The unrelated writer is stopped too but is not a descendant. |
| 749 | let parent = { |
| 750 | let mut guard = manager.write().await; |
| 751 | for id in ["tree-writer", "tree-scout", "tree-stranger"] { |
| 752 | guard.cancel_agent(id).unwrap(); |
| 753 | } |
| 754 | guard.cancel_agent("tree-parent").unwrap() |
| 755 | }; |
| 756 | let parent = preserve_cancelled_work(&manager, parent).await; |
| 757 | assert!( |
| 758 | parent |
| 759 | .result |
| 760 | .as_deref() |
| 761 | .is_some_and(|text| text.contains("scratch/half-done.rs")), |
| 762 | "{:?}", |
| 763 | parent.result |
| 764 | ); |
| 765 | |
| 766 | let guard = manager.read().await; |
| 767 | let writer = guard.get_result("tree-writer").unwrap(); |
| 768 | let writer_text = writer.result.as_deref().unwrap_or_default(); |
| 769 | assert!( |
| 770 | writer_text.starts_with(CANCELLED_BY_PARENT_RESULT), |
| 771 | "{writer_text}" |
| 772 | ); |
| 773 | assert!( |
| 774 | writer_text.contains("scratch/half-done.rs"), |
| 775 | "{writer_text}" |
| 776 | ); |
| 777 | let scout = guard.get_result("tree-scout").unwrap(); |
| 778 | assert_eq!(scout.result.as_deref(), Some(CANCELLED_BY_PARENT_RESULT)); |
| 779 | let stranger = guard.get_result("tree-stranger").unwrap(); |
| 780 | assert_eq!(stranger.result.as_deref(), Some(CANCELLED_BY_PARENT_RESULT)); |
| 781 | } |
| 782 | |
| 783 | /// #5529: a budget death must name the work the worker left on disk. The |
| 784 | /// spawn-time delivery baseline is what makes the inventory attributable to |
| 785 | /// this worker rather than the parent's own dirty files. |
| 786 | #[tokio::test] |
| 787 | async fn run_death_preservation_note_names_surviving_workspace_changes() { |
| 788 | let tmp = tempdir().unwrap(); |
| 789 | let root = tmp.path(); |
| 790 | git(root, &["init", "--quiet"]); |
| 791 | git(root, &["config", "user.name", "Budget test"]); |
| 792 | git(root, &["config", "user.email", "budget@example.invalid"]); |
| 793 | fs::write(root.join("src.rs"), "baseline\n").unwrap(); |
| 794 | git(root, &["add", "--", "src.rs"]); |
| 795 | git(root, &["commit", "--quiet", "-m", "baseline"]); |
| 796 | |
| 797 | let manager = Arc::new(RwLock::new(SubAgentManager::new(root.to_path_buf(), 2))); |
| 798 | let mut spec = make_worker_spec("preserve-worker", root.to_path_buf()); |
| 799 | spec.runtime_profile.permissions.write = true; |
| 800 | manager.write().await.register_worker(spec); |
| 801 | |
| 802 | // The worker's unfinished work lands after the baseline was captured. |
| 803 | fs::create_dir_all(root.join("scratch")).unwrap(); |
| 804 | fs::write(root.join("scratch/leftover.rs"), "wip\n").unwrap(); |
| 805 | |
| 806 | let mut runtime = stub_runtime(); |
| 807 | runtime.manager = Arc::clone(&manager); |
| 808 | |
| 809 | let note = |
| 810 | budget_work_preservation_note(&runtime.manager, "preserve-worker", "wall_time_budget") |
| 811 | .await |
| 812 | .expect("write-scoped worker has a baseline"); |
| 813 | assert!( |
| 814 | note.contains("scratch/leftover.rs"), |
| 815 | "note should name the surviving path: {note}" |
| 816 | ); |
| 817 | assert!(note.contains(&root.display().to_string()), "{note}"); |
| 818 | |
| 819 | // A read-only worker captured no baseline — there is no file work to |
| 820 | // inventory and the note stays absent rather than lying. |
| 821 | let mut scout_spec = make_worker_spec("scout-worker", root.to_path_buf()); |
| 822 | scout_spec.runtime_profile.permissions.write = false; |
| 823 | manager.write().await.register_worker(scout_spec); |
| 824 | assert!( |
| 825 | budget_work_preservation_note(&runtime.manager, "scout-worker", "wall_time_budget") |
| 826 | .await |
| 827 | .is_none() |
| 828 | ); |
| 829 | |
| 830 | // A write-scoped worker that changed nothing still gets an explicit |
| 831 | // "no changes" receipt instead of silence. |
| 832 | let mut clean_spec = make_worker_spec("clean-worker", root.to_path_buf()); |
| 833 | clean_spec.runtime_profile.permissions.write = true; |
| 834 | clean_spec.workspace = root.to_path_buf(); |
| 835 | let clean_root = tempdir().unwrap(); |
| 836 | let clean_path = clean_root.path(); |
| 837 | git(clean_path, &["init", "--quiet"]); |
| 838 | git(clean_path, &["config", "user.name", "Budget test"]); |
| 839 | git( |
| 840 | clean_path, |
| 841 | &["config", "user.email", "budget@example.invalid"], |
| 842 | ); |
| 843 | fs::write(clean_path.join("src.rs"), "baseline\n").unwrap(); |
| 844 | git(clean_path, &["add", "--", "src.rs"]); |
| 845 | git(clean_path, &["commit", "--quiet", "-m", "baseline"]); |
| 846 | clean_spec.workspace = clean_path.to_path_buf(); |
| 847 | manager.write().await.register_worker(clean_spec); |
| 848 | let note = budget_work_preservation_note(&runtime.manager, "clean-worker", "wall_time_budget") |
| 849 | .await |
| 850 | .expect("baseline exists"); |
| 851 | assert!(note.contains("No workspace changes"), "{note}"); |
| 852 | } |
| 853 | |
| 854 | fn git_out(root: &Path, args: &[&str]) -> String { |
| 855 | let output = std::process::Command::new("git") |
| 856 | .arg("-C") |
| 857 | .arg(root) |
| 858 | .args(args) |
| 859 | .output() |
| 860 | .expect("git"); |
| 861 | assert!( |
| 862 | output.status.success(), |
| 863 | "git {args:?}: {}", |
| 864 | String::from_utf8_lossy(&output.stderr) |
| 865 | ); |
| 866 | String::from_utf8_lossy(&output.stdout).trim().to_string() |
| 867 | } |
| 868 | |
| 869 | /// #6194 item 4 / #5529: on an isolated worktree a budget death commits the |
| 870 | /// worker's uncommitted changes as labeled salvage instead of leaving them |
| 871 | /// for manual recovery. |
| 872 | #[tokio::test] |
| 873 | async fn budget_death_checkpoint_commits_uncommitted_work_on_isolated_worktree() { |
| 874 | let tmp = tempdir().unwrap(); |
| 875 | let root = tmp.path(); |
| 876 | git(root, &["init", "--quiet"]); |
| 877 | git(root, &["config", "user.name", "Budget test"]); |
| 878 | git(root, &["config", "user.email", "budget@example.invalid"]); |
| 879 | fs::write(root.join("src.rs"), "baseline\n").unwrap(); |
| 880 | git(root, &["add", "--", "src.rs"]); |
| 881 | git(root, &["commit", "--quiet", "-m", "baseline"]); |
| 882 | |
| 883 | let manager = Arc::new(RwLock::new(SubAgentManager::new(root.to_path_buf(), 2))); |
| 884 | let mut spec = make_worker_spec("checkpoint-worker", root.to_path_buf()); |
| 885 | spec.runtime_profile.permissions.write = true; |
| 886 | spec.launch_manifest = Some(ChildLaunchManifest { |
| 887 | activation: None, |
| 888 | owner_session: "root".to_string(), |
| 889 | child_id: "checkpoint-worker".to_string(), |
| 890 | profile: spec.runtime_profile.clone(), |
| 891 | prompt: spec.objective.clone(), |
| 892 | cwd: Some(root.display().to_string()), |
| 893 | worktree: true, |
| 894 | writable_roots: vec![root.display().to_string()], |
| 895 | writable_files: Vec::new(), |
| 896 | coordination_contracts: Vec::new(), |
| 897 | expected_artifact: None, |
| 898 | deliverables: Vec::new(), |
| 899 | resume_identity: None, |
| 900 | generation: 1, |
| 901 | resume_from_agent_id: None, |
| 902 | }); |
| 903 | manager.write().await.register_worker(spec); |
| 904 | fs::write(root.join("src.rs"), "baseline\nuncommitted fix\n").unwrap(); |
| 905 | fs::write(root.join("new.rs"), "wip\n").unwrap(); |
| 906 | |
| 907 | let mut runtime = stub_runtime(); |
| 908 | runtime.manager = Arc::clone(&manager); |
| 909 | let note = |
| 910 | budget_work_preservation_note(&runtime.manager, "checkpoint-worker", "wall_time_budget") |
| 911 | .await |
| 912 | .expect("note"); |
| 913 | assert!( |
| 914 | note.contains("checkpointed in commit"), |
| 915 | "note should name the salvage commit: {note}" |
| 916 | ); |
| 917 | let subject = git_out(root, &["log", "--format=%s", "-1"]); |
| 918 | assert!( |
| 919 | subject.starts_with("checkpoint: checkpoint-worker (wall_time_budget)"), |
| 920 | "marker message names the worker and cause: {subject}" |
| 921 | ); |
| 922 | assert!( |
| 923 | git_out(root, &["status", "--porcelain=v1", "--"]).is_empty(), |
| 924 | "checkpoint leaves a clean tree" |
| 925 | ); |
| 926 | } |
| 927 | |
| 928 | /// A shared checkout may hold the parent's or a sibling's dirty files, so no |
| 929 | /// auto-commit happens there — the note keeps the manual-salvage wording. |
| 930 | #[tokio::test] |
| 931 | async fn budget_death_checkpoint_skips_shared_checkout() { |
| 932 | let tmp = tempdir().unwrap(); |
| 933 | let root = tmp.path(); |
| 934 | git(root, &["init", "--quiet"]); |
| 935 | git(root, &["config", "user.name", "Budget test"]); |
| 936 | git(root, &["config", "user.email", "budget@example.invalid"]); |
| 937 | fs::write(root.join("src.rs"), "baseline\n").unwrap(); |
| 938 | git(root, &["add", "--", "src.rs"]); |
| 939 | git(root, &["commit", "--quiet", "-m", "baseline"]); |
| 940 | |
| 941 | let manager = Arc::new(RwLock::new(SubAgentManager::new(root.to_path_buf(), 2))); |
| 942 | let mut spec = make_worker_spec("shared-worker", root.to_path_buf()); |
| 943 | spec.runtime_profile.permissions.write = true; |
| 944 | manager.write().await.register_worker(spec); |
| 945 | fs::write(root.join("src.rs"), "baseline\nuncommitted fix\n").unwrap(); |
| 946 | |
| 947 | let mut runtime = stub_runtime(); |
| 948 | runtime.manager = Arc::clone(&manager); |
| 949 | let note = budget_work_preservation_note(&runtime.manager, "shared-worker", "wall_time_budget") |
| 950 | .await |
| 951 | .expect("note"); |
| 952 | assert!(!note.contains("checkpointed in commit"), "{note}"); |
| 953 | assert!(note.contains("survive on disk"), "{note}"); |
| 954 | assert!( |
| 955 | !git_out(root, &["status", "--porcelain=v1", "--"]).is_empty(), |
| 956 | "shared checkout stays dirty" |
| 957 | ); |
| 958 | } |
| 959 | |
| 960 | /// When the worker committed everything itself before death, the note says so |
| 961 | /// instead of claiming a checkpoint or manual salvage. |
| 962 | #[tokio::test] |
| 963 | async fn budget_death_checkpoint_reports_worker_committed_tree() { |
| 964 | let tmp = tempdir().unwrap(); |
| 965 | let root = tmp.path(); |
| 966 | git(root, &["init", "--quiet"]); |
| 967 | git(root, &["config", "user.name", "Budget test"]); |
| 968 | git(root, &["config", "user.email", "budget@example.invalid"]); |
| 969 | fs::write(root.join("src.rs"), "baseline\n").unwrap(); |
| 970 | git(root, &["add", "--", "src.rs"]); |
| 971 | git(root, &["commit", "--quiet", "-m", "baseline"]); |
| 972 | |
| 973 | let manager = Arc::new(RwLock::new(SubAgentManager::new(root.to_path_buf(), 2))); |
| 974 | let mut spec = make_worker_spec("tidy-worker", root.to_path_buf()); |
| 975 | spec.runtime_profile.permissions.write = true; |
| 976 | spec.launch_manifest = Some(ChildLaunchManifest { |
| 977 | activation: None, |
| 978 | owner_session: "root".to_string(), |
| 979 | child_id: "tidy-worker".to_string(), |
| 980 | profile: spec.runtime_profile.clone(), |
| 981 | prompt: spec.objective.clone(), |
| 982 | cwd: Some(root.display().to_string()), |
| 983 | worktree: true, |
| 984 | writable_roots: vec![root.display().to_string()], |
| 985 | writable_files: Vec::new(), |
| 986 | coordination_contracts: Vec::new(), |
| 987 | expected_artifact: None, |
| 988 | deliverables: Vec::new(), |
| 989 | resume_identity: None, |
| 990 | generation: 1, |
| 991 | resume_from_agent_id: None, |
| 992 | }); |
| 993 | manager.write().await.register_worker(spec); |
| 994 | fs::write(root.join("src.rs"), "baseline\nworker fix\n").unwrap(); |
| 995 | git(root, &["add", "--", "src.rs"]); |
| 996 | git(root, &["commit", "--quiet", "-m", "worker fix"]); |
| 997 | |
| 998 | let mut runtime = stub_runtime(); |
| 999 | runtime.manager = Arc::clone(&manager); |
| 1000 | let note = budget_work_preservation_note(&runtime.manager, "tidy-worker", "wall_time_budget") |
| 1001 | .await |
| 1002 | .expect("note"); |
| 1003 | assert!(note.contains("committed before death"), "{note}"); |
| 1004 | } |
| 1005 | |
| 1006 | fn assistant_message(content: Vec<ContentBlock>) -> Message { |
| 1007 | Message { |
| 1008 | role: Role::Assistant, |
| 1009 | content, |
| 1010 | } |
| 1011 | } |
| 1012 | |
| 1013 | fn tool_use(name: &str, input: Value) -> ContentBlock { |
| 1014 | ContentBlock::ToolUse { |
| 1015 | execution_id: None, |
| 1016 | id: format!("call_{name}"), |
| 1017 | name: name.to_string(), |
| 1018 | input, |
| 1019 | caller: None, |
| 1020 | thought_signature: None, |
| 1021 | } |
| 1022 | } |
| 1023 | |
| 1024 | #[test] |
| 1025 | fn fallback_partial_text_prefers_last_assistant_text() { |
| 1026 | let messages = vec![ |
| 1027 | assistant_message(vec![ContentBlock::Text { |
| 1028 | text: "first".to_string(), |
| 1029 | cache_control: None, |
| 1030 | }]), |
| 1031 | assistant_message(vec![ |
| 1032 | tool_use("Read", json!({"path": "src/main.rs"})), |
| 1033 | ContentBlock::Text { |
| 1034 | text: "second".to_string(), |
| 1035 | cache_control: None, |
| 1036 | }, |
| 1037 | ]), |
| 1038 | ]; |
| 1039 | assert_eq!(budget_handback::fallback_partial_text(&messages), "second"); |
| 1040 | } |
| 1041 | |
| 1042 | #[test] |
| 1043 | fn fallback_partial_text_digests_thinking_and_tool_calls_without_text() { |
| 1044 | let messages = vec![ |
| 1045 | assistant_message(vec![ContentBlock::Thinking { |
| 1046 | thinking: "checking whether the ring slot write precedes the read".to_string(), |
| 1047 | signature: None, |
| 1048 | state: None, |
| 1049 | redacted_data: None, |
| 1050 | }]), |
| 1051 | assistant_message(vec![tool_use("Read", json!({"path": "ring.rs"}))]), |
| 1052 | assistant_message(vec![tool_use( |
| 1053 | "Grep", |
| 1054 | json!({"pattern": "slot", "path": "ring.rs"}), |
| 1055 | )]), |
| 1056 | ]; |
| 1057 | let digest = budget_handback::fallback_partial_text(&messages); |
| 1058 | assert!(digest.contains("Tool calls (newest first)"), "{digest}"); |
| 1059 | assert!(digest.contains("- Grep ring.rs"), "{digest}"); |
| 1060 | assert!(digest.contains("- Read ring.rs"), "{digest}"); |
| 1061 | assert!( |
| 1062 | digest.find("- Grep").unwrap() < digest.find("- Read").unwrap(), |
| 1063 | "{digest}" |
| 1064 | ); |
| 1065 | assert!(digest.contains("unverified"), "{digest}"); |
| 1066 | assert!( |
| 1067 | digest.contains("ring slot write precedes the read"), |
| 1068 | "{digest}" |
| 1069 | ); |
| 1070 | } |
| 1071 | |
| 1072 | #[test] |
| 1073 | fn fallback_partial_text_caps_tool_entries_and_reports_overflow() { |
| 1074 | let messages: Vec<Message> = (0..14) |
| 1075 | .map(|i| { |
| 1076 | assistant_message(vec![tool_use( |
| 1077 | "Read", |
| 1078 | json!({"path": format!("file_{i}.rs")}), |
| 1079 | )]) |
| 1080 | }) |
| 1081 | .collect(); |
| 1082 | let digest = budget_handback::fallback_partial_text(&messages); |
| 1083 | assert!(digest.contains("...and 2 more"), "{digest}"); |
| 1084 | assert!(!digest.contains("file_0.rs"), "{digest}"); |
| 1085 | assert!(digest.contains("file_13.rs"), "{digest}"); |
| 1086 | } |
| 1087 | |
| 1088 | #[test] |
| 1089 | fn fallback_partial_text_is_silent_only_when_nothing_was_recorded() { |
| 1090 | assert!(budget_handback::fallback_partial_text(&[]).contains("No assistant text was recorded")); |
| 1091 | let user_only = vec![Message { |
| 1092 | role: Role::User, |
| 1093 | content: vec![ContentBlock::Text { |
| 1094 | text: "do the thing".to_string(), |
| 1095 | cache_control: None, |
| 1096 | }], |
| 1097 | }]; |
| 1098 | assert!( |
| 1099 | budget_handback::fallback_partial_text(&user_only) |
| 1100 | .contains("No assistant text was recorded") |
| 1101 | ); |
| 1102 | } |
| 1103 | |
| 1104 | #[test] |
| 1105 | fn budget_repair_only_rewrites_the_newly_synthesized_final_execution() { |
| 1106 | for (first, last) in [(Some("first"), Some("last")), (None, None)] { |
| 1107 | let mut messages: Vec<Message> = serde_json::from_value(json!([ |
| 1108 | {"role":"assistant","content":[{"type":"tool_use","id":"reused","execution_id":first,"name":"read","input":{}}]}, |
| 1109 | {"role":"user","content":[{"type":"tool_result","tool_use_id":"reused","execution_id":first,"content":"earlier completed output"}]}, |
| 1110 | {"role":"assistant","content":[{"type":"tool_use","id":"reused","execution_id":last,"name":"read","input":{}}]} |
| 1111 | ])).unwrap(); |
| 1112 | let earlier = messages[..2].to_vec(); |
| 1113 | budget_handback::repair_stopped_tool_calls(&mut messages, "fixture deadline"); |
| 1114 | assert_eq!(&messages[..2], earlier.as_slice()); |
| 1115 | assert!( |
| 1116 | matches!(&messages[3].content[0], ContentBlock::ToolResult { execution_id, content, .. } |
| 1117 | if execution_id.as_deref() == last && content.contains("budget_exhausted")) |
| 1118 | ); |
| 1119 | } |
| 1120 | } |
| 1121 |