返回 CodeWhale
user_commands.rs
根目录 / crates / tui / src / commands / user_commands.rs
1 //! User-defined slash commands from `~/.codewhale/commands/<name>.md` and
2 //! workspace-local `<workspace>/.codewhale/commands/<name>.md`.
3 //!
4 //! Users drop `.md` files into a commands directory and the filename
5 //! (without `.md` extension) becomes the default slash-command name. A
6 //! frontmatter `name` may replace it. When invoked, the file contents are sent
7 //! as a user message.
8 //!
9 //! Files may include optional YAML-like frontmatter between `---` markers.
10 //! Supported fields are `name`, `description`, `usage`, `arguments`,
11 //! `argument-hint`, `allowed-tools`, `pausable`, `alias`/`aliases`, and `hidden`.
12 //! Frontmatter is stripped before the command body is sent to the model.
13 //!
14 //! ## Precedence
15 //!
16 //! Workspace-local directories load only in a trusted workspace (`/trust`),
17 //! and a workspace command never replaces a protected built-in such as
18 //! `/trust` or `/undo` (the definition is skipped with a load error; see
19 //! `PROTECTED_BUILTINS` in `user_registry.rs`). Other built-ins stay
20 //! shadowable. Workspace-local directories
21 //! shadow user-global by name:
22 //!
23 //! 1. `<workspace>/.codewhale/commands/` (project-local, highest)
24 //! 2. `<workspace>/.deepseek/commands/` (legacy project-local)
25 //! 3. `<workspace>/.claude/commands/` (Claude Code interop)
26 //! 4. `<workspace>/.cursor/commands/` (Cursor interop)
27 //! 5. `~/.codewhale/commands/` (user-global)
28 //! 6. `~/.deepseek/commands/` (legacy user-global)
29 //!
30 //! ## Permanent Role
31 //!
32 //! This module is the lower-level scanning, frontmatter parsing, and template
33 //! layer for [`super::user_registry::UserCommandRegistry`]. Runtime dispatch
34 //! lives in `user_registry.rs`; this file remains as the shared file I/O and
35 //! parsing boundary documented in `docs/architecture/command-dispatch.md`.
36
37 #[cfg(test)]
38 use std::collections::HashSet;
39 use std::path::{Path, PathBuf};
40
41 #[cfg(test)]
42 use crate::tui::app::{App, AppAction};
43
44 #[cfg(test)]
45 use super::CommandResult;
46
47 /// Path to the global user commands directory: `~/.codewhale/commands/`.
48 fn global_commands_dir() -> PathBuf {
49 let home = codewhale_paths::user_home().unwrap_or_else(|| PathBuf::from("~"));
50 home.join(".codewhale").join("commands")
51 }
52
53 fn legacy_global_commands_dir() -> PathBuf {
54 let home = codewhale_paths::user_home().unwrap_or_else(|| PathBuf::from("~"));
55 home.join(".deepseek").join("commands")
56 }
57
58 /// The workspace whose repository-supplied commands and workflows may load:
59 /// only a trusted one. A cloned repository's `.claude/commands/*.md` is text
60 /// the user never reviewed, sent to the model as the user's own message.
61 fn trusted_workspace(workspace: Option<&Path>) -> Option<&Path> {
62 workspace.filter(|ws| codewhale_runtime::config::is_workspace_trusted(ws))
63 }
64
65 /// Workspace-local command directories, trusted or not, in precedence order.
66 pub(crate) fn workspace_commands_dirs(workspace: &Path) -> [PathBuf; 4] {
67 [
68 workspace.join(".codewhale").join("commands"),
69 workspace.join(".deepseek").join("commands"),
70 workspace.join(".claude").join("commands"),
71 workspace.join(".cursor").join("commands"),
72 ]
73 }
74
75 /// Return all candidate commands directories in precedence order. Workspace
76 /// directories are included only when the workspace is trusted.
77 pub(crate) fn commands_dirs(workspace: Option<&Path>) -> Vec<PathBuf> {
78 let mut dirs = Vec::new();
79 if let Some(ws) = trusted_workspace(workspace) {
80 dirs.extend(workspace_commands_dirs(ws));
81 }
82 dirs.push(global_commands_dir());
83 dirs.push(legacy_global_commands_dir());
84 dirs
85 }
86
87 /// Whether `path` came from the user's own global command or workflow store,
88 /// as opposed to a workspace (repository) directory.
89 pub(crate) fn is_user_global_command_source(path: &Path) -> bool {
90 let home = codewhale_paths::user_home().unwrap_or_else(|| PathBuf::from("~"));
91 [
92 global_commands_dir(),
93 legacy_global_commands_dir(),
94 home.join(".codewhale").join("workflows"),
95 ]
96 .iter()
97 .any(|dir| path.starts_with(dir))
98 }
99
100 /// Saved-workflow slash commands (#4121 packaging): `*.workflow.js` files
101 /// under these directories become `/name` commands that start the workflow
102 /// through the `workflow` tool with the slash arguments forwarded as the
103 /// run's `args`. Workspace definitions shadow the user-global store.
104 pub(crate) fn workflow_dirs(workspace: Option<&Path>) -> Vec<PathBuf> {
105 let mut dirs = Vec::new();
106 if let Some(ws) = trusted_workspace(workspace) {
107 dirs.push(ws.join(".codewhale").join("workflows"));
108 }
109 let home = codewhale_paths::user_home().unwrap_or_else(|| PathBuf::from("~"));
110 dirs.push(home.join(".codewhale").join("workflows"));
111 dirs
112 }
113
114 const MAX_COMMAND_FILE_BYTES: u64 = 1024 * 1024;
115
116 fn read_command_file(path: &Path) -> Result<String, String> {
117 use std::io::Read;
118 let read = std::fs::File::open(path).and_then(|file| {
119 let mut text = String::new();
120 file.take(MAX_COMMAND_FILE_BYTES + 1)
121 .read_to_string(&mut text)?;
122 if text.len() as u64 > MAX_COMMAND_FILE_BYTES {
123 return Err(std::io::Error::new(
124 std::io::ErrorKind::InvalidData,
125 format!("larger than {MAX_COMMAND_FILE_BYTES} bytes"),
126 ));
127 }
128 Ok(text)
129 });
130 match read {
131 Ok(text) => Ok(text),
132 Err(error) => {
133 tracing::warn!(target: "commands", path = %path.display(), %error, "skipping unreadable command file");
134 Err(format!("skipping unreadable command file: {error}"))
135 }
136 }
137 }
138
139 /// Canonical saved-workflow source suffix.
140 pub(crate) const WORKFLOW_SOURCE_SUFFIX: &str = ".workflow.js";
141
142 /// Scan one workflow directory and synthesize a markdown command definition
143 /// per `*.workflow.js` file. Returns `(name, content, source_path)` tuples;
144 /// unreadable entries are skipped.
145 pub(crate) fn load_workflow_commands_from_dir(dir: &Path) -> Vec<(String, String, PathBuf)> {
146 let mut commands = Vec::new();
147 if !dir.is_dir() {
148 return commands;
149 }
150 let Ok(entries) = std::fs::read_dir(dir) else {
151 return commands;
152 };
153 for entry in entries.flatten() {
154 let path = entry.path();
155 let Some(file_name) = path.file_name().and_then(|name| name.to_str()) else {
156 continue;
157 };
158 let Some(stem) = file_name.strip_suffix(WORKFLOW_SOURCE_SUFFIX) else {
159 continue;
160 };
161 let name = stem.to_lowercase();
162 if name.is_empty() {
163 continue;
164 }
165 let description = read_command_file(&path)
166 .ok()
167 .and_then(|source| workflow_headline(&source))
168 .unwrap_or_else(|| format!("Run the saved workflow {name}"));
169 let content = synthesize_workflow_command(&name, &description, &path);
170 commands.push((name, content, path));
171 }
172 commands.sort_by(|a, b| a.0.cmp(&b.0));
173 commands
174 }
175
176 /// First `//` comment line of a workflow source, used as the command
177 /// description in palettes and help.
178 fn workflow_headline(source: &str) -> Option<String> {
179 source.lines().find_map(|line| {
180 let comment = line.trim().strip_prefix("//")?.trim();
181 (!comment.is_empty()).then(|| comment.split_whitespace().collect::<Vec<_>>().join(" "))
182 })
183 }
184
185 fn synthesize_workflow_command(name: &str, description: &str, path: &Path) -> String {
186 // Frontmatter values must stay single-line; the headline is already one
187 // line but defend against pathological sources.
188 let description = description.replace(['\r', '\n'], " ");
189 format!(
190 "---\ndescription: {description}\nusage: /{name} [args...]\narguments: forwarded to the workflow run's args\n---\nStart the saved workflow `{name}` now: call the `workflow` tool with action=\"start\", source_path=\"{path}\", and args built from this argument text: $ARGUMENTS\nIf the argument text is empty, start the run without args. Report the run_id, monitor with the workflow tool's status action, and when the run settles present its receipt summary (status, phases, failures, artifacts). The durable report lands under .codewhale/reports/<run_id>.md.",
191 path = path.display(),
192 )
193 }
194
195 pub(crate) type CommandLoadErrors = Vec<(PathBuf, String)>;
196 pub(crate) type CommandEntry = (String, String, PathBuf);
197
198 #[cfg(test)]
199 pub(crate) fn load_commands_from_dir(dir: &Path) -> Vec<(String, String)> {
200 load_command_entries_from_component(dir)
201 .into_iter()
202 .map(|(name, content, _)| (name, content))
203 .collect()
204 }
205
206 pub(crate) fn load_commands_from_dir_with_errors(
207 dir: &Path,
208 ) -> (Vec<(String, String)>, CommandLoadErrors) {
209 let (entries, errors) = load_command_entries_from_component_with_errors(dir);
210 (
211 entries
212 .into_iter()
213 .map(|(name, content, _)| (name, content))
214 .collect(),
215 errors,
216 )
217 }
218
219 pub(crate) fn load_command_entries_from_component(component: &Path) -> Vec<CommandEntry> {
220 load_command_entries_from_component_with_errors(component).0
221 }
222
223 pub(crate) fn load_command_entries_from_component_with_errors(
224 component: &Path,
225 ) -> (Vec<CommandEntry>, CommandLoadErrors) {
226 if component.is_file() {
227 if component.extension().and_then(|value| value.to_str()) != Some("md") {
228 return (Vec::new(), Vec::new());
229 }
230 let Some(stem) = component.file_stem().and_then(|value| value.to_str()) else {
231 return (Vec::new(), Vec::new());
232 };
233 return match read_command_file(component) {
234 Ok(content) => (
235 vec![(stem.to_lowercase(), content, component.to_path_buf())],
236 Vec::new(),
237 ),
238 Err(error) => (Vec::new(), vec![(component.to_path_buf(), error)]),
239 };
240 }
241
242 let mut commands: Vec<(String, String, PathBuf)> = Vec::new();
243 let mut errors: Vec<(PathBuf, String)> = Vec::new();
244
245 if !component.is_dir() {
246 return (Vec::new(), Vec::new());
247 }
248
249 let entries = match std::fs::read_dir(component) {
250 Ok(entries) => entries,
251 Err(_) => return (Vec::new(), Vec::new()),
252 };
253
254 for entry in entries.flatten() {
255 let path = entry.path();
256 if path.extension().and_then(|e| e.to_str()) != Some("md") {
257 continue;
258 }
259 let stem = match path.file_stem().and_then(|s| s.to_str()) {
260 Some(stem) => stem.to_lowercase(),
261 None => continue,
262 };
263 match read_command_file(&path) {
264 Ok(content) => commands.push((stem, content, path)),
265 Err(error) => errors.push((path, error)),
266 }
267 }
268 commands.sort_by(|left, right| left.0.cmp(&right.0));
269 (commands, errors)
270 }
271
272 /// Scan every candidate commands directory and return merged
273 /// `(name, content)` pairs. Workspace-local directories shadow
274 /// user-global by name — the first occurrence of a name wins.
275 ///
276 /// Pass `None` for the workspace to scan only the global directory
277 /// (backward-compatible with callers that don't have workspace context).
278 #[cfg(test)]
279 pub fn load_user_commands(workspace: Option<&Path>) -> Vec<(String, String)> {
280 let mut seen: HashSet<String> = HashSet::new();
281 let mut commands: Vec<(String, String)> = Vec::new();
282
283 for dir in commands_dirs(workspace) {
284 for (name, content) in load_commands_from_dir(&dir) {
285 if seen.insert(name.clone()) {
286 commands.push((name, content));
287 }
288 }
289 }
290
291 // Sort by name for deterministic ordering.
292 commands.sort_by(|a, b| a.0.cmp(&b.0));
293 commands
294 }
295
296 pub(crate) fn parse_frontmatter(content: &str) -> (Vec<(String, String)>, &str) {
297 let Some(first_line_end) = content.find('\n') else {
298 return (Vec::new(), content);
299 };
300 let first = content[..first_line_end].trim_end_matches('\r');
301
302 if first.trim().chars().all(|ch| ch == '-') && first.trim().len() >= 3 {
303 let mut metadata = Vec::new();
304 let mut offset = first_line_end + 1;
305 let mut unclosed_body_start = None;
306 for raw_line in content[offset..].split_inclusive('\n') {
307 let line_start = offset;
308 let line = raw_line.trim_end_matches(['\r', '\n']);
309 offset += raw_line.len();
310 let trimmed = line.trim();
311 if unclosed_body_start.is_none() {
312 if trimmed.chars().all(|ch| ch == '-') && trimmed.len() >= 3 {
313 let body = content[offset..].trim_start_matches(['\r', '\n']);
314 return (metadata, body);
315 }
316 if let Some((key, value)) = line.split_once(':') {
317 let key = key.trim().to_ascii_lowercase();
318 let raw_value = value.trim();
319 let value = if key == "allowed-tools" {
320 raw_value.to_string()
321 } else {
322 strip_matched_quotes(raw_value).to_string()
323 };
324 if !key.is_empty() {
325 metadata.push((key, value));
326 }
327 } else if !trimmed.is_empty() {
328 unclosed_body_start = Some(line_start);
329 }
330 }
331 }
332 let body_start = unclosed_body_start.unwrap_or(content.len());
333 let body = content[body_start..].trim_start_matches(['\r', '\n']);
334 return (metadata, body);
335 }
336
337 (Vec::new(), content)
338 }
339
340 fn strip_matched_quotes(value: &str) -> &str {
341 if let Some(stripped) = value.strip_prefix('"').and_then(|v| v.strip_suffix('"')) {
342 return stripped;
343 }
344 if let Some(stripped) = value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')) {
345 return stripped;
346 }
347 value
348 }
349
350 pub(crate) fn parse_allowed_tools(value: &str) -> Vec<String> {
351 value
352 .split(',')
353 .map(|tool| {
354 strip_matched_quotes(tool.trim())
355 .trim()
356 .to_ascii_lowercase()
357 })
358 .filter(|tool| !tool.is_empty())
359 .collect()
360 }
361
362 /// Check if the input matches a user-defined command and return the
363 /// content as a `SendMessage` action.
364 ///
365 /// The `input` should be the full command string including the `/`
366 /// prefix (e.g. `/mycmd` or `/mycmd with args`). Only exact matches
367 /// on the command name are considered (no partial/alias matching).
368 /// Substitute $1, $2, $ARGUMENTS placeholders in a command template.
369 pub(crate) fn apply_template(template: &str, args: &str) -> String {
370 let positional: Vec<&str> = args.split_whitespace().collect();
371 let mut result = String::with_capacity(template.len() + args.len());
372 let mut rest = template;
373 while let Some(pos) = rest.find('$') {
374 result.push_str(&rest[..pos]);
375 let after = &rest[pos + 1..];
376 if let Some(tail) = after.strip_prefix("ARGUMENTS") {
377 result.push_str(args);
378 rest = tail;
379 continue;
380 }
381 let digits = if after.starts_with('0') {
382 0
383 } else {
384 after.bytes().take_while(u8::is_ascii_digit).count()
385 };
386 let arg = after[..digits]
387 .parse::<usize>()
388 .ok()
389 .and_then(|n| positional.get(n - 1));
390 if let Some(arg) = arg {
391 result.push_str(arg);
392 rest = &after[digits..];
393 } else {
394 result.push('$');
395 rest = after;
396 }
397 }
398 result.push_str(rest);
399 result
400 }
401
402 #[cfg(test)]
403 pub fn try_dispatch_user_command(app: &mut App, input: &str) -> Option<CommandResult> {
404 let parts: Vec<&str> = input.trim().splitn(2, ' ').collect();
405 let command = parts[0].to_lowercase();
406 let command = command.strip_prefix('/').unwrap_or(&command);
407 let args = parts.get(1).copied().unwrap_or("").trim();
408
409 let user_commands = load_user_commands(Some(&app.workspace));
410
411 for (name, content) in &user_commands {
412 if name == command {
413 let (metadata, body) = parse_frontmatter(content);
414 app.goal.objective = None;
415 app.goal.started_at = None;
416 app.goal.status = codewhale_engine::tools::goal::GoalStatus::Active;
417 app.goal.token_budget = None;
418 app.goal.tokens_used = 0;
419 app.goal.time_used_seconds = 0;
420 app.goal.continuation_count = 0;
421 app.active_allowed_tools = None;
422 app.pausable = false;
423 app.paused = false;
424 app.paused_goal_objective = None;
425 // Clear todos and plan state from the previous command so they
426 // don't bleed into the next one. Both are behind the same locks
427 // the sidebar reads; a contended/poisoned lock is logged and
428 // skipped rather than blocking dispatch.
429 if let Ok(mut todos) = app.todos.try_lock() {
430 todos.clear();
431 } else {
432 tracing::warn!(target: "commands", "todos lock contended or poisoned — previous todos not cleared");
433 }
434 if let Ok(mut plan) = app.plan_state.try_lock() {
435 *plan = codewhale_engine::tools::plan::PlanState::default();
436 } else {
437 tracing::warn!(target: "commands", "plan_state lock contended or poisoned — previous plan not cleared");
438 }
439 for (key, value) in &metadata {
440 match key.as_str() {
441 "description" => {
442 app.goal.objective = Some(value.clone());
443 app.goal.started_at = Some(std::time::Instant::now());
444 }
445 "allowed-tools" => {
446 app.active_allowed_tools = Some(parse_allowed_tools(value));
447 }
448 "pausable" => {
449 app.pausable = value.trim().eq_ignore_ascii_case("true");
450 }
451 _ => {}
452 }
453 }
454 let message = apply_template(body, args);
455 return Some(CommandResult::action(AppAction::SendMessage(message)));
456 }
457 }
458
459 None
460 }
461
462 #[cfg(test)]
463 mod tests {
464 use super::*;
465 use tempfile::TempDir;
466
467 /// Workspace commands load only in a trusted workspace.
468 fn trusted_workspace() -> TempDir {
469 let tmp = TempDir::new().unwrap();
470 codewhale_runtime::config::save_workspace_trust(tmp.path()).expect("trust test workspace");
471 tmp
472 }
473
474 #[test]
475 fn oversized_command_file_is_skipped_not_loaded() {
476 let tmp = TempDir::new().unwrap();
477 std::fs::write(tmp.path().join("small.md"), "small").unwrap();
478 std::fs::write(
479 tmp.path().join("huge.md"),
480 vec![b'x'; MAX_COMMAND_FILE_BYTES as usize + 1],
481 )
482 .unwrap();
483 let names: Vec<String> = load_command_entries_from_component(tmp.path())
484 .into_iter()
485 .map(|(name, _, _)| name)
486 .collect();
487 assert_eq!(names, vec!["small".to_string()]);
488 }
489
490 #[test]
491 fn invalid_utf8_command_file_is_skipped_not_loaded() {
492 let tmp = TempDir::new().unwrap();
493 std::fs::write(tmp.path().join("valid.md"), "valid").unwrap();
494 std::fs::write(tmp.path().join("broken.md"), [0xff, 0xfe, 0x00, 0xc3]).unwrap();
495 let names: Vec<String> = load_command_entries_from_component(tmp.path())
496 .into_iter()
497 .map(|(name, _, _)| name)
498 .collect();
499 assert_eq!(names, vec!["valid".to_string()]);
500 }
501
502 #[test]
503 fn test_global_commands_dir_contains_codewhale_commands() {
504 let dir = global_commands_dir();
505 let parts: Vec<_> = dir
506 .components()
507 .filter_map(|component| component.as_os_str().to_str())
508 .collect();
509 assert!(
510 parts
511 .windows(2)
512 .any(|pair| pair == [".codewhale", "commands"]),
513 "expected .codewhale/commands components in path, got: {}",
514 dir.display()
515 );
516 }
517
518 #[test]
519 fn test_load_user_commands_when_no_dir_exists() {
520 let cmds = load_user_commands(None);
521 // Should not panic; returns empty vec when no directories exist.
522 assert!(cmds.is_empty() || !cmds.is_empty());
523 }
524
525 #[test]
526 fn test_try_dispatch_nonexistent_command() {
527 use crate::tui::app::TuiOptions;
528 use codewhale_runtime::config::Config;
529
530 let options = TuiOptions {
531 ..crate::tui::test_support::test_tui_options(PathBuf::from("."))
532 };
533 let mut app = App::new(options, &Config::default());
534 let result = try_dispatch_user_command(&mut app, "/nonexistent-thing-12345");
535 assert!(result.is_none());
536 }
537
538 // ── Workspace-local commands tests ─────────────────────────────────
539
540 fn write_command(dir: &Path, name: &str, body: &str) {
541 std::fs::create_dir_all(dir).unwrap();
542 std::fs::write(dir.join(format!("{name}.md")), body).unwrap();
543 }
544
545 fn test_options(workspace: PathBuf) -> crate::tui::app::TuiOptions {
546 crate::tui::app::TuiOptions {
547 ..crate::tui::test_support::test_tui_options(workspace)
548 }
549 }
550
551 #[test]
552 fn load_user_commands_scans_workspace_local_dir() {
553 let tmp = trusted_workspace();
554 let ws = tmp.path();
555 let cmds_dir = ws.join(".codewhale").join("commands");
556 write_command(&cmds_dir, "hello", "echo hi");
557
558 let cmds = load_user_commands(Some(ws));
559 let names: Vec<&str> = cmds.iter().map(|(n, _)| n.as_str()).collect();
560 assert!(
561 names.contains(&"hello"),
562 "expected 'hello' in workspace-local commands: {names:?}"
563 );
564 }
565
566 #[test]
567 fn load_user_commands_scans_claude_and_cursor_dirs() {
568 let tmp = trusted_workspace();
569 let ws = tmp.path();
570 write_command(
571 &ws.join(".claude").join("commands"),
572 "claude-cmd",
573 "claude body",
574 );
575 write_command(
576 &ws.join(".cursor").join("commands"),
577 "cursor-cmd",
578 "cursor body",
579 );
580
581 let cmds = load_user_commands(Some(ws));
582 let names: Vec<&str> = cmds.iter().map(|(n, _)| n.as_str()).collect();
583 assert!(
584 names.contains(&"claude-cmd"),
585 "expected 'claude-cmd': {names:?}"
586 );
587 assert!(
588 names.contains(&"cursor-cmd"),
589 "expected 'cursor-cmd': {names:?}"
590 );
591 }
592
593 #[test]
594 fn workspace_local_shadows_global_by_name() {
595 let tmp = trusted_workspace();
596 let ws = tmp.path();
597
598 // Workspace-local version
599 write_command(
600 &ws.join(".codewhale").join("commands"),
601 "shared",
602 "workspace version",
603 );
604 // Global version — simulate by putting it in a "global" temp dir.
605 // Paths resolve via codewhale_paths::user_home (HOME/USERPROFILE-aware). We test the
606 // first-match-wins semantics by putting the same name in both
607 // workspace-scanned dirs. The first dir in precedence order wins.
608 write_command(
609 &ws.join(".claude").join("commands"),
610 "shared",
611 "claude version",
612 );
613
614 let cmds = load_user_commands(Some(ws));
615 let shared = cmds
616 .iter()
617 .find(|(n, _)| n == "shared")
618 .expect("shared present");
619 assert_eq!(
620 shared.1, "workspace version",
621 "workspace-local (.codewhale) must shadow later dirs"
622 );
623 }
624
625 #[test]
626 fn load_user_commands_without_workspace_falls_back_to_global_only() {
627 // When no workspace is passed, only global command directories are
628 // scanned. On test machines these often don't exist, so we just
629 // verify we don't panic.
630 let cmds = load_user_commands(None);
631 // This should not panic; can be empty or have user's real commands.
632 let _ = cmds;
633 }
634
635 #[test]
636 fn try_dispatch_uses_workspace_local_command() {
637 use crate::tui::app::TuiOptions;
638 use codewhale_runtime::config::Config;
639
640 let tmp = trusted_workspace();
641 let ws = tmp.path().to_path_buf();
642 write_command(
643 &ws.join(".deepseek").join("commands"),
644 "hello",
645 "Hello, $ARGUMENTS!",
646 );
647
648 let options = TuiOptions {
649 ..crate::tui::test_support::test_tui_options(ws.clone())
650 };
651 let mut app = App::new(options, &Config::default());
652 let result = try_dispatch_user_command(&mut app, "/hello world");
653 assert!(result.is_some());
654 let cmd_result = result.unwrap();
655 match cmd_result.action {
656 Some(AppAction::SendMessage(msg)) => {
657 assert!(msg.contains("Hello, world!"), "got: {msg}");
658 }
659 other => panic!("expected SendMessage action, got: {other:?}"),
660 }
661 }
662
663 #[test]
664 fn frontmatter_is_stripped_before_dispatch() {
665 use codewhale_runtime::config::Config;
666
667 let tmp = trusted_workspace();
668 let ws = tmp.path().to_path_buf();
669 write_command(
670 &ws.join(".deepseek").join("commands"),
671 "secure",
672 "---\ndescription: Secure scan\nallowed-tools: Bash, Read\n---\nRun $ARGUMENTS",
673 );
674
675 let mut app = App::new(test_options(ws), &Config::default());
676 let result = try_dispatch_user_command(&mut app, "/secure checks").unwrap();
677 match result.action {
678 Some(AppAction::SendMessage(msg)) => assert_eq!(msg, "Run checks"),
679 other => panic!("expected SendMessage action, got: {other:?}"),
680 }
681 }
682
683 #[test]
684 fn review_regression_unclosed_frontmatter_keeps_metadata_and_strips_header() {
685 let (metadata, body) = parse_frontmatter(
686 "---\ndescription: Broken command\nallowed-tools: Bash\nRun the safe body",
687 );
688
689 assert_eq!(
690 metadata,
691 vec![
692 ("description".to_string(), "Broken command".to_string()),
693 ("allowed-tools".to_string(), "Bash".to_string())
694 ]
695 );
696 assert_eq!(body, "Run the safe body");
697 }
698
699 #[test]
700 fn review_regression_unclosed_frontmatter_without_metadata_strips_header() {
701 let (metadata, body) =
702 parse_frontmatter("---\nRun the command body without a closing delimiter");
703
704 assert!(metadata.is_empty());
705 assert_eq!(body, "Run the command body without a closing delimiter");
706 }
707
708 #[test]
709 fn review_regression_frontmatter_strips_only_matched_quote_pairs() {
710 let (metadata, body) = parse_frontmatter("---\ndescription: 'Read\"\n---\nrun");
711
712 assert_eq!(
713 metadata,
714 vec![("description".to_string(), "'Read\"".to_string())]
715 );
716 assert_eq!(body, "run");
717 }
718
719 #[test]
720 fn allowed_tools_frontmatter_sets_app_state() {
721 use codewhale_runtime::config::Config;
722
723 let tmp = trusted_workspace();
724 let ws = tmp.path().to_path_buf();
725 write_command(
726 &ws.join(".deepseek").join("commands"),
727 "secure",
728 "---\nallowed-tools: Bash, Grep\n---\nrun tests",
729 );
730
731 let mut app = App::new(test_options(ws), &Config::default());
732 let _ = try_dispatch_user_command(&mut app, "/secure").unwrap();
733 assert_eq!(
734 app.active_allowed_tools,
735 Some(vec!["bash".to_string(), "grep".to_string()])
736 );
737 }
738
739 #[test]
740 fn pausable_frontmatter_sets_app_state_without_worktree_mutation() {
741 use codewhale_runtime::config::Config;
742
743 if std::process::Command::new("git")
744 .arg("--version")
745 .output()
746 .is_err()
747 {
748 return;
749 }
750
751 let tmp = trusted_workspace();
752 let ws = tmp.path().to_path_buf();
753 let init = std::process::Command::new("git")
754 .args(["-C", ws.to_str().unwrap(), "init"])
755 .output()
756 .expect("git init");
757 assert!(
758 init.status.success(),
759 "git init failed: {}",
760 String::from_utf8_lossy(&init.stderr)
761 );
762 std::fs::write(ws.join("user-work.txt"), "untracked user work").unwrap();
763 write_command(
764 &ws.join(".codewhale").join("commands"),
765 "pause-scan",
766 "---\ndescription: Scan repos\npausable: true\n---\nscan",
767 );
768
769 let mut app = App::new(test_options(ws.clone()), &Config::default());
770 let _ = try_dispatch_user_command(&mut app, "/pause-scan").unwrap();
771
772 assert!(app.pausable);
773 assert!(!app.paused);
774 assert!(app.paused_goal_objective.is_none());
775 assert!(ws.join("user-work.txt").exists());
776 let stash = std::process::Command::new("git")
777 .args(["-C", ws.to_str().unwrap(), "stash", "list"])
778 .output()
779 .expect("git stash list");
780 assert!(
781 stash.status.success(),
782 "git stash list failed: {}",
783 String::from_utf8_lossy(&stash.stderr)
784 );
785 assert!(
786 String::from_utf8_lossy(&stash.stdout).trim().is_empty(),
787 "pausable dispatch must not create git stash entries"
788 );
789 }
790
791 #[test]
792 fn new_user_command_clears_stale_paused_state() {
793 use codewhale_runtime::config::Config;
794
795 let tmp = trusted_workspace();
796 let ws = tmp.path().to_path_buf();
797 let commands_dir = ws.join(".codewhale").join("commands");
798 write_command(
799 &commands_dir,
800 "pause-scan",
801 "---\ndescription: Scan repos\npausable: true\n---\nscan",
802 );
803 write_command(&commands_dir, "plain", "plain command");
804
805 let mut app = App::new(test_options(ws), &Config::default());
806 let _ = try_dispatch_user_command(&mut app, "/pause-scan").unwrap();
807 app.paused = true;
808 app.paused_goal_objective = Some("Scan repos".to_string());
809
810 let _ = try_dispatch_user_command(&mut app, "/plain").unwrap();
811
812 assert!(!app.pausable);
813 assert!(!app.paused);
814 assert!(app.paused_goal_objective.is_none());
815 }
816
817 #[test]
818 fn new_user_command_clears_previous_todos_and_plan() {
819 use codewhale_engine::tools::plan::UpdatePlanArgs;
820 use codewhale_engine::tools::todo::TodoStatus;
821 use codewhale_runtime::config::Config;
822
823 let tmp = trusted_workspace();
824 let ws = tmp.path().to_path_buf();
825 let commands_dir = ws.join(".codewhale").join("commands");
826 write_command(&commands_dir, "first", "first command body");
827 write_command(&commands_dir, "second", "second command body");
828
829 let mut app = App::new(test_options(ws), &Config::default());
830
831 // Seed the state a previous command would leave behind: a non-empty
832 // todo list and a non-empty plan. These should NOT bleed into the
833 // next command. The shared lists are tokio async mutexes, so seed and
834 // observe through `try_lock` (the same sync path dispatch uses).
835 {
836 let mut todos = app.todos.try_lock().expect("todos lock");
837 todos.add(
838 "leftover task from first command".to_string(),
839 TodoStatus::Pending,
840 );
841 }
842 {
843 let mut plan = app.plan_state.try_lock().expect("plan_state lock");
844 plan.update(UpdatePlanArgs {
845 title: Some("leftover plan".to_string()),
846 objective: Some("old goal".to_string()),
847 ..Default::default()
848 });
849 }
850
851 // Dispatch a fresh command — dispatch must reset both.
852 let _ = try_dispatch_user_command(&mut app, "/second").unwrap();
853
854 assert!(
855 app.todos
856 .try_lock()
857 .expect("todos lock")
858 .snapshot()
859 .items
860 .is_empty(),
861 "previous command's todos must be cleared on new command dispatch"
862 );
863 assert!(
864 app.plan_state
865 .try_lock()
866 .expect("plan_state lock")
867 .snapshot()
868 .is_empty(),
869 "previous command's plan must be cleared on new command dispatch"
870 );
871 }
872
873 #[test]
874 fn review_regression_empty_allowed_tools_blocks_all_tools() {
875 use codewhale_runtime::config::Config;
876
877 let tmp = trusted_workspace();
878 let ws = tmp.path().to_path_buf();
879 write_command(
880 &ws.join(".deepseek").join("commands"),
881 "locked",
882 "---\nallowed-tools: \"\"\n---\nrun nothing",
883 );
884
885 let mut app = App::new(test_options(ws), &Config::default());
886 let _ = try_dispatch_user_command(&mut app, "/locked").unwrap();
887 assert_eq!(app.active_allowed_tools, Some(Vec::new()));
888 }
889
890 #[test]
891 fn review_regression_allowed_tools_accepts_per_item_quotes() {
892 use codewhale_runtime::config::Config;
893
894 let tmp = trusted_workspace();
895 let ws = tmp.path().to_path_buf();
896 write_command(
897 &ws.join(".deepseek").join("commands"),
898 "quoted",
899 "---\nallowed-tools: \"exec_shell\", 'read_file'\n---\nrun quoted tools",
900 );
901
902 let mut app = App::new(test_options(ws), &Config::default());
903 let _ = try_dispatch_user_command(&mut app, "/quoted").unwrap();
904 assert_eq!(
905 app.active_allowed_tools,
906 Some(vec!["exec_shell".to_string(), "read_file".to_string()])
907 );
908 }
909
910 #[test]
911 fn review_regression_dispatch_without_frontmatter_resets_previous_command_state() {
912 use codewhale_runtime::config::Config;
913
914 let tmp = trusted_workspace();
915 let ws = tmp.path().to_path_buf();
916 let commands_dir = ws.join(".deepseek").join("commands");
917 write_command(
918 &commands_dir,
919 "described",
920 "---\ndescription: Scan repos\nallowed-tools: Bash\n---\nscan",
921 );
922 write_command(&commands_dir, "plain", "plain command");
923
924 let mut app = App::new(test_options(ws), &Config::default());
925 let _ = try_dispatch_user_command(&mut app, "/described").unwrap();
926 assert_eq!(app.goal.objective.as_deref(), Some("Scan repos"));
927 assert!(app.goal.started_at.is_some());
928 assert_eq!(
929 app.goal.status,
930 codewhale_engine::tools::goal::GoalStatus::Active
931 );
932 assert_eq!(app.goal.token_budget, None);
933 assert_eq!(app.active_allowed_tools, Some(vec!["bash".to_string()]));
934
935 app.goal.status = codewhale_engine::tools::goal::GoalStatus::Blocked;
936 app.goal.token_budget = Some(42);
937 app.goal.tokens_used = 100;
938 app.goal.time_used_seconds = 5;
939 app.goal.continuation_count = 1;
940 let _ = try_dispatch_user_command(&mut app, "/plain").unwrap();
941 assert_eq!(app.goal.objective, None);
942 assert_eq!(app.goal.started_at, None);
943 assert_eq!(
944 app.goal.status,
945 codewhale_engine::tools::goal::GoalStatus::Active
946 );
947 assert_eq!(app.goal.token_budget, None);
948 assert_eq!(app.goal.tokens_used, 0);
949 assert_eq!(app.goal.time_used_seconds, 0);
950 assert_eq!(app.goal.continuation_count, 0);
951 assert_eq!(app.active_allowed_tools, None);
952 }
953
954 #[test]
955 fn description_frontmatter_sets_work_objective_and_autocomplete_description() {
956 use codewhale_runtime::config::Config;
957
958 let tmp = trusted_workspace();
959 let ws = tmp.path().to_path_buf();
960 write_command(
961 &ws.join(".deepseek").join("commands"),
962 "git-scan",
963 "---\ndescription: Scan nested git repositories\nargument-hint: <root>\n---\nscan",
964 );
965
966 let mut app = App::new(test_options(ws.clone()), &Config::default());
967 let _ = try_dispatch_user_command(&mut app, "/git-scan").unwrap();
968 assert_eq!(
969 app.goal.objective.as_deref(),
970 Some("Scan nested git repositories")
971 );
972 let commands = load_user_commands(Some(&ws));
973 let (_, content) = commands
974 .iter()
975 .find(|(name, _)| name == "git-scan")
976 .expect("git-scan command should load");
977 let (metadata, _) = parse_frontmatter(content);
978 assert!(metadata.contains(&(
979 "description".to_string(),
980 "Scan nested git repositories".to_string()
981 )));
982 assert!(metadata.contains(&("argument-hint".to_string(), "<root>".to_string())));
983 }
984
985 #[test]
986 fn parser_preserves_layer_5_1_frontmatter_fields() {
987 let (metadata, body) = parse_frontmatter(
988 "---\nname: inspect\ndescription: Inspect a target\nusage: /inspect <path>\narguments: <path>\nhidden: false\nallowed-tools: Read_File, Grep_Files\n---\ninspect $ARGUMENTS",
989 );
990
991 assert!(metadata.contains(&("name".to_string(), "inspect".to_string())));
992 assert!(metadata.contains(&("description".to_string(), "Inspect a target".to_string())));
993 assert!(metadata.contains(&("usage".to_string(), "/inspect <path>".to_string())));
994 assert!(metadata.contains(&("arguments".to_string(), "<path>".to_string())));
995 assert!(metadata.contains(&("hidden".to_string(), "false".to_string())));
996 assert!(metadata.contains(&(
997 "allowed-tools".to_string(),
998 "Read_File, Grep_Files".to_string()
999 )));
1000 assert_eq!(body, "inspect $ARGUMENTS");
1001 }
1002
1003 #[test]
1004 fn apply_template_substitutes_in_one_pass() {
1005 assert_eq!(
1006 apply_template("explain $ARGUMENTS", "why does awk '{print $1}' fail"),
1007 "explain why does awk '{print $1}' fail"
1008 );
1009 assert_eq!(
1010 apply_template("ship $1 with $ARGUMENTS", "$2 off"),
1011 "ship $2 with $2 off"
1012 );
1013 assert_eq!(apply_template("$10|$1", "a b c d e f g h i j"), "j|a");
1014 assert_eq!(apply_template("$1 $3 $0 $ x", "a b"), "a $3 $0 $ x");
1015 assert_eq!(apply_template("$12", "a"), "$12");
1016 assert_eq!(apply_template("$01", "a"), "$01");
1017 }
1018 }
1019
1019 lines RUST