1use 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
38pub const MAX_COMMAND_FILE_BYTES: usize = 64 * 1024;
41
42pub const MAX_COMMAND_COUNT: usize = 200;
44
45pub const MAX_COMMAND_ID_LEN: usize = 64;
47
48pub fn commands_dir() -> PathBuf {
50 crate::config::Config::config_dir().join("commands")
51}
52
53pub fn confirmations_path() -> PathBuf {
55 commands_dir().join(".confirmations.json")
56}
57
58pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
71#[serde(rename_all = "lowercase")]
72pub enum CommandAuthor {
73 Agent,
75 #[default]
78 User,
79}
80
81#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
83pub struct AgentCommandFile {
84 #[serde(default)]
86 pub created_by: CommandAuthor,
87
88 #[serde(default, skip_serializing_if = "Option::is_none")]
91 pub source_agent: Option<String>,
92
93 #[serde(default, skip_serializing_if = "Option::is_none")]
95 pub created_at: Option<String>,
96
97 pub action: CustomActionConfig,
99}
100
101impl AgentCommandFile {
102 pub fn id(&self) -> &str {
104 self.action.id()
105 }
106
107 pub fn title(&self) -> &str {
109 self.action.title()
110 }
111
112 pub fn is_script(&self) -> bool {
115 matches!(self.action, CustomActionConfig::ShellCommand { .. })
116 }
117
118 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 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
143pub 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
171pub 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#[derive(Debug, Clone)]
203pub struct LoadedCommand {
204 pub file: AgentCommandFile,
205 pub path: PathBuf,
206}
207
208pub 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
243pub 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
253pub 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
289pub 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
310pub 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
344pub 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
365pub type ConfirmationLedger = BTreeMap<String, String>;
367
368pub 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
385pub 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 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 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 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(¯o_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 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 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 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}