safe-chains 0.136.0

Auto-allow safe bash commands in agentic coding tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
use crate::handlers;
use crate::parse::WordSet;

pub struct CommandDoc {
    pub name: String,
    pub kind: DocKind,
    pub url: &'static str,
    pub description: String,
    pub aliases: Vec<String>,
    pub category: String,
}

pub enum DocKind {
    Handler,
}

impl CommandDoc {
    pub fn handler(name: &'static str, url: &'static str, description: impl Into<String>, category: &str) -> Self {
        let raw = description.into();
        let description = raw
            .lines()
            .map(|line| {
                if line.is_empty() || line.starts_with("- ") {
                    line.to_string()
                } else {
                    format!("- {line}")
                }
            })
            .collect::<Vec<_>>()
            .join("\n");
        Self { name: name.to_string(), kind: DocKind::Handler, url, description, aliases: Vec::new(), category: category.to_string() }
    }

    pub fn wordset(name: &'static str, url: &'static str, words: &WordSet, category: &str) -> Self {
        Self::handler(name, url, doc(words).build(), category)
    }

    pub fn wordset_multi(name: &'static str, url: &'static str, words: &WordSet, multi: &[(&str, WordSet)], category: &str) -> Self {
        Self::handler(name, url, doc_multi(words, multi).build(), category)
    }


}

#[derive(Default)]
pub struct DocBuilder {
    subcommands: Vec<String>,
    flags: Vec<String>,
    sections: Vec<String>,
}

impl DocBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn wordset(mut self, words: &WordSet) -> Self {
        for item in words.iter() {
            if item.starts_with('-') {
                self.flags.push(item.to_string());
            } else {
                self.subcommands.push(item.to_string());
            }
        }
        self
    }

    pub fn multi_word(mut self, multi: &[(&str, WordSet)]) -> Self {
        for (prefix, actions) in multi {
            for action in actions.iter() {
                self.subcommands.push(format!("{prefix} {action}"));
            }
        }
        self
    }

    pub fn triple_word(mut self, triples: &[(&str, &str, WordSet)]) -> Self {
        for (a, b, actions) in triples {
            for action in actions.iter() {
                self.subcommands.push(format!("{a} {b} {action}"));
            }
        }
        self
    }

    pub fn subcommand(mut self, name: impl Into<String>) -> Self {
        self.subcommands.push(name.into());
        self
    }

    pub fn section(mut self, text: impl Into<String>) -> Self {
        let s = text.into();
        if !s.is_empty() {
            self.sections.push(s);
        }
        self
    }

    pub fn build(self) -> String {
        let mut lines = Vec::new();
        if !self.subcommands.is_empty() {
            let mut subs = self.subcommands;
            subs.sort();
            lines.push(format!("- Subcommands: {}", subs.join(", ")));
        }
        if !self.flags.is_empty() {
            lines.push(format!("- Flags: {}", self.flags.join(", ")));
        }
        for s in self.sections {
            if s.starts_with("- ") {
                lines.push(s);
            } else {
                lines.push(format!("- {s}"));
            }
        }
        lines.join("\n")
    }
}

pub fn doc(words: &WordSet) -> DocBuilder {
    DocBuilder::new().wordset(words)
}

pub fn doc_multi(words: &WordSet, multi: &[(&str, WordSet)]) -> DocBuilder {
    DocBuilder::new().wordset(words).multi_word(multi)
}

pub fn wordset_items(words: &WordSet) -> String {
    let items: Vec<&str> = words.iter().collect();
    items.join(", ")
}


pub fn all_command_docs() -> Vec<CommandDoc> {
    let mut docs = handlers::handler_docs();
    docs.sort_by_key(|a| a.name.to_ascii_lowercase());
    docs
}

