| 1 | use super::*; |
| 2 | use tempfile::tempdir; |
| 3 | |
| 4 | pub(super) fn status_rows(payload: &Value) -> Vec<Value> { |
| 5 | let columns = payload["columns"].as_array().expect("roster columns"); |
| 6 | let unique = columns |
| 7 | .iter() |
| 8 | .map(|column| column.as_str().expect("column name")) |
| 9 | .collect::<HashSet<_>>(); |
| 10 | assert_eq!(columns.len(), unique.len(), "duplicate roster column"); |
| 11 | payload["agents"] |
| 12 | .as_array() |
| 13 | .expect("roster rows") |
| 14 | .iter() |
| 15 | .map(|row| { |
| 16 | let values = row.as_array().expect("roster row array"); |
| 17 | assert_eq!(columns.len(), values.len(), "row must match its header"); |
| 18 | Value::Object( |
| 19 | columns |
| 20 | .iter() |
| 21 | .zip(values) |
| 22 | .map(|(column, value)| (column.as_str().unwrap().to_string(), value.clone())) |
| 23 | .collect(), |
| 24 | ) |
| 25 | }) |
| 26 | .collect() |
| 27 | } |
| 28 | |
| 29 | fn prior_messages() -> Vec<Message> { |
| 30 | vec![Message { |
| 31 | role: Role::User, |
| 32 | content: vec![ContentBlock::Text { |
| 33 | text: "retained work".into(), |
| 34 | cache_control: None, |
| 35 | }], |
| 36 | }] |
| 37 | } |
| 38 | |
| 39 | #[tokio::test] |
| 40 | async fn lifecycle_bulk_followup_preserves_mappings_and_retries_without_duplicate_workers() { |
| 41 | let dir = tempdir().unwrap(); |
| 42 | let manager = new_shared_subagent_manager(dir.path().to_path_buf(), 12); |
| 43 | let mut sources = Vec::new(); |
| 44 | { |
| 45 | let mut guard = manager.write().await; |
| 46 | for i in 0..6 { |
| 47 | let (id, _) = guard.insert_test_interrupted_continuable_agent( |
| 48 | &format!("parked-{i}"), |
| 49 | dir.path(), |
| 50 | prior_messages(), |
| 51 | ); |
| 52 | let agent = guard.agents.get_mut(&id).unwrap(); |
| 53 | agent.checkpoint.as_mut().unwrap().parked_at_turn_end = true; |
| 54 | agent.agent_type = FleetRole::Scout; |
| 55 | agent.model = "deepseek-v4-flash".into(); |
| 56 | agent.allowed_tools = Some(Vec::new()); |
| 57 | let record = guard.worker_records.get_mut(&id).unwrap(); |
| 58 | record.parent_run_id = None; |
| 59 | record.spec.parent_run_id = None; |
| 60 | let spec = &mut record.spec; |
| 61 | spec.model = "deepseek-v4-flash".into(); |
| 62 | spec.agent_type = FleetRole::Scout; |
| 63 | spec.runtime_profile = WorkerRuntimeProfile::for_role(FleetRole::Scout); |
| 64 | sources.push(id); |
| 65 | } |
| 66 | } |
| 67 | let (client, _, _, fixture_config) = |
| 68 | super::tests::delayed_chat_client(Duration::from_secs(30), "fixture result").await; |
| 69 | let mut runtime = super::tests::stub_runtime(); |
| 70 | runtime.manager = Arc::clone(&manager); |
| 71 | runtime.client = client; |
| 72 | runtime.api_config = Some(Arc::new(fixture_config)); |
| 73 | runtime.context = ToolContext::new(dir.path()); |
| 74 | let tool = coord::AgentsFollowupTool::new(Arc::clone(&manager)).with_runtime(runtime); |
| 75 | let input = json!({"agent_ids": sources, "message": "Continue the assignment."}); |
| 76 | let first = tool |
| 77 | .execute(input.clone(), &ToolContext::new(dir.path())) |
| 78 | .await |
| 79 | .unwrap(); |
| 80 | let first: Value = serde_json::from_str(&first.content).unwrap(); |
| 81 | assert_eq!(first["results"].as_array().unwrap().len(), 6); |
| 82 | assert_eq!(first["errors"], json!([])); |
| 83 | let second = tool |
| 84 | .execute(input, &ToolContext::new(dir.path())) |
| 85 | .await |
| 86 | .unwrap(); |
| 87 | let second: Value = serde_json::from_str(&second.content).unwrap(); |
| 88 | for (a, b) in first["results"] |
| 89 | .as_array() |
| 90 | .unwrap() |
| 91 | .iter() |
| 92 | .zip(second["results"].as_array().unwrap()) |
| 93 | { |
| 94 | assert_eq!(a["from"], b["from"]); |
| 95 | assert_eq!(a["to"], b["to"]); |
| 96 | assert_ne!(a["from"], a["to"]); |
| 97 | } |
| 98 | let mut guard = manager.write().await; |
| 99 | assert_eq!(guard.agents.len(), 12); |
| 100 | for id in sources { |
| 101 | let target = guard.continuation_target(&id).unwrap(); |
| 102 | assert_ne!(target, id); |
| 103 | assert_eq!( |
| 104 | guard.continuation_source(&target).as_deref(), |
| 105 | Some(id.as_str()) |
| 106 | ); |
| 107 | let _ = guard.cancel_agent(&target); |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | #[tokio::test] |
| 112 | async fn lifecycle_bulk_followup_reports_unknown_and_foreign_targets_without_hiding_success() { |
| 113 | let dir = tempdir().unwrap(); |
| 114 | let manager = new_shared_subagent_manager(dir.path().to_path_buf(), 4); |
| 115 | let (owned, foreign) = { |
| 116 | let mut guard = manager.write().await; |
| 117 | let owned = guard.insert_test_running_agent("owned", dir.path()); |
| 118 | let foreign = guard.insert_test_running_agent("foreign", dir.path()); |
| 119 | guard.assign_test_session_owner(&foreign, "another-session"); |
| 120 | (owned, foreign) |
| 121 | }; |
| 122 | let tool = coord::AgentsFollowupTool::new(Arc::clone(&manager)); |
| 123 | let result = tool |
| 124 | .execute( |
| 125 | json!({"agent_ids": [owned, "missing", foreign], "message": "Check progress"}), |
| 126 | &ToolContext::new(dir.path()), |
| 127 | ) |
| 128 | .await |
| 129 | .unwrap(); |
| 130 | let payload: Value = serde_json::from_str(&result.content).unwrap(); |
| 131 | assert_eq!(payload["results"].as_array().unwrap().len(), 1); |
| 132 | assert_eq!(payload["errors"].as_array().unwrap().len(), 2); |
| 133 | assert!(!manager.read().await.child_was_woken(&foreign)); |
| 134 | } |
| 135 | |
| 136 | #[tokio::test] |
| 137 | async fn lifecycle_followup_rejects_ambiguous_and_invalid_batch_inputs_before_delivery() { |
| 138 | let dir = tempdir().unwrap(); |
| 139 | let manager = new_shared_subagent_manager(dir.path().to_path_buf(), 2); |
| 140 | let id = manager |
| 141 | .write() |
| 142 | .await |
| 143 | .insert_test_running_agent("owned", dir.path()); |
| 144 | let tool = coord::AgentsFollowupTool::new(Arc::clone(&manager)); |
| 145 | for input in [ |
| 146 | json!({"agent_id": id, "agent_ids": [id], "message": "x"}), |
| 147 | json!({"agent_ids": [], "message": "x"}), |
| 148 | json!({"agent_ids": [id, 7], "message": "x"}), |
| 149 | json!({"all_parked": "true", "message": "x"}), |
| 150 | json!({"agent_id": id, "message": " "}), |
| 151 | ] { |
| 152 | assert!( |
| 153 | tool.execute(input, &ToolContext::new(dir.path())) |
| 154 | .await |
| 155 | .is_err() |
| 156 | ); |
| 157 | } |
| 158 | assert!(!manager.read().await.child_was_woken(&id)); |
| 159 | } |
| 160 | |
| 161 | #[tokio::test] |
| 162 | async fn lifecycle_resume_lineage_survives_persist_and_rejects_cycles_and_foreign_hops() { |
| 163 | let dir = tempdir().unwrap(); |
| 164 | let base = dir.path().canonicalize().unwrap(); |
| 165 | let state_path = base.join(".codewhale/subagents/state.json"); |
| 166 | let mut manager = SubAgentManager::new(base.clone(), 6).with_state_path(state_path.clone()); |
| 167 | let (a, _) = manager.insert_test_interrupted_continuable_agent("old", &base, prior_messages()); |
| 168 | let (b, _) = |
| 169 | manager.insert_test_interrupted_continuable_agent("continued", &base, prior_messages()); |
| 170 | let (c, _) = |
| 171 | manager.insert_test_interrupted_continuable_agent("latest", &base, prior_messages()); |
| 172 | manager.resume_targets.insert(a.clone(), b.clone()); |
| 173 | manager.resume_targets.insert(b.clone(), c.clone()); |
| 174 | manager.persist_state().unwrap().join().unwrap(); |
| 175 | let mut loaded = SubAgentManager::new(base.clone(), 6).with_state_path(state_path); |
| 176 | loaded.load_state().unwrap(); |
| 177 | assert_eq!(loaded.continuation_target(&a).unwrap(), c); |
| 178 | loaded.resume_targets.insert(c.clone(), a.clone()); |
| 179 | assert!( |
| 180 | loaded |
| 181 | .continuation_target(&a) |
| 182 | .unwrap_err() |
| 183 | .to_string() |
| 184 | .contains("cycle") |
| 185 | ); |
| 186 | loaded.resume_targets.remove(&c); |
| 187 | loaded.assign_test_session_owner(&c, "foreign"); |
| 188 | assert!( |
| 189 | loaded |
| 190 | .continuation_target(&a) |
| 191 | .unwrap_err() |
| 192 | .to_string() |
| 193 | .contains("outside") |
| 194 | ); |
| 195 | } |
| 196 | |
| 197 | #[tokio::test] |
| 198 | async fn lifecycle_compact_roster_bounds_every_state_and_pages_multibyte_names() { |
| 199 | let dir = tempdir().unwrap(); |
| 200 | let manager = new_shared_subagent_manager(dir.path().to_path_buf(), 50); |
| 201 | let mut expected = HashSet::new(); |
| 202 | { |
| 203 | let mut guard = manager.write().await; |
| 204 | for i in 0..37 { |
| 205 | let id = guard.insert_test_running_agent(&format!("bounded-{i}"), dir.path()); |
| 206 | expected.insert(id.clone()); |
| 207 | let agent = guard.agents.get_mut(&id).unwrap(); |
| 208 | agent.session_name = "🐋\"".repeat(4000); |
| 209 | agent.prompt = "archive-only".repeat(10_000); |
| 210 | agent.checkpoint = Some(build_subagent_checkpoint( |
| 211 | &id, |
| 212 | "resume", |
| 213 | &prior_messages(), |
| 214 | 1, |
| 215 | true, |
| 216 | )); |
| 217 | if i % 3 == 1 { |
| 218 | agent.status = SubAgentStatus::Interrupted("reason".repeat(10_000)); |
| 219 | } |
| 220 | if i % 3 == 2 { |
| 221 | agent.status = SubAgentStatus::Failed("failure".repeat(10_000)); |
| 222 | } |
| 223 | let record = guard.worker_records.get_mut(&id).unwrap(); |
| 224 | record.usage.total_tokens = Some(100); |
| 225 | record.verification.summary = "\"🐋".repeat(10_000); |
| 226 | if i > 0 { |
| 227 | record.parent_run_id = Some("agent_bounded-0".into()); |
| 228 | } |
| 229 | } |
| 230 | } |
| 231 | let mut offset = 0; |
| 232 | let mut seen = HashSet::new(); |
| 233 | let mut header = None; |
| 234 | loop { |
| 235 | let result = inspect_agent_from_input( |
| 236 | &json!({"action": "status", "verbose": true, "offset": offset}), |
| 237 | Arc::clone(&manager), |
| 238 | &ToolContext::new(dir.path()), |
| 239 | false, |
| 240 | None, |
| 241 | ) |
| 242 | .await |
| 243 | .unwrap(); |
| 244 | assert!( |
| 245 | result.content.len() <= lifecycle::COMPACT_STATUS_BYTES, |
| 246 | "{}", |
| 247 | result.content.len() |
| 248 | ); |
| 249 | let value: Value = serde_json::from_str(&result.content).unwrap(); |
| 250 | assert_eq!( |
| 251 | *header.get_or_insert_with(|| value["columns"].clone()), |
| 252 | value["columns"] |
| 253 | ); |
| 254 | assert_eq!(value["total_count"], 37); |
| 255 | assert_eq!( |
| 256 | value["usage"]["total_tokens"], 3700, |
| 257 | "scope totals must not be counted per child" |
| 258 | ); |
| 259 | let rows = status_rows(&value); |
| 260 | assert!(!rows.is_empty()); |
| 261 | for row in rows { |
| 262 | assert!(seen.insert(row["agent_id"].as_str().unwrap().to_string())); |
| 263 | for key in [ |
| 264 | "snapshot", |
| 265 | "worker_record", |
| 266 | "checkpoint", |
| 267 | "transcript_handle", |
| 268 | ] { |
| 269 | assert!(row.get(key).is_none(), "{key}"); |
| 270 | } |
| 271 | } |
| 272 | let Some(next) = value["next_offset"].as_u64() else { |
| 273 | break; |
| 274 | }; |
| 275 | assert!(next > offset); |
| 276 | offset = next; |
| 277 | } |
| 278 | assert_eq!(seen, expected); |
| 279 | } |
| 280 | |
| 281 | #[tokio::test] |
| 282 | async fn lifecycle_compact_columns_keep_unknown_usage_and_pending_input_explicit() { |
| 283 | let dir = tempdir().unwrap(); |
| 284 | let mut manager = SubAgentManager::new(dir.path().to_path_buf(), 3); |
| 285 | let zero = manager.insert_test_running_agent("zero", dir.path()); |
| 286 | manager |
| 287 | .worker_records |
| 288 | .get_mut(&zero) |
| 289 | .unwrap() |
| 290 | .usage |
| 291 | .total_tokens = Some(0); |
| 292 | let (pending, _) = |
| 293 | manager.insert_test_interrupted_continuable_agent("pending", dir.path(), prior_messages()); |
| 294 | manager.agents.get_mut(&pending).unwrap().needs_input = Some(SubAgentNeedsInput { |
| 295 | question: "Approve the next validation step?".into(), |
| 296 | }); |
| 297 | let payload = |
| 298 | lifecycle::compact_roster(&manager, &json!({}), "workspace", false, false).unwrap(); |
| 299 | let rows = status_rows(&payload); |
| 300 | let zero = rows.iter().find(|row| row["agent_id"] == zero).unwrap(); |
| 301 | let pending = rows.iter().find(|row| row["agent_id"] == pending).unwrap(); |
| 302 | assert_eq!(zero["total_tokens"], 0); |
| 303 | assert!(zero["needs_input"].is_null()); |
| 304 | assert!(pending["total_tokens"].is_null()); |
| 305 | assert_eq!(pending["needs_input"], "Approve the next validation step?"); |
| 306 | assert_eq!(pending["needs_continuation"], true); |
| 307 | assert_eq!(payload["usage"]["total_tokens"], 0); |
| 308 | assert_eq!(payload["usage"]["reported_workers"], 1); |
| 309 | let empty = SubAgentManager::new(dir.path().join("empty"), 1); |
| 310 | let empty = lifecycle::compact_roster(&empty, &json!({}), "workspace", false, false).unwrap(); |
| 311 | assert_eq!(empty["columns"], payload["columns"]); |
| 312 | assert!(status_rows(&empty).is_empty()); |
| 313 | |
| 314 | let mut settling = SubAgentManager::new(dir.path().join("settling"), 1); |
| 315 | let worker = settling.insert_test_running_agent("worker", dir.path()); |
| 316 | let record = settling.worker_records.get_mut(&worker).unwrap(); |
| 317 | record.usage.total_tokens = Some(7); |
| 318 | for (agent_status, worker_status, complete) in [ |
| 319 | (SubAgentStatus::Running, AgentWorkerStatus::Running, false), |
| 320 | ( |
| 321 | SubAgentStatus::Completed, |
| 322 | AgentWorkerStatus::WaitingForUser, |
| 323 | false, |
| 324 | ), |
| 325 | ( |
| 326 | SubAgentStatus::Completed, |
| 327 | AgentWorkerStatus::Completed, |
| 328 | true, |
| 329 | ), |
| 330 | ] { |
| 331 | settling.agents.get_mut(&worker).unwrap().status = agent_status; |
| 332 | settling.worker_records.get_mut(&worker).unwrap().status = worker_status; |
| 333 | let payload = |
| 334 | lifecycle::compact_roster(&settling, &json!({}), "workspace", false, false).unwrap(); |
| 335 | assert_eq!(payload["usage"]["complete"], complete); |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | #[tokio::test] |
| 340 | async fn lifecycle_addressed_status_follows_lineage_and_detail_is_bounded() { |
| 341 | let dir = tempdir().unwrap(); |
| 342 | let manager = new_shared_subagent_manager(dir.path().to_path_buf(), 3); |
| 343 | let (old, latest) = { |
| 344 | let mut guard = manager.write().await; |
| 345 | guard |
| 346 | .with_store_transaction(|guard| { |
| 347 | let (old, _) = guard.insert_test_interrupted_continuable_agent( |
| 348 | "old", |
| 349 | dir.path(), |
| 350 | prior_messages(), |
| 351 | ); |
| 352 | let latest = guard.insert_test_running_agent("latest", dir.path()); |
| 353 | guard.resume_targets.insert(old.clone(), latest.clone()); |
| 354 | guard.agents.get_mut(&latest).unwrap().result = Some("🐋".repeat(100_000)); |
| 355 | guard.persist_state_synchronously()?; |
| 356 | Ok((old, latest)) |
| 357 | }) |
| 358 | .unwrap() |
| 359 | }; |
| 360 | let context = ToolContext::new(dir.path()); |
| 361 | let roster = inspect_agent_from_input( |
| 362 | &json!({"action": "status"}), |
| 363 | Arc::clone(&manager), |
| 364 | &context, |
| 365 | false, |
| 366 | None, |
| 367 | ) |
| 368 | .await |
| 369 | .unwrap(); |
| 370 | let roster: Value = serde_json::from_str(&roster.content).unwrap(); |
| 371 | let rows = status_rows(&roster); |
| 372 | assert_eq!( |
| 373 | rows.iter().find(|row| row["agent_id"] == old).unwrap()["resumed_as"], |
| 374 | latest |
| 375 | ); |
| 376 | assert_eq!( |
| 377 | rows.iter().find(|row| row["agent_id"] == latest).unwrap()["resumed_from"], |
| 378 | old |
| 379 | ); |
| 380 | let result = inspect_agent_from_input( |
| 381 | &json!({"agent_id": old}), |
| 382 | Arc::clone(&manager), |
| 383 | &context, |
| 384 | false, |
| 385 | None, |
| 386 | ) |
| 387 | .await |
| 388 | .unwrap(); |
| 389 | let row: Value = serde_json::from_str(&result.content).unwrap(); |
| 390 | assert_eq!(row["agent_id"], latest); |
| 391 | assert_eq!(row["addressed_agent_id"], old); |
| 392 | assert_eq!(row["resumed_from"], old); |
| 393 | assert!(row.get("snapshot").is_none()); |
| 394 | let detail = inspect_agent_from_input( |
| 395 | &json!({"agent_id": old, "detail": true}), |
| 396 | manager, |
| 397 | &context, |
| 398 | false, |
| 399 | None, |
| 400 | ) |
| 401 | .await |
| 402 | .unwrap(); |
| 403 | assert!(detail.content.len() <= 32 * 1024); |
| 404 | let row: Value = serde_json::from_str(&detail.content).unwrap(); |
| 405 | assert_eq!(row["detail_bounded"], true); |
| 406 | assert!(row["transcript_handle"].is_object()); |
| 407 | } |
| 408 | |
| 409 | #[tokio::test] |
| 410 | async fn lifecycle_named_cancel_stops_grandchildren_and_preserves_sibling() { |
| 411 | let dir = tempdir().unwrap(); |
| 412 | let mut manager = SubAgentManager::new(dir.path().to_path_buf(), 4); |
| 413 | let parent = manager.insert_test_running_agent("parent", dir.path()); |
| 414 | let child = manager.insert_test_running_agent("child", dir.path()); |
| 415 | let sibling = manager.insert_test_running_agent("sibling", dir.path()); |
| 416 | let record = manager.worker_records.get_mut(&child).unwrap(); |
| 417 | record.parent_run_id = Some(parent.clone()); |
| 418 | record.spec.parent_run_id = Some(parent.clone()); |
| 419 | manager |
| 420 | .cancel_agent_for_session("workspace", &parent) |
| 421 | .unwrap(); |
| 422 | assert_eq!( |
| 423 | manager.get_result(&child).unwrap().status, |
| 424 | SubAgentStatus::Cancelled |
| 425 | ); |
| 426 | assert_eq!( |
| 427 | manager.get_result(&parent).unwrap().status, |
| 428 | SubAgentStatus::Cancelled |
| 429 | ); |
| 430 | assert_eq!( |
| 431 | manager.get_result(&sibling).unwrap().status, |
| 432 | SubAgentStatus::Running |
| 433 | ); |
| 434 | } |
| 435 | |
| 436 | #[test] |
| 437 | fn lifecycle_recovery_never_forks_and_byte_preview_preserves_utf8() { |
| 438 | let instruction = subagent_followup_recovery("agent_parked"); |
| 439 | assert!(instruction.contains("action=\"followup\"")); |
| 440 | assert!(!instruction.contains("resume_from")); |
| 441 | let preview = lifecycle::text_preview(&"🐋".repeat(10_000), 65); |
| 442 | assert!(preview.len() <= 65); |
| 443 | assert!(preview.ends_with("...")); |
| 444 | } |
| 445 | |
| 446 | #[test] |
| 447 | fn lifecycle_park_event_sentinel_and_tool_share_recovery_instruction() { |
| 448 | let agent_id = "agent_parked"; |
| 449 | let instruction = subagent_followup_recovery(agent_id); |
| 450 | let parking = Arc::new(std::sync::atomic::AtomicBool::new(true)); |
| 451 | let (status, output, checkpoint, needs_input, _, _) = |
| 452 | subagent_cancellation_projection(agent_id, &prior_messages(), 1, None, Some(&parking)); |
| 453 | assert!(output.as_deref().unwrap().contains(&instruction)); |
| 454 | assert_eq!(needs_input.as_ref().unwrap().question, instruction); |
| 455 | |
| 456 | let mut result = super::tests::make_snapshot(status); |
| 457 | result.agent_id = agent_id.into(); |
| 458 | result.result = output; |
| 459 | result.checkpoint = checkpoint; |
| 460 | result.needs_input = needs_input; |
| 461 | let sentinel = subagent_done_sentinel(agent_id, &result, false); |
| 462 | let metadata: Value = serde_json::from_str( |
| 463 | sentinel |
| 464 | .strip_prefix("<codewhale:subagent.done>") |
| 465 | .unwrap() |
| 466 | .strip_suffix("</codewhale:subagent.done>") |
| 467 | .unwrap(), |
| 468 | ) |
| 469 | .unwrap(); |
| 470 | assert_eq!(metadata["needs_input"]["question"], instruction); |
| 471 | assert!(AGENT_TOOL_DESCRIPTION.contains(&subagent_followup_recovery("<agent_id>"))); |
| 472 | } |
| 473 | |
| 474 | #[tokio::test] |
| 475 | async fn lifecycle_followup_rechecks_actual_successor_authority() { |
| 476 | let dir = tempdir().unwrap(); |
| 477 | let manager = new_shared_subagent_manager(dir.path().to_path_buf(), 4); |
| 478 | let (caller, old, sibling) = { |
| 479 | let mut guard = manager.write().await; |
| 480 | let caller = guard.insert_test_running_agent("caller", dir.path()); |
| 481 | let (old, _) = guard.insert_test_interrupted_continuable_agent( |
| 482 | "own-child", |
| 483 | dir.path(), |
| 484 | prior_messages(), |
| 485 | ); |
| 486 | let sibling = guard.insert_test_running_agent("sibling", dir.path()); |
| 487 | let record = guard.worker_records.get_mut(&old).unwrap(); |
| 488 | record.parent_run_id = Some(caller.clone()); |
| 489 | record.spec.parent_run_id = Some(caller.clone()); |
| 490 | guard.resume_targets.insert(old.clone(), sibling.clone()); |
| 491 | (caller, old, sibling) |
| 492 | }; |
| 493 | let tool = |
| 494 | coord::AgentsFollowupTool::new(Arc::clone(&manager)).with_optional_caller(Some(caller)); |
| 495 | assert!( |
| 496 | tool.execute( |
| 497 | json!({"agent_id": old, "message": "Try to wake sibling"}), |
| 498 | &ToolContext::new(dir.path()) |
| 499 | ) |
| 500 | .await |
| 501 | .is_err() |
| 502 | ); |
| 503 | assert!(!manager.read().await.child_was_woken(&sibling)); |
| 504 | } |
| 505 | |
| 506 | #[tokio::test] |
| 507 | async fn lifecycle_deliverable_preview_reports_omissions_and_detail_pages_the_full_list() { |
| 508 | let dir = tempdir().unwrap(); |
| 509 | let mut manager = SubAgentManager::new(dir.path().to_path_buf(), 2); |
| 510 | let id = manager.insert_test_running_agent("outputs", dir.path()); |
| 511 | manager |
| 512 | .worker_records |
| 513 | .get_mut(&id) |
| 514 | .unwrap() |
| 515 | .verification |
| 516 | .deliverables = (0..9) |
| 517 | .map(|index| DeliverableVerdict { |
| 518 | path: format!("report-{index}.md"), |
| 519 | status: if index == 8 { |
| 520 | "missing".into() |
| 521 | } else { |
| 522 | "present".into() |
| 523 | }, |
| 524 | bytes: (index != 8).then_some(20), |
| 525 | }) |
| 526 | .collect(); |
| 527 | let compact = lifecycle::compact_row(&manager, &manager.agents[&id]); |
| 528 | assert_eq!(compact["verification"]["deliverables_total"], 9); |
| 529 | assert_eq!(compact["verification"]["deliverables_omitted"], 5); |
| 530 | assert_eq!(compact["verification"]["deliverable_counts"]["missing"], 1); |
| 531 | assert_eq!( |
| 532 | compact["verification"]["deliverables"][0]["status"], |
| 533 | "missing" |
| 534 | ); |
| 535 | let detail = lifecycle::bounded_detail( |
| 536 | json!({"verification": manager.worker_records[&id].verification}), |
| 537 | compact, |
| 538 | 4, |
| 539 | 2, |
| 540 | ); |
| 541 | assert_eq!( |
| 542 | detail["verification"]["deliverables"] |
| 543 | .as_array() |
| 544 | .unwrap() |
| 545 | .len(), |
| 546 | 2 |
| 547 | ); |
| 548 | assert_eq!( |
| 549 | detail["verification"]["deliverables"][0]["path"], |
| 550 | "report-4.md" |
| 551 | ); |
| 552 | assert_eq!(detail["verification"]["deliverables_next_offset"], 6); |
| 553 | } |
| 554 | |
| 555 | #[test] |
| 556 | fn lifecycle_oversized_event_pages_return_every_sequence_once() { |
| 557 | let expected: Vec<u64> = (1..=25).collect(); |
| 558 | let events: Vec<Value> = expected |
| 559 | .iter() |
| 560 | .map(|seq| { |
| 561 | json!({ |
| 562 | "seq": seq, |
| 563 | "status": "running_tool", |
| 564 | "timestamp_ms": 1_700_000_000_000_u64, |
| 565 | "message": "\u{0001}".repeat(160), |
| 566 | "tool_name": "x".repeat(64), |
| 567 | }) |
| 568 | }) |
| 569 | .collect(); |
| 570 | let projection = json!({"worker_record": {"events": events}}); |
| 571 | for (path_bytes, first_page_len) in [(0, 4), (6000, 1), (10000, 1)] { |
| 572 | let compact = json!({ |
| 573 | "agent_id": "agent-test", |
| 574 | "write_progress": {"declared": ["x".repeat(path_bytes)]}, |
| 575 | }); |
| 576 | let mut seen = Vec::new(); |
| 577 | loop { |
| 578 | let offset = seen.len(); |
| 579 | let detail = lifecycle::bounded_detail(projection.clone(), compact.clone(), offset, 20); |
| 580 | let result = lifecycle::status_result(detail, false).unwrap(); |
| 581 | assert!(result.content.len() <= 8192); |
| 582 | let page: Value = serde_json::from_str(&result.content).unwrap(); |
| 583 | let rows = page["recent_events"].as_array().unwrap(); |
| 584 | assert!(!rows.is_empty()); |
| 585 | if offset == 0 { |
| 586 | assert_eq!(rows.len(), first_page_len); |
| 587 | } |
| 588 | assert_eq!(page["events_total"], expected.len()); |
| 589 | seen.extend(rows.iter().map(|row| row["seq"].as_u64().unwrap())); |
| 590 | let Some(next) = page["events_next_offset"].as_u64() else { |
| 591 | break; |
| 592 | }; |
| 593 | assert_eq!(next as usize, seen.len()); |
| 594 | assert!(seen.len() < expected.len()); |
| 595 | } |
| 596 | assert_eq!(seen, expected); |
| 597 | } |
| 598 | |
| 599 | let last_page = |bytes| { |
| 600 | lifecycle::bounded_detail( |
| 601 | projection.clone(), |
| 602 | json!({"agent_id":"agent-test","write_progress":{"declared":["x".repeat(bytes)]}}), |
| 603 | expected.len() - 1, |
| 604 | 20, |
| 605 | ) |
| 606 | }; |
| 607 | let available = 8192 - serde_json::to_vec(&last_page(0)).unwrap().len(); |
| 608 | let result = lifecycle::status_result(last_page(available), false).unwrap(); |
| 609 | assert!(result.content.len() <= 8192); |
| 610 | let page: Value = serde_json::from_str(&result.content).unwrap(); |
| 611 | assert_eq!(page["recent_events"][0]["seq"], 25); |
| 612 | assert!(page.get("events_next_offset").is_none()); |
| 613 | |
| 614 | for (session_bytes, keeps_handle) in [(7200, true), (9000, false)] { |
| 615 | let mut with_handle = projection.clone(); |
| 616 | with_handle["transcript_handle"] = json!({ |
| 617 | "kind": "var_handle", "session_id": "s".repeat(session_bytes), |
| 618 | "name": "transcript", "type": "json", "length": 7, "repr_preview": "", |
| 619 | "sha256": "a".repeat(64), |
| 620 | }); |
| 621 | let detail = lifecycle::bounded_detail( |
| 622 | with_handle.clone(), |
| 623 | json!({"agent_id":"agent-test","summary":"x".repeat(7600)}), |
| 624 | 0, |
| 625 | 20, |
| 626 | ); |
| 627 | let result = lifecycle::status_result(detail, false).unwrap(); |
| 628 | assert!(result.content.len() <= 8192); |
| 629 | let page: Value = serde_json::from_str(&result.content).unwrap(); |
| 630 | assert_eq!(page["recent_events"][0]["seq"], 1); |
| 631 | assert_eq!(page["recent_events"][0]["detail_omitted"], true); |
| 632 | assert_eq!(page["events_next_offset"], 1); |
| 633 | assert_eq!(page["agent_id"], "agent-test"); |
| 634 | if keeps_handle { |
| 635 | assert_eq!(page["transcript_handle"], with_handle["transcript_handle"]); |
| 636 | } else { |
| 637 | assert!(page.get("transcript_handle").is_none()); |
| 638 | assert_eq!(page["transcript_handle_omitted"], true); |
| 639 | } |
| 640 | } |
| 641 | } |
| 642 | |
| 643 | #[tokio::test] |
| 644 | async fn lifecycle_running_row_reports_declared_vs_observed_writes() { |
| 645 | // #6194 item 5: the parent sees the declared/observed write diff while |
| 646 | // the child is still alive, not only in the post-mortem receipt. |
| 647 | let dir = tempdir().unwrap(); |
| 648 | let mut manager = SubAgentManager::new(dir.path().to_path_buf(), 2); |
| 649 | let id = manager.insert_test_running_agent("writer", dir.path()); |
| 650 | { |
| 651 | let record = manager.worker_records.get_mut(&id).unwrap(); |
| 652 | record.spec.runtime_profile.permissions.write = true; |
| 653 | record.spec.launch_manifest = Some(ChildLaunchManifest { |
| 654 | activation: None, |
| 655 | owner_session: "root".to_string(), |
| 656 | child_id: id.clone(), |
| 657 | profile: record.spec.runtime_profile.clone(), |
| 658 | prompt: record.spec.objective.clone(), |
| 659 | cwd: None, |
| 660 | worktree: false, |
| 661 | writable_roots: Vec::new(), |
| 662 | writable_files: Vec::new(), |
| 663 | coordination_contracts: Vec::new(), |
| 664 | expected_artifact: None, |
| 665 | deliverables: vec!["a.rs".to_string(), "b.rs".to_string()], |
| 666 | resume_identity: None, |
| 667 | generation: 1, |
| 668 | resume_from_agent_id: None, |
| 669 | }); |
| 670 | record |
| 671 | .delivery_evidence |
| 672 | .observed_writes |
| 673 | .insert("b.rs".to_string()); |
| 674 | record |
| 675 | .delivery_evidence |
| 676 | .observed_writes |
| 677 | .insert("surprise.rs".to_string()); |
| 678 | } |
| 679 | let row = lifecycle::compact_row(&manager, &manager.agents[&id]); |
| 680 | assert_eq!(row["write_progress"]["declared_total"], 2); |
| 681 | assert_eq!(row["write_progress"]["observed_total"], 2); |
| 682 | assert_eq!(row["write_progress"]["declared"][0], "a.rs"); |
| 683 | assert_eq!(row["write_progress"]["observed"][1], "surprise.rs"); |
| 684 | } |
| 685 | |
| 686 | #[tokio::test] |
| 687 | async fn lifecycle_read_only_row_omits_write_progress() { |
| 688 | let dir = tempdir().unwrap(); |
| 689 | let mut manager = SubAgentManager::new(dir.path().to_path_buf(), 2); |
| 690 | let id = manager.insert_test_running_agent("scout", dir.path()); |
| 691 | let row = lifecycle::compact_row(&manager, &manager.agents[&id]); |
| 692 | assert!(row.get("write_progress").is_none()); |
| 693 | } |
| 694 | |
| 695 | #[tokio::test] |
| 696 | async fn lifecycle_continuation_link_is_durable_before_the_child_can_run() { |
| 697 | let dir = tempdir().unwrap(); |
| 698 | let base = dir.path().canonicalize().unwrap(); |
| 699 | let path = base.join(".codewhale/subagents/state.json"); |
| 700 | let manager = Arc::new(RwLock::new( |
| 701 | SubAgentManager::new(base.clone(), 4).with_state_path(path.clone()), |
| 702 | )); |
| 703 | let (client, calls, _, fixture_config) = |
| 704 | super::tests::delayed_chat_client(Duration::from_secs(30), "fixture").await; |
| 705 | let mut runtime = super::tests::stub_runtime(); |
| 706 | runtime.client = client; |
| 707 | runtime.api_config = Some(Arc::new(fixture_config)); |
| 708 | runtime.manager = Arc::clone(&manager); |
| 709 | runtime.context = ToolContext::new(&base); |
| 710 | let mut guard = manager.write().await; |
| 711 | let (source, _) = |
| 712 | guard.insert_test_interrupted_continuable_agent("durable-source", &base, prior_messages()); |
| 713 | guard.agents.get_mut(&source).unwrap().model = "deepseek-v4-flash".into(); |
| 714 | let record = guard.worker_records.get_mut(&source).unwrap(); |
| 715 | record.parent_run_id = None; |
| 716 | record.spec.parent_run_id = None; |
| 717 | guard |
| 718 | .worker_records |
| 719 | .get_mut(&source) |
| 720 | .unwrap() |
| 721 | .spec |
| 722 | .runtime_profile = WorkerRuntimeProfile::for_role(FleetRole::Scout); |
| 723 | assert!( |
| 724 | !guard.worker_records[&source] |
| 725 | .spec |
| 726 | .runtime_profile |
| 727 | .permissions |
| 728 | .write |
| 729 | ); |
| 730 | let successor = guard |
| 731 | .resume_from_checkpoint(Arc::clone(&manager), runtime, &source, "Continue") |
| 732 | .unwrap(); |
| 733 | // Holding the manager lock keeps run_subagent_task_inner at its first |
| 734 | // await. This is the earliest published snapshot, before any child step. |
| 735 | assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0); |
| 736 | let persisted: DurableSubAgentStore = |
| 737 | serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); |
| 738 | let persisted = persisted.state; |
| 739 | assert_eq!( |
| 740 | persisted.resume_targets.get(&source), |
| 741 | Some(&successor.agent_id) |
| 742 | ); |
| 743 | assert!( |
| 744 | persisted |
| 745 | .agents |
| 746 | .iter() |
| 747 | .any(|agent| agent.id == successor.agent_id) |
| 748 | ); |
| 749 | let _ = guard.cancel_agent(&successor.agent_id); |
| 750 | } |
| 751 | |
| 752 | #[tokio::test] |
| 753 | async fn lifecycle_continuation_persist_failure_rolls_back_worker_and_link() { |
| 754 | let dir = tempdir().unwrap(); |
| 755 | let base = dir.path().canonicalize().unwrap(); |
| 756 | let path = base.join(".codewhale/subagents/state.json"); |
| 757 | let manager = Arc::new(RwLock::new( |
| 758 | SubAgentManager::new(base.clone(), 4).with_state_path(path.clone()), |
| 759 | )); |
| 760 | let mut runtime = super::tests::stub_runtime(); |
| 761 | runtime.manager = Arc::clone(&manager); |
| 762 | runtime.context = ToolContext::new(&base); |
| 763 | let mut guard = manager.write().await; |
| 764 | let (source, _) = |
| 765 | guard.insert_test_interrupted_continuable_agent("failed-source", &base, prior_messages()); |
| 766 | guard.agents.get_mut(&source).unwrap().model = "deepseek-v4-flash".into(); |
| 767 | guard |
| 768 | .worker_records |
| 769 | .get_mut(&source) |
| 770 | .unwrap() |
| 771 | .spec |
| 772 | .runtime_profile = WorkerRuntimeProfile::for_role(FleetRole::Scout); |
| 773 | assert!( |
| 774 | !guard.worker_records[&source] |
| 775 | .spec |
| 776 | .runtime_profile |
| 777 | .permissions |
| 778 | .write |
| 779 | ); |
| 780 | guard.persist_state_synchronously().unwrap(); |
| 781 | let retained_path = path.with_extension("retained-before-failure"); |
| 782 | let result = guard.with_store_transaction(|held| { |
| 783 | std::fs::rename(&path, &retained_path)?; |
| 784 | std::fs::create_dir(&path)?; |
| 785 | let resumed = |
| 786 | held.resume_from_checkpoint(Arc::clone(&manager), runtime, &source, "Continue"); |
| 787 | std::fs::remove_dir(&path)?; |
| 788 | std::fs::rename(&retained_path, &path)?; |
| 789 | resumed |
| 790 | }); |
| 791 | assert!(result.is_err()); |
| 792 | assert_eq!(guard.agents.len(), 1); |
| 793 | assert_eq!(guard.worker_records.len(), 1); |
| 794 | assert!(guard.resume_targets.is_empty()); |
| 795 | assert!(matches!( |
| 796 | guard.get_result(&source).unwrap().status, |
| 797 | SubAgentStatus::Interrupted(_) |
| 798 | )); |
| 799 | } |
| 800 | |
| 801 | #[tokio::test] |
| 802 | async fn lifecycle_cancel_original_stops_its_continuation_and_existing_descendants() { |
| 803 | let dir = tempdir().unwrap(); |
| 804 | let mut manager = SubAgentManager::new(dir.path().to_path_buf(), 5); |
| 805 | let (source, _) = |
| 806 | manager.insert_test_interrupted_continuable_agent("original", dir.path(), prior_messages()); |
| 807 | let current = manager.insert_test_running_agent("current", dir.path()); |
| 808 | let child = manager.insert_test_running_agent("existing-child", dir.path()); |
| 809 | let sibling = manager.insert_test_running_agent("separate-fork", dir.path()); |
| 810 | manager |
| 811 | .resume_targets |
| 812 | .insert(source.clone(), current.clone()); |
| 813 | let record = manager.worker_records.get_mut(&child).unwrap(); |
| 814 | record.parent_run_id = Some(source.clone()); |
| 815 | record.spec.parent_run_id = Some(source.clone()); |
| 816 | |
| 817 | let cancelled = manager |
| 818 | .cancel_agent_for_session("workspace", &source) |
| 819 | .unwrap(); |
| 820 | assert_eq!(cancelled.agent_id, current); |
| 821 | assert_eq!(cancelled.status, SubAgentStatus::Cancelled); |
| 822 | assert_eq!( |
| 823 | manager.get_result(&child).unwrap().status, |
| 824 | SubAgentStatus::Cancelled |
| 825 | ); |
| 826 | assert_eq!( |
| 827 | manager.get_result(&sibling).unwrap().status, |
| 828 | SubAgentStatus::Running |
| 829 | ); |
| 830 | assert!(matches!( |
| 831 | manager.get_result(&source).unwrap().status, |
| 832 | SubAgentStatus::Interrupted(_) |
| 833 | )); |
| 834 | } |
| 835 | |
| 836 | #[tokio::test] |
| 837 | async fn lifecycle_resumed_parent_controls_existing_descendants_but_never_itself_or_siblings() { |
| 838 | let dir = tempdir().unwrap(); |
| 839 | let mut manager = SubAgentManager::new(dir.path().to_path_buf(), 5); |
| 840 | let (source, _) = |
| 841 | manager.insert_test_interrupted_continuable_agent("original", dir.path(), prior_messages()); |
| 842 | let current = manager.insert_test_running_agent("current", dir.path()); |
| 843 | let child = manager.insert_test_running_agent("existing-child", dir.path()); |
| 844 | let sibling = manager.insert_test_running_agent("sibling", dir.path()); |
| 845 | manager |
| 846 | .resume_targets |
| 847 | .insert(source.clone(), current.clone()); |
| 848 | let record = manager.worker_records.get_mut(&child).unwrap(); |
| 849 | record.parent_run_id = Some(source.clone()); |
| 850 | record.spec.parent_run_id = Some(source.clone()); |
| 851 | assert!( |
| 852 | manager |
| 853 | .continuation_target_for_caller("workspace", &child, Some(¤t), "test") |
| 854 | .is_ok() |
| 855 | ); |
| 856 | for forbidden in [&source, ¤t, &sibling] { |
| 857 | assert!( |
| 858 | manager |
| 859 | .continuation_target_for_caller("workspace", forbidden, Some(¤t), "test") |
| 860 | .is_err() |
| 861 | ); |
| 862 | } |
| 863 | |
| 864 | // A corrupt source→sibling link must not turn source authority into |
| 865 | // permission to cancel the unrelated actual successor. |
| 866 | manager |
| 867 | .resume_targets |
| 868 | .insert(child.clone(), sibling.clone()); |
| 869 | let manager = Arc::new(RwLock::new(manager)); |
| 870 | assert!( |
| 871 | cancel_agent_from_input( |
| 872 | &json!({"agent_id": child}), |
| 873 | Arc::clone(&manager), |
| 874 | &ToolContext::new(dir.path()), |
| 875 | Some(¤t), |
| 876 | ) |
| 877 | .await |
| 878 | .is_err() |
| 879 | ); |
| 880 | assert_eq!( |
| 881 | manager.read().await.get_result(&sibling).unwrap().status, |
| 882 | SubAgentStatus::Running |
| 883 | ); |
| 884 | } |
| 885 | |
| 886 | #[tokio::test] |
| 887 | async fn lifecycle_detail_budget_keeps_the_transcript_handle_retrievable() { |
| 888 | let dir = tempdir().unwrap(); |
| 889 | let context = ToolContext::new(dir.path()); |
| 890 | let mut manager = SubAgentManager::new(dir.path().to_path_buf(), 2); |
| 891 | let id = manager.insert_test_running_agent("large-checkpoint", dir.path()); |
| 892 | let messages = (0..20) |
| 893 | .map(|_| Message { |
| 894 | role: Role::User, |
| 895 | content: vec![ContentBlock::Text { |
| 896 | text: "🐋".repeat(1024), |
| 897 | cache_control: None, |
| 898 | }], |
| 899 | }) |
| 900 | .collect::<Vec<_>>(); |
| 901 | manager.agents.get_mut(&id).unwrap().checkpoint = Some(build_subagent_checkpoint( |
| 902 | &id, "retained", &messages, 1, true, |
| 903 | )); |
| 904 | let projection = subagent_session_projection( |
| 905 | &new_shared_subagent_manager(dir.path().to_path_buf(), 1), |
| 906 | manager.get_result(&id).unwrap(), |
| 907 | false, |
| 908 | &context, |
| 909 | manager.get_worker_record_for_session("workspace", &id), |
| 910 | ) |
| 911 | .await; |
| 912 | let expected = projection.transcript_handle.clone(); |
| 913 | let detail = lifecycle::bounded_detail( |
| 914 | serde_json::to_value(projection).unwrap(), |
| 915 | lifecycle::compact_row(&manager, &manager.agents[&id]), |
| 916 | 0, |
| 917 | 20, |
| 918 | ); |
| 919 | assert!(serde_json::to_vec(&detail).unwrap().len() <= 32 * 1024); |
| 920 | let handle: VarHandle = serde_json::from_value(detail["transcript_handle"].clone()).unwrap(); |
| 921 | assert_eq!(handle.session_id, expected.session_id); |
| 922 | assert_eq!(handle.name, expected.name); |
| 923 | assert_eq!(handle.sha256, expected.sha256); |
| 924 | assert!( |
| 925 | context |
| 926 | .runtime |
| 927 | .handle_store |
| 928 | .lock() |
| 929 | .await |
| 930 | .get(&handle) |
| 931 | .is_some() |
| 932 | ); |
| 933 | } |
| 934 | |
| 935 | #[tokio::test] |
| 936 | async fn lifecycle_cleanup_keeps_source_identity_while_descendants_still_need_it() { |
| 937 | let dir = tempdir().unwrap(); |
| 938 | let mut manager = SubAgentManager::new(dir.path().to_path_buf(), 5); |
| 939 | let source = manager.insert_test_running_agent("original", dir.path()); |
| 940 | let current = manager.insert_test_running_agent("continuation", dir.path()); |
| 941 | let child = manager.insert_test_running_agent("existing-child", dir.path()); |
| 942 | manager |
| 943 | .resume_targets |
| 944 | .insert(source.clone(), current.clone()); |
| 945 | let record = manager.worker_records.get_mut(&child).unwrap(); |
| 946 | record.parent_run_id = Some(source.clone()); |
| 947 | record.spec.parent_run_id = Some(source.clone()); |
| 948 | let old = Instant::now() - Duration::from_secs(120); |
| 949 | let old_ms = epoch_millis_now().saturating_sub(120_000); |
| 950 | let source_agent = manager.agents.get_mut(&source).unwrap(); |
| 951 | source_agent.status = SubAgentStatus::Completed; |
| 952 | source_agent.started_at = old; |
| 953 | source_agent.persisted_updated_at_ms = old_ms; |
| 954 | let record = manager.worker_records.get_mut(&source).unwrap(); |
| 955 | record.status = AgentWorkerStatus::Completed; |
| 956 | record.completed_at_ms = Some(old_ms); |
| 957 | |
| 958 | manager |
| 959 | .cleanup_for_session("workspace", Duration::from_secs(60)) |
| 960 | .expect("durable worker operation"); |
| 961 | assert_eq!(manager.continuation_target(&source).unwrap(), current); |
| 962 | assert!( |
| 963 | manager |
| 964 | .continuation_target_for_caller("workspace", &child, Some(¤t), "test") |
| 965 | .is_ok() |
| 966 | ); |
| 967 | manager |
| 968 | .cancel_agent_for_session("workspace", &source) |
| 969 | .unwrap(); |
| 970 | assert_eq!( |
| 971 | manager.get_result(&child).unwrap().status, |
| 972 | SubAgentStatus::Cancelled |
| 973 | ); |
| 974 | |
| 975 | // Once no live work uses either projection, normal expiry reclaims the |
| 976 | // archived workers and their continuation edge together. |
| 977 | let old_ms = epoch_millis_now().saturating_sub(120_000); |
| 978 | for agent in manager.agents.values_mut() { |
| 979 | agent.started_at = old; |
| 980 | agent.persisted_updated_at_ms = old_ms; |
| 981 | } |
| 982 | for record in manager.worker_records.values_mut() { |
| 983 | record.completed_at_ms = Some(old_ms); |
| 984 | } |
| 985 | manager |
| 986 | .cleanup_for_session("workspace", Duration::from_secs(60)) |
| 987 | .expect("durable worker operation"); |
| 988 | assert!(manager.agents.is_empty()); |
| 989 | assert!(manager.worker_records.is_empty()); |
| 990 | assert!(manager.resume_targets.is_empty()); |
| 991 | } |
| 992 | |
| 993 | #[test] |
| 994 | fn reasoning_override_note_names_requested_and_effective_tiers() { |
| 995 | let mut route = ChildRouteReceipt { |
| 996 | requested_type: "explore".into(), |
| 997 | requested_profile: Some("scout".into()), |
| 998 | resolved_profile_id: Some("scout".into()), |
| 999 | profile_origin: Some("workspace".into()), |
| 1000 | canonical_role: "explore".into(), |
| 1001 | provider_id: "gemini".into(), |
| 1002 | model_id: "gemini-4".into(), |
| 1003 | route_source: "profile.model".into(), |
| 1004 | fallback_note: None, |
| 1005 | requested_reasoning: "xhigh".into(), |
| 1006 | effective_reasoning: Some("high".into()), |
| 1007 | runtime_version: "0.10.3".into(), |
| 1008 | runtime_build_sha: "unknown".into(), |
| 1009 | }; |
| 1010 | assert_eq!( |
| 1011 | lifecycle::reasoning_override_note(&route).as_deref(), |
| 1012 | Some( |
| 1013 | "requested thinking 'xhigh' runs as 'high' on gemini/gemini-4 (route ceiling; profile 'scout')" |
| 1014 | ) |
| 1015 | ); |
| 1016 | route.resolved_profile_id = None; |
| 1017 | assert_eq!( |
| 1018 | lifecycle::reasoning_override_note(&route).as_deref(), |
| 1019 | Some("requested thinking 'xhigh' runs as 'high' on gemini/gemini-4 (route ceiling)") |
| 1020 | ); |
| 1021 | route.effective_reasoning = None; |
| 1022 | assert_eq!( |
| 1023 | lifecycle::reasoning_override_note(&route).as_deref(), |
| 1024 | Some("requested thinking 'xhigh' is not sent; gemini/gemini-4 has no reasoning tier") |
| 1025 | ); |
| 1026 | route.effective_reasoning = Some("xhigh".into()); |
| 1027 | assert_eq!(lifecycle::reasoning_override_note(&route), None); |
| 1028 | route.requested_reasoning = "inherit".into(); |
| 1029 | route.effective_reasoning = Some("low".into()); |
| 1030 | assert_eq!(lifecycle::reasoning_override_note(&route), None); |
| 1031 | } |
| 1032 | |
| 1033 | #[tokio::test] |
| 1034 | async fn lifecycle_start_peek_and_status_detail_preserve_fields_and_strip_checkpoint_bloat() { |
| 1035 | let dir = tempdir().unwrap(); |
| 1036 | let manager = new_shared_subagent_manager(dir.path().to_path_buf(), 4); |
| 1037 | let (client, _, _, fixture_config) = |
| 1038 | super::tests::delayed_chat_client(Duration::from_secs(30), "done").await; |
| 1039 | let context = ToolContext::new(dir.path()).with_state_namespace("lifecycle-view-session"); |
| 1040 | let mut runtime = super::tests::stub_runtime(); |
| 1041 | runtime.client = client; |
| 1042 | runtime.api_config = Some(Arc::new(fixture_config)); |
| 1043 | runtime.manager = Arc::clone(&manager); |
| 1044 | runtime.context = context.clone(); |
| 1045 | let _cancel_on_drop = runtime.cancel_token.clone().drop_guard(); |
| 1046 | |
| 1047 | let tool = AgentTool::new(Arc::clone(&manager), runtime); |
| 1048 | let started = tool |
| 1049 | .execute( |
| 1050 | json!({ |
| 1051 | "action": "start", |
| 1052 | "type": "explore", |
| 1053 | "name": "scout-view", |
| 1054 | "prompt": "inspect the harness" |
| 1055 | }), |
| 1056 | &context, |
| 1057 | ) |
| 1058 | .await |
| 1059 | .expect("start succeeds"); |
| 1060 | let start_view = crate::core::engine::tool_result_context_view( |
| 1061 | codewhale_config::ProviderKind::Deepseek, |
| 1062 | "deepseek-v3.2-128k", |
| 1063 | None, |
| 1064 | "agent", |
| 1065 | &started, |
| 1066 | ); |
| 1067 | assert!(!start_view.needs_full_output_artifact); |
| 1068 | assert!(!start_view.text.contains("Child results are self-reports")); |
| 1069 | assert!( |
| 1070 | !start_view |
| 1071 | .text |
| 1072 | .contains("[sub-agent result summarized for parent context]") |
| 1073 | ); |
| 1074 | let start_json: Value = serde_json::from_str(&start_view.text).unwrap(); |
| 1075 | let agent_id = start_json["agent_id"].as_str().unwrap().to_string(); |
| 1076 | assert_eq!(start_json["action"], "start"); |
| 1077 | assert_eq!(start_json["role"], "explore"); |
| 1078 | assert_eq!(start_json["name"], "scout-view"); |
| 1079 | assert_eq!(start_json["status"], "running"); |
| 1080 | assert_eq!( |
| 1081 | start_json["effective_limits"]["max_steps"], |
| 1082 | WorkerRuntimeProfile::EXPLORE_MAX_STEPS |
| 1083 | ); |
| 1084 | assert!(start_json["transcript_handle"].is_object()); |
| 1085 | |
| 1086 | let child = manager |
| 1087 | .write() |
| 1088 | .await |
| 1089 | .agents |
| 1090 | .get_mut(&agent_id) |
| 1091 | .and_then(|agent| agent.task_handle.take()) |
| 1092 | .expect("started child has a task"); |
| 1093 | child.abort(); |
| 1094 | if let Err(error) = child.await { |
| 1095 | assert!(error.is_cancelled(), "started child panicked: {error}"); |
| 1096 | } |
| 1097 | |
| 1098 | let giant_sig = "SIG_BASE64_".repeat(500); |
| 1099 | { |
| 1100 | let mut guard = manager.write().await; |
| 1101 | let agent = guard.agents.get_mut(&agent_id).unwrap(); |
| 1102 | agent.status = SubAgentStatus::Running; |
| 1103 | agent.steps_taken = 4; |
| 1104 | agent.checkpoint = Some(build_subagent_checkpoint( |
| 1105 | &agent_id, |
| 1106 | "checkpointed", |
| 1107 | &[Message { |
| 1108 | role: Role::Assistant, |
| 1109 | content: vec![ |
| 1110 | ContentBlock::Thinking { |
| 1111 | thinking: "deep thoughts".into(), |
| 1112 | signature: Some(giant_sig.clone()), |
| 1113 | state: None, |
| 1114 | redacted_data: None, |
| 1115 | }, |
| 1116 | ContentBlock::ToolUse { |
| 1117 | id: "call-1".into(), |
| 1118 | execution_id: None, |
| 1119 | name: "read".into(), |
| 1120 | input: json!({"path": "Cargo.toml"}), |
| 1121 | caller: None, |
| 1122 | thought_signature: Some(giant_sig.clone()), |
| 1123 | }, |
| 1124 | ], |
| 1125 | }], |
| 1126 | 4, |
| 1127 | true, |
| 1128 | )); |
| 1129 | let record = guard.worker_records.get_mut(&agent_id).unwrap(); |
| 1130 | record.usage.input_tokens = Some(1200); |
| 1131 | record.usage.output_tokens = Some(250); |
| 1132 | record.usage.total_tokens = Some(1450); |
| 1133 | record.latest_message = Some("reading Cargo.toml".into()); |
| 1134 | record.events.clear(); |
| 1135 | for i in 0..120_u64 { |
| 1136 | record.events.push_back(AgentWorkerEvent { |
| 1137 | seq: i + 1, |
| 1138 | worker_id: agent_id.clone(), |
| 1139 | status: AgentWorkerStatus::RunningTool, |
| 1140 | timestamp_ms: 1_700_000_000_000 + i, |
| 1141 | message: Some(format!("step event {i}")), |
| 1142 | step: Some(4), |
| 1143 | tool_name: Some("read".into()), |
| 1144 | }); |
| 1145 | } |
| 1146 | guard.persist_state_synchronously().unwrap(); |
| 1147 | } |
| 1148 | |
| 1149 | let peek = tool |
| 1150 | .execute(json!({"action": "peek", "agent_id": agent_id}), &context) |
| 1151 | .await |
| 1152 | .expect("peek succeeds"); |
| 1153 | let peek_view = crate::core::engine::tool_result_context_view( |
| 1154 | codewhale_config::ProviderKind::Deepseek, |
| 1155 | "deepseek-v3.2-128k", |
| 1156 | None, |
| 1157 | "agent", |
| 1158 | &peek, |
| 1159 | ); |
| 1160 | assert!(!peek_view.needs_full_output_artifact); |
| 1161 | assert!(!peek_view.text.contains("Child results are self-reports")); |
| 1162 | let peek_json: Value = serde_json::from_str(&peek_view.text).unwrap(); |
| 1163 | assert_eq!(peek_json["agent_id"], agent_id); |
| 1164 | assert_eq!(peek_json["role"], "explore"); |
| 1165 | assert_eq!(peek_json["steps"], 4); |
| 1166 | assert!(peek_json["duration_ms"].is_u64()); |
| 1167 | assert_eq!(peek_json["activity"], "reading Cargo.toml"); |
| 1168 | assert_eq!(peek_json["usage"]["total_tokens"], 1450); |
| 1169 | assert!(peek_json["transcript_handle"].is_object()); |
| 1170 | assert_eq!(peek_json["events_total"], 120); |
| 1171 | assert_eq!(peek_json["recent_events"].as_array().unwrap().len(), 8); |
| 1172 | assert_eq!(peek_json["recent_events"][7]["seq"], 120); |
| 1173 | |
| 1174 | let detail = tool |
| 1175 | .execute( |
| 1176 | json!({"action": "status", "agent_id": agent_id, "detail": true}), |
| 1177 | &context, |
| 1178 | ) |
| 1179 | .await |
| 1180 | .expect("status detail succeeds"); |
| 1181 | assert!(detail.content.len() <= 8 * 1024, "{}", detail.content.len()); |
| 1182 | assert!(!detail.content.contains("SIG_BASE64_")); |
| 1183 | assert!(!detail.content.contains("thought_signature")); |
| 1184 | let detail_view = crate::core::engine::tool_result_context_view( |
| 1185 | codewhale_config::ProviderKind::Deepseek, |
| 1186 | "deepseek-v3.2-128k", |
| 1187 | None, |
| 1188 | "agent", |
| 1189 | &detail, |
| 1190 | ); |
| 1191 | assert!(!detail_view.needs_full_output_artifact); |
| 1192 | assert!(!detail_view.text.contains("Child results are self-reports")); |
| 1193 | let detail_json: Value = serde_json::from_str(&detail_view.text).unwrap(); |
| 1194 | assert_eq!(detail_json["agent_id"], agent_id); |
| 1195 | assert_eq!(detail_json["role"], "explore"); |
| 1196 | assert_eq!(detail_json["steps"], 4); |
| 1197 | assert_eq!(detail_json["activity"], "reading Cargo.toml"); |
| 1198 | assert_eq!(detail_json["usage"]["total_tokens"], 1450); |
| 1199 | assert!(detail_json.get("checkpoint").is_none()); |
| 1200 | assert!(detail_json.get("snapshot").is_none()); |
| 1201 | assert!(detail_json.get("worker_record").is_none()); |
| 1202 | assert_eq!(detail_json["checkpoint_summary"]["message_count"], 1); |
| 1203 | assert_eq!(detail_json["events_total"], 120); |
| 1204 | let handle: VarHandle = |
| 1205 | serde_json::from_value(detail_json["transcript_handle"].clone()).unwrap(); |
| 1206 | assert!( |
| 1207 | context |
| 1208 | .runtime |
| 1209 | .handle_store |
| 1210 | .lock() |
| 1211 | .await |
| 1212 | .get(&handle) |
| 1213 | .is_some() |
| 1214 | ); |
| 1215 | } |
| 1216 | |
| 1217 | #[tokio::test] |
| 1218 | async fn lifecycle_cancel_receipt_is_compact_and_suppresses_duplicate_parent_completion() { |
| 1219 | let dir = tempdir().unwrap(); |
| 1220 | let manager = new_shared_subagent_manager(dir.path().to_path_buf(), 4); |
| 1221 | let context = ToolContext::new(dir.path()).with_state_namespace("cancel-suppress-session"); |
| 1222 | let (completion_tx, mut completion_rx) = mpsc::channel::<SubAgentCompletion>(16); |
| 1223 | let (event_tx, mut event_rx) = mpsc::channel(16); |
| 1224 | let (mailbox, mut mailbox_rx) = Mailbox::new(CancellationToken::new()); |
| 1225 | |
| 1226 | let giant_sig = "SIG_BASE64_".repeat(500); |
| 1227 | let (cancelled_id, async_done_id) = { |
| 1228 | let mut guard = manager.write().await; |
| 1229 | let cancelled_id = "agent_cancel_compact".to_string(); |
| 1230 | let async_done_id = "agent_async_finish".to_string(); |
| 1231 | for id in [&cancelled_id, &async_done_id] { |
| 1232 | let (input_tx, _input_rx) = mpsc::unbounded_channel(); |
| 1233 | let mut agent = SubAgent::new( |
| 1234 | id.clone(), |
| 1235 | FleetRole::Scout, |
| 1236 | "explore repo".into(), |
| 1237 | SubAgentAssignment::new("explore repo".into(), None), |
| 1238 | "deepseek-v4-flash".into(), |
| 1239 | None, |
| 1240 | None, |
| 1241 | input_tx, |
| 1242 | dir.path().to_path_buf(), |
| 1243 | guard.current_session_boot_id.clone(), |
| 1244 | ); |
| 1245 | agent.owner_session_id = "cancel-suppress-session".into(); |
| 1246 | agent.steps_taken = 9; |
| 1247 | agent.checkpoint = Some(build_subagent_checkpoint( |
| 1248 | id, |
| 1249 | "in-progress", |
| 1250 | &[Message { |
| 1251 | role: Role::Assistant, |
| 1252 | content: vec![ContentBlock::ToolUse { |
| 1253 | id: "c1".into(), |
| 1254 | execution_id: None, |
| 1255 | name: "read".into(), |
| 1256 | input: json!({"path": "README.md"}), |
| 1257 | caller: None, |
| 1258 | thought_signature: Some(giant_sig.clone()), |
| 1259 | }], |
| 1260 | }], |
| 1261 | 9, |
| 1262 | true, |
| 1263 | )); |
| 1264 | let mut delivery_runtime = super::tests::stub_runtime().child_runtime(); |
| 1265 | delivery_runtime.context = context.clone(); |
| 1266 | delivery_runtime.parent_completion_tx = Some(completion_tx.clone()); |
| 1267 | delivery_runtime.event_tx = Some(event_tx.clone()); |
| 1268 | delivery_runtime.mailbox = Some(mailbox.clone()); |
| 1269 | agent.terminal_delivery = Some(SubAgentTerminalDeliveryContext::from_runtime( |
| 1270 | &delivery_runtime, |
| 1271 | )); |
| 1272 | guard.agents.insert(id.clone(), agent); |
| 1273 | let mut spec = super::tests::make_worker_spec(id, dir.path().to_path_buf()); |
| 1274 | spec.agent_type = FleetRole::Scout; |
| 1275 | guard.register_worker_for_session(spec, "cancel-suppress-session", None); |
| 1276 | let record = guard.worker_records.get_mut(id).unwrap(); |
| 1277 | record.usage.input_tokens = Some(5000); |
| 1278 | record.usage.output_tokens = Some(800); |
| 1279 | record.usage.total_tokens = Some(5800); |
| 1280 | if id == &cancelled_id { |
| 1281 | for seq in 1..=6000_u64 { |
| 1282 | record.events.push_back(AgentWorkerEvent { |
| 1283 | seq, |
| 1284 | worker_id: id.clone(), |
| 1285 | status: AgentWorkerStatus::RunningTool, |
| 1286 | timestamp_ms: 1_700_000_000_000 + seq, |
| 1287 | message: Some(format!("event-{seq}")), |
| 1288 | step: Some(9), |
| 1289 | tool_name: Some("read".into()), |
| 1290 | }); |
| 1291 | } |
| 1292 | } |
| 1293 | } |
| 1294 | (cancelled_id, async_done_id) |
| 1295 | }; |
| 1296 | |
| 1297 | let tool = AgentTool::new(Arc::clone(&manager), super::tests::stub_runtime()); |
| 1298 | let cancel_result = tool |
| 1299 | .execute( |
| 1300 | json!({"action": "cancel", "agent_id": cancelled_id}), |
| 1301 | &context, |
| 1302 | ) |
| 1303 | .await |
| 1304 | .expect("cancel succeeds"); |
| 1305 | assert!( |
| 1306 | cancel_result.content.len() < lifecycle::COMPACT_CANCEL_BYTES, |
| 1307 | "cancel receipt must stay under 4 KiB, got {}B", |
| 1308 | cancel_result.content.len() |
| 1309 | ); |
| 1310 | assert!(!cancel_result.content.contains("SIG_BASE64_")); |
| 1311 | assert!(!cancel_result.content.contains("thought_signature")); |
| 1312 | let cancel_json: Value = serde_json::from_str(&cancel_result.content).unwrap(); |
| 1313 | assert_eq!(cancel_json["action"], "cancel"); |
| 1314 | assert_eq!(cancel_json["agent_id"], cancelled_id); |
| 1315 | assert_eq!(cancel_json["role"], "explore"); |
| 1316 | assert_eq!(cancel_json["status"], "cancelled"); |
| 1317 | assert_eq!(cancel_json["steps"], 9); |
| 1318 | assert_eq!(cancel_json["usage"]["total_tokens"], 5800); |
| 1319 | assert_eq!(cancel_json["cancelled_by_parent"], true); |
| 1320 | assert!(cancel_json["transcript_handle"].is_object()); |
| 1321 | |
| 1322 | assert!( |
| 1323 | completion_rx.try_recv().is_err(), |
| 1324 | "explicit parent cancel must not emit duplicate subagent_completion" |
| 1325 | ); |
| 1326 | let synthesized = manager |
| 1327 | .read() |
| 1328 | .await |
| 1329 | .terminal_results_excluding_for_session("cancel-suppress-session", &HashSet::new()); |
| 1330 | assert!( |
| 1331 | synthesized.is_empty(), |
| 1332 | "explicit parent cancel must not be synthesized into a duplicate completion turn" |
| 1333 | ); |
| 1334 | let host_event = event_rx.try_recv().expect("AgentComplete still emitted"); |
| 1335 | assert!(matches!( |
| 1336 | host_event, |
| 1337 | Event::AgentComplete { id, outcome: Some(SubAgentStatus::Cancelled), .. } |
| 1338 | if id == cancelled_id |
| 1339 | )); |
| 1340 | assert!(mailbox_rx.drain_available().iter().any(|env| { |
| 1341 | matches!(&env.message, MailboxMessage::Cancelled { agent_id, .. } if agent_id == &cancelled_id) |
| 1342 | })); |
| 1343 | |
| 1344 | let mut finished = manager.read().await.get_result(&async_done_id).unwrap(); |
| 1345 | finished.status = SubAgentStatus::Completed; |
| 1346 | finished.result = Some("finished async work".into()); |
| 1347 | finish_terminal_result_owned(Arc::clone(&manager), finished) |
| 1348 | .await |
| 1349 | .expect("async completion commits"); |
| 1350 | let delivered = completion_rx |
| 1351 | .try_recv() |
| 1352 | .expect("async completion must still deliver subagent_completion"); |
| 1353 | assert_eq!(delivered.agent_id, async_done_id); |
| 1354 | } |
| 1355 | |
| 1356 | #[tokio::test] |
| 1357 | async fn lifecycle_explore_caps_reasoning_and_strips_ungranted_mcp_server_instructions() { |
| 1358 | let home = tempdir().unwrap(); |
| 1359 | let owned_home = home.path().canonicalize().unwrap(); |
| 1360 | let _home = crate::test_support::SealedHome::at(&owned_home); |
| 1361 | let mut codex = super::tests::stub_runtime_for_provider("openai-codex"); |
| 1362 | codex.model = "gpt-5.5".to_string(); |
| 1363 | |
| 1364 | for parent_effort in [None, Some("high"), Some("xhigh"), Some("max")] { |
| 1365 | let mut rt = codex.clone(); |
| 1366 | rt.reasoning_effort = parent_effort.map(str::to_string); |
| 1367 | let route = worker_profile_subagent_assignment_route( |
| 1368 | &rt, |
| 1369 | &ModelRoute::Inherit, |
| 1370 | SubAgentThinking::Inherit, |
| 1371 | &FleetRole::Scout, |
| 1372 | ); |
| 1373 | assert_eq!( |
| 1374 | route.reasoning_effort.as_deref(), |
| 1375 | Some("medium"), |
| 1376 | "parent={parent_effort:?}" |
| 1377 | ); |
| 1378 | } |
| 1379 | |
| 1380 | let mut low_parent = codex.clone(); |
| 1381 | low_parent.reasoning_effort = Some("low".to_string()); |
| 1382 | let low_route = worker_profile_subagent_assignment_route( |
| 1383 | &low_parent, |
| 1384 | &ModelRoute::Inherit, |
| 1385 | SubAgentThinking::Inherit, |
| 1386 | &FleetRole::Scout, |
| 1387 | ); |
| 1388 | assert_eq!(low_route.reasoning_effort.as_deref(), Some("low")); |
| 1389 | |
| 1390 | let mut high_parent = codex.clone(); |
| 1391 | high_parent.reasoning_effort = Some("high".to_string()); |
| 1392 | let explicit_override = worker_profile_subagent_assignment_route( |
| 1393 | &high_parent, |
| 1394 | &ModelRoute::Inherit, |
| 1395 | SubAgentThinking::Effort(ReasoningEffort::High), |
| 1396 | &FleetRole::Scout, |
| 1397 | ); |
| 1398 | assert_eq!(explicit_override.reasoning_effort.as_deref(), Some("high")); |
| 1399 | |
| 1400 | let worker_route = worker_profile_subagent_assignment_route( |
| 1401 | &high_parent, |
| 1402 | &ModelRoute::Inherit, |
| 1403 | SubAgentThinking::Inherit, |
| 1404 | &FleetRole::Worker, |
| 1405 | ); |
| 1406 | assert_eq!(worker_route.reasoning_effort.as_deref(), Some("high")); |
| 1407 | |
| 1408 | let mut pool = crate::mcp::McpPool::new(codewhale_mcp::config::McpConfig::default()); |
| 1409 | pool.insert_test_connection("github", &["list_prs"], Some("GitHub guidance")); |
| 1410 | pool.insert_test_connection("linear", &["list_issues"], Some("Linear guidance")); |
| 1411 | pool.insert_test_connection( |
| 1412 | "computer-use", |
| 1413 | &["screenshot"], |
| 1414 | Some("Computer-use guidance"), |
| 1415 | ); |
| 1416 | pool.insert_test_connection("docs", &["search"], Some("Docs guidance")); |
| 1417 | let pool = Arc::new(tokio::sync::Mutex::new(pool)); |
| 1418 | |
| 1419 | let mut explore_runtime = super::tests::stub_runtime() |
| 1420 | .child_runtime() |
| 1421 | .with_mcp_pool(Some(Arc::clone(&pool))); |
| 1422 | explore_runtime.worker_profile = WorkerRuntimeProfile::for_role(FleetRole::Scout); |
| 1423 | let explore_auth = engine::ChildAuthority::capture( |
| 1424 | explore_runtime.clone(), |
| 1425 | FleetRole::Scout, |
| 1426 | "agent_explore_mcp".into(), |
| 1427 | "explore".into(), |
| 1428 | None, |
| 1429 | ); |
| 1430 | let explore_servers = explore_auth.admitted_mcp_servers(&explore_runtime).await; |
| 1431 | assert!(explore_servers.is_empty()); |
| 1432 | |
| 1433 | let mut worker_runtime = super::tests::stub_runtime() |
| 1434 | .child_runtime() |
| 1435 | .with_mcp_pool(Some(Arc::clone(&pool))); |
| 1436 | worker_runtime.worker_profile = WorkerRuntimeProfile::for_role(FleetRole::Worker); |
| 1437 | let scoped_worker_auth = engine::ChildAuthority::capture( |
| 1438 | worker_runtime.clone(), |
| 1439 | FleetRole::Worker, |
| 1440 | "agent_docs_worker".into(), |
| 1441 | "docs-worker".into(), |
| 1442 | Some(vec!["read".into(), "mcp_docs_search".into()]), |
| 1443 | ); |
| 1444 | let scoped_servers = scoped_worker_auth |
| 1445 | .admitted_mcp_servers(&worker_runtime) |
| 1446 | .await; |
| 1447 | assert_eq!(scoped_servers, HashSet::from(["docs".to_string()])); |
| 1448 | |
| 1449 | let full_worker_auth = engine::ChildAuthority::capture( |
| 1450 | worker_runtime.clone(), |
| 1451 | FleetRole::Worker, |
| 1452 | "agent_full_worker".into(), |
| 1453 | "full-worker".into(), |
| 1454 | None, |
| 1455 | ); |
| 1456 | let full_servers = full_worker_auth.admitted_mcp_servers(&worker_runtime).await; |
| 1457 | assert!(!full_servers.contains("computer-use")); |
| 1458 | assert!(full_servers.contains("docs")); |
| 1459 | |
| 1460 | let parent_fork = SubAgentForkContext { |
| 1461 | messages: vec![ |
| 1462 | Message { |
| 1463 | role: Role::User, |
| 1464 | content: vec![ContentBlock::Text { |
| 1465 | text: "investigate subagent lifecycle".into(), |
| 1466 | cache_control: None, |
| 1467 | }], |
| 1468 | }, |
| 1469 | crate::runtime_handoff::mcp_server_instructions_runtime_message(&[ |
| 1470 | ("github".into(), "GitHub guidance".into()), |
| 1471 | ("linear".into(), "Linear guidance".into()), |
| 1472 | ("computer-use".into(), "Computer-use guidance".into()), |
| 1473 | ("docs".into(), "Docs guidance".into()), |
| 1474 | ]), |
| 1475 | ], |
| 1476 | structured_state_block: None, |
| 1477 | work_source: None, |
| 1478 | }; |
| 1479 | let explore_seed = build_initial_subagent_messages( |
| 1480 | "map the lifecycle", |
| 1481 | &SubAgentAssignment::new("map the lifecycle".into(), None), |
| 1482 | &FleetRole::Scout, |
| 1483 | Some(&parent_fork), |
| 1484 | ); |
| 1485 | assert!( |
| 1486 | !explore_seed |
| 1487 | .iter() |
| 1488 | .any(crate::runtime_handoff::is_mcp_server_instructions_message) |
| 1489 | ); |
| 1490 | } |
| 1491 | |
| 1492 | #[test] |
| 1493 | fn aborted_durable_launch_surfaces_and_logs_reconcile_failure() { |
| 1494 | use std::io::{Read as _, Seek as _, SeekFrom}; |
| 1495 | |
| 1496 | let work = crate::work_graph::new_shared_work_runtime( |
| 1497 | crate::tools::todo::new_shared_todo_list(), |
| 1498 | crate::tools::plan::new_shared_plan_state(), |
| 1499 | ); |
| 1500 | let lifecycle = SubAgentWorkLifecycle { |
| 1501 | work, |
| 1502 | session_id: "session-a".to_string(), |
| 1503 | external: "worker:agent-abort".to_string(), |
| 1504 | }; |
| 1505 | let mut output = tempfile::tempfile().unwrap(); |
| 1506 | let subscriber = tracing_subscriber::fmt() |
| 1507 | .without_time() |
| 1508 | .with_ansi(false) |
| 1509 | .with_env_filter(tracing_subscriber::EnvFilter::new("warn")) |
| 1510 | .with_writer(std::sync::Mutex::new(output.try_clone().unwrap())) |
| 1511 | .finish(); |
| 1512 | let error = tracing::subscriber::with_default(subscriber, || { |
| 1513 | fail_aborted_durable_launch("agent-abort", Some(&lifecycle), anyhow!("disk full")) |
| 1514 | }); |
| 1515 | let message = error.to_string(); |
| 1516 | assert!(message.contains("disk full"), "{message}"); |
| 1517 | assert!( |
| 1518 | message.contains("additionally failed to settle lifecycle owner") |
| 1519 | && message.contains("lifecycle observation arrived before graph registration"), |
| 1520 | "{message}" |
| 1521 | ); |
| 1522 | output.seek(SeekFrom::Start(0)).unwrap(); |
| 1523 | let mut logs = String::new(); |
| 1524 | output.read_to_string(&mut logs).unwrap(); |
| 1525 | assert!( |
| 1526 | logs.contains("WARN") |
| 1527 | && logs.contains("failed to mark aborted write-capable launch as Failed") |
| 1528 | && logs.contains("lifecycle observation arrived before graph registration"), |
| 1529 | "{logs}" |
| 1530 | ); |
| 1531 | } |
| 1532 |