secondkey 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
secondkey/cli.py ADDED
@@ -0,0 +1,651 @@
1
+ """secondkey command-line interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import datetime as dt
7
+ import json
8
+ import os
9
+ import re
10
+ import shlex
11
+ import shutil
12
+ import subprocess
13
+ import sys
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from . import __version__, audit, gate
18
+ from . import snapshots as snapmod
19
+ from .classify import classify_tool
20
+ from .policy import PolicyError, default_policy_text, load_policy
21
+ from .store import Store
22
+ from .util import home, whoami
23
+
24
+ USE_COLOR = sys.stdout.isatty() and not os.environ.get("NO_COLOR")
25
+
26
+
27
+ def c(text: str, code: str) -> str:
28
+ return f"\033[{code}m{text}\033[0m" if USE_COLOR else text
29
+
30
+
31
+ def orange(t: str) -> str: return c(t, "38;5;208")
32
+ def green(t: str) -> str: return c(t, "32")
33
+ def red(t: str) -> str: return c(t, "31")
34
+ def dim(t: str) -> str: return c(t, "2")
35
+ def bold(t: str) -> str: return c(t, "1")
36
+
37
+
38
+ DECISION_COLOR = {"allow": green, "ask": orange, "deny": red}
39
+
40
+
41
+ def ago(ts: float | None) -> str:
42
+ if not ts:
43
+ return "-"
44
+ s = int(dt.datetime.now().timestamp() - ts)
45
+ if s < 60:
46
+ return f"{s}s ago"
47
+ if s < 3600:
48
+ return f"{s // 60}m ago"
49
+ if s < 86400:
50
+ return f"{s // 3600}h ago"
51
+ return dt.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M")
52
+
53
+
54
+ def project_root(start: str) -> Path:
55
+ d = Path(start).resolve()
56
+ for p in [d, *d.parents]:
57
+ if (p / ".git").exists():
58
+ return p
59
+ return d
60
+
61
+
62
+ # ------------------------------------------------------------------ init
63
+
64
+ HOOK_MARK = "secondkey hook claude-code"
65
+ _HOOK_RE = re.compile(r"secondkey(?:\.exe)?\\?[\"']?\s+hook\s+(claude-code|cursor)\b", re.I)
66
+
67
+
68
+ def hook_installed(path: Path, agent: str) -> bool:
69
+ """Read an agent's hook config as JSON and look for our hook command."""
70
+ try:
71
+ data = json.loads(path.read_text() or "{}")
72
+ except (OSError, json.JSONDecodeError):
73
+ return False
74
+ groups = (data.get("hooks") or {}).values()
75
+ for entries in groups:
76
+ for e in entries or []:
77
+ cmds = [h.get("command", "") for h in e.get("hooks", [])] if "hooks" in e else [e.get("command", "")]
78
+ if any(is_secondkey_hook(c, agent) for c in cmds):
79
+ return True
80
+ return False
81
+
82
+
83
+ def is_secondkey_hook(command: str, agent: str) -> bool:
84
+ """Recognise our hook however the path was written (secondkey, secondkey.EXE, quoted, python -m)."""
85
+ m = _HOOK_RE.search(str(command or ""))
86
+ return bool(m and m.group(1).lower() == agent)
87
+
88
+
89
+ def hook_command(agent: str) -> str:
90
+ """The command an agent should run for the hook.
91
+
92
+ On Windows, paths are written with forward slashes and double quotes, which work
93
+ in Git Bash (what Claude Code uses on Windows), cmd.exe and PowerShell alike.
94
+ """
95
+ exe = shutil.which("secondkey")
96
+ if os.name == "nt":
97
+ if exe:
98
+ return f'"{exe.replace(os.sep, "/")}" hook {agent}'
99
+ return f'"{sys.executable.replace(os.sep, "/")}" -m secondkey hook {agent}'
100
+ if exe:
101
+ return f"{shlex.quote(exe)} hook {agent}"
102
+ return f"{shlex.quote(sys.executable)} -m secondkey hook {agent}"
103
+
104
+
105
+ def install_claude_hook(settings_path: Path) -> str:
106
+ settings_path.parent.mkdir(parents=True, exist_ok=True)
107
+ data: dict[str, Any] = {}
108
+ if settings_path.exists():
109
+ try:
110
+ data = json.loads(settings_path.read_text() or "{}")
111
+ except json.JSONDecodeError as e:
112
+ raise SystemExit(f"{settings_path} is not valid JSON ({e}); fix it and re-run init.")
113
+ hooks = data.setdefault("hooks", {})
114
+ pre = hooks.setdefault("PreToolUse", [])
115
+ command = hook_command("claude-code")
116
+ status = None
117
+ for group in pre:
118
+ for h in group.get("hooks", []):
119
+ if is_secondkey_hook(h.get("command", ""), "claude-code"):
120
+ if h.get("command") == command:
121
+ status = status or "already installed"
122
+ else:
123
+ h["command"] = command # repair an old or mis-quoted path
124
+ status = "updated"
125
+ if status == "already installed":
126
+ return status
127
+ if status is None:
128
+ pre.append({"matcher": "*", "hooks": [{"type": "command", "command": command, "timeout": 900}]})
129
+ status = "installed"
130
+ tmp = settings_path.with_suffix(".json.tmp")
131
+ tmp.write_text(json.dumps(data, indent=2) + "\n")
132
+ tmp.replace(settings_path)
133
+ return status
134
+
135
+
136
+ CURSOR_EVENTS = ("beforeShellExecution", "beforeReadFile", "beforeMCPExecution")
137
+
138
+
139
+ def install_cursor_hook(hooks_path: Path) -> str:
140
+ hooks_path.parent.mkdir(parents=True, exist_ok=True)
141
+ data: dict[str, Any] = {"version": 1, "hooks": {}}
142
+ if hooks_path.exists():
143
+ try:
144
+ data = json.loads(hooks_path.read_text() or "{}")
145
+ except json.JSONDecodeError as e:
146
+ raise SystemExit(f"{hooks_path} is not valid JSON ({e}); fix it and re-run init.")
147
+ data.setdefault("version", 1)
148
+ hooks = data.setdefault("hooks", {})
149
+ command = hook_command("cursor")
150
+ added = 0
151
+ for ev in CURSOR_EVENTS:
152
+ entries = hooks.setdefault(ev, [])
153
+ mine = [e for e in entries if is_secondkey_hook(e.get("command", ""), "cursor")]
154
+ for e in mine:
155
+ if e.get("command") != command:
156
+ e["command"] = command
157
+ added += 1
158
+ if not mine:
159
+ entries.append({"command": command, "timeout": 900})
160
+ added += 1
161
+ tmp = hooks_path.with_suffix(".json.tmp")
162
+ tmp.write_text(json.dumps(data, indent=2) + "\n")
163
+ tmp.replace(hooks_path)
164
+ return "installed" if added else "already installed"
165
+
166
+
167
+ def cmd_init(a: argparse.Namespace) -> int:
168
+ root = project_root(a.cwd)
169
+ if a.scope == "user":
170
+ policy_path, settings = home() / "policy.yaml", Path.home() / ".claude" / "settings.json"
171
+ cursor_hooks = Path.home() / ".cursor" / "hooks.json"
172
+ else:
173
+ policy_path, settings = root / ".secondkey" / "policy.yaml", root / ".claude" / "settings.json"
174
+ cursor_hooks = root / ".cursor" / "hooks.json"
175
+ policy_path.parent.mkdir(parents=True, exist_ok=True)
176
+ if policy_path.exists() and not a.force:
177
+ print(f"policy {policy_path} {dim('(kept existing; --force to overwrite)')}")
178
+ else:
179
+ text = default_policy_text()
180
+ if a.via_agent:
181
+ text = text.replace("via: secondkey", "via: agent")
182
+ policy_path.write_text(text)
183
+ print(f"policy {policy_path} {green('written')}")
184
+ if not a.no_hook:
185
+ agents = a.agent or ["claude-code"]
186
+ if "claude-code" in agents:
187
+ print(f"hook {settings} {green(install_claude_hook(settings))}")
188
+ if "cursor" in agents:
189
+ print(f"hook {cursor_hooks} {green(install_cursor_hook(cursor_hooks))}")
190
+ print(f"state {home()}")
191
+ print()
192
+ print("Next: start Claude Code in this project. Try asking it to run")
193
+ example = 'psql $DB -c "DROP TABLE x"'
194
+ print(f" {bold('rm -rf ./some-folder')} or {bold(example)}")
195
+ print(f"and approve with {bold('secondkey pending')} / {bold('secondkey approve <id>')}.")
196
+ preview = 'secondkey check "<command>"'
197
+ print(f"Preview any command first: {bold(preview)}")
198
+ return 0
199
+
200
+
201
+ # ------------------------------------------------------------------ check / exec / hook
202
+
203
+ def cmd_check(a: argparse.Namespace) -> int:
204
+ command = " ".join(a.command)
205
+ policy = load_policy(a.cwd, a.policy)
206
+ tool_input = json.loads(command) if a.tool != "Bash" else {"command": command}
207
+ actions = classify_tool(a.tool, tool_input, a.cwd)
208
+ decision = policy.evaluate(actions)
209
+ impact, problems = ([], [])
210
+ if decision.decision != "deny" and decision.snapshot_actions and not a.no_probe:
211
+ impact, problems = snapmod.plan(decision.snapshot_actions, policy)
212
+ if a.json:
213
+ print(json.dumps({"decision": decision.decision, "reason": decision.reason, "policy": policy.source,
214
+ "actions": [{**v.action.to_dict(), "decision": v.decision, "snapshot": v.snapshot, "rule": v.rule}
215
+ for v in decision.verdicts], "impact": impact, "not_protected": problems}, indent=2))
216
+ return 0
217
+ color = DECISION_COLOR[decision.decision]
218
+ print(f"{bold(color(decision.decision.upper()))} {dim('policy: ' + policy.source)}")
219
+ for v in decision.verdicts:
220
+ snap = " + snapshot" if v.snapshot and v.decision != "deny" else ""
221
+ print(f" {DECISION_COLOR[v.decision](v.decision):>5}{snap} {v.action.category:<24} {v.action.summary}")
222
+ for line in impact:
223
+ print(f" impact {line}")
224
+ for p in problems:
225
+ print(f" {orange('not protected')} {p}")
226
+ return 0
227
+
228
+
229
+ def cmd_exec(a: argparse.Namespace) -> int:
230
+ command = " ".join(a.command) if len(a.command) > 1 else (a.command[0] if a.command else "")
231
+ if not command:
232
+ print("usage: secondkey exec -- <command>", file=sys.stderr)
233
+ return 2
234
+ policy = load_policy(a.cwd, a.policy)
235
+ wait = a.wait if a.wait is not None else max(policy.wait_seconds, 300.0)
236
+ if wait > 0 and sys.stderr.isatty():
237
+ print(dim(f"secondkey: checking… (waiting up to {int(wait)}s if approval is needed)"), file=sys.stderr)
238
+ result = gate.evaluate(source="exec", tool="Bash", tool_input={"command": command}, cwd=a.cwd, policy=policy,
239
+ wait=wait, native_ask=False)
240
+ if result.outcome == "deny":
241
+ print(red(result.message), file=sys.stderr)
242
+ return 126
243
+ if result.outcome == "held":
244
+ print(orange(result.message), file=sys.stderr)
245
+ return 3
246
+ if result.message:
247
+ print(dim(result.message), file=sys.stderr)
248
+ return subprocess.run(command, shell=True, cwd=a.cwd).returncode
249
+
250
+
251
+ def cmd_hook(a: argparse.Namespace) -> int:
252
+ if a.agent == "cursor":
253
+ from .hooks import cursor
254
+ return cursor.main()
255
+ from .hooks import claude_code
256
+ return claude_code.main()
257
+
258
+
259
+ # ------------------------------------------------------------------ requests
260
+
261
+ def _print_request(r: Any, verbose: bool = False) -> None:
262
+ status_color = {"pending": orange, "approved": green, "executed": green, "denied": red}.get(r.status, dim)
263
+ print(f"{bold(r.id)} {status_color(r.status)} {dim(ago(r.created))} {dim(r.source)} {dim(r.cwd)}")
264
+ print(f" {r.command if verbose else r.command[:200]}")
265
+ if r.reason:
266
+ print(f" {dim('why:')} {r.reason}")
267
+ for i in r.impact:
268
+ print(f" {dim('impact:')} {i}")
269
+ if r.decided_by:
270
+ print(f" {dim('decided by')} {r.decided_by} {dim(ago(r.decided_at))}")
271
+ if r.snapshot_ids:
272
+ print(f" {dim('snapshots:')} {' '.join(r.snapshot_ids)}")
273
+
274
+
275
+ def cmd_pending(a: argparse.Namespace) -> int:
276
+ store = Store()
277
+ reqs = store.list_requests(None if a.all else "pending", a.limit)
278
+ if not reqs:
279
+ print("No requests waiting for approval." if not a.all else "No requests yet.")
280
+ return 0
281
+ for r in reqs:
282
+ _print_request(r)
283
+ print()
284
+ if not a.all:
285
+ print(dim("approve: secondkey approve <id> deny: secondkey deny <id>"))
286
+ return 0
287
+
288
+
289
+ def cmd_show(a: argparse.Namespace) -> int:
290
+ r = Store().get_request(a.id)
291
+ if not r:
292
+ print(f"no request {a.id}", file=sys.stderr)
293
+ return 1
294
+ _print_request(r, verbose=True)
295
+ return 0
296
+
297
+
298
+ def _decide(a: argparse.Namespace, approve: bool) -> int:
299
+ store = Store()
300
+ r = store.get_request(a.id)
301
+ if not r:
302
+ print(f"no request {a.id}", file=sys.stderr)
303
+ return 1
304
+ policy = load_policy(r.cwd)
305
+ by = a.by or whoami()
306
+ try:
307
+ r = store.decide(a.id, approve, by, policy.ttl_seconds, skip_snapshot=getattr(a, "no_snapshot", False))
308
+ except ValueError as e:
309
+ print(str(e), file=sys.stderr)
310
+ return 1
311
+ audit.record("approve" if approve else "reject", request=r.id, by=by, command=r.command[:2000], cwd=r.cwd,
312
+ without_snapshot=r.skip_snapshot)
313
+ if approve:
314
+ mins = int(policy.ttl_seconds // 60)
315
+ print(f"{green('approved')} {r.id} by {by}. The agent can now retry the exact same command (valid {mins} min).")
316
+ if r.skip_snapshot:
317
+ print(orange("No restore point will be taken for this one."))
318
+ else:
319
+ print(f"{red('denied')} {r.id} by {by}. The agent will be told not to retry.")
320
+ return 0
321
+
322
+
323
+ # ------------------------------------------------------------------ log / snapshots / undo
324
+
325
+ def cmd_log(a: argparse.Namespace) -> int:
326
+ if a.verify:
327
+ ok, n, msg = audit.verify()
328
+ print((green("OK ") if ok else red("TAMPERED ")) + msg)
329
+ return 0 if ok else 1
330
+ rows = list(audit.entries())[-a.limit:]
331
+ if a.json:
332
+ for e in rows:
333
+ print(json.dumps(e))
334
+ return 0
335
+ if not rows:
336
+ print("Audit log is empty.")
337
+ return 0
338
+ color = {"deny": red, "reject": red, "hold": orange, "approve": green, "run_approved": green, "restore": green,
339
+ "allow": dim, "snapshot_failed": red, "ask_agent_prompt": orange}
340
+ for e in rows:
341
+ when = dt.datetime.fromtimestamp(e["ts"]).strftime("%m-%d %H:%M:%S")
342
+ ev = color.get(e["event"], str)(f"{e['event']:<14}")
343
+ detail = e.get("command") or e.get("snapshot") or ""
344
+ extra = []
345
+ if e.get("request"):
346
+ extra.append(e["request"])
347
+ if e.get("by") or e.get("approved_by"):
348
+ extra.append("by " + str(e.get("by") or e.get("approved_by")))
349
+ if e.get("snapshots"):
350
+ extra.append("snap " + ",".join(e["snapshots"]))
351
+ print(f"{dim(when)} {ev} {detail[:90]} {dim(' · '.join(extra))}")
352
+ return 0
353
+
354
+
355
+ def cmd_snapshots(a: argparse.Namespace) -> int:
356
+ snaps = Store().list_snapshots(a.limit)
357
+ if not snaps:
358
+ print("No snapshots yet.")
359
+ return 0
360
+ for s in snaps:
361
+ status = green(s.status) if s.status == "ok" else dim(s.status)
362
+ if s.status == "pruned" and not a.all:
363
+ continue
364
+ print(f"{bold(s.id)} {status:<8} {dim(ago(s.created)):<10} {s.provider:<9} {s.label}"
365
+ + (f" {dim('(' + s.request_id + ')')}" if s.request_id else ""))
366
+ return 0
367
+
368
+
369
+ def cmd_undo(a: argparse.Namespace) -> int:
370
+ store = Store()
371
+ if a.id.startswith("req_"):
372
+ snaps = store.snapshots_for(a.id)
373
+ if not snaps:
374
+ print(f"request {a.id} has no snapshots", file=sys.stderr)
375
+ return 1
376
+ else:
377
+ s = store.get_snapshot(a.id)
378
+ if not s:
379
+ print(f"no snapshot {a.id}", file=sys.stderr)
380
+ return 1
381
+ snaps = [s]
382
+ rc = 0
383
+ for s in snaps:
384
+ if s.status == "pruned":
385
+ print(f"{s.id} was pruned (older than the retention window); its files are gone.")
386
+ rc = 1
387
+ continue
388
+ if s.status == "restored" and not a.force:
389
+ print(f"{s.id} was already restored {ago(s.restored_at)} by {s.restored_by}; use --force to restore again.")
390
+ continue
391
+ print(f"{bold(s.id)} {s.provider} {s.label}")
392
+ try:
393
+ plan = snapmod.describe(s, a.mode)
394
+ except Exception as e: # noqa: BLE001
395
+ plan = [f"(couldn't describe: {e})"]
396
+ for line in plan:
397
+ print(f" will: {line}")
398
+ if a.dry_run:
399
+ continue
400
+ if not a.yes:
401
+ if not sys.stdin.isatty():
402
+ print("refusing to restore without confirmation; pass --yes", file=sys.stderr)
403
+ return 1
404
+ if input("Restore? [y/N] ").strip().lower() not in ("y", "yes"):
405
+ print("skipped")
406
+ continue
407
+ try:
408
+ done = snapmod.restore(s, a.mode, a.force)
409
+ except snapmod.RestoreError as e:
410
+ print(red(f" restore failed: {e}"), file=sys.stderr)
411
+ audit.record("restore_failed", snapshot=s.id, error=str(e)[:500], by=whoami())
412
+ rc = 1
413
+ continue
414
+ except Exception as e: # noqa: BLE001
415
+ print(red(f" restore failed: {e.__class__.__name__}: {e}"), file=sys.stderr)
416
+ audit.record("restore_failed", snapshot=s.id, error=str(e)[:500], by=whoami())
417
+ rc = 1
418
+ continue
419
+ by = whoami()
420
+ store.mark_restored(s.id, by)
421
+ audit.record("restore", snapshot=s.id, request=s.request_id, provider=s.provider, by=by, mode=a.mode)
422
+ for line in done:
423
+ print(f" {green('✓')} {line}")
424
+ return rc
425
+
426
+
427
+ def cmd_prune(a: argparse.Namespace) -> int:
428
+ policy = load_policy(a.cwd)
429
+ store = Store()
430
+ max_bytes = int(a.max_mb * 1024 * 1024) if a.max_mb is not None else None
431
+ removed = snapmod.prune(store, policy, a.older_than, max_bytes, dry_run=a.dry_run)
432
+ live = store.live_snapshots()
433
+ if not removed:
434
+ print(f"Nothing to prune. {len(live)} snapshot(s) kept.")
435
+ return 0
436
+ from .util import human_size
437
+ for s, reason, size in removed:
438
+ print(f"{'would remove' if a.dry_run else red('removed')} {s.id} {human_size(size):>8} {dim(reason)} {s.label[:60]}")
439
+ total = sum(b for _, _, b in removed)
440
+ print(f"{'Would free' if a.dry_run else 'Freed'} {human_size(total)}.")
441
+ if not a.dry_run:
442
+ audit.record("prune", snapshots=[s.id for s, _, _ in removed], by=whoami(), bytes=total)
443
+ return 0
444
+
445
+
446
+ def cmd_doctor(a: argparse.Namespace) -> int:
447
+ import platform
448
+ from .util import human_size, run
449
+ ok_mark, warn_mark, bad_mark = green("✓"), orange("!"), red("✗")
450
+ problems = 0
451
+
452
+ def line(mark: str, label: str, detail: str) -> None:
453
+ print(f" {mark} {label:<26} {detail}")
454
+
455
+ print(bold("SecondKey doctor"))
456
+ line(ok_mark, "version", f"secondkey {__version__}, Python {platform.python_version()}, {platform.system()}")
457
+ try:
458
+ p = load_policy(a.cwd)
459
+ line(ok_mark, "policy", f"{p.source} ({len(p.rules)} rules, approvals via {p.approval.get('via', 'secondkey')})")
460
+ except PolicyError as e:
461
+ line(bad_mark, "policy", str(e))
462
+ problems += 1
463
+ p = None
464
+ h = home()
465
+ if os.name == "nt":
466
+ # POSIX mode bits mean nothing on Windows; the user profile's ACLs keep it private.
467
+ line(ok_mark, "state directory", f"{h} (inside your Windows user profile)")
468
+ else:
469
+ mode = h.stat().st_mode & 0o777
470
+ line(ok_mark if not mode & 0o077 else warn_mark, "state directory", f"{h} (permissions {oct(mode)[2:]})")
471
+ root = project_root(a.cwd)
472
+ hooks = []
473
+ for name, path in (("Claude Code (project)", root / ".claude" / "settings.json"),
474
+ ("Claude Code (user)", Path.home() / ".claude" / "settings.json"),
475
+ ("Cursor (project)", root / ".cursor" / "hooks.json"),
476
+ ("Cursor (user)", Path.home() / ".cursor" / "hooks.json")):
477
+ try:
478
+ agent = "cursor" if "Cursor" in name else "claude-code"
479
+ if path.exists() and hook_installed(path, agent):
480
+ hooks.append(name)
481
+ except OSError:
482
+ pass
483
+ if hooks:
484
+ line(ok_mark, "agent hooks", ", ".join(hooks))
485
+ else:
486
+ line(bad_mark, "agent hooks", "none installed: run `secondkey init` (or `secondkey init --agent cursor`)")
487
+ problems += 1
488
+ tools = [("git", "git snapshots"), ("psql", "Postgres impact + restore"), ("pg_dump", "Postgres snapshots"),
489
+ ("pg_restore", "Postgres undo"), ("mysqldump", "MySQL snapshots"), ("kubectl", "Kubernetes snapshots"),
490
+ ("terraform", "Terraform state backup"), ("aws", "AWS EBS/RDS/S3 snapshots"), ("docker", "Docker volume snapshots"),
491
+ ("neonctl", "Neon branch snapshots")]
492
+ for tool, feature in tools:
493
+ path = shutil.which(tool)
494
+ if path:
495
+ ver = ""
496
+ if tool in ("pg_dump", "psql"):
497
+ import re as _re
498
+ m = _re.search(r"\d+\.\d+", run([tool, "--version"], check=False).stdout)
499
+ ver = f" (v{m.group(0)})" if m else ""
500
+ line(ok_mark, tool, f"{feature}{ver}")
501
+ else:
502
+ line(dim("·"), tool, dim(f"not found: {feature} unavailable"))
503
+ if p is not None:
504
+ line(ok_mark if p.slack_webhook() else dim("·"), "slack", "notifications on" if p.slack_webhook() else dim("off (set SECONDKEY_SLACK_WEBHOOK)"))
505
+ ok, n, msg = audit.verify()
506
+ line(ok_mark if ok else bad_mark, "audit log", msg)
507
+ problems += 0 if ok else 1
508
+ store = Store()
509
+ live = store.live_snapshots()
510
+ size = sum(snapmod.dir_size(s.path) for s in live if os.path.isdir(s.path))
511
+ line(ok_mark, "snapshots", f"{len(live)} kept, {human_size(size)} on disk")
512
+ pend = store.list_requests("pending")
513
+ line(orange("!") if pend else ok_mark, "pending approvals", f"{len(pend)}" + (" (run `secondkey pending`)" if pend else ""))
514
+ print()
515
+ print(green("All good.") if not problems else orange(f"{problems} problem(s) found."))
516
+ return 0 if not problems else 1
517
+
518
+
519
+ def cmd_policy(a: argparse.Namespace) -> int:
520
+ p = load_policy(a.cwd, a.policy)
521
+ if a.default:
522
+ print(default_policy_text(), end="")
523
+ return 0
524
+ print(f"policy: {p.source}")
525
+ for i, r in enumerate(p.rules):
526
+ snap = " + snapshot" if r.snapshot and r.action != "deny" else ""
527
+ print(f" {DECISION_COLOR[r.action](r.action):>5}{snap:<11} {', '.join(r.match)}")
528
+ print(f" {DECISION_COLOR[p.default](p.default):>5}{'':<11} (everything else)")
529
+ print(f"approval via {p.approval.get('via', 'secondkey')}, wait {int(p.wait_seconds)}s, approvals valid {int(p.ttl_seconds // 60)} min")
530
+ print(f"slack notifications: {'on' if p.slack_webhook() else 'off'}")
531
+ return 0
532
+
533
+
534
+ # ------------------------------------------------------------------ parser
535
+
536
+ def build_parser() -> argparse.ArgumentParser:
537
+ ap = argparse.ArgumentParser(prog="secondkey", description="The second key for every AI agent action.")
538
+ ap.add_argument("--version", action="version", version=f"secondkey {__version__}")
539
+ ap.add_argument("-C", dest="cwd", default=os.getcwd(), help="run as if started in this directory")
540
+ sub = ap.add_subparsers(dest="cmd", required=True)
541
+
542
+ p = sub.add_parser("init", help="write a policy and install the Claude Code hook")
543
+ p.add_argument("--scope", choices=["project", "user"], default="project")
544
+ p.add_argument("--no-hook", action="store_true", help="only write the policy")
545
+ p.add_argument("--force", action="store_true", help="overwrite an existing policy")
546
+ p.add_argument("--via-agent", action="store_true", help="approve in the agent's own prompt instead of `secondkey approve`")
547
+ p.add_argument("--agent", action="append", choices=["claude-code", "cursor"],
548
+ help="which agent to hook (repeatable; default claude-code)")
549
+ p.set_defaults(fn=cmd_init)
550
+
551
+ p = sub.add_parser("check", help="show what SecondKey would decide for a command (nothing is run)")
552
+ p.add_argument("command", nargs="+")
553
+ p.add_argument("--tool", default="Bash", help="tool name; for non-Bash tools pass tool_input JSON as the command")
554
+ p.add_argument("--policy")
555
+ p.add_argument("--json", action="store_true")
556
+ p.add_argument("--no-probe", action="store_true", help="don't connect to databases/clusters to estimate impact")
557
+ p.set_defaults(fn=cmd_check)
558
+
559
+ p = sub.add_parser("exec", help="run a command through the gate (for agents without hook support)")
560
+ p.add_argument("command", nargs=argparse.REMAINDER)
561
+ p.add_argument("--wait", type=float, default=None, help="seconds to wait for approval (default 300)")
562
+ p.add_argument("--policy")
563
+ p.set_defaults(fn=cmd_exec)
564
+
565
+ p = sub.add_parser("hook", help="agent hook entry point (used by `init`)")
566
+ p.add_argument("agent", choices=["claude-code", "cursor"])
567
+ p.set_defaults(fn=cmd_hook)
568
+
569
+ p = sub.add_parser("pending", help="list commands waiting for approval")
570
+ p.add_argument("--all", action="store_true", help="include decided requests")
571
+ p.add_argument("-n", "--limit", type=int, default=30)
572
+ p.set_defaults(fn=cmd_pending)
573
+
574
+ p = sub.add_parser("show", help="show one request")
575
+ p.add_argument("id")
576
+ p.set_defaults(fn=cmd_show)
577
+
578
+ p = sub.add_parser("approve", help="turn the second key for a held command")
579
+ p.add_argument("id")
580
+ p.add_argument("--by", help="approver name (default: current user)")
581
+ p.add_argument("--no-snapshot", action="store_true", help="run without taking a restore point")
582
+ p.set_defaults(fn=lambda a: _decide(a, True))
583
+
584
+ p = sub.add_parser("deny", help="reject a held command")
585
+ p.add_argument("id")
586
+ p.add_argument("--by")
587
+ p.set_defaults(fn=lambda a: _decide(a, False))
588
+
589
+ p = sub.add_parser("log", help="show the audit log")
590
+ p.add_argument("-n", "--limit", type=int, default=40)
591
+ p.add_argument("--verify", action="store_true", help="check the hash chain for tampering")
592
+ p.add_argument("--json", action="store_true")
593
+ p.set_defaults(fn=cmd_log)
594
+
595
+ p = sub.add_parser("snapshots", help="list restore points")
596
+ p.add_argument("-n", "--limit", type=int, default=30)
597
+ p.add_argument("--all", action="store_true", help="include pruned ones")
598
+ p.set_defaults(fn=cmd_snapshots)
599
+
600
+ p = sub.add_parser("undo", help="restore a snapshot (or every snapshot of a request)")
601
+ p.add_argument("id", help="snap_... or req_...")
602
+ p.add_argument("--mode", choices=["full", "data", "exact"],
603
+ help="postgres: data = put saved rows back, keep newer ones (default when tables exist); "
604
+ "exact = also remove rows written since; full = drop and recreate the tables")
605
+ p.add_argument("--force", action="store_true", help="overwrite things that exist again / restore twice")
606
+ p.add_argument("--yes", "-y", action="store_true", help="don't ask for confirmation")
607
+ p.add_argument("--dry-run", action="store_true", help="only show what would happen")
608
+ p.set_defaults(fn=cmd_undo)
609
+
610
+ p = sub.add_parser("prune", help="delete old restore points (also runs automatically once a day)")
611
+ p.add_argument("--older-than", type=float, metavar="DAYS", help="default: snapshots.retention_days")
612
+ p.add_argument("--max-mb", type=float, help="default: snapshots.max_total_mb")
613
+ p.add_argument("--dry-run", action="store_true")
614
+ p.set_defaults(fn=cmd_prune)
615
+
616
+ p = sub.add_parser("proxy", help="run a Postgres proxy that gates every query (scripts, ORMs, migrations)")
617
+ p.add_argument("--listen", default="127.0.0.1:6543", help="host:port to listen on (default 127.0.0.1:6543)")
618
+ p.add_argument("--upstream", required=True, help="the real database: host:port or a unix socket path")
619
+ p.add_argument("--upstream-ssl", action="store_true", help="use TLS to the upstream database (Python 3.11+)")
620
+ p.add_argument("--wait", type=float, default=0, help="seconds to wait for an approval before failing the query")
621
+ p.add_argument("--snapshot-dsn", help="connection string pg_dump should use (default: upstream + client's db/user)")
622
+ p.set_defaults(fn=lambda a: __import__("secondkey.proxy", fromlist=["run_proxy"]).run_proxy(
623
+ __import__("secondkey.proxy", fromlist=["config_from_args"]).config_from_args(a)))
624
+
625
+ p = sub.add_parser("doctor", help="check the installation, hooks, tools and state")
626
+ p.set_defaults(fn=cmd_doctor)
627
+
628
+ p = sub.add_parser("policy", help="show the effective policy")
629
+ p.add_argument("--policy")
630
+ p.add_argument("--default", action="store_true", help="print the built-in default policy")
631
+ p.set_defaults(fn=cmd_policy)
632
+ return ap
633
+
634
+
635
+ def main(argv: list[str] | None = None) -> int:
636
+ args = build_parser().parse_args(argv)
637
+ if getattr(args, "command", None) and args.cmd == "exec" and args.command[:1] == ["--"]:
638
+ args.command = args.command[1:]
639
+ try:
640
+ return int(args.fn(args) or 0)
641
+ except PolicyError as e:
642
+ print(red(f"policy error: {e}"), file=sys.stderr)
643
+ return 2
644
+ except KeyboardInterrupt:
645
+ return 130
646
+ except BrokenPipeError: # e.g. `secondkey log | head`
647
+ try:
648
+ sys.stdout = open(os.devnull, "w")
649
+ except OSError:
650
+ pass
651
+ return 0