const GLOSSARY: &str = "\
| Term | Meaning |\n\
|------|---------|\n\
| **Allowed standalone flags** | Flags that take no value (`--verbose`, `-v`). Listed on flat commands. |\n\
| **Flags** | Same as standalone flags, but in the shorter format used within subcommand entries. |\n\
| **Allowed valued flags** | Flags that require a value (`--output file`, `-j 4`). |\n\
| **Valued** | Same as valued flags, in shorter format within subcommand entries. |\n\
| **Bare invocation allowed** | The command can be run with no arguments at all. |\n\
| **Subcommands** | Named subcommands that are allowed (e.g. `git log`, `cargo test`). |\n\
| **Positional arguments only** | No specific flags are listed; only positional arguments are accepted. |\n\
| **(requires --flag)** | A guarded subcommand that is only allowed when a specific flag is present (e.g. `cargo fmt` requires `--check`). |\n\
\n\
Unlisted flags, subcommands, and commands are not allowed.\n";

pub fn render_markdown(docs: &[CommandDoc]) -> String {
    let mut out = format!(
        "# Supported Commands\n\n\
         Auto-generated by `safe-chains --list-commands`. These commands, subcommands, and flags are safe to run individually or in combination.\n\n\
         ## Glossary\n\n{GLOSSARY}\n",
    );

    for doc in docs {
        out.push_str(&render_command_entry(doc));
    }

    out
}

fn category_display_name(slug: &str) -> &'static str {
    match slug {
        "ai" => "AI Tools",
        "android" => "Android",
        "ansible" => "Ansible",
        "binary" => "Binary Analysis",
        "builtins" => "Shell Builtins",
        "cloud" => "Cloud Providers",
        "containers" => "Containers",
        "data" => "Data Processing",
        "dotnet" => ".NET",
        "forges" => "Code Forges",
        "fs" => "Filesystem",
        "fuzzy" => "Fuzzy Finders",
        "go" => "Go",
        "hash" => "Hashing",
        "jvm" => "JVM",
        "kafka" => "Kafka",
        "magick" => "ImageMagick",
        "net" => "Networking",
        "node" => "Node.js",
        "php" => "PHP",
        "pm" => "Package Managers",
        "python" => "Python",
        "r" => "R",
        "ruby" => "Ruby",
        "rust" => "Rust",
        "search" => "Search",
        "swift" => "Swift",
        "sysinfo" => "System Info",
        "system" => "System",
        "text" => "Text Processing",
        "tools" => "Developer Tools",
        "vcs" => "Version Control",
        "wrappers" => "Shell Wrappers",
        "xcode" => "Xcode",
        other => panic!("unknown category '{other}' — add it to category_display_name() in src/docs.rs")
    }
}

fn render_command_entry(doc: &CommandDoc) -> String {
    let mut out = String::new();
    out.push_str(&format!("### `{}`\n", doc.name));
    out.push_str(&format!(
        "<p class=\"cmd-url\"><a href=\"{}\">{}</a></p>\n\n",
        doc.url, doc.url,
    ));
    if !doc.aliases.is_empty() {
        let alias_str: Vec<String> = doc.aliases.iter().map(|a| format!("`{a}`")).collect();
        out.push_str(&format!("Aliases: {}\n\n", alias_str.join(", ")));
    }
    out.push_str(&format!("{}\n\n", doc.description));
    out
}

