返回 CodeWhale
tests.rs
根目录 / crates / engine / src / core / engine / preview / tests.rs
1 use super::*;
2 use crate::core::ops::TurnSpec;
3
4 fn tool(name: &str, deferred: bool) -> Tool {
5 Tool {
6 tool_type: None,
7 name: name.to_string(),
8 description: format!("{name} description"),
9 input_schema: json!({"type": "object", "properties": {}}),
10 allowed_callers: None,
11 defer_loading: Some(deferred),
12 input_examples: None,
13 strict: None,
14 cache_control: None,
15 }
16 }
17
18 #[test]
19 fn active_catalog_hash_tracks_membership_order_and_schema() {
20 let base = vec![tool("Bash", false), tool("File", false)];
21 let baseline = active_tool_catalog_sha256(&base);
22
23 assert_eq!(baseline, active_tool_catalog_sha256(&base.clone()));
24
25 let mut reordered = base.clone();
26 reordered.swap(0, 1);
27 assert_ne!(baseline, active_tool_catalog_sha256(&reordered));
28
29 let mut fewer = base.clone();
30 fewer.pop();
31 assert_ne!(baseline, active_tool_catalog_sha256(&fewer));
32
33 let mut retyped = base.clone();
34 retyped[0].input_schema = json!({"type": "object", "required": ["cmd"]});
35 assert_ne!(baseline, active_tool_catalog_sha256(&retyped));
36 }
37
38 #[test]
39 fn preview_and_production_share_one_input_estimate_and_send_decision() {
40 let messages = vec![Message {
41 role: Role::User,
42 content: vec![ContentBlock::Text {
43 text: "near the context ceiling".to_string(),
44 cache_control: None,
45 }],
46 }];
47 let system = SystemPrompt::Text("stable system".to_string());
48
49 // Production sends stored history and nothing else, and preview describes
50 // that same list, so a single estimate drives the manifest number and the
51 // overflow/no-exact-outbound decision. There is no second synthetic list
52 // to charge a separate framing overhead for.
53 let estimate = crate::compaction::estimate_input_tokens_conservative(&messages, Some(&system));
54
55 let ceiling = estimate - 1;
56 assert_eq!(
57 crate::request_manifest::production_input_headroom(Some(ceiling), estimate),
58 Some(-1)
59 );
60 assert!(crate::request_manifest::production_input_budget_exceeded(
61 Some(ceiling),
62 estimate
63 ));
64 assert!(!crate::request_manifest::production_input_budget_exceeded(
65 Some(estimate),
66 estimate
67 ));
68 }
69
70 #[test]
71 fn standard_and_full_are_reported_collapsed_from_the_real_shaper() {
72 let catalog = vec![tool("Bash", false), tool("agent", false), tool("Web", true)];
73 let always_load = std::collections::HashSet::new();
74 assert!(
75 standard_and_full_collapse(&catalog, &always_load),
76 "Standard and Full apply no narrowing today, so they must report collapsed"
77 );
78 }
79
80 #[tokio::test]
81 async fn pending_shell_completion_makes_the_body_unavailable_without_draining_it() {
82 let config = deepseek_config();
83 let identity = deepseek_identity();
84 let (mut engine, _handle, _tmp) = preview_engine(&config);
85 engine.config.features.disable(Feature::Mcp);
86 let owner_session_id = engine.session.id.clone();
87
88 {
89 let mut manager = engine.shell_manager.lock().expect("shell manager");
90 let command = if cfg!(windows) {
91 "Start-Sleep -Seconds 30"
92 } else {
93 "sleep 30"
94 };
95 manager
96 .execute_with_options_env_for_session(
97 command,
98 None,
99 30_000,
100 true,
101 None,
102 false,
103 None,
104 std::collections::HashMap::new(),
105 &owner_session_id,
106 )
107 .expect("background shell starts");
108 assert!(manager.may_have_undelivered_completion_for_session(&owner_session_id));
109 }
110
111 let planned = plan(&config, &identity, false, "inspect the next request").await;
112 let manifest = engine
113 .build_request_manifest(inputs(false, Some(planned), "inspect the next request"))
114 .await;
115 let unavailable = match &manifest.body {
116 Availability::Unavailable(unavailable) => unavailable,
117 Availability::Exact(_) => panic!("pending shell completion must fail closed"),
118 };
119 assert_eq!(
120 unavailable.reason,
121 UnavailableReason::RuntimeTransformsBeforeSend
122 );
123 assert!(
124 unavailable
125 .detail
126 .as_deref()
127 .is_some_and(|detail| detail.contains("background shell completion")),
128 "{unavailable:?}"
129 );
130
131 let mut manager = engine.shell_manager.lock().expect("shell manager");
132 assert!(
133 manager.may_have_undelivered_completion_for_session(&owner_session_id),
134 "preview must not drain or report the completion"
135 );
136 let _ = manager.kill_running();
137 let _ = manager.drain_finished_jobs_with_evidence();
138 }
139
140 #[tokio::test]
141 async fn running_direct_child_fails_closed_without_consuming_or_mutating_state() {
142 let config = deepseek_config();
143 let identity = deepseek_identity();
144 let (mut engine, _handle, tmp) = preview_engine(&config);
145 engine.config.features.disable(Feature::Mcp);
146 let active_session_id = engine.session.id.clone();
147 let mut before = {
148 let mut manager = engine.subagent_manager.write().await;
149 let agent_id = manager.insert_test_running_direct_child("preview_pending", tmp.path());
150 manager.assign_test_session_owner(&agent_id, &active_session_id);
151 serde_json::to_value(manager.list()).expect("manager snapshot")
152 };
153 if let Some(rows) = before.as_array_mut() {
154 for row in rows {
155 row.as_object_mut()
156 .expect("agent object")
157 .remove("duration_ms");
158 }
159 }
160 let delivered_before = engine.delivered_subagent_completion_ids.clone();
161
162 let planned = plan(&config, &identity, false, "inspect while child runs").await;
163 let manifest = engine
164 .build_request_manifest(inputs(false, Some(planned), "inspect while child runs"))
165 .await;
166 let unavailable = match &manifest.body {
167 Availability::Unavailable(unavailable) => unavailable,
168 Availability::Exact(_) => panic!("running child must fail closed"),
169 };
170 assert_eq!(
171 unavailable.reason,
172 UnavailableReason::RuntimeTransformsBeforeSend
173 );
174 assert!(
175 unavailable
176 .detail
177 .as_deref()
178 .is_some_and(|detail| detail.contains("running or undelivered sub-agent"))
179 );
180
181 let mut after = {
182 let manager = engine.subagent_manager.read().await;
183 assert!(manager.may_transform_next_parent_request_for_session(
184 &active_session_id,
185 &engine.delivered_subagent_completion_ids,
186 ));
187 serde_json::to_value(manager.list()).expect("manager snapshot")
188 };
189 if let Some(rows) = after.as_array_mut() {
190 for row in rows {
191 row.as_object_mut()
192 .expect("agent object")
193 .remove("duration_ms");
194 }
195 }
196 assert_eq!(before, after, "preview must not mutate child state");
197 assert_eq!(
198 delivered_before, engine.delivered_subagent_completion_ids,
199 "preview must not claim child delivery"
200 );
201 }
202
203 #[tokio::test]
204 async fn terminal_undelivered_child_fails_closed_without_claiming_delivery() {
205 let config = deepseek_config();
206 let identity = deepseek_identity();
207 let (mut engine, _handle, tmp) = preview_engine(&config);
208 engine.config.features.disable(Feature::Mcp);
209 let active_session_id = engine.session.id.clone();
210 let agent_id = {
211 let mut manager = engine.subagent_manager.write().await;
212 let agent_id = manager.insert_test_terminal_direct_child("preview_terminal", tmp.path());
213 manager.assign_test_session_owner(&agent_id, &active_session_id);
214 agent_id
215 };
216
217 let planned = plan(&config, &identity, false, "inspect settled child").await;
218 let manifest = engine
219 .build_request_manifest(inputs(false, Some(planned), "inspect settled child"))
220 .await;
221 assert!(matches!(manifest.body, Availability::Unavailable(_)));
222 assert!(
223 !engine.delivered_subagent_completion_ids.contains(&agent_id),
224 "preview must not claim terminal delivery"
225 );
226 let manager = engine.subagent_manager.read().await;
227 assert!(manager.may_transform_next_parent_request_for_session(
228 &active_session_id,
229 &engine.delivered_subagent_completion_ids,
230 ));
231 assert!(matches!(
232 manager
233 .get_result(&agent_id)
234 .expect("terminal child")
235 .status,
236 crate::tools::subagent::SubAgentStatus::Completed
237 ));
238 }
239
240 #[test]
241 fn turn_metadata_uses_planned_cross_route_limits_not_installed_limits() {
242 let config = deepseek_config();
243 let (mut engine, _handle, _tmp) = preview_engine(&config);
244 // Pressure advice is only surfaced when the user opts out of automatic
245 // maintenance. The route-budget assertion still applies in that mode.
246 engine.config.compaction.enabled = false;
247 engine.api_provider = ProviderKind::Deepseek;
248 let installed_limits = codewhale_config::route::RouteLimits {
249 context_tokens: Some(4_096),
250 input_tokens: None,
251 output_tokens: Some(512),
252 output_declared: false,
253 };
254 engine.active_route_limits = Some(installed_limits);
255 // Large enough to be critical for the installed 4K route, but safely
256 // below the warning threshold for the planned 123K route.
257 engine.session.messages.push(Message {
258 role: Role::User,
259 content: vec![ContentBlock::Text {
260 text: "x".repeat(20_000),
261 cache_control: None,
262 }],
263 });
264 let prompt_context = NextTurnPromptContext::for_planned_turn(
265 ProviderKind::Openrouter,
266 "qwen/qwen3.6-flash".to_string(),
267 Some(codewhale_config::route::RouteLimits {
268 context_tokens: Some(123_456),
269 input_tokens: None,
270 output_tokens: Some(4_096),
271 output_declared: false,
272 }),
273 AppMode::Agent,
274 None,
275 GoalStatus::Active,
276 None,
277 false,
278 None,
279 );
280 let system_prompt = engine.compose_stable_system_prompt(&prompt_context);
281 let planned_pressure = engine
282 .context_pressure_line(
283 "cross-route budget",
284 &prompt_context,
285 system_prompt.as_ref(),
286 &engine.session.messages,
287 None,
288 )
289 .unwrap();
290 assert!(planned_pressure.contains("/ 123456 context tokens"));
291 assert!(!planned_pressure.contains("Context pressure:"));
292 let installed_context = NextTurnPromptContext::for_planned_turn(
293 ProviderKind::Deepseek,
294 "deepseek-v4-flash".to_string(),
295 Some(installed_limits),
296 AppMode::Agent,
297 None,
298 GoalStatus::Active,
299 None,
300 false,
301 None,
302 );
303 let pressure = engine
304 .context_pressure_line(
305 "cross-route budget",
306 &installed_context,
307 None,
308 &engine.session.messages,
309 None,
310 )
311 .unwrap();
312 assert!(pressure.contains("Context pressure: critical"));
313 assert!(pressure.contains("/ 4096 context tokens"));
314 assert!(pressure.contains("Making room automatically is off"));
315 let message = engine.user_text_message_from_snapshot(
316 "cross-route budget".to_string(),
317 &prompt_context.model,
318 true,
319 None,
320 false,
321 UserInputProvenance::ExternalUser,
322 TurnMetadataSnapshot {
323 planned_compaction: None,
324 prompt_context: &prompt_context,
325 system_prompt: system_prompt.as_ref(),
326 approval_mode: ApprovalMode::Suggest,
327 working_set: &engine.session.working_set,
328 messages: &engine.session.messages,
329 policy_narrowing: None,
330 },
331 );
332 let metadata = message
333 .content
334 .iter()
335 .filter_map(|block| match block {
336 ContentBlock::Text { text, .. } => Some(text.as_str()),
337 _ => None,
338 })
339 .next_back()
340 .expect("turn metadata text");
341 assert!(
342 !metadata.contains("Context pressure:"),
343 "planned route metadata must remain below warning: {metadata}"
344 );
345 assert!(metadata.contains("/ 123456 context tokens"), "{metadata}");
346 assert!(!metadata.contains("/ 4096 context tokens"), "{metadata}");
347 }
348
349 /// #perf-r5: the pressure-line helper must estimate the history IN PLACE and
350 /// add the composer text arithmetically. Guards two things at once:
351 ///
352 /// 1. Equivalence — the arithmetic form must equal the naive
353 /// "clone + push + estimate" reference for non-trivial inputs (Unicode
354 /// multi-byte content included, since Text blocks count *chars* for the
355 /// conservative estimator but the delta path counts... the same rule as
356 /// `estimate_tokens_for_message`: bytes/4).
357 /// 2. The contract that empty/no-op composer text costs nothing extra.
358 #[test]
359 fn context_pressure_delta_matches_clone_and_push_reference() {
360 let config = deepseek_config();
361 let (mut engine, _handle, _tmp) = preview_engine(&config);
362 engine.api_provider = ProviderKind::Deepseek;
363 let installed_limits = codewhale_config::route::RouteLimits {
364 context_tokens: Some(64_000),
365 input_tokens: None,
366 output_tokens: Some(512),
367 output_declared: false,
368 };
369 engine.active_route_limits = Some(installed_limits);
370 // Multi-byte content on purpose: chars().count() != len() here, so an
371 // arity mistake between the byte rule (estimator) would surface.
372 engine.session.messages.push(Message {
373 role: Role::User,
374 content: vec![ContentBlock::Text {
375 text: "héllo wörld — ünïcode ✓ ".repeat(500),
376 cache_control: None,
377 }],
378 });
379 engine.session.messages.push(Message {
380 role: Role::Assistant,
381 content: vec![ContentBlock::Thinking {
382 thinking: "step".repeat(100),
383 signature: None,
384 state: None,
385 redacted_data: None,
386 }],
387 });
388 // Replayed-reasoning case (#perf-r5 fresh-eyes fix): an assistant message
389 // carrying BOTH thinking and a tool call keeps its reasoning content in
390 // every subsequent request — the estimator counts those bytes, and this
391 // was the exact arm the delta helper originally missed. Both parity
392 // variants of the thinking byte-count are exercised below.
393 engine.session.messages.push(Message {
394 role: Role::Assistant,
395 content: vec![
396 ContentBlock::Thinking {
397 thinking: "replayed".repeat(300), // 8 bytes per unit -> even count
398 signature: None,
399 state: None,
400 redacted_data: None,
401 },
402 ContentBlock::ToolUse {
403 execution_id: None,
404 id: "call_1".to_string(),
405 name: "bash".to_string(),
406 input: json!({"command": "echo hello"}),
407 caller: None,
408 thought_signature: None,
409 },
410 ],
411 });
412 engine.session.messages.push(Message {
413 role: Role::Assistant,
414 content: vec![
415 ContentBlock::Thinking {
416 thinking: "odd replay".to_string(), // 11 bytes / 4 = 2 (even)... use odd total
417 signature: None,
418 state: None,
419 redacted_data: None,
420 },
421 ContentBlock::ToolUse {
422 execution_id: None,
423 id: "call_2".to_string(),
424 name: "read".to_string(),
425 input: json!({"path": "x"}), // 13-byte JSON -> 3
426 caller: None,
427 thought_signature: None,
428 },
429 ],
430 });
431 let _prompt_context = NextTurnPromptContext::for_planned_turn(
432 ProviderKind::Deepseek,
433 "deepseek-v4-flash".to_string(),
434 Some(installed_limits),
435 AppMode::Agent,
436 None,
437 GoalStatus::Active,
438 None,
439 false,
440 None,
441 );
442 let _ = &_prompt_context;
443
444 // Naive reference implementation: clone the transcript, push a
445 // hypothetical user message, run the full conservative estimator.
446 let reference = |engine: &Engine, text: &str| -> usize {
447 let mut messages: Vec<Message> =
448 codewhale_runtime::prompt_zones::AppendLog::clone(&engine.session.messages).into();
449 if !text.trim().is_empty() {
450 messages.push(Message {
451 role: Role::User,
452 content: vec![ContentBlock::Text {
453 text: text.to_string(),
454 cache_control: None,
455 }],
456 });
457 }
458 crate::compaction::estimate_input_tokens_conservative(&messages, None)
459 };
460
461 for text in [
462 "",
463 " ",
464 "short",
465 "a much longer composer draft with punctuation…",
466 "中文のかな한글",
467 ] {
468 let via_pressure_line_input =
469 crate::compaction::estimate_input_tokens_conservative_with_text(
470 &engine.session.messages,
471 None,
472 text,
473 );
474 assert_eq!(
475 via_pressure_line_input,
476 reference(&engine, text),
477 "delta arithmetic diverged from clone+push+estimate for {text:?}"
478 );
479 }
480 }
481
482 /// #perf-r5 guard: billed input above the threshold must report pressure with
483 /// a provably-empty history — proving the short-circuit answers from billing
484 /// alone without consulting message contents.
485 #[test]
486 fn billed_pressure_above_threshold_answers_from_billing_alone() {
487 let config = CompactionConfig {
488 enabled: true,
489 token_threshold: 1_000,
490 ..Default::default()
491 };
492 let pressure = crate::compaction::compaction_pressure_reached_with_billed(
493 &[], // empty history: only billing can prove pressure
494 None,
495 &config,
496 Some(2_000),
497 );
498 assert!(pressure, "billed 2000 >= threshold 1000 must be pressure");
499 }
500
501 /// #perf-r5 guard: under-threshold billing keeps the old max() semantics —
502 /// an estimate above the trigger still fires even when billing is quiet.
503 #[test]
504 fn billed_below_threshold_still_fires_on_estimate() {
505 let config = CompactionConfig {
506 enabled: true,
507 token_threshold: 100,
508 ..Default::default()
509 };
510 let big = Message {
511 role: Role::User,
512 content: vec![ContentBlock::Text {
513 text: "x".repeat(4 * 200),
514 cache_control: None,
515 }],
516 };
517 let pressure = crate::compaction::compaction_pressure_reached_with_billed(
518 std::slice::from_ref(&big),
519 None,
520 &config,
521 Some(10), // below threshold; must not short-circuit to false either
522 );
523 assert!(pressure, "estimate 200 (+1.0 framing) >= 100 must fire");
524 }
525
526 /// #perf-r5 guard: a direct `session.messages` overwrite (the SyncSession
527 /// restore path) must advance `messages_revision` so the token-estimate
528 /// cache invalidates instead of serving the pre-sync value.
529 #[test]
530 fn sync_restore_bumps_messages_revision_for_estimate_cache() {
531 use crate::core::engine::token_estimate_cache::TokenEstimateCache;
532
533 let config = deepseek_config();
534 let (mut engine, _handle, _tmp) = preview_engine(&config);
535 engine.session.add_message(Message {
536 role: Role::User,
537 content: vec![ContentBlock::Text {
538 text: "before restore".to_string(),
539 cache_control: None,
540 }],
541 });
542 let revision_before = engine.session.messages_revision;
543 let mut cache = TokenEstimateCache::new();
544 let stale = cache.lookup_or_compute(
545 revision_before,
546 engine.session.system_prompt.as_ref(),
547 &engine.session.messages,
548 );
549
550 // Simulate the restore's direct field assignment.
551 engine.session.messages = Vec::new().into();
552 engine.session.bump_messages_revision();
553
554 assert_ne!(
555 engine.session.messages_revision, revision_before,
556 "restore must bump the revision the estimate cache keys on"
557 );
558 let fresh = cache.lookup_or_compute(
559 engine.session.messages_revision,
560 engine.session.system_prompt.as_ref(),
561 &engine.session.messages,
562 );
563 assert_ne!(
564 fresh, stale,
565 "cache must recompute after a restore-driven revision bump"
566 );
567 }
568
569 #[tokio::test]
570 async fn compaction_preview_uses_the_planned_routes_system_prompt() {
571 let config = deepseek_config();
572 let (mut engine, _handle, _tmp) = preview_engine(&config);
573 engine.config.features.disable(Feature::Mcp);
574
575 let messages: Vec<Message> = (0..30)
576 .map(|index| Message {
577 role: if index % 2 == 0 {
578 Role::User
579 } else {
580 Role::Assistant
581 },
582 content: vec![ContentBlock::Text {
583 text: "x".repeat(10_000),
584 cache_control: None,
585 }],
586 })
587 .collect();
588 let installed_prompt = SystemPrompt::Text("installed route".to_string());
589 let planned_prompt = SystemPrompt::Text("planned-route-system ".repeat(1_500));
590 engine.session.system_prompt = Some(installed_prompt.clone());
591
592 let installed_pressure =
593 crate::compaction::estimate_input_tokens_for_pressure(&messages, Some(&installed_prompt));
594 let planned_pressure =
595 crate::compaction::estimate_input_tokens_for_pressure(&messages, Some(&planned_prompt));
596 assert!(planned_pressure > installed_pressure);
597 let compaction = crate::compaction::CompactionConfig {
598 enabled: true,
599 token_threshold: installed_pressure + (planned_pressure - installed_pressure) / 2,
600 ..Default::default()
601 };
602
603 let planned_reasons = engine
604 .preview_runtime_transforms(&messages, Some(&planned_prompt), &compaction)
605 .await;
606 assert!(
607 planned_reasons.contains(&"making room would summarize the conversation first"),
608 "the planned route prompt crosses the compaction threshold: {planned_reasons:?}"
609 );
610
611 let installed_reasons = engine
612 .preview_runtime_transforms(&messages, Some(&installed_prompt), &compaction)
613 .await;
614 assert!(
615 !installed_reasons.contains(&"making room would summarize the conversation first"),
616 "the installed route prompt is the below-threshold control: {installed_reasons:?}"
617 );
618 }
619
620 #[tokio::test]
621 async fn planned_route_builds_subagent_catalog_without_installed_client() {
622 let config = deepseek_config();
623 let identity = deepseek_identity();
624 let (mut engine, _handle, _tmp) = preview_engine(&config);
625 engine.config.features.disable(Feature::Mcp);
626 let _ = engine.config.features.enable(Feature::Subagents);
627 engine.config.subagents_enabled = true;
628 engine.codewhale_client = None;
629 let planned = plan(&config, &identity, false, "planned child route").await;
630 let route = planned.route.validate().expect("planned route validates");
631 let planned_model = route.model.clone();
632 let policy = TurnAuthority::from_effective_fields(
633 AppMode::Agent,
634 false,
635 false,
636 false,
637 ApprovalMode::Suggest,
638 );
639 let build = engine
640 .build_turn_tool_registry_and_catalog(
641 &policy,
642 &[],
643 None,
644 SubAgentWiring::Inert,
645 McpAccess::PassiveSnapshot,
646 &[],
647 TurnRouteContext {
648 provider: route.identity.provider,
649 model: route.model.clone(),
650 capabilities: route.candidate.capabilities(),
651 limits: crate::route_budget::known_route_limits(route.candidate.limits()),
652 client: Some(route.client),
653 api_config: route.config,
654 locale_tag: engine.config.locale_tag.clone(),
655 role_models: engine.subagent_role_models(),
656 auto_model: false,
657 reasoning_effort: planned.effective_reasoning_effort,
658 reasoning_effort_auto: planned.auto_controls_reasoning,
659 },
660 "",
661 )
662 .await;
663 assert!(
664 build
665 .surface
666 .catalog
667 .iter()
668 .any(|tool| tool.name == "agent"),
669 "the planned route client must make sub-agent tools available"
670 );
671 assert_eq!(
672 build.subagent_runtime_model.as_deref(),
673 Some(planned_model.as_str()),
674 "the child runtime must carry the planned route model"
675 );
676 }
677
678 /// Auto routing with no hypothetical prompt: every route-derived fact is
679 /// structurally absent, and the flag is never cleared just because the
680 /// session happens to have an installed route.
681 #[tokio::test]
682 async fn auto_route_without_a_prompt_omits_every_final_fact() {
683 let tmp = tempfile::tempdir().expect("tempdir");
684 let (mut engine, _handle) = Engine::new(
685 EngineConfig {
686 workspace: tmp.path().to_path_buf(),
687 ..Default::default()
688 },
689 &codewhale_runtime::config::Config::default(),
690 );
691
692 let manifest = engine
693 .build_request_manifest(PreviewRequestInputs {
694 mode: AppMode::Agent,
695 allow_shell: false,
696 trust_mode: false,
697 auto_approve: false,
698 approval_mode: ApprovalMode::Suggest,
699 allowed_tools: None,
700 dynamic_tools: Vec::new(),
701 provenance: UserInputProvenance::ExternalUser,
702 requested_model: "auto".to_string(),
703 requested_reasoning: "auto".to_string(),
704 auto_model: true,
705 hypothetical_prompt_supplied: false,
706 next_turn: None,
707 unresolved: PreviewUnresolved::AutoRouteNeedsPrompt,
708 })
709 .await;
710
711 assert!(manifest.route.exact().is_none());
712 assert!(manifest.tools.exact().is_none());
713 assert!(manifest.body.exact().is_none());
714 assert_eq!(manifest.session.requested_model.as_str(), "auto");
715 assert!(manifest.session.auto_model_routing);
716 assert!(!manifest.session.hypothetical_prompt_supplied);
717
718 let json = manifest.to_json();
719 for forbidden in [
720 "provider_id",
721 "wire_model",
722 "endpoint_fingerprint",
723 "body_sha256",
724 "tool_surface_budget",
725 "billing",
726 ] {
727 assert!(!json.contains(forbidden), "{forbidden} leaked:\n{json}");
728 }
729 }
730
731 fn deepseek_config() -> codewhale_runtime::config::Config {
732 let providers = codewhale_runtime::config::ProvidersConfig {
733 deepseek: codewhale_runtime::config::ProviderConfig {
734 api_key: Some("sk-test-deepseek".to_string()),
735 model: Some("deepseek-chat".to_string()),
736 ..codewhale_runtime::config::ProviderConfig::default()
737 },
738 ..codewhale_runtime::config::ProvidersConfig::default()
739 };
740 {
741 let __cw_config_init_0_0 = Some("deepseek".to_string());
742 let __cw_config_init_0_1 = Some(providers);
743 let mut __cw_config_init_0_value: codewhale_runtime::config::Config =
744 codewhale_runtime::config::Config::default();
745 __cw_config_init_0_value.provider = __cw_config_init_0_0;
746 __cw_config_init_0_value.providers = __cw_config_init_0_1;
747 __cw_config_init_0_value
748 }
749 }
750
751 fn deepseek_identity() -> codewhale_runtime::config::ProviderIdentity {
752 codewhale_runtime::config::Config::default()
753 .builtin_provider_identity(ProviderKind::Deepseek)
754 .unwrap()
755 }
756
757 /// Run the *production* route planner, provider-free: with `auto_model`
758 /// the classifier short-circuits to the inventory heuristic under `cfg!(any(test, feature = "test-support"))`.
759 async fn plan(
760 config: &codewhale_runtime::config::Config,
761 identity: &codewhale_runtime::config::ProviderIdentity,
762 auto_model: bool,
763 prompt: &str,
764 ) -> crate::turn_route_plan::PlannedTurnRoute {
765 plan_for(
766 config,
767 identity,
768 ProviderKind::Deepseek,
769 "deepseek-chat",
770 auto_model,
771 prompt,
772 )
773 .await
774 }
775
776 async fn plan_for(
777 config: &codewhale_runtime::config::Config,
778 identity: &codewhale_runtime::config::ProviderIdentity,
779 provider: ProviderKind,
780 model: &str,
781 auto_model: bool,
782 prompt: &str,
783 ) -> crate::turn_route_plan::PlannedTurnRoute {
784 plan_with_reasoning(
785 config,
786 identity,
787 provider,
788 model,
789 auto_model,
790 if auto_model {
791 crate::reasoning_preference::ReasoningEffort::Auto
792 } else {
793 crate::reasoning_preference::ReasoningEffort::High
794 },
795 prompt,
796 )
797 .await
798 }
799
800 /// `plan_for` with the requested reasoning tier under test control. The
801 /// exact-route matrix needs `off` to observe a route that normalizes it
802 /// (direct Moonshot K3 sends `low`).
803 async fn plan_with_reasoning(
804 config: &codewhale_runtime::config::Config,
805 identity: &codewhale_runtime::config::ProviderIdentity,
806 provider: ProviderKind,
807 model: &str,
808 auto_model: bool,
809 reasoning_effort: crate::reasoning_preference::ReasoningEffort,
810 prompt: &str,
811 ) -> crate::turn_route_plan::PlannedTurnRoute {
812 crate::turn_route_plan::plan_turn_route(crate::turn_route_plan::TurnRoutePlanRequest {
813 accounting_origin: None,
814 route_config: config,
815 app_route_identity: identity,
816 api_provider: provider,
817 app_model: model,
818 auto_model,
819 reasoning_effort,
820 mode: AppMode::Agent,
821 content: prompt,
822 auto_router_context: "",
823 should_auto_resolve: auto_model,
824 allow_auto_router_response_cache: false,
825 preflight_required: false,
826 auto_compact_user_configured: false,
827 auto_compact: true,
828 auto_compact_threshold_percent: 80.0,
829 })
830 .await
831 .expect("the shared planner resolves a configured route")
832 }
833
834 fn preview_engine(
835 config: &codewhale_runtime::config::Config,
836 ) -> (Engine, EngineHandle, tempfile::TempDir) {
837 let tmp = tempfile::tempdir().expect("tempdir");
838 let (engine, handle) = Engine::new(
839 EngineConfig {
840 workspace: tmp.path().to_path_buf(),
841 ..Default::default()
842 },
843 config,
844 );
845 (engine, handle, tmp)
846 }
847
848 /// The engine plus its handle: a turn is admitted only while its event
849 /// consumer is alive, as in every production embedding, so callers keep the
850 /// handle for the engine's lifetime even though these fixtures read no events.
851 fn wire_preview_engine(
852 config: &codewhale_runtime::config::Config,
853 ) -> (Engine, crate::core::engine::EngineHandle, tempfile::TempDir) {
854 let tmp = tempfile::tempdir().expect("tempdir");
855 let (mut engine, handle) = Engine::new(
856 EngineConfig {
857 workspace: tmp.path().to_path_buf(),
858 max_steps: 1,
859 snapshots_enabled: false,
860 terminal_chrome_enabled: false,
861 ..Default::default()
862 },
863 config,
864 );
865 engine.config.features.disable(Feature::Mcp);
866 engine.config.subagents_enabled = false;
867 (engine, handle, tmp)
868 }
869
870 fn inputs(
871 auto_model: bool,
872 planned: Option<crate::turn_route_plan::PlannedTurnRoute>,
873 prompt: &str,
874 ) -> PreviewRequestInputs {
875 PreviewRequestInputs {
876 mode: AppMode::Agent,
877 allow_shell: false,
878 trust_mode: false,
879 auto_approve: false,
880 approval_mode: ApprovalMode::Suggest,
881 allowed_tools: None,
882 dynamic_tools: Vec::new(),
883 provenance: UserInputProvenance::ExternalUser,
884 requested_model: if auto_model {
885 "auto".to_string()
886 } else {
887 "deepseek-chat".to_string()
888 },
889 requested_reasoning: if auto_model { "auto" } else { "high" }.to_string(),
890 auto_model,
891 hypothetical_prompt_supplied: true,
892 next_turn: planned.map(|planned| {
893 let prompt_context = NextTurnPromptContext::for_planned_turn(
894 planned.route.identity.provider,
895 planned.route.model.clone(),
896 crate::route_budget::known_route_limits(planned.route.candidate.limits()),
897 AppMode::Agent,
898 None,
899 GoalStatus::Active,
900 None,
901 false,
902 None,
903 );
904 Box::new(PreviewNextTurn {
905 content: prompt.to_string(),
906 route: Box::new(planned.route),
907 prompt_context,
908 reasoning_effort: planned.effective_reasoning_effort,
909 reasoning_effort_auto: planned.auto_controls_reasoning,
910 auto_route_source: planned
911 .auto_selection
912 .as_ref()
913 .map(|selection| selection.source.label().to_string()),
914 routing_source: planned.routing_source,
915 compaction: planned.compaction,
916 })
917 }),
918 unresolved: PreviewUnresolved::NoPrompt,
919 }
920 }
921
922 /// Typed controls for the preview/wire parity fixture. Defaults mirror the
923 /// ordinary active DeepSeek turn; individual tests override only the
924 /// production context they are proving.
925 struct PreviewWireFixture {
926 goal_objective: Option<String>,
927 goal_status: GoalStatus,
928 translation_enabled: bool,
929 verbosity: Option<String>,
930 requested_model: Option<String>,
931 requested_reasoning: Option<String>,
932 }
933
934 impl Default for PreviewWireFixture {
935 fn default() -> Self {
936 Self {
937 goal_objective: None,
938 goal_status: GoalStatus::Active,
939 translation_enabled: false,
940 verbosity: None,
941 requested_model: None,
942 requested_reasoning: None,
943 }
944 }
945 }
946
947 async fn assert_preview_matches_first_wire_body(
948 engine: &mut Engine,
949 server: &wiremock::MockServer,
950 planned: crate::turn_route_plan::PlannedTurnRoute,
951 prompt: &str,
952 fixture: PreviewWireFixture,
953 ) -> (RequestManifest, serde_json::Value) {
954 let PreviewWireFixture {
955 goal_objective,
956 goal_status,
957 translation_enabled,
958 verbosity,
959 requested_model,
960 requested_reasoning,
961 } = fixture;
962 let production_route = planned.route.clone();
963 let compaction = planned.compaction.clone();
964 let reasoning_effort = planned.effective_reasoning_effort.clone();
965 let reasoning_effort_auto = planned.auto_controls_reasoning;
966 let mut preview_inputs = inputs(false, Some(planned), prompt);
967 if let Some(requested_model) = requested_model {
968 preview_inputs.requested_model = requested_model;
969 }
970 if let Some(requested_reasoning) = requested_reasoning {
971 preview_inputs.requested_reasoning = requested_reasoning;
972 }
973 let next = preview_inputs.next_turn.as_mut().expect("planned preview");
974 next.prompt_context = NextTurnPromptContext::for_planned_turn(
975 production_route.identity.provider,
976 production_route.model.clone(),
977 crate::route_budget::known_route_limits(production_route.candidate.limits()),
978 AppMode::Agent,
979 goal_objective.clone(),
980 goal_status,
981 None,
982 translation_enabled,
983 verbosity.clone(),
984 );
985 let manifest = engine.build_request_manifest(preview_inputs).await;
986 let preview_hash = manifest
987 .body
988 .exact()
989 .expect("preview body is exact")
990 .body_sha256
991 .clone();
992
993 let _ = engine
994 .handle_send_message(TurnSpec {
995 profile_constitution: None,
996 content: prompt.to_string(),
997 mode: AppMode::Agent,
998 route: Box::new(production_route),
999 compaction: Box::new(compaction),
1000 initial_routed_usage: Box::new(crate::cost_status::RuntimeUsageBatch::default()),
1001 goal_objective,
1002 goal_token_budget: None,
1003 goal_status,
1004 reasoning_effort,
1005 reasoning_effort_auto,
1006 auto_model: false,
1007 allow_shell: false,
1008 trust_mode: false,
1009 auto_approve: false,
1010 approval_mode: ApprovalMode::Suggest,
1011 translation_enabled,
1012 allowed_tools: None,
1013 dynamic_tools: Vec::new(),
1014 hook_executor: None,
1015 verbosity,
1016 provenance: UserInputProvenance::ExternalUser,
1017 input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson,
1018 images: Vec::new(),
1019 max_output_tokens: None,
1020 submission_id: None,
1021 })
1022 .await;
1023
1024 let requests = server
1025 .received_requests()
1026 .await
1027 .expect("wire mock records requests");
1028 assert_eq!(requests.len(), 1, "the fixture must make one provider call");
1029 let first_wire_body: serde_json::Value =
1030 serde_json::from_slice(&requests[0].body).expect("first HTTP body is JSON");
1031 let first_wire_hash = codewhale_runtime::hashing::sha256_hex(
1032 codewhale_runtime::hashing::canonical_json(&first_wire_body).as_bytes(),
1033 );
1034 assert_eq!(
1035 preview_hash, first_wire_hash,
1036 "preview hash must match the body captured at the HTTP boundary"
1037 );
1038 (manifest, first_wire_body)
1039 }
1040
1041 #[tokio::test]
1042 async fn graph_backed_todo_is_not_reinjected_into_the_first_http_body() {
1043 use wiremock::matchers::method;
1044 use wiremock::{Mock, MockServer, ResponseTemplate};
1045
1046 let server = MockServer::start().await;
1047 Mock::given(method("POST"))
1048 .respond_with(
1049 ResponseTemplate::new(200)
1050 .insert_header("content-type", "text/event-stream")
1051 .set_body_string("data: [DONE]\n\n"),
1052 )
1053 .mount(&server)
1054 .await;
1055 let mut config = deepseek_config();
1056 config
1057 .providers
1058 .as_mut()
1059 .expect("providers")
1060 .deepseek
1061 .base_url = Some(server.uri());
1062 let identity = deepseek_identity();
1063 let (mut engine, _handle, _tmp) = wire_preview_engine(&config);
1064 let graph_todos = crate::tools::todo::TodoListSnapshot {
1065 items: vec![crate::tools::todo::TodoItem {
1066 id: 1,
1067 content: "preserve this graph-authoritative Work item".to_string(),
1068 status: crate::tools::todo::TodoStatus::InProgress,
1069 }],
1070 completion_pct: 0,
1071 in_progress_id: Some(1),
1072 };
1073 let work = crate::work_graph::new_shared_work_runtime(
1074 engine.config.todos.clone(),
1075 engine.config.plan_state.clone(),
1076 );
1077 work.restore(
1078 "preview-graph-work",
1079 None,
1080 &graph_todos,
1081 &crate::tools::plan::PlanSnapshot::default(),
1082 )
1083 .expect("restore graph-backed Work state");
1084 *engine.config.todos.lock().await = crate::tools::todo::TodoList::new();
1085 assert!(
1086 engine.config.todos.lock().await.snapshot().is_empty(),
1087 "legacy projection is intentionally stale for this authority test"
1088 );
1089 engine.config.runtime_services.work = Some(work);
1090
1091 let prompt = "inspect the request without restating the To-do list";
1092 let planned = plan(&config, &identity, false, prompt).await;
1093 let (_, first_wire_body) = assert_preview_matches_first_wire_body(
1094 &mut engine,
1095 &server,
1096 planned,
1097 prompt,
1098 PreviewWireFixture::default(),
1099 )
1100 .await;
1101 let body_text = first_wire_body.to_string();
1102 assert!(
1103 !body_text.contains("<codewhale:work_state>")
1104 && !body_text.contains("preserve this graph-authoritative Work item"),
1105 "provider requests must not receive a synthetic per-step To-do tail: {body_text}"
1106 );
1107 }
1108
1109 #[tokio::test]
1110 async fn exhausted_active_goal_remains_previewable() {
1111 let config = deepseek_config();
1112 let identity = deepseek_identity();
1113 let (mut engine, _handle, _tmp) = preview_engine(&config);
1114 engine.config.features.disable(Feature::Mcp);
1115 sync_goal_state_from_host(
1116 &engine.config.goal_state,
1117 Some("finish the release"),
1118 Some(100),
1119 GoalStatus::Active,
1120 );
1121 engine
1122 .config
1123 .goal_state
1124 .lock()
1125 .expect("goal state")
1126 .record_usage(100, 0, std::time::Instant::now());
1127
1128 let prompt = "continue the release";
1129 let planned = plan(&config, &identity, false, prompt).await;
1130 let manifest = engine
1131 .build_request_manifest(inputs(false, Some(planned), prompt))
1132 .await;
1133 assert!(manifest.route.exact().is_some());
1134 assert!(manifest.tools.exact().is_some());
1135 assert!(manifest.body.exact().is_some());
1136 }
1137
1138 #[tokio::test]
1139 async fn resumed_goal_with_raised_budget_becomes_previewable_again() {
1140 let config = deepseek_config();
1141 let identity = deepseek_identity();
1142 let (mut engine, _handle, _tmp) = preview_engine(&config);
1143 engine.config.features.disable(Feature::Mcp);
1144 sync_goal_state_from_host(
1145 &engine.config.goal_state,
1146 Some("finish the release"),
1147 Some(100),
1148 GoalStatus::Active,
1149 );
1150 {
1151 let mut state = engine.config.goal_state.lock().expect("goal state");
1152 state.record_usage(100, 0, std::time::Instant::now());
1153 state
1154 .mark_paused(GoalPauseReason::BudgetLimit)
1155 .expect("pause goal");
1156 }
1157 sync_goal_state_from_host(
1158 &engine.config.goal_state,
1159 Some("finish the release"),
1160 Some(200),
1161 GoalStatus::Active,
1162 );
1163
1164 let prompt = "continue under the raised budget";
1165 let planned = plan(&config, &identity, false, prompt).await;
1166 let manifest = engine
1167 .build_request_manifest(inputs(false, Some(planned), prompt))
1168 .await;
1169 assert!(manifest.body.exact().is_some());
1170 }
1171
1172 #[tokio::test]
1173 async fn lowering_active_goal_budget_below_used_tokens_keeps_preview_open() {
1174 let config = deepseek_config();
1175 let identity = deepseek_identity();
1176 let (mut engine, _handle, _tmp) = preview_engine(&config);
1177 engine.config.features.disable(Feature::Mcp);
1178 sync_goal_state_from_host(
1179 &engine.config.goal_state,
1180 Some("finish the release"),
1181 Some(200),
1182 GoalStatus::Active,
1183 );
1184 engine
1185 .config
1186 .goal_state
1187 .lock()
1188 .expect("goal state")
1189 .record_usage(100, 0, std::time::Instant::now());
1190 sync_goal_state_from_host(
1191 &engine.config.goal_state,
1192 Some("finish the release"),
1193 Some(50),
1194 GoalStatus::Active,
1195 );
1196
1197 let prompt = "continue after lowering the budget";
1198 let planned = plan(&config, &identity, false, prompt).await;
1199 let manifest = engine
1200 .build_request_manifest(inputs(false, Some(planned), prompt))
1201 .await;
1202 assert!(manifest.route.exact().is_some());
1203 assert!(manifest.tools.exact().is_some());
1204 assert!(manifest.body.exact().is_some());
1205 }
1206
1207 #[tokio::test]
1208 async fn translation_prompt_context_matches_captured_first_production_body() {
1209 use wiremock::matchers::method;
1210 use wiremock::{Mock, MockServer, ResponseTemplate};
1211
1212 let server = MockServer::start().await;
1213 Mock::given(method("POST"))
1214 .respond_with(
1215 ResponseTemplate::new(200)
1216 .insert_header("content-type", "text/event-stream")
1217 .set_body_string("data: [DONE]\n\n"),
1218 )
1219 .mount(&server)
1220 .await;
1221 let mut config = deepseek_config();
1222 config
1223 .providers
1224 .as_mut()
1225 .expect("providers")
1226 .deepseek
1227 .base_url = Some(server.uri());
1228 let identity = deepseek_identity();
1229 let (mut engine, _handle, _tmp) = wire_preview_engine(&config);
1230 engine.config.translation_enabled = false;
1231 let planned = plan(&config, &identity, false, "/translate explain this").await;
1232 let _ = assert_preview_matches_first_wire_body(
1233 &mut engine,
1234 &server,
1235 planned,
1236 "/translate explain this",
1237 PreviewWireFixture {
1238 translation_enabled: true,
1239 verbosity: Some("concise".to_string()),
1240 ..Default::default()
1241 },
1242 )
1243 .await;
1244 }
1245
1246 #[tokio::test]
1247 async fn cold_skills_context_preview_matches_the_first_wire_body() {
1248 use wiremock::matchers::method;
1249 use wiremock::{Mock, MockServer, ResponseTemplate};
1250
1251 let server = MockServer::start().await;
1252 Mock::given(method("POST"))
1253 .respond_with(
1254 ResponseTemplate::new(200)
1255 .insert_header("content-type", "text/event-stream")
1256 .set_body_string("data: [DONE]\n\n"),
1257 )
1258 .mount(&server)
1259 .await;
1260 let mut config = deepseek_config();
1261 config
1262 .providers
1263 .as_mut()
1264 .expect("providers")
1265 .deepseek
1266 .base_url = Some(server.uri());
1267 let (mut engine, _handle, _workspace) = wire_preview_engine(&config);
1268 let skills = tempfile::tempdir().expect("skills root");
1269 let skill = skills.path().join("preview-parity-fixture");
1270 std::fs::create_dir(&skill).expect("skill directory");
1271 std::fs::write(
1272 skill.join("SKILL.md"),
1273 "---\nname: preview-parity-fixture\ndescription: Preview parity fixture.\n---\n\nLoad this exact preview fixture instruction.\n",
1274 )
1275 .expect("skill definition");
1276 engine.config.skills_dir = skills.path().to_path_buf();
1277 Arc::make_mut(&mut engine.config.skills_config).always_load =
1278 Some(vec!["preview-parity-fixture".to_string()]);
1279
1280 let prompt = "inspect the first turn";
1281 let identity = deepseek_identity();
1282 let planned = plan(&config, &identity, false, prompt).await;
1283 let (_, wire) = assert_preview_matches_first_wire_body(
1284 &mut engine,
1285 &server,
1286 planned,
1287 prompt,
1288 PreviewWireFixture::default(),
1289 )
1290 .await;
1291 assert!(
1292 wire.to_string()
1293 .contains("Load this exact preview fixture instruction.")
1294 );
1295 }
1296
1297 #[tokio::test]
1298 async fn paused_detach_goal_context_matches_captured_first_production_body() {
1299 use wiremock::matchers::method;
1300 use wiremock::{Mock, MockServer, ResponseTemplate};
1301
1302 let server = MockServer::start().await;
1303 Mock::given(method("POST"))
1304 .respond_with(
1305 ResponseTemplate::new(200)
1306 .insert_header("content-type", "text/event-stream")
1307 .set_body_string("data: [DONE]\n\n"),
1308 )
1309 .mount(&server)
1310 .await;
1311 let mut config = deepseek_config();
1312 config
1313 .providers
1314 .as_mut()
1315 .expect("providers")
1316 .deepseek
1317 .base_url = Some(server.uri());
1318 let identity = deepseek_identity();
1319 let (mut engine, _handle, _tmp) = wire_preview_engine(&config);
1320 engine.config.goal_objective = Some("stale paused objective".to_string());
1321 sync_goal_state_from_host(
1322 &engine.config.goal_state,
1323 Some("stale paused objective"),
1324 None,
1325 GoalStatus::Active,
1326 );
1327 let prompt = "answer only this new question\n\nCodewhale paused custom slash command context:\nThe user is not resuming that paused command.";
1328 let planned = plan(&config, &identity, false, prompt).await;
1329 let (_, first_wire_body) = assert_preview_matches_first_wire_body(
1330 &mut engine,
1331 &server,
1332 planned,
1333 prompt,
1334 PreviewWireFixture::default(),
1335 )
1336 .await;
1337 assert!(
1338 !first_wire_body
1339 .to_string()
1340 .contains("stale paused objective"),
1341 "detached paused goal leaked onto the first wire body"
1342 );
1343 }
1344
1345 #[tokio::test]
1346 async fn anthropic_preview_matches_the_first_native_messages_wire_body() {
1347 use wiremock::matchers::{method, path};
1348 use wiremock::{Mock, MockServer, ResponseTemplate};
1349
1350 let server = MockServer::start().await;
1351 Mock::given(method("POST"))
1352 .and(path("/v1/messages"))
1353 .respond_with(
1354 ResponseTemplate::new(200)
1355 .insert_header("content-type", "text/event-stream")
1356 .set_body_string("data: {\"type\":\"message_stop\"}\n\n"),
1357 )
1358 .mount(&server)
1359 .await;
1360 let model = "claude-sonnet-4-6";
1361 let config = {
1362 let __cw_config_init_1_0 = Some("anthropic".to_string());
1363 let __cw_config_init_1_1 = Some(codewhale_runtime::config::ProvidersConfig {
1364 anthropic: codewhale_runtime::config::ProviderConfig {
1365 api_key: Some("test-anthropic-key".to_string()),
1366 base_url: Some(server.uri()),
1367 model: Some(model.to_string()),
1368 ..codewhale_runtime::config::ProviderConfig::default()
1369 },
1370 ..codewhale_runtime::config::ProvidersConfig::default()
1371 });
1372 let mut __cw_config_init_1_value: codewhale_runtime::config::Config =
1373 codewhale_runtime::config::Config::default();
1374 __cw_config_init_1_value.provider = __cw_config_init_1_0;
1375 __cw_config_init_1_value.providers = __cw_config_init_1_1;
1376 __cw_config_init_1_value
1377 };
1378 let identity = config
1379 .builtin_provider_identity(ProviderKind::Anthropic)
1380 .unwrap();
1381 let (mut engine, _handle, _tmp) = wire_preview_engine(&config);
1382 let prompt = "inspect the native Messages payload";
1383 let planned = plan_for(
1384 &config,
1385 &identity,
1386 ProviderKind::Anthropic,
1387 model,
1388 false,
1389 prompt,
1390 )
1391 .await;
1392 let (_, first_wire_body) = assert_preview_matches_first_wire_body(
1393 &mut engine,
1394 &server,
1395 planned,
1396 prompt,
1397 PreviewWireFixture::default(),
1398 )
1399 .await;
1400
1401 assert!(first_wire_body.get("system").is_some());
1402 assert!(first_wire_body.get("messages").is_some());
1403 assert!(first_wire_body.get("input").is_none());
1404 }
1405
1406 // ---------------------------------------------------------------------
1407 // #4707 — provider-free exact-route request/receipt matrix.
1408 //
1409 // The four route wire-truths are already pinned at the client boundary
1410 // (`client.rs`, `client/chat.rs`). What was missing is the *join*: that the
1411 // manifest a user reads from `/preview-request` describes the very bytes
1412 // those routes put on the wire. Each case below runs the production
1413 // planner, previews, then sends one turn through a local capture server
1414 // with the semantic endpoint left exact, and asserts the manifest against
1415 // the captured body — hash, sizes, route facts, and the requested→effective
1416 // reasoning triple.
1417 // ---------------------------------------------------------------------
1418
1419 /// One exact provider route in the matrix.
1420 struct MatrixRoute {
1421 /// Test-facing name; also the failure-message prefix.
1422 name: &'static str,
1423 provider: ProviderKind,
1424 provider_key: &'static str,
1425 base_url: &'static str,
1426 model: &'static str,
1427 requested_reasoning: crate::reasoning_preference::ReasoningEffort,
1428 requested_reasoning_label: &'static str,
1429 /// Reasoning-control keys the manifest must report, in receipt order.
1430 expect_control_keys: &'static [&'static str],
1431 /// Effort actually on the wire — `None` when the route publishes a
1432 /// thinking toggle with no granularity. Never a fabricated tier.
1433 expect_wire_effort: Option<&'static str>,
1434 expect_wire_effort_source: Option<&'static str>,
1435 /// The output-cap key this route writes, and the one it must not.
1436 expect_output_cap_key: &'static str,
1437 expect_absent_output_cap_key: &'static str,
1438 }
1439
1440 fn glm_5_2_zai_coding() -> MatrixRoute {
1441 MatrixRoute {
1442 name: "GLM-5.2 @ Z.ai coding",
1443 provider: ProviderKind::Zai,
1444 provider_key: "zai",
1445 base_url: codewhale_config::descriptors::defaults::DEFAULT_ZAI_BASE_URL,
1446 model: codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL,
1447 requested_reasoning: crate::reasoning_preference::ReasoningEffort::High,
1448 requested_reasoning_label: "high",
1449 expect_control_keys: &["reasoning_effort", "thinking"],
1450 expect_wire_effort: Some("high"),
1451 expect_wire_effort_source: Some("reasoning_effort"),
1452 expect_output_cap_key: "max_tokens",
1453 expect_absent_output_cap_key: "max_completion_tokens",
1454 }
1455 }
1456
1457 fn glm_5_turbo_zai() -> MatrixRoute {
1458 MatrixRoute {
1459 name: "GLM-5-Turbo @ Z.ai",
1460 provider: ProviderKind::Zai,
1461 provider_key: "zai",
1462 base_url: codewhale_config::descriptors::defaults::DEFAULT_ZAI_BASE_URL,
1463 model: codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_TURBO_MODEL,
1464 requested_reasoning: crate::reasoning_preference::ReasoningEffort::High,
1465 requested_reasoning_label: "high",
1466 // No invented granularity: the toggle ships, the tier does not.
1467 expect_control_keys: &["thinking"],
1468 expect_wire_effort: None,
1469 expect_wire_effort_source: None,
1470 expect_output_cap_key: "max_tokens",
1471 expect_absent_output_cap_key: "max_completion_tokens",
1472 }
1473 }
1474
1475 fn kimi_k3_moonshot_direct() -> MatrixRoute {
1476 MatrixRoute {
1477 name: "kimi-k3 @ api.moonshot.ai",
1478 provider: ProviderKind::Moonshot,
1479 provider_key: "moonshot",
1480 base_url: codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL,
1481 model: codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL,
1482 // The visible normalization: `off` is not a tier this route has.
1483 requested_reasoning: crate::reasoning_preference::ReasoningEffort::Off,
1484 requested_reasoning_label: "off",
1485 expect_control_keys: &["reasoning_effort"],
1486 expect_wire_effort: Some("low"),
1487 expect_wire_effort_source: Some("reasoning_effort"),
1488 expect_output_cap_key: "max_completion_tokens",
1489 expect_absent_output_cap_key: "max_tokens",
1490 }
1491 }
1492
1493 fn k3_kimi_code() -> MatrixRoute {
1494 MatrixRoute {
1495 name: "k3 @ api.kimi.com/coding/v1",
1496 provider: ProviderKind::Moonshot,
1497 provider_key: "moonshot",
1498 base_url: codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL,
1499 model: codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
1500 requested_reasoning: crate::reasoning_preference::ReasoningEffort::Off,
1501 requested_reasoning_label: "off",
1502 expect_control_keys: &["thinking"],
1503 expect_wire_effort: Some("low"),
1504 expect_wire_effort_source: Some("thinking.effort"),
1505 expect_output_cap_key: "max_tokens",
1506 expect_absent_output_cap_key: "max_completion_tokens",
1507 }
1508 }
1509
1510 fn minimax_m3() -> MatrixRoute {
1511 MatrixRoute {
1512 name: "MiniMax-M3 @ api.minimax.io",
1513 provider: ProviderKind::Minimax,
1514 provider_key: "minimax",
1515 base_url: codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_BASE_URL,
1516 model: codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_MODEL,
1517 requested_reasoning: crate::reasoning_preference::ReasoningEffort::High,
1518 requested_reasoning_label: "high",
1519 expect_control_keys: &["thinking", "reasoning_split"],
1520 expect_wire_effort: None,
1521 expect_wire_effort_source: None,
1522 expect_output_cap_key: "max_completion_tokens",
1523 expect_absent_output_cap_key: "max_tokens",
1524 }
1525 }
1526
1527 fn matrix_routes() -> Vec<MatrixRoute> {
1528 vec![
1529 glm_5_2_zai_coding(),
1530 glm_5_turbo_zai(),
1531 kimi_k3_moonshot_direct(),
1532 k3_kimi_code(),
1533 minimax_m3(),
1534 ]
1535 }
1536
1537 fn matrix_config(route: &MatrixRoute) -> codewhale_runtime::config::Config {
1538 let entry = codewhale_runtime::config::ProviderConfig {
1539 api_key: Some(format!("sk-test-{}-matrix-key", route.provider_key)),
1540 base_url: Some(route.base_url.to_string()),
1541 model: Some(route.model.to_string()),
1542 ..codewhale_runtime::config::ProviderConfig::default()
1543 };
1544 let mut providers = codewhale_runtime::config::ProvidersConfig::default();
1545 match route.provider {
1546 ProviderKind::Zai => providers.zai = entry,
1547 ProviderKind::Moonshot => providers.moonshot = entry,
1548 ProviderKind::Minimax => providers.minimax = entry,
1549 other => panic!("{}: unhandled matrix provider {other:?}", route.name),
1550 }
1551 {
1552 let __cw_config_init_2_0 = Some(route.provider_key.to_string());
1553 let __cw_config_init_2_1 = Some(providers);
1554 let mut __cw_config_init_2_value: codewhale_runtime::config::Config =
1555 codewhale_runtime::config::Config::default();
1556 __cw_config_init_2_value.provider = __cw_config_init_2_0;
1557 __cw_config_init_2_value.providers = __cw_config_init_2_1;
1558 __cw_config_init_2_value
1559 }
1560 }
1561
1562 fn matrix_identity(route: &MatrixRoute) -> codewhale_runtime::config::ProviderIdentity {
1563 matrix_config(route)
1564 .resolve_provider_pin_identity(route.provider_key)
1565 .unwrap()
1566 }
1567
1568 /// Plan the exact route through production, then redirect only the
1569 /// *transport* at the local capture server. The endpoint identity the
1570 /// route shaper reads is untouched, so the captured body is the body
1571 /// `api.z.ai` / `api.moonshot.ai` / `api.kimi.com` / `api.minimax.io`
1572 /// would have received.
1573 async fn matrix_planned_route(
1574 route: &MatrixRoute,
1575 config: &codewhale_runtime::config::Config,
1576 transport_base_url: Option<&str>,
1577 prompt: &str,
1578 ) -> crate::turn_route_plan::PlannedTurnRoute {
1579 let identity = matrix_identity(route);
1580 let mut planned = plan_with_reasoning(
1581 config,
1582 &identity,
1583 route.provider,
1584 route.model,
1585 false,
1586 route.requested_reasoning,
1587 prompt,
1588 )
1589 .await;
1590 if let Some(transport_base_url) = transport_base_url {
1591 let validated = planned
1592 .route
1593 .clone()
1594 .validate()
1595 .expect("the matrix route validates into a concrete client");
1596 let mut client = validated.client.clone();
1597 client.set_test_chat_transport_base_url(transport_base_url.to_string());
1598 planned.route = crate::route_runtime::ValidatedRuntimeRoute {
1599 client,
1600 ..validated
1601 }
1602 .into_resolved();
1603 }
1604 planned
1605 }
1606
1607 /// Non-system messages on a Chat Completions body — the manifest counts
1608 /// the system region separately, so `message_count` must exclude it.
1609 fn non_system_message_count(body: &serde_json::Value) -> usize {
1610 body.get("messages")
1611 .and_then(serde_json::Value::as_array)
1612 .map(|messages| {
1613 messages
1614 .iter()
1615 .filter(|message| {
1616 message.get("role").and_then(serde_json::Value::as_str) != Some("system")
1617 })
1618 .count()
1619 })
1620 .unwrap_or_default()
1621 }
1622
1623 async fn assert_matrix_route(route: &MatrixRoute) {
1624 use wiremock::matchers::method;
1625 use wiremock::{Mock, MockServer, ResponseTemplate};
1626
1627 let name = route.name;
1628 let server = MockServer::start().await;
1629 Mock::given(method("POST"))
1630 .respond_with(
1631 ResponseTemplate::new(200)
1632 .insert_header("content-type", "text/event-stream")
1633 .set_body_string("data: [DONE]\n\n"),
1634 )
1635 .mount(&server)
1636 .await;
1637
1638 let config = matrix_config(route);
1639 let (mut engine, _handle, _tmp) = wire_preview_engine(&config);
1640 let prompt = "inspect the exact next request for this route";
1641 let uri = server.uri();
1642 let planned = matrix_planned_route(route, &config, Some(uri.as_str()), prompt).await;
1643 let planned_provider = planned.route.identity.provider;
1644 let planned_base_url = planned.route.candidate.endpoint().base_url.clone();
1645 let planned_model = planned.route.model.clone();
1646 let expected_wire_model = codewhale_config::route::resolve_model(
1647 planned_provider,
1648 &planned_model,
1649 Some(&planned_base_url),
1650 )
1651 .map_or_else(
1652 |_| planned_model.trim().to_string(),
1653 |resolved| resolved.wire_id,
1654 );
1655 assert_eq!(
1656 planned_base_url.trim_end_matches('/'),
1657 route.base_url.trim_end_matches('/'),
1658 "{name}: the planner must keep the exact configured endpoint"
1659 );
1660
1661 let (manifest, body) = assert_preview_matches_first_wire_body(
1662 &mut engine,
1663 &server,
1664 planned,
1665 prompt,
1666 PreviewWireFixture {
1667 requested_model: Some(route.model.to_string()),
1668 requested_reasoning: Some(route.requested_reasoning_label.to_string()),
1669 ..Default::default()
1670 },
1671 )
1672 .await;
1673
1674 // --- Route facts -------------------------------------------------
1675 let facts = manifest
1676 .route
1677 .exact()
1678 .expect("a configured fixed route is exact");
1679 assert_eq!(facts.provider_id.as_str(), route.provider_key, "{name}");
1680 assert_eq!(facts.wire_model.as_str(), expected_wire_model, "{name}");
1681 assert_eq!(facts.dialect, "chat-completions", "{name}");
1682 assert_eq!(facts.routing_source, "active-fixed-route", "{name}");
1683 assert_eq!(
1684 body.get("model").and_then(serde_json::Value::as_str),
1685 Some(expected_wire_model.as_str()),
1686 "{name}: the manifest's wire model must be the model on the wire: {body}"
1687 );
1688
1689 // --- Body identity, byte accounting, and size estimates ----------
1690 let facts_body = manifest.body.exact().expect("a prompted body is exact");
1691 let canonical = codewhale_runtime::hashing::canonical_json(&body);
1692 assert_eq!(
1693 facts_body.body_sha256,
1694 codewhale_runtime::hashing::sha256_hex(canonical.as_bytes()),
1695 "{name}: manifest body hash must equal the captured wire body hash"
1696 );
1697 assert_eq!(
1698 facts_body.body_canonical_json_bytes,
1699 canonical.len(),
1700 "{name}: canonical body size must describe the captured body"
1701 );
1702 assert_eq!(
1703 facts_body.system_canonical_json_bytes
1704 + facts_body.tool_schema_canonical_json_bytes
1705 + facts_body.message_canonical_json_bytes
1706 + facts_body.framing_canonical_json_bytes,
1707 facts_body.body_canonical_json_bytes,
1708 "{name}: the four accounting classes must sum to the body"
1709 );
1710 assert!(
1711 facts_body.system_canonical_json_bytes > 0,
1712 "{name}: this route sends a system region"
1713 );
1714 assert!(
1715 facts_body.tool_schema_canonical_json_bytes > 0,
1716 "{name}: this route sends tool schemas"
1717 );
1718 assert!(
1719 facts_body.message_canonical_json_bytes > 0,
1720 "{name}: this route sends messages"
1721 );
1722 assert_eq!(
1723 facts_body.message_count,
1724 non_system_message_count(&body),
1725 "{name}: message_count counts the non-system messages on the wire"
1726 );
1727 assert!(
1728 facts_body.tool_result_canonical_json_bytes <= facts_body.message_canonical_json_bytes,
1729 "{name}: tool results are a subset of messages"
1730 );
1731 assert!(
1732 facts_body.attachment_canonical_json_bytes <= facts_body.message_canonical_json_bytes,
1733 "{name}: attachments are a subset of messages"
1734 );
1735 assert_eq!(
1736 facts_body.tool_schema_wire_sha256,
1737 body.get("tools").map(|tools| {
1738 codewhale_runtime::hashing::sha256_hex(
1739 codewhale_runtime::hashing::canonical_json(tools).as_bytes(),
1740 )
1741 }),
1742 "{name}: the tool-schema digest must be over the schemas on the wire"
1743 );
1744 assert!(
1745 facts_body.estimates.system > 0 && facts_body.estimates.tool_schemas > 0,
1746 "{name}: per-class estimates are derived from the same wire regions"
1747 );
1748 assert!(
1749 facts_body.estimates.total_conservative > 0,
1750 "{name}: a whole-body estimate is available"
1751 );
1752
1753 // --- Output cap: exactly the key this route writes ----------------
1754 let wire_cap = body
1755 .get(route.expect_output_cap_key)
1756 .and_then(serde_json::Value::as_u64);
1757 assert!(
1758 wire_cap.is_some(),
1759 "{name}: expected `{}` on the wire: {body}",
1760 route.expect_output_cap_key
1761 );
1762 assert!(
1763 body.get(route.expect_absent_output_cap_key).is_none(),
1764 "{name}: `{}` must not be on the wire: {body}",
1765 route.expect_absent_output_cap_key
1766 );
1767 assert_eq!(
1768 facts_body.wire_output_cap_tokens, wire_cap,
1769 "{name}: the reported output cap is the one literally on the wire"
1770 );
1771
1772 // --- requested → effective reasoning ------------------------------
1773 assert_eq!(
1774 manifest.session.requested_model.as_str(),
1775 route.model,
1776 "{name}"
1777 );
1778 assert_eq!(
1779 manifest.session.requested_reasoning.as_str(),
1780 route.requested_reasoning_label,
1781 "{name}"
1782 );
1783 assert_eq!(
1784 facts_body.reasoning_resolution,
1785 ReasoningResolution::Explicit,
1786 "{name}: a fixed route with an explicitly requested tier"
1787 );
1788 assert_eq!(
1789 facts_body.reasoning_wire_control_keys, route.expect_control_keys,
1790 "{name}: reasoning-control keys, against the captured body {body}"
1791 );
1792 assert_eq!(
1793 facts_body
1794 .reasoning_wire_effort
1795 .as_ref()
1796 .map(|effort| effort.as_str()),
1797 route.expect_wire_effort,
1798 "{name}: wire effort, against the captured body {body}"
1799 );
1800 assert_eq!(
1801 facts_body.reasoning_wire_effort_source.as_deref(),
1802 route.expect_wire_effort_source,
1803 "{name}"
1804 );
1805 // Every reported control key is genuinely present on the wire, and the
1806 // reported effort is genuinely readable at the reported key path.
1807 for key in &facts_body.reasoning_wire_control_keys {
1808 assert!(
1809 body.get(key).is_some(),
1810 "{name}: reported control key `{key}` is not on the wire: {body}"
1811 );
1812 }
1813 match (
1814 facts_body.reasoning_wire_effort_source.as_deref(),
1815 route.expect_wire_effort,
1816 ) {
1817 (Some("reasoning_effort"), Some(effort)) => assert_eq!(
1818 body.get("reasoning_effort")
1819 .and_then(serde_json::Value::as_str),
1820 Some(effort),
1821 "{name}: {body}"
1822 ),
1823 (Some(path), Some(effort)) => {
1824 let pointer = format!("/{}", path.replace('.', "/"));
1825 assert_eq!(
1826 body.pointer(&pointer).and_then(serde_json::Value::as_str),
1827 Some(effort),
1828 "{name}: {body}"
1829 );
1830 }
1831 (None, None) => assert!(
1832 body.get("reasoning_effort").is_none(),
1833 "{name}: no effort was reported, so none may be on the wire: {body}"
1834 ),
1835 (source, effort) => panic!("{name}: inconsistent effort receipt {source:?}/{effort:?}"),
1836 }
1837
1838 // --- Provider-authoritative usage ---------------------------------
1839 // A preview describes a request that has not been sent. Unknown stays
1840 // unknown; it never becomes a zero.
1841 assert!(
1842 matches!(
1843 &facts_body.provider_reported_usage,
1844 Availability::Unavailable(unavailable)
1845 if unavailable.reason == UnavailableReason::ProviderRequestNotExecuted
1846 ),
1847 "{name}: preview must not claim provider usage"
1848 );
1849 let json = manifest.to_json();
1850 assert!(
1851 !json.contains("\"input_tokens\""),
1852 "{name}: no fabricated usage counters reach the surface:\n{json}"
1853 );
1854 }
1855
1856 #[tokio::test]
1857 async fn matrix_glm_5_2_zai_coding_preview_matches_the_first_wire_body() {
1858 assert_matrix_route(&glm_5_2_zai_coding()).await;
1859 }
1860
1861 #[tokio::test]
1862 async fn matrix_glm_5_turbo_zai_preview_matches_the_first_wire_body() {
1863 assert_matrix_route(&glm_5_turbo_zai()).await;
1864 }
1865
1866 #[tokio::test]
1867 async fn matrix_kimi_k3_moonshot_direct_preview_matches_the_first_wire_body() {
1868 assert_matrix_route(&kimi_k3_moonshot_direct()).await;
1869 }
1870
1871 #[tokio::test]
1872 async fn matrix_k3_kimi_code_preview_matches_the_first_wire_body() {
1873 assert_matrix_route(&k3_kimi_code()).await;
1874 }
1875
1876 #[tokio::test]
1877 async fn matrix_minimax_m3_preview_matches_the_first_wire_body() {
1878 assert_matrix_route(&minimax_m3()).await;
1879 }
1880
1881 /// The active tool-catalog hash is a *catalog identity*, not a wire fact:
1882 /// the same catalog under the same posture must hash the same on every
1883 /// route, however differently each dialect then shapes those schemas.
1884 /// (Unit-level membership/order/schema sensitivity is pinned by
1885 /// `active_catalog_hash_tracks_membership_order_and_schema`.)
1886 #[tokio::test]
1887 async fn matrix_routes_share_one_active_tool_catalog_hash() {
1888 let workspace = tempfile::tempdir().expect("tempdir");
1889 let prompt = "describe the shared tool catalog";
1890 let mut observed: Vec<(&'static str, usize, String, String)> = Vec::new();
1891
1892 for route in matrix_routes() {
1893 let config = matrix_config(&route);
1894 let (mut engine, _handle) = Engine::new(
1895 EngineConfig {
1896 workspace: workspace.path().to_path_buf(),
1897 max_steps: 1,
1898 snapshots_enabled: false,
1899 terminal_chrome_enabled: false,
1900 ..Default::default()
1901 },
1902 &config,
1903 );
1904 engine.config.features.disable(Feature::Mcp);
1905 engine.config.subagents_enabled = false;
1906
1907 let planned = matrix_planned_route(&route, &config, None, prompt).await;
1908 let manifest = engine
1909 .build_request_manifest(inputs(false, Some(planned), prompt))
1910 .await;
1911 let tools = manifest
1912 .tools
1913 .exact()
1914 .expect("MCP is off, so the tool surface is exact");
1915 assert!(
1916 tools.standard_and_full_surfaces_collapsed,
1917 "{}: this fixture's catalog fits both budgets, so the surface \
1918 budget label cannot change catalog membership",
1919 route.name
1920 );
1921 observed.push((
1922 route.name,
1923 tools.active_tool_count,
1924 tools.active_tool_catalog_sha256.clone(),
1925 tools.tool_surface_budget.clone(),
1926 ));
1927 }
1928
1929 assert_eq!(observed.len(), 5, "every matrix route is represented");
1930 let (first_name, first_count, first_hash, _) = observed[0].clone();
1931 for (name, count, hash, _) in &observed {
1932 assert_eq!(
1933 *count, first_count,
1934 "{name} vs {first_name}: the matrix fixture holds the tool surface constant"
1935 );
1936 assert_eq!(
1937 hash, &first_hash,
1938 "{name} vs {first_name}: one catalog must hash to one identity across routes"
1939 );
1940 }
1941
1942 // …and the routes really are distinct in capability posture: the shared
1943 // hash is a genuine cross-route agreement, not five copies of one
1944 // route. GLM-5.2 publishes a `Full` tool surface budget while
1945 // GLM-5-Turbo publishes `Standard`, and the catalog identity is
1946 // unchanged by that difference.
1947 let budgets: std::collections::BTreeSet<&str> = observed
1948 .iter()
1949 .map(|(_, _, _, budget)| budget.as_str())
1950 .collect();
1951 assert!(
1952 budgets.len() > 1,
1953 "the matrix spans routes with different surface budgets: {budgets:?}"
1954 );
1955 }
1956
1957 /// Provider-authoritative usage is never a preview fact, and it is never a
1958 /// zero standing in for "not measured". It becomes knowable only when a
1959 /// response reports it, through the same `parse_usage` seam the turn loop
1960 /// uses.
1961 #[tokio::test]
1962 async fn provider_reported_usage_is_unavailable_until_a_response_reports_it() {
1963 use wiremock::matchers::method;
1964 use wiremock::{Mock, MockServer, ResponseTemplate};
1965
1966 let usage = json!({"prompt_tokens": 137, "completion_tokens": 24, "total_tokens": 161});
1967 let stream = format!(
1968 "data: {}\n\ndata: {}\n\ndata: [DONE]\n\n",
1969 json!({
1970 "choices": [{"index": 0, "delta": {"content": "ok"}}],
1971 }),
1972 json!({
1973 "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
1974 "usage": usage,
1975 })
1976 );
1977
1978 let server = MockServer::start().await;
1979 Mock::given(method("POST"))
1980 .respond_with(
1981 ResponseTemplate::new(200)
1982 .insert_header("content-type", "text/event-stream")
1983 .set_body_string(stream),
1984 )
1985 .mount(&server)
1986 .await;
1987
1988 let mut config = deepseek_config();
1989 config
1990 .providers
1991 .as_mut()
1992 .expect("providers")
1993 .deepseek
1994 .base_url = Some(server.uri());
1995 let identity = deepseek_identity();
1996 let (mut engine, _handle, _tmp) = wire_preview_engine(&config);
1997
1998 let prompt = "count the tokens this turn will report";
1999 let planned = plan(&config, &identity, false, prompt).await;
2000 let production_route = planned.route.clone();
2001 let compaction = planned.compaction.clone();
2002 let reasoning_effort = planned.effective_reasoning_effort.clone();
2003 let reasoning_effort_auto = planned.auto_controls_reasoning;
2004
2005 let manifest = engine
2006 .build_request_manifest(inputs(false, Some(planned), prompt))
2007 .await;
2008 let body = manifest.body.exact().expect("a prompted body is exact");
2009 assert!(
2010 matches!(
2011 &body.provider_reported_usage,
2012 Availability::Unavailable(unavailable)
2013 if unavailable.reason == UnavailableReason::ProviderRequestNotExecuted
2014 ),
2015 "no request occurred, so there is nothing the provider reported"
2016 );
2017 assert_eq!(
2018 engine.session.total_usage.input_tokens, 0,
2019 "and nothing has been recorded yet"
2020 );
2021 assert_eq!(engine.session.total_usage.output_tokens, 0);
2022
2023 let _ = engine
2024 .handle_send_message(TurnSpec {
2025 profile_constitution: None,
2026 content: prompt.to_string(),
2027 mode: AppMode::Agent,
2028 route: Box::new(production_route),
2029 compaction: Box::new(compaction),
2030 initial_routed_usage: Box::new(crate::cost_status::RuntimeUsageBatch::default()),
2031 goal_objective: None,
2032 goal_token_budget: None,
2033 goal_status: GoalStatus::Active,
2034 reasoning_effort,
2035 reasoning_effort_auto,
2036 auto_model: false,
2037 allow_shell: false,
2038 trust_mode: false,
2039 auto_approve: false,
2040 approval_mode: ApprovalMode::Suggest,
2041 translation_enabled: false,
2042 allowed_tools: None,
2043 dynamic_tools: Vec::new(),
2044 hook_executor: None,
2045 verbosity: None,
2046 provenance: UserInputProvenance::ExternalUser,
2047 input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson,
2048 images: Vec::new(),
2049 max_output_tokens: None,
2050 submission_id: None,
2051 })
2052 .await;
2053
2054 // The completed turn's counts are exactly what `parse_usage` reads off
2055 // the reported usage object — no rounding, no substituted estimate.
2056 let parsed = crate::client::parse_usage(Some(&usage));
2057 assert_eq!(u64::from(parsed.input_tokens), 137);
2058 assert_eq!(u64::from(parsed.output_tokens), 24);
2059 assert_eq!(
2060 (
2061 engine.session.total_usage.input_tokens,
2062 engine.session.total_usage.output_tokens
2063 ),
2064 (
2065 u64::from(parsed.input_tokens),
2066 u64::from(parsed.output_tokens)
2067 ),
2068 "the turn records the provider-authoritative counts, not an estimate"
2069 );
2070 let reported = crate::request_manifest::ProviderReportedUsage {
2071 input_tokens: engine.session.total_usage.input_tokens,
2072 output_tokens: engine.session.total_usage.output_tokens,
2073 };
2074 assert_eq!(reported.input_tokens, 137);
2075 assert_eq!(reported.output_tokens, 24);
2076 }
2077
2078 /// A fixed route with a hypothetical prompt describes the next turn
2079 /// exactly: route, tools, and body are all published, and the prompt is
2080 /// part of the hashed body.
2081 #[tokio::test]
2082 async fn fixed_route_with_a_prompt_describes_the_exact_next_turn() {
2083 let mut config = deepseek_config();
2084 config
2085 .providers
2086 .as_mut()
2087 .expect("providers")
2088 .deepseek
2089 .context_window = Some(123_456);
2090 let identity = deepseek_identity();
2091 let (mut engine, _handle, _tmp) = preview_engine(&config);
2092 engine.config.features.disable(Feature::Mcp);
2093 engine.active_route_limits = Some(codewhale_config::route::RouteLimits {
2094 context_tokens: Some(4_096),
2095 input_tokens: Some(3_000),
2096 output_tokens: Some(512),
2097 output_declared: false,
2098 });
2099
2100 let planned = plan(&config, &identity, false, "refactor the parser").await;
2101 let planned_limits = crate::route_budget::known_route_limits(planned.route.candidate.limits());
2102 let expected_input_budget = context_input_budget_for_route(
2103 planned.route.identity.provider,
2104 &planned.route.model,
2105 planned_limits,
2106 0,
2107 );
2108 let expected_wire_output = crate::route_budget::effective_max_output_tokens_for_route(
2109 planned.route.identity.provider,
2110 &planned.route.model,
2111 planned_limits,
2112 );
2113 let manifest = engine
2114 .build_request_manifest(inputs(false, Some(planned), "refactor the parser"))
2115 .await;
2116
2117 let route = manifest.route.exact().expect("a fixed route is exact");
2118 assert_eq!(route.provider_id.as_str(), "deepseek");
2119 assert_eq!(route.routing_source, "active-fixed-route");
2120 assert_eq!(route.dialect, "openai-responses");
2121 assert_eq!(route.caller_entrypoint, "streaming");
2122 assert_eq!(route.body_stream_field, Some(true));
2123 assert_eq!(route.context_limit_tokens, 123_456);
2124 assert_eq!(
2125 route.context_limit_source,
2126 crate::route_runtime::ContextWindowSource::Configured
2127 );
2128 assert_eq!(
2129 route.route_input_limit_tokens,
2130 planned_limits.and_then(|limits| limits.input_tokens)
2131 );
2132 assert_eq!(
2133 route.route_output_limit_tokens,
2134 planned_limits.and_then(|limits| limits.output_tokens)
2135 );
2136 assert!(!route.wire_model.is_redacted());
2137 assert!(
2138 manifest.tools.exact().is_some(),
2139 "MCP is off in this engine"
2140 );
2141
2142 let body = manifest.body.exact().expect("a prompted body is exact");
2143 assert_eq!(body.input_budget_ceiling_tokens, expected_input_budget);
2144 assert_eq!(
2145 body.wire_output_cap_tokens,
2146 Some(u64::from(expected_wire_output))
2147 );
2148 assert_eq!(body.body_sha256.len(), 64);
2149 assert!(
2150 body.message_count >= 1,
2151 "the hypothetical prompt is a message"
2152 );
2153 assert!(body.local_system_tools_component_sha256.is_some());
2154 assert!(manifest.session.hypothetical_prompt_supplied);
2155
2156 // The prompt is genuinely part of the request being described.
2157 let other_planned = plan(&config, &identity, false, "write the release notes").await;
2158 let other = engine
2159 .build_request_manifest(inputs(
2160 false,
2161 Some(other_planned),
2162 "write the release notes",
2163 ))
2164 .await;
2165 assert_ne!(
2166 body.body_sha256,
2167 other.body.exact().expect("exact").body_sha256,
2168 "a different next prompt must produce a different body hash"
2169 );
2170 }
2171
2172 /// The engine can describe an Auto route receipt supplied by a trusted
2173 /// host without consulting installed state. The human preview command
2174 /// deliberately never obtains such a receipt, because doing so would call
2175 /// the provider-backed classifier.
2176 #[tokio::test]
2177 async fn host_supplied_auto_route_receipt_matches_the_production_planner() {
2178 let config = deepseek_config();
2179 let identity = deepseek_identity();
2180 let (mut engine, _handle, _tmp) = preview_engine(&config);
2181 engine.config.features.disable(Feature::Mcp);
2182
2183 let planned = plan(&config, &identity, true, "explain this stack trace").await;
2184 let planned_provider = planned.effective_provider;
2185 let planned_identity = planned.effective_provider_identity.clone();
2186 let planned_model = planned.route.model.clone();
2187 let planned_base_url = planned.route.candidate.endpoint().base_url.clone();
2188 assert!(
2189 planned.auto_controls_reasoning,
2190 "the helper requests auto reasoning for its auto-model fixture"
2191 );
2192
2193 let manifest = engine
2194 .build_request_manifest(inputs(true, Some(planned), "explain this stack trace"))
2195 .await;
2196
2197 let route = manifest
2198 .route
2199 .exact()
2200 .expect("auto + prompt resolves a route");
2201 assert_eq!(route.provider_id.as_str(), planned_provider.as_str());
2202 assert_eq!(route.routing_source, "auto-provider-classifier");
2203 assert_eq!(planned_identity, "deepseek");
2204 assert_eq!(
2205 route.wire_model.as_str(),
2206 codewhale_config::route::resolve_model(
2207 planned_provider,
2208 &planned_model,
2209 Some(&planned_base_url),
2210 )
2211 .map_or_else(
2212 |_| planned_model.trim().to_string(),
2213 |resolved| resolved.wire_id
2214 ),
2215 "the wire model is the planner's model after route remapping — not \
2216 the model the session happens to have installed"
2217 );
2218 assert_eq!(
2219 manifest.session.requested_model.as_str(),
2220 "auto",
2221 "the manifest never reports the resolved model as the user's selection"
2222 );
2223
2224 let body = match &manifest.body {
2225 Availability::Exact(body) => body,
2226 Availability::Unavailable(unavailable) => {
2227 panic!("auto + prompt should have an exact body: {unavailable:?}")
2228 }
2229 };
2230 assert_ne!(
2231 body.reasoning_resolution,
2232 ReasoningResolution::Explicit,
2233 "an auto-routed turn never claims an explicit user tier"
2234 );
2235
2236 // The hypothetical prompt is part of the hashed body on the auto path
2237 // too, not only on the fixed one.
2238 let other = plan(&config, &identity, true, "rename one local variable").await;
2239 let other = engine
2240 .build_request_manifest(inputs(true, Some(other), "rename one local variable"))
2241 .await;
2242 assert_ne!(
2243 body.body_sha256,
2244 other.body.exact().expect("exact").body_sha256
2245 );
2246 }
2247
2248 /// The passive path must not create an MCP pool, connect a server, or
2249 /// emit a UI event — it reports the tool surface unavailable instead.
2250 #[tokio::test]
2251 async fn preview_tool_snapshot_has_no_mcp_or_event_side_effects() {
2252 let tmp = tempfile::tempdir().expect("tempdir");
2253 let config = {
2254 let __cw_config_init_3_0 = Some("deepseek".to_string());
2255 let mut __cw_config_init_3_value: codewhale_runtime::config::Config =
2256 codewhale_runtime::config::Config::default();
2257 __cw_config_init_3_value.provider = __cw_config_init_3_0;
2258 __cw_config_init_3_value
2259 };
2260 let (mut engine, handle) = Engine::new(
2261 EngineConfig {
2262 workspace: tmp.path().to_path_buf(),
2263 ..Default::default()
2264 },
2265 &config,
2266 );
2267 let _ = engine.config.features.enable(Feature::Mcp);
2268
2269 let policy = TurnAuthority::from_effective_fields(
2270 AppMode::Agent,
2271 false,
2272 false,
2273 false,
2274 ApprovalMode::Suggest,
2275 );
2276 let build = engine
2277 .build_turn_tool_registry_and_catalog(
2278 &policy,
2279 &[],
2280 None,
2281 SubAgentWiring::Inert,
2282 McpAccess::PassiveSnapshot,
2283 &[],
2284 TurnRouteContext {
2285 provider: engine.api_provider,
2286 model: engine.session.model.clone(),
2287 capabilities: engine.active_route_capabilities,
2288 limits: engine.active_route_limits,
2289 client: engine.codewhale_client.clone(),
2290 api_config: Box::new(engine.api_config.clone()),
2291 locale_tag: engine.config.locale_tag.clone(),
2292 role_models: engine.subagent_role_models(),
2293 auto_model: false,
2294 reasoning_effort: None,
2295 reasoning_effort_auto: false,
2296 },
2297 "",
2298 )
2299 .await;
2300
2301 assert!(
2302 engine.mcp_pool.is_none(),
2303 "a passive snapshot must not create the MCP pool"
2304 );
2305 assert!(
2306 matches!(build.mcp, McpToolState::Unavailable { .. }),
2307 "with no connected pool the MCP tool state is unavailable, not empty"
2308 );
2309 assert!(build.mcp.server_count().is_none());
2310 drop(handle);
2311 }
2312
2313 /// The reviewed blocker: with MCP enabled but nothing connected, the
2314 /// preview built a catalog with zero MCP tools, prepared a body from it,
2315 /// and published that body as `Exact` — a hash of a request no turn would
2316 /// ever send. The body must inherit the tool surface's typed reason.
2317 #[tokio::test]
2318 async fn unavailable_mcp_state_makes_the_body_unavailable_too() {
2319 let config = deepseek_config();
2320 let identity = deepseek_identity();
2321 let (mut engine, _handle, _tmp) = preview_engine(&config);
2322 // MCP on, pool never started: a real turn would connect and could
2323 // discover tools this catalog does not contain.
2324 let _ = engine.config.features.enable(Feature::Mcp);
2325
2326 let planned = plan(&config, &identity, false, "refactor the parser").await;
2327 let manifest = engine
2328 .build_request_manifest(inputs(false, Some(planned), "refactor the parser"))
2329 .await;
2330
2331 assert!(
2332 manifest.tools.exact().is_none(),
2333 "an unconnected MCP pool is not a snapshottable tool surface"
2334 );
2335 assert!(
2336 manifest.body.exact().is_none(),
2337 "a body built from a tool surface missing its MCP contribution \
2338 must not be published as exact"
2339 );
2340 assert!(
2341 manifest.route.exact().is_some(),
2342 "the route does not depend on the MCP contribution and stays exact"
2343 );
2344
2345 // No body fact — hash, byte count, or local component fingerprint —
2346 // reaches either surface.
2347 let json = manifest.to_json();
2348 for forbidden in [
2349 "body_sha256",
2350 "local_system_tools_component_sha256",
2351 "tool_schema_wire_sha256",
2352 "body_canonical_json_bytes",
2353 "estimated_input_headroom_tokens",
2354 ] {
2355 assert!(!json.contains(forbidden), "{forbidden} leaked:\n{json}");
2356 }
2357 assert!(json.contains("mcp-state-not-snapshottable"), "{json}");
2358 assert!(engine.mcp_pool.is_none(), "no pool was created by looking");
2359 }
2360
2361 /// A preview is an inspection. Every piece of engine state a turn would
2362 /// have written must be byte-identical afterwards — including the ones the
2363 /// earlier implementation wrote and restored around an `.await`.
2364 #[tokio::test]
2365 async fn building_a_manifest_writes_no_engine_state() {
2366 let config = deepseek_config();
2367 let identity = deepseek_identity();
2368 let (mut engine, _handle, _tmp) = preview_engine(&config);
2369 engine.config.features.disable(Feature::Mcp);
2370 engine.config.allowed_tools = Some(vec!["Bash".to_string()]);
2371 engine.session.add_message(Message {
2372 role: Role::User,
2373 content: vec![ContentBlock::Text {
2374 text: "an earlier turn".to_string(),
2375 cache_control: None,
2376 }],
2377 });
2378
2379 let allowed_before = engine.config.allowed_tools.clone();
2380 let disallowed_before = engine.config.disallowed_tools.clone();
2381 let messages_before = engine.messages_with_turn_metadata();
2382 let model_before = engine.session.model.clone();
2383 let system_prompt_before = system_prompt_hash(engine.session.system_prompt.as_ref());
2384 let system_hash_before = engine.session.last_system_prompt_hash;
2385 let working_set_before = engine.session.working_set.summary_block(
2386 &engine.config.workspace,
2387 &crate::tools::file::working_set_read_allowed,
2388 );
2389 let provider_before = engine.api_provider;
2390 let mode_before = engine.current_mode;
2391 let narrowing_before = format!("{:?}", engine.last_policy_narrowing);
2392 let turn_counter_before = engine.turn_counter;
2393
2394 // A *different* command-scoped gate than the installed one, and a
2395 // prompt that mentions a path so the working set would move if the
2396 // preview observed it on the session rather than on a clone.
2397 let mut preview_inputs = inputs(
2398 false,
2399 Some(plan(&config, &identity, false, "inspect src/lib.rs").await),
2400 "inspect src/lib.rs",
2401 );
2402 preview_inputs.allowed_tools = Some(vec!["Read".to_string()]);
2403 let manifest = engine.build_request_manifest(preview_inputs).await;
2404 assert!(manifest.body.exact().is_some(), "fixture should be exact");
2405
2406 assert_eq!(engine.config.allowed_tools, allowed_before, "tool gate");
2407 assert_eq!(engine.config.disallowed_tools, disallowed_before);
2408 assert_eq!(
2409 engine.messages_with_turn_metadata(),
2410 messages_before,
2411 "history"
2412 );
2413 assert_eq!(engine.session.model, model_before);
2414 assert_eq!(
2415 system_prompt_hash(engine.session.system_prompt.as_ref()),
2416 system_prompt_before
2417 );
2418 assert_eq!(engine.session.last_system_prompt_hash, system_hash_before);
2419 assert_eq!(
2420 engine.session.working_set.summary_block(
2421 &engine.config.workspace,
2422 &crate::tools::file::working_set_read_allowed,
2423 ),
2424 working_set_before,
2425 "the hypothetical message is observed on a clone, never on the session"
2426 );
2427 assert_eq!(engine.api_provider, provider_before);
2428 assert_eq!(engine.current_mode, mode_before);
2429 assert_eq!(
2430 format!("{:?}", engine.last_policy_narrowing),
2431 narrowing_before
2432 );
2433 assert_eq!(engine.turn_counter, turn_counter_before);
2434 assert!(engine.mcp_pool.is_none());
2435 }
2436
2437 /// The gate is a parameter, so it shapes the previewed catalog without
2438 /// ever being installed.
2439 #[tokio::test]
2440 async fn the_previewed_tool_gate_applies_without_being_installed() {
2441 let config = deepseek_config();
2442 let identity = deepseek_identity();
2443 let (mut engine, _handle, _tmp) = preview_engine(&config);
2444 engine.config.features.disable(Feature::Mcp);
2445
2446 let wide = engine
2447 .build_request_manifest(inputs(
2448 false,
2449 Some(plan(&config, &identity, false, "do the thing").await),
2450 "do the thing",
2451 ))
2452 .await;
2453
2454 let mut narrow_inputs = inputs(
2455 false,
2456 Some(plan(&config, &identity, false, "do the thing").await),
2457 "do the thing",
2458 );
2459 narrow_inputs.allowed_tools = Some(vec!["Read".to_string()]);
2460 let narrow = engine.build_request_manifest(narrow_inputs).await;
2461
2462 let wide_tools = wide.tools.exact().expect("exact");
2463 let narrow_tools = narrow.tools.exact().expect("exact");
2464 assert!(
2465 narrow_tools.active_tool_count < wide_tools.active_tool_count,
2466 "the passed gate must narrow the previewed catalog: {} vs {}",
2467 narrow_tools.active_tool_count,
2468 wide_tools.active_tool_count
2469 );
2470 assert_eq!(
2471 narrow.session.allowed_tool_gate_count,
2472 Some(1),
2473 "and the session section reports the gate that was previewed"
2474 );
2475 assert_eq!(
2476 engine.config.allowed_tools, None,
2477 "…while the engine keeps its own"
2478 );
2479 }
2480
2481 /// A plan failure still happened *because of* a supplied prompt. Reporting
2482 /// otherwise tells the user to pass the flag they just passed.
2483 #[tokio::test]
2484 async fn a_failed_plan_still_reports_that_a_prompt_was_supplied() {
2485 let (mut engine, _handle, _tmp) = preview_engine(&codewhale_runtime::config::Config::default());
2486 let mut failed = inputs(false, None, "");
2487 failed.unresolved = PreviewUnresolved::PlanFailed(
2488 "no API key configured for route 'my-gateway' at /home/someone/.config".to_string(),
2489 );
2490
2491 let manifest = engine.build_request_manifest(failed).await;
2492 assert!(manifest.session.hypothetical_prompt_supplied);
2493 assert!(manifest.route.exact().is_none());
2494
2495 let rendered = manifest.render();
2496 assert!(
2497 !rendered.contains("Pass `--prompt <text>`"),
2498 "the user already did:\n{rendered}"
2499 );
2500 // …and the raw host text never reaches a surface verbatim.
2501 for surface in [rendered, manifest.to_json()] {
2502 assert!(!surface.contains("my-gateway'"), "{surface}");
2503 assert!(!surface.contains("/home/someone"), "{surface}");
2504 }
2505 }
2506
2507 /// Pending runtime injections are *counted*, never consumed, and they make
2508 /// the body unavailable rather than silently absent from it.
2509 #[tokio::test]
2510 async fn pending_runtime_injections_make_the_body_unavailable_without_consuming_them() {
2511 let config = deepseek_config();
2512 let identity = deepseek_identity();
2513 let (mut engine, _handle, _tmp) = preview_engine(&config);
2514 engine.config.features.disable(Feature::Mcp);
2515 engine
2516 .pending_lsp_blocks
2517 .push(codewhale_lsp::DiagnosticBlock {
2518 file: std::path::PathBuf::from("src/lib.rs"),
2519 items: Vec::new(),
2520 });
2521
2522 let manifest = engine
2523 .build_request_manifest(inputs(
2524 false,
2525 Some(plan(&config, &identity, false, "fix it").await),
2526 "fix it",
2527 ))
2528 .await;
2529
2530 assert!(
2531 manifest.body.exact().is_none(),
2532 "the turn loop would inject diagnostics before the first request"
2533 );
2534 assert!(manifest.route.exact().is_some());
2535 assert_eq!(
2536 engine.pending_lsp_blocks.len(),
2537 1,
2538 "inspecting must not flush the pending blocks"
2539 );
2540 assert!(
2541 manifest
2542 .to_json()
2543 .contains("runtime-transforms-before-send"),
2544 "{}",
2545 manifest.to_json()
2546 );
2547 }
2548
2548 lines RUST