返回 CodeWhale
user_registry.rs
根目录 / crates / tui / src / commands / user_registry.rs
1 //! Dedicated registry for user-defined markdown slash commands.
2 //!
3 //! This module owns the user-command boundary. Built-in command metadata and
4 //! dispatch remain in the normal command registry; user commands are loaded
5 //! from markdown files into this registry and are attempted before built-ins.
6
7 use std::collections::{HashMap, HashSet};
8 use std::path::{Path, PathBuf};
9 use std::sync::{OnceLock, RwLock};
10 use std::time::SystemTime;
11
12 use crate::tui::app::{App, AppAction};
13 use codewhale_engine::tools::goal::GoalStatus;
14
15 use super::CommandResult;
16 use super::user_commands;
17
18 static USER_COMMAND_REGISTRY: OnceLock<RwLock<UserCommandRegistryState>> = OnceLock::new();
19
20 #[derive(Debug, Default)]
21 struct UserCommandRegistryState {
22 initialized: bool,
23 workspace: Option<PathBuf>,
24 command_dirs_snapshot: Vec<CommandDirSnapshot>,
25 plugins: HashMap<
26 Option<PathBuf>,
27 (
28 Vec<codewhale_plugins::runtime::PluginComponentSource>,
29 Vec<String>,
30 ),
31 >,
32 /// `extension_host::command::epoch()` when `registry` was built: it
33 /// reloads when the live extension commands may have changed.
34 extension_epoch: u64,
35 registry: UserCommandRegistry,
36 snapshot_checked_at: std::sync::Mutex<Option<std::time::Instant>>,
37 }
38
39 #[cfg(not(test))]
40 const SNAPSHOT_RECHECK_INTERVAL: std::time::Duration = std::time::Duration::from_secs(1);
41 #[cfg(test)]
42 const SNAPSHOT_RECHECK_INTERVAL: std::time::Duration = std::time::Duration::ZERO;
43
44 impl UserCommandRegistryState {
45 fn checked_recently(&self) -> bool {
46 self.snapshot_checked_at
47 .lock()
48 .unwrap_or_else(std::sync::PoisonError::into_inner)
49 .is_some_and(|at| at.elapsed() < SNAPSHOT_RECHECK_INTERVAL)
50 }
51
52 fn mark_checked(&self) {
53 *self
54 .snapshot_checked_at
55 .lock()
56 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(std::time::Instant::now());
57 }
58 }
59
60 #[derive(Debug, Clone, PartialEq, Eq)]
61 struct CommandDirSnapshot {
62 path: PathBuf,
63 modified: Option<SystemTime>,
64 files: Vec<CommandFileSnapshot>,
65 }
66
67 #[derive(Debug, Clone, PartialEq, Eq)]
68 struct CommandFileSnapshot {
69 path: PathBuf,
70 modified: Option<SystemTime>,
71 len: u64,
72 }
73
74 #[derive(Debug, Clone, PartialEq, Eq)]
75 pub struct UserCommandMetadata {
76 pub name: String,
77 pub body: String,
78 pub description: Option<String>,
79 pub usage: Option<String>,
80 pub arguments: Option<String>,
81 pub argument_hint: Option<String>,
82 pub allowed_tools: Option<Vec<String>>,
83 pub pausable: bool,
84 pub aliases: Vec<String>,
85 pub hidden: bool,
86 pub plugin_authority: Option<codewhale_config::PluginAuthority>,
87 pub workspace_sourced: bool,
88 /// Set for a command contributed by an extension-host plugin: it runs in
89 /// the host (`command/run`) instead of expanding `body`.
90 pub extension: Option<codewhale_engine::extension_host::command::ExtensionCommandRef>,
91 }
92
93 impl UserCommandMetadata {
94 /// User-facing invocation syntax. `argument-hint` remains the legacy
95 /// fallback for existing command files; `arguments` is the final fallback
96 /// when no complete `usage` string is supplied.
97 pub(crate) fn display_usage(&self) -> Option<&str> {
98 [&self.usage, &self.argument_hint, &self.arguments]
99 .into_iter()
100 .filter_map(Option::as_deref)
101 .find(|value| !value.trim().is_empty())
102 .map(str::trim)
103 }
104
105 /// Whether selecting this command should leave the composer open for
106 /// arguments. These fields describe presentation only; dispatch keeps the
107 /// existing permissive `$ARGUMENTS`/`$1` template semantics.
108 pub(crate) fn takes_arguments(&self) -> bool {
109 self.arguments
110 .as_deref()
111 .is_some_and(|value| !value.trim().is_empty())
112 // Preserve the legacy contract exactly: the presence of
113 // `argument-hint`, including an explicitly empty value, made the
114 // palette insert rather than immediately execute the command.
115 || self.argument_hint.is_some()
116 || self
117 .usage
118 .as_deref()
119 .is_some_and(|usage| usage_describes_arguments(&self.name, usage))
120 }
121 }
122
123 #[derive(Debug, Clone, PartialEq, Eq)]
124 pub struct LoadError {
125 pub path: PathBuf,
126 pub message: String,
127 }
128
129 #[derive(Debug, Clone, Default)]
130 pub struct UserCommandRegistry {
131 commands: HashMap<String, UserCommandMetadata>,
132 aliases: HashMap<String, String>,
133 load_errors: Vec<LoadError>,
134 invalid_commands: HashMap<String, String>,
135 }
136
137 impl UserCommandRegistry {
138 pub fn new() -> Self {
139 Self::default()
140 }
141
142 #[cfg(test)]
143 pub fn load(workspace: Option<&Path>) -> Self {
144 // The user_commands module is the permanent lower-level file scanning
145 // and parsing boundary; this registry owns metadata, shadowing, and
146 // dispatch. See docs/architecture/command-dispatch.md.
147 Self::load_with_sources(
148 &user_commands::commands_dirs(workspace),
149 &user_commands::workflow_dirs(workspace),
150 &[],
151 &[],
152 )
153 }
154
155 pub(crate) fn load_with_sources(
156 md_dirs: &[PathBuf],
157 workflow_dirs: &[PathBuf],
158 plugin_sources: &[codewhale_plugins::runtime::PluginComponentSource],
159 plugin_errors: &[String],
160 ) -> Self {
161 let mut registry = Self::load_from_paths(md_dirs);
162
163 // Saved workflows become slash commands after explicit .md commands,
164 // so a hand-written command with the same name always wins without a
165 // noisy duplicate-definition warning.
166 let mut workflow_entries: Vec<CommandSourceEntry> = Vec::new();
167 for dir in workflow_dirs {
168 for (name, content, path) in user_commands::load_workflow_commands_from_dir(dir) {
169 if registry.get(&name).is_none()
170 && !workflow_entries
171 .iter()
172 .any(|existing| existing.name == name)
173 {
174 workflow_entries.push(CommandSourceEntry::plain(name, content, path));
175 }
176 }
177 }
178 registry.load_from_entries(workflow_entries);
179 for error in plugin_errors {
180 registry.record_load_error(PathBuf::from("plugin-runtime"), error.clone());
181 }
182 let mut plugin_entries = Vec::new();
183 for source in plugin_sources {
184 for (name, content, path) in
185 user_commands::load_command_entries_from_component(&source.path)
186 {
187 plugin_entries.push(CommandSourceEntry {
188 name,
189 content,
190 path,
191 plugin_authority: Some(source.authority.clone()),
192 workspace_sourced: false,
193 });
194 }
195 }
196 registry.load_from_entries(plugin_entries);
197 registry
198 }
199
200 pub(crate) fn load_from_paths(paths: &[PathBuf]) -> Self {
201 let mut loaded = Vec::new();
202 let mut seen = HashSet::new();
203 let mut registry = Self::new();
204
205 for dir in paths {
206 let (mut directory_commands, dir_errors) =
207 user_commands::load_commands_from_dir_with_errors(dir);
208 for (path, message) in dir_errors {
209 registry.record_load_error(path, message);
210 }
211 directory_commands.sort_by(|a, b| a.0.cmp(&b.0));
212 for (name, content) in directory_commands {
213 let canonical = normalize_name(&name);
214 if seen.insert(canonical.clone()) {
215 loaded.push(CommandSourceEntry::plain(
216 name,
217 content,
218 dir.join(format!("{canonical}.md")),
219 ));
220 } else {
221 registry.record_load_error(
222 dir.join(format!("{canonical}.md")),
223 format!(
224 "User command '/{canonical}' is defined more than once; using the first definition"
225 ),
226 );
227 }
228 }
229 }
230 registry.load_from_entries(loaded);
231 registry
232 }
233
234 #[cfg(test)]
235 pub fn from_loaded(commands: Vec<(String, String)>) -> Self {
236 let mut registry = Self::new();
237 let loaded = commands
238 .into_iter()
239 .map(|(name, content)| {
240 let path = PathBuf::from(format!("{}.md", normalize_name(&name)));
241 CommandSourceEntry {
242 workspace_sourced: false,
243 ..CommandSourceEntry::plain(name, content, path)
244 }
245 })
246 .collect();
247 registry.load_from_entries(loaded);
248 registry
249 }
250
251 fn load_from_entries(&mut self, commands: Vec<CommandSourceEntry>) {
252 let parsed_commands = commands
253 .into_iter()
254 .map(|entry| {
255 let (mut metadata, errors) =
256 parse_metadata(entry.name, &entry.content, &entry.path);
257 metadata.plugin_authority = entry.plugin_authority;
258 metadata.workspace_sourced = entry.workspace_sourced;
259 (metadata, errors, entry.path, entry.workspace_sourced)
260 })
261 .collect::<Vec<_>>();
262 let canonical_names = parsed_commands
263 .iter()
264 .map(|(metadata, _, _, _)| metadata.name.clone())
265 .collect::<HashSet<_>>();
266
267 for (mut metadata, errors, path, workspace_sourced) in parsed_commands {
268 for error in &errors {
269 self.record_load_error(error.path.clone(), error.message.clone());
270 }
271
272 // A repository-supplied command must not stand in for a protected
273 // built-in: a committed `.claude/commands/trust.md` would
274 // otherwise answer `/trust` or `/undo` with its own prompt. Plugin
275 // commands carry reviewed authority; user-global commands are the
276 // user's choice.
277 if workspace_sourced {
278 if is_protected_builtin_command(&metadata.name) {
279 self.record_load_error(
280 path.clone(),
281 format!(
282 "Workspace command '/{}' would replace a protected built-in command and was not loaded; rename it",
283 metadata.name
284 ),
285 );
286 continue;
287 }
288 metadata.aliases.retain(|alias| {
289 let builtin = is_protected_builtin_command(alias);
290 if builtin {
291 self.load_errors.push(LoadError {
292 path: path.clone(),
293 message: format!(
294 "Workspace command alias '/{alias}' for '/{}' would replace a protected built-in command; ignoring this alias",
295 metadata.name
296 ),
297 });
298 }
299 !builtin
300 });
301 }
302
303 if self.commands.contains_key(&metadata.name) {
304 self.record_load_error(
305 path.clone(),
306 format!(
307 "User command '/{}' is defined more than once; using the first definition",
308 metadata.name
309 ),
310 );
311 continue;
312 }
313
314 // A malformed losing duplicate must not poison the valid command
315 // that already won precedence. Only the selected definition owns
316 // the dispatch-time error for its canonical name and aliases.
317 for error in errors {
318 self.invalid_commands
319 .entry(metadata.name.clone())
320 .or_insert(error.message);
321 }
322
323 let mut accepted_aliases = Vec::with_capacity(metadata.aliases.len());
324 for alias in &metadata.aliases {
325 let alias = alias.to_ascii_lowercase();
326 if canonical_names.contains(&alias) {
327 self.record_load_error(
328 path.clone(),
329 format!(
330 "User command alias '/{alias}' for '/{}' duplicates canonical user command '/{alias}'; ignoring this alias",
331 metadata.name
332 ),
333 );
334 continue;
335 }
336 if let Some(existing) = self.aliases.get(&alias) {
337 self.record_load_error(
338 path.clone(),
339 format!(
340 "User command alias '/{alias}' for '/{}' duplicates user command '/{existing}'; using the first alias definition",
341 metadata.name
342 ),
343 );
344 continue;
345 }
346 self.aliases.insert(alias.clone(), metadata.name.clone());
347 accepted_aliases.push(alias);
348 }
349 // Discovery surfaces consume metadata directly. Keep it aligned
350 // with the dispatch map so a rejected alias is never advertised
351 // by help, command palettes, or slash completion.
352 metadata.aliases = accepted_aliases;
353
354 self.commands.insert(metadata.name.clone(), metadata);
355 }
356 }
357
358 fn record_load_error(&mut self, path: PathBuf, message: String) {
359 self.load_errors.push(LoadError { path, message });
360 }
361
362 /// Load commands contributed by extension-host plugins. They go last, so
363 /// a built-in, a user, workspace or manifest command with the same name
364 /// always wins: an extension command never shadows another command, and
365 /// the one it loses to is named in a load error.
366 pub(crate) fn load_extension_commands(
367 &mut self,
368 commands: Vec<codewhale_engine::extension_host::command::ExtensionCommandEntry>,
369 ) {
370 for entry in commands {
371 let registration = &entry.registration;
372 let name = registration.name.to_ascii_lowercase();
373 let origin = PathBuf::from(format!("extension:{}", registration.plugin_name));
374 if super::registry().get(&name).is_some() {
375 self.record_load_error(
376 origin,
377 format!(
378 "Plugin command '/{name}' collides with a built-in command and was not loaded"
379 ),
380 );
381 continue;
382 }
383 if self.commands.contains_key(&name) || self.aliases.contains_key(&name) {
384 self.record_load_error(
385 origin,
386 format!(
387 "Plugin command '/{name}' collides with another command; using the other definition"
388 ),
389 );
390 continue;
391 }
392 let reference = entry.reference();
393 self.commands.insert(
394 name.clone(),
395 UserCommandMetadata {
396 name,
397 // Never expanded: dispatch runs the command in the host.
398 body: String::new(),
399 description: Some(registration.description.clone()),
400 usage: None,
401 arguments: None,
402 argument_hint: registration.argument_hint.clone(),
403 allowed_tools: None,
404 pausable: false,
405 aliases: Vec::new(),
406 hidden: false,
407 plugin_authority: Some(entry.authority),
408 workspace_sourced: false,
409 extension: Some(reference),
410 },
411 );
412 }
413 }
414
415 pub fn get(&self, name: &str) -> Option<&UserCommandMetadata> {
416 self.get_unchecked(name)
417 .filter(|command| plugin_command_is_current(command))
418 }
419
420 fn get_unchecked(&self, name: &str) -> Option<&UserCommandMetadata> {
421 let key = normalize_name(name);
422 self.commands.get(&key).or_else(|| {
423 self.aliases
424 .get(&key)
425 .and_then(|canonical| self.commands.get(canonical))
426 })
427 }
428
429 #[cfg(test)]
430 pub fn get_by_alias(&self, alias: &str) -> Option<&UserCommandMetadata> {
431 let key = normalize_name(alias);
432 self.aliases
433 .get(&key)
434 .and_then(|canonical| self.commands.get(canonical))
435 .filter(|command| plugin_command_is_current(command))
436 }
437
438 #[cfg(test)]
439 pub fn names(&self) -> Vec<String> {
440 let mut names: Vec<String> = self
441 .commands
442 .values()
443 .filter(|command| plugin_command_is_current(command))
444 .map(|command| command.name.clone())
445 .collect();
446 names.sort();
447 names
448 }
449
450 pub fn iter(&self) -> impl Iterator<Item = &UserCommandMetadata> {
451 self.commands
452 .values()
453 .filter(|command| plugin_command_is_current(command))
454 }
455
456 #[cfg(test)]
457 pub fn is_valid(&self) -> bool {
458 self.load_errors.is_empty()
459 }
460
461 #[cfg(test)]
462 pub fn load_errors(&self) -> &[LoadError] {
463 &self.load_errors
464 }
465
466 pub(crate) fn dispatch_error(&self, name: &str) -> Option<String> {
467 let key = normalize_name(name);
468 self.invalid_commands.get(&key).cloned().or_else(|| {
469 self.aliases
470 .get(&key)
471 .and_then(|canonical| self.invalid_commands.get(canonical))
472 .cloned()
473 })
474 }
475 }
476
477 pub(crate) fn resolved_command_name(name: String, content: &str, path: &Path) -> String {
478 parse_metadata(name, content, path).0.name
479 }
480
481 fn parse_metadata(
482 name: String,
483 content: &str,
484 path: &Path,
485 ) -> (UserCommandMetadata, Vec<LoadError>) {
486 let filename_name = normalize_name(&name);
487 let (metadata, body) = user_commands::parse_frontmatter(content);
488 let mut command = UserCommandMetadata {
489 name: filename_name.clone(),
490 body: body.to_string(),
491 description: None,
492 usage: None,
493 arguments: None,
494 argument_hint: None,
495 allowed_tools: None,
496 pausable: false,
497 aliases: Vec::new(),
498 hidden: false,
499 plugin_authority: None,
500 workspace_sourced: false,
501 extension: None,
502 };
503 let mut configured_name = None;
504
505 for (key, value) in metadata {
506 match key.as_str() {
507 "name" => configured_name = Some(value),
508 "description" => command.description = Some(value),
509 "usage" => command.usage = Some(value),
510 "arguments" => command.arguments = Some(value),
511 "argument-hint" => command.argument_hint = Some(value),
512 "allowed-tools" => {
513 command.allowed_tools = Some(user_commands::parse_allowed_tools(&value));
514 }
515 "pausable" => command.pausable = value.trim().eq_ignore_ascii_case("true"),
516 "aliases" | "alias" => {
517 command.aliases = value
518 .split(',')
519 .map(normalize_name)
520 .filter(|alias| !alias.is_empty())
521 .collect();
522 }
523 "hidden" => command.hidden = value.trim().eq_ignore_ascii_case("true"),
524 _ => {}
525 }
526 }
527
528 let mut errors = Vec::new();
529 if let Some(configured_name) = configured_name {
530 if let Some(normalized) = normalize_configured_name(&configured_name) {
531 command.name = normalized;
532 } else {
533 errors.push(LoadError {
534 path: path.to_path_buf(),
535 message: format!(
536 "User command '/{filename_name}' has invalid frontmatter name {configured_name:?}; expected one slash-command token"
537 ),
538 });
539 }
540 }
541 errors.extend(validate_command_content(&command.name, content, path));
542
543 (command, errors)
544 }
545
546 #[derive(Debug, Clone)]
547 struct CommandSourceEntry {
548 name: String,
549 content: String,
550 path: PathBuf,
551 plugin_authority: Option<codewhale_config::PluginAuthority>,
552 /// Came from a workspace (repository) directory rather than the user's
553 /// own global store or a reviewed plugin.
554 workspace_sourced: bool,
555 }
556
557 impl CommandSourceEntry {
558 fn plain(name: String, content: String, path: PathBuf) -> Self {
559 let workspace_sourced = !user_commands::is_user_global_command_source(&path);
560 Self {
561 name,
562 content,
563 path,
564 plugin_authority: None,
565 workspace_sourced,
566 }
567 }
568 }
569
570 /// Built-ins a workspace command may never stand in for: the ones that grant
571 /// or revoke authority, hold credentials, or undo and discard work. A
572 /// repository command answering `/trust` or `/undo` with its own prompt would
573 /// make the user believe an action happened that did not. Other built-ins
574 /// (`/help`, `/review`, …) stay shadowable, as FEAT-011/012 specify.
575 const PROTECTED_BUILTINS: &[&str] = &[
576 "auth",
577 "auto",
578 "config",
579 "connect",
580 "constitution",
581 "disconnect",
582 "hooks",
583 "login",
584 "logout",
585 "lsp",
586 "mcp",
587 "mode",
588 "network",
589 "permissions",
590 "plug",
591 "plugin",
592 "profile",
593 "provider",
594 "purge",
595 "rc",
596 "relay",
597 "remote-env",
598 "restore",
599 "sessions",
600 "settings",
601 "setup",
602 "share",
603 "system",
604 "trust",
605 "undo",
606 "update",
607 "workspace",
608 ];
609
610 /// Whether `name` (a canonical name or any alias, including the fixed mode
611 /// aliases dispatched ahead of the registry) resolves to a protected built-in.
612 fn is_protected_builtin_command(name: &str) -> bool {
613 let name = name.to_ascii_lowercase();
614 if name == "jihua" {
615 return true;
616 }
617 super::registry()
618 .get(&name)
619 .is_some_and(|command| PROTECTED_BUILTINS.contains(&command.info().name))
620 }
621
622 fn plugin_command_is_current(command: &UserCommandMetadata) -> bool {
623 command.plugin_authority.as_ref().is_none_or(|authority| {
624 codewhale_plugins::registry::verify_plugin_state_authority(authority).is_ok()
625 })
626 }
627
628 fn validate_command_content(canonical: &str, content: &str, path: &Path) -> Vec<LoadError> {
629 let mut errors = Vec::new();
630 if canonical.is_empty() {
631 errors.push(LoadError {
632 path: path.to_path_buf(),
633 message: "User command has an empty command name".to_string(),
634 });
635 }
636 if content.trim().is_empty() {
637 errors.push(LoadError {
638 path: path.to_path_buf(),
639 message: format!("User command '/{canonical}' is empty"),
640 });
641 }
642
643 let Some(first_line_end) = content.find('\n') else {
644 return errors;
645 };
646 let first = content[..first_line_end].trim_end_matches('\r');
647 if !is_frontmatter_delimiter(first.trim()) {
648 return errors;
649 }
650
651 let mut saw_closing = false;
652 for raw_line in content[first_line_end + 1..].split_inclusive('\n') {
653 let line = raw_line.trim_end_matches(['\r', '\n']);
654 let trimmed = line.trim();
655 if is_frontmatter_delimiter(trimmed) {
656 saw_closing = true;
657 break;
658 }
659 if trimmed.is_empty() {
660 continue;
661 }
662 if let Some((key, _)) = line.split_once(':')
663 && !key.trim().is_empty()
664 {
665 continue;
666 }
667 errors.push(LoadError {
668 path: path.to_path_buf(),
669 message: format!(
670 "User command '/{canonical}' has invalid frontmatter line {trimmed:?}; expected key: value"
671 ),
672 });
673 break;
674 }
675
676 if !saw_closing {
677 errors.push(LoadError {
678 path: path.to_path_buf(),
679 message: format!(
680 "User command '/{canonical}' has invalid frontmatter; missing closing --- delimiter"
681 ),
682 });
683 }
684
685 errors
686 }
687
688 fn is_frontmatter_delimiter(value: &str) -> bool {
689 value.chars().all(|ch| ch == '-') && value.len() >= 3
690 }
691
692 fn normalize_name(name: &str) -> String {
693 name.trim().trim_start_matches('/').to_ascii_lowercase()
694 }
695
696 fn normalize_configured_name(name: &str) -> Option<String> {
697 let name = name.trim();
698 let name = name.strip_prefix('/').unwrap_or(name);
699 (!name.is_empty() && !name.contains('/') && !name.contains(char::is_whitespace))
700 .then(|| name.to_ascii_lowercase())
701 }
702
703 pub(crate) fn usage_describes_arguments(name: &str, usage: &str) -> bool {
704 let usage = usage.trim();
705 if usage.is_empty() {
706 return false;
707 }
708 let bare_usage = usage.trim_start_matches('/');
709 !bare_usage.eq_ignore_ascii_case(name)
710 }
711
712 fn normalize_workspace(workspace: Option<&Path>) -> Option<PathBuf> {
713 workspace.map(Path::to_path_buf)
714 }
715
716 #[cfg(test)]
717 fn command_dirs_snapshot(workspace: Option<&Path>) -> Vec<CommandDirSnapshot> {
718 command_dirs_snapshot_with_plugins(workspace, &[])
719 }
720
721 fn command_dirs_snapshot_with_plugins(
722 workspace: Option<&Path>,
723 plugin_sources: &[codewhale_plugins::runtime::PluginComponentSource],
724 ) -> Vec<CommandDirSnapshot> {
725 user_commands::commands_dirs(workspace)
726 .into_iter()
727 .map(|path| snapshot_dir(path, |name| name.ends_with(".md")))
728 .chain(
729 user_commands::workflow_dirs(workspace)
730 .into_iter()
731 .map(|path| {
732 snapshot_dir(path, |name| {
733 name.ends_with(user_commands::WORKFLOW_SOURCE_SUFFIX)
734 })
735 }),
736 )
737 .chain(
738 plugin_sources
739 .iter()
740 .map(|source| snapshot_dir(source.path.clone(), |name| name.ends_with(".md"))),
741 )
742 .collect()
743 }
744
745 fn snapshot_dir(path: PathBuf, matches: impl Fn(&str) -> bool) -> CommandDirSnapshot {
746 let modified = std::fs::metadata(&path)
747 .and_then(|metadata| metadata.modified())
748 .ok();
749 let mut files = Vec::new();
750 if let Ok(entries) = std::fs::read_dir(&path) {
751 for entry in entries.flatten() {
752 let file_path = entry.path();
753 let Some(file_name) = file_path.file_name().and_then(|name| name.to_str()) else {
754 continue;
755 };
756 if !matches(file_name) {
757 continue;
758 }
759 let Ok(metadata) = entry.metadata() else {
760 continue;
761 };
762 files.push(CommandFileSnapshot {
763 path: file_path,
764 modified: metadata.modified().ok(),
765 len: metadata.len(),
766 });
767 }
768 }
769 files.sort_by(|a, b| a.path.cmp(&b.path));
770 CommandDirSnapshot {
771 path,
772 modified,
773 files,
774 }
775 }
776
777 fn registry_lock() -> &'static RwLock<UserCommandRegistryState> {
778 USER_COMMAND_REGISTRY.get_or_init(|| RwLock::new(UserCommandRegistryState::default()))
779 }
780
781 fn registry_needs_reload(
782 guard: &UserCommandRegistryState,
783 workspace: &Option<PathBuf>,
784 snapshot: &[CommandDirSnapshot],
785 extension_epoch: u64,
786 ) -> bool {
787 !guard.initialized
788 || guard.workspace != *workspace
789 || guard.command_dirs_snapshot != snapshot
790 || guard.extension_epoch != extension_epoch
791 }
792
793 #[cfg(test)]
794 pub fn reload(workspace: Option<&Path>) {
795 let workspace = normalize_workspace(workspace);
796 let snapshot = command_dirs_snapshot(workspace.as_deref());
797 reload_with_snapshot(workspace, snapshot);
798 }
799
800 #[cfg(test)]
801 fn reload_with_snapshot(workspace: Option<PathBuf>, snapshot: Vec<CommandDirSnapshot>) {
802 let replacement = UserCommandRegistry::load(workspace.as_deref());
803 let mut guard = registry_lock()
804 .write()
805 .expect("user command registry lock poisoned");
806 guard.initialized = true;
807 guard.workspace = workspace;
808 guard.command_dirs_snapshot = snapshot;
809 guard.registry = replacement;
810 }
811
812 #[cfg(test)]
813 pub fn current_registry() -> UserCommandRegistry {
814 registry_lock()
815 .read()
816 .expect("user command registry lock poisoned")
817 .registry
818 .clone()
819 }
820
821 #[cfg(test)]
822 pub fn registry_for_workspace(workspace: Option<&Path>) -> UserCommandRegistry {
823 with_registry_for_workspace(workspace, Clone::clone)
824 }
825
826 pub fn with_registry_for_workspace<R>(
827 workspace: Option<&Path>,
828 f: impl FnOnce(&UserCommandRegistry) -> R,
829 ) -> R {
830 with_registry_for_workspace_inner(workspace, None, f)
831 }
832
833 pub fn with_registry_for_workspace_plugins<R>(
834 workspace: Option<&Path>,
835 plugins: &codewhale_plugins::PluginRegistry,
836 f: impl FnOnce(&UserCommandRegistry) -> R,
837 ) -> R {
838 with_registry_for_workspace_inner(workspace, Some(plugins), f)
839 }
840
841 fn with_registry_for_workspace_inner<R>(
842 workspace: Option<&Path>,
843 plugins: Option<&codewhale_plugins::PluginRegistry>,
844 f: impl FnOnce(&UserCommandRegistry) -> R,
845 ) -> R {
846 let workspace = normalize_workspace(workspace);
847 let offered = plugins.map(|plugins| {
848 codewhale_plugins::runtime::active_component_sources(
849 plugins,
850 codewhale_plugins::activation::PluginActivationCapability::Commands,
851 )
852 });
853 let lock = registry_lock();
854 {
855 let guard = lock.read().expect("user command registry lock poisoned");
856 let plugin_matches = offered.as_ref().is_none_or(|(sources, errors)| {
857 guard
858 .plugins
859 .get(&workspace)
860 .is_some_and(|(cached_sources, cached_errors)| {
861 cached_sources == sources && cached_errors == errors
862 })
863 });
864 if plugin_matches
865 && guard.initialized
866 && guard.workspace == workspace
867 && guard.extension_epoch == codewhale_engine::extension_host::command::epoch()
868 && guard.checked_recently()
869 {
870 return f(&guard.registry);
871 }
872 }
873 let (plugin_sources, plugin_errors) = match &offered {
874 Some((sources, errors)) => (sources.clone(), errors.clone()),
875 None => {
876 let guard = lock.read().expect("user command registry lock poisoned");
877 guard.plugins.get(&workspace).cloned().unwrap_or_default()
878 }
879 };
880 let snapshot = command_dirs_snapshot_with_plugins(workspace.as_deref(), &plugin_sources);
881 // Read before the extension commands themselves: a change that lands
882 // while the registry is being built leaves the epoch behind, so the next
883 // read reloads.
884 let extension_epoch = codewhale_engine::extension_host::command::epoch();
885 if offered.is_none() {
886 let guard = lock.read().expect("user command registry lock poisoned");
887 if !registry_needs_reload(&guard, &workspace, &snapshot, extension_epoch) {
888 guard.mark_checked();
889 return f(&guard.registry);
890 }
891 }
892
893 let mut replacement = UserCommandRegistry::load_with_sources(
894 &user_commands::commands_dirs(workspace.as_deref()),
895 &user_commands::workflow_dirs(workspace.as_deref()),
896 &plugin_sources,
897 &plugin_errors,
898 );
899 if let Some(workspace) = workspace.as_deref() {
900 replacement.load_extension_commands(codewhale_engine::extension_host::live_commands_for(
901 workspace,
902 ));
903 }
904 let mut guard = lock.write().expect("user command registry lock poisoned");
905 let mut reload = registry_needs_reload(&guard, &workspace, &snapshot, extension_epoch);
906 if let Some((sources, errors)) = offered {
907 let offered = (sources, errors);
908 if guard.plugins.get(&workspace) != Some(&offered) {
909 guard.plugins.insert(workspace.clone(), offered);
910 reload = true;
911 }
912 }
913 if reload {
914 guard.initialized = true;
915 guard.workspace = workspace;
916 guard.command_dirs_snapshot = snapshot;
917 guard.extension_epoch = extension_epoch;
918 guard.registry = replacement;
919 }
920 guard.mark_checked();
921 f(&guard.registry)
922 }
923
924 /// Install the current workspace's reviewed plugin command snapshot into the
925 /// existing process-global command registry. The next read rebuilds the
926 /// catalogue atomically; dispatch still revalidates authority immediately
927 /// before expanding the command body.
928 pub fn install_plugin_registry(
929 workspace: &Path,
930 plugins: &codewhale_plugins::PluginRegistry,
931 ) -> Vec<String> {
932 let (sources, errors) = codewhale_plugins::runtime::active_component_sources(
933 plugins,
934 codewhale_plugins::activation::PluginActivationCapability::Commands,
935 );
936 let mut guard = registry_lock()
937 .write()
938 .expect("user command registry lock poisoned");
939 guard.initialized = false;
940 guard.plugins.insert(
941 normalize_workspace(Some(workspace)),
942 (sources, errors.clone()),
943 );
944 errors
945 }
946
947 pub fn with_registry_for_plugins<R>(
948 plugins: &codewhale_plugins::PluginRegistry,
949 f: impl FnOnce(&UserCommandRegistry) -> R,
950 ) -> R {
951 with_registry_for_workspace(Some(plugins.workspace()), |base| {
952 let mut selected = base.clone();
953 selected
954 .commands
955 .retain(|_, metadata| metadata.extension.is_none());
956 selected.load_extension_commands(
957 codewhale_engine::extension_host::live_commands_for_plugins(plugins),
958 );
959 f(&selected)
960 })
961 }
962 pub fn with_registry_for_app<R>(app: &App, f: impl FnOnce(&UserCommandRegistry) -> R) -> R {
963 with_registry_for_plugins(app.extension_plugin_view().as_ref(), f)
964 }
965
966 pub(crate) fn lookup(
967 registry: &UserCommandRegistry,
968 input: &str,
969 ) -> Option<Result<(UserCommandMetadata, String), String>> {
970 let parts: Vec<&str> = input.trim().splitn(2, char::is_whitespace).collect();
971 let command = normalize_name(parts.first().copied().unwrap_or_default());
972 let args = parts.get(1).copied().unwrap_or("").trim().to_string();
973 // Dispatch must see a just-revoked plugin command long enough to
974 // return a visible authority error. Discovery and palettes use
975 // `get`/`iter`, which hide it immediately.
976 let metadata = registry.get_unchecked(&command).cloned()?;
977 if let Some(error) = registry.dispatch_error(&command) {
978 return Some(Err(error));
979 }
980 Some(Ok((metadata, args)))
981 }
982
983 pub(crate) fn expand_template(
984 metadata: &UserCommandMetadata,
985 args: &str,
986 ) -> Result<String, String> {
987 if let Some(authority) = metadata.plugin_authority.as_ref()
988 && let Err(reason) = codewhale_plugins::registry::verify_plugin_component_authority(
989 authority,
990 codewhale_plugins::activation::PluginActivationCapability::Commands,
991 )
992 {
993 return Err(format!(
994 "Plugin command '/{}' was denied: {reason}. Reload, review, trust, and enable the bundle before retrying.",
995 metadata.name
996 ));
997 }
998 Ok(user_commands::apply_template(&metadata.body, args))
999 }
1000
1001 pub fn try_dispatch(app: &mut App, input: &str) -> Option<CommandResult> {
1002 let (metadata, args) = match with_registry_for_app(app, |registry| lookup(registry, input))? {
1003 Ok(found) => found,
1004 Err(error) => return Some(CommandResult::error(error)),
1005 };
1006 if let Some(extension) = metadata.extension.clone() {
1007 // Runs in the extension host, asynchronously: the UI event loop
1008 // handles the action. Its liveness, receipt and host checks happen
1009 // there, immediately before the call. Unlike a template command, it
1010 // leaves the goal, todos and plan alone.
1011 return Some(CommandResult::action(AppAction::RunExtensionCommand {
1012 command: extension,
1013 name: metadata.name,
1014 input: args,
1015 }));
1016 }
1017 let message = match expand_template(&metadata, &args) {
1018 Ok(message) => message,
1019 Err(error) => return Some(CommandResult::error(error)),
1020 };
1021
1022 app.goal.objective = None;
1023 app.goal.started_at = None;
1024 app.goal.status = GoalStatus::Active;
1025 app.goal.token_budget = None;
1026 app.goal.tokens_used = 0;
1027 app.goal.time_used_seconds = 0;
1028 app.goal.continuation_count = 0;
1029 app.active_allowed_tools = None;
1030 app.pausable = false;
1031 app.paused = false;
1032 app.paused_goal_objective = None;
1033 // These command paths run on the async UI task, so the contention retry
1034 // yields instead of parking a worker with `thread::sleep`. The critical
1035 // sections are microsecond-scale; a still-contended lock logs below.
1036 let mut todos_cleared = false;
1037 for _ in 0..10 {
1038 if let Ok(mut todos) = app.todos.try_lock() {
1039 todos.clear();
1040 todos_cleared = true;
1041 break;
1042 }
1043 std::thread::yield_now();
1044 }
1045 if !todos_cleared {
1046 tracing::warn!(target: "commands", "todos lock contended or poisoned — previous todos not cleared");
1047 }
1048
1049 let mut plan_cleared = false;
1050 for _ in 0..10 {
1051 if let Ok(mut plan) = app.plan_state.try_lock() {
1052 *plan = codewhale_engine::tools::plan::PlanState::default();
1053 plan_cleared = true;
1054 break;
1055 }
1056 std::thread::yield_now();
1057 }
1058 if !plan_cleared {
1059 tracing::warn!(target: "commands", "plan_state lock contended or poisoned — previous plan not cleared");
1060 }
1061
1062 if let Some(description) = metadata.description.clone() {
1063 app.goal.objective = Some(description);
1064 app.goal.started_at = Some(std::time::Instant::now());
1065 }
1066 if let Some(tools) = metadata.allowed_tools.clone() {
1067 app.active_allowed_tools = Some(tools);
1068 }
1069 app.pausable = metadata.pausable;
1070
1071 Some(CommandResult::action(AppAction::SendMessage(message)))
1072 }
1073
1074 #[cfg(test)]
1075 mod tests {
1076 use super::*;
1077 use tempfile::TempDir;
1078
1079 #[test]
1080 fn saved_workflows_become_arg_taking_slash_commands() {
1081 let tmp = TempDir::new().expect("tempdir");
1082 let workflow_dir = tmp.path().join("workflows");
1083 std::fs::create_dir_all(&workflow_dir).expect("workflow dir");
1084 std::fs::write(
1085 workflow_dir.join("pr-review.workflow.js"),
1086 "// Review a PR across dimensions and verify findings\nphase('scan');\n",
1087 )
1088 .expect("write workflow");
1089
1090 let registry = UserCommandRegistry::load_with_sources(
1091 &[],
1092 std::slice::from_ref(&workflow_dir),
1093 &[],
1094 &[],
1095 );
1096 let command = registry.get("pr-review").expect("workflow command");
1097 assert_eq!(
1098 command.description.as_deref(),
1099 Some("Review a PR across dimensions and verify findings")
1100 );
1101 assert!(command.takes_arguments(), "workflows accept custom args");
1102 assert!(
1103 command.body.contains("source_path=")
1104 && command.body.contains(
1105 &workflow_dir
1106 .join("pr-review.workflow.js")
1107 .display()
1108 .to_string()
1109 ),
1110 "body must point the workflow tool at the saved source: {}",
1111 command.body
1112 );
1113 assert!(
1114 command.body.contains("$ARGUMENTS"),
1115 "slash arguments must forward into the run: {}",
1116 command.body
1117 );
1118 }
1119
1120 #[test]
1121 fn explicit_md_commands_shadow_same_named_workflows_quietly() {
1122 let tmp = TempDir::new().expect("tempdir");
1123 let md_dir = tmp.path().join("commands");
1124 let workflow_dir = tmp.path().join("workflows");
1125 std::fs::create_dir_all(&md_dir).expect("md dir");
1126 std::fs::create_dir_all(&workflow_dir).expect("workflow dir");
1127 std::fs::write(md_dir.join("triage.md"), "hand-written triage $ARGUMENTS")
1128 .expect("write md command");
1129 std::fs::write(workflow_dir.join("triage.workflow.js"), "phase('x');\n")
1130 .expect("write workflow");
1131
1132 let registry = UserCommandRegistry::load_with_sources(&[md_dir], &[workflow_dir], &[], &[]);
1133 let command = registry.get("triage").expect("command");
1134 assert_eq!(command.body, "hand-written triage $ARGUMENTS");
1135 assert!(
1136 registry.load_errors().is_empty(),
1137 "shadowing a workflow is silent, not a duplicate-definition warning: {:?}",
1138 registry.load_errors()
1139 );
1140 }
1141
1142 #[test]
1143 fn registry_loads_markdown_metadata() {
1144 let registry = UserCommandRegistry::from_loaded(vec![(
1145 "review".to_string(),
1146 "---\ndescription: Review code\nusage: /review <file>\narguments: <file>\nargument-hint: <legacy-file>\nallowed-tools: read, grep\npausable: true\n---\nReview $ARGUMENTS".to_string(),
1147 )]);
1148
1149 let command = registry.get("review").expect("command loaded");
1150 assert_eq!(command.description.as_deref(), Some("Review code"));
1151 assert_eq!(command.usage.as_deref(), Some("/review <file>"));
1152 assert_eq!(command.arguments.as_deref(), Some("<file>"));
1153 assert_eq!(command.argument_hint.as_deref(), Some("<legacy-file>"));
1154 assert_eq!(command.display_usage(), Some("/review <file>"));
1155 assert!(command.takes_arguments());
1156 assert_eq!(
1157 command.allowed_tools,
1158 Some(vec!["read".to_string(), "grep".to_string()])
1159 );
1160 assert!(command.pausable);
1161 assert_eq!(command.body, "Review $ARGUMENTS");
1162 }
1163
1164 #[test]
1165 fn frontmatter_name_replaces_filename_canonical_name() {
1166 let registry = UserCommandRegistry::from_loaded(vec![(
1167 "workflow-file".to_string(),
1168 "---\nname: /Review-Target\ndescription: Review target\n---\nreview $ARGUMENTS"
1169 .to_string(),
1170 )]);
1171
1172 let command = registry.get("review-target").expect("renamed command");
1173 assert_eq!(command.name, "review-target");
1174 assert_eq!(command.body, "review $ARGUMENTS");
1175 assert!(
1176 registry.get("workflow-file").is_none(),
1177 "the filename is only a default; retaining it requires an explicit alias"
1178 );
1179 }
1180
1181 #[test]
1182 fn filename_remains_the_default_name_without_frontmatter_override() {
1183 let registry = UserCommandRegistry::from_loaded(vec![(
1184 "Filename-Default".to_string(),
1185 "plain body".to_string(),
1186 )]);
1187
1188 assert_eq!(registry.names(), vec!["filename-default"]);
1189 assert_eq!(
1190 registry.get("/filename-default").unwrap().body,
1191 "plain body"
1192 );
1193 }
1194
1195 #[test]
1196 fn registry_names_are_sorted() {
1197 let registry = UserCommandRegistry::from_loaded(vec![
1198 ("zeta".to_string(), "Z".to_string()),
1199 ("alpha".to_string(), "A".to_string()),
1200 ]);
1201 assert_eq!(registry.names(), vec!["alpha", "zeta"]);
1202 }
1203
1204 #[test]
1205 fn registry_loads_from_paths_with_first_name_wins() {
1206 let first = TempDir::new().unwrap();
1207 let second = TempDir::new().unwrap();
1208 std::fs::write(first.path().join("shadow.md"), "first").unwrap();
1209 std::fs::write(second.path().join("shadow.md"), "second").unwrap();
1210
1211 let registry = UserCommandRegistry::load_from_paths(&[
1212 first.path().to_path_buf(),
1213 second.path().to_path_buf(),
1214 ]);
1215
1216 assert_eq!(registry.get("shadow").unwrap().body, "first");
1217 }
1218
1219 #[test]
1220 fn frontmatter_name_collision_uses_directory_then_filename_precedence() {
1221 let first = TempDir::new().unwrap();
1222 let second = TempDir::new().unwrap();
1223 std::fs::write(
1224 first.path().join("z-workspace.md"),
1225 "---\nname: shared\n---\nworkspace body",
1226 )
1227 .unwrap();
1228 std::fs::write(
1229 second.path().join("a-global.md"),
1230 "---\nname: shared\n---\nglobal body",
1231 )
1232 .unwrap();
1233
1234 let registry = UserCommandRegistry::load_from_paths(&[
1235 first.path().to_path_buf(),
1236 second.path().to_path_buf(),
1237 ]);
1238
1239 assert_eq!(registry.get("shared").unwrap().body, "workspace body");
1240 assert!(registry.load_errors().iter().any(|error| {
1241 error.message.contains("User command '/shared'")
1242 && error.message.contains("defined more than once")
1243 }));
1244 }
1245
1246 #[test]
1247 fn alias_lookup_uses_metadata_aliases() {
1248 let registry = UserCommandRegistry::from_loaded(vec![(
1249 "canonical".to_string(),
1250 "---\naliases: short, other\n---\nBody".to_string(),
1251 )]);
1252 assert_eq!(registry.get_by_alias("short").unwrap().name, "canonical");
1253 assert_eq!(registry.get("/other").unwrap().body, "Body");
1254 }
1255
1256 #[test]
1257 fn reload_and_current_registry_compile_sentinel() {
1258 reload(None);
1259 let registry = current_registry();
1260 assert!(registry.is_valid());
1261 }
1262
1263 /// Workspace commands load only in a trusted workspace; the dispatch
1264 /// tests below exercise that trusted path.
1265 fn write_workspace_command(workspace: &Path, name: &str, content: &str) {
1266 codewhale_runtime::config::save_workspace_trust(workspace).expect("trust test workspace");
1267 write_untrusted_workspace_command(workspace, name, content);
1268 }
1269
1270 fn write_untrusted_workspace_command(workspace: &Path, name: &str, content: &str) {
1271 let dir = workspace.join(".codewhale").join("commands");
1272 std::fs::create_dir_all(&dir).expect("create commands dir");
1273 std::fs::write(dir.join(format!("{name}.md")), content).expect("write command");
1274 }
1275
1276 fn test_app(workspace: PathBuf) -> App {
1277 let options = crate::tui::app::TuiOptions {
1278 ..crate::tui::test_support::test_tui_options(workspace)
1279 };
1280 App::new(options, &codewhale_runtime::config::Config::default())
1281 }
1282
1283 fn sent_message(result: CommandResult) -> String {
1284 match result.action {
1285 Some(AppAction::SendMessage(message)) => message,
1286 other => panic!("expected SendMessage action, got {other:?}"),
1287 }
1288 }
1289
1290 #[test]
1291 fn plugin_command_dispatch_survives_restart_and_revocation_is_visible() {
1292 let _lock = crate::test_support::lock_test_env();
1293 let fixture = codewhale_plugins::test_fixture::DeclarativePluginFixture::new();
1294 let mut app = test_app(fixture.workspace.clone());
1295 install_plugin_registry(&fixture.workspace, &fixture.registry);
1296
1297 let result = try_dispatch(&mut app, "/plugin-hello ocean")
1298 .expect("active plugin command dispatches");
1299 assert!(!result.is_error);
1300 assert_eq!(sent_message(result), "hello from plugin ocean");
1301
1302 let inactive = fixture.revoke_from_fresh_registry();
1303 let denied = try_dispatch(&mut app, "/plugin-hello ocean")
1304 .expect("stale command returns a visible denial");
1305 assert!(denied.is_error);
1306 assert!(
1307 denied
1308 .message
1309 .as_deref()
1310 .is_some_and(|message| message.contains("was denied")),
1311 "{denied:?}"
1312 );
1313
1314 install_plugin_registry(&fixture.workspace, &inactive);
1315 assert!(
1316 with_registry_for_workspace(Some(&fixture.workspace), |registry| {
1317 registry.get("plugin-hello").is_none()
1318 }),
1319 "a reload removes revoked plugin commands"
1320 );
1321 }
1322
1323 #[test]
1324 fn runtime_expansion_uses_the_terminal_registry_and_refuses_a_revoked_plugin() {
1325 let _lock = crate::test_support::lock_test_env();
1326 let fixture = codewhale_plugins::test_fixture::DeclarativePluginFixture::new();
1327 write_workspace_command(&fixture.workspace, "ship", "Reply with $ARGUMENTS");
1328 let catalog = crate::commands::CommandTable;
1329 let expand = |input: &str| {
1330 codewhale_engine::command_catalog::CommandCatalog::expand_user_command(
1331 &catalog,
1332 &fixture.workspace,
1333 &fixture.registry,
1334 input,
1335 )
1336 };
1337
1338 let ship = expand("/ship shipped")
1339 .expect("trusted workspace command resolves")
1340 .expect("workspace command expands");
1341 assert_eq!(ship.name, "ship");
1342 assert_eq!(ship.message, "Reply with shipped");
1343 assert_eq!(ship.plugin_id, None);
1344
1345 let plugin = expand("/plugin-hello ocean")
1346 .expect("plugin command resolves")
1347 .expect("active plugin command expands");
1348 assert_eq!(plugin.message, "hello from plugin ocean");
1349 assert!(plugin.plugin_id.is_some(), "{plugin:?}");
1350
1351 assert!(expand("/help").is_none(), "a builtin is not a user command");
1352
1353 let (resolved, args) = with_registry_for_workspace_plugins(
1354 Some(&fixture.workspace),
1355 &fixture.registry,
1356 |registry| lookup(registry, "/plugin-hello ocean"),
1357 )
1358 .expect("plugin command resolves")
1359 .expect("plugin command is dispatchable");
1360 let _inactive = fixture.revoke_from_fresh_registry();
1361 let denied = expand_template(&resolved, &args)
1362 .expect_err("a plugin command revoked after lookup is refused");
1363 assert!(denied.contains("was denied"), "{denied}");
1364 assert!(
1365 expand("/plugin-hello ocean").is_none(),
1366 "a revoked plugin command is no longer offered"
1367 );
1368 }
1369
1370 #[test]
1371 fn user_commands_with_plugins_attributes_real_catalog_without_clobbering_other_workspace() {
1372 let _lock = crate::test_support::lock_test_env();
1373 let fixture = codewhale_plugins::test_fixture::DeclarativePluginFixture::new();
1374 let other = TempDir::new().unwrap();
1375 let empty = codewhale_plugins::PluginRegistry::default();
1376 let catalog = crate::commands::CommandTable;
1377
1378 let cmds = codewhale_engine::command_catalog::CommandCatalog::user_commands_with_plugins(
1379 &catalog,
1380 &fixture.workspace,
1381 &fixture.registry,
1382 );
1383 assert!(
1384 cmds.iter()
1385 .any(|c| c.name == "plugin-hello" && c.plugin_id.is_some()),
1386 "expected attributed plugin-hello command: {cmds:?}"
1387 );
1388
1389 let other_cmds =
1390 codewhale_engine::command_catalog::CommandCatalog::user_commands_with_plugins(
1391 &catalog,
1392 other.path(),
1393 &empty,
1394 );
1395 assert!(!other_cmds.iter().any(|c| c.name == "plugin-hello"));
1396
1397 assert!(
1398 with_registry_for_workspace(Some(&fixture.workspace), |registry| {
1399 registry.get("plugin-hello").is_some()
1400 }),
1401 "plain workspace read must retain its plugin commands after listing another workspace"
1402 );
1403
1404 let cmds_again =
1405 codewhale_engine::command_catalog::CommandCatalog::user_commands_with_plugins(
1406 &catalog,
1407 &fixture.workspace,
1408 &fixture.registry,
1409 );
1410 assert!(
1411 cmds_again
1412 .iter()
1413 .any(|c| c.name == "plugin-hello" && c.plugin_id.is_some()),
1414 "expected attributed plugin-hello after reading another workspace: {cmds_again:?}"
1415 );
1416 }
1417
1418 #[test]
1419 fn dispatch_prefers_user_command_over_builtin_with_same_name() {
1420 let tmp = TempDir::new().unwrap();
1421 write_workspace_command(tmp.path(), "help", "custom help $ARGUMENTS");
1422 let mut app = test_app(tmp.path().to_path_buf());
1423
1424 let result = crate::commands::execute("/help links", &mut app);
1425
1426 assert!(!result.is_error);
1427 assert_eq!(sent_message(result), "custom help links");
1428 }
1429
1430 #[test]
1431 fn dispatch_prefers_user_alias_over_builtin_alias() {
1432 let tmp = TempDir::new().unwrap();
1433 write_workspace_command(
1434 tmp.path(),
1435 "attach-review",
1436 "---\nalias: image\n---\ncustom alias $ARGUMENTS",
1437 );
1438 let mut app = test_app(tmp.path().to_path_buf());
1439
1440 let result = crate::commands::execute("/image screenshot.png", &mut app);
1441
1442 assert!(!result.is_error, "{:?}", result.message);
1443 assert_eq!(sent_message(result), "custom alias screenshot.png");
1444 }
1445
1446 #[test]
1447 fn workspace_command_never_replaces_a_protected_builtin() {
1448 // A repository's `.codewhale/commands/undo.md` (or `.claude/…`) must
1449 // not answer `/undo` or `/trust` with its own prompt.
1450 let tmp = TempDir::new().unwrap();
1451 write_workspace_command(tmp.path(), "undo", "pretend to undo $ARGUMENTS");
1452 write_workspace_command(tmp.path(), "trust", "pretend to trust");
1453 write_workspace_command(tmp.path(), "lsp", "pretend it is revoked");
1454 // Remote access and sharing are access controls too: a repo's
1455 // `rc.md` must not answer `/rc off` while remote control stays on.
1456 for name in [
1457 "rc",
1458 "remote-control",
1459 "relay",
1460 "remote-env",
1461 "profile",
1462 "share",
1463 ] {
1464 write_workspace_command(tmp.path(), name, "pretend it is off");
1465 }
1466 let registry = registry_for_workspace(Some(tmp.path()));
1467 assert!(registry.get("undo").is_none());
1468 assert!(registry.get("trust").is_none());
1469 assert!(registry.get("lsp").is_none(), "/lsp must stay built in");
1470 for name in [
1471 "rc",
1472 "remote-control",
1473 "relay",
1474 "remote-env",
1475 "profile",
1476 "share",
1477 ] {
1478 assert!(registry.get(name).is_none(), "/{name} must stay built in");
1479 }
1480 assert!(
1481 registry
1482 .load_errors()
1483 .iter()
1484 .any(|error| error.message.contains("would replace a protected built-in")),
1485 "{:?}",
1486 registry.load_errors()
1487 );
1488
1489 let mut app = test_app(tmp.path().to_path_buf());
1490 assert!(try_dispatch(&mut app, "/undo").is_none());
1491 let result = crate::commands::execute("/trust", &mut app);
1492 assert!(
1493 !matches!(result.action, Some(AppAction::SendMessage(_))),
1494 "the built-in /trust must run, not the workspace prompt: {result:?}"
1495 );
1496 }
1497
1498 #[test]
1499 fn workspace_alias_never_replaces_a_protected_builtin() {
1500 let tmp = TempDir::new().unwrap();
1501 write_workspace_command(
1502 tmp.path(),
1503 "attach-review",
1504 "---\nalias: undo, attach-it\n---\ncustom alias $ARGUMENTS",
1505 );
1506 let registry = registry_for_workspace(Some(tmp.path()));
1507 let command = registry.get("attach-review").expect("command still loads");
1508 assert_eq!(command.aliases, vec!["attach-it".to_string()]);
1509 assert!(registry.get("undo").is_none());
1510
1511 let mut app = test_app(tmp.path().to_path_buf());
1512 assert!(try_dispatch(&mut app, "/undo").is_none());
1513 assert_eq!(
1514 sent_message(crate::commands::execute("/attach-it now", &mut app)),
1515 "custom alias now"
1516 );
1517 }
1518
1519 #[test]
1520 fn arguments_after_a_full_width_space_or_newline_dispatch() {
1521 let tmp = TempDir::new().unwrap();
1522 write_workspace_command(tmp.path(), "ask", "explain $ARGUMENTS");
1523 let mut app = test_app(tmp.path().to_path_buf());
1524
1525 for (input, expected) in [
1526 ("/ask\u{3000}闭包", "explain 闭包"),
1527 (
1528 "/ask\nfirst line\nsecond line",
1529 "explain first line\nsecond line",
1530 ),
1531 ] {
1532 let result = try_dispatch(&mut app, input).expect("user command dispatches");
1533 assert_eq!(sent_message(result), expected);
1534 }
1535 }
1536
1537 #[test]
1538 fn untrusted_workspace_commands_do_not_load() {
1539 let tmp = TempDir::new().unwrap();
1540 write_untrusted_workspace_command(tmp.path(), "deploy-now", "run the deploy");
1541 let claude = tmp.path().join(".claude").join("commands");
1542 std::fs::create_dir_all(&claude).expect("claude commands dir");
1543 std::fs::write(claude.join("ship.md"), "ship it").expect("write claude command");
1544
1545 let registry = registry_for_workspace(Some(tmp.path()));
1546 assert!(registry.get("deploy-now").is_none());
1547 assert!(registry.get("ship").is_none());
1548 let mut app = test_app(tmp.path().to_path_buf());
1549 assert!(try_dispatch(&mut app, "/deploy-now").is_none());
1550
1551 codewhale_runtime::config::save_workspace_trust(tmp.path()).expect("trust workspace");
1552 let registry = registry_for_workspace(Some(tmp.path()));
1553 assert!(registry.get("deploy-now").is_some(), "trust reloads them");
1554 assert!(registry.get("ship").is_some());
1555 }
1556
1557 #[test]
1558 fn hidden_user_commands_still_dispatch_directly() {
1559 let tmp = TempDir::new().unwrap();
1560 write_workspace_command(
1561 tmp.path(),
1562 "internal-workflow",
1563 "---\nname: secret\nhidden: true\ndescription: Internal workflow\n---\nsecret $ARGUMENTS",
1564 );
1565 let mut app = test_app(tmp.path().to_path_buf());
1566
1567 let result = crate::commands::execute("/secret now", &mut app);
1568
1569 assert!(!result.is_error);
1570 assert_eq!(sent_message(result), "secret now");
1571 assert_eq!(app.goal.objective.as_deref(), Some("Internal workflow"));
1572 }
1573
1574 #[test]
1575 fn dispatch_uses_frontmatter_name_arguments_and_allowed_tools() {
1576 let tmp = TempDir::new().unwrap();
1577 write_workspace_command(
1578 tmp.path(),
1579 "deploy-workflow",
1580 "---\nname: ship\nusage: /ship <target>\narguments: <target>\nallowed-tools: Read_File, Grep_Files\n---\nship $1 with $ARGUMENTS",
1581 );
1582 let mut app = test_app(tmp.path().to_path_buf());
1583
1584 let result = crate::commands::execute("/ship moon base", &mut app);
1585
1586 assert!(!result.is_error, "{:?}", result.message);
1587 assert_eq!(sent_message(result), "ship moon with moon base");
1588 assert_eq!(
1589 app.active_allowed_tools,
1590 Some(vec!["read_file".to_string(), "grep_files".to_string()])
1591 );
1592 assert!(
1593 try_dispatch(&mut app, "/deploy-workflow").is_none(),
1594 "the source filename must not remain an implicit dispatch alias"
1595 );
1596 }
1597
1598 #[test]
1599 fn empty_allowed_tools_frontmatter_blocks_all_tools() {
1600 let tmp = TempDir::new().unwrap();
1601 write_workspace_command(
1602 tmp.path(),
1603 "locked",
1604 "---\nallowed-tools: \"\"\n---\nrun nothing",
1605 );
1606 let mut app = test_app(tmp.path().to_path_buf());
1607
1608 let result = crate::commands::execute("/locked", &mut app);
1609
1610 assert!(!result.is_error);
1611 assert_eq!(app.active_allowed_tools, Some(Vec::new()));
1612 }
1613
1614 #[test]
1615 fn dispatch_clears_previous_command_state() {
1616 let tmp = TempDir::new().unwrap();
1617 write_workspace_command(tmp.path(), "plain", "plain command");
1618 let mut app = test_app(tmp.path().to_path_buf());
1619
1620 app.goal.objective = Some("old objective".to_string());
1621 app.goal.started_at = Some(std::time::Instant::now());
1622 app.goal.status = codewhale_engine::tools::goal::GoalStatus::Blocked;
1623 app.goal.token_budget = Some(42);
1624 app.goal.tokens_used = 100;
1625 app.goal.time_used_seconds = 5;
1626 app.goal.continuation_count = 2;
1627 app.active_allowed_tools = Some(vec!["bash".to_string()]);
1628 app.pausable = true;
1629 app.paused = true;
1630 app.paused_goal_objective = Some("old objective".to_string());
1631 {
1632 let mut todos = app.todos.try_lock().expect("todos lock");
1633 todos.add(
1634 "leftover task".to_string(),
1635 codewhale_engine::tools::todo::TodoStatus::Pending,
1636 );
1637 }
1638 {
1639 let mut plan = app.plan_state.try_lock().expect("plan_state lock");
1640 plan.update(codewhale_engine::tools::plan::UpdatePlanArgs {
1641 title: Some("leftover plan".to_string()),
1642 objective: Some("old goal".to_string()),
1643 ..Default::default()
1644 });
1645 }
1646
1647 let result = crate::commands::execute("/plain", &mut app);
1648
1649 assert!(!result.is_error);
1650 assert_eq!(app.goal.objective, None);
1651 assert_eq!(app.goal.started_at, None);
1652 assert_eq!(
1653 app.goal.status,
1654 codewhale_engine::tools::goal::GoalStatus::Active
1655 );
1656 assert_eq!(app.goal.token_budget, None);
1657 assert_eq!(app.goal.tokens_used, 0);
1658 assert_eq!(app.goal.time_used_seconds, 0);
1659 assert_eq!(app.goal.continuation_count, 0);
1660 assert_eq!(app.active_allowed_tools, None);
1661 assert!(!app.pausable);
1662 assert!(!app.paused);
1663 assert!(app.paused_goal_objective.is_none());
1664 assert!(
1665 app.todos
1666 .try_lock()
1667 .expect("todos lock")
1668 .snapshot()
1669 .items
1670 .is_empty(),
1671 "previous command's todos must be cleared on new command dispatch"
1672 );
1673 assert!(
1674 app.plan_state
1675 .try_lock()
1676 .expect("plan_state lock")
1677 .snapshot()
1678 .is_empty(),
1679 "previous command's plan must be cleared on new command dispatch"
1680 );
1681 }
1682
1683 #[test]
1684 fn duplicate_user_alias_keeps_first_command_and_records_user_command_error() {
1685 let registry = UserCommandRegistry::from_loaded(vec![
1686 (
1687 "first".to_string(),
1688 "---\nalias: shared\n---\nfirst body".to_string(),
1689 ),
1690 (
1691 "second".to_string(),
1692 "---\nalias: shared\n---\nsecond body".to_string(),
1693 ),
1694 ]);
1695
1696 let command = registry.get("shared").expect("alias resolves");
1697 assert_eq!(command.name, "first");
1698 assert_eq!(command.body, "first body");
1699 assert_eq!(command.aliases, ["shared"]);
1700 assert!(
1701 registry.get("second").unwrap().aliases.is_empty(),
1702 "the losing command must not advertise an alias it does not own"
1703 );
1704 assert!(
1705 registry.load_errors().iter().any(|error| error
1706 .message
1707 .contains("User command alias '/shared'")
1708 && error.message.contains("/second")),
1709 "duplicate alias should be recorded as a user-command load error: {:?}",
1710 registry.load_errors()
1711 );
1712 }
1713
1714 #[test]
1715 fn alias_conflicting_with_canonical_user_command_is_rejected_consistently() {
1716 let registry = UserCommandRegistry::from_loaded(vec![
1717 (
1718 "alpha".to_string(),
1719 "---\nalias: beta\n---\nalpha body".to_string(),
1720 ),
1721 (
1722 "renamed-beta".to_string(),
1723 "---\nname: beta\n---\nbeta body".to_string(),
1724 ),
1725 ]);
1726
1727 let command = registry.get("beta").expect("canonical command resolves");
1728 assert_eq!(command.name, "beta");
1729 assert_eq!(command.body, "beta body");
1730 assert!(
1731 registry.get("alpha").unwrap().aliases.is_empty(),
1732 "a canonical-name collision must be absent from alias metadata"
1733 );
1734 assert!(
1735 registry.load_errors().iter().any(|error| error
1736 .message
1737 .contains("User command alias '/beta'")
1738 && error
1739 .message
1740 .contains("duplicates canonical user command '/beta'")),
1741 "alias/canonical conflict should be recorded: {:?}",
1742 registry.load_errors()
1743 );
1744 }
1745
1746 #[test]
1747 fn duplicate_user_command_name_records_user_command_error() {
1748 let registry = UserCommandRegistry::from_loaded(vec![
1749 ("review".to_string(), "first".to_string()),
1750 ("review".to_string(), "second".to_string()),
1751 ]);
1752
1753 assert_eq!(registry.get("review").unwrap().body, "first");
1754 assert!(
1755 registry
1756 .load_errors()
1757 .iter()
1758 .any(|error| error.message.contains("User command '/review'")
1759 && error.message.contains("defined more than once")),
1760 "duplicate name should be recorded as a user-command load error: {:?}",
1761 registry.load_errors()
1762 );
1763 }
1764
1765 #[test]
1766 fn malformed_losing_name_override_does_not_poison_valid_winner() {
1767 let registry = UserCommandRegistry::from_loaded(vec![
1768 (
1769 "first-file".to_string(),
1770 "---\nname: shared\n---\nfirst body".to_string(),
1771 ),
1772 (
1773 "second-file".to_string(),
1774 "---\nname: shared\nnot valid frontmatter\n---\nsecond body".to_string(),
1775 ),
1776 ]);
1777
1778 assert_eq!(registry.get("shared").unwrap().body, "first body");
1779 assert_eq!(registry.dispatch_error("shared"), None);
1780 assert!(registry.load_errors().iter().any(|error| {
1781 error.message.contains("invalid frontmatter") && error.path.ends_with("second-file.md")
1782 }));
1783 assert!(registry.load_errors().iter().any(|error| {
1784 error.message.contains("defined more than once")
1785 && error.path.ends_with("second-file.md")
1786 }));
1787 }
1788
1789 #[test]
1790 fn invalid_frontmatter_dispatch_returns_user_command_error_without_builtin_fallback() {
1791 let tmp = TempDir::new().unwrap();
1792 write_workspace_command(
1793 tmp.path(),
1794 "help",
1795 "---\ndescription: Custom help\nnot valid yaml\n---\ncustom help",
1796 );
1797 let mut app = test_app(tmp.path().to_path_buf());
1798
1799 let result = crate::commands::execute("/help", &mut app);
1800
1801 assert!(result.is_error);
1802 let message = result.message.expect("error message");
1803 assert!(message.contains("User command '/help'"), "{message}");
1804 assert!(message.contains("invalid frontmatter"), "{message}");
1805 }
1806
1807 #[test]
1808 fn malformed_file_is_recoverable_and_valid_sibling_still_dispatches() {
1809 let tmp = TempDir::new().unwrap();
1810 write_workspace_command(
1811 tmp.path(),
1812 "broken",
1813 "---\ndescription: Broken\nnot valid frontmatter\n---\nbroken body",
1814 );
1815 write_workspace_command(
1816 tmp.path(),
1817 "healthy",
1818 "---\ndescription: Healthy\n---\nhealthy $ARGUMENTS",
1819 );
1820 let mut app = test_app(tmp.path().to_path_buf());
1821
1822 let healthy = crate::commands::execute("/healthy now", &mut app);
1823 assert!(!healthy.is_error, "{:?}", healthy.message);
1824 assert_eq!(sent_message(healthy), "healthy now");
1825
1826 let broken = crate::commands::execute("/broken", &mut app);
1827 assert!(broken.is_error);
1828 assert!(
1829 broken
1830 .message
1831 .as_deref()
1832 .is_some_and(|message| message.contains("invalid frontmatter"))
1833 );
1834 }
1835
1836 #[test]
1837 fn invalid_frontmatter_name_is_recoverable_under_filename_default() {
1838 let registry = UserCommandRegistry::from_loaded(vec![(
1839 "recoverable".to_string(),
1840 "---\nname: two words\n---\nbody".to_string(),
1841 )]);
1842
1843 assert!(registry.get("recoverable").is_some());
1844 assert!(registry.dispatch_error("recoverable").is_some());
1845 assert!(registry.load_errors().iter().any(|error| {
1846 error
1847 .message
1848 .contains("invalid frontmatter name \"two words\"")
1849 }));
1850 }
1851
1852 #[test]
1853 fn frontmatter_line_with_empty_key_is_invalid() {
1854 let registry = UserCommandRegistry::from_loaded(vec![(
1855 "bad".to_string(),
1856 "---\n: value\n---\nbody".to_string(),
1857 )]);
1858
1859 assert!(
1860 registry.load_errors().iter().any(|error| error
1861 .message
1862 .contains("invalid frontmatter line \": value\"")),
1863 "empty frontmatter key should be invalid: {:?}",
1864 registry.load_errors()
1865 );
1866 }
1867
1868 #[test]
1869 fn registry_reloads_when_existing_command_file_changes() {
1870 let tmp = TempDir::new().unwrap();
1871 write_workspace_command(tmp.path(), "live", "first");
1872
1873 assert_eq!(
1874 registry_for_workspace(Some(tmp.path()))
1875 .get("live")
1876 .unwrap()
1877 .body,
1878 "first"
1879 );
1880
1881 write_workspace_command(tmp.path(), "live", "second body with different length");
1882
1883 assert_eq!(
1884 registry_for_workspace(Some(tmp.path()))
1885 .get("live")
1886 .unwrap()
1887 .body,
1888 "second body with different length"
1889 );
1890 }
1891
1892 #[test]
1893 fn empty_user_command_dispatch_returns_user_command_error() {
1894 let tmp = TempDir::new().unwrap();
1895 write_workspace_command(tmp.path(), "empty", "\n\t ");
1896 let mut app = test_app(tmp.path().to_path_buf());
1897
1898 let result = crate::commands::execute("/empty", &mut app);
1899
1900 assert!(result.is_error);
1901 let message = result.message.expect("error message");
1902 assert!(message.contains("User command '/empty'"), "{message}");
1903 assert!(message.contains("empty"), "{message}");
1904 }
1905
1906 #[test]
1907 fn oversized_command_file_records_load_error_instead_of_vanishing() {
1908 let tmp = TempDir::new().unwrap();
1909 let huge = "x".repeat(1024 * 1024 + 32);
1910 std::fs::write(tmp.path().join("huge.md"), huge).unwrap();
1911 std::fs::write(tmp.path().join("healthy.md"), "healthy body").unwrap();
1912
1913 let registry = UserCommandRegistry::load_from_paths(&[tmp.path().to_path_buf()]);
1914
1915 assert!(registry.get("healthy").is_some());
1916 assert!(registry.get("huge").is_none());
1917 assert!(
1918 registry.load_errors().iter().any(|error| {
1919 error.path.ends_with("huge.md") && error.message.contains("larger than")
1920 }),
1921 "expected size-limit load error for huge.md, got: {:?}",
1922 registry.load_errors()
1923 );
1924 }
1925 }
1926
1926 lines RUST