pub fn render_book(docs: &[CommandDoc], output_dir: &std::path::Path) {
    use std::collections::BTreeMap;
    use std::fs;

    let commands_dir = output_dir.join("src").join("commands");
    fs::create_dir_all(&commands_dir).expect("failed to create commands dir");

    let mut by_category: BTreeMap<&str, Vec<&CommandDoc>> = BTreeMap::new();
    for doc in docs {
        by_category.entry(&doc.category).or_default().push(doc);
    }

    let total: usize = by_category.values().map(|v| v.len()).sum();

    let includes_dir = output_dir.join("src").join("includes");
    fs::create_dir_all(&includes_dir).expect("failed to create includes dir");
    fs::write(includes_dir.join("command-count.md"), format!("{total}\n"))
        .expect("failed to write command-count.md");

    let mut readme = format!(
        "# Command Reference\n\n\
         safe-chains knows {total} commands across {} categories.\n\n\
         ## Glossary\n\n{GLOSSARY}\n",
        by_category.len(),
    );
    for (slug, cmds) in &by_category {
        let name = category_display_name(slug);
        readme.push_str(&format!(
            "- [{}]({}.md) ({} commands)\n",
            name, slug, cmds.len(),
        ));
    }
    readme.push('\n');
    fs::write(commands_dir.join("README.md"), &readme)
        .expect("failed to write commands/README.md");

    for (slug, cmds) in &by_category {
        let name = category_display_name(slug);
        let mut page = format!("# {name}\n\n");
        for doc in cmds {
            page.push_str(&render_command_entry(doc));
        }
        fs::write(commands_dir.join(format!("{slug}.md")), &page)
            .expect("failed to write category page");
    }

    eprintln!("Generated {} category pages:", by_category.len());
    for slug in by_category.keys() {
        eprintln!("  - [{}](commands/{}.md)", category_display_name(slug), slug);
    }
}

