返回 CodeWhale
test_cases_18.rs
根目录 / crates / engine / src / core / engine / tests / test_cases_18.rs
1 /// A thinking-only mid-stream drop must recover without ever claiming a
2 /// visible partial reply was preserved, and must leave exactly one
3 /// authoritative assistant answer in the persisted conversation.
4 #[tokio::test]
5 async fn interactive_thinking_only_drop_preserves_nothing_and_never_claims_it_did() {
6 let _environment = lock_test_env();
7 let workspace = tempdir().expect("owned stream recovery workspace");
8 let fixture_state = workspace.path().join(".codewhale");
9 fs::create_dir_all(&fixture_state).unwrap();
10 fs::write(
11 fixture_state.join("AGENTS.md"),
12 "Preserve the exact operator input.\n",
13 )
14 .unwrap();
15 let _state_home = EnvVarGuard::set("CODEWHALE_HOME", &fixture_state);
16 let model = std::sync::Arc::new(ThinkingOnlyDropModelClient {
17 calls: std::sync::atomic::AtomicUsize::new(0),
18 failures: 1,
19 });
20 let client: crate::core::model_client::SharedModelClient = model.clone();
21 let config = Config::default();
22 let engine_config = EngineConfig {
23 max_steps: 1,
24 snapshots_enabled: false,
25 subagents_enabled: false,
26 terminal_chrome_enabled: true,
27 ..deterministic_engine_config(workspace.path())
28 };
29 let (mut engine, handle) = Engine::new_with_model_client(engine_config, &config, client);
30 engine.instruction_settings.home = Some(workspace.path().to_path_buf());
31 engine.refresh_system_prompt();
32 let run_task = tokio::spawn(engine.run());
33
34 handle
35 .send(Op::SendMessage(TurnSpec {
36 profile_constitution: None,
37 max_output_tokens: None,
38 content: "solve the task".to_string(),
39 images: Vec::new(),
40 mode: AppMode::Agent,
41 route: resolved_route_for_test(
42 &config,
43 codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL,
44 ),
45 compaction: Box::new(CompactionConfig::default()),
46 initial_routed_usage: Box::default(),
47 goal_objective: None,
48 goal_token_budget: None,
49 goal_status: crate::tools::goal::GoalStatus::Active,
50 reasoning_effort: None,
51 reasoning_effort_auto: false,
52 auto_model: false,
53 allow_shell: false,
54 trust_mode: false,
55 auto_approve: false,
56 approval_mode: ApprovalMode::Suggest,
57 translation_enabled: false,
58 allowed_tools: None,
59 dynamic_tools: Vec::new(),
60 hook_executor: None,
61 verbosity: None,
62 provenance: UserInputProvenance::ExternalUser,
63 input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson,
64 submission_id: None,
65 }))
66 .await
67 .expect("send thinking-only drop turn");
68
69 let mut events = Vec::new();
70 loop {
71 let event = tokio::time::timeout(model_turn_event_timeout(), async {
72 handle.rx_event.write().await.recv().await
73 })
74 .await
75 .expect("thinking-only drop event timeout")
76 .expect("thinking-only drop event");
77 let terminal = matches!(event, Event::TurnComplete { .. });
78 events.push(event);
79 if terminal {
80 break;
81 }
82 }
83 handle.send(Op::Shutdown).await.expect("shutdown engine");
84 run_task.await.expect("engine task");
85
86 assert_eq!(
87 model.calls.load(std::sync::atomic::Ordering::SeqCst),
88 1,
89 "thinking-only drop must not replay an admitted request"
90 );
91 let status = events
92 .iter()
93 .find_map(|event| match event {
94 Event::TurnComplete { status, .. } => Some(*status),
95 _ => None,
96 })
97 .expect("terminal TurnComplete");
98 assert_eq!(status, TurnOutcomeStatus::Failed);
99
100 assert!(
101 !events.iter().any(|event| matches!(
102 event,
103 Event::Status { message } if message.starts_with("Retry attempt: stream-resume 1/")
104 )),
105 "the first retry must be visible without claiming hidden reasoning was preserved"
106 );
107
108 // The persisted conversation keeps the operator's turn and exactly one
109 // authoritative assistant answer — no synthetic `[runtime]` user message,
110 // no duplicated answer, no orphaned thinking-only assistant cell.
111 let transcript = events
112 .iter()
113 .rev()
114 .find_map(|event| match event {
115 Event::SessionUpdated {
116 source: _,
117 messages,
118 ..
119 } => Some(messages.clone()),
120 _ => None,
121 })
122 .expect("final SessionUpdated");
123 assert_eq!(
124 transcript
125 .iter()
126 .filter(|message| {
127 message.role == "user"
128 && !crate::runtime_handoff::is_internal_runtime_handoff(message)
129 })
130 .count(),
131 1,
132 "the operator's own turn must be the only user message: {transcript:?}"
133 );
134 assert_eq!(
135 transcript
136 .iter()
137 .filter(|message| message.role == "assistant")
138 .count(),
139 0,
140 "exactly one authoritative assistant answer after recovery: {transcript:?}"
141 );
142 let transcript_text = transcript
143 .iter()
144 .flat_map(|message| message.content.iter())
145 .filter_map(|block| match block {
146 ContentBlock::Text { text, .. } => Some(text.as_str()),
147 _ => None,
148 })
149 .collect::<Vec<_>>()
150 .join("\n");
151 assert!(
152 !transcript_text.contains("[runtime]"),
153 "a retried turn must not insert a synthetic user message: {transcript_text}"
154 );
155 assert!(
156 !transcript_text.contains("hidden reasoning that no operator ever saw"),
157 "an invisible thinking-only fragment must not be persisted as reply text: {transcript_text}"
158 );
159 assert_eq!(
160 transcript_text
161 .matches("the one authoritative answer")
162 .count(),
163 0,
164 "the recovered answer must be persisted exactly once: {transcript_text}"
165 );
166 }
167
168 /// A model client that answers with ONLY hidden reasoning and a clean stop for
169 /// its first `reasoning_only` calls, then a real text answer. No transport
170 /// error: the stream completes normally but carries no sendable content — the
171 /// reasoning-model failure mode #5546-adjacent that used to dead-end the turn.
172 struct ReasoningOnlyCleanFinishModelClient {
173 calls: std::sync::atomic::AtomicUsize,
174 reasoning_only: usize,
175 stop_reason: &'static str,
176 /// Every outbound request's messages, in order, so a test can tell a
177 /// request-scoped nudge from one written into the session.
178 requests: std::sync::Mutex<Vec<Vec<codewhale_models::Message>>>,
179 }
180
181 #[async_trait::async_trait]
182 impl crate::core::model_client::ModelClient for ReasoningOnlyCleanFinishModelClient {
183 fn provider_name(&self) -> &str {
184 "reasoning-only"
185 }
186
187 fn model(&self) -> &str {
188 "local-model"
189 }
190
191 async fn create_message(
192 &self,
193 _request: codewhale_models::MessageRequest,
194 ) -> anyhow::Result<codewhale_models::MessageResponse> {
195 anyhow::bail!("reasoning-only recovery uses the streaming model boundary")
196 }
197
198 async fn create_message_stream(
199 &self,
200 _request: codewhale_models::MessageRequest,
201 ) -> anyhow::Result<crate::llm_client::StreamEventBox> {
202 use crate::llm_client::mock::canned;
203 if let Ok(mut requests) = self.requests.lock() {
204 requests.push(_request.messages.clone());
205 }
206 let call = self
207 .calls
208 .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
209 .saturating_add(1);
210 if call <= self.reasoning_only {
211 // A protocol-complete response that opened and closed only a
212 // thinking block: no text, no tool call, and a clean stop reason.
213 let events: Vec<anyhow::Result<codewhale_models::StreamEvent>> = vec![
214 Ok(canned::message_start("reasoning_only_msg")),
215 Ok(StreamEvent::ContentBlockStart {
216 index: 0,
217 content_block: codewhale_models::ContentBlockStart::Thinking {
218 thinking: String::new(),
219 },
220 }),
221 Ok(canned::thinking_delta(0, "reasoning with no final channel")),
222 Ok(canned::block_stop(0)),
223 Ok(canned::message_delta(self.stop_reason, None)),
224 Ok(canned::message_stop()),
225 ];
226 return Ok(Box::pin(futures_util::stream::iter(events)));
227 }
228 let events = canned::simple_text_turn("the recovered answer")
229 .into_iter()
230 .map(Ok);
231 Ok(Box::pin(futures_util::stream::iter(events)))
232 }
233
234 async fn health_check(&self) -> anyhow::Result<bool> {
235 Ok(true)
236 }
237 }
238
239 async fn run_reasoning_only_turn(
240 reasoning_only: usize,
241 stop_reason: &'static str,
242 ) -> (
243 std::sync::Arc<ReasoningOnlyCleanFinishModelClient>,
244 Vec<Event>,
245 ) {
246 run_reasoning_only_turn_with_reprompts(
247 reasoning_only,
248 stop_reason,
249 codewhale_runtime::config::DEFAULT_REASONING_ONLY_REPROMPTS,
250 )
251 .await
252 }
253
254 async fn run_reasoning_only_turn_with_reprompts(
255 reasoning_only: usize,
256 stop_reason: &'static str,
257 max_reprompts: u32,
258 ) -> (
259 std::sync::Arc<ReasoningOnlyCleanFinishModelClient>,
260 Vec<Event>,
261 ) {
262 let model = std::sync::Arc::new(ReasoningOnlyCleanFinishModelClient {
263 calls: std::sync::atomic::AtomicUsize::new(0),
264 reasoning_only,
265 stop_reason,
266 requests: std::sync::Mutex::new(Vec::new()),
267 });
268 let client: crate::core::model_client::SharedModelClient = model.clone();
269 let config = Config::default();
270 let engine_config = EngineConfig {
271 max_steps: 1,
272 snapshots_enabled: false,
273 subagents_enabled: false,
274 terminal_chrome_enabled: true,
275 reasoning_only_max_reprompts: max_reprompts,
276 ..EngineConfig::default()
277 };
278 let (engine, handle) = Engine::new_with_model_client(engine_config, &config, client);
279 let run_task = tokio::spawn(engine.run());
280 handle
281 .send(Op::SendMessage(TurnSpec {
282 profile_constitution: None,
283 max_output_tokens: None,
284 content: "solve the task".to_string(),
285 images: Vec::new(),
286 mode: AppMode::Agent,
287 route: resolved_route_for_test(
288 &config,
289 codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL,
290 ),
291 compaction: Box::new(CompactionConfig::default()),
292 initial_routed_usage: Box::default(),
293 goal_objective: None,
294 goal_token_budget: None,
295 goal_status: crate::tools::goal::GoalStatus::Active,
296 reasoning_effort: None,
297 reasoning_effort_auto: false,
298 auto_model: false,
299 allow_shell: false,
300 trust_mode: false,
301 auto_approve: false,
302 approval_mode: ApprovalMode::Suggest,
303 translation_enabled: false,
304 allowed_tools: None,
305 dynamic_tools: Vec::new(),
306 hook_executor: None,
307 verbosity: None,
308 provenance: UserInputProvenance::ExternalUser,
309 input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson,
310 submission_id: None,
311 }))
312 .await
313 .expect("send reasoning-only turn");
314 let mut events = Vec::new();
315 loop {
316 let event = tokio::time::timeout(model_turn_event_timeout(), async {
317 handle.rx_event.write().await.recv().await
318 })
319 .await
320 .expect("reasoning-only event timeout")
321 .expect("reasoning-only event");
322 let terminal = matches!(event, Event::TurnComplete { .. });
323 events.push(event);
324 if terminal {
325 break;
326 }
327 }
328 handle.send(Op::Shutdown).await.expect("shutdown engine");
329 run_task.await.expect("engine task");
330 (model, events)
331 }
332
333 /// A reasoning-only clean-stop response is re-requested and the turn recovers
334 /// with the real answer. Local fixtures make no cache-hit or billing claim.
335 #[tokio::test]
336 async fn reasoning_only_clean_stop_is_retried_and_recovers() {
337 let (model, events) = run_reasoning_only_turn(1, "stop").await;
338
339 let terminal = events
340 .iter()
341 .find_map(|event| match event {
342 Event::ToolRequestSnapshot { snapshot } => snapshot.terminal.as_ref(),
343 _ => None,
344 })
345 .expect("terminal diagnostics through existing event authority");
346 assert_eq!(terminal.model_requests_started, 2);
347 assert_eq!(terminal.reasoning_only_reprompts, 1);
348 assert_eq!(terminal.transparent_stream_retries, 0);
349 assert_eq!(terminal.status, Some(TurnOutcomeStatus::Completed));
350
351 assert_eq!(
352 model.calls.load(std::sync::atomic::Ordering::SeqCst),
353 2,
354 "the reasoning-only response must be re-requested exactly once"
355 );
356 let status = events
357 .iter()
358 .find_map(|event| match event {
359 Event::TurnComplete { status, .. } => Some(*status),
360 _ => None,
361 })
362 .expect("terminal TurnComplete");
363 assert_eq!(status, TurnOutcomeStatus::Completed);
364
365 let recovery = events
366 .iter()
367 .filter_map(|event| match event {
368 Event::Status { message } if message.contains("re-requesting the answer") => {
369 Some(message.clone())
370 }
371 _ => None,
372 })
373 .collect::<Vec<_>>();
374 assert_eq!(recovery.len(), 1, "exactly one recovery notice: {events:?}");
375 assert!(
376 recovery[0].starts_with("Retry attempt: reasoning-only 1/"),
377 "attempt announced: {recovery:?}"
378 );
379
380 // No hard failure surfaced.
381 assert!(
382 !events.iter().any(|event| matches!(
383 event,
384 Event::Error { envelope, .. } if envelope.message.contains("no answer or tool call")
385 )),
386 "a recovered turn must not surface the incomplete-response error: {events:?}"
387 );
388 assert_eq!(events.iter().filter(|event| matches!(event, Event::Status { message } if message.starts_with("Retry recovery: per-kind counter reasoning-only used 1/") && message.ends_with("turn completed"))).count(), 1);
389 }
390
391 /// An output-length stop is a real budget hit, not a transient — it must NOT
392 /// be retried and must fail honestly.
393 #[tokio::test]
394 async fn reasoning_only_length_stop_fails_without_retry() {
395 let (model, events) = run_reasoning_only_turn(1, "length").await;
396
397 let diagnostic = events
398 .iter()
399 .find_map(|event| match event {
400 Event::ToolRequestSnapshot { snapshot } => snapshot.terminal.as_ref(),
401 _ => None,
402 })
403 .expect("terminal request diagnostics");
404 assert!(
405 diagnostic
406 .last_prepared_output_limit_tokens
407 .is_some_and(|tokens| tokens > 0)
408 );
409 assert!(
410 events.iter().any(|event| matches!(
411 event,
412 Event::Error { envelope, .. }
413 if envelope.message.contains("response output limit")
414 && envelope.message.contains("including reasoning")
415 )),
416 "a length stop must explain the actual output constraint"
417 );
418
419 assert_eq!(
420 model.calls.load(std::sync::atomic::Ordering::SeqCst),
421 1,
422 "a length stop must not be retried"
423 );
424 assert!(
425 !events.iter().any(|event| matches!(
426 event,
427 Event::Status { message } if message.contains("re-requesting the answer")
428 )),
429 "a length stop must not announce a retry: {events:?}"
430 );
431 let status = events
432 .iter()
433 .find_map(|event| match event {
434 Event::TurnComplete { status, .. } => Some(*status),
435 _ => None,
436 })
437 .expect("terminal TurnComplete");
438 assert_eq!(status, TurnOutcomeStatus::Failed);
439 }
440
441 /// The reasoning-only nudge rides one request and is never written to the
442 /// session.
443 ///
444 /// This is the distinction that matters: a nudge added with
445 /// `add_session_message` would persist into the transcript, the exports, and
446 /// every later turn's context — a message the user never sent. A
447 /// request-scoped nudge appears in exactly one outbound request and leaves the
448 /// conversation as it found it.
449 ///
450 /// The two are told apart by message counts across successive requests. With
451 /// a ceiling of 3 the model is asked four times. Persisted, the counts would
452 /// grow cumulatively (n, n, n+1, n+2); request-scoped, the nudged requests
453 /// each carry exactly one extra message over the same baseline.
454 #[tokio::test]
455 async fn the_reasoning_only_nudge_rides_one_request_and_never_joins_the_session() {
456 let (model, events) = run_reasoning_only_turn_with_reprompts(usize::MAX, "stop", 3).await;
457
458 let requests = model.requests.lock().expect("captured requests").clone();
459 assert_eq!(requests.len(), 4, "one initial request plus three retries");
460
461 let baseline = requests[0].len();
462 assert_eq!(
463 requests[1].len(),
464 baseline,
465 "the first retry is a bare cached-prefix re-request, with no nudge"
466 );
467 assert_eq!(
468 requests[2].len(),
469 baseline + 1,
470 "the second retry carries the nudge"
471 );
472 assert_eq!(
473 requests[3].len(),
474 baseline + 1,
475 "the nudge did not accumulate: it was spent on the previous request, \
476 not added to the session"
477 );
478
479 let nudge = codewhale_runtime::config::DEFAULT_REASONING_ONLY_REPROMPT_MESSAGE;
480 let carries_nudge = |messages: &Vec<codewhale_models::Message>| {
481 serde_json::to_string(messages)
482 .expect("messages serialize")
483 .contains(nudge)
484 };
485 assert!(!carries_nudge(&requests[0]), "no nudge before any failure");
486 assert!(!carries_nudge(&requests[1]), "no nudge on the first retry");
487 assert!(
488 carries_nudge(&requests[2]),
489 "nudge present once retrying again"
490 );
491
492 // C02-04: model-visible means logged. Every request the nudge rides
493 // leaves a durable (internal) receipt carrying its exact text.
494 let receipts: Vec<&str> = events
495 .iter()
496 .filter_map(|event| match event {
497 Event::Status { message }
498 if message.starts_with(crate::core::events::REQUEST_NUDGE_RECEIPT_PREFIX) =>
499 {
500 Some(message.as_str())
501 }
502 _ => None,
503 })
504 .collect();
505 assert_eq!(
506 receipts.len(),
507 requests
508 .iter()
509 .filter(|request| carries_nudge(request))
510 .count(),
511 "one receipt per nudged request"
512 );
513 assert!(receipts.iter().all(|receipt| receipt.ends_with(nudge)));
514 assert_eq!(
515 crate::core::events::status_visibility(receipts[0]),
516 crate::core::events::StatusVisibility::Internal,
517 "durable clients keep the receipt, collapsed"
518 );
519 }
520
521 /// A model that only ever returns reasoning is bounded: it retries up to the
522 /// ceiling and then fails honestly rather than looping forever.
523 #[tokio::test]
524 async fn reasoning_only_forever_is_bounded_then_fails() {
525 let (model, events) = run_reasoning_only_turn(usize::MAX, "stop").await;
526
527 assert_eq!(
528 model.calls.load(std::sync::atomic::Ordering::SeqCst),
529 1 + codewhale_runtime::config::DEFAULT_REASONING_ONLY_REPROMPTS as usize,
530 "reasoning-only retries are bounded by [reasoning_only] max_reprompts"
531 );
532 let status = events
533 .iter()
534 .find_map(|event| match event {
535 Event::TurnComplete { status, .. } => Some(*status),
536 _ => None,
537 })
538 .expect("terminal TurnComplete");
539 assert_eq!(status, TurnOutcomeStatus::Failed);
540 let attempts = events
541 .iter()
542 .filter_map(|event| match event {
543 Event::Status { message } if message.starts_with("Retry attempt: reasoning-only ") => {
544 Some(message)
545 }
546 _ => None,
547 })
548 .collect::<Vec<_>>();
549 let max = codewhale_runtime::config::DEFAULT_REASONING_ONLY_REPROMPTS;
550 assert_eq!(attempts.len(), max as usize);
551 for (index, message) in attempts.iter().enumerate() {
552 assert!(message.starts_with(&format!(
553 "Retry attempt: reasoning-only {}/{};",
554 index + 1,
555 max
556 )));
557 }
558 assert_eq!(events.iter().filter(|event| matches!(event, Event::Status { message } if message == &format!("Retry stopped: per-kind counter reasoning-only used {max}/{max} retries; turn failed"))).count(), 1);
559 }
560
561 #[tokio::test]
562 async fn headless_turn_fails_with_real_error_after_network_drop_budget_exhausted() {
563 let (model, events) =
564 run_headless_turn_with_flaky_network(1 + super::DEFAULT_STREAM_MAX_RESUMES as usize).await;
565
566 assert_eq!(
567 model.calls.load(std::sync::atomic::Ordering::SeqCst),
568 1,
569 "initial attempt plus the bounded resume budget, then the turn fails"
570 );
571 let (status, error) = events
572 .iter()
573 .find_map(|event| match event {
574 Event::TurnComplete { status, error, .. } => Some((status, error)),
575 _ => None,
576 })
577 .expect("terminal TurnComplete");
578 assert_eq!(*status, TurnOutcomeStatus::Failed);
579 let error = error
580 .as_deref()
581 .expect("exhausted network-drop retries must report the real error");
582 assert!(
583 error.contains("Provider stream connection dropped"),
584 "the surfaced error must name the network drop: {error}"
585 );
586 assert!(
587 error.contains("error decoding response body"),
588 "the underlying provider error must stay attached: {error}"
589 );
590 assert_eq!(
591 codewhale_error_taxonomy::classify_error_message(error),
592 codewhale_error_taxonomy::ErrorCategory::Network,
593 "the terminal failure must classify as retryable infra (network)"
594 );
595 let error_events = events
596 .iter()
597 .filter(|event| matches!(event, Event::Error { .. }))
598 .count();
599 assert_eq!(
600 error_events, 1,
601 "only the final, budget-exhausted attempt may emit an error event: {events:?}"
602 );
603 assert_eq!(
604 events
605 .iter()
606 .filter(|event| matches!(event,
607 Event::Status { message } if message.starts_with("Retry attempt: stream-resume ")
608 ))
609 .count(),
610 0,
611 "every admitted resume must have its own numbered progress receipt"
612 );
613 }
614
615 // === Issue #66: error taxonomy wired through engine + audit + capacity ===
616
617 /// A failed-tool audit entry must carry the typed `category` and `severity`
618 /// fields derived from the underlying `ToolError`. This is what makes
619 /// downstream tooling able to bucket failures without scraping the message
620 /// string.
621 #[test]
622 fn tool_failure_audit_payload_carries_category_and_severity() {
623 use crate::tools::spec::ToolError;
624 use codewhale_error_taxonomy::ErrorEnvelope;
625
626 let error = ToolError::Timeout { seconds: 30 };
627 let envelope: ErrorEnvelope = error.clone().into();
628 let payload = json!({
629 "event": "tool.result",
630 "tool_id": "tool-1",
631 "tool_name": "exec_shell",
632 "status": ToolExecutionOutcome::from_legacy(Err(error.clone())).status.as_str(),
633 "success": false,
634 "error": error.to_string(),
635 "category": envelope.category.to_string(),
636 "severity": envelope.severity.to_string(),
637 });
638
639 assert_eq!(payload["category"], "timeout");
640 assert_eq!(payload["severity"], "warning");
641 assert_eq!(payload["status"], "timed_out");
642 assert_eq!(payload["success"], false);
643 }
644
645 // ── #136: post-edit LSP diagnostics hook ─────────────────────────────────
646
647 #[test]
648 fn edited_paths_scenario() {
649 // Scenario consolidation of: edited_paths_for_edit_file_returns_path, edited_paths_for_write_file_returns_path, edited_paths_for_apply_patch_with_replace_returns_each_path, edited_paths_for_apply_patch_with_legacy_changes_returns_each_path, edited_paths_for_apply_patch_with_diff_text_extracts_paths, edited_paths_for_apply_patch_with_invalid_diff_returns_empty, edited_paths_for_unknown_tool_returns_empty
650 // from edited_paths_for_edit_file_returns_path
651 {
652 let input = json!({ "path": "src/foo.rs", "search": "x", "replace": "y" });
653 let paths = edited_paths_for_tool("edit_file", &input);
654 assert_eq!(paths, vec![PathBuf::from("src/foo.rs")]);
655 }
656 // from edited_paths_for_write_file_returns_path
657 {
658 let input = json!({ "path": "src/bar.rs", "content": "fn main() {}" });
659 let paths = edited_paths_for_tool("write_file", &input);
660 assert_eq!(paths, vec![PathBuf::from("src/bar.rs")]);
661 }
662 // from edited_paths_for_apply_patch_with_replace_returns_each_path
663 {
664 let input = json!({
665 "replace": [
666 { "path": "a.rs", "content": "" },
667 { "path": "b.rs", "content": "" }
668 ]
669 });
670 let paths = edited_paths_for_tool("apply_patch", &input);
671 assert_eq!(paths, vec![PathBuf::from("a.rs"), PathBuf::from("b.rs")]);
672 }
673 // from edited_paths_for_apply_patch_with_legacy_changes_returns_each_path
674 {
675 let input = json!({
676 "changes": [
677 { "path": "a.rs", "content": "" },
678 { "path": "b.rs", "content": "" }
679 ]
680 });
681 let paths = edited_paths_for_tool("apply_patch", &input);
682 assert_eq!(paths, vec![PathBuf::from("a.rs"), PathBuf::from("b.rs")]);
683 }
684 // from edited_paths_for_apply_patch_with_diff_text_extracts_paths
685 {
686 let input = json!({
687 "patch": "--- a/foo.rs\n+++ b/foo.rs\n@@ -1 +1 @@\n-let x: i32 = 0;\n+let x: i32 = \"oops\";\n"
688 });
689 let paths = edited_paths_for_tool("apply_patch", &input);
690 assert_eq!(paths, vec![PathBuf::from("foo.rs")]);
691 }
692 // from edited_paths_for_apply_patch_with_invalid_diff_returns_empty
693 {
694 let input = json!({
695 "patch": "@@ -1 +1 @@\n-old\n+new\n"
696 });
697 let paths = edited_paths_for_tool("apply_patch", &input);
698 assert!(paths.is_empty());
699 }
700 // from edited_paths_for_unknown_tool_returns_empty
701 {
702 let input = json!({ "path": "irrelevant.rs" });
703 let paths = edited_paths_for_tool("read_file", &input);
704 assert!(paths.is_empty());
705 let paths = edited_paths_for_tool("grep_files", &input);
706 assert!(paths.is_empty());
707 }
708 }
709
710 #[test]
711 fn parse_patch_paths_skips_dev_null() {
712 let patch = "--- a/keep.rs\n+++ b/keep.rs\n@@ -1 +1 @@\n-old\n+new\n--- a/deleted.rs\n+++ /dev/null\n@@ -1 +0,0 @@\n-delete me\n";
713 let paths = edited_paths_for_tool("apply_patch", &json!({ "patch": patch }));
714 assert_eq!(paths, vec![PathBuf::from("keep.rs")]);
715 }
716
717 #[tokio::test]
718 async fn post_edit_hook_injects_diagnostics_message_before_next_request() {
719 use codewhale_lsp::{Diagnostic, Language, Severity};
720 use std::sync::Arc;
721
722 let tmp = tempdir().expect("tempdir");
723 let workspace = tmp.path().to_path_buf();
724 let target = workspace.join("src").join("main.rs");
725 fs::create_dir_all(workspace.join("src")).unwrap();
726 fs::write(&target, "let x: i32 = \"not a number\";").unwrap();
727
728 let lsp_config = codewhale_lsp::LspConfig::default();
729 let engine_config = EngineConfig {
730 workspace: workspace.clone(),
731 lsp_config: Some(lsp_config),
732 ..Default::default()
733 };
734 let (mut engine, _handle) = Engine::new(engine_config, &Config::default());
735
736 // Install a fake transport that always reports a type error.
737 let fake = Arc::new(codewhale_lsp::tests::FakeTransport::new(vec![Diagnostic {
738 line: 1,
739 column: 14,
740 severity: Severity::Error,
741 message: "expected i32, found &str".to_string(),
742 }]));
743 engine
744 .lsp_manager
745 .install_test_transport(Language::Rust, fake)
746 .await;
747
748 // Simulate the success path of an edit_file tool call.
749 let input = json!({ "path": "src/main.rs", "search": "0", "replace": "\"not a number\"" });
750 engine.run_post_edit_lsp_hook("edit_file", &input).await;
751 assert_eq!(engine.pending_lsp_blocks.len(), 1);
752
753 // Flush prepares the synthetic message.
754 let messages_before = engine.session.messages.len();
755 engine.flush_pending_lsp_diagnostics().await;
756 assert_eq!(engine.session.messages.len(), messages_before + 1);
757
758 let last = engine.session.messages.last().expect("message appended");
759 assert_eq!(last.role, "user");
760 // turn_meta is now at the tail of the content array (PR #2517).
761 let meta = match last.content.last() {
762 Some(codewhale_models::ContentBlock::Text { text, .. }) => text.clone(),
763 other => panic!("expected text block at tail, got {other:?}"),
764 };
765 assert!(meta.starts_with("<turn_meta>\n"));
766 let diagnostic_text = last
767 .content
768 .iter()
769 .find_map(|block| match block {
770 codewhale_models::ContentBlock::Text { text, .. }
771 if text.contains("<diagnostics file=\"") =>
772 {
773 Some(text)
774 }
775 _ => None,
776 })
777 .expect("diagnostics text block");
778 assert!(diagnostic_text.contains("ERROR [1:14] expected i32, found &str"));
779 }
780
781 #[tokio::test]
782 async fn post_edit_hook_is_silent_when_lsp_disabled() {
783 let tmp = tempdir().expect("tempdir");
784 let workspace = tmp.path().to_path_buf();
785 let target = workspace.join("src").join("main.rs");
786 fs::create_dir_all(workspace.join("src")).unwrap();
787 fs::write(&target, "fn main() {}").unwrap();
788
789 let lsp_config = codewhale_lsp::LspConfig {
790 enabled: false,
791 ..Default::default()
792 };
793 let engine_config = EngineConfig {
794 workspace: workspace.clone(),
795 lsp_config: Some(lsp_config),
796 ..Default::default()
797 };
798 let (mut engine, _handle) = Engine::new(engine_config, &Config::default());
799
800 let input = json!({ "path": "src/main.rs", "search": "x", "replace": "y" });
801 engine.run_post_edit_lsp_hook("edit_file", &input).await;
802 assert!(engine.pending_lsp_blocks.is_empty());
803
804 let messages_before = engine.session.messages.len();
805 engine.flush_pending_lsp_diagnostics().await;
806 assert_eq!(engine.session.messages.len(), messages_before);
807 }
808
809 #[tokio::test]
810 async fn post_edit_hook_skips_unknown_tool_names() {
811 use codewhale_lsp::{Diagnostic, Language, Severity};
812 use std::sync::Arc;
813
814 let tmp = tempdir().expect("tempdir");
815 let engine_config = EngineConfig {
816 workspace: tmp.path().to_path_buf(),
817 lsp_config: Some(codewhale_lsp::LspConfig::default()),
818 ..Default::default()
819 };
820 let (mut engine, _handle) = Engine::new(engine_config, &Config::default());
821 let fake = Arc::new(codewhale_lsp::tests::FakeTransport::new(vec![Diagnostic {
822 line: 1,
823 column: 1,
824 severity: Severity::Error,
825 message: "should not be reported".to_string(),
826 }]));
827 engine
828 .lsp_manager
829 .install_test_transport(Language::Rust, fake.clone())
830 .await;
831
832 let input = json!({ "path": "src/main.rs" });
833 engine.run_post_edit_lsp_hook("read_file", &input).await;
834 assert!(engine.pending_lsp_blocks.is_empty());
835 assert_eq!(fake.call_count(), 0);
836 }
837
838 #[test]
839 fn turn_tool_context_and_surface_gate_lsp_by_config() {
840 let tmp = tempdir().expect("tempdir");
841 let authority = crate::core::authority::TurnAuthority::from_effective_fields(
842 AppMode::Agent,
843 true,
844 true,
845 true,
846 ApprovalMode::Bypass,
847 );
848 let route_for = |engine: &Engine| TurnRouteContext {
849 provider: ProviderKind::Deepseek,
850 model: "test-model".to_string(),
851 capabilities: codewhale_config::route::RouteCapabilities::default(),
852 limits: None,
853 client: None,
854 api_config: Box::new(Config::default()),
855 locale_tag: engine.config.locale_tag.clone(),
856 role_models: engine.subagent_role_models(),
857 auto_model: false,
858 reasoning_effort: None,
859 reasoning_effort_auto: false,
860 };
861
862 let (engine_off, _handle_off) = Engine::new(
863 EngineConfig {
864 workspace: tmp.path().to_path_buf(),
865 lsp_config: None,
866 ..Default::default()
867 },
868 &Config::default(),
869 );
870 let ctx_off = engine_off.build_tool_context_for_turn(&authority, &route_for(&engine_off));
871 assert!(ctx_off.lsp_manager.is_none());
872
873 let registry_off = ToolRegistryBuilder::new()
874 .with_file_tools()
875 .with_lsp_tool()
876 .build(ctx_off);
877 let catalog_off = build_model_tool_catalog(
878 registry_off.to_api_tools_with_cache(true),
879 Vec::new(),
880 AppMode::Agent,
881 &HashSet::new(),
882 );
883 let surface_off = ToolSurfacePolicy::new(
884 registry_off,
885 Some(catalog_off),
886 AppMode::Agent,
887 &HashSet::new(),
888 false,
889 None,
890 None,
891 None,
892 crate::core::engine::tool_catalog::ToolMode::Direct,
893 );
894 assert!(surface_off.catalog.iter().all(|tool| tool.name != "lsp"));
895
896 let (engine_on, _handle_on) = Engine::new(
897 EngineConfig {
898 workspace: tmp.path().to_path_buf(),
899 lsp_config: Some(codewhale_lsp::LspConfig::default()),
900 ..Default::default()
901 },
902 &Config::default(),
903 );
904 let ctx_on = engine_on.build_tool_context_for_turn(&authority, &route_for(&engine_on));
905 assert!(
906 ctx_on
907 .lsp_manager
908 .as_ref()
909 .is_some_and(|manager| manager.config().enabled)
910 );
911
912 let registry_on = ToolRegistryBuilder::new()
913 .with_file_tools()
914 .with_lsp_tool()
915 .build(ctx_on);
916 let catalog_on = build_model_tool_catalog(
917 registry_on.to_api_tools_with_cache(true),
918 Vec::new(),
919 AppMode::Agent,
920 &HashSet::new(),
921 );
922 let surface_on = ToolSurfacePolicy::new(
923 registry_on,
924 Some(catalog_on),
925 AppMode::Agent,
926 &HashSet::new(),
927 false,
928 None,
929 None,
930 None,
931 crate::core::engine::tool_catalog::ToolMode::Direct,
932 );
933 assert!(surface_on.catalog.iter().any(|tool| tool.name == "lsp"));
934 }
935
936 // ── #3802: non-blocking send for ListSubAgents refresh events ─────────────
937
938 #[test]
939 fn agent_list_event_carries_the_typed_coordination_projection() {
940 use crate::tools::subagent::coord::{DecisionRecord, DecisionStatus};
941
942 let mut manager = SubAgentManager::new(PathBuf::from("."), 1);
943 let recorded = manager
944 .record_coordination_decision(DecisionRecord {
945 decision_id: "decision-event".to_string(),
946 subject: "typed event".to_string(),
947 status: DecisionStatus::Accepted,
948 owner: "root".to_string(),
949 scope: Vec::new(),
950 constraints: Vec::new(),
951 evidence_handles: Vec::new(),
952 version: 1,
953 sequence: 0,
954 })
955 .expect("record decision");
956 manager
957 .stamp_coordination_sequence_for_session(recorded.sequence, "session-a")
958 .expect("stamp decision owner");
959
960 let Event::AgentList {
961 owner_session_id,
962 agents,
963 coordination,
964 ..
965 } = agent_list_event(&manager, "session-a")
966 else {
967 panic!("expected AgentList event");
968 };
969 assert!(agents.is_empty());
970 assert_eq!(owner_session_id, "session-a");
971 assert_eq!(coordination.decisions.len(), 1);
972 assert_eq!(coordination.decisions[0].decision_id, "decision-event");
973 assert_eq!(coordination.decisions[0].status, DecisionStatus::Accepted);
974 assert!(coordination.bounded);
975 assert_eq!(coordination.limit, 24);
976 }
977
978 #[test]
979 fn engine_handle_try_send_does_not_block_when_op_channel_is_full() {
980 use tokio::sync::mpsc;
981
982 // Create a channel with the smallest possible capacity.
983 let (tx_op, rx_op) = mpsc::channel::<Op>(1);
984
985 // Construct a minimal EngineHandle with the tiny channel.
986 let cancel_token = CancellationToken::new();
987 let handle = EngineHandle {
988 run_completion: None,
989 mcp_auth_context: crate::mcp::process_mcp_auth_context(),
990 goal_state: new_shared_goal_state(),
991 sandbox_enforcement: codewhale_sandbox::policy::SandboxEnforcement::Unavailable,
992 tx_op,
993 rx_event: Arc::new(RwLock::new(mpsc::channel::<Event>(1).1)),
994 cancel_token: Arc::new(StdMutex::new(cancel_token)),
995 cancel_reason: Arc::new(StdMutex::new(None)),
996 tx_approval: mpsc::channel(1).0,
997 current_approval: Arc::new(parking_lot::Mutex::new(None)),
998 mock_approval_publications: None,
999 tx_user_input: mpsc::channel(1).0,
1000 tx_steer: mpsc::channel(1).0,
1001 turn_controls: Arc::new(StdMutex::new(handle::TurnControls::default())),
1002 host_profile: EngineHostProfile::Normal,
1003 owner_surface_attached: false,
1004 shared_paused: Arc::new(StdMutex::new(false)),
1005 client_preflight_required: true,
1006 live_runtime_authority: Arc::new(StdMutex::new(LiveRuntimeAuthorityState::new(
1007 LiveRuntimeAuthority::from_fields(
1008 AppMode::Agent,
1009 false,
1010 false,
1011 false,
1012 ApprovalMode::Suggest,
1013 None,
1014 ),
1015 ))),
1016 auto_review_state: Arc::new(parking_lot::Mutex::new(
1017 crate::core::authority::auto_review::AutoReviewConversationState::default(),
1018 )),
1019 compaction_cancellation: Arc::new(StdMutex::new(CompactionCancellationState::default())),
1020 turn_heartbeat: turn_heartbeat::TurnHeartbeat::new(),
1021 subagent_manager: crate::tools::subagent::new_shared_subagent_manager(
1022 std::env::temp_dir(),
1023 1,
1024 ),
1025 terminal_worker_events: None,
1026 mcp_pool_slot: Arc::default(),
1027 exec_policy: codewhale_execpolicy::ExecPolicyEngine::default(),
1028 };
1029
1030 // Fill the op channel with one message (capacity = 1).
1031 handle
1032 .tx_op
1033 .try_send(Op::ListSubAgents)
1034 .expect("first send should succeed");
1035
1036 // A live posture update must publish immediately even though its wake-up
1037 // cannot fit. The already-queued operation will wake the engine, which
1038 // applies this pending authority before handling it.
1039 let result = handle.try_send(Op::ChangeMode {
1040 mode: AppMode::Agent,
1041 allow_shell: true,
1042 trust_mode: false,
1043 auto_approve: false,
1044 approval_mode: ApprovalMode::Auto,
1045 configured_sandbox_mode: None,
1046 });
1047 let error = result.expect_err("try_send should fail when channel is full");
1048 assert!(matches!(
1049 error.downcast_ref::<mpsc::error::TrySendError<Op>>(),
1050 Some(mpsc::error::TrySendError::Full(Op::ChangeMode { .. }))
1051 ));
1052 let authority = handle.runtime_permission_authority();
1053 assert_eq!(authority.approval_mode, ApprovalMode::Auto);
1054 assert!(!authority.auto_approve);
1055
1056 handle
1057 .cancel_compaction("compact-full-mailbox")
1058 .expect("full mailbox must not block compaction cancellation");
1059 assert!(
1060 handle
1061 .compaction_cancellation
1062 .lock()
1063 .expect("cancellation state")
1064 .claim("compact-full-mailbox")
1065 .is_none(),
1066 "cancellation authority remains visible even when its wake-up op cannot fit"
1067 );
1068 drop(rx_op);
1069 let error = handle.try_send(Op::ListSubAgents).unwrap_err();
1070 assert!(matches!(
1071 error.downcast_ref::<mpsc::error::TrySendError<Op>>(),
1072 Some(mpsc::error::TrySendError::Closed(Op::ListSubAgents))
1073 ));
1074 }
1075
1076 #[tokio::test]
1077 async fn full_mailbox_posture_update_supersedes_queued_change_mode() {
1078 use ApprovalMode;
1079
1080 let tmp = tempdir().expect("tempdir");
1081 let config = EngineConfig {
1082 workspace: tmp.path().to_path_buf(),
1083 ..Default::default()
1084 };
1085 let (engine, handle) = Engine::new(config, &Config::default());
1086
1087 handle
1088 .try_send(Op::ChangeMode {
1089 mode: AppMode::Plan,
1090 allow_shell: false,
1091 trust_mode: false,
1092 auto_approve: false,
1093 approval_mode: ApprovalMode::Suggest,
1094 configured_sandbox_mode: None,
1095 })
1096 .expect("queue older posture");
1097 for _ in 1..ENGINE_OP_CHANNEL_CAPACITY {
1098 handle
1099 .try_send(Op::ListSubAgents)
1100 .expect("fill operation mailbox");
1101 }
1102
1103 let result = handle.try_send(Op::ChangeMode {
1104 mode: AppMode::Agent,
1105 allow_shell: true,
1106 trust_mode: false,
1107 auto_approve: false,
1108 approval_mode: ApprovalMode::Auto,
1109 configured_sandbox_mode: Some("read-only".to_string()),
1110 });
1111 assert!(
1112 result.is_err(),
1113 "latest posture wake-up must see a full mailbox"
1114 );
1115
1116 let run = tokio::spawn(engine.run());
1117 let snapshot = tokio::time::timeout(
1118 std::time::Duration::from_secs(2),
1119 handle.get_session_snapshot(),
1120 )
1121 .await
1122 .expect("snapshot after mailbox drain")
1123 .expect("session snapshot");
1124
1125 assert_eq!(snapshot.mode, "agent");
1126 let authority = handle.runtime_permission_authority();
1127 assert_eq!(authority.approval_mode, ApprovalMode::Auto);
1128 assert!(!authority.auto_approve);
1129
1130 handle.send(Op::Shutdown).await.expect("shutdown engine");
1131 run.await.expect("engine task");
1132 }
1133
1134 #[tokio::test]
1135 async fn reload_mcp_op_recovers_from_invalid_initial_config_in_process() {
1136 let tmp = tempdir().expect("tempdir");
1137 let workspace = tmp.path().join("workspace");
1138 std::fs::create_dir_all(&workspace).expect("workspace");
1139 let config_path = tmp.path().join("mcp.json");
1140 let secret = "mcp-op-secret-must-not-escape";
1141 std::fs::write(
1142 &config_path,
1143 format!(r#"{{"servers":{{"bad":{{"token":"{secret}"}} trailing}}}}"#),
1144 )
1145 .expect("invalid config");
1146 let engine_config = EngineConfig {
1147 workspace,
1148 mcp_config_path: config_path.clone(),
1149 ..Default::default()
1150 };
1151 let (engine, handle) = Engine::new(engine_config, &Config::default());
1152 let task = tokio::spawn(async move { engine.run().await });
1153
1154 let error = handle
1155 .reload_mcp(config_path.clone())
1156 .await
1157 .expect_err("invalid config must fail closed");
1158 assert!(!error.to_string().contains(secret));
1159 std::fs::write(
1160 &config_path,
1161 r#"{"servers":{"ready":{"command":"node","disabled":true}}}"#,
1162 )
1163 .expect("fixed config");
1164
1165 let snapshot = handle
1166 .reload_mcp(config_path.clone())
1167 .await
1168 .expect("fixed config reloads without restarting the engine")
1169 .snapshot;
1170 assert!(!snapshot.reload_required);
1171 assert_eq!(snapshot.servers.len(), 1);
1172 assert_eq!(snapshot.servers[0].name, "ready");
1173 assert!(!snapshot.servers[0].enabled);
1174
1175 let alternate_path = tmp.path().join("alternate-mcp.json");
1176 std::fs::write(
1177 &alternate_path,
1178 r#"{"servers":{"alternate":{"command":"node","disabled":true}}}"#,
1179 )
1180 .expect("alternate config");
1181 let alternate = handle
1182 .reload_mcp(alternate_path.clone())
1183 .await
1184 .expect("a changed config path replaces the engine pool in process")
1185 .snapshot;
1186 assert_eq!(alternate.config_path, alternate_path);
1187 assert_eq!(alternate.servers.len(), 1);
1188 assert_eq!(alternate.servers[0].name, "alternate");
1189
1190 handle.send(Op::Shutdown).await.expect("shutdown");
1191 task.await.expect("engine task");
1192 }
1193
1194 #[tokio::test]
1195 async fn mcp_boot_reports_ready_server_before_stalled_server_finishes() {
1196 assert_incremental_mcp_boot(false).await;
1197 }
1198
1199 fn test_node_binary() -> Option<String> {
1200 std::process::Command::new("node")
1201 .arg("--version")
1202 .output()
1203 .is_ok_and(|out| out.status.success())
1204 .then(|| "node".to_string())
1205 }
1206
1207 #[tokio::test]
1208 async fn first_turn_waits_for_explicit_mcp_schema_without_waiting_for_unrelated_server() {
1209 let Some(node) = test_node_binary() else {
1210 return;
1211 };
1212 let tmp = tempdir().expect("tempdir");
1213 let fixture_manager = Arc::new(crate::extension_host::ExtensionHostManager::new(
1214 crate::extension_host::ExtensionHostOptions {
1215 root: Some(tmp.path().join("host-home")),
1216 ..Default::default()
1217 },
1218 ));
1219 let _fixture_manager_guard =
1220 crate::extension_host::TestManagerGuard::install(Arc::clone(&fixture_manager));
1221 let server = tmp.path().join("server.mjs");
1222 let release = tmp.path().join("release-slow");
1223 let release_fast = tmp.path().join("release-fast");
1224 fs::write(&server, r#"import fs from 'node:fs';
1225 import path from 'node:path';
1226 import readline from 'node:readline';
1227 readline.createInterface({ input: process.stdin }).on('line', async line => {
1228 const request = JSON.parse(line);
1229 if (request.id === undefined) return;
1230 if (request.method === 'initialize') {
1231 fs.writeFileSync(path.join(process.argv[3], 'started-' + process.argv[2]), 'ready');
1232 while (!fs.existsSync(path.join(process.argv[3], 'release-' + process.argv[2]))) await new Promise(r => setTimeout(r, 10));
1233 }
1234 const result = request.method === 'initialize'
1235 ? { protocolVersion: '2024-11-05', capabilities: { tools: {} }, serverInfo: { name: process.argv[2], version: '1' } }
1236 : { tools: ['ready', 'denied', 'hidden'].map(name => ({ name, inputSchema: { type: 'object' } })) };
1237 process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, result }) + '\n');
1238 });"#).expect("fixture");
1239 let config_path = tmp.path().join("mcp.json");
1240 fs::write(
1241 &config_path,
1242 serde_json::to_vec(&json!({
1243 // `slow` must still be connecting when the fast build completes,
1244 // and `fast` must not be declared dead while a cold Windows runner
1245 // spawns Node. Ordering here is proven by the release files below,
1246 // never by a timeout, so this bound only has to outlast the test.
1247 "timeouts": { "connect_timeout": 120 },
1248 "servers": {
1249 "fast": { "command": node, "args": [server, "fast", tmp.path()] },
1250 // `slow` is deliberately unselected: `required` keeps it in
1251 // the eager boot set under lazy boot (#6033) so it can stand
1252 // in for "an unrelated server still connecting".
1253 "slow": { "command": node, "args": [server, "slow", tmp.path()], "required": true },
1254 "failed": { "command": "codewhale-missing-mcp-fixture-38911" }
1255 }
1256 }))
1257 .unwrap(),
1258 )
1259 .unwrap();
1260 let api_config = Config::default();
1261 let (mut engine, _handle) = Engine::new(
1262 EngineConfig {
1263 workspace: tmp.path().to_path_buf(),
1264 mcp_config_path: config_path,
1265 tools_always_load: HashSet::from(["mcp_fast_ready".to_string()]),
1266 ..Default::default()
1267 },
1268 &api_config,
1269 );
1270 engine
1271 .start_mcp_session_boot(McpConnectRefresh::IfChanged)
1272 .await
1273 .expect("session boot starts");
1274 assert!(
1275 engine.mcp_tools().await.is_empty(),
1276 "ordinary startup remains nonblocking"
1277 );
1278 // Separate Windows/CI process startup from the schema-wait assertion.
1279 // Both children have received initialize, but neither can answer until
1280 // this test releases its own gate. No fixed delay stands in for readiness.
1281 // The budget is generous because it covers two cold Node spawns on a
1282 // windows-latest runner that has just finished a ~15 min compile; a tight
1283 // bound here fails the setup, not the behavior under test.
1284 tokio::time::timeout(Duration::from_secs(60), async {
1285 while !tmp.path().join("started-fast").exists() || !tmp.path().join("started-slow").exists()
1286 {
1287 engine.drain_mcp_boot_updates().await;
1288 for name in ["fast", "slow"] {
1289 assert!(
1290 !engine.mcp_connection_errors.contains_key(name),
1291 "{name} fixture failed before initialize: {:?}",
1292 engine.mcp_connection_errors.get(name)
1293 );
1294 }
1295 tokio::time::sleep(Duration::from_millis(10)).await;
1296 }
1297 })
1298 .await
1299 .expect("both MCP fixtures must reach initialize before checking first-turn ordering");
1300 let route = TurnRouteContext {
1301 provider: ProviderKind::Deepseek,
1302 model: DEFAULT_TEXT_MODEL.to_string(),
1303 capabilities: codewhale_config::route::RouteCapabilities::default(),
1304 limits: None,
1305 client: engine.codewhale_client.clone(),
1306 api_config: Box::new(api_config),
1307 locale_tag: engine.config.locale_tag.clone(),
1308 role_models: engine.subagent_role_models(),
1309 auto_model: false,
1310 reasoning_effort: None,
1311 reasoning_effort_auto: false,
1312 };
1313 let policy = crate::core::authority::TurnAuthority::from_effective_fields(
1314 AppMode::Agent,
1315 false,
1316 false,
1317 false,
1318 ApprovalMode::Suggest,
1319 );
1320 let build = {
1321 let build = engine.build_turn_tool_registry_and_catalog(
1322 &policy,
1323 &[],
1324 Some(vec![
1325 "mcp_fast_ready".to_string(),
1326 "mcp_failed_ready".to_string(),
1327 ]),
1328 SubAgentWiring::Inert,
1329 McpAccess::Connect,
1330 &[],
1331 route,
1332 "",
1333 );
1334 tokio::pin!(build);
1335 std::future::poll_fn(|cx| {
1336 assert!(
1337 std::future::Future::poll(build.as_mut(), cx).is_pending(),
1338 "the first turn must wait for the explicitly selected fast schema"
1339 );
1340 std::task::Poll::Ready(())
1341 })
1342 .await;
1343 fs::write(&release_fast, "release").unwrap();
1344 tokio::time::timeout(Duration::from_secs(5), build).await
1345 };
1346 let unrelated_pending = !release.exists()
1347 && engine.mcp_boot_in_flight
1348 && !engine.mcp_connection_errors.contains_key("slow");
1349 let connected = engine
1350 .mcp_pool
1351 .as_ref()
1352 .unwrap()
1353 .lock()
1354 .await
1355 .connected_servers()
1356 .into_iter()
1357 .map(str::to_owned)
1358 .collect::<Vec<_>>();
1359 engine.cancel_token.cancel();
1360 tokio::time::timeout(
1361 Duration::from_millis(100),
1362 engine.wait_for_explicit_mcp_boot(Some(&["mcp_slow_ready".to_string()]), &[]),
1363 )
1364 .await
1365 .expect("stop interrupts explicit schema wait");
1366 let _turn_control = engine.begin_turn_control();
1367 fs::write(&release, "release").unwrap();
1368 let build = build.unwrap_or_else(|error| {
1369 panic!(
1370 "explicit fast/failed selections must not wait for slow: {error:?}; connected={connected:?}; errors={:?}",
1371 engine.mcp_connection_errors
1372 )
1373 });
1374 assert!(
1375 unrelated_pending,
1376 "success must precede the unrelated server's release, completion, or timeout"
1377 );
1378 let active = build.surface.active.unwrap_or_default();
1379 assert_eq!(
1380 active
1381 .iter()
1382 .map(|tool| tool.name.as_str())
1383 .collect::<Vec<_>>(),
1384 ["mcp_fast_ready"]
1385 );
1386 assert!(engine.mcp_connection_errors.contains_key("failed"));
1387
1388 // The unrelated connection finishes during the same turn. Refresh into a
1389 // narrowed policy, then execute the actual tool-search activation path.
1390 let policy = ToolSurfacePolicy::new(
1391 ToolRegistryBuilder::new().build(ToolContext::for_empty_registry()),
1392 Some(vec![api_tool("read")]),
1393 AppMode::Agent,
1394 &HashSet::new(),
1395 false,
1396 Some(vec![
1397 "tool_search".into(),
1398 "mcp_slow_ready".into(),
1399 "mcp_slow_denied".into(),
1400 ]),
1401 Some(vec!["mcp_slow_denied".into()]),
1402 None,
1403 crate::core::engine::tool_catalog::ToolMode::Direct,
1404 );
1405 let mut catalog = policy.catalog.clone();
1406 let mut active = policy.active_names.clone();
1407 catalog.push(api_tool("mcp_removed_ready"));
1408 active.insert("mcp_removed_ready".to_string());
1409 tokio::time::timeout(Duration::from_secs(5), async {
1410 while !catalog.iter().any(|tool| tool.name == "mcp_slow_ready") {
1411 engine
1412 .refresh_boot_mcp_catalog(&policy, &mut catalog, &mut active)
1413 .await;
1414 tokio::task::yield_now().await;
1415 }
1416 })
1417 .await
1418 .expect("completed tools join this turn");
1419 assert!(
1420 !active.contains("mcp_slow_ready"),
1421 "fresh MCP tools stay deferred"
1422 );
1423 assert!(
1424 !active.contains("mcp_removed_ready"),
1425 "removed authority leaves active tools"
1426 );
1427 assert!(
1428 catalog
1429 .iter()
1430 .all(|tool| !tool.name.starts_with("mcp_") || tool.name == "mcp_slow_ready")
1431 );
1432 let result = tool_catalog::execute_tool_search_with_cache(
1433 "tool_search",
1434 &json!({"query":"mcp_slow_ready", "match":"regex"}),
1435 &catalog,
1436 &mut active,
1437 &mut engine.session.tool_activation_cache,
1438 )
1439 .expect("real search");
1440 assert!(result.success);
1441 assert!(active.contains("mcp_slow_ready"));
1442 engine.wait_for_mcp_boot().await;
1443 fixture_manager.shutdown().await;
1444 }
1445
1446 #[tokio::test]
1447 async fn mcp_boot_does_not_restore_servers_removed_during_handshake() {
1448 assert_incremental_mcp_boot(true).await;
1449 }
1450
1451 async fn assert_incremental_mcp_boot(invalidate_config: bool) {
1452 if std::process::Command::new("node")
1453 .arg("--version")
1454 .output()
1455 .is_err()
1456 {
1457 tracing::warn!("skipping MCP stdio fixture because node is unavailable");
1458 return;
1459 }
1460 let tmp = tempdir().expect("tempdir");
1461 let fixture_manager = Arc::new(crate::extension_host::ExtensionHostManager::new(
1462 crate::extension_host::ExtensionHostOptions {
1463 root: Some(tmp.path().join("host-home")),
1464 ..Default::default()
1465 },
1466 ));
1467 let _fixture_manager_guard =
1468 crate::extension_host::TestManagerGuard::install(Arc::clone(&fixture_manager));
1469 let server = tmp.path().join("server.mjs");
1470 let release = tmp.path().join("release-slow");
1471 std::fs::write(
1472 &server,
1473 r#"import fs from 'node:fs';
1474 import readline from 'node:readline';
1475 const lines = readline.createInterface({ input: process.stdin });
1476 lines.on('line', async (line) => {
1477 const request = JSON.parse(line);
1478 if (request.id === undefined) return;
1479 if (process.argv[2] === 'slow' && request.method === 'initialize') {
1480 while (!fs.existsSync(process.argv[3])) {
1481 await new Promise(resolve => setTimeout(resolve, 10));
1482 }
1483 }
1484 const result = request.method === 'initialize'
1485 ? { protocolVersion: '2024-11-05', capabilities: { tools: {} },
1486 serverInfo: { name: process.argv[2], version: '1' } }
1487 : { tools: [{ name: 'ready', inputSchema: { type: 'object' } }] };
1488 process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, result }) + '\n');
1489 });
1490 "#,
1491 )
1492 .expect("server fixture");
1493 let config_path = tmp.path().join("mcp.json");
1494 std::fs::write(
1495 &config_path,
1496 serde_json::to_vec(&serde_json::json!({
1497 "timeouts": { "connect_timeout": 30 },
1498 "servers": {
1499 // Both marked `required` so lazy boot (#6033) still starts
1500 // them eagerly — this test proves progress ordering, not the
1501 // lazy/eligible split.
1502 "fast": { "command": "node", "args": [server, "fast", release], "required": true },
1503 "slow": { "command": "node", "args": [server, "slow", release], "required": true }
1504 }
1505 }))
1506 .expect("config JSON"),
1507 )
1508 .expect("MCP config");
1509 let (mut engine, handle) = Engine::new(
1510 EngineConfig {
1511 workspace: tmp.path().to_path_buf(),
1512 mcp_config_path: config_path.clone(),
1513 ..Default::default()
1514 },
1515 &Config::default(),
1516 );
1517 let pool = engine.ensure_mcp_pool().await.expect("engine pool");
1518 let task = tokio::spawn(async move { engine.run().await });
1519 let mut events = handle.rx_event.write().await;
1520 // This proves ordering, not Node cold-start speed on a loaded runner.
1521 let progress = tokio::time::timeout(Duration::from_secs(30), async {
1522 while let Some(event) = events.recv().await {
1523 if let Event::McpSessionBoot {
1524 snapshot,
1525 connecting,
1526 finished: false,
1527 ..
1528 } = event
1529 && connecting == ["slow"]
1530 {
1531 return snapshot;
1532 }
1533 }
1534 panic!("engine event channel closed");
1535 })
1536 .await;
1537 let ready_tools = pool.lock().await.to_api_tools();
1538 if invalidate_config {
1539 std::fs::write(
1540 &config_path,
1541 r#"{"servers":{"slow":{"command":"node","disabled":true}}}"#,
1542 )
1543 .expect("remove servers");
1544 pool.lock()
1545 .await
1546 .reload_if_config_changed()
1547 .await
1548 .expect("reload config");
1549 }
1550 // Release and shut down even when testing the old batch-buffered behavior.
1551 std::fs::write(&release, "continue").expect("release stalled fixture");
1552 let finished = tokio::time::timeout(Duration::from_secs(30), async {
1553 while let Some(event) = events.recv().await {
1554 if let Event::McpSessionBoot {
1555 snapshot,
1556 finished: true,
1557 ..
1558 } = event
1559 {
1560 return snapshot;
1561 }
1562 }
1563 panic!("engine event channel closed");
1564 })
1565 .await;
1566 drop(events);
1567 handle.send(Op::Shutdown).await.expect("shutdown");
1568 task.await.expect("engine task");
1569 fixture_manager.shutdown().await;
1570 let progress = progress.expect("fast server must be visible before slow server is released");
1571 assert!(
1572 progress
1573 .servers
1574 .iter()
1575 .any(|row| row.name == "fast" && row.connected)
1576 );
1577 assert!(
1578 progress
1579 .servers
1580 .iter()
1581 .any(|row| row.name == "slow" && !row.connected)
1582 );
1583 assert!(ready_tools.iter().any(|tool| tool.name == "mcp_fast_ready"));
1584 assert!(!ready_tools.iter().any(|tool| tool.name == "mcp_slow_ready"));
1585 let finished = finished.expect("finished boot");
1586 if invalidate_config {
1587 assert_eq!(finished.servers.len(), 1);
1588 assert!(!finished.servers[0].enabled);
1589 assert!(!finished.servers[0].connected);
1590 assert!(pool.lock().await.to_api_tools().is_empty());
1591 } else {
1592 assert!(finished.servers.iter().all(|row| row.connected));
1593 }
1594 }
1595
1596 /// Lazy boot (#6033): a configured server nobody selected and nobody marked
1597 /// `required` must not be spawned at session start. The fixture writes a
1598 /// `started-<name>` marker when it receives `initialize`, so the lazy
1599 /// server's absence is proven by the file that never appears — not by a
1600 /// timeout on "it would have started by now".
1601 #[tokio::test]
1602 async fn lazy_boot_leaves_unselected_servers_unspawned() {
1603 let Some(node) = test_node_binary() else {
1604 return;
1605 };
1606 let tmp = tempdir().expect("tempdir");
1607 let server = tmp.path().join("server.mjs");
1608 fs::write(
1609 &server,
1610 r#"import fs from 'node:fs';
1611 import path from 'node:path';
1612 import readline from 'node:readline';
1613 readline.createInterface({ input: process.stdin }).on('line', line => {
1614 const request = JSON.parse(line);
1615 if (request.id === undefined) return;
1616 if (request.method === 'initialize') {
1617 fs.writeFileSync(path.join(process.argv[3], 'started-' + process.argv[2]), 'ready');
1618 }
1619 const result = request.method === 'initialize'
1620 ? { protocolVersion: '2024-11-05', capabilities: { tools: {} }, serverInfo: { name: process.argv[2], version: '1' } }
1621 : { tools: [{ name: 'ready', inputSchema: { type: 'object' } }] };
1622 process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, result }) + '\n');
1623 });"#,
1624 )
1625 .expect("fixture");
1626 let config_path = tmp.path().join("mcp.json");
1627 fs::write(
1628 &config_path,
1629 serde_json::to_vec(&serde_json::json!({
1630 "servers": {
1631 "eager": { "command": node, "args": [server, "eager", tmp.path()], "required": true },
1632 "lazy": { "command": node, "args": [server, "lazy", tmp.path()], "lazy": true }
1633 }
1634 }))
1635 .unwrap(),
1636 )
1637 .expect("MCP config");
1638 let (engine, handle) = Engine::new(
1639 EngineConfig {
1640 workspace: tmp.path().to_path_buf(),
1641 mcp_config_path: config_path,
1642 ..Default::default()
1643 },
1644 &Config::default(),
1645 );
1646 let task = tokio::spawn(async move { engine.run().await });
1647 let mut events = handle.rx_event.write().await;
1648 let finished = tokio::time::timeout(Duration::from_secs(30), async {
1649 while let Some(event) = events.recv().await {
1650 if let Event::McpSessionBoot {
1651 snapshot,
1652 connecting,
1653 finished: true,
1654 ..
1655 } = event
1656 {
1657 return (snapshot, connecting);
1658 }
1659 }
1660 panic!("engine event channel closed");
1661 })
1662 .await
1663 .expect("boot must finish");
1664 drop(events);
1665 handle.send(Op::Shutdown).await.expect("shutdown");
1666 task.await.expect("engine task");
1667
1668 let (snapshot, connecting) = finished;
1669 assert!(
1670 tmp.path().join("started-eager").exists(),
1671 "a required server is still eager"
1672 );
1673 assert!(
1674 !tmp.path().join("started-lazy").exists(),
1675 "an unselected, unrequired server must not be spawned at boot"
1676 );
1677 assert!(connecting.is_empty());
1678 let lazy = snapshot
1679 .servers
1680 .iter()
1681 .find(|server| server.name == "lazy")
1682 .expect("configured lazy server still appears in the snapshot");
1683 assert!(!lazy.connected);
1684 assert!(lazy.error.is_none(), "lazy is a state, not a failure");
1685 let eager = snapshot
1686 .servers
1687 .iter()
1688 .find(|server| server.name == "eager")
1689 .expect("required server in snapshot");
1690 assert!(eager.connected);
1691
1692 let (mut engine, _handle) = Engine::new(
1693 EngineConfig {
1694 workspace: tmp.path().to_path_buf(),
1695 mcp_config_path: tmp.path().join("mcp.json"),
1696 ..Default::default()
1697 },
1698 &Config::default(),
1699 );
1700 engine.ensure_mcp_pool().await.expect("MCP pool");
1701 let dependencies = ["lazy".to_string(), "unknown".to_string()];
1702 engine
1703 .wait_for_explicit_mcp_boot(Some(&[]), &dependencies)
1704 .await;
1705 assert!(!tmp.path().join("started-lazy").exists());
1706 engine.wait_for_explicit_mcp_boot(None, &dependencies).await;
1707 assert!(tmp.path().join("started-lazy").exists());
1708 assert!(!tmp.path().join("started-unknown").exists());
1709 }
1710
1711 #[tokio::test]
1712 async fn mcp_boot_updates_preserve_authority_errors_and_replace_ordinary_errors() {
1713 let tmp = tempdir().expect("tempdir");
1714 let engine_config = EngineConfig {
1715 workspace: tmp.path().to_path_buf(),
1716 ..Default::default()
1717 };
1718 let (mut engine, _handle) = Engine::new(engine_config, &Config::default());
1719 engine.mcp_event_generation = 3;
1720 engine.mcp_boot_generation = Some(3);
1721 engine.mcp_boot_in_flight = true;
1722 engine.mcp_connection_errors = HashMap::from([(
1723 "stale-transport".to_string(),
1724 "obsolete connection failure".to_string(),
1725 )]);
1726 let authority_errors = Arc::new(HashMap::from([(
1727 "revoked-plugin".to_string(),
1728 "plugin authority revoked or changed".to_string(),
1729 )]));
1730
1731 engine
1732 .apply_mcp_boot_update(McpBootUpdate::Progress {
1733 generation: 3,
1734 authority_errors: Arc::clone(&authority_errors),
1735 connection_errors: HashMap::from([(
1736 "current-transport".to_string(),
1737 "current connection failure".to_string(),
1738 )]),
1739 connecting: Vec::new(),
1740 })
1741 .await;
1742 assert_eq!(
1743 engine.mcp_connection_errors,
1744 HashMap::from([
1745 (
1746 "revoked-plugin".to_string(),
1747 "plugin authority revoked or changed".to_string(),
1748 ),
1749 (
1750 "current-transport".to_string(),
1751 "current connection failure".to_string(),
1752 ),
1753 ])
1754 );
1755 assert!(!engine.mcp_connection_errors.contains_key("stale-transport"));
1756 assert_eq!(
1757 engine.session.pending_prefix_change_reason.as_deref(),
1758 Some("mcp-session-boot")
1759 );
1760
1761 engine.mcp_connection_errors.insert(
1762 "stale-between-updates".to_string(),
1763 "must not survive finished".to_string(),
1764 );
1765 engine
1766 .apply_mcp_boot_update(McpBootUpdate::Finished {
1767 generation: 3,
1768 authority_errors,
1769 connection_errors: HashMap::from([(
1770 "final-transport".to_string(),
1771 "final connection failure".to_string(),
1772 )]),
1773 })
1774 .await;
1775 assert_eq!(
1776 engine.mcp_connection_errors,
1777 HashMap::from([
1778 (
1779 "revoked-plugin".to_string(),
1780 "plugin authority revoked or changed".to_string(),
1781 ),
1782 (
1783 "final-transport".to_string(),
1784 "final connection failure".to_string(),
1785 ),
1786 ])
1787 );
1788 }
1789 // Actual optional stdio servers; no provider request or invented tool catalogue.
1790 async fn mcp_search_fixture(
1791 allowed: Option<Vec<String>>,
1792 ) -> (
1793 crate::extension_host::TestManagerGuard,
1794 Arc<crate::extension_host::ExtensionHostManager>,
1795 Engine,
1796 tool_catalog::ToolSurfacePolicy,
1797 tempfile::TempDir,
1798 Arc<crate::llm_client::mock::MockLlmClient>,
1799 ) {
1800 let node = test_node_binary().expect("MCP discovery qualification requires Node");
1801 let tmp = tempdir().expect("tempdir");
1802 let fixture_manager = Arc::new(crate::extension_host::ExtensionHostManager::new(
1803 crate::extension_host::ExtensionHostOptions {
1804 root: Some(tmp.path().join("host-home")),
1805 ..Default::default()
1806 },
1807 ));
1808 let fixture_manager_guard =
1809 crate::extension_host::TestManagerGuard::install(Arc::clone(&fixture_manager));
1810 let server = tmp.path().join("discovery.mjs");
1811 fs::write(&server, r#"import fs from 'node:fs';
1812 import path from 'node:path';
1813 import readline from 'node:readline';
1814 readline.createInterface({input:process.stdin}).on('line', line => {
1815 const r = JSON.parse(line); if (r.id === undefined) return;
1816 const name = process.argv[2], root = process.argv[3];
1817 if (r.method === 'initialize') {
1818 fs.writeFileSync(path.join(root, 'started-' + name), 'started');
1819 if (name === 'stalled') return;
1820 }
1821 if (r.method === 'tools/list') fs.writeFileSync(path.join(root, 'listed-' + name), 'listed');
1822 const result = r.method === 'initialize'
1823 ? {protocolVersion:'2024-11-05',capabilities:{tools:{}},serverInfo:{name,version:'1'}}
1824 : {tools:[{name:'actual',description:'Actual MCP fixture',inputSchema:{type:'object',properties:{verified:{type:'boolean'}},required:['verified']}}]};
1825 process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:r.id,result}) + '\n');
1826 });"#).unwrap();
1827 let config_path = tmp.path().join("mcp.json");
1828 fs::write(
1829 &config_path,
1830 serde_json::to_vec(&json!({"servers": {
1831 "engram": {"command":node,"args":[server,"engram",tmp.path()],"required":false,"lazy":true},
1832 "unrelated": {"command":node,"args":[server,"unrelated",tmp.path()],"required":false,"lazy":true},
1833 "disabled": {"command":node,"args":[server,"disabled",tmp.path()],"enabled":false},
1834 "stalled": {"command":node,"args":[server,"stalled",tmp.path()],"required":false,"lazy":true},
1835 "failed": {"command":"codewhale-missing-mcp-discovery-6828","lazy":true}
1836 }}))
1837 .unwrap(),
1838 )
1839 .unwrap();
1840 let api = Config::default();
1841 let model = Arc::new(crate::llm_client::mock::MockLlmClient::new(Vec::new()));
1842 let client: crate::core::model_client::SharedModelClient = model.clone();
1843 let (mut engine, _) = Engine::new_with_model_client(
1844 EngineConfig {
1845 workspace: tmp.path().to_path_buf(),
1846 mcp_config_path: config_path,
1847 ..Default::default()
1848 },
1849 &api,
1850 client,
1851 );
1852 engine
1853 .start_mcp_session_boot(McpConnectRefresh::IfChanged)
1854 .await
1855 .unwrap();
1856 assert!(
1857 !tmp.path().join("started-engram").exists(),
1858 "optional boot must remain lazy"
1859 );
1860 let authority = crate::core::authority::TurnAuthority::from_effective_fields(
1861 AppMode::Agent,
1862 true,
1863 false,
1864 false,
1865 ApprovalMode::Suggest,
1866 );
1867 let route = TurnRouteContext {
1868 provider: ProviderKind::Deepseek,
1869 model: DEFAULT_TEXT_MODEL.to_string(),
1870 capabilities: codewhale_config::route::RouteCapabilities::default(),
1871 limits: None,
1872 client: engine.codewhale_client.clone(),
1873 api_config: Box::new(api),
1874 locale_tag: engine.config.locale_tag.clone(),
1875 role_models: engine.subagent_role_models(),
1876 auto_model: false,
1877 reasoning_effort: None,
1878 reasoning_effort_auto: false,
1879 };
1880 let build = engine
1881 .build_turn_tool_registry_and_catalog(
1882 &authority,
1883 &[],
1884 allowed,
1885 SubAgentWiring::Inert,
1886 McpAccess::Connect,
1887 &[],
1888 route,
1889 "discovery",
1890 )
1891 .await;
1892 (
1893 fixture_manager_guard,
1894 fixture_manager,
1895 engine,
1896 build.surface,
1897 tmp,
1898 model,
1899 )
1900 }
1901
1902 #[tokio::test]
1903 async fn mcp_tool_search_discovers_optional_server_real_schema_without_eager_siblings() {
1904 let (_fixture_manager_guard, fixture_manager, mut engine, policy, tmp, model) =
1905 mcp_search_fixture(None).await;
1906 let mut surface = crate::core::engine::ChildSurfaceProbe {
1907 policy,
1908 cache: crate::core::session::ToolActivationCache::default(),
1909 };
1910 let result = engine
1911 .probe_child_tool_batch(
1912 &mut surface,
1913 crate::core::engine::ChildProbeCall {
1914 id: "mcp-discovery".into(),
1915 execution_id: "mcp-discovery".into(),
1916 name: "tool_search".into(),
1917 input: json!({"query":"engram","match":"bm25"}),
1918 },
1919 )
1920 .await
1921 .expect("actual Core planner and executor search");
1922 assert!(result.result.success);
1923 let catalog = &surface.policy.catalog;
1924 assert!(
1925 tmp.path().join("listed-engram").exists(),
1926 "schema must come from tools/list"
1927 );
1928 assert!(!tmp.path().join("started-unrelated").exists());
1929 let tool = catalog
1930 .iter()
1931 .find(|tool| tool.name == "mcp_engram_actual")
1932 .expect("real advertised tool");
1933 assert_eq!(
1934 tool.input_schema["properties"]["verified"]["type"],
1935 "boolean"
1936 );
1937 assert_eq!(tool.input_schema["required"], json!(["verified"]));
1938 assert!(surface.policy.active_names.contains("mcp_engram_actual"));
1939 assert!(
1940 result.result.metadata.as_ref().unwrap()["tool_references"]
1941 .as_array()
1942 .unwrap()
1943 .iter()
1944 .any(|name| name == "mcp_engram_actual")
1945 );
1946 assert!(!catalog.iter().any(|tool| tool.name == "mcp_engram_guessed"));
1947 assert_eq!(
1948 model.call_count(),
1949 0,
1950 "MCP discovery must not call a provider"
1951 );
1952 fixture_manager.shutdown().await;
1953 }
1954
1955 #[tokio::test]
1956 async fn mcp_tool_search_respects_captured_turn_ceiling_and_disabled_servers() {
1957 let (_fixture_manager_guard, fixture_manager, mut engine, policy, tmp, model) =
1958 mcp_search_fixture(Some(vec!["tool_search".into()])).await;
1959 let mut catalog = policy.catalog.clone();
1960 let mut active = policy.active_names.clone();
1961 engine
1962 .discover_mcp_for_tool_search(
1963 ("tool_search", &json!({"query":"mcp_.*","match":"regex"})),
1964 &policy,
1965 &mut catalog,
1966 &mut active,
1967 None,
1968 )
1969 .await
1970 .unwrap();
1971 for name in ["engram", "unrelated", "disabled", "stalled"] {
1972 assert!(!tmp.path().join(format!("started-{name}")).exists());
1973 }
1974 assert!(!catalog.iter().any(|tool| tool.name.starts_with("mcp_")));
1975 assert_eq!(
1976 model.call_count(),
1977 0,
1978 "MCP discovery must not call a provider"
1979 );
1980 fixture_manager.shutdown().await;
1981 }
1982
1983 #[tokio::test]
1984 async fn mcp_tool_search_failed_connection_is_bounded_without_guessed_tools() {
1985 let (_fixture_manager_guard, fixture_manager, mut engine, policy, _tmp, model) =
1986 mcp_search_fixture(None).await;
1987 let mut catalog = policy.catalog.clone();
1988 let mut active = policy.active_names.clone();
1989 tokio::time::timeout(
1990 Duration::from_secs(6),
1991 engine.discover_mcp_for_tool_search(
1992 ("tool_search", &json!({"query":"failed"})),
1993 &policy,
1994 &mut catalog,
1995 &mut active,
1996 None,
1997 ),
1998 )
1999 .await
2000 .expect("existing five-second bound")
2001 .unwrap();
2002 assert!(engine.mcp_connection_errors.contains_key("failed"));
2003 assert!(
2004 !catalog
2005 .iter()
2006 .any(|tool| tool.name.starts_with("mcp_failed_"))
2007 );
2008 assert_eq!(
2009 model.call_count(),
2010 0,
2011 "MCP discovery must not call a provider"
2012 );
2013 fixture_manager.shutdown().await;
2014 }
2015
2016 #[tokio::test]
2017 async fn mcp_tool_search_cancel_aborts_handshake_and_clears_connecting() {
2018 let (_fixture_manager_guard, fixture_manager, mut engine, policy, tmp, model) =
2019 mcp_search_fixture(None).await;
2020 let pool = engine.mcp_pool.clone().unwrap();
2021 let cancel = engine.cancel_token.clone();
2022 let mut catalog = policy.catalog.clone();
2023 let mut active = policy.active_names.clone();
2024 let input = json!({"query":"stalled"});
2025 let discovery = engine.discover_mcp_for_tool_search(
2026 ("tool_search", &input),
2027 &policy,
2028 &mut catalog,
2029 &mut active,
2030 None,
2031 );
2032 tokio::pin!(discovery);
2033 let result = tokio::time::timeout(Duration::from_secs(6), async {
2034 loop {
2035 tokio::select! {
2036 result = &mut discovery => break result,
2037 () = tokio::time::sleep(Duration::from_millis(10)) => {
2038 if tmp.path().join("started-stalled").exists() { cancel.cancel(); }
2039 }
2040 }
2041 }
2042 })
2043 .await
2044 .expect("cancel remains bounded");
2045 assert!(matches!(result, Err(ToolError::PermissionDenied { .. })));
2046 assert!(pool.lock().await.connecting_servers().is_empty());
2047 assert!(pool.lock().await.to_api_tools().is_empty());
2048 assert_eq!(
2049 model.call_count(),
2050 0,
2051 "MCP discovery must not call a provider"
2052 );
2053 fixture_manager.shutdown().await;
2054 }
2055
2056 #[tokio::test]
2057 async fn turn_catalog_drops_an_mcp_tool_switched_off_after_the_server_connected() {
2058 let Some(node) = test_node_binary() else {
2059 return;
2060 };
2061 let tmp = tempdir().expect("tempdir");
2062 let fixture_manager = Arc::new(crate::extension_host::ExtensionHostManager::new(
2063 crate::extension_host::ExtensionHostOptions {
2064 root: Some(tmp.path().join("host-home")),
2065 ..Default::default()
2066 },
2067 ));
2068 let _fixture_manager_guard =
2069 crate::extension_host::TestManagerGuard::install(Arc::clone(&fixture_manager));
2070 let server = tmp.path().join("server.mjs");
2071 fs::write(&server, r#"import readline from 'node:readline';
2072 const lines = readline.createInterface({ input: process.stdin });
2073 lines.on('line', (line) => {
2074 const request = JSON.parse(line);
2075 if (request.id === undefined) return;
2076 const result = request.method === 'initialize'
2077 ? { protocolVersion: '2024-11-05', capabilities: { tools: {} }, serverInfo: { name: 'issues', version: '1' } }
2078 : { tools: ['list_issues', 'close_issue'].map(name => ({ name, inputSchema: { type: 'object' } })) };
2079 process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, result }) + '\n');
2080 });"#).expect("fixture");
2081 let config_path = tmp.path().join("mcp.json");
2082 let write_config = |disabled: &[&str], age: u64| {
2083 fs::write(
2084 &config_path,
2085 serde_json::to_vec(&json!({
2086 "timeouts": { "connect_timeout": 120 },
2087 "servers": {
2088 "issues": { "command": node, "args": [server], "required": true, "disabled_tools": disabled }
2089 }
2090 }))
2091 .unwrap(),
2092 )
2093 .unwrap();
2094 fs::File::options()
2095 .write(true)
2096 .open(&config_path)
2097 .and_then(|file| {
2098 file.set_modified(std::time::SystemTime::now() - Duration::from_secs(age))
2099 })
2100 .unwrap();
2101 };
2102 write_config(&[], 60);
2103 let (mut engine, _handle) = Engine::new(
2104 EngineConfig {
2105 workspace: tmp.path().to_path_buf(),
2106 mcp_config_path: config_path.clone(),
2107 ..Default::default()
2108 },
2109 &Config::default(),
2110 );
2111 engine
2112 .start_mcp_session_boot(McpConnectRefresh::IfChanged)
2113 .await
2114 .expect("session boot starts");
2115 let names = |tools: Vec<Tool>| {
2116 tools
2117 .into_iter()
2118 .map(|tool| tool.name)
2119 .collect::<HashSet<_>>()
2120 };
2121 let deadline = tokio::time::Instant::now() + Duration::from_secs(60);
2122 while !names(engine.mcp_tools().await).contains("mcp_issues_close_issue") {
2123 assert!(
2124 tokio::time::Instant::now() < deadline,
2125 "fixture server never connected"
2126 );
2127 tokio::time::sleep(Duration::from_millis(20)).await;
2128 }
2129
2130 write_config(&["close_issue"], 0);
2131 assert!(!names(engine.mcp_tools().await).contains("mcp_issues_close_issue"));
2132 let deadline = tokio::time::Instant::now() + Duration::from_secs(60);
2133 loop {
2134 let offered = names(engine.mcp_tools().await);
2135 assert!(!offered.contains("mcp_issues_close_issue"), "{offered:?}");
2136 if offered.contains("mcp_issues_list_issues") {
2137 break;
2138 }
2139 assert!(
2140 tokio::time::Instant::now() < deadline,
2141 "server never reconnected"
2142 );
2143 tokio::time::sleep(Duration::from_millis(20)).await;
2144 }
2145 fixture_manager.shutdown().await;
2146 }
2147
2147 lines RUST