返回 CodeWhale
debug_diagnostics_surface_tests.rs
根目录 / crates / tui / src / commands / debug_diagnostics_surface_tests.rs
1 //! FEAT-029: public command-surface and localization parity for the
2 //! `debug::diagnostics` slice.
3 //!
4 //! The host regressions prove handler/rendering parity. This module proves the
5 //! *observable command surface* is unchanged: registry metadata (name, aliases,
6 //! usage), registry position, the `description_key` -> catalog bridge, palette
7 //! and discovery classification, and canonical-name/alias dispatch equivalence
8 //! through the public `execute` seam.
9 //!
10 //! It lives at the `commands` root for the same FEAT-045 extraction reason as
11 //! the regression suite. The metadata fixture was captured from the
12 //! untouched implementation and compared byte-for-byte.
13
14 use codewhale_localization::{Locale, MessageId};
15
16 use crate::commands::debug_diagnostics_test_support::{DiagnosticsHarness, assert_fixture};
17 use crate::commands::{CommandResult, execute};
18 use crate::tui::app::AppAction;
19 use codewhale_config::ProviderKind;
20
21 /// The eight declared diagnostics commands in registry order, with their exact
22 /// aliases and catalog description ids.
23 const DIAGNOSTICS: &[(&str, &[&str], MessageId)] = &[
24 ("tokens", &[], MessageId::CmdTokensDescription),
25 ("cost", &[], MessageId::CmdCostDescription),
26 ("balance", &[], MessageId::CmdBalanceDescription),
27 ("cache", &[], MessageId::CmdCacheDescription),
28 (
29 "preview-request",
30 &["dryrun", "preview_request"],
31 MessageId::CmdPreviewRequestDescription,
32 ),
33 ("tools", &["tool-studio"], MessageId::CmdToolsDescription),
34 ("system", &["xitong"], MessageId::CmdSystemDescription),
35 ("context", &["ctx"], MessageId::CmdContextDescription),
36 ];
37
38 fn info(name: &str) -> &'static crate::commands::CommandInfo {
39 crate::commands::get_command_info(name)
40 .unwrap_or_else(|| panic!("/{name} must remain registered"))
41 }
42
43 /// Freeze the complete registry metadata surface (name, aliases, usage,
44 /// English description, palette text, discovery flags) for all eight commands.
45 #[test]
46 fn diagnostics_surface_metadata_matches_baseline() {
47 let _harness = DiagnosticsHarness::new();
48 let mut out = String::new();
49 for (name, _, _) in DIAGNOSTICS {
50 let info = info(name);
51 out.push_str(&format!("name: {}\n", info.name));
52 out.push_str(&format!("aliases: {:?}\n", info.aliases));
53 out.push_str(&format!("usage: {}\n", info.usage));
54 out.push_str(&format!(
55 "description_en: {}\n",
56 info.description_for(Locale::En)
57 ));
58 out.push_str(&format!(
59 "palette_en: {}\n",
60 info.palette_description_for(Locale::En)
61 ));
62 out.push_str(&format!(
63 "requires_argument: {}\n",
64 info.requires_argument()
65 ));
66 out.push_str(&format!("unlisted: {}\n", info.is_unlisted()));
67 out.push_str(&format!(
68 "show_in_empty_discovery: {}\n",
69 info.show_in_empty_discovery()
70 ));
71 out.push_str("---\n");
72 }
73 assert_fixture("surface_metadata.txt", &out);
74 }
75
76 /// Every canonical name and alias resolves to the same registry entry, and the
77 /// `description_key` bridge maps to the expected catalog `MessageId`.
78 #[test]
79 fn diagnostics_names_aliases_and_description_bridge_are_exact() {
80 let registry = crate::commands::registry();
81 for (name, aliases, description_id) in DIAGNOSTICS {
82 let canonical = info(name);
83 assert_eq!(canonical.name, *name, "canonical name");
84 assert_eq!(canonical.aliases, *aliases, "/{name} alias list");
85 assert_eq!(
86 canonical.description_id, *description_id,
87 "/{name} catalog bridge"
88 );
89 assert!(
90 !canonical.description_for(Locale::En).trim().is_empty(),
91 "/{name} must resolve an English description"
92 );
93
94 let entry = registry
95 .get(name)
96 .unwrap_or_else(|| panic!("/{name} must be registered"));
97 assert_eq!(entry.info().name, *name);
98 for alias in *aliases {
99 let via_alias = registry
100 .get(alias)
101 .unwrap_or_else(|| panic!("/{alias} must resolve"));
102 assert_eq!(
103 via_alias.info().name,
104 *name,
105 "/{alias} must resolve to /{name}"
106 );
107 assert_eq!(via_alias.info().usage, canonical.usage, "/{alias} usage");
108 }
109 }
110 }
111
112 /// Portable description keys resolve to the exact original catalog ids for
113 /// every member; metadata does not grant a runtime presentation facet.
114 #[test]
115 fn diagnostics_description_keys_resolve_to_the_original_catalog() {
116 let keys = [
117 ("tokens", "cmd_tokens_description"),
118 ("cost", "cmd_cost_description"),
119 ("balance", "cmd_balance_description"),
120 ("cache", "cmd_cache_description"),
121 ("preview-request", "cmd_preview_request_description"),
122 ("tools", "cmd_tools_description"),
123 ("system", "cmd_system_description"),
124 ("context", "cmd_context_description"),
125 ];
126 for ((name, _, id), (expected_name, key)) in DIAGNOSTICS.iter().zip(keys) {
127 assert_eq!(*name, expected_name);
128 assert_eq!(super::contract::key_to_message_id(key), Some(*id));
129 assert_eq!(info(name).description_id, *id);
130 assert!(!info(name).description_for(Locale::Ja).is_empty());
131 }
132 assert_eq!(
133 super::contract::key_to_message_id("cmd_not_registered_description"),
134 None
135 );
136 }
137
138 /// Runtime presentation uses the existing catalog and exact named-placeholder
139 /// contract for only the three commands that need it. Literal metadata is
140 /// separately bridged above; an unknown key or incomplete replacements fail.
141 #[test]
142 fn diagnostics_runtime_translation_uses_original_catalog_and_placeholder_contract() {
143 let mut harness = DiagnosticsHarness::new();
144 harness.app.ui_locale = Locale::Ja;
145 let mut bundle = harness.app.command_contexts();
146 let mut parts = bundle
147 .contexts(codewhale_command_contract::handler::CommandCapabilities::PRESENTATION)
148 .into_parts();
149 let presentation = parts.presentation.as_deref_mut().unwrap();
150 assert_eq!(
151 presentation.translate("cmd_cost_coverage", &[("priced", "2"), ("turns", "3")]),
152 Ok("対象: 課金対象ターン 3 件のうち 2 件を算定しました。".into())
153 );
154 assert_eq!(
155 presentation.translate(
156 "cmd_cache_totals",
157 &[
158 ("sum_in", "4"),
159 ("sum_hit", "2"),
160 ("sum_miss", "1"),
161 ("avg", "50%")
162 ],
163 ),
164 Ok("Σ 入力: 4 Σ ヒット: 2 Σ ミス: 1 平均ヒット率: 50%\n".into())
165 );
166 assert_eq!(
167 presentation.translate(
168 "cmd_tokens_context_with_window",
169 &[("used", "6"), ("window", "12"), ("percent", "50.0")],
170 ),
171 Ok("~6 / 12 (50.0%)".into())
172 );
173 assert_eq!(
174 presentation.translate("cmd_cost_coverage", &[("priced", "2")]),
175 Err("invalid translation replacement contract".into())
176 );
177 assert_eq!(
178 presentation.translate("cmd_not_registered", &[]),
179 Err("unknown translation key".into())
180 );
181 }
182
183 /// The production registry now exposes exactly the declared facets, including
184 /// each alias. Preview stays a pure function, not a contextual empty envelope.
185 #[test]
186 fn diagnostics_registrations_expose_exact_facets_and_preview_is_pure() {
187 use codewhale_command_contract::handler::{
188 CommandCapabilities as Caps, CommandContexts, CommandHandler,
189 };
190
191 let mut harness = DiagnosticsHarness::new();
192 for (name, aliases, _) in DIAGNOSTICS {
193 let expected = match *name {
194 "tokens" | "cost" | "cache" => Caps::DEBUG_DIAGNOSTICS | Caps::PRESENTATION,
195 "preview-request" => Caps::NONE,
196 _ => Caps::DEBUG_DIAGNOSTICS,
197 };
198 for spelling in std::iter::once(*name).chain(aliases.iter().copied()) {
199 let registered = crate::commands::registry()
200 .get(spelling)
201 .expect("registered spelling");
202 match registered
203 .contextual_handler()
204 .expect("portable registration")
205 {
206 CommandHandler::Pure(pure) => {
207 assert_eq!(*name, "preview-request", "only preview is pure");
208 assert_eq!(expected, Caps::NONE);
209 assert!(matches!(
210 pure(Some("json")).action,
211 Some(AppAction::PreviewOutboundRequest { json: true, .. })
212 ));
213 }
214 CommandHandler::Contextual {
215 capabilities,
216 handler,
217 } => {
218 assert_ne!(*name, "preview-request");
219 assert_eq!(capabilities, expected, "/{spelling} declaration");
220 let result = handler(CommandContexts::empty(), None);
221 assert!(result.is_error);
222 assert_eq!(
223 result.message.as_deref(),
224 Some("Error: Command capability unavailable: debug_diagnostics")
225 );
226 assert!(result.action.is_none());
227
228 let mut bundle = harness.app.command_contexts();
229 let parts = bundle.contexts(capabilities).into_parts();
230 let codewhale_command_contract::handler::ContextParts {
231 session,
232 model,
233 cost,
234 mode_policy,
235 system_prompt,
236 skills,
237 workspace,
238 presentation,
239 media,
240 memory,
241 project,
242 skill_group,
243 plugin,
244 lifecycle,
245 control,
246 export,
247 structcopy,
248 debug_receipts,
249 debug_change,
250 debug_history,
251 debug_diff,
252 debug_undo,
253 debug_diagnostics,
254 permissions,
255 config_status,
256 config,
257 pet,
258 trust,
259 login,
260 work_surface,
261 navigation,
262 voice_input,
263 } = parts;
264 assert!(
265 permissions.is_none()
266 && config_status.is_none()
267 && config.is_none()
268 && pet.is_none()
269 && trust.is_none()
270 && login.is_none()
271 && work_surface.is_none()
272 && navigation.is_none()
273 && voice_input.is_none()
274 );
275 assert!(debug_diagnostics.is_some(), "/{spelling} needs diagnostics");
276 assert_eq!(
277 presentation.is_some(),
278 expected.contains(Caps::PRESENTATION),
279 "/{spelling} presentation"
280 );
281 for (facet, exposed) in [
282 ("session", session.is_some()),
283 ("model", model.is_some()),
284 ("cost", cost.is_some()),
285 ("mode_policy", mode_policy.is_some()),
286 ("system_prompt", system_prompt.is_some()),
287 ("skills", skills.is_some()),
288 ("workspace", workspace.is_some()),
289 ("media", media.is_some()),
290 ("memory", memory.is_some()),
291 ("project", project.is_some()),
292 ("skill_group", skill_group.is_some()),
293 ("plugin", plugin.is_some()),
294 ("lifecycle", lifecycle.is_some()),
295 ("control", control.is_some()),
296 ("export", export.is_some()),
297 ("structcopy", structcopy.is_some()),
298 ("debug_receipts", debug_receipts.is_some()),
299 ("debug_change", debug_change.is_some()),
300 ("debug_history", debug_history.is_some()),
301 ("debug_diff", debug_diff.is_some()),
302 ("debug_undo", debug_undo.is_some()),
303 ] {
304 assert!(!exposed, "/{spelling} must not expose {facet}");
305 }
306 }
307 }
308 }
309 }
310 for name in ["receipts", "change", "edit", "diff", "undo", "retry"] {
311 assert!(
312 crate::commands::registry()
313 .get(name)
314 .unwrap()
315 .contextual_handler()
316 .is_some(),
317 "/{name} must use its portable registration"
318 );
319 }
320 }
321
322 /// Registry position inside the debug group is preserved: the eight
323 /// diagnostics commands stay in their original relative order and the five
324 /// The other debug commands remain registered around these diagnostics.
325 #[test]
326 fn diagnostics_registry_position_matches_baseline() {
327 let names: Vec<&str> = crate::commands::command_infos()
328 .iter()
329 .map(|info| info.name)
330 .collect();
331 let position = |name: &str| {
332 names
333 .iter()
334 .position(|candidate| *candidate == name)
335 .unwrap_or_else(|| panic!("/{name} must be registered; found {names:?}"))
336 };
337
338 let order = [
339 "tokens",
340 "cost",
341 "receipts",
342 "balance",
343 "cache",
344 "preview-request",
345 "tools",
346 "change",
347 "system",
348 "context",
349 "edit",
350 "diff",
351 "undo",
352 "retry",
353 ];
354 for pair in order.windows(2) {
355 assert!(
356 position(pair[0]) < position(pair[1]),
357 "/{} must stay before /{}",
358 pair[0],
359 pair[1]
360 );
361 }
362 }
363
364 fn render(result: &CommandResult) -> String {
365 let mut out = String::new();
366 out.push_str(&format!("is_error: {}\n", result.is_error));
367 match &result.message {
368 Some(message) => out.push_str(&format!("message:\n{message}\n")),
369 None => out.push_str("message: <none>\n"),
370 }
371 match &result.action {
372 Some(action) => out.push_str(&format!("action: {action:?}\n")),
373 None => out.push_str("action: <none>\n"),
374 }
375 out
376 }
377
378 /// Canonical names and every compatibility alias dispatch to byte-identical
379 /// results through the public seam.
380 #[test]
381 fn public_dispatch_canonical_and_alias_are_byte_equivalent() {
382 let preview_cases = [
383 "/preview-request json",
384 "/preview-request json --prompt keep the bytes",
385 "/preview-request base-prompt",
386 ];
387 for command in preview_cases {
388 let canonical = {
389 let mut canonical_harness = DiagnosticsHarness::new();
390 execute(command, &mut canonical_harness.app)
391 };
392 for alias in ["dryrun", "preview_request"] {
393 let aliased = command.replacen("preview-request", alias, 1);
394 let mut alias_harness = DiagnosticsHarness::new();
395 let aliased_result = execute(&aliased, &mut alias_harness.app);
396 assert_eq!(
397 render(&canonical),
398 render(&aliased_result),
399 "{aliased} must match {command}"
400 );
401 }
402 }
403
404 // /tools and /tool-studio share the prepared-snapshot payload.
405 let canonical = {
406 let mut canonical_harness = DiagnosticsHarness::new();
407 canonical_harness.app.session.last_tool_request_snapshot = Some(snapshot());
408 execute("/tools json", &mut canonical_harness.app)
409 };
410 let mut alias_harness = DiagnosticsHarness::new();
411 alias_harness.app.session.last_tool_request_snapshot = Some(snapshot());
412 let aliased = execute("/tool-studio json", &mut alias_harness.app);
413 assert_eq!(render(&canonical), render(&aliased));
414
415 // /system and /xitong share the exact message.
416 let canonical = {
417 let mut canonical_harness = DiagnosticsHarness::new();
418 canonical_harness.app.system_prompt =
419 Some(codewhale_models::SystemPrompt::Text("aliased".to_string()));
420 execute("/system", &mut canonical_harness.app)
421 };
422 let mut alias_harness = DiagnosticsHarness::new();
423 alias_harness.app.system_prompt =
424 Some(codewhale_models::SystemPrompt::Text("aliased".to_string()));
425 let aliased = execute("/xitong", &mut alias_harness.app);
426 assert_eq!(render(&canonical), render(&aliased));
427
428 // /context and /ctx share the bare inspector action.
429 let canonical = {
430 let mut canonical_harness = DiagnosticsHarness::new();
431 execute("/context", &mut canonical_harness.app)
432 };
433 let mut alias_harness = DiagnosticsHarness::new();
434 let aliased = execute("/ctx", &mut alias_harness.app);
435 assert!(matches!(
436 canonical.action,
437 Some(AppAction::OpenContextInspector)
438 ));
439 assert_eq!(render(&canonical), render(&aliased));
440 }
441
442 /// `/preview-request` remains a pure action-only leaf through the public
443 /// dispatch path; no prompt, route or provider state is read.
444 #[test]
445 fn preview_request_remains_the_pure_registration() {
446 // The public dispatcher still uses the staged function wrapper until
447 // Phase 6 wires the portable registrations. Even here preview creates no
448 // facet bundle and parses the action without provider/session state.
449 let mut harness = DiagnosticsHarness::new();
450 harness.app.api_provider = ProviderKind::Ollama;
451 let result = execute("/preview-request", &mut harness.app);
452 assert!(matches!(
453 result.action,
454 Some(AppAction::PreviewOutboundRequest { .. })
455 ));
456 }
457
458 fn snapshot() -> codewhale_engine::tool_inspection::ToolInspectionSnapshot {
459 codewhale_engine::tool_inspection::ToolInspectionSnapshot::from_prepared_request(
460 "turn-1",
461 2,
462 Some(&[tool("read_file"), tool("write_file")]),
463 )
464 }
465
466 fn tool(name: &str) -> codewhale_models::Tool {
467 codewhale_models::Tool {
468 tool_type: Some("function".to_string()),
469 name: name.to_string(),
470 description: format!("{name} test tool"),
471 input_schema: serde_json::json!({
472 "type": "object",
473 "properties": {"path": {"type": "string"}}
474 }),
475 allowed_callers: None,
476 defer_loading: Some(false),
477 input_examples: None,
478 strict: Some(true),
479 cache_control: None,
480 }
481 }
482
482 lines RUST