pub fn render_opencode_json(patterns: &[String]) -> String {
    use serde_json::{Map, Value};
    use std::fs;

    let mut root: Map<String, Value> = fs::read_to_string("opencode.json")
        .ok()
        .and_then(|s| serde_json::from_str(&s).ok())
        .and_then(|v: Value| v.as_object().cloned())
        .unwrap_or_else(|| {
            let mut m = Map::new();
            m.insert(
                "$schema".to_string(),
                Value::String("https://opencode.ai/config.json".to_string()),
            );
            m
        });

    let mut bash = Map::new();
    bash.insert("*".to_string(), Value::String("ask".to_string()));
    for pat in patterns {
        bash.insert(pat.clone(), Value::String("allow".to_string()));
    }

    let permission = root
        .entry("permission")
        .or_insert_with(|| Value::Object(Map::new()));
    if !permission.is_object() {
        *permission = Value::Object(Map::new());
    }
    if let Value::Object(perm_map) = permission {
        perm_map.insert("bash".to_string(), Value::Object(bash));
    }

    let mut out = serde_json::to_string_pretty(&Value::Object(root)).unwrap_or_default();
    out.push('\n');
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn all_commands_have_url() {
        for doc in all_command_docs() {
            assert!(!doc.url.is_empty(), "{} has no documentation URL", doc.name);
            assert!(
                doc.url.starts_with("https://"),
                "{} URL must use https: {}",
                doc.name,
                doc.url
            );
        }
    }

    #[test]
    fn all_commands_have_valid_category() {
        for doc in all_command_docs() {
            assert!(!doc.category.is_empty(), "{} has no category", doc.name);
            category_display_name(&doc.category);
        }
    }

    #[test]
    fn builder_two_sections() {
        let ws = WordSet::new(&["--version", "list", "show"]);
        assert_eq!(doc(&ws).build(), "- Subcommands: list, show\n- Flags: --version");
    }

    #[test]
    fn builder_subcommands_only() {
        let ws = WordSet::new(&["list", "show"]);
        assert_eq!(doc(&ws).build(), "- Subcommands: list, show");
    }

    #[test]
    fn builder_flags_only() {
        let ws = WordSet::new(&["--check", "--version"]);
        assert_eq!(doc(&ws).build(), "- Flags: --check, --version");
    }

    #[test]
    fn builder_three_sections() {
        let ws = WordSet::new(&["--version", "list", "show"]);
        assert_eq!(
            doc(&ws).section("Guarded: foo (bar only).").build(),
            "- Subcommands: list, show\n- Flags: --version\n- Guarded: foo (bar only)."
        );
    }

    #[test]
    fn builder_multi_word_merged() {
        let ws = WordSet::new(&["--version", "info", "show"]);
        let multi: &[(&str, WordSet)] =
            &[("config", WordSet::new(&["get", "list"]))];
        assert_eq!(
            doc_multi(&ws, multi).build(),
            "- Subcommands: config get, config list, info, show\n- Flags: --version"
        );
    }

    #[test]
    fn builder_multi_word_with_extra_section() {
        let ws = WordSet::new(&["--version", "show"]);
        let multi: &[(&str, WordSet)] =
            &[("config", WordSet::new(&["get", "list"]))];
        assert_eq!(
            doc_multi(&ws, multi).section("Guarded: foo.").build(),
            "- Subcommands: config get, config list, show\n- Flags: --version\n- Guarded: foo."
        );
    }

    #[test]
    fn builder_no_flags_with_extra() {
        let ws = WordSet::new(&["list", "show"]);
        assert_eq!(
            doc(&ws).section("Also: foo.").build(),
            "- Subcommands: list, show\n- Also: foo."
        );
    }

    #[test]
    fn builder_custom_sections_only() {
        assert_eq!(
            DocBuilder::new()
                .section("Read-only: foo.")
                .section("Always safe: bar.")
                .section("Guarded: baz.")
                .build(),
            "- Read-only: foo.\n- Always safe: bar.\n- Guarded: baz."
        );
    }

    #[test]
    fn builder_triple_word() {
        let ws = WordSet::new(&["--version", "diff"]);
        let triples: &[(&str, &str, WordSet)] =
            &[("git", "remote", WordSet::new(&["list"]))];
        assert_eq!(
            doc(&ws).triple_word(triples).build(),
            "- Subcommands: diff, git remote list\n- Flags: --version"
        );
    }

    #[test]
    fn builder_subcommand_method() {
        let ws = WordSet::new(&["--version", "list"]);
        assert_eq!(
            doc(&ws).subcommand("plugin-list").build(),
            "- Subcommands: list, plugin-list\n- Flags: --version"
        );
    }

    #[test]
    fn render_opencode_json_valid() {
        let patterns = vec!["grep".to_string(), "grep *".to_string(), "ls".to_string()];
        let json = render_opencode_json(&patterns);
        let parsed: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");
        let bash = &parsed["permission"]["bash"];
        assert_eq!(bash["*"], "ask");
        assert_eq!(bash["grep"], "allow");
        assert_eq!(bash["grep *"], "allow");
        assert_eq!(bash["ls"], "allow");
        assert!(bash["rm"].is_null());
    }

    #[test]
    fn render_opencode_json_has_schema() {
        let json = render_opencode_json(&[]);
        let parsed: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");
        assert_eq!(parsed["$schema"], "https://opencode.ai/config.json");
    }

    #[test]
    fn render_opencode_json_trailing_newline() {
        let json = render_opencode_json(&[]);
        assert!(json.ends_with('\n'));
    }

    #[test]
    fn render_opencode_json_merges_existing() {
        use std::fs;
        let dir = tempfile::tempdir().expect("tmpdir");
        let config_path = dir.path().join("opencode.json");
        fs::write(
            &config_path,
            r#"{"$schema":"https://opencode.ai/config.json","model":"claude-sonnet-4-6","permission":{"bash":{"rm *":"deny"}}}"#,
        )
        .expect("write");

        let prev = std::env::current_dir().expect("cwd");
        std::env::set_current_dir(dir.path()).expect("cd");
        let json = render_opencode_json(&["ls".to_string()]);
        std::env::set_current_dir(prev).expect("cd back");

        let parsed: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");
        assert_eq!(parsed["model"], "claude-sonnet-4-6", "existing keys preserved");
        assert_eq!(parsed["permission"]["bash"]["*"], "ask");
        assert_eq!(parsed["permission"]["bash"]["ls"], "allow");
        assert!(
            parsed["permission"]["bash"]["rm *"].is_null(),
            "old bash rules replaced, not merged"
        );
    }

}