termaxa 0.14.1

A cooperative gate for the shell commands AI coding agents run — command previews, automatic backups, allow/ask/deny policy, and audit logging.
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
use anyhow::{Context, Result};
use serde_json::{json, Value};
use std::fs;
use std::path::Path;
use std::process::Command;

pub const STARTER_POLICY: &str = r#"# Termaxa policy — first matching rule wins; `*` is a wildcard.
# Actions: allow (run silently) | ask (require approval) | deny (block)
#
# ORDER MATTERS, and the hard stops come first on purpose. Until v0.14.1 the
# read-only allows sat at the top, so a broad prefix shadowed the stop below
# it: `git branch -D main` matched `git branch*` and was ALLOWED, and
# `echo $(rm -rf /)` matched `echo *` before `*rm -rf*` could deny it. A rule
# that can never be reached is not a rule. Put your own exceptions ABOVE the
# deny you want them to override — that is what first-match-wins is for.
#
# Matching is case-insensitive, so a rule cannot distinguish `-D` from `-d`.
# Where a flag's case carries the meaning (git branch -D, rm -R), the rule
# covers both and the action is chosen for the safer of the two.
version: 1
default: ask

rules:
  # ---- destructive: hard stops ----
  - match: "git push*--force*"
    action: deny
    reason: "Force pushes are blocked by policy. Open a PR instead."
  - match: "rm -rf /*"
    action: deny
    reason: "Recursive delete from root is blocked."
  # Broad recursive-force deletes (any target), Unix + PowerShell + cmd
  # forms. DENY by default: with auto-approving agent UIs, `ask` silently
  # degrades to `allow`. Relax deliberately, per project, if you need to.
  - match: "*rm -rf*"
    action: deny
    reason: "Recursive force delete blocked by default policy."
  - match: "*rm -fr*"
    action: deny
    reason: "Recursive force delete blocked by default policy."
  - match: "*Remove-Item*-Recurse*"
    action: deny
    reason: "Recursive delete (PowerShell) blocked by default policy."
  - match: "*Remove-Item*-Force*"
    action: deny
    reason: "Forced delete (PowerShell) blocked by default policy."
  - match: "*Get-ChildItem*Remove-Item*"
    action: deny
    reason: "Bulk delete pipeline (PowerShell) blocked by default policy."
  - match: "*del /s*"
    action: deny
    reason: "Recursive delete (cmd) blocked by default policy."
  - match: "*rmdir /s*"
    action: deny
    reason: "Recursive delete (cmd) blocked by default policy."
  - match: "*rd /s*"
    action: deny
    reason: "Recursive delete (cmd) blocked by default policy."
  - match: "kubectl delete*"
    action: deny
    reason: "kubectl delete is blocked. Use a manifest change + apply."
  - match: "*drop table*"
    action: deny
    reason: "DROP TABLE is blocked. Archive or rename instead."
  - match: "*drop database*"
    action: deny
    reason: "DROP DATABASE is blocked."
  - match: "terraform destroy*"
    action: deny
    reason: "terraform destroy is blocked by policy."
  - match: "tofu destroy*"
    action: deny
    reason: "tofu destroy is blocked by policy."

  # ---- consequential: human in the loop ----
  # `git branch -D` force-deletes an unmerged branch. Case-insensitive
  # matching cannot separate it from the safe `-d`, so this asks rather than
  # denies; the commits remain in the reflog either way.
  - match: "git branch*-d*"
    action: ask
    reason: "Deleting a branch. `-D` force-deletes even if unmerged."
  - match: "git push*"
    action: ask
  - match: "terraform apply*"
    action: ask
  - match: "tofu apply*"
    action: ask
  - match: "docker rm*"
    action: ask
  - match: "docker system prune*"
    action: ask
  - match: "npm publish*"
    action: ask
  - match: "cargo publish*"
    action: ask
  - match: "gh pr merge*"
    action: ask
  - match: "aws *"
    action: ask
  - match: "curl*"
    action: ask
  - match: "ssh *"
    action: ask

  # ---- read-only operations: let the agent work ----
  - match: "git status*"
    action: allow
  - match: "git diff*"
    action: allow
  - match: "git log*"
    action: allow
  - match: "git branch*"
    action: allow
  - match: "git commit*"
    action: allow
  - match: "ls*"
    action: allow
  - match: "cat *"
    action: allow
  - match: "grep*"
    action: allow
  - match: "echo *"
    action: allow
  - match: "git remote -v"
    action: allow
  - match: "git fetch*"
    action: allow
  - match: "terraform plan*"
    action: allow
  - match: "terraform init*"
    action: allow
  - match: "tofu plan*"
    action: allow
  - match: "kubectl get*"
    action: allow
  - match: "kubectl describe*"
    action: allow
  - match: "docker ps*"
    action: allow

# Session circuit breaker (v0.11): if the same destructive intent
# (file delete / db destroy / git force / infra destroy) is asked or
# denied `threshold` times in one agent session, further variants are
# DENIED automatically. Human-approved commands don't count.
circuit_breaker:
  enabled: true
  threshold: 2   # trip on the 3rd attempt
