Skip to main content

par_term_config/
agent_commands.rs

1//! Agent-authored command files: load, validate, and persist the per-command
2//! YAML files under `<config_dir>/commands/`.
3//!
4//! A command file wraps exactly one [`CustomActionConfig`] variant plus
5//! provenance fields. The design (docs/plans/2026-09-24-agent-authored-commands-design.md,
6//! approved 2026-09-24) keeps `id`/`title` inside `action` because every
7//! variant embeds both as required fields; the wrapper carries no duplicate.
8//!
9//! * **script** commands are `shell_command` actions and require first-run
10//!   confirmation keyed on a SHA-256 of the canonical action payload
11//!   (the confirmation ledger, D4b).
12//! * **macro** commands are any of the other five variants and need no
13//!   confirmation.
14//!
15//! Provenance (D4c) lives in the file (`created_by`), not in the path: agents
16//! may freely overwrite files they authored, while user-authored files are
17//! refused by the MCP write path. This module enforces the invariants on
18//! load and provides the write/delete primitives the MCP tools call; it does
19//! not decide policy beyond `action.id == <filename stem>`, which is a
20//! filesystem-safety invariant (no path traversal) rather than a trust rule.
21//!
22//! # Crate placement
23//!
24//! This lives in `par-term-config` because the format wraps
25//! `CustomActionConfig` (defined in this crate) and both the root crate
26//! (palette/dispatch/CLI) and `par-term-mcp` (the write path) must agree on
27//! one definition without an edge through the root crate.
28
29use crate::atomic_save::save_bytes_atomic;
30use crate::snippets::CustomActionConfig;
31use anyhow::{Context, Result, bail};
32use serde::{Deserialize, Serialize};
33use sha2::{Digest, Sha256};
34use std::collections::BTreeMap;
35use std::fs;
36use std::path::{Path, PathBuf};
37
38/// Maximum bytes of one command file accepted on the write path. Bounds
39/// damage from a compromised agent (design, Security notes).
40pub const MAX_COMMAND_FILE_BYTES: usize = 64 * 1024;
41
42/// Maximum number of command files kept in the commands directory.
43pub const MAX_COMMAND_COUNT: usize = 200;
44
45/// Maximum length of a command id in bytes.
46pub const MAX_COMMAND_ID_LEN: usize = 64;
47
48/// The commands directory, `<config_dir>/commands/`.
49pub fn commands_dir() -> PathBuf {
50    crate::config::Config::config_dir().join("commands")
51}
52
53/// The confirmation ledger, `<config_dir>/commands/.confirmations.json`.
54pub fn confirmations_path() -> PathBuf {
55    commands_dir().join(".confirmations.json")
56}
57
58/// A valid command id: `[a-z0-9-]+`, 1..=64 bytes. The charset is deliberate —
59/// it is also the set of characters safe as a filename stem on every platform
60/// and unambiguous inside the `agent-cmd:<id>` keybinding prefix.
61pub fn is_valid_command_id(id: &str) -> bool {
62    !id.is_empty()
63        && id.len() <= MAX_COMMAND_ID_LEN
64        && id
65            .bytes()
66            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
67}
68
69/// Who authored a command file.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
71#[serde(rename_all = "lowercase")]
72pub enum CommandAuthor {
73    /// Written by an agent through the MCP tools (or hand-tagged as such).
74    Agent,
75    /// Written by the user by hand. The field being absent also means user —
76    /// files predate the tag or were dropped in without one.
77    #[default]
78    User,
79}
80
81/// One command file on disk.
82#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
83pub struct AgentCommandFile {
84    /// Who authored this command. Absent deserializes as [`CommandAuthor::User`].
85    #[serde(default)]
86    pub created_by: CommandAuthor,
87
88    /// The authoring agent, required when `created_by == agent`. Validated on
89    /// load; ignored (and pointless) for user commands.
90    #[serde(default, skip_serializing_if = "Option::is_none")]
91    pub source_agent: Option<String>,
92
93    /// Creation timestamp (RFC 3339). Informational only.
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub created_at: Option<String>,
96
97    /// The wrapped action. Exactly one `CustomActionConfig` variant.
98    pub action: CustomActionConfig,
99}
100
101impl AgentCommandFile {
102    /// The command id (delegates to the embedded action's id).
103    pub fn id(&self) -> &str {
104        self.action.id()
105    }
106
107    /// The display title (delegates to the embedded action's title).
108    pub fn title(&self) -> &str {
109        self.action.title()
110    }
111
112    /// Whether this is a script command (a `shell_command` action) — the only
113    /// kind subject to first-run confirmation (D4b).
114    pub fn is_script(&self) -> bool {
115        matches!(self.action, CustomActionConfig::ShellCommand { .. })
116    }
117
118    /// SHA-256 over the canonical serialization of the `action` payload.
119    /// Any change to the action produces a new hash, resetting confirmation.
120    pub fn body_hash(&self) -> String {
121        let bytes = serde_json::to_vec(&self.action).unwrap_or_default();
122        let digest = Sha256::digest(&bytes);
123        let mut hex = String::with_capacity(digest.len() * 2);
124        for b in digest {
125            use std::fmt::Write as _;
126            let _ = write!(hex, "{b:02x}");
127        }
128        hex
129    }
130
131    /// Palette label per the design: `<title> · agent (<source_agent>)` for
132    /// agent commands, plain `<title>` for user commands.
133    pub fn palette_label(&self) -> String {
134        match (self.created_by, &self.source_agent) {
135            (CommandAuthor::Agent, Some(agent)) => {
136                format!("{} · agent ({})", self.title(), agent)
137            }
138            _ => self.title().to_string(),
139        }
140    }
141}
142
143/// Load and validate one command file.
144///
145/// Validation: id charset/length, `action.id == <filename stem>`, and
146/// `source_agent` present when `created_by == agent`. The stem equality check
147/// doubles as the no-path-traversal guard for the whole feature — an id can
148/// never name a file other than its own.
149pub fn load_command_file(path: &Path) -> Result<AgentCommandFile> {
150    let stem = path
151        .file_stem()
152        .and_then(|s| s.to_str())
153        .context("command file has no UTF-8 stem")?;
154
155    let bytes = fs::read(path).with_context(|| format!("reading {}", path.display()))?;
156    if bytes.len() > MAX_COMMAND_FILE_BYTES {
157        bail!(
158            "command file {} exceeds {} bytes",
159            path.display(),
160            MAX_COMMAND_FILE_BYTES
161        );
162    }
163
164    let file: AgentCommandFile =
165        serde_yaml_ng::from_slice(&bytes).with_context(|| format!("parsing {}", path.display()))?;
166
167    validate_command(&file, stem)?;
168    Ok(file)
169}
170
171/// Validate an in-memory command against its expected filename stem.
172pub fn validate_command(file: &AgentCommandFile, expected_stem: &str) -> Result<()> {
173    let id = file.id();
174    if !is_valid_command_id(id) {
175        bail!(
176            "command id {:?} is invalid: 1-{} bytes of [a-z0-9-]",
177            id,
178            MAX_COMMAND_ID_LEN
179        );
180    }
181    if id != expected_stem {
182        bail!(
183            "action id {:?} does not match filename stem {:?}",
184            id,
185            expected_stem
186        );
187    }
188    if file.created_by == CommandAuthor::Agent
189        && file.source_agent.as_deref().unwrap_or("").is_empty()
190    {
191        bail!("source_agent is required when created_by is agent");
192    }
193    if let Some(agent) = &file.source_agent
194        && agent.trim().is_empty()
195    {
196        bail!("source_agent must not be blank");
197    }
198    Ok(())
199}
200
201/// A validated command plus its source path, as kept in the store's snapshot.
202#[derive(Debug, Clone)]
203pub struct LoadedCommand {
204    pub file: AgentCommandFile,
205    pub path: PathBuf,
206}
207
208/// Load every valid command in the directory. Invalid files are skipped with
209/// a log line, never a dialog storm (design, Directory watching). Hidden
210/// files (the ledger, editor droppings) and non-YAML files are ignored.
211pub fn load_all_commands(dir: &Path) -> Vec<LoadedCommand> {
212    let mut out = Vec::new();
213    let entries = match fs::read_dir(dir) {
214        Ok(e) => e,
215        Err(e) => {
216            log::debug!(
217                "commands dir {} unreadable ({e}) — treating as empty",
218                dir.display()
219            );
220            return out;
221        }
222    };
223    for entry in entries.flatten() {
224        let path = entry.path();
225        if !path.is_file() {
226            continue;
227        }
228        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
229            continue;
230        };
231        if name.starts_with('.') || !name.ends_with(".yaml") {
232            continue;
233        }
234        match load_command_file(&path) {
235            Ok(file) => out.push(LoadedCommand { file, path }),
236            Err(e) => log::warn!("skipping invalid command file {}: {e:#}", path.display()),
237        }
238    }
239    out.sort_by(|a, b| a.file.id().cmp(b.file.id()));
240    out
241}
242
243/// Serialize a command file to YAML bytes.
244pub fn command_to_yaml(file: &AgentCommandFile) -> Result<Vec<u8>> {
245    let s = serde_yaml_ng::to_string(file).context("serializing command file")?;
246    let mut bytes = s.into_bytes();
247    if bytes.last() != Some(&b'\n') {
248        bytes.push(b'\n');
249    }
250    Ok(bytes)
251}
252
253/// Write one command file atomically. Refuses to overwrite a user-authored
254/// command (D4c) and enforces the directory file-count cap.
255pub fn save_command_file(file: &AgentCommandFile, dir: &Path) -> Result<PathBuf> {
256    let id = file.id();
257    validate_command(file, id)?;
258
259    fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
260
261    let path = dir.join(format!("{id}.yaml"));
262    if path.exists() {
263        let existing = load_command_file(&path)?;
264        if existing.created_by == CommandAuthor::User {
265            bail!(
266                "refusing to overwrite user-authored command {id:?} — the user must \
267                 approve or edit it manually"
268            );
269        }
270    } else if load_all_commands(dir).len() >= MAX_COMMAND_COUNT {
271        bail!(
272            "commands directory is full ({} files); delete commands before adding more",
273            MAX_COMMAND_COUNT
274        );
275    }
276
277    let bytes = command_to_yaml(file)?;
278    if bytes.len() > MAX_COMMAND_FILE_BYTES {
279        bail!(
280            "serialized command is {} bytes; cap is {}",
281            bytes.len(),
282            MAX_COMMAND_FILE_BYTES
283        );
284    }
285    save_bytes_atomic(&path, &bytes).with_context(|| format!("writing {}", path.display()))?;
286    Ok(path)
287}
288
289/// Delete one command file. Refuses to delete a user-authored command (D4c).
290/// Ledger entries for the id are pruned by the caller.
291pub fn delete_command_file(id: &str, dir: &Path) -> Result<()> {
292    if !is_valid_command_id(id) {
293        bail!("invalid command id {id:?}");
294    }
295    let path = dir.join(format!("{id}.yaml"));
296    if !path.exists() {
297        bail!("no such command: {id}");
298    }
299    let existing = load_command_file(&path)?;
300    if existing.created_by == CommandAuthor::User {
301        bail!(
302            "refusing to delete user-authored command {id:?} — the user must \
303             approve or delete it manually"
304        );
305    }
306    fs::remove_file(&path).with_context(|| format!("deleting {}", path.display()))?;
307    Ok(())
308}
309
310/// Replace one existing command file's YAML with the user's authority — the
311/// Settings UI edit path. Provenance is preserved: the saved file keeps the
312/// existing `created_by` / `source_agent` whatever the edited text says
313/// (owner decision D2), and the id cannot change (it is the filename).
314/// A changed script body gets a new hash, so it asks for confirmation again.
315pub fn update_command_yaml_as_user(id: &str, yaml: &str, dir: &Path) -> Result<PathBuf> {
316    if !is_valid_command_id(id) {
317        bail!("invalid command id {id:?}");
318    }
319    let path = dir.join(format!("{id}.yaml"));
320    let existing = load_command_file(&path)?;
321    let mut edited: AgentCommandFile =
322        serde_yaml_ng::from_str(yaml).context("parsing edited command")?;
323    if edited.id() != id {
324        bail!(
325            "the command id cannot change (was {id:?}, now {:?})",
326            edited.id()
327        );
328    }
329    edited.created_by = existing.created_by;
330    edited.source_agent = existing.source_agent;
331    validate_command(&edited, id)?;
332    let bytes = command_to_yaml(&edited)?;
333    if bytes.len() > MAX_COMMAND_FILE_BYTES {
334        bail!(
335            "serialized command is {} bytes; cap is {}",
336            bytes.len(),
337            MAX_COMMAND_FILE_BYTES
338        );
339    }
340    save_bytes_atomic(&path, &bytes).with_context(|| format!("writing {}", path.display()))?;
341    Ok(path)
342}
343
344/// Delete one command file with the user's authority — the Settings UI path.
345/// Unlike [`delete_command_file`] (the MCP path) this removes user-authored
346/// files too: provenance gates what an *agent* may do, not the user. The
347/// id's ledger entry is pruned here as well, so a later command recreated
348/// under the same id with the same body asks for confirmation again.
349pub fn delete_command_file_as_user(id: &str, dir: &Path) -> Result<()> {
350    if !is_valid_command_id(id) {
351        bail!("invalid command id {id:?}");
352    }
353    let path = dir.join(format!("{id}.yaml"));
354    if !path.exists() {
355        bail!("no such command: {id}");
356    }
357    fs::remove_file(&path).with_context(|| format!("deleting {}", path.display()))?;
358    let mut ledger = load_confirmation_ledger(dir);
359    if ledger.remove(id).is_some() {
360        save_confirmation_ledger(&ledger, dir)?;
361    }
362    Ok(())
363}
364
365/// The confirmation ledger: command id → approved body hash.
366pub type ConfirmationLedger = BTreeMap<String, String>;
367
368/// Load the confirmation ledger. A missing or corrupt file is an empty
369/// ledger — worst case a script asks for confirmation again.
370pub fn load_confirmation_ledger(dir: &Path) -> ConfirmationLedger {
371    let path = dir.join(".confirmations.json");
372    let Ok(bytes) = fs::read(&path) else {
373        return BTreeMap::new();
374    };
375    serde_json::from_slice(&bytes).unwrap_or_else(|e| {
376        log::warn!(
377            "confirmation ledger {} unreadable ({e}); starting empty — \
378             scripts will re-ask for confirmation",
379            path.display()
380        );
381        BTreeMap::new()
382    })
383}
384
385/// Persist the confirmation ledger atomically.
386pub fn save_confirmation_ledger(ledger: &ConfirmationLedger, dir: &Path) -> Result<()> {
387    let path = dir.join(".confirmations.json");
388    let bytes = serde_json::to_vec_pretty(ledger).context("serializing confirmation ledger")?;
389    save_bytes_atomic(&path, &bytes).with_context(|| format!("writing {}", path.display()))?;
390    Ok(())
391}
392
393#[cfg(test)]
394mod tests {
395    use super::*;
396
397    fn script_file(id: &str) -> AgentCommandFile {
398        let yaml = format!(
399            "created_by: agent\nsource_agent: claude-code\naction:\n  type: shell_command\n  \
400             id: {id}\n  title: Test\n  command: echo\n  args: [\"hi\"]\n"
401        );
402        serde_yaml_ng::from_str(&yaml).unwrap()
403    }
404
405    fn macro_file(id: &str) -> AgentCommandFile {
406        let yaml = format!(
407            "created_by: user\naction:\n  type: insert_text\n  id: {id}\n  title: Greet\n  \
408             text: hello\n"
409        );
410        serde_yaml_ng::from_str(&yaml).unwrap()
411    }
412
413    #[test]
414    fn roundtrip_script_file() {
415        let f = script_file("deploy-staging");
416        assert_eq!(f.id(), "deploy-staging");
417        assert!(f.is_script());
418        assert!(f.source_agent.as_deref() == Some("claude-code"));
419        let bytes = command_to_yaml(&f).unwrap();
420        let back: AgentCommandFile = serde_yaml_ng::from_slice(&bytes).unwrap();
421        assert_eq!(back, f);
422    }
423
424    #[test]
425    fn macro_is_not_script_and_needs_no_source() {
426        let f = macro_file("greet");
427        assert_eq!(f.created_by, CommandAuthor::User);
428        assert!(!f.is_script());
429        assert!(validate_command(&f, "greet").is_ok());
430    }
431
432    #[test]
433    fn id_charset_rejected() {
434        assert!(is_valid_command_id("deploy-staging"));
435        assert!(is_valid_command_id("a"));
436        assert!(!is_valid_command_id(""));
437        assert!(!is_valid_command_id("Deploy"));
438        assert!(!is_valid_command_id("has space"));
439        assert!(!is_valid_command_id("has/slash"));
440        assert!(!is_valid_command_id("caf\u{e9}"));
441        let long = "a".repeat(MAX_COMMAND_ID_LEN + 1);
442        assert!(!is_valid_command_id(&long));
443    }
444
445    #[test]
446    fn validate_rejects_stem_mismatch() {
447        let f = script_file("one-id");
448        let err = validate_command(&f, "other-id").unwrap_err();
449        assert!(err.to_string().contains("does not match"));
450    }
451
452    #[test]
453    fn validate_rejects_agent_without_source() {
454        let mut f = script_file("x");
455        f.source_agent = None;
456        let err = validate_command(&f, "x").unwrap_err();
457        assert!(err.to_string().contains("source_agent"));
458    }
459
460    #[test]
461    fn body_hash_changes_with_action() {
462        let mut f = script_file("x");
463        let h1 = f.body_hash();
464        if let CustomActionConfig::ShellCommand { title, .. } = &mut f.action {
465            *title = "Changed".to_string();
466        }
467        assert_ne!(h1, f.body_hash());
468    }
469
470    #[test]
471    fn save_refuses_user_overwrite_and_delete() {
472        let dir = tempfile::tempdir().unwrap();
473        let user = macro_file("mine");
474        save_command_file(&user, dir.path()).unwrap();
475
476        // Overwrite attempt with an agent-tagged body of the same id.
477        let evil = script_file("mine");
478        let err = save_command_file(&evil, dir.path()).unwrap_err();
479        assert!(err.to_string().contains("user-authored"));
480
481        let err = delete_command_file("mine", dir.path()).unwrap_err();
482        assert!(err.to_string().contains("user-authored"));
483    }
484
485    #[test]
486    fn user_update_keeps_provenance_and_refuses_id_change() {
487        let dir = tempfile::tempdir().unwrap();
488        let original = script_file("deploy");
489        save_command_file(&original, dir.path()).unwrap();
490
491        // The edit tries to claim the file for the user and changes the body.
492        let edited = "created_by: user\naction:\n  type: shell_command\n  id: deploy\n  \
493                      title: Deploy v2\n  command: echo\n  args: [\"bye\"]\n";
494        update_command_yaml_as_user("deploy", edited, dir.path()).unwrap();
495        let saved = load_command_file(&dir.path().join("deploy.yaml")).unwrap();
496        assert_eq!(saved.title(), "Deploy v2");
497        assert_eq!(saved.created_by, CommandAuthor::Agent);
498        assert_eq!(saved.source_agent.as_deref(), Some("claude-code"));
499        assert_ne!(saved.body_hash(), original.body_hash());
500
501        let renamed = edited.replace("id: deploy", "id: other");
502        let err = update_command_yaml_as_user("deploy", &renamed, dir.path()).unwrap_err();
503        assert!(err.to_string().contains("cannot change"), "{err}");
504        assert!(update_command_yaml_as_user("deploy", "not: [valid", dir.path()).is_err());
505        assert!(update_command_yaml_as_user("missing", edited, dir.path()).is_err());
506        // Failed edits left the file untouched.
507        let still = load_command_file(&dir.path().join("deploy.yaml")).unwrap();
508        assert_eq!(still, saved);
509    }
510
511    #[test]
512    fn user_delete_removes_user_file_and_prunes_ledger() {
513        let dir = tempfile::tempdir().unwrap();
514        save_command_file(&macro_file("mine"), dir.path()).unwrap();
515        save_command_file(&script_file("theirs"), dir.path()).unwrap();
516        let mut ledger = ConfirmationLedger::new();
517        ledger.insert("theirs".to_string(), "hash".to_string());
518        ledger.insert("other".to_string(), "hash-o".to_string());
519        save_confirmation_ledger(&ledger, dir.path()).unwrap();
520
521        // The MCP path still refuses the user-authored file.
522        assert!(delete_command_file("mine", dir.path()).is_err());
523        delete_command_file_as_user("mine", dir.path()).unwrap();
524        assert!(!dir.path().join("mine.yaml").exists());
525
526        delete_command_file_as_user("theirs", dir.path()).unwrap();
527        assert!(load_all_commands(dir.path()).is_empty());
528        let after = load_confirmation_ledger(dir.path());
529        assert!(!after.contains_key("theirs"));
530        assert_eq!(after.get("other").map(String::as_str), Some("hash-o"));
531
532        assert!(delete_command_file_as_user("mine", dir.path()).is_err());
533        assert!(delete_command_file_as_user("../escape", dir.path()).is_err());
534    }
535
536    #[test]
537    fn save_then_load_roundtrip() {
538        let dir = tempfile::tempdir().unwrap();
539        let f = script_file("round-trip");
540        let path = save_command_file(&f, dir.path()).unwrap();
541        assert!(path.ends_with("round-trip.yaml"));
542
543        let all = load_all_commands(dir.path());
544        assert_eq!(all.len(), 1);
545        assert_eq!(all[0].file, f);
546    }
547
548    #[test]
549    fn load_all_skips_invalid_files_quietly() {
550        let dir = tempfile::tempdir().unwrap();
551        std::fs::write(dir.path().join("good.yaml"), "").unwrap();
552        // Invalid: id doesn't match stem.
553        std::fs::write(
554            dir.path().join("bad.yaml"),
555            "created_by: user\naction:\n  type: insert_text\n  id: wrong\n  title: T\n  \
556             text: x\n",
557        )
558        .unwrap();
559        std::fs::write(dir.path().join(".confirmations.json"), "{}").unwrap();
560
561        let all = load_all_commands(dir.path());
562        // good.yaml is empty -> parse error -> skipped; bad.yaml -> mismatch -> skipped.
563        assert!(all.is_empty());
564    }
565
566    #[test]
567    fn ledger_roundtrip_and_corrupt_tolerated() {
568        let dir = tempfile::tempdir().unwrap();
569        let mut ledger = ConfirmationLedger::new();
570        ledger.insert("a".to_string(), "hash-a".to_string());
571        save_confirmation_ledger(&ledger, dir.path()).unwrap();
572        assert_eq!(load_confirmation_ledger(dir.path()), ledger);
573
574        std::fs::write(dir.path().join(".confirmations.json"), "not json").unwrap();
575        assert!(load_confirmation_ledger(dir.path()).is_empty());
576    }
577
578    #[test]
579    fn palette_label_includes_agent_provenance() {
580        let f = script_file("x");
581        assert_eq!(f.palette_label(), "Test · agent (claude-code)");
582        let u = macro_file("greet");
583        assert_eq!(u.palette_label(), "Greet");
584    }
585
586    #[test]
587    fn command_count_cap_enforced() {
588        let dir = tempfile::tempdir().unwrap();
589        for i in 0..MAX_COMMAND_COUNT {
590            let f = macro_file(&format!("cmd-{i:03}"));
591            save_command_file(&f, dir.path()).unwrap();
592        }
593        let extra = macro_file("cmd-extra");
594        let err = save_command_file(&extra, dir.path()).unwrap_err();
595        assert!(err.to_string().contains("full"));
596    }
597}