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
mod audit;
mod backup;
mod context;
mod delete;
mod doctor;
mod hook;
mod init;
mod intent;
mod notify;
mod paths;
mod pg;
mod policy;
mod preview;
mod report;
mod runner;
mod shell;
mod ui;
use anyhow::{bail, Result};
use clap::{Parser, Subcommand};
use policy::Policy;
#[derive(Parser)]
#[command(
name = "termaxa",
version,
about = "Execution gate for AI coding agents: policy, previews, automatic backups, audit",
after_help = "EXAMPLES:\n termaxa init --claude-code wire up Claude Code (also: --cursor --codex --copilot)\n termaxa doctor is the gate actually wired up?\n termaxa check \"git push --force\" dry-run a command against policy\n termaxa run -- terraform apply gated execution with preview + backup\n termaxa log --decision deny what got blocked\n termaxa report summarize the last AI session\n\nDOCS: https://github.com/termaxa/termaxa"
)]
struct Cli {
#[command(subcommand)]
command: Option<Cmd>,
}
#[derive(Subcommand)]
enum Cmd {
/// Scaffold .termaxa/ in the current directory and detect agents & tools
Init {
/// Also install the PreToolUse hook into .claude/settings.json
#[arg(long = "claude-code")]
claude_code: bool,
/// Also write the Cursor hook (.cursor/hooks.json)
#[arg(long = "cursor")]
cursor: bool,
/// Also write the Codex hook config
#[arg(long = "codex")]
codex: bool,
/// Also write the GitHub Copilot CLI hook (.github/hooks/)
#[arg(long = "copilot")]
copilot: bool,
},
/// Check whether Termaxa is actually wired up and able to see commands
Doctor,
/// Evaluate a command against policy without running it
Check {
/// The command string, e.g. "git push --force origin main"
command: Vec<String>,
},
/// Claude Code PreToolUse hook mode (reads hook JSON on stdin)
Hook,
/// Execute a command through the policy gate: termaxa run -- git push
Run {
#[arg(last = true)]
argv: Vec<String>,
},
/// Show recent audit log entries
Log {
/// Number of entries to show
#[arg(short, long, default_value_t = 20)]
n: usize,
/// Filter by decision: allow | ask | deny
#[arg(long)]
decision: Option<String>,
/// Filter by source: hook | run | check
#[arg(long)]
source: Option<String>,
/// Emit raw JSON lines instead of the pretty format
#[arg(long)]
json: bool,
},
/// Notification tools
Notify {
/// Send a probe message to the configured webhook and report loudly
#[arg(long)]
test: bool,
},
/// Aggregate statistics from the audit log
Stats,
/// List backups taken by the insurance engine
Backups,
/// Restore a backup by id (see `termaxa backups`)
Rollback { id: String },
/// Show where policy and state live for this project
Paths,
/// Generate an execution report from the audit trail
Report {
/// Report on a specific session id (default: most recent session)
#[arg(long)]
session: Option<String>,
/// Report over all activity, not just the latest session
#[arg(long)]
all: bool,
/// Rollup window in days for the "Last N days" section
#[arg(long, default_value_t = 30)]
days: u64,
/// Emit markdown instead of the terminal box
#[arg(long)]
md: bool,
},
}
fn main() {
// Piping to `head`/`less` closes stdout early; without this, println!
// panics with "Broken pipe". Restore the default SIGPIPE disposition so
// termaxa dies quietly like every other CLI. (Windows has no SIGPIPE.)
#[cfg(unix)]
unsafe {
libc::signal(libc::SIGPIPE, libc::SIG_DFL);
}
let cli = Cli::parse();
let code = match dispatch(cli) {
Ok(code) => code,
Err(e) => {
eprintln!("termaxa: {:#}", e);
2
}
};
std::process::exit(code);
}
fn dispatch(cli: Cli) -> Result<i32> {
// Bare `termaxa` prints the welcome screen, not clap's help wall. The
// first thing a new user types after installing is the binary name; five
// lines and one runnable command teach more than a list of flags.
let Some(command) = cli.command else {
ui::welcome(env!("CARGO_PKG_VERSION"));
return Ok(0);
};
match command {
Cmd::Init {
claude_code,
cursor,
codex,
copilot,
} => {
init::run(
&std::env::current_dir()?,
claude_code,
cursor,
codex,
copilot,
)?;
Ok(0)
}
Cmd::Doctor => {
let dir = std::env::current_dir()?;
doctor::run(&dir)
}
Cmd::Check { command } => {
let cmd = command.join(" ");
if cmd.trim().is_empty() {
bail!("usage: termaxa check \"<command>\"");
}
// `check` is a read-only dry run, so it works with zero setup.
// If there's no project .termaxa/, fall back to the built-in
// starter policy (demo mode). run/hook require an explicit
// project policy (decision #19).
let resolved = paths::resolve().ok();
let (policy, state_dir) = match &resolved {
Some(p) => (Policy::load(&p.policy_file())?, p.state_dir.clone()),
None => {
eprintln!("{}", ui::dim("ℹ Demo mode — no project policy found."));
eprintln!(
"{}",
ui::dim("ℹ Using Termaxa's built-in starter policy (read-only).")
);
eprintln!(
"{}\n",
ui::dim(
"ℹ Run `termaxa init` to create a policy you can review and customize."
)
);
(Policy::builtin()?, paths::demo_state_dir()?)
}
};
let base = policy.evaluate_command(&cmd);
let signals = context::gather(&cmd);
let (decision, escalated) = context::apply(base, &signals);
println!();
println!("{}", ui::field("command", &cmd));
println!(
"{}",
ui::field("decision", &ui::decision(&decision.action.to_string()))
);
if let Some(rule) = &decision.matched_rule {
println!("{}", ui::field("rule", &ui::dim(rule)));
}
println!("{}", ui::field("reason", &decision.reason));
for s in &signals {
let line = if s.escalate {
format!("{} {}", s.label, ui::amber("⚠"))
} else {
s.label.clone()
};
println!("{}", ui::field("context", &ui::dim(&line)));
}
if escalated {
println!(
"{}",
ui::field("note", &ui::amber("context escalated allow → ask"))
);
}
let mut preview_summary = None;
let root = resolved.as_ref().and_then(|p| p.project_dir.parent());
if let Some(pv) = preview::generate(&cmd, root) {
println!("\n{}", ui::bold(&pv.title));
for l in &pv.lines {
println!("{}", l);
}
preview_summary = Some(pv.summary);
}
// Record the dry-run in the audit trail with source "check".
let log = audit::AuditLog::new(&state_dir)?;
let (ts_ms, ts) = audit::now();
log.append(&audit::AuditEntry {
ts_ms,
ts,
source: "check".into(),
command: cmd.clone(),
decision: decision.action.to_string(),
matched_rule: decision.matched_rule.clone(),
reason: decision.reason.clone(),
signals: signals.iter().map(|s| s.label.clone()).collect(),
escalated,
session: None,
backup: None,
preview: preview_summary,
intent: intent::classify_command(&cmd).map(|i| i.label().to_string()),
approved: None,
exit_code: None,
cwd: std::env::current_dir()
.map(|p| p.display().to_string())
.unwrap_or_default(),
})?;
// Exit codes make `termaxa check` scriptable: 0 allow, 3 ask, 4 deny.
Ok(match decision.action {
policy::Action::Allow => 0,
policy::Action::Ask => 3,
policy::Action::Deny => 4,
})
}
Cmd::Hook => {
hook::run()?;
Ok(0)
}
Cmd::Run { argv } => {
let p = paths::resolve()?;
runner::run(&p, &argv)
}
Cmd::Log {
n,
decision,
source,
json,
} => {
let p = paths::resolve()?;
let log = audit::AuditLog::new(&p.state_dir)?;
// Read generously, filter, then trim to n — so filters don't starve.
let entries: Vec<_> = log
.read_last(100_000)?
.into_iter()
.filter(|e| decision.as_deref().is_none_or(|d| e.decision == d))
.filter(|e| source.as_deref().is_none_or(|s| e.source == s))
.collect();
let skip = entries.len().saturating_sub(n);
let entries: Vec<_> = entries.into_iter().skip(skip).collect();
if json {
for e in &entries {
println!("{}", serde_json::to_string(e)?);
}
return Ok(0);
}
if entries.is_empty() {
println!("{}", ui::dim("(audit log is empty)"));
return Ok(0);
}
for e in entries {
// Shared with the report: a post-execution receipt is a
// success, not a denial (the v0.12 fix), and the colour comes
// from one place so every surface agrees.
let mark = ui::mark(&e.decision, &e.source);
let outcome = match (e.approved, e.exit_code) {
(Some(true), Some(code)) => format!(" → approved, exit {}", code),
(Some(false), _) => " → not run".to_string(),
(None, Some(code)) => format!(" → exit {}", code),
_ => String::new(),
};
let sess = e
.session
.as_deref()
.map(|s| format!(" ({})", &s[..s.len().min(8)]))
.unwrap_or_default();
println!(
"{} {} [{}{}] {} — {}{}{}",
ui::dim(&e.ts),
mark,
e.source,
sess,
e.command,
e.reason,
if e.escalated {
format!(" {}", ui::amber("⚠ escalated"))
} else {
String::new()
},
outcome
);
}
Ok(0)
}
Cmd::Notify { test } => {
let p = paths::resolve()?;
let policy = Policy::load(&p.policy_file())?;
if test {
notify::test(&policy)
} else {
println!("usage: termaxa notify --test");
Ok(1)
}
}
Cmd::Stats => {
let p = paths::resolve()?;
let log = audit::AuditLog::new(&p.state_dir)?;
let entries = log.read_last(1_000_000)?;
if entries.is_empty() {
println!("{}", ui::dim("(audit log is empty)"));
return Ok(0);
}
let total = entries.len();
let count =
|f: &dyn Fn(&audit::AuditEntry) -> bool| entries.iter().filter(|e| f(e)).count();
println!("entries : {}", total);
println!(
" allow : {}",
ui::green(&count(&|e| e.decision == "allow").to_string())
);
println!(
" ask : {}",
ui::amber(&count(&|e| e.decision == "ask").to_string())
);
println!(
" deny : {}",
ui::red(&count(&|e| e.decision == "deny").to_string())
);
println!(
"by source : hook {} / run {} / check {}",
count(&|e| e.source == "hook"),
count(&|e| e.source == "run"),
count(&|e| e.source == "check")
);
println!("escalated : {}", count(&|e| e.escalated));
let sessions: std::collections::HashSet<_> = entries
.iter()
.filter_map(|e| e.session.as_deref())
.collect();
println!("sessions : {}", sessions.len());
let mut denied: std::collections::HashMap<&str, usize> =
std::collections::HashMap::new();
for e in entries.iter().filter(|e| e.decision == "deny") {
*denied.entry(e.command.as_str()).or_default() += 1;
}
let mut top: Vec<_> = denied.into_iter().collect();
top.sort_by_key(|t| std::cmp::Reverse(t.1));
if !top.is_empty() {
println!("top denied :");
for (cmd, n) in top.into_iter().take(5) {
println!(" {}× {}", n, cmd);
}
}
Ok(0)
}
Cmd::Backups => {
let p = paths::resolve()?;
let records = backup::list(&p.state_dir)?;
if records.is_empty() {
println!("{}", ui::dim("(no backups yet)"));
return Ok(0);
}
for r in records {
println!(
"{} {} [{}] {}\n insures: {}",
r.id,
ui::dim(&r.ts),
r.kind,
r.note,
ui::dim(&r.command)
);
}
Ok(0)
}
Cmd::Report {
session,
all,
days,
md,
} => {
let p = paths::resolve()?;
report::run(&p, report::Scope { session, all, days }, md)
}
Cmd::Paths => {
let p = paths::resolve()?;
println!("policy : {}", p.policy_file().display());
println!("state : {}", p.state_dir.display());
println!(
"logs : {}",
p.state_dir.join("logs").join("audit.jsonl").display()
);
println!("backups: {}", p.state_dir.join("backups").display());
Ok(0)
}
Cmd::Rollback { id } => {
let p = paths::resolve()?;
let records = backup::list(&p.state_dir)?;
let Some(rec) = records.iter().find(|r| r.id == id) else {
bail!("no backup with id `{}` — see `termaxa backups`", id);
};
println!("restore : {} [{}]", rec.id, rec.kind);
println!("saved : {}", rec.note);
println!("insured : {}", rec.command);
print!("Restoring writes data. Proceed? [y/N] ");
use std::io::Write as _;
std::io::stdout().flush()?;
let mut line = String::new();
std::io::stdin().read_line(&mut line)?;
if !matches!(line.trim().to_lowercase().as_str(), "y" | "yes") {
eprintln!("termaxa: rollback declined.");
return Ok(1);
}
let msg = backup::restore(&p.state_dir, &id)?;
println!("{} {}", ui::green("✓"), msg);
Ok(0)
}
}
}