"#;

pub fn run(
    dir: &Path,
    write_claude_hook: bool,
    write_cursor_hook: bool,
    write_codex_hook: bool,
    write_copilot_hook: bool,
) -> Result<()> {
    let termaxa_dir = dir.join(".termaxa");
    fs::create_dir_all(&termaxa_dir)?;

    let policy_path = termaxa_dir.join("policy.yaml");
    if policy_path.exists() {
        println!("• .termaxa/policy.yaml already exists — leaving it untouched");
    } else {
        fs::write(&policy_path, STARTER_POLICY)?;
        println!("✓ wrote .termaxa/policy.yaml (starter policy)");
    }

    // --- detect agent harnesses ---
    println!("\nAgent harnesses detected:");
    let mut found_any = false;
    for (label, probe) in [
        (
            "Claude Code",
            dir.join(".claude").exists() || which("claude"),
        ),
        ("Cursor", dir.join(".cursor").exists()),
        ("OpenHands", which("openhands")),
        ("Codex CLI", which("codex")),
    ] {
        if probe {
            println!("  ✓ {}", label);
            found_any = true;
        }
    }
    if !found_any {
        println!("  (none found — hook mode still works once you add one)");
    }

    // --- detect tools worth governing ---
    println!("\nTools detected on PATH:");
    for tool in [
        "git",
        "docker",
        "terraform",
        "kubectl",
        "aws",
        "psql",
        "npm",
        "cargo",
        "gh",
        "ssh",
    ] {
        if which(tool) {
            println!("  ✓ {}", tool);
        }
    }

    // --- wire up Claude Code PreToolUse hook ---
    if write_claude_hook {
        install_claude_hook(dir)?;
    } else {
        if write_cursor_hook {
            let dir_c = dir.join(".cursor");
            fs::create_dir_all(&dir_c)?;
            let hooks_path = dir_c.join("hooks.json");
            // Use the absolute path to THIS binary. On Windows, a bare "termaxa hook"
            // can fail PATH/quoting resolution inside Cursor's hook runner; an
            // absolute exe path is the documented fix.
            let exe = std::env::current_exe()
                .ok()
                .and_then(|p| p.to_str().map(str::to_string))
                .unwrap_or_else(|| "termaxa".to_string());
            let cmd = format!("{} hook", exe);
            let hooks = serde_json::json!({
                "version": 1,
                "hooks": {
                    "beforeShellExecution": [ { "command": cmd } ],
                    "afterShellExecution": [ { "command": cmd } ]
                }
            });
            fs::write(&hooks_path, serde_json::to_string_pretty(&hooks)?)?;
            println!("✓ wrote .cursor/hooks.json (before + after ShellExecution -> termaxa hook)");
            println!("  NOTE: restart Cursor after this so it reloads hook config.");
        }

        println!("\nTo wire Termaxa into Claude Code, run: termaxa init --claude-code");
        println!("To wire Termaxa into Cursor (v1.7+), run: termaxa init --cursor");

        if write_codex_hook {
            // Codex uses the same PreToolUse contract as Claude Code.
            let dir_x = dir.join(".codex");
            fs::create_dir_all(&dir_x)?;
            let hooks_path = dir_x.join("hooks.json");
            let hooks = serde_json::json!({
                "version": 1,
                "hooks": { "PreToolUse": [ { "command": "termaxa hook" } ] }
            });
            fs::write(&hooks_path, serde_json::to_string_pretty(&hooks)?)?;
            println!("✓ wrote .codex/hooks.json (Codex PreToolUse -> termaxa hook)");
        }

        if write_copilot_hook {
            let dir_h = dir.join(".github").join("hooks");
            fs::create_dir_all(&dir_h)?;
            let hooks_path = dir_h.join("hooks.json");
            // Copilot CLI: preToolUse hook, fail-closed on deny.
            let hooks = serde_json::json!({
                "version": 1,
                "hooks": {
                    "preToolUse": [
                        { "type": "command", "command": "termaxa hook", "failClosed": true }
                    ]
                }
            });
            fs::write(&hooks_path, serde_json::to_string_pretty(&hooks)?)?;
            println!("✓ wrote .github/hooks/hooks.json (Copilot preToolUse -> termaxa hook, fail-closed)");
        }

        println!("Other agents: termaxa init --codex | --copilot");
        print_hook_snippet();
    }

    if let Ok(p) = crate::paths::resolve() {
        println!("\nRuntime state (logs, backups) lives OUTSIDE the repo:");
        println!("  {}", p.state_dir.display());
    }

    println!("\nDone. Try:  termaxa check \"git push --force origin main\"");
    Ok(())
}

