返回 CodeWhale
mod.rs
根目录 / crates / tui / src / commands / mod.rs
1 //! Slash command registry and dispatch system
2 //!
3 //! This module provides a modular command system inspired by Codex-rs.
4 //! Commands are organized by category and dispatched through a central strategy
5 //! registry. Built-in handlers live in group-owned areas under [`groups`]; this
6 //! module keeps registry construction, user-command precedence, and the
7 //! fall-through behaviour.
8
9 pub(crate) mod background_host;
10 mod builtin_execution;
11 mod config_group;
12 mod config_host;
13 mod config_main_host;
14 mod config_main_import_host;
15 #[cfg(test)]
16 mod config_policy_host;
17 pub(crate) mod contract;
18 pub(crate) use contract::from_command_mode;
19 #[cfg(test)]
20 mod core_copy_host_tests;
21 mod core_navigation_host;
22 #[cfg(test)]
23 mod core_navigation_host_tests;
24 pub mod discovery;
25 mod fleet_host;
26 pub(crate) mod groups;
27 #[cfg(test)]
28 mod model_setup_host_tests;
29 #[cfg(test)]
30 mod workflow_host_tests;
31
32 // FEAT-025 host services for the session-export slice: the shared recovery
33 // writer and the protected export-destination resolver/writer. Declared at the
34 // `commands` root so they stay outside `groups/session`, which FEAT-043 moves
35 // to `codewhale-commands`.
36 mod session_export_host;
37 pub mod traits;
38 pub mod user_commands;
39 pub mod user_registry;
40
41 #[cfg(test)]
42 #[path = "epic_dispatch_acceptance.rs"]
43 mod epic_dispatch_acceptance;
44
45 // Extension slash commands through the real command table and `App` dispatch;
46 // they cannot live in `extension_host`, a runtime module that may not depend
47 // on this one.
48 #[cfg(test)]
49 mod extension_host_tests;
50
51 #[cfg(test)]
52 #[path = "epic_discovery_acceptance.rs"]
53 mod epic_discovery_acceptance;
54
55 // TUI-hosted session acceptance and persistence regressions deliberately stay
56 // outside `groups/session`, which FEAT-043 moves to `codewhale-commands`.
57 #[cfg(all(test, feature = "long-running-tests"))]
58 mod session_acceptance;
59 #[cfg(test)]
60 mod session_control_regression_tests;
61 #[cfg(test)]
62 mod session_export_regression_tests;
63 #[cfg(test)]
64 mod session_structcopy_host_tests;
65 #[cfg(test)]
66 mod session_structcopy_regression_tests;
67 // FEAT-025 Phase 5: public command-surface parity lives at the `commands` root
68 // for the same extraction reason as the host regressions above.
69 #[cfg(test)]
70 mod session_export_surface_tests;
71 // FEAT-025 audit hardening: shared host-bound test support for both export
72 // test suites (timestamp normalisation and the exhaustive envelope check).
73 #[cfg(test)]
74 mod session_export_test_support;
75 #[cfg(test)]
76 mod session_lifecycle_regression_tests;
77 #[cfg(test)]
78 pub(crate) use session_lifecycle_regression_tests::acknowledge_new_session;
79
80 use std::sync::OnceLock;
81
82 pub(crate) use config_main_host::{set_workspace_trust, trust_change_note};
83 pub(crate) use contract::constitution::open_manager as open_constitution_manager;
84 pub(crate) use contract::debug_operations::{
85 plan_undo_range, restore_undo_range, undo_range_input,
86 };
87
88 /// Stage a rollback of the last exchange for the UI to apply, or `None` when
89 /// there is no user message to roll back. Nothing is mutated here.
90 pub(crate) fn staged_conversation_undo(
91 app: &mut crate::tui::app::App,
92 ) -> Option<codewhale_command_contract::facets::SessionSyncPayload> {
93 let undone = contract::debug_operations::undo_conversation_for_engine(app);
94 (undone.removed > 0).then_some(undone.sync)
95 }
96 pub use traits::CommandInfo;
97
98 // Long-standing public paths that predate the group layout.
99 /// `/fleet add` and the picker's ⇧F share these gates; the UI applies them
100 /// against the live `Config`.
101 pub(crate) use fleet_host::{fleet_catalog_rejection, fleet_provider_rejection};
102 pub(crate) use groups::memory::{notes_path, read_notes};
103 pub use groups::project::share;
104
105 // Voice capture plumbing shared with the hotbar and the UI event loop.
106 #[path = "core_navigation_voice_host.rs"]
107 pub mod voice;
108
109 #[cfg(test)]
110 mod debug_diagnostics_baseline_tests;
111 // Host fixtures for the eight diagnostics commands live outside the movable
112 // debug group; CW-SLICE selects them together with the frozen baseline tests.
113 #[cfg(test)]
114 mod debug_diagnostics_host_tests;
115 #[cfg(test)]
116 mod debug_diagnostics_regression_tests;
117 #[cfg(test)]
118 mod debug_diagnostics_surface_tests;
119 #[cfg(test)]
120 mod debug_diagnostics_test_support;
121
122 #[cfg(test)]
123 mod debug_change_host_tests;
124 mod debug_group;
125 #[cfg(test)]
126 mod debug_mutation_host_tests;
127 mod session_group;
128 mod session_reset;
129
130 use crate::tui::app::{App, AppAction};
131 use codewhale_config::AppMode;
132
133 /// Shared result shape; host actions remain consumed by the existing event loop.
134 pub type CommandResult = codewhale_command_contract::outcome::CommandResult<AppAction>;
135
136 static REGISTRY: OnceLock<traits::CommandRegistry> = OnceLock::new();
137
138 fn build_registry() -> traits::CommandRegistry {
139 let mut registry = traits::CommandRegistry::empty();
140 for &group in groups::all_command_groups() {
141 registry.register_group(group);
142 }
143 #[cfg(test)]
144 {
145 registry.register_test_only(feat015_ctx_command());
146 }
147 registry
148 }
149
150 /// FEAT-015 test-only contextual command (D6).
151 ///
152 /// Registered into the global registry only in test builds; the production
153 /// registry is untouched. The command implements the portable contract
154 /// `RegisterCommand` shape, and its handler cannot name concrete `App`; the
155 /// TUI bridge resolves metadata and dispatches it through public `execute()`.
156 #[cfg(test)]
157 struct Feat015TestCommand;
158
159 #[cfg(test)]
160 impl codewhale_command_contract::metadata::RegisterCommand<CommandResult> for Feat015TestCommand {
161 fn info() -> &'static codewhale_command_contract::metadata::CommandInfo {
162 static INFO: codewhale_command_contract::metadata::CommandInfo =
163 codewhale_command_contract::metadata::CommandInfo {
164 name: "feat015ctx",
165 aliases: &[],
166 usage: "/feat015ctx",
167 description_key: "cmd_workspace_description",
168 };
169 &INFO
170 }
171
172 fn handler() -> codewhale_command_contract::handler::CommandHandler<CommandResult> {
173 codewhale_command_contract::handler::CommandHandler::Contextual {
174 capabilities: codewhale_command_contract::handler::CommandCapabilities::WORKSPACE
175 .union(codewhale_command_contract::handler::CommandCapabilities::MODE_POLICY)
176 .union(codewhale_command_contract::handler::CommandCapabilities::COST),
177 handler: feat015_contextual,
178 }
179 }
180 }
181
182 /// Test-only contextual handler: reads workspace, mode, and currency facets
183 /// through the envelope and returns the host-selected result type. It has no
184 /// concrete `App` parameter or TUI state in its input surface.
185 #[cfg(test)]
186 fn feat015_contextual(
187 contexts: codewhale_command_contract::handler::CommandContexts<'_>,
188 arg: Option<&str>,
189 ) -> CommandResult {
190 use codewhale_command_contract::handler::ContextParts;
191 let parts: ContextParts<'_> = contexts.into_parts();
192 let Some(workspace) = parts.workspace else {
193 return CommandResult::error("Command capability unavailable: workspace");
194 };
195 let Some(mode_policy) = parts.mode_policy else {
196 return CommandResult::error("Command capability unavailable: mode-policy");
197 };
198 let Some(cost) = parts.cost else {
199 return CommandResult::error("Command capability unavailable: cost");
200 };
201 let workspace = workspace.workspace();
202 let mode = mode_policy.mode();
203 let currency = cost.display_currency();
204 let normalized = arg.unwrap_or("");
205 CommandResult::message(format!(
206 "feat015ctx workspace={} mode={:?} currency={:?} arg={}",
207 workspace.display(),
208 mode,
209 currency,
210 normalized
211 ))
212 }
213
214 #[cfg(test)]
215 static FEAT015_CTX: OnceLock<&'static traits::ContextualCommand> = OnceLock::new();
216
217 #[cfg(test)]
218 fn feat015_ctx_command() -> &'static traits::ContextualCommand {
219 FEAT015_CTX.get_or_init(|| {
220 Box::leak(Box::new(
221 traits::ContextualCommand::from_contract::<Feat015TestCommand>()
222 .expect("FEAT-015 portable registration must bridge into the TUI registry"),
223 ))
224 })
225 }
226
227 pub fn registry() -> &'static traits::CommandRegistry {
228 REGISTRY.get_or_init(build_registry)
229 }
230
231 /// The built-in command table as the extension host asks about it: the one
232 /// read-only metadata snapshot and built-in collision check. The
233 /// composition root installs it at startup (`lib.rs`), so the runtime-side host
234 /// never depends on this module.
235 pub(crate) struct CommandTable;
236
237 impl codewhale_engine::command_catalog::CommandCatalog for CommandTable {
238 fn answers_to(&self, name: &str) -> bool {
239 // `jihua` and `zidong` are mode aliases, and `pet` is the former name
240 // of `/whale`; the dispatcher answers them ahead of the registry.
241 matches!(name, "jihua" | "pet") || registry().get(name).is_some()
242 }
243
244 fn builtins(&self) -> Vec<codewhale_engine::command_catalog::BuiltinCommand> {
245 command_infos()
246 .into_iter()
247 .map(|info| codewhale_engine::command_catalog::BuiltinCommand {
248 name: info.name.to_string(),
249 aliases: info
250 .aliases
251 .iter()
252 .map(|alias| (*alias).to_string())
253 .collect(),
254 usage: info.usage.to_string(),
255 description_id: info.description_id,
256 subcommands: info.subcommands().into_iter().map(str::to_string).collect(),
257 takes_arguments: user_registry::usage_describes_arguments(info.name, info.usage),
258 requires_argument: info.requires_argument(),
259 requires_required_argument: info.requires_required_argument(),
260 composer_wants_trailing_space: info.composer_wants_trailing_space(),
261 palette_runs_directly: info.palette_runs_directly(),
262 show_in_empty_discovery: info.show_in_empty_discovery(),
263 discovery: info.discovery(),
264 unlisted: info.is_unlisted(),
265 })
266 .collect()
267 }
268
269 fn serves_builtin(&self, name: &str) -> bool {
270 builtin_execution::serves_builtin(name)
271 }
272
273 fn execute_builtin(
274 &self,
275 name: &str,
276 args: Option<&str>,
277 host: &codewhale_engine::command_catalog::BuiltinCommandHostSnapshot,
278 ) -> Option<codewhale_engine::command_catalog::BuiltinCommandExecution> {
279 builtin_execution::execute_builtin(name, args, host)
280 }
281
282 fn user_commands(
283 &self,
284 workspace: &std::path::Path,
285 ) -> Vec<codewhale_engine::command_catalog::UserCommand> {
286 user_registry::with_registry_for_workspace(Some(workspace), user_registry_entries)
287 }
288
289 fn user_commands_with_plugins(
290 &self,
291 workspace: &std::path::Path,
292 plugins: &codewhale_plugins::PluginRegistry,
293 ) -> Vec<codewhale_engine::command_catalog::UserCommand> {
294 user_registry::with_registry_for_workspace_plugins(
295 Some(workspace),
296 plugins,
297 user_registry_entries,
298 )
299 }
300
301 fn expands_user_commands(&self) -> bool {
302 true
303 }
304
305 fn expand_user_command(
306 &self,
307 workspace: &std::path::Path,
308 plugins: &codewhale_plugins::PluginRegistry,
309 input: &str,
310 ) -> Option<Result<codewhale_engine::command_catalog::ExpandedUserCommand, String>> {
311 let found = user_registry::with_registry_for_workspace_plugins(
312 Some(workspace),
313 plugins,
314 |registry| user_registry::lookup(registry, input),
315 )?;
316 let (metadata, args) = match found {
317 Ok(found) => found,
318 Err(error) => return Some(Err(error)),
319 };
320 if metadata.extension.is_some() {
321 return None;
322 }
323 Some(
324 user_registry::expand_template(&metadata, &args).map(|message| {
325 codewhale_engine::command_catalog::ExpandedUserCommand {
326 plugin_id: metadata
327 .plugin_authority
328 .as_ref()
329 .map(|authority| authority.plugin_id.as_str().to_string()),
330 name: metadata.name,
331 message,
332 allowed_tools: metadata.allowed_tools,
333 }
334 }),
335 )
336 }
337 }
338
339 fn user_registry_entries(
340 registry: &user_registry::UserCommandRegistry,
341 ) -> Vec<codewhale_engine::command_catalog::UserCommand> {
342 let mut bindings = std::collections::HashMap::<String, Vec<String>>::new();
343 for info in command_infos() {
344 for spelling in std::iter::once(info.name).chain(info.aliases.iter().copied()) {
345 if let Some(command) = registry.get(spelling) {
346 bindings
347 .entry(command.name.clone())
348 .or_default()
349 .push(spelling.to_string());
350 }
351 }
352 }
353 registry
354 .iter()
355 .map(|metadata| codewhale_engine::command_catalog::UserCommand {
356 name: metadata.name.clone(),
357 aliases: metadata.aliases.clone(),
358 description: metadata.description.clone(),
359 usage: metadata.display_usage().map(str::to_string),
360 takes_arguments: metadata.takes_arguments(),
361 hidden: metadata.hidden,
362 extension: metadata.extension.is_some(),
363 plugin_id: metadata
364 .plugin_authority
365 .as_ref()
366 .map(|authority| authority.plugin_id.as_str().to_string()),
367 workspace_sourced: metadata.workspace_sourced,
368 builtin_bindings: bindings.remove(&metadata.name).unwrap_or_default(),
369 })
370 .collect()
371 }
372
373 pub fn command_infos() -> Vec<&'static CommandInfo> {
374 let mut infos = registry().infos();
375 if !crate::tui::account_login::ACCOUNT_SIGN_IN_ENABLED {
376 infos.retain(|info| info.name != "login");
377 }
378 infos
379 }
380
381 pub fn get_command_info(name: &str) -> Option<&'static CommandInfo> {
382 registry().get_info(name)
383 }
384
385 /// Execute a slash command with its captured active configuration.
386 pub fn execute_with_config(
387 cmd: &str,
388 app: &mut App,
389 config: &codewhale_runtime::config::Config,
390 ) -> CommandResult {
391 execute_in_context(cmd, app, Some(config))
392 }
393
394 /// Legacy fixture entry; it cannot authorize a model route change.
395 #[cfg(test)]
396 pub fn execute(cmd: &str, app: &mut App) -> CommandResult {
397 execute_in_context(cmd, app, None)
398 }
399
400 pub(crate) fn pending_session_control_command(cmd: &str) -> bool {
401 let mut parts = cmd.trim().splitn(2, char::is_whitespace);
402 let command = parts
403 .next()
404 .unwrap_or_default()
405 .trim_start_matches('/')
406 .to_ascii_lowercase();
407 let Some(command) = registry().get(&command) else {
408 return false;
409 };
410 let arg = parts.next().unwrap_or_default().trim();
411 let verb = arg.split_whitespace().next().unwrap_or_default();
412 match command.info().name {
413 "exit" => true,
414 "agent" | "workflow" => matches!(verb, "cancel" | "stop" | "abort"),
415 "task" => verb.eq_ignore_ascii_case("cancel") || verb.eq_ignore_ascii_case("stop"),
416 "jobs" => matches!(
417 verb.to_ascii_lowercase().as_str(),
418 "cancel" | "kill" | "stop" | "cancel-all" | "kill-all" | "stop-all"
419 ),
420 "automation" => verb.eq_ignore_ascii_case("pause"),
421 "rc" => arg == "stop",
422 "goal" => matches!(arg, "pause" | "paused"),
423 "advisor" => matches!(arg, "off" | "disable" | "no" | "0" | "false"),
424 _ => false,
425 }
426 }
427
428 fn execute_in_context(
429 cmd: &str,
430 app: &mut App,
431 config: Option<&codewhale_runtime::config::Config>,
432 ) -> CommandResult {
433 if app.pending_fresh_session.is_some() && !pending_session_control_command(cmd) {
434 return CommandResult::error(
435 "A new session is awaiting Engine confirmation; the current draft and transcript are preserved.",
436 );
437 }
438 // Keep the command's raw remainder available for commands whose payload is
439 // byte-sensitive. Most slash commands intentionally receive a normalized
440 // argument below; `/preview-request --prompt`, however, must describe the
441 // exact prompt the send path would receive, including trailing whitespace
442 // and newlines.
443 let dispatch_input = cmd.trim_start();
444 let command_token_end = dispatch_input
445 .find(char::is_whitespace)
446 .unwrap_or(dispatch_input.len());
447 let raw_remainder = &dispatch_input[command_token_end..];
448 let trimmed = cmd.trim();
449
450 // `$skillname` is a backward-compatible alias for `/skill skillname`.
451 // Resolve it early so skills can be loaded with the `$` prefix.
452 if let Some(skill_input) = trimmed.strip_prefix('$') {
453 let skill_input = skill_input.trim_start();
454 if skill_input.is_empty() {
455 return CommandResult::error(
456 "Type a skill name after $. For example: $getting-started",
457 );
458 }
459 let parts: Vec<&str> = skill_input.splitn(2, char::is_whitespace).collect();
460 let skill_name = parts.first().copied().unwrap_or("");
461 let arg = parts
462 .get(1)
463 .map(|value| value.trim())
464 .filter(|value| !value.is_empty());
465 if let Some(result) = run_skill_by_name(app, config, skill_name, arg) {
466 return result;
467 }
468 return CommandResult::error(format!(
469 "Unknown skill: ${skill_name}. Type /skills to see installed skills."
470 ));
471 }
472
473 let parts: Vec<&str> = trimmed.splitn(2, char::is_whitespace).collect();
474 let command = parts
475 .first()
476 .copied()
477 .unwrap_or_default()
478 .trim_start_matches('/')
479 .to_ascii_lowercase();
480 let arg = parts
481 .get(1)
482 .map(|value| value.trim())
483 .filter(|value| !value.is_empty());
484
485 // Check user-defined commands FIRST so they can override built-ins.
486 // Workspace (repository) commands load only in a trusted workspace and
487 // never under a protected built-in such as /trust or /undo — the
488 // registry drops those at load.
489 if app.pending_fresh_session.is_none()
490 && let Some(result) = user_registry::try_dispatch(app, trimmed)
491 {
492 return result;
493 }
494
495 // Permanent backward-compatible mode aliases. They select a fixed mode
496 // rather than the canonical `/mode` behavior, so they still dispatch
497 // before registry lookup. Ordinary compatibility aliases belong in their
498 // command's `CommandInfo` metadata.
499 if command == "jihua" {
500 return config_group::mode_alias(app, "plan");
501 }
502 let command = if command == "pet" {
503 "whale".to_string()
504 } else {
505 command
506 };
507
508 if let Some(command_object) = registry().get(command.as_str()) {
509 let command_arg = if matches!(command_object.info().name, "preview-request" | "plugin") {
510 Some(raw_remainder)
511 } else {
512 arg
513 };
514 if let Some(handler) = command_object.contextual_handler() {
515 return match handler {
516 codewhale_command_contract::handler::CommandHandler::Pure(pure_fn) => {
517 pure_fn(command_arg)
518 }
519 codewhale_command_contract::handler::CommandHandler::Contextual {
520 capabilities,
521 handler: contextual,
522 } => {
523 let mut background = background_host::host(app, capabilities);
524 let mut bundle = app.command_contexts_with_config(config);
525 let mut contexts = bundle.contexts(capabilities);
526 if let Some(background) = background.as_mut() {
527 contexts = contexts.with_background(background);
528 }
529 contextual(contexts, command_arg)
530 }
531 };
532 }
533 return CommandResult::error("command has no executable handler");
534 }
535
536 match command.as_str() {
537 // Permanent legacy migration hints. These are deliberately excluded
538 // from registry/autocomplete and only appear when users type old names.
539 "set" => CommandResult::error(
540 "The /set command was retired. Use /config to edit settings and /settings to inspect current values.",
541 ),
542 "deepseek" => {
543 CommandResult::error("The /deepseek command was renamed. Use /links (aliases: /api).")
544 }
545 "doctor" => CommandResult::error(
546 "The /doctor command is a CLI diagnostic. Run `codewhale doctor` or `codewhale doctor --json`; use `/setup` in the TUI for readiness and verification.",
547 ),
548
549 _ => {
550 // Third source: skills (lowest precedence after native and user-config).
551 // Try to run a skill whose name matches the command.
552 if let Some(result) = run_skill_by_name(app, config, command.as_str(), arg) {
553 return result;
554 }
555 let suggestions = user_registry::with_registry_for_app(app, |user_commands| {
556 suggest_command_names(command.as_str(), 3, user_commands)
557 });
558 if suggestions.is_empty() {
559 CommandResult::error(format!(
560 "Unknown command: /{command}. Type /help for available commands."
561 ))
562 } else {
563 let list = suggestions
564 .into_iter()
565 .map(|name| format!("/{name}"))
566 .collect::<Vec<_>>()
567 .join(", ");
568 CommandResult::error(format!(
569 "Unknown command: /{command}. Did you mean: {list}? Type /help for available commands."
570 ))
571 }
572 }
573 }
574 }
575
576 fn run_skill_by_name(
577 app: &mut App,
578 config: Option<&codewhale_runtime::config::Config>,
579 name: &str,
580 arg: Option<&str>,
581 ) -> Option<CommandResult> {
582 let mut bundle = app.command_contexts_with_config(config);
583 let contexts =
584 bundle.contexts(codewhale_command_contract::handler::CommandCapabilities::SKILL_GROUP);
585 let mut parts = contexts.into_parts();
586 let skill_group = parts.skill_group.as_deref_mut()?;
587 groups::skills::try_activate_skill_portable(skill_group, name, arg)
588 }
589
590 /// Update a configuration value programmatically (used by interactive UI views).
591 pub fn set_config_value(app: &mut App, key: &str, value: &str, persist: bool) -> CommandResult {
592 let locale = app.ui_locale;
593 config_host::render_config_reply(
594 config_main_host::set_config_value(app, key, value, persist),
595 locale,
596 )
597 }
598
599 /// Switch the interaction mode (plan / work / operate).
600 pub fn switch_mode(app: &mut App, mode: AppMode) -> String {
601 config_main_host::switch_mode(app, mode)
602 }
603
604 fn suggest_command_names(
605 input: &str,
606 limit: usize,
607 user_commands: &user_registry::UserCommandRegistry,
608 ) -> Vec<String> {
609 let query = input.trim().to_ascii_lowercase();
610 if query.is_empty() || limit == 0 {
611 return Vec::new();
612 }
613
614 let mut scored: Vec<(u8, usize, String)> = Vec::new();
615 for command in registry().infos() {
616 // A user command can shadow a built-in canonical name or just one of
617 // its aliases. Score only the built-in spellings that still dispatch
618 // to the built-in so suggestions never advertise different behavior.
619 if user_commands.get(command.name).is_some() {
620 continue;
621 }
622 let candidates = std::iter::once(command.name).chain(
623 command
624 .aliases
625 .iter()
626 .copied()
627 .filter(|alias| user_commands.get(alias).is_none()),
628 );
629 if let Some((rank, distance)) =
630 codewhale_config::suggest::best_suggestion_score(&query, candidates)
631 {
632 scored.push((rank, distance, command.name.to_string()));
633 }
634 }
635
636 for command in user_commands.iter().filter(|command| !command.hidden) {
637 let candidates = std::iter::once(command.name.as_str()).chain(
638 command.aliases.iter().map(String::as_str).filter(|alias| {
639 user_commands
640 .get(alias)
641 .is_some_and(|resolved| resolved.name == command.name)
642 }),
643 );
644 if let Some((rank, distance)) =
645 codewhale_config::suggest::best_suggestion_score(&query, candidates)
646 {
647 scored.push((rank, distance, command.name.clone()));
648 }
649 }
650
651 scored.sort_by(|a, b| {
652 a.0.cmp(&b.0)
653 .then_with(|| a.1.cmp(&b.1))
654 .then_with(|| a.2.cmp(&b.2))
655 });
656 scored
657 .into_iter()
658 .take(limit)
659 .map(|(_, _, name)| name)
660 .collect()
661 }
662
663 #[cfg(test)]
664 mod tests {
665 use super::*;
666 use crate::tui::app::{App, AppAction, TuiOptions};
667 use crate::tui::work_surface::{RailPanel, WorkSurfacePlacement};
668 use codewhale_config::ProviderKind;
669 use codewhale_engine::tools::plan::{PlanItemArg, StepStatus, UpdatePlanArgs};
670 use codewhale_engine::tools::todo::TodoStatus;
671 use codewhale_localization::{Locale, MessageId};
672 use codewhale_runtime::config::Config;
673 use std::path::{Path, PathBuf};
674 use tempfile::tempdir;
675
676 fn is_palette_safe_command_name(name: &str) -> bool {
677 let bytes = name.as_bytes();
678 !bytes.is_empty()
679 && bytes.first().is_some_and(u8::is_ascii_alphanumeric)
680 && bytes.last().is_some_and(u8::is_ascii_alphanumeric)
681 && bytes
682 .iter()
683 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-')
684 && !name.contains("--")
685 }
686
687 fn create_test_app() -> App {
688 let options = TuiOptions {
689 ..crate::tui::test_support::test_tui_options(PathBuf::from("."))
690 };
691 App::new(options, &Config::default())
692 }
693
694 #[test]
695 fn user_registry_module_is_compiled() {
696 super::user_registry::reload(None);
697 let registry = super::user_registry::current_registry();
698 assert!(registry.is_valid());
699 }
700
701 #[test]
702 fn preview_request_dispatch_preserves_prompt_edge_bytes() {
703 let mut app = create_test_app();
704 let result = execute("/preview-request --prompt lead\ntrail ", &mut app);
705
706 assert!(!result.is_error, "{result:?}");
707 assert!(matches!(
708 result.action,
709 Some(AppAction::PreviewOutboundRequest {
710 json: false,
711 base_prompt_only: false,
712 hypothetical_prompt,
713 }) if hypothetical_prompt.as_deref() == Some(" lead\ntrail ")
714 ));
715 }
716
717 #[test]
718 fn user_command_shadows_builtin_before_group_dispatch() {
719 let temp = tempdir().unwrap();
720 crate::test_support::trust_workspace(temp.path());
721 let commands_dir = temp.path().join(".codewhale").join("commands");
722 std::fs::create_dir_all(&commands_dir).unwrap();
723 std::fs::write(
724 commands_dir.join("help.md"),
725 "---\ndescription: User help\n---\nuser help $ARGUMENTS",
726 )
727 .unwrap();
728
729 let mut app = crate::tui::test_support::test_app_with_options(
730 crate::tui::test_support::test_tui_options(temp.path()),
731 );
732 super::user_registry::reload(Some(temp.path()));
733
734 let result = execute("/help now", &mut app);
735 assert!(!result.is_error);
736 match result.action {
737 Some(AppAction::SendMessage(message)) => assert_eq!(message, "user help now"),
738 other => panic!("expected user command SendMessage action, got {other:?}"),
739 }
740 std::fs::write(commands_dir.join("voice.md"), "user voice").unwrap();
741 super::user_registry::reload(Some(temp.path()));
742 assert!(
743 matches!(execute("/voice", &mut app).action, Some(AppAction::SendMessage(message)) if message == "user voice")
744 );
745 app.voice_enabled = true;
746 let shortcut = crate::commands::voice::voice(&mut app);
747 assert!(!shortcut.is_error && shortcut.action.is_none());
748 assert!(
749 !app.voice_enabled,
750 "builtin voice shortcut must not dispatch a shadowing user command"
751 );
752 let missing =
753 super::core_navigation_host::dispatch(&mut app, "__missing_navigation_builtin__", None);
754 assert!(missing.is_error && missing.action.is_none());
755 assert!(!app.voice_enabled);
756 }
757
758 #[test]
759 fn removed_user_command_reloads_and_falls_back_to_builtin() {
760 let temp = tempdir().unwrap();
761 crate::test_support::trust_workspace(temp.path());
762 let commands_dir = temp.path().join(".codewhale").join("commands");
763 std::fs::create_dir_all(&commands_dir).unwrap();
764 let command_path = commands_dir.join("help.md");
765 std::fs::write(&command_path, "user help").unwrap();
766
767 let mut app = crate::tui::test_support::test_app_with_options(
768 crate::tui::test_support::test_tui_options(temp.path()),
769 );
770 super::user_registry::reload(Some(temp.path()));
771 assert!(matches!(
772 execute("/help config", &mut app).action,
773 Some(AppAction::SendMessage(_))
774 ));
775
776 std::fs::remove_file(command_path).unwrap();
777 super::user_registry::reload(Some(temp.path()));
778 let result = execute("/help config", &mut app);
779 assert!(!result.is_error);
780 assert!(
781 result
782 .message
783 .as_deref()
784 .is_some_and(|message| message.contains("config")),
785 "built-in /help should handle the command"
786 );
787 assert!(result.action.is_none());
788 }
789
790 #[test]
791 fn command_registry_contains_config_and_links_but_not_set_or_deepseek() {
792 assert!(command_infos().iter().any(|cmd| cmd.name == "config"));
793 assert!(get_command_info("experiments").is_none());
794 assert!(get_command_info("experimental").is_none());
795 let rail = command_infos()
796 .into_iter()
797 .find(|cmd| cmd.name == "workbar")
798 .expect("workbar command should exist");
799 assert_eq!(rail.aliases, &["rail", "sidebar"]);
800 assert_eq!(rail.description_id, MessageId::CmdSidebarDescription);
801 assert!(rail.description_for(Locale::En).contains("workbar"));
802 assert!(rail.subcommands().contains(&"terminal"));
803 assert!(command_infos().iter().any(|cmd| cmd.name == "links"));
804 let hf = command_infos()
805 .into_iter()
806 .find(|cmd| cmd.name == "hf")
807 .expect("hf command should exist");
808 assert_eq!(hf.aliases, &["huggingface"]);
809 assert_eq!(hf.description_id, MessageId::CmdHfDescription);
810 assert!(hf.description_for(Locale::En).contains("Hugging Face"));
811 assert!(command_infos().iter().any(|cmd| cmd.name == "memory"));
812 assert!(!command_infos().iter().any(|cmd| cmd.name == "set"));
813 assert!(!command_infos().iter().any(|cmd| cmd.name == "deepseek"));
814 }
815
816 #[test]
817 fn whale_command_is_registered_and_the_workbar_no_longer_advertises_watch() {
818 let whale = command_infos()
819 .into_iter()
820 .find(|cmd| cmd.name == "whale")
821 .expect("whale command should exist");
822 assert_eq!(whale.description_id, MessageId::CmdPetDescription);
823 assert!(whale.usage.starts_with("/whale"));
824 for verb in ["full", "still", "name", "color"] {
825 assert!(whale.subcommands().contains(&verb), "{verb}");
826 }
827 assert!(get_command_info("pet").is_none(), "/pet is unlisted");
828 let rail = command_infos()
829 .into_iter()
830 .find(|cmd| cmd.name == "workbar")
831 .expect("workbar command should exist");
832 assert!(!rail.usage.contains("watch"), "{}", rail.usage);
833 }
834
835 #[test]
836 fn links_command_has_api_and_lianjie_aliases() {
837 let links = command_infos()
838 .into_iter()
839 .find(|cmd| cmd.name == "links")
840 .expect("links command should exist");
841 assert_eq!(links.aliases, &["api", "lianjie"]);
842 }
843
844 #[test]
845 fn dashboard_command_opens_agent_board_with_board_alias() {
846 let dashboard = command_infos()
847 .into_iter()
848 .find(|cmd| cmd.name == "dashboard")
849 .expect("dashboard command should exist");
850 assert_eq!(dashboard.aliases, &["board"]);
851 assert_eq!(dashboard.usage, "/dashboard");
852 assert_eq!(dashboard.description_id, MessageId::CmdDashboardDescription);
853
854 let mut app = create_test_app();
855 for cmd in ["/dashboard", "/board"] {
856 let result = execute(cmd, &mut app);
857 assert!(!result.is_error, "{cmd}: {result:?}");
858 assert!(matches!(result.action, Some(AppAction::OpenAgentBoard)));
859 }
860 }
861
862 #[test]
863 fn transcript_command_is_discoverable_and_opens_live_overlay() {
864 let transcript = command_infos()
865 .into_iter()
866 .find(|cmd| cmd.name == "transcript")
867 .expect("transcript command should exist");
868 assert_eq!(transcript.usage, "/transcript");
869 assert!(transcript.show_in_empty_discovery());
870
871 let mut app = create_test_app();
872 let result = execute("/transcript", &mut app);
873 assert!(!result.is_error);
874 assert!(matches!(result.action, Some(AppAction::OpenLiveTranscript)));
875 }
876
877 #[test]
878 fn hf_alias_dispatches_to_concepts_helper() {
879 let mut app = create_test_app();
880 let result = execute("/huggingface concepts", &mut app);
881 assert!(!result.is_error);
882 let message = result.message.expect("concepts message");
883 assert!(message.contains("Hugging Face provider route"));
884 assert!(message.contains("Hugging Face MCP"));
885 assert!(message.contains("Hub workflows"));
886 }
887
888 #[test]
889 fn login_slash_command_reports_status_and_key_opens_picker() {
890 let mut app = create_test_app();
891 let status = execute("/login status", &mut app);
892 assert!(!status.is_error);
893 let message = status.message.expect("login status");
894 assert!(message.contains("Codewhale login"), "{message}");
895 assert!(message.contains("Account:"), "{message}");
896 assert_eq!(
897 message.contains("codewhale login"),
898 crate::tui::account_login::ACCOUNT_SIGN_IN_ENABLED,
899 "{message}"
900 );
901 // No-brand invariant: the internal cloud-agent slot is not user
902 // surface, so status never names it or teaches a set-slot command.
903 assert!(!message.contains("Daytona"), "{message}");
904 assert!(!message.contains("set-slot"), "{message}");
905
906 assert_eq!(
907 execute("/login", &mut app).action,
908 Some(AppAction::StartAccountLogin)
909 );
910 assert_eq!(
911 execute("/login account", &mut app).action,
912 Some(AppAction::StartAccountLogin)
913 );
914 assert_eq!(
915 execute("/logout", &mut app).action,
916 Some(AppAction::StartAccountLogout)
917 );
918 let key = execute("/login key", &mut app);
919 assert!(!key.is_error);
920 assert_eq!(key.action, Some(AppAction::OpenProviderPicker));
921
922 let daytona = execute("/login daytona", &mut app);
923 assert!(daytona.is_error);
924 let err = daytona.message.expect("usage");
925 assert!(err.contains("Usage: /login [status|account|key]"), "{err}");
926 assert!(err.contains("/connect <provider>"), "{err}");
927
928 let unknown = execute("/login oauth", &mut app);
929 assert!(unknown.is_error);
930 let err = unknown.message.expect("usage");
931 assert!(err.contains("Usage: /login"), "{err}");
932
933 assert_eq!(
934 execute("/connect", &mut app).action,
935 Some(AppAction::OpenModelConnectionSetup)
936 );
937 let connect = execute("/connect nothing-enabled", &mut app);
938 assert!(connect.is_error);
939 let err = connect.message.expect("usage");
940 assert!(
941 err.contains("Usage: /connect [account|<provider>]"),
942 "{err}"
943 );
944 assert_eq!(
945 err.contains("`/login`"),
946 crate::tui::account_login::ACCOUNT_SIGN_IN_ENABLED,
947 "{err}"
948 );
949 assert!(execute("/disconnect", &mut app).is_error);
950 assert!(execute("/disconnect nothing-enabled", &mut app).is_error);
951 }
952
953 #[test]
954 fn xai_device_auth_slash_command_starts_login() {
955 let mut app = create_test_app();
956 let result = execute("/auth xai-device", &mut app);
957 assert!(!result.is_error);
958 assert!(matches!(
959 result.action,
960 Some(AppAction::StartXaiDeviceLogin)
961 ));
962 }
963
964 #[test]
965 fn chatgpt_auth_slash_command_starts_login() {
966 let mut app = create_test_app();
967 let result = execute("/auth chatgpt", &mut app);
968 assert!(!result.is_error);
969 assert!(matches!(
970 result.action,
971 Some(AppAction::StartChatgptPkceLogin)
972 ));
973 }
974
975 #[test]
976 fn chatgpt_revoke_slash_command_defers_to_the_event_loop() {
977 // The remote revoke is a blocking round trip; the command must hand it
978 // to the loop instead of doing it inline (#5784 review).
979 let mut app = create_test_app();
980 let result = execute("/auth chatgpt-revoke", &mut app);
981 assert!(!result.is_error);
982 assert!(matches!(result.action, Some(AppAction::StartChatgptRevoke)));
983 }
984
985 #[test]
986 fn rlm_slash_command_routes_to_persistent_tool_instruction() {
987 let mut app = create_test_app();
988 let result = execute("/rlm 2 inspect this long corpus", &mut app);
989 assert!(!result.is_error);
990 assert!(
991 result
992 .message
993 .as_deref()
994 .unwrap_or("")
995 .contains("persistent working context")
996 );
997 let Some(AppAction::SendMessage(message)) = result.action else {
998 panic!("expected SendMessage action");
999 };
1000 assert!(message.contains("`rlm` tool"));
1001 assert!(message.contains("`open` with `file_path` or `content`"));
1002 assert!(message.contains("`eval`"));
1003 assert!(message.contains("`close`"));
1004 assert!(!message.contains("`repl` block"));
1005 }
1006
1007 /// `/kernel` was briefly introduced by an in-flight change and rejected:
1008 /// the persistent working context is ordinary Agent behavior, not a
1009 /// control surface users have to learn.
1010 #[test]
1011 fn kernel_is_not_a_command() {
1012 let mut app = create_test_app();
1013 let result = execute("/kernel inspect the fresh corpus", &mut app);
1014 assert!(
1015 result.is_error,
1016 "/kernel must not resolve to a registered command"
1017 );
1018 }
1019
1020 #[test]
1021 fn agent_slash_command_routes_to_persistent_tool_instruction() {
1022 let mut app = create_test_app();
1023 let result = execute("/agent 0 inspect the parser", &mut app);
1024 assert!(!result.is_error);
1025 let Some(AppAction::SendMessage(message)) = result.action else {
1026 panic!("expected SendMessage action");
1027 };
1028 assert!(message.contains("`agent`"));
1029 assert!(message.contains("max_depth: 0"));
1030 }
1031
1032 #[test]
1033 fn relay_slash_command_routes_to_session_relay_instruction() {
1034 let mut app = create_test_app();
1035 app.goal.objective = Some("Unify the work surface".to_string());
1036 app.goal.token_budget = Some(12_000);
1037 {
1038 let mut todos = app.todos.try_lock().expect("todo lock");
1039 todos.add("inspect workspace".to_string(), TodoStatus::Completed);
1040 todos.add("patch relay command".to_string(), TodoStatus::InProgress);
1041 }
1042 {
1043 let mut plan = app.plan_state.try_lock().expect("plan lock");
1044 plan.update(UpdatePlanArgs {
1045 objective: Some("Keep relays grounded".to_string()),
1046 explanation: Some("RLM-style strategy".to_string()),
1047 sources_used: vec!["transcript context".to_string()],
1048 critical_files: vec!["crates/tui/src/commands/mod.rs".to_string()],
1049 constraints: vec!["Do not invent verification".to_string()],
1050 verification_plan: Some("Check relay prompt assertions".to_string()),
1051 handoff_packet: Some("Next thread should read the To-do list".to_string()),
1052 plan: vec![PlanItemArg {
1053 step: "keep To-do primary".to_string(),
1054 status: StepStatus::InProgress,
1055 }],
1056 ..UpdatePlanArgs::default()
1057 });
1058 }
1059
1060 let result = execute("/relay verify install", &mut app);
1061 assert!(!result.is_error);
1062 assert!(
1063 result
1064 .message
1065 .as_deref()
1066 .unwrap_or_default()
1067 .contains(codewhale_engine::prompts::HANDOFF_RELATIVE_PATH)
1068 );
1069 let Some(AppAction::SendMessage(message)) = result.action else {
1070 panic!("expected SendMessage action");
1071 };
1072 assert!(message.contains("session relay"));
1073 assert!(message.contains("接力"));
1074 // The relay is written where the next session reads it first.
1075 assert!(message.contains(&format!(
1076 "Write or update `{}`",
1077 codewhale_engine::prompts::HANDOFF_RELATIVE_PATH
1078 )));
1079 assert!(message.contains("# Session relay"));
1080 assert!(message.contains("Requested relay focus: verify install"));
1081 assert!(message.contains("Goal objective: Unify the work surface"));
1082 assert!(message.contains("Goal token budget: 12000"));
1083 // #3983: the relay artifact shows the same bounded To-do snapshot body
1084 // a forked agent is handed — byte for byte.
1085 let expected_body = codewhale_engine::todo_snapshot::todo_snapshot_body(
1086 &app.todos.try_lock().expect("todo lock").snapshot(),
1087 )
1088 .expect("canonical body");
1089 assert_eq!(
1090 expected_body,
1091 "To-do (50% settled)\n- [x] #1 inspect workspace\n- [~] #2 patch relay command"
1092 );
1093 assert!(
1094 message.contains(&expected_body),
1095 "relay must embed the canonical To-do body: {message}"
1096 );
1097 assert!(message.contains("Conversational strategy notes from update_plan"));
1098 assert!(message.contains("Objective: Keep relays grounded"));
1099 assert!(message.contains("Explanation: RLM-style strategy"));
1100 assert!(message.contains("Source: transcript context"));
1101 assert!(message.contains("Critical file: crates/tui/src/commands/mod.rs"));
1102 assert!(message.contains("Constraint: Do not invent verification"));
1103 assert!(message.contains("Verification plan: Check relay prompt assertions"));
1104 assert!(message.contains("Handoff packet: Next thread should read the To-do list"));
1105 assert!(message.contains("[in_progress] keep To-do primary"));
1106 assert!(
1107 !message.contains("Work checklist"),
1108 "relay copy should use To-do vocabulary: {message}"
1109 );
1110 }
1111
1112 /// #3983: `update_plan` is conversational strategy, not a To-do. A session
1113 /// with plan state and an empty To-do has no list to hand off, and the
1114 /// relay artifact must not manufacture one.
1115 #[test]
1116 fn relay_does_not_present_plan_only_state_as_work_state() {
1117 let mut app = create_test_app();
1118 {
1119 let mut plan = app.plan_state.try_lock().expect("plan lock");
1120 plan.update(UpdatePlanArgs {
1121 objective: Some("Ship the To-do seam".to_string()),
1122 plan: vec![PlanItemArg {
1123 step: "draft the renderer".to_string(),
1124 status: StepStatus::InProgress,
1125 }],
1126 ..UpdatePlanArgs::default()
1127 });
1128 }
1129
1130 let result = execute("/relay", &mut app);
1131 let Some(AppAction::SendMessage(message)) = result.action else {
1132 panic!("expected SendMessage action");
1133 };
1134
1135 assert!(
1136 !message.contains("Current To-do:"),
1137 "plan-only state must not render as a To-do: {message}"
1138 );
1139 assert!(
1140 !message.contains("To-do ("),
1141 "plan-only state must not synthesize a To-do list: {message}"
1142 );
1143 assert!(message.contains("Conversational strategy notes from update_plan"));
1144 }
1145
1146 /// #3983: a graph-backed update is authoritative immediately, even before
1147 /// the compatibility To-do projection is published to the UI.
1148 #[tokio::test]
1149 async fn relay_reads_same_turn_graph_backed_work_update() {
1150 use codewhale_engine::tools::spec::ToolSpec as _;
1151
1152 let mut app = create_test_app();
1153 let work = codewhale_engine::work_graph::new_shared_work_runtime(
1154 app.todos.clone(),
1155 app.plan_state.clone(),
1156 );
1157 app.runtime_services.work = Some(work.clone());
1158
1159 let mut context = codewhale_engine::tools::spec::ToolContext::new(app.workspace.clone());
1160 context.runtime.work = Some(work);
1161 codewhale_engine::tools::todo::TodoWriteTool::new(app.todos.clone())
1162 .execute(
1163 serde_json::json!({
1164 "todos": [{"content": "relay the staged graph", "status": "in_progress"}]
1165 }),
1166 &context,
1167 )
1168 .await
1169 .expect("graph-backed todo_write");
1170
1171 assert!(
1172 app.todos.lock().await.snapshot().is_empty(),
1173 "precondition: legacy projection has not published yet"
1174 );
1175
1176 let result = execute("/relay", &mut app);
1177 let Some(AppAction::SendMessage(message)) = result.action else {
1178 panic!("expected SendMessage action");
1179 };
1180 assert!(
1181 message.contains("[~] #1 relay the staged graph"),
1182 "{message}"
1183 );
1184 }
1185
1186 #[test]
1187 fn relay_command_has_bilingual_aliases() {
1188 let relay = command_infos()
1189 .into_iter()
1190 .find(|cmd| cmd.name == "relay")
1191 .expect("relay command should exist");
1192 assert_eq!(relay.aliases, &["batonpass", "接力"]);
1193 assert!(relay.description_for(Locale::ZhHans).contains("接力"));
1194 assert!(relay.description_for(Locale::ZhHant).contains("接力"));
1195
1196 let mut app = create_test_app();
1197 let result = execute("/接力 next hand", &mut app);
1198 assert!(!result.is_error);
1199 let Some(AppAction::SendMessage(message)) = result.action else {
1200 panic!("expected SendMessage action");
1201 };
1202 assert!(message.contains("Requested relay focus: next hand"));
1203 }
1204
1205 /// AT-008: No built-in command name or alias is registered twice,
1206 /// and no built-in alias collides with another command's canonical name.
1207 /// This test iterates every command from `command_infos()` (all 9 groups)
1208 /// and asserts uniqueness across the full set of names and aliases.
1209 #[test]
1210 fn command_registry_has_unique_names_and_aliases() {
1211 let mut names = std::collections::BTreeSet::new();
1212 for command in command_infos() {
1213 assert!(
1214 names.insert(command.name),
1215 "duplicate command name /{}",
1216 command.name
1217 );
1218 }
1219
1220 let mut aliases = std::collections::BTreeSet::new();
1221 for command in command_infos() {
1222 for alias in command.aliases {
1223 assert!(
1224 !names.contains(alias),
1225 "alias /{alias} collides with a command name"
1226 );
1227 assert!(aliases.insert(*alias), "duplicate command alias /{alias}");
1228 }
1229 }
1230 }
1231
1232 /// AT-009: Command ownership contract — top-level `commands/mod.rs` only
1233 /// registers groups (`groups::all_command_groups()`), each group owns its
1234 /// `commands()` list, and every command has valid metadata.
1235 ///
1236 /// Config and debug groups are documented permanent exceptions: they keep
1237 /// group-local `CommandInfo` statics and `dispatch()` in `mod.rs` rather
1238 /// than extracting every command into a focused module. This is accepted
1239 /// final structure per FEAT-008 §3.2.
1240 ///
1241 /// Enforcement strategy:
1242 /// - Exactly 9 source-verified groups (from `groups/mod.rs`)
1243 /// - Each group owns its commands() list
1244 /// - Config and debug exceptions verified within their specific groups by
1245 /// identifying the group through its first command ("config" and "tokens")
1246 /// - Not circular: the group-iterated command count is a consistency check;
1247 /// the primary enforcement is exact group count + per-group non-empty + valid metadata
1248 #[test]
1249 fn command_ownership_contract_is_enforced() {
1250 let groups = groups::all_command_groups();
1251
1252 // AT-009 primary: exactly 9 groups matching groups/mod.rs
1253 assert_eq!(
1254 groups.len(),
1255 9,
1256 "expected exactly 9 command groups (core, session, config, debug, \
1257 project, skills, memory, plugins, utility), got {}",
1258 groups.len()
1259 );
1260
1261 let mut total_commands = 0;
1262 let mut has_config = false;
1263 let mut has_debug = false;
1264 for &group in groups {
1265 let commands = group.commands();
1266 assert!(
1267 !commands.is_empty(),
1268 "each group must have at least one command"
1269 );
1270 for cmd in commands {
1271 let info = cmd.info();
1272 assert!(!info.name.is_empty(), "command name must not be empty");
1273 assert!(
1274 is_palette_safe_command_name(info.name),
1275 "/{} command names must be lowercase ASCII kebab-case",
1276 info.name
1277 );
1278 let usage_prefix = format!("/{}", info.name);
1279 assert!(
1280 info.usage.starts_with(&usage_prefix),
1281 "/{} usage must start with /{{name}}, got {:?}",
1282 info.name,
1283 info.usage
1284 );
1285 }
1286 total_commands += commands.len();
1287
1288 // Identify config and debug groups by their command content to
1289 // verify permanent-exception counts within the correct group.
1290 if commands.iter().any(|c| c.info().name == "config") {
1291 has_config = true;
1292 assert_eq!(
1293 commands.len(),
1294 18,
1295 "config group (group-local metadata exception) expected \
1296 exactly 18 commands, got {}",
1297 commands.len()
1298 );
1299 }
1300 if commands.iter().any(|c| c.info().name == "tokens") {
1301 has_debug = true;
1302 assert_eq!(
1303 commands.len(),
1304 14,
1305 "debug group (group-local metadata exception) expected \
1306 exactly 14 commands, got {}",
1307 commands.len()
1308 );
1309 }
1310 }
1311
1312 // Config and debug groups must be found and verified by content identity
1313 assert!(
1314 has_config,
1315 "config group not found (expected first command: /config)"
1316 );
1317 assert!(
1318 has_debug,
1319 "debug group not found (expected first command: /tokens)"
1320 );
1321
1322 // Consistency: group-iterated command count must match registry.
1323 // FEAT-015 registers one test-only contextual command (`/feat015ctx`)
1324 // under `#[cfg(test)]` to prove the dual-path seam (D6); it is not
1325 // part of any production group.
1326 let test_only_count = command_infos()
1327 .iter()
1328 .filter(|info| info.name == "feat015ctx")
1329 .count();
1330 let hidden_login = usize::from(!crate::tui::account_login::ACCOUNT_SIGN_IN_ENABLED);
1331 assert_eq!(
1332 total_commands + test_only_count,
1333 command_infos().len() + hidden_login,
1334 "group-iterated command count must match registry infos count"
1335 );
1336 }
1337
1338 #[test]
1339 fn command_groups_are_cached_once() {
1340 let first_groups = groups::all_command_groups();
1341 let second_groups = groups::all_command_groups();
1342 assert!(
1343 std::ptr::eq(first_groups.as_ptr(), second_groups.as_ptr()),
1344 "command group list should be cached"
1345 );
1346
1347 for &group in first_groups {
1348 let first_commands = group.commands();
1349 let second_commands = group.commands();
1350 assert!(
1351 std::ptr::eq(first_commands.as_ptr(), second_commands.as_ptr()),
1352 "command list should be cached per group"
1353 );
1354 }
1355 }
1356
1357 #[test]
1358 fn command_registry_metadata_is_complete_and_palette_safe() {
1359 for command in command_infos() {
1360 assert!(!command.name.is_empty(), "command name must not be empty");
1361 assert_eq!(
1362 command.name.trim(),
1363 command.name,
1364 "/{} command name must not need trimming",
1365 command.name
1366 );
1367 assert!(
1368 is_palette_safe_command_name(command.name),
1369 "/{} command names must stay lowercase ASCII kebab-case",
1370 command.name
1371 );
1372
1373 let expected_usage_prefix = format!("/{}", command.name);
1374 assert!(
1375 command.usage.starts_with(&expected_usage_prefix),
1376 "/{} usage must start with its canonical slash command, got {:?}",
1377 command.name,
1378 command.usage
1379 );
1380
1381 let description = command.description_for(Locale::En);
1382 assert!(
1383 !description.trim().is_empty(),
1384 "/{} must have non-empty English help text",
1385 command.name
1386 );
1387 // #3913: descriptions must not restate the usage field — the
1388 // palette and /help already append `usage` when arguments exist.
1389 assert!(
1390 !description.contains(command.usage),
1391 "/{} description embeds its usage string {:?}: {description:?}",
1392 command.name,
1393 command.usage
1394 );
1395 assert!(
1396 !description.contains(&format!("/{}", command.name)),
1397 "/{} description embeds slash-command syntax that usage already covers: {description:?}",
1398 command.name
1399 );
1400 for banned_prefix in ["Toolbox:", "Reference:"] {
1401 assert!(
1402 !description.starts_with(banned_prefix),
1403 "/{} description should not start with {banned_prefix:?}: {description:?}",
1404 command.name
1405 );
1406 }
1407
1408 let palette_command = command.palette_command();
1409 assert!(
1410 palette_command.starts_with(&expected_usage_prefix),
1411 "/{} palette command must use the canonical command, got {:?}",
1412 command.name,
1413 palette_command
1414 );
1415 assert_eq!(
1416 palette_command.ends_with(' '),
1417 command.requires_argument(),
1418 "/{} palette command spacing must match argument requirement",
1419 command.name
1420 );
1421
1422 for &alias in command.aliases {
1423 assert!(
1424 !alias.trim().is_empty(),
1425 "/{} alias must not be empty",
1426 command.name
1427 );
1428 assert_eq!(
1429 alias.trim(),
1430 alias,
1431 "/{} alias /{alias} must not need trimming",
1432 command.name
1433 );
1434 assert!(
1435 !alias.starts_with('/'),
1436 "/{} alias /{alias} must be stored without a slash",
1437 command.name
1438 );
1439 assert!(
1440 !alias.chars().any(char::is_whitespace),
1441 "/{} alias /{alias} must not contain whitespace",
1442 command.name
1443 );
1444 assert!(
1445 !alias.chars().any(|ch| ch.is_ascii_uppercase()),
1446 "/{} alias /{alias} must not contain uppercase ASCII",
1447 command.name
1448 );
1449 }
1450 }
1451 }
1452
1453 #[test]
1454 fn flagship_orchestration_and_workspace_commands_are_visible_at_the_palette_root() {
1455 for name in [
1456 "auto",
1457 "goal",
1458 "hooks",
1459 "tokens",
1460 "translate",
1461 "workflow",
1462 "workspace",
1463 ] {
1464 let info = registry()
1465 .get_info(name)
1466 .unwrap_or_else(|| panic!("/{name} must be registered"));
1467 assert!(
1468 info.show_in_empty_discovery(),
1469 "/{name} must appear at the palette root (#5442 / #5439)"
1470 );
1471 assert!(
1472 !traits::ADVANCED_DISCOVERY_COMMANDS.contains(&name),
1473 "/{name} must not stay on the Advanced discovery list"
1474 );
1475 }
1476 }
1477
1478 #[test]
1479 fn plugin_command_is_primary_discovery() {
1480 use codewhale_engine::command_catalog::CommandCatalog;
1481
1482 assert!(!traits::ADVANCED_DISCOVERY_COMMANDS.contains(&"plugin"));
1483 let info = registry().get_info("plugin").expect("/plugin registered");
1484 assert!(info.show_in_empty_discovery());
1485 let row = CommandTable
1486 .builtins()
1487 .into_iter()
1488 .find(|row| row.name == "plugin")
1489 .expect("/plugin in the built-in catalog");
1490 assert_eq!(
1491 row.discovery,
1492 codewhale_command_contract::CommandDiscovery::Primary
1493 );
1494 assert!(row.show_in_empty_discovery);
1495 }
1496
1497 #[test]
1498 fn command_discovery_tier_lists_use_canonical_registered_names() {
1499 for (tier_name, names) in [
1500 ("advanced", traits::ADVANCED_DISCOVERY_COMMANDS),
1501 ("compatibility", traits::COMPATIBILITY_DISCOVERY_COMMANDS),
1502 ] {
1503 for &name in names {
1504 let info = registry()
1505 .get_info(name)
1506 .unwrap_or_else(|| panic!("{tier_name} discovery entry {name:?} must resolve"));
1507 assert_eq!(
1508 info.name, name,
1509 "{tier_name} discovery entry {name:?} must be canonical, not an alias for /{}",
1510 info.name
1511 );
1512 }
1513 }
1514 }
1515
1516 #[test]
1517 fn command_info_resolves_canonical_names_and_aliases() {
1518 use codewhale_command_contract::handler::{
1519 CommandCapabilities as Caps, CommandContexts, CommandHandler, ContextParts,
1520 };
1521 struct MissingTemplate;
1522 impl codewhale_command_contract::facets::CommandPresentationContext for MissingTemplate {
1523 fn translate(&self, _: &str, _: &[(&str, &str)]) -> Result<String, String> {
1524 Err("template unavailable".into())
1525 }
1526 }
1527 for (name, service, needs_presentation) in [
1528 ("help", Caps::NAVIGATION, true),
1529 ("copy", Caps::RESPONSE_COPY, true),
1530 ("home", Caps::NAVIGATION, true),
1531 ("overview", Caps::NAVIGATION, true),
1532 ("links", Caps::NAVIGATION, true),
1533 ("anchor", Caps::WORKSPACE, false),
1534 ("workspace", Caps::WORKSPACE, true),
1535 ("translate", Caps::CONFIG, true),
1536 ("voice", Caps::VOICE_INPUT, true),
1537 ("voicesend", Caps::VOICE_INPUT, true),
1538 ("voicecontrol", Caps::VOICE_INPUT, true),
1539 ] {
1540 let expected = if needs_presentation {
1541 service | Caps::PRESENTATION
1542 } else {
1543 service
1544 };
1545 let CommandHandler::Contextual {
1546 capabilities,
1547 handler,
1548 } = registry().get(name).unwrap().contextual_handler().unwrap()
1549 else {
1550 panic!("/{name} must declare scoped authority");
1551 };
1552 assert_eq!(capabilities, expected);
1553 let missing = handler(CommandContexts::empty(), Some("missing-facet-input"));
1554 assert!(missing.is_error && missing.action.is_none());
1555 let mut app = create_test_app();
1556 app.launch.dismiss();
1557 let before_view = format!("{:?}", app.view_stack.top_kind());
1558 let before_translation = app.translation_enabled;
1559 app.voice_enabled = name == "voice";
1560 let before_voice = (
1561 app.voice_enabled,
1562 app.voice_send_enabled,
1563 app.voice_control_enabled,
1564 );
1565 if needs_presentation {
1566 let missing_presentation = {
1567 let mut bundle = app.command_contexts();
1568 handler(bundle.contexts(service), None)
1569 };
1570 assert!(missing_presentation.is_error && missing_presentation.action.is_none());
1571 assert!(
1572 missing_presentation
1573 .message
1574 .as_deref()
1575 .is_some_and(|text| text.contains("presentation"))
1576 );
1577 }
1578 if name == "translate" || service == Caps::VOICE_INPUT {
1579 let mut failing = MissingTemplate;
1580 let failure = {
1581 let mut bundle = app.command_contexts();
1582 handler(
1583 bundle.contexts(service).with_presentation(&mut failing),
1584 None,
1585 )
1586 };
1587 assert!(failure.is_error && failure.action.is_none());
1588 }
1589 assert!(!app.launch.visible);
1590 assert_eq!(format!("{:?}", app.view_stack.top_kind()), before_view);
1591 assert_eq!(app.translation_enabled, before_translation);
1592 assert_eq!(
1593 (
1594 app.voice_enabled,
1595 app.voice_send_enabled,
1596 app.voice_control_enabled
1597 ),
1598 before_voice
1599 );
1600 let mut bundle = app.command_contexts();
1601 let mut contexts = bundle.contexts(capabilities);
1602 let response_copy = contexts.take_response_copy().is_some();
1603 let ContextParts {
1604 session,
1605 model,
1606 cost,
1607 mode_policy,
1608 system_prompt,
1609 skills,
1610 workspace,
1611 presentation,
1612 media,
1613 memory,
1614 project,
1615 skill_group,
1616 plugin,
1617 lifecycle,
1618 control,
1619 export,
1620 structcopy,
1621 debug_receipts,
1622 debug_change,
1623 debug_history,
1624 debug_diff,
1625 debug_undo,
1626 debug_diagnostics,
1627 permissions,
1628 config_status,
1629 config,
1630 pet,
1631 trust,
1632 login,
1633 work_surface,
1634 navigation,
1635 voice_input,
1636 } = contexts.into_parts();
1637 for (capability, exposed) in [
1638 (Caps::SESSION, session.is_some()),
1639 (Caps::MODEL, model.is_some()),
1640 (Caps::COST, cost.is_some()),
1641 (Caps::MODE_POLICY, mode_policy.is_some()),
1642 (Caps::SYSTEM_PROMPT, system_prompt.is_some()),
1643 (Caps::SKILLS, skills.is_some()),
1644 (Caps::WORKSPACE, workspace.is_some()),
1645 (Caps::PRESENTATION, presentation.is_some()),
1646 (Caps::MEDIA, media.is_some()),
1647 (Caps::MEMORY, memory.is_some()),
1648 (Caps::PROJECT, project.is_some()),
1649 (Caps::SKILL_GROUP, skill_group.is_some()),
1650 (Caps::PLUGIN, plugin.is_some()),
1651 (Caps::SESSION_LIFECYCLE, lifecycle.is_some()),
1652 (Caps::SESSION_CONTROL, control.is_some()),
1653 (Caps::SESSION_EXPORT, export.is_some()),
1654 (Caps::RESPONSE_COPY, response_copy),
1655 (Caps::SESSION_STRUCTCOPY, structcopy.is_some()),
1656 (Caps::DEBUG_RECEIPTS, debug_receipts.is_some()),
1657 (Caps::DEBUG_CHANGE, debug_change.is_some()),
1658 (Caps::DEBUG_HISTORY, debug_history.is_some()),
1659 (Caps::DEBUG_DIFF, debug_diff.is_some()),
1660 (Caps::DEBUG_UNDO, debug_undo.is_some()),
1661 (Caps::DEBUG_DIAGNOSTICS, debug_diagnostics.is_some()),
1662 (Caps::PERMISSIONS, permissions.is_some()),
1663 (Caps::CONFIG_STATUS, config_status.is_some()),
1664 (Caps::CONFIG, config.is_some()),
1665 (Caps::PET, pet.is_some()),
1666 (Caps::TRUST, trust.is_some()),
1667 (Caps::LOGIN, login.is_some()),
1668 (Caps::WORK_SURFACE, work_surface.is_some()),
1669 (Caps::NAVIGATION, navigation.is_some()),
1670 (Caps::VOICE_INPUT, voice_input.is_some()),
1671 ] {
1672 assert_eq!(
1673 exposed,
1674 expected.contains(capability),
1675 "/{name} facet {capability:?}"
1676 );
1677 }
1678 }
1679 for (name, expected) in [
1680 ("hotbar", AppAction::OpenHotbarSetup),
1681 ("transcript", AppAction::OpenLiveTranscript),
1682 ("turn", AppAction::OpenTurnInspector),
1683 ] {
1684 let handler = registry().get(name).unwrap().contextual_handler().unwrap();
1685 let codewhale_command_contract::handler::CommandHandler::Pure(run) = handler else {
1686 panic!("/{name} must be pure and require no host envelope");
1687 };
1688 let result = run(None);
1689 assert_eq!(result.action, Some(expected.clone()));
1690 assert!(result.message.is_none());
1691 assert!(!result.is_error);
1692 let mut app = create_test_app();
1693 let shortcut = super::core_navigation_host::dispatch(&mut app, name, None);
1694 assert_eq!(shortcut.action, Some(expected));
1695 assert!(shortcut.message.is_none());
1696 assert!(!shortcut.is_error);
1697 }
1698 for command in command_infos() {
1699 for lookup in [command.name.to_string(), format!("/{}", command.name)] {
1700 let resolved = get_command_info(&lookup)
1701 .unwrap_or_else(|| panic!("{lookup:?} should resolve to /{}", command.name));
1702 assert_eq!(resolved.name, command.name);
1703 }
1704
1705 for &alias in command.aliases {
1706 for lookup in [alias.to_string(), format!("/{alias}")] {
1707 let resolved = get_command_info(&lookup).unwrap_or_else(|| {
1708 panic!("{lookup:?} should resolve to /{}", command.name)
1709 });
1710 assert_eq!(resolved.name, command.name);
1711 }
1712 }
1713 }
1714 }
1715
1716 #[test]
1717 fn every_registered_command_has_a_help_topic() {
1718 let mut app = create_test_app();
1719 for command in command_infos() {
1720 let result = execute(&format!("/help {}", command.name), &mut app);
1721 assert!(
1722 !result.is_error,
1723 "/help {} returned an error: {result:?}",
1724 command.name
1725 );
1726 let message = result
1727 .message
1728 .unwrap_or_else(|| panic!("/help {} should return text", command.name));
1729 assert!(
1730 message.contains(command.name),
1731 "/help {} should mention the command name, got {message:?}",
1732 command.name
1733 );
1734 assert!(
1735 message.contains(command.usage),
1736 "/help {} should include usage {:?}, got {message:?}",
1737 command.name,
1738 command.usage
1739 );
1740 }
1741 }
1742
1743 #[test]
1744 fn context_command_opens_inspector_and_keeps_ctx_alias() {
1745 let context = command_infos()
1746 .into_iter()
1747 .find(|cmd| cmd.name == "context")
1748 .expect("context command should exist");
1749 assert_eq!(context.aliases, &["ctx"]);
1750 assert!(context.description_for(Locale::En).contains("inspector"));
1751
1752 let mut app = create_test_app();
1753 let result = execute("/ctx", &mut app);
1754 assert!(matches!(
1755 result.action,
1756 Some(AppAction::OpenContextInspector)
1757 ));
1758
1759 let report = execute("/context report", &mut app);
1760 let message = report.message.expect("context report should return text");
1761 assert!(message.contains("Context Source Map"));
1762 }
1763
1764 #[test]
1765 fn cache_inspect_dispatches_through_cache_command() {
1766 let mut app = create_test_app();
1767 let result = execute("/cache inspect", &mut app);
1768 let msg = result.message.expect("cache inspect should return text");
1769 assert!(msg.contains("Cache Inspect"));
1770 assert!(msg.contains("Base static prefix hash:"));
1771 assert!(msg.contains("Full request prefix hash:"));
1772 assert!(result.action.is_none());
1773 }
1774
1775 #[test]
1776 fn cache_warmup_dispatches_action() {
1777 let mut app = create_test_app();
1778 let result = execute("/cache warmup", &mut app);
1779 assert!(result.message.is_none());
1780 assert!(matches!(result.action, Some(AppAction::CacheWarmup)));
1781 }
1782
1783 #[test]
1784 fn execute_config_opens_config_view_action() {
1785 let mut app = create_test_app();
1786 let result = execute("/config", &mut app);
1787 assert!(result.message.is_none());
1788 assert!(matches!(result.action, Some(AppAction::OpenConfigView)));
1789 }
1790
1791 #[test]
1792 fn execute_verbose_toggles_live_transcript_detail() {
1793 let mut app = create_test_app();
1794 assert!(!app.verbose_transcript);
1795
1796 let result = execute("/verbose on", &mut app);
1797 assert!(!result.is_error);
1798 assert!(app.verbose_transcript);
1799 assert!(result.message.unwrap().contains("on"));
1800
1801 let result = execute("/verbose off", &mut app);
1802 assert!(!result.is_error);
1803 assert!(!app.verbose_transcript);
1804 assert!(result.message.unwrap().contains("off"));
1805 }
1806
1807 #[test]
1808 fn voice_send_and_voice_control_commands_toggle_state() {
1809 let mut app = create_test_app();
1810 assert!(!app.voice_send_enabled);
1811 assert!(!app.voice_control_enabled);
1812
1813 for invocation in ["/voicesend", "/voice-send", "/yuyinsend", "/语音发送"] {
1814 let result = execute(invocation, &mut app);
1815 assert!(!result.is_error, "{invocation} should toggle cleanly");
1816 assert!(result.action.is_none());
1817 assert!(result.message.is_some());
1818 }
1819 // Four toggles land back at disabled.
1820 assert!(!app.voice_send_enabled);
1821
1822 let result = execute("/voicecontrol", &mut app);
1823 assert!(!result.is_error);
1824 assert!(app.voice_control_enabled);
1825 let result = execute("/voice-control", &mut app);
1826 assert!(!result.is_error);
1827 assert!(!app.voice_control_enabled);
1828 }
1829
1830 /// `/voice` defers the actual capture to the UI event loop via
1831 /// `AppAction::VoiceCapture`, so executing it never records audio.
1832 /// On hosts without a recorder it must fail gracefully instead.
1833 #[test]
1834 fn voice_command_toggles_on_and_off_or_fails_gracefully() {
1835 use codewhale_command_contract::handler::{CommandContexts, CommandHandler};
1836 struct VoiceState {
1837 enabled: bool,
1838 available: bool,
1839 probes: std::cell::Cell<usize>,
1840 }
1841 impl codewhale_command_contract::navigation::CommandVoiceInputContext for VoiceState {
1842 fn recorder_available(&self) -> bool {
1843 self.probes.set(self.probes.get() + 1);
1844 self.available
1845 }
1846 fn voice_enabled(&self) -> bool {
1847 self.enabled
1848 }
1849 fn set_voice_enabled(&mut self, enabled: bool) {
1850 self.enabled = enabled;
1851 }
1852 fn send_enabled(&self) -> bool {
1853 unreachable!("voice must not read send state")
1854 }
1855 fn set_send_enabled(&mut self, _: bool) {
1856 unreachable!("voice must not set send state")
1857 }
1858 fn control_enabled(&self) -> bool {
1859 unreachable!("voice must not read control state")
1860 }
1861 fn set_control_enabled(&mut self, _: bool) {
1862 unreachable!("voice must not set control state")
1863 }
1864 }
1865 struct Labels {
1866 fail: bool,
1867 }
1868 impl codewhale_command_contract::facets::CommandPresentationContext for Labels {
1869 fn translate(&self, key: &str, _: &[(&str, &str)]) -> Result<String, String> {
1870 if self.fail {
1871 return Err("missing fixture template".into());
1872 }
1873 match key {
1874 "voice_enabled" => Ok("Voice enabled".into()),
1875 "voice_disabled" => Ok("Voice disabled".into()),
1876 "voice_err_no_recorder" => Ok("Recorder unavailable".into()),
1877 _ => Err("unexpected voice label".into()),
1878 }
1879 }
1880 }
1881 let CommandHandler::Contextual { handler, .. } = registry()
1882 .get("voice")
1883 .unwrap()
1884 .contextual_handler()
1885 .unwrap()
1886 else {
1887 panic!("voice must be contextual");
1888 };
1889 for available in [false, true] {
1890 let mut voice = VoiceState {
1891 enabled: false,
1892 available,
1893 probes: std::cell::Cell::new(0),
1894 };
1895 let mut labels = Labels { fail: false };
1896 let on = handler(
1897 CommandContexts::empty()
1898 .with_voice_input(&mut voice)
1899 .with_presentation(&mut labels),
1900 None,
1901 );
1902 assert_eq!(on.is_error, !available);
1903 assert_eq!(voice.enabled, available);
1904 assert_eq!(on.action, available.then_some(AppAction::VoiceCapture));
1905 assert_eq!(voice.probes.get(), 1);
1906 voice.enabled = true;
1907 voice.available = false;
1908 let off = handler(
1909 CommandContexts::empty()
1910 .with_voice_input(&mut voice)
1911 .with_presentation(&mut labels),
1912 None,
1913 );
1914 assert!(!off.is_error && off.action.is_none() && !voice.enabled);
1915 assert_eq!(
1916 voice.probes.get(),
1917 1,
1918 "voice-off must not probe recorder availability"
1919 );
1920 voice.available = true;
1921 labels.fail = true;
1922 let failed = handler(
1923 CommandContexts::empty()
1924 .with_voice_input(&mut voice)
1925 .with_presentation(&mut labels),
1926 None,
1927 );
1928 assert!(failed.is_error && failed.action.is_none() && !voice.enabled);
1929 }
1930 let mut app = create_test_app();
1931 let result = execute("/voice", &mut app);
1932 if app.voice_enabled {
1933 assert!(!result.is_error);
1934 assert!(matches!(result.action, Some(AppAction::VoiceCapture)));
1935 let off = execute("/voice", &mut app);
1936 assert!(!off.is_error);
1937 assert!(off.action.is_none());
1938 assert!(!app.voice_enabled);
1939 } else {
1940 assert!(result.is_error);
1941 assert!(result.action.is_none());
1942 }
1943 }
1944
1945 #[test]
1946 fn execute_rail_sets_placement_and_reports_actual_state() {
1947 let mut app = create_test_app();
1948
1949 let result = execute("/workbar off", &mut app);
1950 assert!(!result.is_error);
1951 assert_eq!(app.work_surface.placement, WorkSurfacePlacement::Off);
1952 assert!(
1953 result
1954 .message
1955 .as_deref()
1956 .unwrap_or_default()
1957 .contains("Workbar is off")
1958 );
1959
1960 let result = execute("/rail right", &mut app);
1961 assert!(!result.is_error);
1962 assert_eq!(app.work_surface.placement, WorkSurfacePlacement::Right);
1963 assert!(
1964 result
1965 .message
1966 .as_deref()
1967 .unwrap_or_default()
1968 .contains("right placement")
1969 );
1970
1971 // The /rail and /sidebar aliases drive the same workbar.
1972 let result = execute("/sidebar left", &mut app);
1973 assert!(!result.is_error);
1974 assert_eq!(app.work_surface.placement, WorkSurfacePlacement::Left);
1975
1976 let result = execute("/rail top", &mut app);
1977 assert!(!result.is_error);
1978 assert_eq!(app.work_surface.placement, WorkSurfacePlacement::Top);
1979
1980 // Bare /workbar reports the actual rendered state; it must never claim
1981 // visibility for a surface that cannot render.
1982 app.work_surface.placement = WorkSurfacePlacement::Off;
1983 let result = execute("/workbar", &mut app);
1984 assert!(!result.is_error);
1985 assert!(
1986 result
1987 .message
1988 .as_deref()
1989 .unwrap_or_default()
1990 .contains("Workbar is off")
1991 );
1992 }
1993
1994 #[test]
1995 fn execute_rail_accepts_panel_targets_and_legacy_words() {
1996 let mut app = create_test_app();
1997
1998 let result = execute("/rail agents", &mut app);
1999 assert!(!result.is_error);
2000 assert_eq!(app.work_surface.panel, RailPanel::Agents);
2001
2002 let result = execute("/sidebar context", &mut app);
2003 assert!(!result.is_error);
2004 assert_eq!(app.work_surface.panel, RailPanel::Context);
2005
2006 let result = execute("/rail activity", &mut app);
2007 assert!(!result.is_error);
2008 assert_eq!(
2009 app.work_surface.panel,
2010 RailPanel::Tasks,
2011 "activity maps onto the Tasks panel"
2012 );
2013
2014 let result = execute("/rail pinned", &mut app);
2015 assert!(!result.is_error);
2016 assert_eq!(
2017 app.work_surface.panel,
2018 RailPanel::Tasks,
2019 "pinned folded into the tasks view"
2020 );
2021 let result = execute("/rail files", &mut app);
2022 assert!(!result.is_error);
2023 assert_eq!(app.work_surface.panel, RailPanel::Files);
2024
2025 let result = execute("/sidebar on", &mut app);
2026 assert!(!result.is_error);
2027 assert_eq!(
2028 app.work_surface.placement,
2029 WorkSurfacePlacement::Bottom,
2030 "on restores the default bottom workbar (round 3)"
2031 );
2032
2033 let result = execute("/sidebar none", &mut app);
2034 assert!(!result.is_error);
2035 assert_eq!(app.work_surface.placement, WorkSurfacePlacement::Off);
2036 }
2037
2038 #[test]
2039 fn execute_rail_rejects_invalid_args() {
2040 let mut app = create_test_app();
2041 let result = execute("/rail maybe", &mut app);
2042 assert!(result.is_error);
2043 assert!(
2044 result
2045 .message
2046 .as_deref()
2047 .unwrap_or_default()
2048 .contains("Usage: /workbar")
2049 );
2050 }
2051
2052 #[test]
2053 fn execute_links_and_aliases_return_links_message() {
2054 let mut app = create_test_app();
2055 for cmd in ["/links", "/api", "/lianjie"] {
2056 let result = execute(cmd, &mut app);
2057 let msg = result.message.expect("links commands should return text");
2058 assert!(msg.contains("https://codewhale.net/en/docs"));
2059 assert!(msg.contains("https://codewhale.net/en/community"));
2060 assert!(msg.contains("https://github.com/codewhale-hq/CodeWhale"));
2061 assert!(msg.contains("https://app.codewhale.net"));
2062 assert!(msg.contains("separate sign-in"));
2063 assert!(msg.contains("not connected to the current local session"));
2064 assert!(msg.contains("https://platform.deepseek.com"));
2065 assert!(result.action.is_none());
2066 }
2067 }
2068
2069 #[test]
2070 fn execute_workspace_alias_switches_workspace() {
2071 let dir = tempdir().expect("temp dir");
2072 let mut app = create_test_app();
2073 let result = execute(&format!("/cwd {}", dir.path().display()), &mut app);
2074 assert!(matches!(
2075 result.action,
2076 Some(AppAction::SwitchWorkspace { workspace }) if workspace == dir.path().canonicalize().unwrap()
2077 ));
2078 }
2079
2080 #[test]
2081 fn removed_set_and_deepseek_commands_show_migration_hints() {
2082 let mut app = create_test_app();
2083 let set_result = execute("/set model deepseek-v4-pro", &mut app);
2084 let set_msg = set_result
2085 .message
2086 .expect("legacy command should return an error message");
2087 assert!(set_msg.contains("The /set command was retired"));
2088 assert!(set_msg.contains("/config"));
2089 assert!(set_msg.contains("/settings"));
2090 assert!(set_result.action.is_none());
2091
2092 let deepseek_result = execute("/deepseek", &mut app);
2093 let deepseek_msg = deepseek_result
2094 .message
2095 .expect("legacy command should return an error message");
2096 assert!(deepseek_msg.contains("The /deepseek command was renamed"));
2097 assert!(deepseek_msg.contains("/links"));
2098 assert!(deepseek_msg.contains("/api"));
2099 assert!(deepseek_result.action.is_none());
2100 }
2101
2102 #[test]
2103 fn view_plan_command_opens_plan_artifact_viewer() {
2104 let mut app = create_test_app();
2105 for cmd in ["/view-plan", "/view_plan edit"] {
2106 let result = execute(cmd, &mut app);
2107 assert!(!result.is_error);
2108 let expected = cmd.split_whitespace().nth(1).map(ToString::to_string);
2109 assert!(matches!(
2110 result.action,
2111 Some(AppAction::OpenPlanArtifact { arg }) if arg == expected
2112 ));
2113 }
2114 }
2115
2116 /// Seals the user's home *and* points the config at the fixture's own
2117 /// file. Dispatching every command reaches credentials, sessions, snapshots,
2118 /// plugin bundles, audit logs and the `/import-claude` report — all of which
2119 /// resolve under the home, so pinning the config path alone (as this once
2120 /// did) left them on the developer's real profile.
2121 struct ConfigPathGuard {
2122 // Fields drop in order: restore the config path, then the seal.
2123 _config_path: crate::test_support::EnvVarGuard,
2124 _home: crate::test_support::SealedHome,
2125 }
2126
2127 impl ConfigPathGuard {
2128 fn new(config_path: &Path) -> Self {
2129 let home = crate::test_support::SealedHome::new();
2130 let config = crate::test_support::EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", config_path);
2131 Self {
2132 _config_path: config,
2133 _home: home,
2134 }
2135 }
2136 }
2137
2138 /// Build an App scoped to an isolated tempdir so dispatch-side-effects
2139 /// (e.g. `/init` writing AGENTS.md, explicit `/export <path>` writes, or
2140 /// `/logout` clearing credentials) don't pollute the repo working tree or
2141 /// the developer's real config when the smoke tests run.
2142 fn create_isolated_test_app() -> (App, tempfile::TempDir, ConfigPathGuard) {
2143 let tmpdir = tempfile::TempDir::new().expect("tempdir for smoke test");
2144 let workspace = tmpdir.path().to_path_buf();
2145 let config_path = workspace.join(".deepseek").join("config.toml");
2146 std::fs::create_dir_all(config_path.parent().expect("config parent")).expect("config dir");
2147 let guard = ConfigPathGuard::new(&config_path);
2148 // Skills live under the workspace here, so they load only once trusted.
2149 crate::test_support::trust_workspace(&workspace);
2150 let options = TuiOptions {
2151 config_path: Some(config_path),
2152 skills_dir: workspace.join("skills"),
2153 memory_path: workspace.join("memory.md"),
2154 mcp_config_path: workspace.join("mcp.json"),
2155 ..crate::tui::test_support::test_tui_options(workspace.clone())
2156 };
2157 let app = App::new(options, &Config::default());
2158 assert!(
2159 app.dispatch_completion_tx.is_none(),
2160 "dispatch smoke fixtures must not permit native window mutations"
2161 );
2162 (app, tmpdir, guard)
2163 }
2164
2165 /// Smoke test: every entry in `command_infos()` must dispatch to a real handler.
2166 /// A dispatch miss surfaces as the fall-through `Unknown command:` error
2167 /// message in `execute`. This catches the case where a new command is
2168 /// added to `command_infos()` (so it shows up in `/help` and the palette) but
2169 /// the matching arm in `execute` is forgotten — the user would type the
2170 /// command, see it autocomplete, and then get an unhelpful "did you
2171 /// mean" suggestion. Also catches panics in handlers because the test
2172 /// runner unwinds the panic and reports the offending command.
2173 /// `/save` still defaults its output path, while `/export` accepts a legacy
2174 /// direct file path. Pass explicit tempdir paths so this smoke test covers
2175 /// both file handlers without touching the developer's clipboard.
2176 fn invocation_for(command_name: &str, alias_or_name: &str, tmpdir: &std::path::Path) -> String {
2177 match command_name {
2178 "save" => format!("/{alias_or_name} {}", tmpdir.join("session.json").display()),
2179 "export" => format!("/{alias_or_name} {}", tmpdir.join("chat.md").display()),
2180 _ => format!("/{alias_or_name}"),
2181 }
2182 }
2183
2184 /// `/restore` is covered by its own dedicated tests in
2185 /// `commands/restore.rs` that serialize on the global env mutex via
2186 /// `scoped_home` (snapshot repo init shells out to git, which races
2187 /// against parallel-running tests). Skip it here so this smoke test
2188 /// stays parallel-safe.
2189 ///
2190 /// `/pin` is covered on every platform. The headless fixture has no
2191 /// completion mailbox, so Windows rejects it before resolving or changing
2192 /// a host window; the former synchronous message-pump wait cannot occur.
2193 fn skip_in_dispatch_smoke(name: &str) -> bool {
2194 name == "restore"
2195 }
2196
2197 /// Upper bound on a single command dispatch in the smoke tests.
2198 ///
2199 /// Generous next to the millisecond each handler actually takes, and far
2200 /// below nextest's 600 s test timeout, so a handler that blocks fails the
2201 /// test *by name* instead of burning a ten-minute CI slot with no
2202 /// attribution (#5919).
2203 const DISPATCH_WATCHDOG: std::time::Duration = std::time::Duration::from_secs(30);
2204
2205 /// Dispatch one command under a per-command watchdog and return the
2206 /// handler's message.
2207 ///
2208 /// The app is built and the command executed on a dedicated thread; the
2209 /// test thread waits on the result with a timeout. A handler that never
2210 /// returns leaves its thread parked, but the test itself fails
2211 /// immediately, naming the invocation. A handler that panics still
2212 /// surfaces as that panic — the smoke tests are the repo's only
2213 /// panic-in-a-handler net, so the payload is resumed rather than
2214 /// swallowed.
2215 fn dispatch_under_watchdog(command_name: &str, alias_or_name: &str) -> Option<String> {
2216 let label = format!("/{alias_or_name}");
2217 let (tx, rx) = std::sync::mpsc::channel();
2218 let name = command_name.to_string();
2219 let alias = alias_or_name.to_string();
2220 let handle = std::thread::Builder::new()
2221 .name(format!("dispatch-smoke-{alias_or_name}"))
2222 // Command handlers are deeply recursive in debug builds; match the
2223 // 16 MiB the CI runner sets via RUST_MIN_STACK for the main thread.
2224 .stack_size(16 * 1024 * 1024)
2225 .spawn(move || {
2226 let (mut app, tmpdir, _guard) = create_isolated_test_app();
2227 let invocation = invocation_for(&name, &alias, tmpdir.path());
2228 let result = execute(&invocation, &mut app);
2229 let _ = tx.send(result.message);
2230 })
2231 .expect("spawn dispatch smoke thread");
2232
2233 let started = std::time::Instant::now();
2234 match rx.recv_timeout(DISPATCH_WATCHDOG) {
2235 Ok(message) => {
2236 let _ = handle.join();
2237 // Quiet on the common path; a handler heading for the
2238 // watchdog still leaves a named breadcrumb in the log.
2239 let elapsed = started.elapsed();
2240 if elapsed > std::time::Duration::from_secs(1) {
2241 eprintln!("dispatch smoke: {label} took {elapsed:?}");
2242 }
2243 message
2244 }
2245 Err(std::sync::mpsc::RecvTimeoutError::Timeout) => panic!(
2246 "{label} did not return within {DISPATCH_WATCHDOG:?}: its handler blocks. \
2247 Fix the handler or add it to skip_in_dispatch_smoke with a reason."
2248 ),
2249 Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => match handle.join() {
2250 Ok(()) => panic!("{label} dispatch thread ended without producing a result"),
2251 Err(payload) => std::panic::resume_unwind(payload),
2252 },
2253 }
2254 }
2255
2256 #[test]
2257 fn slash_parser_preserves_arguments_after_the_command_name() {
2258 let mut app = create_test_app();
2259 let result = execute("/agent 2 review this carefully", &mut app);
2260 assert!(!result.is_error);
2261 let Some(AppAction::SendMessage(message)) = result.action else {
2262 panic!("expected /agent to send a model instruction");
2263 };
2264 assert!(message.contains(r#"prompt: "review this carefully""#));
2265 assert!(message.contains("max_depth: 2"));
2266
2267 let mut app = create_test_app();
2268 let result = execute(" /relay ship command harness ", &mut app);
2269 assert!(!result.is_error);
2270 let Some(AppAction::SendMessage(message)) = result.action else {
2271 panic!("expected /relay to send a model instruction");
2272 };
2273 assert!(message.contains("Requested relay focus: ship command harness"));
2274
2275 let mut app = create_test_app();
2276 let result = execute("/rlm 3 inspect this corpus", &mut app);
2277 assert!(!result.is_error);
2278 let Some(AppAction::SendMessage(message)) = result.action else {
2279 panic!("expected /rlm to send a model instruction");
2280 };
2281 assert!(message.contains(r#"this text: "inspect this corpus""#));
2282 assert!(message.contains("`rlm` tool"));
2283 }
2284
2285 #[test]
2286 fn representative_command_groups_keep_dispatch_surfaces() {
2287 let mut app = create_test_app();
2288 let help = execute("/help clear", &mut app)
2289 .message
2290 .expect("/help clear should return text");
2291 assert!(help.contains("clear"));
2292 assert!(help.contains("/clear"));
2293
2294 let mut app = create_test_app();
2295 let result = execute("/config", &mut app);
2296 assert!(matches!(result.action, Some(AppAction::OpenConfigView)));
2297
2298 let mut app = create_test_app();
2299 let result = execute("/relay command boundary", &mut app);
2300 assert!(!result.is_error);
2301 assert!(matches!(
2302 result.action,
2303 Some(AppAction::SendMessage(message))
2304 if message.contains("Requested relay focus: command boundary")
2305 ));
2306
2307 let mut app = create_test_app();
2308 let note_help = execute("/note help", &mut app)
2309 .message
2310 .expect("/note help should return text");
2311 assert!(note_help.contains("Usage: /note"));
2312
2313 let mut app = create_test_app();
2314 let result = execute("/goal ship layer 2 | budget: 100", &mut app);
2315 assert!(!result.is_error);
2316 assert!(matches!(
2317 result.action,
2318 Some(AppAction::SetGoalObjective {
2319 ref objective,
2320 token_budget: Some(100)
2321 }) if objective == "ship layer 2"
2322 ));
2323 // The hunt-era alias is gone: `/hunt` must not resolve anymore.
2324 assert!(execute("/hunt ship layer 2", &mut app).is_error);
2325
2326 let (mut app, _tmpdir, _guard) = create_isolated_test_app();
2327 let result = execute("/skills", &mut app);
2328 assert!(matches!(
2329 result.action,
2330 Some(AppAction::OpenExtensions {
2331 tab: crate::tui::views::extensions::ExtensionsTab::Skills
2332 })
2333 ));
2334
2335 let mut app = create_test_app();
2336 let result = execute("/task list", &mut app);
2337 assert!(matches!(result.action, Some(AppAction::TaskList)));
2338
2339 let mut app = create_test_app();
2340 let tokens = execute("/tokens", &mut app)
2341 .message
2342 .expect("/tokens should return text");
2343 assert!(tokens.contains("deepseek-v4-pro"));
2344 }
2345
2346 /// Smoke test: every entry in `command_infos()` must dispatch to a real handler.
2347 /// A dispatch miss surfaces as the fall-through `Unknown command:` error
2348 /// message in `execute`. This catches the case where a new command is
2349 /// added to `command_infos()` (so it shows up in `/help` and the palette) but
2350 /// the matching arm in `execute` is forgotten — the user would type the
2351 /// command, see it autocomplete, and then get an unhelpful "did you
2352 /// mean" suggestion. Also catches panics in handlers because the test
2353 /// runner unwinds the panic and reports the offending command.
2354 #[test]
2355 fn every_registered_command_dispatches_to_a_handler() {
2356 for command in command_infos() {
2357 if skip_in_dispatch_smoke(command.name) {
2358 continue;
2359 }
2360 if let Some(msg) = dispatch_under_watchdog(command.name, command.name) {
2361 assert!(
2362 !msg.contains("Unknown command"),
2363 "/{} fell through to the unknown-command branch: {msg}",
2364 command.name,
2365 );
2366 }
2367 }
2368 }
2369
2370 /// Same check, but for declared aliases — `/q` should not fall through
2371 /// just because the registry lists it as an alias of `/exit`.
2372 #[test]
2373 fn every_command_alias_dispatches_to_a_handler() {
2374 for command in command_infos() {
2375 if skip_in_dispatch_smoke(command.name) {
2376 continue;
2377 }
2378 for alias in command.aliases {
2379 if let Some(msg) = dispatch_under_watchdog(command.name, alias) {
2380 assert!(
2381 !msg.contains("Unknown command"),
2382 "/{alias} (alias of /{}) fell through to unknown: {msg}",
2383 command.name,
2384 );
2385 }
2386 }
2387 }
2388 }
2389
2390 #[test]
2391 fn balance_command_has_own_help_text() {
2392 let info = get_command_info("balance").expect("balance command should be registered");
2393 assert_eq!(info.description_id, MessageId::CmdBalanceDescription);
2394 assert!(
2395 info.description_for(Locale::En)
2396 .contains("provider account balance")
2397 );
2398 }
2399
2400 #[test]
2401 fn balance_command_dispatches_live_fetch_for_prepaid_providers() {
2402 let mut app = create_test_app();
2403 for provider in [
2404 ProviderKind::Deepseek,
2405 ProviderKind::Openrouter,
2406 ProviderKind::Siliconflow,
2407 ] {
2408 app.api_provider = provider;
2409 let result = execute("/balance", &mut app);
2410 assert!(!result.is_error, "{provider:?}");
2411 assert!(
2412 matches!(result.action, Some(AppAction::FetchBalance)),
2413 "{provider:?} should dispatch a live remaining-credit fetch"
2414 );
2415 }
2416 }
2417
2418 #[test]
2419 fn balance_command_reports_unsupported_provider_clearly() {
2420 let mut app = create_test_app();
2421 app.set_provider_identity(ProviderKind::Ollama, "ollama");
2422
2423 let result = execute("/balance", &mut app);
2424 let msg = result
2425 .message
2426 .expect("unsupported providers should return a clear message");
2427
2428 assert!(!result.is_error);
2429 assert!(msg.contains("Ollama"));
2430 assert!(msg.contains("not supported"));
2431 assert!(msg.contains("dashboard"));
2432 }
2433
2434 #[test]
2435 fn unknown_command_suggests_nearest_match() {
2436 let mut app = create_test_app();
2437 let result = execute("/modle", &mut app);
2438 let msg = result
2439 .message
2440 .expect("unknown command should return an error message");
2441 assert!(msg.contains("Unknown command: /modle"));
2442 assert!(msg.contains("Did you mean:"));
2443 assert!(msg.contains("/model"));
2444 }
2445
2446 #[test]
2447 fn unknown_command_without_close_match_keeps_help_guidance() {
2448 let mut app = create_test_app();
2449 let result = execute("/zzzzzz", &mut app);
2450 let msg = result
2451 .message
2452 .expect("unknown command should return an error message");
2453 assert!(msg.contains("Unknown command: /zzzzzz"));
2454 assert!(msg.contains("Type /help for available commands."));
2455 }
2456
2457 #[test]
2458 fn dollar_skill_prefix_with_no_name_shows_usage() {
2459 let mut app = create_test_app();
2460 let result = execute("$", &mut app);
2461 assert!(result.is_error);
2462 let msg = result.message.expect("should return error message");
2463 assert!(msg.contains("Type a skill name after $"));
2464 }
2465
2466 #[test]
2467 fn dollar_skill_prefix_unknown_skill_reports_unknown_skill() {
2468 let mut app = create_test_app();
2469 let result = execute("$definitely-not-a-real-skill-12345", &mut app);
2470 assert!(result.is_error);
2471 let msg = result.message.expect("should return error message");
2472 assert!(msg.contains("Unknown skill: $definitely-not-a-real-skill-12345"));
2473 assert!(msg.contains("/skills"));
2474 }
2475
2476 #[test]
2477 fn dollar_skill_prefix_does_not_break_existing_slash_dispatch() {
2478 let mut app = create_test_app();
2479 let result = execute("/help", &mut app);
2480 assert!(!result.is_error);
2481 }
2482
2483 fn write_test_skill(root: &Path, name: &str) {
2484 let skill_dir = root.join("skills").join(name);
2485 std::fs::create_dir_all(&skill_dir).expect("skill directory");
2486 std::fs::write(
2487 skill_dir.join("SKILL.md"),
2488 format!(
2489 "---\nname: {name}\ndescription: Test {name} skill\n---\nFollow the test instructions."
2490 ),
2491 )
2492 .expect("skill fixture");
2493 }
2494
2495 #[test]
2496 fn task_bearing_skill_invocations_send_the_task_on_the_activated_turn() {
2497 for invocation in ["$foo do X", "/foo do X", "/skill foo do X"] {
2498 let (mut app, tmpdir, _guard) = create_isolated_test_app();
2499 write_test_skill(tmpdir.path(), "foo");
2500
2501 let result = execute(invocation, &mut app);
2502
2503 assert!(!result.is_error, "{invocation}: {result:?}");
2504 assert!(
2505 result
2506 .message
2507 .as_deref()
2508 .is_some_and(|message| message.contains("Skill 'foo' activated")),
2509 "{invocation}: {result:?}"
2510 );
2511 assert!(
2512 matches!(result.action, Some(AppAction::SendMessage(ref task)) if task == "do X"),
2513 "{invocation}: {result:?}"
2514 );
2515 assert!(
2516 app.active_skill
2517 .as_deref()
2518 .is_some_and(|instruction| instruction.contains("# Skill: foo")),
2519 "{invocation} did not arm foo for the dispatched task"
2520 );
2521 }
2522 }
2523
2524 #[test]
2525 fn bare_dollar_skill_still_arms_the_next_message() {
2526 let (mut app, tmpdir, _guard) = create_isolated_test_app();
2527 write_test_skill(tmpdir.path(), "foo");
2528
2529 let result = execute("$foo", &mut app);
2530
2531 assert!(!result.is_error, "{result:?}");
2532 assert!(result.action.is_none());
2533 assert!(
2534 app.active_skill
2535 .as_deref()
2536 .is_some_and(|instruction| instruction.contains("# Skill: foo"))
2537 );
2538 }
2539
2540 #[test]
2541 fn shorthand_can_invoke_a_skill_named_install_without_stealing_management_commands() {
2542 for invocation in ["$install do X", "/install do X"] {
2543 let (mut app, tmpdir, _guard) = create_isolated_test_app();
2544 write_test_skill(tmpdir.path(), "install");
2545
2546 let result = execute(invocation, &mut app);
2547
2548 assert!(!result.is_error, "{invocation}: {result:?}");
2549 assert!(
2550 matches!(result.action, Some(AppAction::SendMessage(ref task)) if task == "do X"),
2551 "{invocation}: {result:?}"
2552 );
2553 assert!(
2554 app.active_skill
2555 .as_deref()
2556 .is_some_and(|instruction| instruction.contains("# Skill: install")),
2557 "{invocation} did not activate the install skill"
2558 );
2559 }
2560
2561 let (mut app, tmpdir, _guard) = create_isolated_test_app();
2562 write_test_skill(tmpdir.path(), "install");
2563 let result = execute("/skill install", &mut app);
2564 assert!(result.is_error, "management subcommand should show usage");
2565 assert!(
2566 result
2567 .message
2568 .as_deref()
2569 .is_some_and(|message| message.contains("/skill install"))
2570 );
2571 assert!(result.action.is_none());
2572 assert!(app.active_skill.is_none());
2573 }
2574
2575 // ---------------------------------------------------------------------
2576 // FEAT-015: test-only contextual dispatch through the public dispatcher
2577 // (D6). The fixture is registered into the global registry only in test
2578 // builds and executes through the public `execute()`.
2579 // ---------------------------------------------------------------------
2580
2581 #[test]
2582 fn feat015_contextual_command_executes_through_public_dispatcher() {
2583 let mut app = create_test_app();
2584 let result = execute("/feat015ctx hello", &mut app);
2585 assert!(!result.is_error, "{result:?}");
2586 let message = result.message.expect("message");
2587 assert!(message.contains("workspace="), "{message}");
2588 assert!(message.contains("mode="), "{message}");
2589 assert!(message.contains("currency="), "{message}");
2590 assert!(message.contains("arg=hello"), "{message}");
2591 assert!(result.action.is_none());
2592 }
2593
2594 #[test]
2595 fn feat015_contextual_command_fails_safely_without_declared_facets() {
2596 let result = feat015_contextual(
2597 codewhale_command_contract::handler::CommandContexts::empty(),
2598 None,
2599 );
2600 assert!(result.is_error, "{result:?}");
2601 assert_eq!(
2602 result.message.as_deref(),
2603 Some("Error: Command capability unavailable: workspace")
2604 );
2605 assert!(result.action.is_none());
2606 }
2607
2608 #[test]
2609 fn feat015_contextual_command_is_registered_only_in_test_builds() {
2610 // The fixture entry is present in the test-build registry with a
2611 // capability-scoped handler; production builds never see it.
2612 assert!(registry().has_contextual_handler("feat015ctx"));
2613 let info = registry().get_info("feat015ctx").expect("info");
2614 assert_eq!(info.name, "feat015ctx");
2615 assert_eq!(
2616 info.description_id,
2617 codewhale_localization::MessageId::CmdWorkspaceDescription,
2618 "portable description_key must bridge to the TUI localization id"
2619 );
2620 }
2621
2622 #[test]
2623 fn feat015_all_production_entries_use_command_contract() {
2624 for name in [
2625 "advisor",
2626 "agent",
2627 "copy",
2628 "exit",
2629 "hf",
2630 "modeldb",
2631 "models",
2632 "model",
2633 "provider",
2634 "setup",
2635 "pin",
2636 "profile",
2637 "queue",
2638 "rlm",
2639 "stash",
2640 "agents",
2641 "subagents",
2642 ] {
2643 assert!(
2644 registry().has_contextual_handler(name),
2645 "/{name} must use the command contract"
2646 );
2647 }
2648 assert_eq!(get_command_info("whales").unwrap().name, "agents");
2649 use codewhale_command_contract::handler::{CommandCapabilities as Caps, CommandHandler};
2650 for (name, expected) in [
2651 ("model", Some(Caps::MODEL_SELECTION)),
2652 ("provider", Some(Caps::PROVIDER_ROUTES)),
2653 ("setup", None),
2654 ("clear", Some(Caps::CLEAR.union(Caps::PRESENTATION))),
2655 ("effort", Some(Caps::EFFORT.union(Caps::PRESENTATION))),
2656 ("feedback", Some(Caps::FEEDBACK.union(Caps::PRESENTATION))),
2657 (
2658 "workflow",
2659 Some(Caps::WORKFLOW_CONTROL.union(Caps::WORKFLOW_REVIEW)),
2660 ),
2661 ("workflows", Some(Caps::WORKFLOW_CONTROL)),
2662 ("auto", Some(Caps::AUTO_REVIEW.union(Caps::PRESENTATION))),
2663 ("router", None),
2664 ("constitution", Some(Caps::CONSTITUTION)),
2665 ("hooks", Some(Caps::HOOKS)),
2666 ("fleet", Some(Caps::FLEET)),
2667 ("lane", Some(Caps::LANE)),
2668 ] {
2669 let handler = registry().get(name).unwrap().contextual_handler().unwrap();
2670 let actual = match handler {
2671 CommandHandler::Pure(_) => None,
2672 CommandHandler::Contextual { capabilities, .. } => Some(capabilities),
2673 };
2674 assert_eq!(actual, expected, "/{name} host capabilities");
2675 }
2676 let legacy: Vec<_> = registry()
2677 .iter()
2678 .filter(|command| command.contextual_handler().is_none())
2679 .map(|command| command.info().name)
2680 .collect();
2681 assert!(
2682 legacy.is_empty(),
2683 "built-in commands without portable handlers: {legacy:?}"
2684 );
2685 }
2686
2687 // ---------------------------------------------------------------------
2688 // FEAT-018: public pure/contextual dispatch and seven-entry inventory
2689 // (Task 6.2). These tests enter through the public registry/dispatch seam
2690 // and prove both handler variants plus all seven utility metadata records.
2691 // ---------------------------------------------------------------------
2692
2693 #[test]
2694 fn feat018_all_seven_utility_entries_are_registered_with_portable_handlers() {
2695 for name in [
2696 "attach",
2697 "automation",
2698 "jobs",
2699 "mcp",
2700 "network",
2701 "task",
2702 "update",
2703 ] {
2704 let info = registry()
2705 .get_info(name)
2706 .unwrap_or_else(|| panic!("/{name} must be registered"));
2707 assert_eq!(info.name, name, "canonical name");
2708 assert!(
2709 registry().has_contextual_handler(name),
2710 "/{name} must carry a portable handler"
2711 );
2712 }
2713 }
2714
2715 #[test]
2716 fn feat018_pure_utility_command_dispatches_through_public_seam() {
2717 let mut app = create_test_app();
2718 // /jobs is a Pure handler: it must execute without building an
2719 // envelope and return the same action as the parser.
2720 let result = execute("/jobs list", &mut app);
2721 assert!(!result.is_error, "{result:?}");
2722 assert!(
2723 matches!(
2724 result.action,
2725 Some(crate::tui::app::AppAction::ShellJob(
2726 crate::tui::app::ShellJobAction::List
2727 ))
2728 ),
2729 "{result:?}"
2730 );
2731
2732 // /update declares only the background facet; without a completion
2733 // mailbox a bare check runs inline, reaches the plan resolver and
2734 // returns a message (or a safe error in a test environment), never a panic.
2735 let result = execute("/update", &mut app);
2736 assert!(result.message.is_some() || result.is_error, "{result:?}");
2737 }
2738
2739 #[test]
2740 fn feat018_contextual_utility_commands_dispatch_through_public_seam() {
2741 let mut app = create_test_app();
2742
2743 // /automation (contextual, presentation facet): list action.
2744 let automation = execute("/automation list", &mut app);
2745 assert!(
2746 matches!(
2747 automation.action,
2748 Some(crate::tui::app::AppAction::Automation(
2749 crate::tui::app::AutomationAction::List
2750 ))
2751 ),
2752 "{automation:?}"
2753 );
2754
2755 // /task (contextual, workspace facet): digest without a runtime must
2756 // produce the canonical no-active text.
2757 let task = execute("/task digest", &mut app);
2758 assert_eq!(
2759 task.message.as_deref(),
2760 Some("No active operations or to-do items."),
2761 "{task:?}"
2762 );
2763
2764 // /mcp (contextual, presentation facet): status maps to Show action.
2765 let mcp = execute("/mcp status", &mut app);
2766 assert!(
2767 matches!(
2768 mcp.action,
2769 Some(crate::tui::app::AppAction::Mcp(
2770 crate::tui::app::McpUiAction::Show
2771 ))
2772 ),
2773 "{mcp:?}"
2774 );
2775
2776 // /attach (contextual, workspace + media facets): missing path is a
2777 // safe error, never a panic, and the composer is untouched.
2778 let attach = execute("/attach", &mut app);
2779 assert!(attach.is_error, "{attach:?}");
2780 assert!(app.input.is_empty(), "composer must stay unchanged");
2781
2782 // /network (pure): list produces a message.
2783 let network = execute("/network list", &mut app);
2784 assert!(network.message.is_some() || network.is_error, "{network:?}");
2785 }
2786
2787 // FEAT-021 project group public dispatch (Phase 6)
2788
2789 #[test]
2790 fn feat021_project_entries_register_through_portable_bridge() {
2791 use codewhale_command_contract::handler::{CommandCapabilities, CommandHandler};
2792
2793 for (name, expected) in [
2794 (
2795 "init",
2796 CommandCapabilities::WORKSPACE
2797 .union(CommandCapabilities::PRESENTATION)
2798 .union(CommandCapabilities::BACKGROUND),
2799 ),
2800 ("lsp", CommandCapabilities::PROJECT),
2801 ("share", CommandCapabilities::SESSION_EXPORT),
2802 (
2803 "goal",
2804 CommandCapabilities::PROJECT.union(CommandCapabilities::PRESENTATION),
2805 ),
2806 ] {
2807 assert!(
2808 registry().has_contextual_handler(name),
2809 "/{name} must register through the portable bridge"
2810 );
2811 let handler = registry()
2812 .get(name)
2813 .expect("entry")
2814 .contextual_handler()
2815 .expect("contextual handler");
2816 let CommandHandler::Contextual { capabilities, .. } = handler else {
2817 panic!("/{name} must be contextual");
2818 };
2819 assert_eq!(capabilities, expected, "/{name} exact capability set");
2820 }
2821 }
2822
2823 #[test]
2824 fn feat021_project_commands_dispatch_through_public_seam() {
2825 let mut app = create_test_app();
2826 app.workspace = PathBuf::from(".");
2827
2828 // /init: creating message + SendMessage action.
2829 let init = execute("/init", &mut app);
2830 assert!(!init.is_error, "{init:?}");
2831 assert!(matches!(init.action, Some(AppAction::SendMessage(_))));
2832
2833 // /lsp status reaches the adapter through the public seam.
2834 let lsp = execute("/lsp status", &mut app);
2835 assert!(!lsp.is_error, "{lsp:?}");
2836 let lsp_msg = lsp.message.expect("lsp message");
2837 assert!(lsp_msg.contains("Language servers are off"), "{lsp_msg}");
2838
2839 // /share help is a safe no-op route.
2840 let share = execute("/share help", &mut app);
2841 assert!(!share.is_error, "{share:?}");
2842
2843 // /goal status without a goal prints usage (no panic).
2844 let goal = execute("/goal status", &mut app);
2845 assert!(!goal.is_error, "{goal:?}");
2846
2847 // Metadata bridges to the TUI localization ids.
2848 for (name, id) in [
2849 ("init", MessageId::CmdInitDescription),
2850 ("lsp", MessageId::CmdLspDescription),
2851 ("share", MessageId::CmdShareDescription),
2852 ("goal", MessageId::CmdGoalDescription),
2853 ] {
2854 let info = registry().get_info(name).expect("info");
2855 assert_eq!(info.description_id, id, "/{name} description bridge");
2856 }
2857 }
2858
2859 #[test]
2860 fn feat021_public_dispatch_never_panics_on_project_commands() {
2861 let mut app = create_test_app();
2862 app.workspace = PathBuf::from(".");
2863 for command in [
2864 "/init",
2865 "/init ",
2866 "/lsp",
2867 "/lsp status",
2868 "/lsp approve",
2869 "/lsp approve bogus",
2870 "/lsp revoke",
2871 "/lsp revoke bogus",
2872 "/lsp bogus",
2873 "/share",
2874 "/share help",
2875 "/share bogus",
2876 "/goal",
2877 "/goal status",
2878 "/goal pause",
2879 "/goal resume",
2880 "/goal done",
2881 "/goal bogus",
2882 "/goal 42",
2883 ] {
2884 let result = execute(command, &mut app);
2885 // Every path returns a result; none may panic.
2886 assert!(
2887 result.message.is_some() || result.action.is_some(),
2888 "{command}: {result:?}"
2889 );
2890 }
2891 }
2892
2893 // ---------------------------------------------------------------------
2894 // FEAT-019: public memory registration/dispatch and exact capability
2895 // declarations (Task 6.2). Tests enter through the registry and the
2896 // public `execute` seam and prove the memory group's portable entries.
2897 // ---------------------------------------------------------------------
2898
2899 /// App with an isolated temp workspace and memory enabled.
2900 fn memory_test_app(tmpdir: &tempfile::TempDir) -> App {
2901 let options = TuiOptions {
2902 memory_path: tmpdir.path().join("memory.md"),
2903 use_memory: true,
2904 ..crate::tui::test_support::test_tui_options(tmpdir.path())
2905 };
2906 App::new(options, &Config::default())
2907 }
2908
2909 #[test]
2910 fn feat019_memory_entries_are_registered_with_exact_capabilities() {
2911 for (name, expected) in [
2912 (
2913 "note",
2914 codewhale_command_contract::handler::CommandCapabilities::WORKSPACE,
2915 ),
2916 (
2917 "memory",
2918 codewhale_command_contract::handler::CommandCapabilities::WORKSPACE
2919 .union(codewhale_command_contract::handler::CommandCapabilities::MEMORY),
2920 ),
2921 ] {
2922 assert!(
2923 registry().has_contextual_handler(name),
2924 "/{name} must register through the portable bridge"
2925 );
2926 let handler = registry()
2927 .get(name)
2928 .expect("entry")
2929 .contextual_handler()
2930 .expect("contextual handler");
2931 let codewhale_command_contract::handler::CommandHandler::Contextual {
2932 capabilities,
2933 ..
2934 } = handler
2935 else {
2936 panic!("/{name} must be contextual");
2937 };
2938 assert_eq!(capabilities, expected, "/{name} exact capability set");
2939 assert!(
2940 !capabilities.contains(
2941 codewhale_command_contract::handler::CommandCapabilities::PRESENTATION
2942 ) && !capabilities
2943 .contains(codewhale_command_contract::handler::CommandCapabilities::MEDIA),
2944 "/{name} must not declare presentation or media"
2945 );
2946 }
2947 }
2948
2949 // ---------------------------------------------------------------------
2950 // FEAT-022: skills group registration + public dispatch (Task 6.2).
2951 // All four commands register through the portable bridge; frontier state
2952 // is asserted by the migration fixtures and live gate.
2953 // ---------------------------------------------------------------------
2954
2955 /// Seals the user's home so global skill discovery stays hermetic.
2956 fn feat022_scoped_home(_tmp: &tempfile::TempDir) -> crate::test_support::SealedHome {
2957 crate::test_support::SealedHome::new()
2958 }
2959
2960 fn feat022_test_app(tmp: &tempfile::TempDir) -> App {
2961 // The fixture's skills dir lives inside its workspace.
2962 crate::test_support::trust_workspace(tmp.path());
2963 let mut options = crate::tui::test_support::test_tui_options(tmp.path());
2964 options.skills_dir = tmp.path().join("skills");
2965 crate::tui::test_support::test_app_with_options(options)
2966 }
2967
2968 fn feat022_write_skill(dir: &std::path::Path, name: &str) {
2969 let skill_dir = dir.join(name);
2970 std::fs::create_dir_all(&skill_dir).unwrap();
2971 std::fs::write(
2972 skill_dir.join("SKILL.md"),
2973 format!("---\nname: {name}\ndescription: {name} skill\n---\n{name} instructions"),
2974 )
2975 .unwrap();
2976 }
2977
2978 #[test]
2979 fn feat022_all_four_skills_entries_are_registered_with_portable_handlers() {
2980 use codewhale_command_contract::handler::{CommandCapabilities, CommandHandler};
2981
2982 for (name, alias, expected) in [
2983 (
2984 "skills",
2985 Some("jinengliebiao"),
2986 CommandCapabilities::SKILL_GROUP,
2987 ),
2988 (
2989 "skill",
2990 Some("jineng"),
2991 CommandCapabilities::SKILL_GROUP.union(CommandCapabilities::SKILLS),
2992 ),
2993 ("review", Some("shencha"), CommandCapabilities::SKILL_GROUP),
2994 ("restore", None, CommandCapabilities::SKILL_GROUP),
2995 ] {
2996 let info = registry()
2997 .get_info(name)
2998 .unwrap_or_else(|| panic!("/{name} must be registered"));
2999 assert_eq!(info.name, name, "canonical name");
3000 let handler = registry()
3001 .get(name)
3002 .expect("entry")
3003 .contextual_handler()
3004 .expect("contextual handler");
3005 let CommandHandler::Contextual { capabilities, .. } = handler else {
3006 panic!("/{name} must be contextual");
3007 };
3008 assert_eq!(capabilities, expected, "/{name} exact capability set");
3009 if let Some(alias) = alias {
3010 assert!(
3011 registry().get_info(alias).is_some(),
3012 "/{name} alias {alias} must resolve"
3013 );
3014 }
3015 }
3016 }
3017
3018 #[test]
3019 fn feat019_note_dispatches_through_public_seam() {
3020 let tmpdir = tempfile::TempDir::new().unwrap();
3021 let mut app = memory_test_app(&tmpdir);
3022
3023 let appended = execute("/note hello from dispatch", &mut app);
3024 assert!(!appended.is_error, "{appended:?}");
3025 assert!(
3026 appended
3027 .message
3028 .as_deref()
3029 .is_some_and(|msg| msg.contains("Note appended to")),
3030 "{appended:?}"
3031 );
3032 let notes = tmpdir.path().join(".deepseek").join("notes.md");
3033 assert!(notes.exists(), "notes file written under the workspace");
3034 let content = std::fs::read_to_string(&notes).unwrap();
3035 assert!(content.contains("hello from dispatch"));
3036
3037 // Metadata bridges to the TUI localization id.
3038 let info = registry().get_info("note").expect("note info");
3039 assert_eq!(
3040 info.description_id,
3041 codewhale_localization::MessageId::CmdNoteDescription
3042 );
3043 }
3044
3045 #[test]
3046 fn feat019_memory_dispatches_through_public_seam() {
3047 let tmpdir = tempfile::TempDir::new().unwrap();
3048 let mut app = memory_test_app(&tmpdir);
3049
3050 let path = execute("/memory path", &mut app);
3051 assert!(!path.is_error, "{path:?}");
3052 // The native store root is a directory; memory.md is only the legacy
3053 // import anchor, no longer the authoritative path.
3054 assert_eq!(
3055 path.message.as_deref(),
3056 Some(tmpdir.path().join("memory").to_str().unwrap())
3057 );
3058
3059 // Native status reaches the real adapter through the public seam.
3060 let status = execute("/memory native status", &mut app);
3061 assert!(!status.is_error, "{status:?}");
3062 let msg = status.message.expect("status message");
3063 assert!(msg.contains("Native memory root:"), "{msg}");
3064
3065 let info = registry().get_info("memory").expect("memory info");
3066 assert_eq!(
3067 info.description_id,
3068 codewhale_localization::MessageId::CmdMemoryDescription
3069 );
3070 }
3071
3072 #[test]
3073 fn feat019_public_dispatch_never_panics_on_memory_commands() {
3074 let tmpdir = tempfile::TempDir::new().unwrap();
3075 let mut app = memory_test_app(&tmpdir);
3076 for command in [
3077 "/note",
3078 "/note ",
3079 "/memory",
3080 "/memory native bogus",
3081 "/memory wat",
3082 ] {
3083 let result = execute(command, &mut app);
3084 // Every path returns a result; none may panic.
3085 assert!(result.message.is_some(), "{command}: {result:?}");
3086 }
3087 }
3088
3089 #[test]
3090 fn feat022_skills_commands_dispatch_through_public_seam() {
3091 let tmp = tempfile::TempDir::new().unwrap();
3092 let _home = feat022_scoped_home(&tmp);
3093 let mut app = feat022_test_app(&tmp);
3094 std::fs::create_dir_all(tmp.path().join("skills")).unwrap();
3095 feat022_write_skill(&tmp.path().join("skills"), "demo");
3096
3097 // Bare /skills opens Plugins; explicit manage retains the mutation surface.
3098 let result = execute("/skills", &mut app);
3099 assert!(!result.is_error, "{result:?}");
3100 assert!(
3101 matches!(
3102 result.action,
3103 Some(crate::tui::app::AppAction::OpenExtensions {
3104 tab: crate::tui::views::extensions::ExtensionsTab::Skills
3105 })
3106 ),
3107 "{result:?}"
3108 );
3109
3110 assert!(matches!(
3111 execute("/skills manage", &mut app).action,
3112 Some(AppAction::OpenSkillsManager)
3113 ));
3114 let mcp_info = get_command_info("mcp").expect("registered MCP command");
3115 assert!(mcp_info.aliases.contains(&"mcps"));
3116 assert_eq!(get_command_info("mcps").unwrap().name, mcp_info.name);
3117 for command in ["/mcp", "/mcps"] {
3118 assert!(
3119 matches!(
3120 execute(command, &mut app).action,
3121 Some(AppAction::OpenExtensions {
3122 tab: crate::tui::views::extensions::ExtensionsTab::Mcp
3123 })
3124 ),
3125 "{command}"
3126 );
3127 }
3128
3129 // /skill activates the demo skill and sets active_skill.
3130 let result = execute("/skill demo", &mut app);
3131 assert!(!result.is_error, "{result:?}");
3132 assert!(result.message.unwrap().contains("Skill 'demo' activated."));
3133 assert!(app.active_skill.is_some());
3134
3135 // /restore with no snapshots shows the empty message.
3136 let result = execute("/restore", &mut app);
3137 assert!(!result.is_error, "{result:?}");
3138 assert!(result.message.unwrap().contains("No snapshots"));
3139
3140 // /review without a target prints usage.
3141 let result = execute("/review", &mut app);
3142 assert!(result.is_error, "{result:?}");
3143 assert!(result.message.unwrap().contains("Usage: /review"));
3144 }
3145
3146 #[test]
3147 fn feat022_aliases_dispatch_through_public_seam() {
3148 // All four aliases (jinengliebiao, jineng, shencha) resolve through the
3149 // registry to the same portable handlers as the canonical names.
3150 let tmp = tempfile::TempDir::new().unwrap();
3151 let _home = feat022_scoped_home(&tmp);
3152 let mut app = feat022_test_app(&tmp);
3153 std::fs::create_dir_all(tmp.path().join("skills")).unwrap();
3154 feat022_write_skill(&tmp.path().join("skills"), "demo");
3155
3156 let result = execute("/jinengliebiao", &mut app);
3157 assert!(
3158 matches!(
3159 result.action,
3160 Some(crate::tui::app::AppAction::OpenExtensions {
3161 tab: crate::tui::views::extensions::ExtensionsTab::Skills
3162 })
3163 ),
3164 "{result:?}"
3165 );
3166
3167 let result = execute("/jineng demo", &mut app);
3168 assert!(!result.is_error, "{result:?}");
3169 assert!(result.message.unwrap().contains("Skill 'demo' activated."));
3170
3171 let result = execute("/shencha", &mut app);
3172 assert!(result.is_error, "{result:?}");
3173 assert!(result.message.unwrap().contains("Usage: /review"));
3174 }
3175
3176 #[test]
3177 fn feat022_context_exposure_is_exact_per_d4() {
3178 // The test-only full envelope exposes every adapter; production
3179 // dispatch exposes only each handler's declared facets.
3180 // skills/review/restore consume only skill_group; skill also consumes
3181 // skills for cache refreshes.
3182 let tmp = tempfile::TempDir::new().unwrap();
3183 let _home = feat022_scoped_home(&tmp);
3184 let mut app = feat022_test_app(&tmp);
3185 let mut bundle = app.command_contexts();
3186 let parts = bundle.parts();
3187 assert!(parts.skill_group.is_some());
3188 assert!(parts.skills.is_some());
3189 // Missing-facet safety through the public seam is covered by the
3190 // handler-level tests; here we assert the envelope carries both.
3191 }
3192
3193 // ---------------------------------------------------------------------
3194 // FEAT-020 plugins group public dispatch (Phase 6)
3195 // ---------------------------------------------------------------------
3196
3197 /// App with an isolated temp workspace and a discovered plugin bundle.
3198 fn plugin_test_app(tmpdir: &tempfile::TempDir) -> App {
3199 // Write a minimal plugin bundle so the registry discovers real data.
3200 let bundle = tmpdir.path().join(".codewhale/plugins/demo");
3201 std::fs::create_dir_all(bundle.join("skills/hello")).unwrap();
3202 std::fs::write(
3203 bundle.join("plugin.toml"),
3204 "schema_version = 1\n[plugin]\nname = \"demo\"\nversion = \"1.0.0\"\ndescription = \"Import spreadsheet data safely\"\n[skills]\npath = \"skills\"\n",
3205 )
3206 .unwrap();
3207 std::fs::write(
3208 bundle.join("skills/hello/SKILL.md"),
3209 "---\nname: hello\ndescription: hello\n---\nbody\n",
3210 )
3211 .unwrap();
3212 let options = TuiOptions {
3213 ..crate::tui::test_support::test_tui_options(tmpdir.path())
3214 };
3215 let mut app = App::new(options, &Config::default());
3216 let discovery = codewhale_plugins::PluginDiscoveryContext::capture_pre_dotenv();
3217 app.plugin_registry = discovery.registry_for_workspace(tmpdir.path());
3218 app
3219 }
3220
3221 #[test]
3222 fn feat020_plugin_entry_is_registered_with_exact_capabilities() {
3223 let name = "plugin";
3224 assert!(
3225 registry().has_contextual_handler(name),
3226 "/{name} must register through the portable bridge"
3227 );
3228 let handler = registry()
3229 .get(name)
3230 .expect("entry")
3231 .contextual_handler()
3232 .expect("contextual handler");
3233 let codewhale_command_contract::handler::CommandHandler::Contextual {
3234 capabilities, ..
3235 } = handler
3236 else {
3237 panic!("/{name} must be contextual");
3238 };
3239 let expected = codewhale_command_contract::handler::CommandCapabilities::WORKSPACE
3240 .union(codewhale_command_contract::handler::CommandCapabilities::PRESENTATION)
3241 .union(codewhale_command_contract::handler::CommandCapabilities::PLUGIN)
3242 .union(codewhale_command_contract::handler::CommandCapabilities::SESSION_LIFECYCLE);
3243 assert_eq!(capabilities, expected, "/{name} exact capability set");
3244 // Undeclared facets stay absent.
3245 assert!(
3246 !capabilities.contains(codewhale_command_contract::handler::CommandCapabilities::MEDIA)
3247 );
3248 assert!(
3249 !capabilities
3250 .contains(codewhale_command_contract::handler::CommandCapabilities::MEMORY)
3251 );
3252 assert!(
3253 !capabilities
3254 .contains(codewhale_command_contract::handler::CommandCapabilities::SKILLS)
3255 );
3256 assert!(
3257 !capabilities
3258 .contains(codewhale_command_contract::handler::CommandCapabilities::PROJECT)
3259 );
3260 assert!(
3261 !capabilities
3262 .contains(codewhale_command_contract::handler::CommandCapabilities::SKILL_GROUP)
3263 );
3264 }
3265
3266 #[test]
3267 fn feat020_plugin_dispatches_through_public_seam() {
3268 let _home = crate::test_support::SealedHome::new();
3269 let tmpdir = tempfile::TempDir::new().unwrap();
3270 let mut app = plugin_test_app(&tmpdir);
3271
3272 // Bare action opens the extensions view (no panic).
3273 let bare = execute("/plugin", &mut app);
3274 assert!(bare.action.is_some(), "{bare:?}");
3275
3276 // List reaches the real adapter through the public seam.
3277 let list = execute("/plugin list", &mut app);
3278 assert!(!list.is_error, "{list:?}");
3279 let msg = list.message.expect("list message");
3280 assert!(msg.contains("demo"), "{msg}");
3281
3282 // Metadata bridges to the TUI localization id.
3283 let info = registry().get_info("plugin").expect("plugin info");
3284 assert_eq!(
3285 info.description_id,
3286 codewhale_localization::MessageId::CmdPluginDescription
3287 );
3288 }
3289
3290 #[test]
3291 fn feat020_public_dispatch_never_panics_on_plugin_commands() {
3292 let _home = crate::test_support::SealedHome::new();
3293 let tmpdir = tempfile::TempDir::new().unwrap();
3294 let mut app = plugin_test_app(&tmpdir);
3295 for command in [
3296 "/plugin",
3297 "/plugin ",
3298 "/plugin list",
3299 "/plugin show nope",
3300 "/plugin validate",
3301 "/plugin tools",
3302 "/plugin marketplace",
3303 "/plugin import kimi",
3304 "/plugin suggest",
3305 ] {
3306 let result = execute(command, &mut app);
3307 // Every path returns a result; none may panic.
3308 assert!(
3309 result.message.is_some() || result.action.is_some(),
3310 "{command}: {result:?}"
3311 );
3312 }
3313 }
3314
3315 // -----------------------------------------------------------------------
3316 // FEAT-023 Phase 6 (Task 6.2): the nine lifecycle registrations dispatch
3317 // through the public seam with exact capability declarations.
3318 // -----------------------------------------------------------------------
3319
3320 #[test]
3321 fn feat023_lifecycle_entries_register_through_portable_bridge() {
3322 use codewhale_command_contract::handler::{CommandCapabilities, CommandHandler};
3323
3324 for name in ["branch", "fork", "load", "new", "save", "sessions", "tree"] {
3325 assert!(
3326 registry().has_contextual_handler(name),
3327 "/{name} must register through the portable bridge"
3328 );
3329 let handler = registry()
3330 .get(name)
3331 .expect("entry")
3332 .contextual_handler()
3333 .expect("contextual handler");
3334 let CommandHandler::Contextual { capabilities, .. } = handler else {
3335 panic!("/{name} must be contextual");
3336 };
3337 assert_eq!(
3338 capabilities,
3339 CommandCapabilities::SESSION_LIFECYCLE,
3340 "/{name} declares lifecycle authority only"
3341 );
3342 }
3343 // Pure handlers register through the bridge with no host bundle.
3344 for name in ["compact", "purge"] {
3345 assert!(
3346 registry().has_contextual_handler(name),
3347 "/{name} must register through the portable bridge"
3348 );
3349 let handler = registry()
3350 .get(name)
3351 .expect("entry")
3352 .contextual_handler()
3353 .expect("pure handler");
3354 assert!(
3355 matches!(handler, CommandHandler::Pure(_)),
3356 "/{name} must be pure (no host context bundle)"
3357 );
3358 }
3359 // FEAT-026 completes the final session command adoption.
3360 assert!(
3361 registry().has_contextual_handler("structcopy"),
3362 "/structcopy must use the shared command boundary"
3363 );
3364 }
3365
3366 // ---------------------------------------------------------------------
3367 // FEAT-024: session control entries register through the portable bridge
3368 // (D3/D6) — five declare SESSION_CONTROL only; `/remote-env` and `/color`
3369 // declare control plus presentation; export/structcopy have independent
3370 // authority.
3371 // ---------------------------------------------------------------------
3372
3373 #[test]
3374 fn feat024_control_entries_register_through_portable_bridge() {
3375 use codewhale_command_contract::handler::{CommandCapabilities, CommandHandler};
3376
3377 for name in ["relay", "rename", "resume", "rc", "title"] {
3378 assert!(
3379 registry().has_contextual_handler(name),
3380 "/{name} must register through the portable bridge"
3381 );
3382 let handler = registry()
3383 .get(name)
3384 .expect("entry")
3385 .contextual_handler()
3386 .expect("contextual handler");
3387 let CommandHandler::Contextual { capabilities, .. } = handler else {
3388 panic!("/{name} must be contextual");
3389 };
3390 assert_eq!(
3391 capabilities,
3392 CommandCapabilities::SESSION_CONTROL,
3393 "/{name} declares control authority only"
3394 );
3395 }
3396 for name in ["remote-env", "color"] {
3397 assert!(
3398 registry().has_contextual_handler(name),
3399 "/{name} must register through the portable bridge"
3400 );
3401 let handler = registry()
3402 .get(name)
3403 .expect("entry")
3404 .contextual_handler()
3405 .expect("contextual handler");
3406 let CommandHandler::Contextual { capabilities, .. } = handler else {
3407 panic!("/{name} must be contextual");
3408 };
3409 assert_eq!(
3410 capabilities,
3411 CommandCapabilities::SESSION_CONTROL.union(CommandCapabilities::PRESENTATION),
3412 "/{name} declares control plus presentation only"
3413 );
3414 }
3415 // FEAT-026 also registers structcopy through its own narrow boundary.
3416 assert!(
3417 registry().has_contextual_handler("structcopy"),
3418 "/structcopy must use the shared command boundary"
3419 );
3420 }
3421
3422 #[test]
3423 fn feat023_lifecycle_commands_dispatch_through_public_seam() {
3424 let _home = crate::test_support::SealedHome::new();
3425 let mut app = create_test_app();
3426 app.workspace = PathBuf::from(".");
3427
3428 // Pure handlers need no App machinery.
3429 let compact = execute("/compact the auth refactor", &mut app);
3430 assert_eq!(
3431 compact.message.as_deref(),
3432 Some("Making room (focus: the auth refactor)…")
3433 );
3434 assert!(matches!(
3435 compact.action,
3436 Some(AppAction::CompactContext { focus: Some(ref f) }) if f == "the auth refactor"
3437 ));
3438 let purge = execute("/purge", &mut app);
3439 assert_eq!(
3440 purge.message.as_deref(),
3441 Some("Agent context purge triggered...")
3442 );
3443 assert!(matches!(purge.action, Some(AppAction::PurgeContext)));
3444
3445 // Contextual handler reaches the adapter through the seam; /tree on a
3446 // bare app reports no active session.
3447 let tree = execute("/tree", &mut app);
3448 assert!(
3449 tree.message
3450 .as_deref()
3451 .unwrap_or_default()
3452 .contains("No active session"),
3453 "{tree:?}"
3454 );
3455
3456 // Subcommand routing and usage errors stay byte-exact.
3457 let bad = execute("/sessions teleport", &mut app);
3458 assert!(
3459 bad.message
3460 .as_deref()
3461 .unwrap_or_default()
3462 .contains("unknown subcommand `teleport`"),
3463 "{bad:?}"
3464 );
3465 let branch_usage = execute("/branch", &mut app);
3466 assert!(
3467 branch_usage
3468 .message
3469 .as_deref()
3470 .unwrap_or_default()
3471 .starts_with("Usage: /branch <entry_id>"),
3472 "{branch_usage:?}"
3473 );
3474 }
3475
3476 #[test]
3477 fn feat024_control_commands_dispatch_through_public_seam() {
3478 let _home = crate::test_support::SealedHome::new();
3479 let mut app = create_test_app();
3480 app.workspace = PathBuf::from(".");
3481
3482 // /relay composes through the control adapter and emits the bounded
3483 // SendMessage action; only SESSION_CONTROL is exposed.
3484 let relay = execute("/relay handoff notes", &mut app);
3485 assert_eq!(
3486 relay.message.as_deref(),
3487 Some("Preparing session relay at .codewhale/handoff.md...")
3488 );
3489 let relay_message = match relay.action {
3490 Some(AppAction::SendMessage(message)) => message,
3491 other => panic!("expected SendMessage, got {other:?}"),
3492 };
3493 assert!(relay_message.contains("Create a compact session relay (接力)"));
3494 assert!(relay_message.contains("- Requested relay focus: handoff notes"));
3495
3496 // /rc status reaches the remote-control service through the facet.
3497 let rc = execute("/rc status", &mut app);
3498 assert_eq!(rc.message.as_deref(), Some("Remote control: off"));
3499
3500 // /remote-env bare overview is localized through the presentation
3501 // facet with the exact source-custody boundary copy.
3502 let remote_env = execute("/remote-env", &mut app);
3503 assert!(
3504 remote_env
3505 .message
3506 .as_deref()
3507 .unwrap_or_default()
3508 .contains("Hosted Work starts a new environment"),
3509 "{remote_env:?}"
3510 );
3511
3512 // /rename and /title validation boundaries stay exact over the seam.
3513 let rename = execute("/rename", &mut app);
3514 assert_eq!(
3515 rename.message.as_deref(),
3516 Some("Error: Usage: /rename <new title>")
3517 );
3518 let title = execute("/title", &mut app);
3519 assert!(
3520 title
3521 .message
3522 .as_deref()
3523 .unwrap_or_default()
3524 .contains("Window title: [unset]"),
3525 "{title:?}"
3526 );
3527
3528 // Bare /resume opens the picker through the adapter.
3529 let resume = execute("/resume", &mut app);
3530 assert!(!resume.is_error);
3531 assert!(resume.action.is_none());
3532 assert!(resume.message.is_none());
3533 }
3534
3535 // ---------------------------------------------------------------------
3536 // ---------------------------------------------------------------------
3537
3538 #[test]
3539 fn feat025_export_entry_registers_through_portable_bridge() {
3540 use codewhale_command_contract::handler::{CommandCapabilities, CommandHandler};
3541
3542 assert!(
3543 registry().has_contextual_handler("export"),
3544 "/export must register through the portable bridge"
3545 );
3546 assert!(
3547 registry().has_contextual_handler("daochu"),
3548 "/daochu must resolve to the same portable bridge entry"
3549 );
3550
3551 let handler = registry()
3552 .get("export")
3553 .expect("entry")
3554 .contextual_handler()
3555 .expect("contextual handler");
3556 let CommandHandler::Contextual { capabilities, .. } = handler else {
3557 panic!("/export must be contextual");
3558 };
3559 assert_eq!(
3560 capabilities,
3561 CommandCapabilities::SESSION_EXPORT,
3562 "/export declares export authority only"
3563 );
3564
3565 let declarers = |capability| {
3566 let mut names: Vec<_> = registry().iter().filter(|command| {
3567 matches!(command.contextual_handler(), Some(CommandHandler::Contextual { capabilities, .. }) if capabilities.contains(capability))
3568 }).map(|command| command.info().name).collect();
3569 names.sort_unstable();
3570 names
3571 };
3572 assert_eq!(
3573 declarers(CommandCapabilities::SESSION_EXPORT),
3574 ["export", "share"]
3575 );
3576 assert_eq!(declarers(CommandCapabilities::RESPONSE_COPY), ["copy"]);
3577
3578 assert!(
3579 registry().has_contextual_handler("structcopy"),
3580 "/structcopy must use the shared command boundary"
3581 );
3582 }
3583
3584 #[test]
3585 fn feat025_export_registered_handler_fails_safely_without_authority() {
3586 // The dispatcher builds the envelope from the declared capabilities and
3587 // calls this exact handler object. A narrower envelope that omits the
3588 // export facet must return the safe error before parsing or performing
3589 // any projection, clipboard, recovery, resolution, or write operation.
3590 let handler = registry()
3591 .get("export")
3592 .expect("entry")
3593 .contextual_handler()
3594 .expect("contextual handler");
3595 let codewhale_command_contract::handler::CommandHandler::Contextual {
3596 handler: contextual,
3597 ..
3598 } = handler
3599 else {
3600 panic!("/export must be contextual");
3601 };
3602
3603 for arg in [None, Some("clipboard"), Some("file out.md")] {
3604 let result = contextual(
3605 codewhale_command_contract::handler::CommandContexts::empty(),
3606 arg,
3607 );
3608 assert!(result.is_error, "{arg:?} must fail without authority");
3609 assert_eq!(
3610 result.message.as_deref(),
3611 Some("Error: Command capability unavailable: session_export"),
3612 "{arg:?} must keep the exact safe error"
3613 );
3614 assert!(result.action.is_none(), "{arg:?} must produce no action");
3615 }
3616 }
3617 }
3618
3619 #[cfg(test)]
3620 mod config_policy_host_tests;
3621 #[cfg(test)]
3622 mod config_policy_permissions_tests;
3623 #[cfg(test)]
3624 mod config_policy_status_tests;
3625
3625 lines RUST