Skip to main content

symforge/cli/
harness_command.rs

1//! Per-harness `symforge-admin` command-file install (009 US3, D2).
2//!
3//! Installs a `symforge-admin` command file where the harness supports one (e.g.
4//! Claude Code `~/.claude/commands/symforge-admin.md`); harnesses without a
5//! command-file convention rely on the universal MCP prompt instead (no guessed
6//! or broken file — the MCP prompt is the floor). Reuses the restorable-backup
7//! write path (FR-016).
8//!
9//! The universal affordance is the MCP prompt `symforge-admin` (registered in
10//! `protocol::prompts`); this module is the *convenience layer* — a one-keystroke
11//! slash-command for harnesses that document a command-file format. Across the
12//! live [`HarnessId`] set, only **Claude Code** documents one (markdown
13//! slash-commands under `~/.claude/commands/`); the rest (Codex, Gemini, Cursor,
14//! KiloCode, Claude Desktop) get the MCP prompt only — guessing a format we
15//! cannot verify would ship a broken affordance (a nonworking feature, D2).
16
17use std::path::{Path, PathBuf};
18
19use crate::cli::harness::HarnessId;
20use crate::cli::harness_apply::{BackupRecord, write_backup};
21
22/// On-disk filename for the Claude Code `symforge-admin` slash-command file
23/// installed under `~/.claude/commands/`.
24pub const CLAUDE_ADMIN_COMMAND_FILE: &str = "symforge-admin.md";
25
26/// Markdown body of the Claude Code `/symforge-admin` slash-command. Invoking it
27/// runs the `symforge admin` CLI verb, which returns a running dashboard's URL
28/// immediately or starts a new server in the foreground (contracts/command-file.md).
29const CLAUDE_ADMIN_COMMAND_BODY: &str = "\
30---
31description: Open the SymForge operator dashboard (reuse a running server, or start one in the background)
32---
33
34Run the SymForge admin verb to open the operator dashboard.
35
36Execute this command in the project root:
37
38```
39symforge admin
40```
41
42If a dashboard is already running on the remembered port, `symforge admin` prints
43its URL and returns immediately. If none is running it STARTS a new server and
44serves it IN THE FOREGROUND until you stop it (Ctrl-C) — so if you are an agent
45running this in a shell tool, launch it as a background/detached process (e.g.
46append `&` or run it detached) and then read the printed dashboard URL, or the
47tool call blocks until it times out and kills the fresh server.
48
49If your environment cannot run shell commands, use the `symforge-admin` MCP
50prompt instead, which reports the running dashboard URL.
51";
52
53/// Whether a harness got a command file installed, and where — or why it did not.
54///
55/// Returned per harness from [`install_admin_command_file`] so the caller can
56/// report exactly which harness got the one-keystroke command vs which rely on
57/// the universal MCP prompt (no harness silently gets nothing — the MCP prompt is
58/// the floor for all of them).
59///
60/// `PartialEq`/`Eq` are intentionally not derived: the `Installed` variant holds
61/// a [`BackupRecord`] (a `005` type that does not implement them, and whose
62/// timestamped backup path is not a meaningful equality key). Callers match on
63/// the variant instead.
64#[derive(Debug, Clone)]
65pub enum CommandFileOutcome {
66    /// A command file was written at `path` (with `backup` if it pre-existed).
67    Installed {
68        id: HarnessId,
69        path: PathBuf,
70        backup: Option<BackupRecord>,
71    },
72    /// The harness documents no command-file format; it relies on the MCP prompt
73    /// only. No file was written (no guessed/broken affordance).
74    PromptOnly { id: HarnessId },
75    /// Writing the command file failed; the harness still has the MCP prompt.
76    Failed { id: HarnessId, reason: String },
77}
78
79/// Install the `symforge-admin` command file for a single harness under `home`.
80///
81/// - **Claude Code**: writes `<home>/.claude/commands/symforge-admin.md`, backing
82///   up any pre-existing file first (restorable-backup path, FR-016) and writing
83///   atomically.
84/// - **Any other harness**: writes nothing and returns
85///   [`CommandFileOutcome::PromptOnly`] — these harnesses use the MCP prompt
86///   (D2, no guessed format).
87///
88/// `home` is injected (a TempDir in tests, the operator home in production) so no
89/// real config is touched in tests (FR-018).
90pub fn install_admin_command_file(home: &Path, id: HarnessId) -> CommandFileOutcome {
91    match id {
92        HarnessId::ClaudeCode => install_claude_admin_command_file(home),
93        // No documented command-file format → the MCP prompt is the affordance.
94        HarnessId::ClaudeDesktop
95        | HarnessId::Codex
96        | HarnessId::Gemini
97        | HarnessId::KiloCode
98        | HarnessId::Cursor => CommandFileOutcome::PromptOnly { id },
99    }
100}
101
102/// Install the Claude Code command file under `<home>/.claude/commands/`,
103/// backing up an existing file first (restorable-backup path) and writing
104/// atomically.
105fn install_claude_admin_command_file(home: &Path) -> CommandFileOutcome {
106    let id = HarnessId::ClaudeCode;
107    let path = claude_admin_command_path(home);
108
109    if let Some(parent) = path.parent()
110        && let Err(e) = std::fs::create_dir_all(parent)
111    {
112        return CommandFileOutcome::Failed {
113            id,
114            reason: format!("creating {}: {e}", parent.display()),
115        };
116    }
117
118    // Back up any pre-existing command file before overwriting (restorable
119    // backup, FR-016) so an operator's custom command is never lost unbacked.
120    let backup = if path.exists() {
121        match write_backup(&path) {
122            Ok(record) => Some(record),
123            Err(e) => {
124                return CommandFileOutcome::Failed {
125                    id,
126                    reason: format!("backing up {}: {e}", path.display()),
127                };
128            }
129        }
130    } else {
131        None
132    };
133
134    if let Err(e) = atomic_write(&path, CLAUDE_ADMIN_COMMAND_BODY.as_bytes()) {
135        return CommandFileOutcome::Failed {
136            id,
137            reason: format!("writing {}: {e}", path.display()),
138        };
139    }
140
141    CommandFileOutcome::Installed { id, path, backup }
142}
143
144/// The Claude Code `symforge-admin` command-file path under `home`.
145fn claude_admin_command_path(home: &Path) -> PathBuf {
146    home.join(".claude")
147        .join("commands")
148        .join(CLAUDE_ADMIN_COMMAND_FILE)
149}
150
151/// Atomically write `content` to `path` (temp file in the same dir + rename),
152/// mirroring `harness_apply::atomic_write` (private to that module) and
153/// `operator_profile::atomic_write_in`.
154fn atomic_write(path: &Path, content: &[u8]) -> std::io::Result<()> {
155    use std::io::Write;
156    let parent = path.parent().ok_or_else(|| {
157        std::io::Error::new(
158            std::io::ErrorKind::InvalidInput,
159            "command-file path has no parent directory",
160        )
161    })?;
162    let mut tmp = tempfile::NamedTempFile::new_in(parent)?;
163    tmp.write_all(content)?;
164    tmp.flush()?;
165    tmp.as_file().sync_all()?;
166    // rename(2) on Unix / MoveFileExW(MOVEFILE_REPLACE_EXISTING) on Windows.
167    tmp.persist(path).map_err(|e| e.error)?;
168    Ok(())
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    #[test]
176    fn installs_claude_code_command_file() {
177        let home = tempfile::tempdir().expect("temp home");
178        let outcome = install_admin_command_file(home.path(), HarnessId::ClaudeCode);
179
180        let path = match outcome {
181            CommandFileOutcome::Installed { path, backup, id } => {
182                assert_eq!(id, HarnessId::ClaudeCode);
183                assert!(backup.is_none(), "fresh install has no backup");
184                path
185            }
186            other => panic!("expected Installed, got {other:?}"),
187        };
188
189        assert_eq!(path, claude_admin_command_path(home.path()));
190        let body = std::fs::read_to_string(&path).expect("command file written");
191        assert!(
192            body.contains("symforge admin"),
193            "body invokes the verb: {body}"
194        );
195        assert!(
196            body.contains("description:"),
197            "body has slash-command front matter"
198        );
199    }
200
201    #[test]
202    fn reinstall_backs_up_existing_command_file() {
203        let home = tempfile::tempdir().expect("temp home");
204        let path = claude_admin_command_path(home.path());
205        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
206        let prior = "my custom symforge-admin command\n";
207        std::fs::write(&path, prior).unwrap();
208
209        let outcome = install_admin_command_file(home.path(), HarnessId::ClaudeCode);
210        let backup = match outcome {
211            CommandFileOutcome::Installed {
212                backup: Some(b), ..
213            } => b,
214            other => panic!("expected Installed with a backup, got {other:?}"),
215        };
216
217        // The new body is in place; the prior body is preserved byte-exact in the
218        // backup (restorable).
219        let body = std::fs::read_to_string(&path).unwrap();
220        assert!(body.contains("symforge admin"));
221        assert_eq!(std::fs::read_to_string(&backup.backup).unwrap(), prior);
222    }
223
224    #[test]
225    fn no_format_harness_installs_nothing() {
226        let home = tempfile::tempdir().expect("temp home");
227        for id in [
228            HarnessId::Codex,
229            HarnessId::Gemini,
230            HarnessId::Cursor,
231            HarnessId::KiloCode,
232            HarnessId::ClaudeDesktop,
233        ] {
234            let outcome = install_admin_command_file(home.path(), id);
235            match outcome {
236                CommandFileOutcome::PromptOnly { id: got } => assert_eq!(got, id),
237                other => panic!(
238                    "{id:?} has no documented command-file format; \
239                     expected PromptOnly, got {other:?}"
240                ),
241            }
242        }
243        // No `.claude` tree was created for the no-format harnesses (the Claude
244        // Code path is the only writer).
245        assert!(!home.path().join(".claude").exists());
246    }
247}