fn install_claude_hook(dir: &Path) -> Result<()> {
    let claude_dir = dir.join(".claude");
    fs::create_dir_all(&claude_dir)?;
    let settings_path = claude_dir.join("settings.json");

    let mut settings: Value = if settings_path.exists() {
        let raw = fs::read_to_string(&settings_path)?;
        serde_json::from_str(&raw).context("existing .claude/settings.json is not valid JSON")?
    } else {
        json!({})
    };

    let hook_entry = json!({
        "matcher": "Bash",
        "hooks": [{ "type": "command", "command": "termaxa hook" }]
    });

    let hooks = settings
        .as_object_mut()
        .context("settings.json root must be an object")?
        .entry("hooks")
        .or_insert(json!({}));
    let pre = hooks
        .as_object_mut()
        .context("hooks must be an object")?
        .entry("PreToolUse")
        .or_insert(json!([]));
    let arr = pre.as_array_mut().context("PreToolUse must be an array")?;

    let already = arr.iter().any(|e| {
        e.pointer("/hooks/0/command")
            .and_then(|c| c.as_str())
            .map(|c| c.contains("termaxa hook"))
            .unwrap_or(false)
    });
    if already {
        println!("\n• Claude Code hook already installed in .claude/settings.json");
    } else {
        arr.push(hook_entry);
        println!("\n✓ installed PreToolUse hook in .claude/settings.json");
    }

    // PostToolUse receipt hook (feeds the breaker's approved-ask exclusion).
    // Same command; Termaxa branches on the event name internally.
    let post_entry = json!({
        "matcher": "Bash",
        "hooks": [{ "type": "command", "command": "termaxa hook" }]
    });
    let post = settings
        .as_object_mut()
        .context("settings.json root must be an object")?
        .get_mut("hooks")
        .and_then(|h| h.as_object_mut())
        .context("hooks must be an object")?
        .entry("PostToolUse")
        .or_insert(json!([]));
    let post_arr = post
        .as_array_mut()
        .context("PostToolUse must be an array")?;
    let post_already = post_arr.iter().any(|e| {
        e.pointer("/hooks/0/command")
            .and_then(|c| c.as_str())
            .map(|c| c.contains("termaxa hook"))
            .unwrap_or(false)
    });
    if !post_already {
        post_arr.push(post_entry);
        println!("✓ installed PostToolUse hook in .claude/settings.json");
    }

    fs::write(&settings_path, serde_json::to_string_pretty(&settings)?)?;
    Ok(())
}

fn print_hook_snippet() {
    println!(
        r#"
  .claude/settings.json snippet:
  {{
    "hooks": {{
      "PreToolUse": [
        {{
          "matcher": "Bash",
          "hooks": [{{ "type": "command", "command": "termaxa hook" }}]
        }}
      ]
    }}
  }}"#
    );
}

pub(crate) fn which(bin: &str) -> bool {
    // `which` on Unix, `where` on Windows
    let finder = if cfg!(windows) { "where" } else { "which" };
    Command::new(finder)
        .arg(bin)
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

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

    /// `examples/policy.yaml` is the file people copy. It had drifted to 28
    /// rules against the starter's 44 — missing every broad delete deny and
    /// the whole circuit_breaker block — with nothing to signal it was weaker.
    /// It is now generated from STARTER_POLICY, and this test is what keeps it
    /// generated: an example policy that is quietly less safe than the real
    /// one is worse than no example at all.
    #[test]
    fn shipped_example_policy_matches_the_starter_policy() {
        // Normalise line endings before comparing. Git checks this file out
        // with CRLF on Windows (core.autocrlf) while STARTER_POLICY is a Rust
        // literal with LF, so a byte comparison fails on Windows only. What
        // this test is for is content drift, not line endings.
        let example = include_str!("../examples/policy.yaml").replace("\r\n", "\n");
        assert_eq!(
            example, STARTER_POLICY,
            "examples/policy.yaml has drifted from init::STARTER_POLICY. \
             Regenerate it rather than editing it by hand."
        );
    }

    /// Schipper review, finding 3: order is load-bearing, so assert the shape
    /// rather than trusting a comment to hold.
    #[test]
    fn hard_stops_are_reachable_before_the_read_only_allows() {
        let p: crate::policy::Policy = serde_yaml::from_str(STARTER_POLICY).unwrap();
        let first_allow = p
            .rules
            .iter()
            .position(|r| r.action == crate::policy::Action::Allow)
            .expect("starter policy has allow rules");
        let last_deny = p
            .rules
            .iter()
            .rposition(|r| r.action == crate::policy::Action::Deny)
            .expect("starter policy has deny rules");
        assert!(
            last_deny < first_allow,
            "a deny rule sits below an allow prefix and can never be reached"
        );
    }

    #[test]
    fn the_shadowed_commands_are_no_longer_allowed() {
        let p: crate::policy::Policy = serde_yaml::from_str(STARTER_POLICY).unwrap();
        for cmd in [
            "git branch -D main",
            "echo $(rm -rf /)",
            "git status & rm -rf /",
        ] {
            assert_ne!(
                p.evaluate_command(cmd).action,
                crate::policy::Action::Allow,
                "{cmd} is still allowed"
            );
        }
    }
}