| 1 | #[tokio::test] |
| 2 | async fn queued_goal_clear_refreshes_prompt_and_cancels_stale_continuation() { |
| 3 | let config = Config::default(); |
| 4 | let engine_config = EngineConfig { |
| 5 | snapshots_enabled: false, |
| 6 | terminal_chrome_enabled: false, |
| 7 | goal_objective: Some("clear this goal".to_string()), |
| 8 | goal_token_budget: Some(42_000), |
| 9 | ..EngineConfig::default() |
| 10 | }; |
| 11 | let (engine, handle) = Engine::new(engine_config, &config); |
| 12 | let goal_state = engine.config.goal_state.clone(); |
| 13 | let run_task = tokio::spawn(engine.run()); |
| 14 | |
| 15 | // Model the mailbox order produced when the user clears a goal while its |
| 16 | // prior turn is still finishing: the control reaches the queue before the |
| 17 | // synthetic continuation that TurnComplete schedules. |
| 18 | handle |
| 19 | .send(Op::SetGoalStatus { |
| 20 | goal_id: None, |
| 21 | status: crate::tools::goal::GoalStatus::Active, |
| 22 | clear: true, |
| 23 | }) |
| 24 | .await |
| 25 | .expect("queue goal clear"); |
| 26 | handle |
| 27 | .send(Op::ContinueGoal { |
| 28 | dynamic_tools: Vec::new(), |
| 29 | engine_schedule_id: None, |
| 30 | }) |
| 31 | .await |
| 32 | .expect("queue stale continuation"); |
| 33 | |
| 34 | // This receipt sits behind both operations. Once it arrives, a stale |
| 35 | // continuation has either incorrectly started a turn or been consumed. |
| 36 | let session = handle |
| 37 | .get_session_snapshot() |
| 38 | .await |
| 39 | .expect("post-clear session snapshot"); |
| 40 | let prompt = match session.system_prompt.expect("post-clear system prompt") { |
| 41 | SystemPrompt::Text(text) => text, |
| 42 | SystemPrompt::Blocks(blocks) => blocks |
| 43 | .into_iter() |
| 44 | .map(|block| block.text) |
| 45 | .collect::<Vec<_>>() |
| 46 | .join("\n"), |
| 47 | }; |
| 48 | assert!( |
| 49 | !prompt.contains("<session_goal>"), |
| 50 | "cleared config fallback must not restore the goal prompt: {prompt}" |
| 51 | ); |
| 52 | let snapshot = goal_state.lock().expect("goal lock").snapshot(); |
| 53 | assert_eq!(snapshot.objective, None); |
| 54 | assert_eq!(snapshot.status, "none"); |
| 55 | assert_eq!(snapshot.token_budget, None); |
| 56 | |
| 57 | let mut saw_clear_session = false; |
| 58 | let mut saw_clear_goal = false; |
| 59 | let mut saw_clear_status = false; |
| 60 | { |
| 61 | let mut events = handle.rx_event.write().await; |
| 62 | while let Ok(event) = events.try_recv() { |
| 63 | match event { |
| 64 | Event::TurnStarted { .. } => { |
| 65 | panic!("queued clear must prevent a stale goal continuation") |
| 66 | } |
| 67 | Event::SessionUpdated { |
| 68 | source: _, |
| 69 | system_prompt, |
| 70 | .. |
| 71 | } => { |
| 72 | let prompt = match system_prompt.expect("clear SessionUpdated prompt") { |
| 73 | SystemPrompt::Text(text) => text, |
| 74 | SystemPrompt::Blocks(blocks) => blocks |
| 75 | .into_iter() |
| 76 | .map(|block| block.text) |
| 77 | .collect::<Vec<_>>() |
| 78 | .join("\n"), |
| 79 | }; |
| 80 | assert!(!prompt.contains("<session_goal>"), "{prompt}"); |
| 81 | saw_clear_session = true; |
| 82 | } |
| 83 | Event::GoalUpdated { snapshot } => { |
| 84 | assert_eq!(snapshot.objective, None); |
| 85 | assert_eq!(snapshot.status, "none"); |
| 86 | saw_clear_goal = true; |
| 87 | } |
| 88 | Event::Status { message } if message == "Goal cleared." => { |
| 89 | saw_clear_status = true; |
| 90 | } |
| 91 | _ => {} |
| 92 | } |
| 93 | } |
| 94 | } |
| 95 | assert!( |
| 96 | saw_clear_session, |
| 97 | "clear must refresh persisted prompt state" |
| 98 | ); |
| 99 | assert!(saw_clear_goal, "clear must emit a canonical empty snapshot"); |
| 100 | assert!(saw_clear_status, "clear must remain user-visible"); |
| 101 | |
| 102 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 103 | run_task.await.expect("engine task"); |
| 104 | } |
| 105 | |
| 106 | fn goal_custom_route_config() -> Config { |
| 107 | let mut custom = HashMap::new(); |
| 108 | custom.insert( |
| 109 | "custom-a".to_string(), |
| 110 | codewhale_runtime::config::ProviderConfig { |
| 111 | kind: Some("openai-compatible".to_string()), |
| 112 | base_url: Some("http://127.0.0.1:18181/v1".to_string()), |
| 113 | model: Some("local-model".to_string()), |
| 114 | api_key: Some("local-test-key".to_string()), |
| 115 | ..codewhale_runtime::config::ProviderConfig::default() |
| 116 | }, |
| 117 | ); |
| 118 | { |
| 119 | let __cw_config_init_0_0 = Some("custom-a".to_string()); |
| 120 | let __cw_config_init_0_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 121 | custom, |
| 122 | ..codewhale_runtime::config::ProvidersConfig::default() |
| 123 | }); |
| 124 | let mut __cw_config_init_0_value: Config = Config::default(); |
| 125 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 126 | __cw_config_init_0_value.providers = __cw_config_init_0_1; |
| 127 | __cw_config_init_0_value |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | #[tokio::test] |
| 132 | async fn ordinary_prose_never_activates_a_goal() { |
| 133 | let request_entered = std::sync::Arc::new(tokio::sync::Notify::new()); |
| 134 | let release_request = std::sync::Arc::new(tokio::sync::Notify::new()); |
| 135 | let model = std::sync::Arc::new(FirstRequestGatedGoalModelClient { |
| 136 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 137 | request_entered: std::sync::Arc::clone(&request_entered), |
| 138 | release_request: std::sync::Arc::clone(&release_request), |
| 139 | }); |
| 140 | let config = goal_custom_route_config(); |
| 141 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 142 | let (engine, handle) = Engine::new_with_model_client( |
| 143 | EngineConfig { |
| 144 | model: "local-model".to_string(), |
| 145 | max_steps: 1, |
| 146 | snapshots_enabled: false, |
| 147 | terminal_chrome_enabled: false, |
| 148 | ..EngineConfig::default() |
| 149 | }, |
| 150 | &config, |
| 151 | client, |
| 152 | ); |
| 153 | let goal_state = engine.config.goal_state.clone(); |
| 154 | let run_task = tokio::spawn(engine.run()); |
| 155 | |
| 156 | handle |
| 157 | .send(Op::SendMessage(TurnSpec { |
| 158 | profile_constitution: None, |
| 159 | max_output_tokens: None, |
| 160 | content: "hello - take over and make it your /goal to solve navier stokes".to_string(), |
| 161 | images: Vec::new(), |
| 162 | mode: AppMode::Agent, |
| 163 | route: resolved_route_for_test(&config, "local-model"), |
| 164 | compaction: Box::new(CompactionConfig::default()), |
| 165 | initial_routed_usage: Box::default(), |
| 166 | goal_objective: None, |
| 167 | goal_token_budget: None, |
| 168 | goal_status: crate::tools::goal::GoalStatus::Active, |
| 169 | reasoning_effort: None, |
| 170 | reasoning_effort_auto: false, |
| 171 | auto_model: false, |
| 172 | allow_shell: false, |
| 173 | trust_mode: false, |
| 174 | auto_approve: false, |
| 175 | approval_mode: ApprovalMode::Suggest, |
| 176 | translation_enabled: false, |
| 177 | allowed_tools: None, |
| 178 | dynamic_tools: Vec::new(), |
| 179 | hook_executor: None, |
| 180 | verbosity: None, |
| 181 | provenance: UserInputProvenance::ExternalUser, |
| 182 | input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson, |
| 183 | submission_id: None, |
| 184 | })) |
| 185 | .await |
| 186 | .expect("send explicit natural goal turn"); |
| 187 | |
| 188 | // #6290 rework: the natural-language `/goal` prose parser is gone. The |
| 189 | // same wording that used to activate a goal is now an ordinary turn; |
| 190 | // only the model (`create_goal`) or the `/goal` command creates one. |
| 191 | let mut saw_goal = false; |
| 192 | loop { |
| 193 | let event = tokio::time::timeout(model_turn_event_timeout(), async { |
| 194 | handle.rx_event.write().await.recv().await |
| 195 | }) |
| 196 | .await |
| 197 | .expect("prose goal event timeout") |
| 198 | .expect("prose goal event"); |
| 199 | match event { |
| 200 | Event::GoalUpdated { .. } => { |
| 201 | saw_goal = true; |
| 202 | } |
| 203 | Event::TurnStarted { .. } => { |
| 204 | assert!( |
| 205 | !saw_goal, |
| 206 | "ordinary prose must not publish a goal before provider work starts" |
| 207 | ); |
| 208 | break; |
| 209 | } |
| 210 | _ => {} |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | tokio::time::timeout(model_turn_event_timeout(), request_entered.notified()) |
| 215 | .await |
| 216 | .expect("provider request was never entered"); |
| 217 | release_request.notify_one(); |
| 218 | let _ = tokio::time::timeout(model_turn_event_timeout(), handle.get_session_snapshot()) |
| 219 | .await |
| 220 | .expect("turn did not settle") |
| 221 | .expect("post-turn session snapshot"); |
| 222 | let snapshot = goal_state.lock().expect("goal lock").snapshot(); |
| 223 | assert_eq!(snapshot.objective.as_deref(), None); |
| 224 | assert!(!snapshot.is_active()); |
| 225 | assert_eq!(model.calls.load(std::sync::atomic::Ordering::SeqCst), 1); |
| 226 | |
| 227 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 228 | run_task.await.expect("engine task"); |
| 229 | } |
| 230 | |
| 231 | /// Drive one turn in `mode` and report what the goal path did before the |
| 232 | /// provider was called: the objective published by `GoalUpdated` (if any), |
| 233 | /// whether the engine goal state is active, and how many Operate contract |
| 234 | /// messages the session log holds afterwards. |
| 235 | async fn operate_goal_probe(mode: AppMode, prompt: &str) -> (Option<String>, bool, usize) { |
| 236 | let request_entered = std::sync::Arc::new(tokio::sync::Notify::new()); |
| 237 | let release_request = std::sync::Arc::new(tokio::sync::Notify::new()); |
| 238 | let model = std::sync::Arc::new(FirstRequestGatedGoalModelClient { |
| 239 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 240 | request_entered: std::sync::Arc::clone(&request_entered), |
| 241 | release_request: std::sync::Arc::clone(&release_request), |
| 242 | }); |
| 243 | let config = goal_custom_route_config(); |
| 244 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 245 | let (engine, handle) = Engine::new_with_model_client( |
| 246 | EngineConfig { |
| 247 | model: "local-model".to_string(), |
| 248 | max_steps: 1, |
| 249 | snapshots_enabled: false, |
| 250 | terminal_chrome_enabled: false, |
| 251 | ..EngineConfig::default() |
| 252 | }, |
| 253 | &config, |
| 254 | client, |
| 255 | ); |
| 256 | let goal_state = engine.config.goal_state.clone(); |
| 257 | let run_task = tokio::spawn(engine.run()); |
| 258 | |
| 259 | handle |
| 260 | .send(Op::SendMessage(TurnSpec { |
| 261 | profile_constitution: None, |
| 262 | max_output_tokens: None, |
| 263 | content: prompt.to_string(), |
| 264 | images: Vec::new(), |
| 265 | mode, |
| 266 | route: resolved_route_for_test(&config, "local-model"), |
| 267 | compaction: Box::new(CompactionConfig::default()), |
| 268 | initial_routed_usage: Box::default(), |
| 269 | goal_objective: None, |
| 270 | goal_token_budget: None, |
| 271 | goal_status: crate::tools::goal::GoalStatus::Active, |
| 272 | reasoning_effort: None, |
| 273 | reasoning_effort_auto: false, |
| 274 | auto_model: false, |
| 275 | allow_shell: false, |
| 276 | trust_mode: false, |
| 277 | auto_approve: false, |
| 278 | approval_mode: ApprovalMode::Suggest, |
| 279 | translation_enabled: false, |
| 280 | allowed_tools: None, |
| 281 | dynamic_tools: Vec::new(), |
| 282 | hook_executor: None, |
| 283 | verbosity: None, |
| 284 | provenance: UserInputProvenance::ExternalUser, |
| 285 | input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson, |
| 286 | submission_id: None, |
| 287 | })) |
| 288 | .await |
| 289 | .expect("send probe turn"); |
| 290 | |
| 291 | let mut published_objective = None; |
| 292 | loop { |
| 293 | let event = tokio::time::timeout(model_turn_event_timeout(), async { |
| 294 | handle.rx_event.write().await.recv().await |
| 295 | }) |
| 296 | .await |
| 297 | .expect("probe event timeout") |
| 298 | .expect("probe event"); |
| 299 | match event { |
| 300 | Event::GoalUpdated { snapshot } if snapshot.status == "active" => { |
| 301 | published_objective = snapshot.objective; |
| 302 | } |
| 303 | Event::TurnStarted { .. } => break, |
| 304 | _ => {} |
| 305 | } |
| 306 | } |
| 307 | tokio::time::timeout(model_turn_event_timeout(), request_entered.notified()) |
| 308 | .await |
| 309 | .expect("provider request was never entered"); |
| 310 | let active = goal_state.lock().expect("goal lock").is_active(); |
| 311 | if active { |
| 312 | // Stop autonomous continuation after the one provider call. |
| 313 | handle |
| 314 | .send(Op::SetGoalStatus { |
| 315 | goal_id: None, |
| 316 | status: crate::tools::goal::GoalStatus::Paused, |
| 317 | clear: false, |
| 318 | }) |
| 319 | .await |
| 320 | .expect("queue goal pause"); |
| 321 | } |
| 322 | release_request.notify_one(); |
| 323 | let snapshot = tokio::time::timeout(model_turn_event_timeout(), handle.get_session_snapshot()) |
| 324 | .await |
| 325 | .expect("probe turn did not settle") |
| 326 | .expect("probe session snapshot"); |
| 327 | let contracts = snapshot |
| 328 | .messages |
| 329 | .iter() |
| 330 | .filter(|message| crate::runtime_handoff::is_operate_contract_message(message)) |
| 331 | .count(); |
| 332 | assert_eq!(model.calls.load(std::sync::atomic::Ordering::SeqCst), 1); |
| 333 | |
| 334 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 335 | run_task.await.expect("engine task"); |
| 336 | (published_objective, active, contracts) |
| 337 | } |
| 338 | |
| 339 | #[tokio::test] |
| 340 | async fn operate_never_promotes_wording_to_a_goal() { |
| 341 | let prompt = |
| 342 | "Migrate the settings loader to the new config crate and keep the old keys readable"; |
| 343 | |
| 344 | // The verb-list promotion is gone: an ordinary work prompt is an ordinary |
| 345 | // turn in every mode, and the model decides goals through `create_goal` |
| 346 | // (docs/design/TUI_DECONSTRUCTION.md, founder clarification 2026-09-09). |
| 347 | let (objective, active, contracts) = operate_goal_probe(AppMode::Agent, prompt).await; |
| 348 | assert_eq!( |
| 349 | objective, None, |
| 350 | "the host must not infer a goal from wording" |
| 351 | ); |
| 352 | assert!(!active); |
| 353 | assert_eq!(contracts, 0, "Operate appends no contract"); |
| 354 | |
| 355 | let (objective, active, contracts) = operate_goal_probe(AppMode::Agent, prompt).await; |
| 356 | assert_eq!(objective, None, "Work must not promote a prompt to a goal"); |
| 357 | assert!(!active); |
| 358 | assert_eq!(contracts, 0, "Work never sees the Operate contract"); |
| 359 | |
| 360 | // #6290 rework: even an explicit-looking declaration is ordinary |
| 361 | // prose now — the host never parses it, and the model decides goals |
| 362 | // through `create_goal`. |
| 363 | let (objective, active, contracts) = |
| 364 | operate_goal_probe(AppMode::Agent, "Please set /goal to ship the release").await; |
| 365 | assert_eq!( |
| 366 | objective, None, |
| 367 | "prose asking for a goal must not create one host-side" |
| 368 | ); |
| 369 | assert!(!active); |
| 370 | assert_eq!(contracts, 0); |
| 371 | } |
| 372 | |
| 373 | #[tokio::test] |
| 374 | async fn operate_leaves_followup_and_long_questions_as_ordinary_turns() { |
| 375 | let report = "what about like rust or docker builds or something"; |
| 376 | let (objective, active, contracts) = operate_goal_probe(AppMode::Agent, report).await; |
| 377 | assert_eq!( |
| 378 | objective, None, |
| 379 | "conversational followup must remain ordinary turn in Operate" |
| 380 | ); |
| 381 | assert!(!active); |
| 382 | assert_eq!(contracts, 0); |
| 383 | |
| 384 | let long_q = |
| 385 | "why did the build fail on the last step when running under docker on macos with rust 1.80"; |
| 386 | let (objective, active, contracts) = operate_goal_probe(AppMode::Agent, long_q).await; |
| 387 | assert_eq!( |
| 388 | objective, None, |
| 389 | "long question without punctuation must remain ordinary turn" |
| 390 | ); |
| 391 | assert!(!active); |
| 392 | assert_eq!(contracts, 0); |
| 393 | |
| 394 | let zh_followup = "那 rust 或者 docker 构建呢"; |
| 395 | let (objective, active, contracts) = operate_goal_probe(AppMode::Agent, zh_followup).await; |
| 396 | assert_eq!( |
| 397 | objective, None, |
| 398 | "Chinese followup must remain ordinary turn in Operate" |
| 399 | ); |
| 400 | assert!(!active); |
| 401 | assert_eq!(contracts, 0); |
| 402 | } |
| 403 | |
| 404 | #[tokio::test] |
| 405 | async fn operate_does_not_create_a_goal_when_the_work_request_declines_one() { |
| 406 | let prompt = "Run one bounded cancellation check. Do not edit files, inspect other files, create a goal, spawn agents, or start any other tool."; |
| 407 | let (objective, active, contracts) = operate_goal_probe(AppMode::Agent, prompt).await; |
| 408 | assert_eq!(objective, None); |
| 409 | assert!(!active); |
| 410 | assert_eq!(contracts, 0, "Operate appends no contract"); |
| 411 | } |
| 412 | |
| 413 | #[tokio::test] |
| 414 | async fn operate_turns_append_no_contract_and_never_replace_an_existing_goal() { |
| 415 | let first_entered = std::sync::Arc::new(tokio::sync::Notify::new()); |
| 416 | let release_first = std::sync::Arc::new(tokio::sync::Notify::new()); |
| 417 | let model = std::sync::Arc::new(IndexedGatedGoalModelClient { |
| 418 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 419 | gates: HashMap::from([( |
| 420 | 1, |
| 421 | ( |
| 422 | std::sync::Arc::clone(&first_entered), |
| 423 | std::sync::Arc::clone(&release_first), |
| 424 | ), |
| 425 | )]), |
| 426 | max_calls: 2, |
| 427 | }); |
| 428 | let config = goal_custom_route_config(); |
| 429 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 430 | let (engine, handle) = Engine::new_with_model_client( |
| 431 | EngineConfig { |
| 432 | model: "local-model".to_string(), |
| 433 | max_steps: 1, |
| 434 | snapshots_enabled: false, |
| 435 | terminal_chrome_enabled: false, |
| 436 | ..EngineConfig::default() |
| 437 | }, |
| 438 | &config, |
| 439 | client, |
| 440 | ); |
| 441 | let goal_state = engine.config.goal_state.clone(); |
| 442 | let run_task = tokio::spawn(engine.run()); |
| 443 | |
| 444 | let send = |content: &str, goal_objective: Option<String>, goal_status| { |
| 445 | Op::SendMessage(TurnSpec { |
| 446 | profile_constitution: None, |
| 447 | max_output_tokens: None, |
| 448 | content: content.to_string(), |
| 449 | images: Vec::new(), |
| 450 | mode: AppMode::Agent, |
| 451 | route: resolved_route_for_test(&config, "local-model"), |
| 452 | compaction: Box::new(CompactionConfig::default()), |
| 453 | initial_routed_usage: Box::default(), |
| 454 | goal_objective, |
| 455 | goal_token_budget: None, |
| 456 | goal_status, |
| 457 | reasoning_effort: None, |
| 458 | reasoning_effort_auto: false, |
| 459 | auto_model: false, |
| 460 | allow_shell: false, |
| 461 | trust_mode: false, |
| 462 | auto_approve: false, |
| 463 | approval_mode: ApprovalMode::Suggest, |
| 464 | translation_enabled: false, |
| 465 | allowed_tools: None, |
| 466 | dynamic_tools: Vec::new(), |
| 467 | hook_executor: None, |
| 468 | verbosity: None, |
| 469 | provenance: UserInputProvenance::ExternalUser, |
| 470 | input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson, |
| 471 | submission_id: None, |
| 472 | }) |
| 473 | }; |
| 474 | |
| 475 | let first_objective = |
| 476 | "Migrate the settings loader to the new config crate and keep the old keys readable"; |
| 477 | // #6290 rework: prose no longer creates goals, so the unfinished goal |
| 478 | // this test needs is seeded directly — the same `GoalState::create` path |
| 479 | // the `/goal` command and the model's `create_goal` tool use. |
| 480 | goal_state |
| 481 | .lock() |
| 482 | .expect("goal lock") |
| 483 | .create(first_objective.to_string(), None) |
| 484 | .expect("seed unfinished goal"); |
| 485 | handle |
| 486 | .send(send( |
| 487 | first_objective, |
| 488 | Some(first_objective.to_string()), |
| 489 | crate::tools::goal::GoalStatus::Active, |
| 490 | )) |
| 491 | .await |
| 492 | .expect("send first Operate turn"); |
| 493 | tokio::time::timeout(model_turn_event_timeout(), first_entered.notified()) |
| 494 | .await |
| 495 | .expect("first provider request was never entered"); |
| 496 | assert_eq!( |
| 497 | goal_state.lock().expect("goal lock").objective(), |
| 498 | Some(first_objective) |
| 499 | ); |
| 500 | handle |
| 501 | .send(Op::SetGoalStatus { |
| 502 | goal_id: None, |
| 503 | status: crate::tools::goal::GoalStatus::Paused, |
| 504 | clear: false, |
| 505 | }) |
| 506 | .await |
| 507 | .expect("queue goal pause"); |
| 508 | release_first.notify_one(); |
| 509 | let _ = tokio::time::timeout(model_turn_event_timeout(), handle.get_session_snapshot()) |
| 510 | .await |
| 511 | .expect("first turn did not settle") |
| 512 | .expect("first session snapshot"); |
| 513 | |
| 514 | // Second Operate prompt while the (paused) goal is still unfinished: the |
| 515 | // host reports that goal, so the prompt is ordinary work under it. |
| 516 | handle |
| 517 | .send(send( |
| 518 | "Refactor the provider table so it survives a config reload", |
| 519 | Some(first_objective.to_string()), |
| 520 | crate::tools::goal::GoalStatus::Paused, |
| 521 | )) |
| 522 | .await |
| 523 | .expect("send second Operate turn"); |
| 524 | let snapshot = tokio::time::timeout(model_turn_event_timeout(), handle.get_session_snapshot()) |
| 525 | .await |
| 526 | .expect("second turn did not settle") |
| 527 | .expect("second session snapshot"); |
| 528 | assert_eq!(model.calls.load(std::sync::atomic::Ordering::SeqCst), 2); |
| 529 | let contracts = snapshot |
| 530 | .messages |
| 531 | .iter() |
| 532 | .filter(|message| crate::runtime_handoff::is_operate_contract_message(message)) |
| 533 | .count(); |
| 534 | assert_eq!(contracts, 0, "Operate turns append no contract"); |
| 535 | let goal = goal_state.lock().expect("goal lock").snapshot(); |
| 536 | assert_eq!(goal.objective.as_deref(), Some(first_objective)); |
| 537 | assert_eq!(goal.status, "paused"); |
| 538 | |
| 539 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 540 | run_task.await.expect("engine task"); |
| 541 | } |
| 542 | |
| 543 | fn without_named_custom_route(mut config: Config) -> Config { |
| 544 | config |
| 545 | .providers |
| 546 | .as_mut() |
| 547 | .expect("custom providers") |
| 548 | .custom |
| 549 | .clear(); |
| 550 | config |
| 551 | } |
| 552 | |
| 553 | #[tokio::test] |
| 554 | async fn exhausted_goal_reaches_route_failure_without_budget_pause() { |
| 555 | let config = goal_custom_route_config(); |
| 556 | let engine_config = EngineConfig { |
| 557 | model: "local-model".to_string(), |
| 558 | snapshots_enabled: false, |
| 559 | terminal_chrome_enabled: false, |
| 560 | goal_objective: Some("stop at the budget".to_string()), |
| 561 | goal_token_budget: Some(10), |
| 562 | ..EngineConfig::default() |
| 563 | }; |
| 564 | let (mut engine, handle) = Engine::new(engine_config, &config); |
| 565 | let goal_state = engine.config.goal_state.clone(); |
| 566 | goal_state |
| 567 | .lock() |
| 568 | .expect("goal lock") |
| 569 | .record_usage(11, 0, std::time::Instant::now()); |
| 570 | |
| 571 | let invalid_route_config = without_named_custom_route(config); |
| 572 | engine.authoritative_route_config = |
| 573 | Some(Arc::new(parking_lot::RwLock::new(invalid_route_config))); |
| 574 | assert!( |
| 575 | engine.current_runtime_route().is_err(), |
| 576 | "fixture must prove route resolution cannot succeed" |
| 577 | ); |
| 578 | let run_task = tokio::spawn(engine.run()); |
| 579 | |
| 580 | handle |
| 581 | .send(Op::ContinueGoal { |
| 582 | dynamic_tools: Vec::new(), |
| 583 | engine_schedule_id: None, |
| 584 | }) |
| 585 | .await |
| 586 | .expect("queue exhausted continuation"); |
| 587 | |
| 588 | let mut saw_route_error = false; |
| 589 | let mut saw_blocked_goal = false; |
| 590 | while !(saw_route_error && saw_blocked_goal) { |
| 591 | let event = tokio::time::timeout(model_turn_event_timeout(), async { |
| 592 | handle.rx_event.write().await.recv().await |
| 593 | }) |
| 594 | .await |
| 595 | .expect("budget terminal event timeout") |
| 596 | .expect("budget terminal event"); |
| 597 | match event { |
| 598 | Event::TurnStarted { .. } => { |
| 599 | panic!("an exhausted goal must not start a turn before route resolution") |
| 600 | } |
| 601 | Event::Error { envelope, .. } => { |
| 602 | assert!( |
| 603 | envelope.message.contains("route is no longer valid"), |
| 604 | "the exhausted goal must reach the invalid-route failure, got: {envelope:?}" |
| 605 | ); |
| 606 | saw_route_error = true; |
| 607 | } |
| 608 | Event::GoalUpdated { snapshot } if snapshot.status == "paused" => { |
| 609 | panic!( |
| 610 | "budgets are telemetry-only in unbounded goal mode; the goal must not pause on budget (pause_reason={:?})", |
| 611 | snapshot.pause_reason |
| 612 | ); |
| 613 | } |
| 614 | Event::GoalUpdated { snapshot } if snapshot.status == "blocked" => { |
| 615 | assert_eq!(snapshot.tokens_used, 11); |
| 616 | assert_eq!(snapshot.token_budget, Some(10)); |
| 617 | assert_eq!( |
| 618 | snapshot.pause_reason, None, |
| 619 | "budget must never be the pause reason in unbounded goal mode" |
| 620 | ); |
| 621 | saw_blocked_goal = true; |
| 622 | } |
| 623 | _ => {} |
| 624 | } |
| 625 | } |
| 626 | |
| 627 | let snapshot = goal_state.lock().expect("goal lock").snapshot(); |
| 628 | assert_eq!(snapshot.status, "blocked"); |
| 629 | assert_eq!(snapshot.tokens_used, 11); |
| 630 | assert_eq!(snapshot.token_budget, Some(10)); |
| 631 | assert_eq!(snapshot.pause_reason, None); |
| 632 | |
| 633 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 634 | run_task.await.expect("engine task"); |
| 635 | } |
| 636 | |
| 637 | #[tokio::test] |
| 638 | async fn continuation_circuit_breaker_pauses_with_run_limit_reason() { |
| 639 | // #5052: the backstop is configurable ([goal] max_continuations) and set |
| 640 | // deliberately past the retired hardcoded cap of 10 to prove an operate |
| 641 | // goal is no longer stopped there — only the configured backstop halts a |
| 642 | // pathological loop that never emits a terminal signal. |
| 643 | let backstop = 12u32; |
| 644 | let config = Config::default(); |
| 645 | let (engine, handle) = Engine::new( |
| 646 | EngineConfig { |
| 647 | snapshots_enabled: false, |
| 648 | terminal_chrome_enabled: false, |
| 649 | goal_objective: Some("stop a runaway continuation loop".to_string()), |
| 650 | goal_max_continuations: backstop, |
| 651 | ..EngineConfig::default() |
| 652 | }, |
| 653 | &config, |
| 654 | ); |
| 655 | let goal_state = engine.config.goal_state.clone(); |
| 656 | { |
| 657 | let mut goal = goal_state.lock().expect("goal lock"); |
| 658 | for _ in 0..backstop { |
| 659 | goal.record_continuation(); |
| 660 | } |
| 661 | } |
| 662 | let run_task = tokio::spawn(engine.run()); |
| 663 | |
| 664 | handle |
| 665 | .send(Op::ContinueGoal { |
| 666 | dynamic_tools: Vec::new(), |
| 667 | engine_schedule_id: None, |
| 668 | }) |
| 669 | .await |
| 670 | .expect("queue capped continuation"); |
| 671 | |
| 672 | let mut saw_pause = false; |
| 673 | let mut saw_reason = false; |
| 674 | while !(saw_pause && saw_reason) { |
| 675 | let event = tokio::time::timeout(model_turn_event_timeout(), async { |
| 676 | handle.rx_event.write().await.recv().await |
| 677 | }) |
| 678 | .await |
| 679 | .expect("continuation cap event timeout") |
| 680 | .expect("continuation cap event"); |
| 681 | match event { |
| 682 | Event::TurnStarted { .. } => panic!("capped goal must not start another turn"), |
| 683 | Event::GoalUpdated { snapshot } if snapshot.status == "paused" => { |
| 684 | assert_eq!( |
| 685 | snapshot.pause_reason, |
| 686 | Some(crate::tools::goal::GoalPauseReason::Backoff) |
| 687 | ); |
| 688 | saw_pause = true; |
| 689 | } |
| 690 | Event::Status { message } if message.contains("automatic continuations") => { |
| 691 | assert!(message.contains(&backstop.to_string()), "{message}"); |
| 692 | assert!(message.contains("[goal] max_continuations"), "{message}"); |
| 693 | saw_reason = true; |
| 694 | } |
| 695 | _ => {} |
| 696 | } |
| 697 | } |
| 698 | |
| 699 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 700 | run_task.await.expect("engine task"); |
| 701 | } |
| 702 | |
| 703 | #[tokio::test] |
| 704 | async fn goal_continues_past_legacy_ten_pass_cap_when_budget_remains() { |
| 705 | // #5052 regression: 10 automatic continuations used to be a terminal stop. |
| 706 | // With the default backstop and budget remaining, the loop must keep |
| 707 | // dispatching toward the completion gate. |
| 708 | let config = Config::default(); |
| 709 | let (engine, _handle) = Engine::new( |
| 710 | EngineConfig { |
| 711 | snapshots_enabled: false, |
| 712 | terminal_chrome_enabled: false, |
| 713 | goal_objective: Some("run to the completion gate, not a pass count".to_string()), |
| 714 | goal_token_budget: Some(1_000_000), |
| 715 | ..EngineConfig::default() |
| 716 | }, |
| 717 | &config, |
| 718 | ); |
| 719 | { |
| 720 | let mut goal = engine.config.goal_state.lock().expect("goal lock"); |
| 721 | for _ in 0..10 { |
| 722 | goal.record_continuation(); |
| 723 | } |
| 724 | } |
| 725 | |
| 726 | match engine.goal_continuation_if_active() { |
| 727 | GoalContinuationAction::Dispatch { snapshot, .. } => { |
| 728 | assert_eq!(snapshot.continuation_count, 11); |
| 729 | } |
| 730 | other => panic!("goal must continue past 10 passes, got {other:?}"), |
| 731 | } |
| 732 | |
| 733 | // A backstop of 0 means unlimited-with-budget-stops: even a pathological |
| 734 | // pass count keeps continuing while budget remains. |
| 735 | let (engine, _handle) = Engine::new( |
| 736 | EngineConfig { |
| 737 | snapshots_enabled: false, |
| 738 | terminal_chrome_enabled: false, |
| 739 | goal_objective: Some("unlimited backstop".to_string()), |
| 740 | goal_token_budget: Some(1_000_000), |
| 741 | goal_max_continuations: 0, |
| 742 | ..EngineConfig::default() |
| 743 | }, |
| 744 | &config, |
| 745 | ); |
| 746 | { |
| 747 | let mut goal = engine.config.goal_state.lock().expect("goal lock"); |
| 748 | for _ in 0..500 { |
| 749 | goal.record_continuation(); |
| 750 | } |
| 751 | } |
| 752 | assert!( |
| 753 | matches!( |
| 754 | engine.goal_continuation_if_active(), |
| 755 | GoalContinuationAction::Dispatch { .. } |
| 756 | ), |
| 757 | "backstop 0 must not stop an in-budget goal" |
| 758 | ); |
| 759 | } |
| 760 | |
| 761 | /// T08-03: the cross-turn continuation gate stops at an *enforced* token |
| 762 | /// budget, the same stop the intra-turn gate and the host take, and keeps |
| 763 | /// the default advisory behavior when enforcement is off. |
| 764 | #[tokio::test] |
| 765 | async fn cross_turn_goal_continuation_stops_at_an_enforced_token_budget() { |
| 766 | let config = Config::default(); |
| 767 | for enforce in [true, false] { |
| 768 | let (engine, _handle) = Engine::new( |
| 769 | EngineConfig { |
| 770 | snapshots_enabled: false, |
| 771 | terminal_chrome_enabled: false, |
| 772 | goal_objective: Some("stop at the enforced budget".to_string()), |
| 773 | goal_token_budget: Some(100), |
| 774 | goal_enforce_token_budget: enforce, |
| 775 | ..EngineConfig::default() |
| 776 | }, |
| 777 | &config, |
| 778 | ); |
| 779 | engine |
| 780 | .config |
| 781 | .goal_state |
| 782 | .lock() |
| 783 | .expect("goal lock") |
| 784 | .record_usage(100, 0, std::time::Instant::now()); |
| 785 | let action = engine.goal_continuation_if_active(); |
| 786 | if enforce { |
| 787 | assert!( |
| 788 | matches!( |
| 789 | action, |
| 790 | GoalContinuationAction::Stopped { |
| 791 | reason: crate::tools::goal::GoalPauseReason::BudgetLimit, |
| 792 | .. |
| 793 | } |
| 794 | ), |
| 795 | "an exhausted enforced budget must not dispatch another turn: {action:?}" |
| 796 | ); |
| 797 | } else { |
| 798 | assert!( |
| 799 | matches!(action, GoalContinuationAction::Dispatch { .. }), |
| 800 | "an advisory budget keeps the goal running: {action:?}" |
| 801 | ); |
| 802 | } |
| 803 | } |
| 804 | } |
| 805 | |
| 806 | #[tokio::test] |
| 807 | async fn invalid_route_blocks_active_goal_and_refreshes_projections() { |
| 808 | let config = goal_custom_route_config(); |
| 809 | let engine_config = EngineConfig { |
| 810 | model: "local-model".to_string(), |
| 811 | snapshots_enabled: false, |
| 812 | terminal_chrome_enabled: false, |
| 813 | goal_objective: Some("keep going across route drift".to_string()), |
| 814 | ..EngineConfig::default() |
| 815 | }; |
| 816 | let (mut engine, handle) = Engine::new(engine_config, &config); |
| 817 | let goal_state = engine.config.goal_state.clone(); |
| 818 | engine.authoritative_route_config = Some(Arc::new(parking_lot::RwLock::new( |
| 819 | without_named_custom_route(config), |
| 820 | ))); |
| 821 | assert!( |
| 822 | engine.current_runtime_route().is_err(), |
| 823 | "fixture must fail before dispatch" |
| 824 | ); |
| 825 | let run_task = tokio::spawn(engine.run()); |
| 826 | |
| 827 | handle |
| 828 | .send(Op::ContinueGoal { |
| 829 | dynamic_tools: Vec::new(), |
| 830 | engine_schedule_id: None, |
| 831 | }) |
| 832 | .await |
| 833 | .expect("queue active continuation"); |
| 834 | let session = handle |
| 835 | .get_session_snapshot() |
| 836 | .await |
| 837 | .expect("post-route-failure session snapshot"); |
| 838 | |
| 839 | let prompt = match session.system_prompt.expect("blocked system prompt") { |
| 840 | SystemPrompt::Text(text) => text, |
| 841 | SystemPrompt::Blocks(blocks) => blocks |
| 842 | .into_iter() |
| 843 | .map(|block| block.text) |
| 844 | .collect::<Vec<_>>() |
| 845 | .join("\n"), |
| 846 | }; |
| 847 | assert!(!prompt.contains("<session_goal>"), "{prompt}"); |
| 848 | let snapshot = goal_state.lock().expect("goal lock").snapshot(); |
| 849 | assert_eq!(snapshot.status, "blocked"); |
| 850 | assert!( |
| 851 | snapshot |
| 852 | .blocker |
| 853 | .as_deref() |
| 854 | .is_some_and(|blocker| blocker.contains("provider route is no longer valid")), |
| 855 | "{snapshot:?}" |
| 856 | ); |
| 857 | |
| 858 | let mut saw_route_error = false; |
| 859 | let mut saw_blocked_session = false; |
| 860 | let mut saw_blocked_goal = false; |
| 861 | let mut saw_blocked_status = false; |
| 862 | { |
| 863 | let mut events = handle.rx_event.write().await; |
| 864 | while let Ok(event) = events.try_recv() { |
| 865 | match event { |
| 866 | Event::TurnStarted { .. } => { |
| 867 | panic!("invalid route must not start a continuation turn") |
| 868 | } |
| 869 | Event::Error { envelope, .. } => { |
| 870 | assert!(format!("{envelope:?}").contains("provider route is no longer valid")); |
| 871 | saw_route_error = true; |
| 872 | } |
| 873 | Event::SessionUpdated { |
| 874 | system_prompt: Some(system_prompt), |
| 875 | .. |
| 876 | } => { |
| 877 | let prompt = match system_prompt { |
| 878 | SystemPrompt::Text(text) => text, |
| 879 | SystemPrompt::Blocks(blocks) => blocks |
| 880 | .into_iter() |
| 881 | .map(|block| block.text) |
| 882 | .collect::<Vec<_>>() |
| 883 | .join("\n"), |
| 884 | }; |
| 885 | assert!(!prompt.contains("<session_goal>"), "{prompt}"); |
| 886 | saw_blocked_session = true; |
| 887 | } |
| 888 | Event::GoalUpdated { snapshot } if snapshot.status == "blocked" => { |
| 889 | saw_blocked_goal = true; |
| 890 | } |
| 891 | Event::Status { message } |
| 892 | if message.contains("provider route is no longer valid") => |
| 893 | { |
| 894 | assert!(message.contains("resume the goal"), "{message}"); |
| 895 | saw_blocked_status = true; |
| 896 | } |
| 897 | _ => {} |
| 898 | } |
| 899 | } |
| 900 | } |
| 901 | assert!(saw_route_error, "route failure must remain visible"); |
| 902 | assert!( |
| 903 | saw_blocked_session, |
| 904 | "session prompt projection must refresh" |
| 905 | ); |
| 906 | assert!(saw_blocked_goal, "sidebar must receive blocked state"); |
| 907 | assert!(saw_blocked_status, "blocked reason must remain visible"); |
| 908 | |
| 909 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 910 | run_task.await.expect("engine task"); |
| 911 | } |
| 912 | |
| 913 | #[tokio::test] |
| 914 | async fn rejected_continuation_dispatch_blocks_goal_after_failed_turn() { |
| 915 | let config = goal_custom_route_config(); |
| 916 | let engine_config = EngineConfig { |
| 917 | model: "local-model".to_string(), |
| 918 | snapshots_enabled: false, |
| 919 | terminal_chrome_enabled: false, |
| 920 | goal_objective: Some("keep going after dispatch".to_string()), |
| 921 | ..EngineConfig::default() |
| 922 | }; |
| 923 | let (mut engine, handle) = Engine::new(engine_config, &config); |
| 924 | let goal_state = engine.config.goal_state.clone(); |
| 925 | assert!(engine.current_runtime_route().is_ok()); |
| 926 | // Exercise the continuation caller's `false` boundary deterministically: |
| 927 | // the route installs, but the injected-model authority has no client with |
| 928 | // which to start the request. |
| 929 | engine.model_client_injected = true; |
| 930 | engine.model_client = None; |
| 931 | let run_task = tokio::spawn(engine.run()); |
| 932 | |
| 933 | handle |
| 934 | .send(Op::ContinueGoal { |
| 935 | dynamic_tools: Vec::new(), |
| 936 | engine_schedule_id: None, |
| 937 | }) |
| 938 | .await |
| 939 | .expect("queue rejected continuation"); |
| 940 | let session = handle |
| 941 | .get_session_snapshot() |
| 942 | .await |
| 943 | .expect("post-rejection session snapshot"); |
| 944 | |
| 945 | let prompt = match session.system_prompt.expect("blocked system prompt") { |
| 946 | SystemPrompt::Text(text) => text, |
| 947 | SystemPrompt::Blocks(blocks) => blocks |
| 948 | .into_iter() |
| 949 | .map(|block| block.text) |
| 950 | .collect::<Vec<_>>() |
| 951 | .join("\n"), |
| 952 | }; |
| 953 | assert!(!prompt.contains("<session_goal>"), "{prompt}"); |
| 954 | let snapshot = goal_state.lock().expect("goal lock").snapshot(); |
| 955 | assert_eq!(snapshot.status, "blocked"); |
| 956 | assert!( |
| 957 | snapshot |
| 958 | .blocker |
| 959 | .as_deref() |
| 960 | .is_some_and(|blocker| blocker.contains("next model turn could not be started")), |
| 961 | "{snapshot:?}" |
| 962 | ); |
| 963 | |
| 964 | let mut starts = 0; |
| 965 | let mut saw_failed_turn = false; |
| 966 | let mut saw_dispatch_error = false; |
| 967 | let mut saw_blocked_session = false; |
| 968 | let mut saw_blocked_goal = false; |
| 969 | let mut saw_blocked_status = false; |
| 970 | { |
| 971 | let mut events = handle.rx_event.write().await; |
| 972 | while let Ok(event) = events.try_recv() { |
| 973 | match event { |
| 974 | Event::TurnStarted { .. } => starts += 1, |
| 975 | Event::TurnComplete { status, .. } => { |
| 976 | assert_eq!(status, TurnOutcomeStatus::Failed); |
| 977 | saw_failed_turn = true; |
| 978 | } |
| 979 | Event::Error { .. } => saw_dispatch_error = true, |
| 980 | Event::SessionUpdated { |
| 981 | system_prompt: Some(system_prompt), |
| 982 | .. |
| 983 | } => { |
| 984 | let prompt = match system_prompt { |
| 985 | SystemPrompt::Text(text) => text, |
| 986 | SystemPrompt::Blocks(blocks) => blocks |
| 987 | .into_iter() |
| 988 | .map(|block| block.text) |
| 989 | .collect::<Vec<_>>() |
| 990 | .join("\n"), |
| 991 | }; |
| 992 | assert!(!prompt.contains("<session_goal>"), "{prompt}"); |
| 993 | saw_blocked_session = true; |
| 994 | } |
| 995 | Event::GoalUpdated { snapshot } if snapshot.status == "blocked" => { |
| 996 | saw_blocked_goal = true; |
| 997 | } |
| 998 | Event::Status { message } |
| 999 | if message.contains("next model turn could not be started") => |
| 1000 | { |
| 1001 | assert!(message.contains("resume the goal"), "{message}"); |
| 1002 | saw_blocked_status = true; |
| 1003 | } |
| 1004 | _ => {} |
| 1005 | } |
| 1006 | } |
| 1007 | } |
| 1008 | assert_eq!( |
| 1009 | starts, 1, |
| 1010 | "dispatch reached exactly one engine turn boundary" |
| 1011 | ); |
| 1012 | assert!( |
| 1013 | saw_failed_turn, |
| 1014 | "rejected dispatch must surface a failed turn" |
| 1015 | ); |
| 1016 | assert!( |
| 1017 | saw_dispatch_error, |
| 1018 | "rejected dispatch must surface its error" |
| 1019 | ); |
| 1020 | assert!( |
| 1021 | saw_blocked_session, |
| 1022 | "session prompt projection must refresh" |
| 1023 | ); |
| 1024 | assert!(saw_blocked_goal, "sidebar must receive blocked state"); |
| 1025 | assert!(saw_blocked_status, "blocked reason must remain visible"); |
| 1026 | |
| 1027 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 1028 | run_task.await.expect("engine task"); |
| 1029 | } |
| 1030 | |
| 1031 | #[tokio::test] |
| 1032 | async fn started_nonretryable_continuation_failure_blocks_goal_with_bounded_reason() { |
| 1033 | let failure_marker = "HTTP 400 Bad Request: deterministic continuation failure"; |
| 1034 | let leaked_secret = "sk-goal-secret-sentinel-123456"; |
| 1035 | let failure_message = format!( |
| 1036 | "{failure_marker}: {leaked_secret} {}", |
| 1037 | "provider detail ".repeat(80) |
| 1038 | ); |
| 1039 | let model = std::sync::Arc::new(FailingGoalModelClient { |
| 1040 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 1041 | message: failure_message.clone(), |
| 1042 | }); |
| 1043 | let config = goal_custom_route_config(); |
| 1044 | let engine_config = EngineConfig { |
| 1045 | model: "local-model".to_string(), |
| 1046 | snapshots_enabled: false, |
| 1047 | terminal_chrome_enabled: false, |
| 1048 | goal_objective: Some("block a failed continuation truthfully".to_string()), |
| 1049 | ..EngineConfig::default() |
| 1050 | }; |
| 1051 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 1052 | let (engine, handle) = Engine::new_with_model_client(engine_config, &config, client); |
| 1053 | let goal_state = engine.config.goal_state.clone(); |
| 1054 | let run_task = tokio::spawn(engine.run()); |
| 1055 | |
| 1056 | handle |
| 1057 | .send(Op::ContinueGoal { |
| 1058 | dynamic_tools: Vec::new(), |
| 1059 | engine_schedule_id: None, |
| 1060 | }) |
| 1061 | .await |
| 1062 | .expect("queue failing continuation"); |
| 1063 | let session = tokio::time::timeout(model_turn_event_timeout(), handle.get_session_snapshot()) |
| 1064 | .await |
| 1065 | .expect("failed continuation did not terminalize") |
| 1066 | .expect("post-failure session snapshot"); |
| 1067 | |
| 1068 | let prompt = match session.system_prompt.expect("blocked system prompt") { |
| 1069 | SystemPrompt::Text(text) => text, |
| 1070 | SystemPrompt::Blocks(blocks) => blocks |
| 1071 | .into_iter() |
| 1072 | .map(|block| block.text) |
| 1073 | .collect::<Vec<_>>() |
| 1074 | .join("\n"), |
| 1075 | }; |
| 1076 | assert!(!prompt.contains("<session_goal>"), "{prompt}"); |
| 1077 | let snapshot = goal_state.lock().expect("goal lock").snapshot(); |
| 1078 | assert_eq!(snapshot.status, "blocked"); |
| 1079 | let blocker = snapshot.blocker.as_deref().expect("failure blocker"); |
| 1080 | assert!(blocker.contains(failure_marker), "{blocker}"); |
| 1081 | assert!(blocker.contains("resume the goal"), "{blocker}"); |
| 1082 | assert!(!blocker.contains(leaked_secret), "{blocker}"); |
| 1083 | assert!( |
| 1084 | blocker.contains(codewhale_config::persistence::REDACTED), |
| 1085 | "{blocker}" |
| 1086 | ); |
| 1087 | assert!( |
| 1088 | blocker.len() <= GOAL_CONTINUATION_FAILURE_DETAIL_MAX_BYTES + 160, |
| 1089 | "failure reason must remain bounded: {} bytes", |
| 1090 | blocker.len() |
| 1091 | ); |
| 1092 | assert!( |
| 1093 | blocker.len() < failure_message.len(), |
| 1094 | "long provider detail must be truncated" |
| 1095 | ); |
| 1096 | assert_eq!( |
| 1097 | model.calls.load(std::sync::atomic::Ordering::SeqCst), |
| 1098 | 1, |
| 1099 | "a nonretryable started failure must not dispatch again" |
| 1100 | ); |
| 1101 | |
| 1102 | let mut starts = 0; |
| 1103 | let mut saw_failed_turn = false; |
| 1104 | let mut saw_provider_error = false; |
| 1105 | let mut saw_blocked_goal = false; |
| 1106 | let mut saw_blocked_status = false; |
| 1107 | { |
| 1108 | let mut events = handle.rx_event.write().await; |
| 1109 | while let Ok(event) = events.try_recv() { |
| 1110 | match event { |
| 1111 | Event::TurnStarted { .. } => starts += 1, |
| 1112 | Event::TurnComplete { status, error, .. } => { |
| 1113 | assert_eq!(status, TurnOutcomeStatus::Failed); |
| 1114 | assert!( |
| 1115 | error |
| 1116 | .as_deref() |
| 1117 | .is_some_and(|message| message.contains(failure_marker)), |
| 1118 | "{error:?}" |
| 1119 | ); |
| 1120 | saw_failed_turn = true; |
| 1121 | } |
| 1122 | Event::Error { envelope, .. } => { |
| 1123 | if envelope.message.contains(failure_marker) { |
| 1124 | saw_provider_error = true; |
| 1125 | } |
| 1126 | } |
| 1127 | Event::GoalUpdated { snapshot } if snapshot.status == "blocked" => { |
| 1128 | saw_blocked_goal = true; |
| 1129 | } |
| 1130 | Event::Status { message } if message.contains(failure_marker) => { |
| 1131 | assert!(message.contains("resume the goal"), "{message}"); |
| 1132 | saw_blocked_status = true; |
| 1133 | } |
| 1134 | _ => {} |
| 1135 | } |
| 1136 | } |
| 1137 | } |
| 1138 | assert_eq!(starts, 1, "exactly one continuation turn must start"); |
| 1139 | assert!(saw_failed_turn, "failed turn receipt must remain visible"); |
| 1140 | assert!( |
| 1141 | saw_provider_error, |
| 1142 | "provider error event must remain visible" |
| 1143 | ); |
| 1144 | assert!(saw_blocked_goal, "goal must publish its blocked snapshot"); |
| 1145 | assert!(saw_blocked_status, "bounded failure must remain visible"); |
| 1146 | |
| 1147 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 1148 | run_task.await.expect("engine task"); |
| 1149 | } |
| 1150 | |
| 1151 | #[tokio::test] |
| 1152 | async fn headless_host_drains_existing_engine_completion_inbox_before_exit() { |
| 1153 | use crate::llm_client::mock::{MockLlmClient, canned}; |
| 1154 | |
| 1155 | let workspace = tempdir().unwrap(); |
| 1156 | let config = goal_custom_route_config(); |
| 1157 | let mock = Arc::new(MockLlmClient::new(vec![canned::simple_text_turn( |
| 1158 | "child evidence integrated by the existing Engine", |
| 1159 | )])); |
| 1160 | let (engine, handle) = Engine::new_with_model_client( |
| 1161 | EngineConfig { |
| 1162 | model: "local-model".into(), |
| 1163 | terminal_chrome_enabled: false, |
| 1164 | ..deterministic_engine_config(workspace.path()) |
| 1165 | }, |
| 1166 | &config, |
| 1167 | mock.clone(), |
| 1168 | ); |
| 1169 | assert!(engine.subagent_settlement_snapshot().await.is_settled()); |
| 1170 | // Reproduce the host boundary: the parent already ended, and a terminal |
| 1171 | // child's receipt is waiting for the Engine's normal idle fan-in path. |
| 1172 | engine |
| 1173 | .tx_event |
| 1174 | .send(Event::TurnComplete { |
| 1175 | source_accounting: false, |
| 1176 | |
| 1177 | turn_id: None, |
| 1178 | submission_id: None, |
| 1179 | compaction_id: None, |
| 1180 | usage: Usage::default(), |
| 1181 | parent_route_usage: Usage::default(), |
| 1182 | routed_usage_dropped_records: 0, |
| 1183 | status: TurnOutcomeStatus::Completed, |
| 1184 | error: None, |
| 1185 | tool_catalog: None, |
| 1186 | base_url: None, |
| 1187 | }) |
| 1188 | .await |
| 1189 | .unwrap(); |
| 1190 | engine |
| 1191 | .tx_subagent_completion |
| 1192 | .try_send(SubAgentCompletion { |
| 1193 | owner_session_id: engine.session.id.clone(), |
| 1194 | agent_id: "headless-settled-child".into(), |
| 1195 | payload: "bounded local fixture evidence".into(), |
| 1196 | }) |
| 1197 | .unwrap(); |
| 1198 | let pending = engine.subagent_settlement_snapshot().await; |
| 1199 | assert_eq!(pending.running_children, 0); |
| 1200 | assert_eq!(pending.pending_completions, 1); |
| 1201 | assert!( |
| 1202 | !pending.is_settled(), |
| 1203 | "terminal child alone cannot release the host" |
| 1204 | ); |
| 1205 | |
| 1206 | let run = tokio::spawn(engine.run()); |
| 1207 | let mut events = crate::exec_events::ExecAgentEvents::new( |
| 1208 | handle.clone(), |
| 1209 | Instant::now() + model_turn_event_timeout(), |
| 1210 | ); |
| 1211 | let mut content = String::new(); |
| 1212 | let mut starts = 0; |
| 1213 | tokio::time::timeout(model_turn_event_timeout(), async { |
| 1214 | loop { |
| 1215 | match events.next().await.expect("host event") { |
| 1216 | Event::TurnStarted { .. } => starts += 1, |
| 1217 | Event::MessageDelta { content: delta, .. } => content.push_str(&delta), |
| 1218 | Event::TurnComplete { status, .. } => { |
| 1219 | assert_eq!(status, TurnOutcomeStatus::Completed); |
| 1220 | break; |
| 1221 | } |
| 1222 | _ => {} |
| 1223 | } |
| 1224 | } |
| 1225 | }) |
| 1226 | .await |
| 1227 | .expect("bounded headless settlement"); |
| 1228 | assert_eq!(starts, 1, "fan-in uses exactly one existing Engine turn"); |
| 1229 | assert_eq!(mock.call_count(), 1); |
| 1230 | assert!(content.contains("child evidence integrated")); |
| 1231 | assert!(!handle.is_cancelled()); |
| 1232 | handle.send(Op::Shutdown).await.unwrap(); |
| 1233 | tokio::time::timeout(Duration::from_secs(3), run) |
| 1234 | .await |
| 1235 | .unwrap() |
| 1236 | .unwrap(); |
| 1237 | } |
| 1238 | |
| 1239 | #[tokio::test] |
| 1240 | async fn host_managed_engine_does_not_self_dispatch_goal_continuation() { |
| 1241 | use crate::llm_client::mock::{MockLlmClient, canned}; |
| 1242 | |
| 1243 | let mut custom = HashMap::new(); |
| 1244 | custom.insert( |
| 1245 | "custom-a".to_string(), |
| 1246 | codewhale_runtime::config::ProviderConfig { |
| 1247 | kind: Some("openai-compatible".to_string()), |
| 1248 | base_url: Some("http://127.0.0.1:18181/v1".to_string()), |
| 1249 | model: Some("local-model".to_string()), |
| 1250 | api_key: Some("local-test-key".to_string()), |
| 1251 | ..codewhale_runtime::config::ProviderConfig::default() |
| 1252 | }, |
| 1253 | ); |
| 1254 | let config = { |
| 1255 | let __cw_config_init_1_0 = Some("custom-a".to_string()); |
| 1256 | let __cw_config_init_1_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1257 | custom, |
| 1258 | ..codewhale_runtime::config::ProvidersConfig::default() |
| 1259 | }); |
| 1260 | let mut __cw_config_init_1_value: Config = Config::default(); |
| 1261 | __cw_config_init_1_value.provider = __cw_config_init_1_0; |
| 1262 | __cw_config_init_1_value.providers = __cw_config_init_1_1; |
| 1263 | __cw_config_init_1_value |
| 1264 | }; |
| 1265 | let runtime_services = crate::tools::spec::RuntimeToolServices { |
| 1266 | active_thread_id: Some("thr_host_managed".to_string()), |
| 1267 | ..crate::tools::spec::RuntimeToolServices::default() |
| 1268 | }; |
| 1269 | let engine_config = EngineConfig { |
| 1270 | max_steps: 0, |
| 1271 | snapshots_enabled: false, |
| 1272 | terminal_chrome_enabled: false, |
| 1273 | goal_objective: Some("keep going".to_string()), |
| 1274 | runtime_services, |
| 1275 | ..EngineConfig::default() |
| 1276 | }; |
| 1277 | let mock = Arc::new(MockLlmClient::new(vec![canned::simple_text_turn( |
| 1278 | "host-managed turn complete", |
| 1279 | )])); |
| 1280 | let client: crate::core::model_client::SharedModelClient = mock.clone(); |
| 1281 | let (engine, handle) = Engine::new_with_model_client(engine_config, &config, client); |
| 1282 | let run_task = tokio::spawn(engine.run()); |
| 1283 | |
| 1284 | handle |
| 1285 | .send(Op::SendMessage(TurnSpec { |
| 1286 | profile_constitution: None, |
| 1287 | max_output_tokens: None, |
| 1288 | content: "one host-owned turn".to_string(), |
| 1289 | images: Vec::new(), |
| 1290 | mode: AppMode::Agent, |
| 1291 | route: resolved_route_for_test(&config, "local-model"), |
| 1292 | compaction: Box::new(CompactionConfig::default()), |
| 1293 | initial_routed_usage: Box::default(), |
| 1294 | goal_objective: Some("keep going".to_string()), |
| 1295 | goal_token_budget: None, |
| 1296 | goal_status: crate::tools::goal::GoalStatus::Active, |
| 1297 | reasoning_effort: None, |
| 1298 | reasoning_effort_auto: false, |
| 1299 | auto_model: false, |
| 1300 | allow_shell: false, |
| 1301 | trust_mode: false, |
| 1302 | auto_approve: false, |
| 1303 | approval_mode: ApprovalMode::Suggest, |
| 1304 | translation_enabled: false, |
| 1305 | allowed_tools: None, |
| 1306 | dynamic_tools: Vec::new(), |
| 1307 | hook_executor: None, |
| 1308 | verbosity: None, |
| 1309 | provenance: UserInputProvenance::ExternalUser, |
| 1310 | input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson, |
| 1311 | submission_id: None, |
| 1312 | })) |
| 1313 | .await |
| 1314 | .expect("send host-owned goal turn"); |
| 1315 | |
| 1316 | let mut starts = 0; |
| 1317 | loop { |
| 1318 | let event = tokio::time::timeout(Duration::from_secs(3), async { |
| 1319 | handle.rx_event.write().await.recv().await |
| 1320 | }) |
| 1321 | .await |
| 1322 | .expect("host engine event timeout") |
| 1323 | .expect("host engine event"); |
| 1324 | match event { |
| 1325 | Event::TurnStarted { .. } => starts += 1, |
| 1326 | Event::TurnComplete { .. } => break, |
| 1327 | _ => {} |
| 1328 | } |
| 1329 | } |
| 1330 | assert_eq!(starts, 1); |
| 1331 | assert_eq!( |
| 1332 | mock.call_count(), |
| 1333 | 1, |
| 1334 | "the host-owned turn runs exactly once" |
| 1335 | ); |
| 1336 | assert!( |
| 1337 | tokio::time::timeout(Duration::from_millis(200), async { |
| 1338 | handle.rx_event.write().await.recv().await |
| 1339 | }) |
| 1340 | .await |
| 1341 | .is_err(), |
| 1342 | "a hosted engine must wait for an explicit durable turn claim" |
| 1343 | ); |
| 1344 | |
| 1345 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 1346 | run_task.await.expect("engine task"); |
| 1347 | } |
| 1348 | |
| 1349 | #[tokio::test] |
| 1350 | async fn cancellation_during_blocked_idle_handoff_survives_turn_admission() { |
| 1351 | use crate::llm_client::mock::{MockLlmClient, canned}; |
| 1352 | |
| 1353 | for child_completion in [true, false] { |
| 1354 | let workspace = tempdir().unwrap(); |
| 1355 | let config = goal_custom_route_config(); |
| 1356 | let mock = Arc::new(MockLlmClient::new(vec![canned::simple_text_turn( |
| 1357 | "must not dispatch after cancellation", |
| 1358 | )])); |
| 1359 | let (mut engine, mut handle) = Engine::new_with_model_client( |
| 1360 | EngineConfig { |
| 1361 | model: "local-model".into(), |
| 1362 | terminal_chrome_enabled: false, |
| 1363 | ..deterministic_engine_config(workspace.path()) |
| 1364 | }, |
| 1365 | &config, |
| 1366 | mock.clone(), |
| 1367 | ); |
| 1368 | // Force the handoff to stop at its status send after its initial |
| 1369 | // cancellation check and before handle_send_message admits a turn. |
| 1370 | let (tx, rx) = tokio::sync::mpsc::channel(1); |
| 1371 | engine.tx_event = tx; |
| 1372 | handle.rx_event = Arc::new(RwLock::new(rx)); |
| 1373 | engine.tx_event.send(Event::status("full")).await.unwrap(); |
| 1374 | let completion = SubAgentCompletion { |
| 1375 | owner_session_id: engine.session.id.clone(), |
| 1376 | agent_id: "cancel-race-child".into(), |
| 1377 | payload: "retained-after-cancel-race".into(), |
| 1378 | }; |
| 1379 | let mut wake: std::pin::Pin<Box<dyn std::future::Future<Output = ()> + '_>> = |
| 1380 | if child_completion { |
| 1381 | Box::pin(engine.handle_idle_subagent_completion(completion)) |
| 1382 | } else { |
| 1383 | Box::pin(engine.handle_idle_shell_completion_wake()) |
| 1384 | }; |
| 1385 | assert!( |
| 1386 | tokio::time::timeout(Duration::from_millis(5), &mut wake) |
| 1387 | .await |
| 1388 | .is_err(), |
| 1389 | "the full event channel must hold the handoff before admission" |
| 1390 | ); |
| 1391 | handle.cancel_with_reason(CancelReason::External); |
| 1392 | handle.rx_event.write().await.try_recv().unwrap(); |
| 1393 | tokio::time::timeout(Duration::from_secs(2), &mut wake) |
| 1394 | .await |
| 1395 | .expect("cancelled handoff returns without a provider call"); |
| 1396 | drop(wake); |
| 1397 | assert_eq!(mock.call_count(), 0); |
| 1398 | assert!(handle.is_cancelled()); |
| 1399 | assert!(engine.delivered_subagent_completion_ids.is_empty()); |
| 1400 | assert_eq!( |
| 1401 | engine.rx_subagent_completion.len(), |
| 1402 | usize::from(child_completion) |
| 1403 | ); |
| 1404 | if child_completion { |
| 1405 | assert!( |
| 1406 | engine |
| 1407 | .rx_subagent_completion |
| 1408 | .try_recv() |
| 1409 | .unwrap() |
| 1410 | .payload |
| 1411 | .contains("retained-after-cancel-race") |
| 1412 | ); |
| 1413 | } |
| 1414 | // A new explicit user action still receives a fresh turn control. |
| 1415 | let _turn = engine.begin_turn_control(); |
| 1416 | assert!(!handle.is_cancelled()); |
| 1417 | let existing_child = engine.cancel_token.child_token(); |
| 1418 | drop(_turn); |
| 1419 | let _automatic = |
| 1420 | engine.begin_turn_control_for_provenance(UserInputProvenance::SubAgentHandoff); |
| 1421 | handle.cancel(); |
| 1422 | assert!( |
| 1423 | existing_child.is_cancelled(), |
| 1424 | "stopping an automatic continuation must also stop earlier request siblings" |
| 1425 | ); |
| 1426 | } |
| 1427 | } |
| 1428 | |
| 1429 | #[tokio::test] |
| 1430 | async fn cancelled_parent_defers_child_receipts_until_an_explicit_turn() { |
| 1431 | use crate::llm_client::mock::{MockLlmClient, canned}; |
| 1432 | |
| 1433 | for reason in [CancelReason::User, CancelReason::External] { |
| 1434 | let workspace = tempdir().unwrap(); |
| 1435 | let config = Config::default(); |
| 1436 | let mock = Arc::new(MockLlmClient::new(vec![canned::simple_text_turn( |
| 1437 | "Explicit continuation completed.", |
| 1438 | )])); |
| 1439 | let (mut engine, handle) = Engine::new_with_model_client( |
| 1440 | deterministic_engine_config(workspace.path()), |
| 1441 | &config, |
| 1442 | mock.clone(), |
| 1443 | ); |
| 1444 | handle.cancel_with_reason(reason); |
| 1445 | // Exercise a completion selected just before cancellation arrived. |
| 1446 | engine |
| 1447 | .handle_idle_subagent_completion(SubAgentCompletion { |
| 1448 | owner_session_id: engine.session.id.clone(), |
| 1449 | agent_id: "cancelled-worker".into(), |
| 1450 | payload: "parked-child-evidence".into(), |
| 1451 | }) |
| 1452 | .await; |
| 1453 | assert_eq!( |
| 1454 | mock.call_count(), |
| 1455 | 0, |
| 1456 | "cancellation must forbid a model wake" |
| 1457 | ); |
| 1458 | assert!(engine.delivered_subagent_completion_ids.is_empty()); |
| 1459 | assert_eq!(engine.rx_subagent_completion.len(), 1); |
| 1460 | assert!( |
| 1461 | tokio::time::timeout(Duration::from_millis(50), engine.next_run_input(false)) |
| 1462 | .await |
| 1463 | .is_err(), |
| 1464 | "the idle loop must leave the receipt queued without spinning" |
| 1465 | ); |
| 1466 | |
| 1467 | let run = tokio::spawn(engine.run()); |
| 1468 | handle |
| 1469 | .send(external_user_message_op( |
| 1470 | "Continue explicitly", |
| 1471 | AppMode::Agent, |
| 1472 | &config, |
| 1473 | )) |
| 1474 | .await |
| 1475 | .unwrap(); |
| 1476 | tokio::time::timeout(Duration::from_secs(5), async { |
| 1477 | while let Some(event) = handle.rx_event.write().await.recv().await { |
| 1478 | if matches!(event, Event::TurnComplete { .. }) { |
| 1479 | break; |
| 1480 | } |
| 1481 | } |
| 1482 | }) |
| 1483 | .await |
| 1484 | .expect("explicit turn completes"); |
| 1485 | assert_eq!(mock.call_count(), 1); |
| 1486 | let snapshot = handle.get_session_snapshot().await.unwrap(); |
| 1487 | assert!( |
| 1488 | serde_json::to_string(&snapshot.messages) |
| 1489 | .unwrap() |
| 1490 | .contains("parked-child-evidence"), |
| 1491 | "the next explicit turn must retain the completion receipt" |
| 1492 | ); |
| 1493 | handle.send(Op::Shutdown).await.unwrap(); |
| 1494 | run.await.unwrap(); |
| 1495 | } |
| 1496 | } |
| 1497 |