@mokuyoaxis/agent-guard 0.2.2

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.
Files changed (77) hide show
  1. package/CONTRIBUTING.md +101 -0
  2. package/LICENSE +21 -0
  3. package/README.md +558 -0
  4. package/README.zh-CN.md +488 -0
  5. package/adapters/INTEGRATION.md +94 -0
  6. package/adapters/claude/README.md +141 -0
  7. package/adapters/claude/compatibility.json +17 -0
  8. package/adapters/claude/harness/README.md +59 -0
  9. package/adapters/claude/harness/mock_anthropic_api.mjs +47 -0
  10. package/adapters/claude/harness/run_scenario.sh +79 -0
  11. package/adapters/claude/harness/run_scenario_no_python3.sh +49 -0
  12. package/adapters/claude/hook_bridge.sh +33 -0
  13. package/adapters/claude/pre_tool_use.py +264 -0
  14. package/adapters/claude/settings.example.json +16 -0
  15. package/adapters/codex/harness/README.md +53 -0
  16. package/adapters/codex/harness/acceptance.py +226 -0
  17. package/adapters/dsh/README.md +62 -0
  18. package/adapters/dsh/cordis.patch.yml +30 -0
  19. package/adapters/dsh/lib/index.js +500 -0
  20. package/adapters/kimi-code/README.md +169 -0
  21. package/adapters/kimi-code/compatibility.json +17 -0
  22. package/adapters/kimi-code/config.example.toml +26 -0
  23. package/adapters/kimi-code/hook_bridge.sh +32 -0
  24. package/adapters/kimi-code/pre_tool_use.py +72 -0
  25. package/core/__init__.py +47 -0
  26. package/core/audit.py +86 -0
  27. package/core/classifier.py +1175 -0
  28. package/core/dialects.py +898 -0
  29. package/core/policy.py +817 -0
  30. package/core/recovery.py +700 -0
  31. package/core/redaction.py +1096 -0
  32. package/core/safe_view.py +212 -0
  33. package/docs/architecture.md +223 -0
  34. package/docs/compatibility.md +142 -0
  35. package/docs/development-note-unguarded-deletion.md +187 -0
  36. package/docs/friction.md +266 -0
  37. package/docs/harness-capabilities.md +72 -0
  38. package/docs/host-drift.md +142 -0
  39. package/docs/publishing-from-ephemeral-environments.md +104 -0
  40. package/docs/release-notes-0.2.0-rc1.md +46 -0
  41. package/docs/release-notes-0.2.0.md +72 -0
  42. package/docs/release-notes-0.2.1.md +78 -0
  43. package/docs/release-notes-0.2.2.md +120 -0
  44. package/docs/secret-guard-analysis.md +416 -0
  45. package/docs/secret-guard-architecture.md +93 -0
  46. package/docs/secret-guard-design.md +649 -0
  47. package/docs/test-report-claude-code-harness.md +462 -0
  48. package/docs/test-report-codex-gpt-5.6-sol.md +335 -0
  49. package/docs/test-report-codex-gpt-6-astra-high.md +129 -0
  50. package/docs/test-report-dsh-0.1.5-rc.1.md +84 -0
  51. package/docs/test-report-dsh-v0.1.1.md +126 -0
  52. package/docs/test-report-kimi-code-block.md +198 -0
  53. package/docs/test-report-zcode-glm-flash.md +241 -0
  54. package/docs/threat-model.md +44 -0
  55. package/doctor.py +756 -0
  56. package/live_sentinel.py +339 -0
  57. package/package.json +69 -0
  58. package/skills/delete-guard/SKILL.md +109 -0
  59. package/skills/delete-guard/agents/openai.yaml +4 -0
  60. package/skills/delete-guard/references/policy.md +161 -0
  61. package/skills/delete-guard/scripts/_bootstrap.py +8 -0
  62. package/skills/delete-guard/scripts/check.py +370 -0
  63. package/skills/delete-guard/scripts/gc.py +103 -0
  64. package/skills/delete-guard/scripts/restore.py +98 -0
  65. package/skills/delete-guard/scripts/safe_delete.py +256 -0
  66. package/skills/delete-guard/scripts/status.py +130 -0
  67. package/skills/exfil-guard/SKILL.md +143 -0
  68. package/skills/exfil-guard/agents/openai.yaml +4 -0
  69. package/skills/exfil-guard/references/channels.md +58 -0
  70. package/skills/exfil-guard/references/rules.md +194 -0
  71. package/skills/exfil-guard/scripts/_bootstrap.py +8 -0
  72. package/skills/exfil-guard/scripts/check_span.py +250 -0
  73. package/skills/exfil-guard/scripts/sanitize.py +155 -0
  74. package/skills/exfil-guard/scripts/view.py +44 -0
  75. package/skills/recovery-audit/SKILL.md +283 -0
  76. package/skills/recovery-audit/agents/openai.yaml +4 -0
  77. package/skills/recovery-audit/references/evidence-records.md +85 -0
@@ -0,0 +1,8 @@
1
+ """Shared sys.path bootstrap for the delete-guard CLI scripts."""
2
+ import os
3
+ import sys
4
+
5
+ _HERE = os.path.dirname(os.path.abspath(__file__))
6
+ _REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(_HERE)))
7
+ if _REPO_ROOT not in sys.path:
8
+ sys.path.insert(0, _REPO_ROOT)
@@ -0,0 +1,370 @@
1
+ #!/usr/bin/env python3
2
+ """check - classify a shell command before it runs (harness adapter entry).
3
+
4
+ check.py [--cwd DIR] [--enforce] [--json]
5
+ [--dialect {posix,cmd,powershell}] -- COMMAND...
6
+
7
+ Advisory mode (default): prints the verdict and does not mutate command
8
+ targets. It records the assessment when audit storage is available.
9
+ --enforce: performs the compensations first (relocate targets / git snapshot
10
+ / git-clean enumeration+relocation) and tells the caller to PROCEED, or
11
+ refuses with BLOCKED. Any BLOCK in the line means nothing is executed.
12
+ --dialect selects the lexical front end for COMMAND: `posix` (default,
13
+ unchanged behaviour), `cmd`, or `powershell`. Aliases such as `pwsh` and
14
+ `cmd.exe` are accepted. The dialect is NOT validated by argparse's
15
+ `choices` on purpose: an unknown selector must produce an explicit BLOCK
16
+ decision (with a reason code), not an argparse usage error that a harness
17
+ could mistake for "nothing to worry about".
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import json
23
+ import os
24
+ import sys
25
+ import time
26
+
27
+ import _bootstrap # noqa: F401
28
+
29
+ from core import AUDIT_NAME, TRASH_DIRNAME
30
+ from core import audit, classifier, dialects, policy, recovery
31
+
32
+
33
+ _REDACTED_COMMAND = "<redacted>"
34
+ _SAFE_OPS = frozenset({
35
+ "rm", "rmdir", "unlink", "shred", "find", "git", "del", "erase",
36
+ "rd", "ri", "remove-item",
37
+ })
38
+
39
+
40
+ def _safe_op(op: str) -> str:
41
+ """Only emit known verb names, never a verb copied unchecked from input."""
42
+ name = op.lower()
43
+ return name if name in _SAFE_OPS else "<opaque>"
44
+
45
+
46
+ class EnumerationUnavailable(Exception):
47
+ """The target set could not be enumerated, so the effect is unknown.
48
+
49
+ Deliberately NOT a compensation failure: nothing was attempted and
50
+ nothing was mutated. `git clean -fdx` outside a repository (or with a
51
+ `git` that cannot run) has an unknown blast radius, which is the same
52
+ fact as every other effect-uncertainty shape - so it takes the same
53
+ verdict (policy.md row 11b), not COMPENSATION_FAILED.
54
+ """
55
+
56
+
57
+ class DurableAuditUnavailable(Exception):
58
+ """An execution/ASK intent could not cross the durable audit boundary."""
59
+
60
+
61
+ def main() -> int:
62
+ ap = argparse.ArgumentParser(description=__doc__)
63
+ ap.add_argument("--cwd")
64
+ ap.add_argument("--enforce", action="store_true")
65
+ ap.add_argument("--json", action="store_true", dest="as_json")
66
+ # No argparse `choices`: an unknown dialect must reach the policy layer
67
+ # as an explicit BLOCK, not as a usage error (see module docstring).
68
+ ap.add_argument("--dialect", default=None, metavar="{posix,cmd,powershell}",
69
+ help="shell dialect of COMMAND (default: posix)")
70
+ ap.add_argument("command", nargs=argparse.REMAINDER)
71
+ args = ap.parse_args()
72
+ cmd_tokens = [t for t in args.command if t != "--"]
73
+ cmd = " ".join(cmd_tokens)
74
+
75
+ base = os.path.abspath(args.cwd) if args.cwd else os.getcwd()
76
+ workspace = classifier.discover_workspace(base)
77
+ trash_root = os.environ.get(
78
+ "AGENT_GUARD_TRASH", os.path.join(workspace, TRASH_DIRNAME))
79
+ mode = policy.load_mode(trash_root)["mode"]
80
+ ctx = policy.PolicyContext(
81
+ workspace=workspace, trash_root=trash_root, base_dir=base, mode=mode)
82
+ engine = recovery.RecoveryEngine(workspace, trash_root)
83
+ audit_path = os.path.join(trash_root, AUDIT_NAME)
84
+
85
+ started = time.monotonic()
86
+
87
+ # Resolve the dialect BEFORE classifying: an unusable selector means the
88
+ # command line was never classified, which is a BLOCK (with its own
89
+ # reason code) - never a silent fallback to POSIX.
90
+ resolution = dialects.resolve_dialect(
91
+ args.dialect if args.dialect is not None
92
+ else os.environ.get("AGENT_GUARD_DIALECT"),
93
+ source="flag --dialect" if args.dialect is not None
94
+ else "env AGENT_GUARD_DIALECT")
95
+
96
+ if resolution.ok:
97
+ specs, parse_error = classifier.classify_command(
98
+ cmd, resolution.dialect)
99
+ verdicts = policy.decide_ops(specs, ctx) if not parse_error else [
100
+ policy.Verdict(policy.DECISION_BLOCK,
101
+ policy.CODE_BLOCK_UNDETERMINABLE_EFFECT,
102
+ [f"parse error: {parse_error}"])]
103
+ else:
104
+ # No classification happened; the only safe verdict is BLOCK.
105
+ specs, parse_error = [], None
106
+ verdicts = [policy.decide_dialect_failure(resolution)]
107
+
108
+ top = policy.worst(verdicts)
109
+ latency_ms = round((time.monotonic() - started) * 1000, 1)
110
+ check_id = audit.new_txid()
111
+ requested = resolution.requested
112
+ if requested is None:
113
+ safe_requested = None
114
+ elif resolution.ok and isinstance(requested, str):
115
+ safe_requested = requested.strip().lower() or None
116
+ else:
117
+ safe_requested = "<redacted>"
118
+
119
+ out = {
120
+ "command": _REDACTED_COMMAND,
121
+ "check_id": check_id,
122
+ "mode": mode,
123
+ "dialect": resolution.dialect,
124
+ "dialect_requested": safe_requested,
125
+ "dialect_outcome": "ok" if resolution.ok else "unusable",
126
+ "decision": top.decision,
127
+ "code": top.code,
128
+ "explanation": policy.EXPLANATIONS.get(top.code, "Guard decision."),
129
+ # Policy notes can contain raw target spellings or parser fragments.
130
+ # The stable reason code and static explanation are the public detail.
131
+ "reasons": [],
132
+ "guard_latency_ms": latency_ms,
133
+ "ops": [{"op": _safe_op(s.op), "kind": s.kind,
134
+ "dialect": getattr(s, "dialect", resolution.dialect),
135
+ "undeterminable": s.undeterminable}
136
+ for s in specs],
137
+ "enforced": bool(args.enforce),
138
+ }
139
+ if not resolution.ok:
140
+ out["dialect_error"] = ("invalid dialect selector" if
141
+ resolution.kind == "invalid" else
142
+ "unknown dialect selector")
143
+
144
+ def finish(code):
145
+ out["exit"] = code
146
+ if args.as_json:
147
+ print(json.dumps(out, ensure_ascii=False, indent=2))
148
+ else:
149
+ summary = f"{out['decision']} [{out['code']}]"
150
+ print(summary)
151
+ for reason in out["reasons"][:4]:
152
+ print(f" - {reason}")
153
+ return code
154
+
155
+ def record(entry, required=False):
156
+ """Append audit, optionally making durability an authorization gate.
157
+
158
+ Establishing the ignore rule before the audit directory prevents a
159
+ blocked request from dirtying a fresh Git worktree. If audit storage
160
+ is unavailable, blocked/advisory requests keep their safer decision.
161
+ An execution authorization uses ``required=True`` and fails closed.
162
+ """
163
+ try:
164
+ engine.ensure_layout()
165
+ audit.append({"check_id": check_id, **entry}, audit_path)
166
+ return True
167
+ except Exception:
168
+ if required:
169
+ raise DurableAuditUnavailable from None
170
+ out.setdefault("warnings", []).append(
171
+ "audit unavailable: record could not be stored")
172
+ return False
173
+
174
+ def block_for_audit(reason, compensations=None):
175
+ """Refuse execution when its durable audit boundary is unavailable."""
176
+ out["decision"], out["code"] = "BLOCK", \
177
+ policy.CODE_BLOCK_COMPENSATION_FAILED
178
+ out["explanation"] = policy.EXPLANATIONS[out["code"]]
179
+ out["reasons"] = [reason]
180
+ out.setdefault("warnings", []).append(
181
+ "audit unavailable: execution was not authorized")
182
+ if compensations:
183
+ out["compensations"] = compensations
184
+ return finish(2)
185
+
186
+ if not args.enforce:
187
+ record({"event": "check", "decision": top.decision,
188
+ "code": top.code, "command": _REDACTED_COMMAND,
189
+ "dialect": resolution.dialect,
190
+ "dialect_requested": safe_requested,
191
+ "dialect_outcome": "ok" if resolution.ok else "unusable",
192
+ "guard_latency_ms": latency_ms})
193
+ return finish(0)
194
+
195
+ if top.asks:
196
+ # Single-execution authorization point. Adapters map this to their
197
+ # native ask UI; a harness without ask support degrades to deny
198
+ # while keeping the explanation (never silently allow).
199
+ try:
200
+ record({"event": "ask", "code": top.code,
201
+ "command": _REDACTED_COMMAND,
202
+ "reasons": out["reasons"], "phase": "intent"},
203
+ required=True)
204
+ except Exception:
205
+ return block_for_audit("durable ASK audit intent unavailable")
206
+ return finish(3)
207
+
208
+ if top.blocked:
209
+ record({"event": "enforce-block", "code": top.code,
210
+ "command": _REDACTED_COMMAND, "reasons": out["reasons"],
211
+ "guard_latency_ms": latency_ms})
212
+ return finish(2)
213
+
214
+ # Execute compensations in order; collect public recovery evidence before
215
+ # every attempt so even an exception after a partial move retains a txid.
216
+ compensations = []
217
+ mutating_codes = {
218
+ policy.CODE_ALLOW_REGENERABLE,
219
+ policy.CODE_ALLOW_TRASH_GC,
220
+ policy.CODE_RELOCATE_PATHS,
221
+ policy.CODE_RELOCATE_TREE,
222
+ policy.CODE_RELOCATE_NARROW,
223
+ policy.CODE_RELOCATE_VIA_CLEAN_ENUMERATE,
224
+ policy.CODE_SNAPSHOT_GIT_STASH,
225
+ }
226
+ needs_durable_audit = any(
227
+ verdict.code in mutating_codes for verdict in verdicts)
228
+ try:
229
+ # Authorization must be durable before enumeration, compensation or
230
+ # a direct regenerable/GC delete is allowed to reach the host shell.
231
+ if needs_durable_audit:
232
+ record({"event": "enforce-intent", "code": top.code,
233
+ "command": _REDACTED_COMMAND,
234
+ "guard_latency_ms": latency_ms}, required=True)
235
+ for spec, verdict in zip(specs, verdicts):
236
+ if spec.kind == classifier.KIND_FS_DELETE and \
237
+ verdict.decision == policy.DECISION_RELOCATE:
238
+ target_specs = classifier.classify_paths(
239
+ spec.targets, base, workspace, trash_root)
240
+ txid = audit.new_txid()
241
+ compensation = {"strategy": "relocate", "txid": txid,
242
+ "status": "started", "moved": 0,
243
+ "skipped": 0}
244
+ compensations.append(compensation)
245
+ report = engine.relocate(target_specs, txid=txid, meta={
246
+ "tool": "check --enforce", "check_id": check_id,
247
+ "command": _REDACTED_COMMAND})
248
+ compensation.update({
249
+ "moved": len(report["moved"]),
250
+ "skipped": len(report.get("skipped", [])),
251
+ "status": "complete",
252
+ })
253
+ if report.get("storage_failure"):
254
+ compensation["status"] = "storage-failed"
255
+ raise recovery.StorageUnavailable(
256
+ "quarantine storage unavailable during relocation")
257
+ if report.get("skipped"):
258
+ compensation["status"] = "partial"
259
+ raise RuntimeError(
260
+ "relocation did not cover every requested target")
261
+ elif verdict.code == policy.CODE_RELOCATE_VIA_CLEAN_ENUMERATE:
262
+ flags = getattr(spec, "extra_flags", [])
263
+ paths, err = engine.enumerate_git_clean(
264
+ base, flags, getattr(spec, "targets", []))
265
+ if err:
266
+ raise EnumerationUnavailable(
267
+ f"git clean enumeration failed: {err}")
268
+ target_specs = classifier.classify_paths(
269
+ paths, base, workspace, trash_root)
270
+ txid = audit.new_txid()
271
+ compensation = {"strategy": "clean-enumerate",
272
+ "txid": txid, "status": "started",
273
+ "moved": 0, "skipped": 0,
274
+ "enumerated": len(paths)}
275
+ compensations.append(compensation)
276
+ report = engine.relocate(target_specs, txid=txid, meta={
277
+ "tool": "check --enforce", "strategy": "clean-enumerate",
278
+ "check_id": check_id, "command": _REDACTED_COMMAND})
279
+ compensation.update({
280
+ "moved": len(report["moved"]),
281
+ "skipped": len(report.get("skipped", [])),
282
+ "status": "complete",
283
+ })
284
+ if report.get("storage_failure"):
285
+ compensation["status"] = "storage-failed"
286
+ raise recovery.StorageUnavailable(
287
+ "quarantine storage unavailable during git clean")
288
+ if report.get("skipped") or len(report["moved"]) != len(paths):
289
+ compensation["status"] = "partial"
290
+ raise RuntimeError(
291
+ "git clean compensation did not cover every target")
292
+ elif verdict.code == policy.CODE_SNAPSHOT_GIT_STASH:
293
+ txid = audit.new_txid()
294
+ compensation = {"strategy": "snapshot", "txid": txid,
295
+ "status": "started", "sha": None}
296
+ compensations.append(compensation)
297
+ snap = engine.snapshot_git(cwd=base, txid=txid, meta={
298
+ "tool": "check --enforce", "check_id": check_id,
299
+ "command": _REDACTED_COMMAND})
300
+ if not snap.get("ok"):
301
+ compensation["status"] = "failed"
302
+ raise RuntimeError(
303
+ "git snapshot failed: " +
304
+ (snap.get("error") or "unknown snapshot failure"))
305
+ compensation.update({"status": "complete",
306
+ "sha": snap["sha"]})
307
+ except DurableAuditUnavailable:
308
+ return block_for_audit("durable execution audit intent unavailable",
309
+ compensations)
310
+ except EnumerationUnavailable:
311
+ # The targets exist but their set is unknowable; refusing is the
312
+ # only honest verdict. Nothing was mutated, so this is not a
313
+ # compensation failure and must not be reported as one.
314
+ out["decision"], out["code"] = "BLOCK", \
315
+ policy.CODE_BLOCK_UNDETERMINABLE_EFFECT
316
+ out["explanation"] = policy.EXPLANATIONS[out["code"]]
317
+ out["reasons"] = ["git clean enumeration failed"]
318
+ if compensations:
319
+ out["compensations"] = compensations
320
+ record({"event": "enforce-block", "code": out["code"],
321
+ "command": _REDACTED_COMMAND, "reasons": out["reasons"]})
322
+ return finish(2)
323
+ except recovery.StorageUnavailable:
324
+ # Hard principle: never fall back to permanent deletion.
325
+ out["decision"], out["code"] = "BLOCK", \
326
+ policy.CODE_BLOCK_RELOCATE_FAILED_STORAGE
327
+ out["explanation"] = policy.EXPLANATIONS[out["code"]]
328
+ out["reasons"] = ["quarantine storage unavailable"]
329
+ if compensations:
330
+ for item in compensations:
331
+ if item.get("status") == "started":
332
+ item["status"] = "incomplete"
333
+ out["compensations"] = compensations
334
+ record({"event": "enforce-block", "code": out["code"],
335
+ "command": _REDACTED_COMMAND, "reasons": out["reasons"]})
336
+ return finish(2)
337
+ except Exception: # compensation failed: refuse to proceed
338
+ out["decision"], out["code"] = "BLOCK", \
339
+ policy.CODE_BLOCK_COMPENSATION_FAILED
340
+ out["explanation"] = policy.EXPLANATIONS[out["code"]]
341
+ out["reasons"] = ["compensation failed"]
342
+ if compensations:
343
+ for item in compensations:
344
+ if item.get("status") == "started":
345
+ item["status"] = "incomplete"
346
+ out["compensations"] = compensations
347
+ record({"event": "enforce-error", "command": _REDACTED_COMMAND,
348
+ "code": out["code"], "error": "compensation failed"})
349
+ return finish(2)
350
+
351
+ out["compensations"] = compensations
352
+ out["decision"] = "ALLOW"
353
+ try:
354
+ record({"event": "enforce-proceed", "command": _REDACTED_COMMAND,
355
+ "compensations": compensations,
356
+ "guard_latency_ms": latency_ms},
357
+ required=needs_durable_audit)
358
+ except Exception:
359
+ return block_for_audit(
360
+ "durable execution audit unavailable after compensation",
361
+ compensations)
362
+ return finish(0)
363
+
364
+
365
+ if __name__ == "__main__":
366
+ try:
367
+ sys.exit(main())
368
+ except Exception:
369
+ print("agent-guard internal error", file=sys.stderr)
370
+ sys.exit(1)
@@ -0,0 +1,103 @@
1
+ #!/usr/bin/env python3
2
+ """gc - quarantine retention maintenance (B4 policy).
3
+
4
+ Default is a DRY PLAN: shows what is GC_ELIGIBLE (soft 30-day retention or
5
+ 5 GiB cap, oldest first) and touches nothing. Purging is explicit:
6
+
7
+ gc.py # plan only
8
+ gc.py --execute --txid ID [--txid ID ...]
9
+ gc.py --execute --all-eligible
10
+
11
+ Every purge writes manifest tombstones and audit records; the audit log
12
+ itself is never garbage-collected.
13
+
14
+ Authority model (deliberate): --execute is allowed non-interactively.
15
+ Scheduled maintenance is legitimate, and purging already-quarantined
16
+ evidence is categorically lower-risk than capability escalation (which DOES
17
+ require a human terminal). Compensating control: every purge is audited
18
+ with session identity, and the audit trail is immutable by policy. Capacity limits NEVER cause the guard to
19
+ fall back to permanent deletion of live targets - see
20
+ CODE_RELOCATE_FAILED_STORAGE.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import json
26
+ import os
27
+ import sys
28
+
29
+ import _bootstrap # noqa: F401
30
+
31
+ from core import AUDIT_NAME, TRASH_DIRNAME, audit
32
+ from core import classifier, recovery
33
+
34
+
35
+ def main() -> int:
36
+ ap = argparse.ArgumentParser(description=__doc__)
37
+ ap.add_argument("--json", action="store_true", dest="as_json")
38
+ ap.add_argument("--execute", action="store_true",
39
+ help="actually purge (default: plan only)")
40
+ ap.add_argument("--txid", action="append", default=[],
41
+ help="transaction to purge (repeatable)")
42
+ ap.add_argument("--all-eligible", action="store_true",
43
+ help="purge every GC_ELIGIBLE transaction")
44
+ args = ap.parse_args()
45
+
46
+ base = os.getcwd()
47
+ workspace = classifier.discover_workspace(base)
48
+ trash_root = os.environ.get(
49
+ "AGENT_GUARD_TRASH", os.path.join(workspace, TRASH_DIRNAME))
50
+ engine = recovery.RecoveryEngine(workspace, trash_root)
51
+ plan = engine.gc_plan()
52
+
53
+ if not args.execute:
54
+ payload = {"mode": "plan", **plan}
55
+ if args.as_json:
56
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
57
+ else:
58
+ print(f"quarantine bytes: {plan['total_bytes']} "
59
+ f"(soft cap {plan['size_limit_bytes']})")
60
+ for entry in plan["eligible"]:
61
+ print(f" GC_ELIGIBLE [{entry['reason']}] {entry['txid']} "
62
+ f"{entry['bytes']}B {entry['items']} items")
63
+ if not plan["eligible"]:
64
+ print(" nothing eligible")
65
+ print("(dry plan; pass --execute to purge)")
66
+ return 0
67
+
68
+ txids = list(args.txid)
69
+ if args.all_eligible:
70
+ txids.extend(e["txid"] for e in plan["eligible"])
71
+ if not txids:
72
+ print("nothing selected: pass --txid or --all-eligible",
73
+ file=sys.stderr)
74
+ return 1
75
+
76
+ # Preflight both identity and audit durability before irreversible purge.
77
+ # A failed final receipt still leaves this intent plus manifest tombstones.
78
+ engine.validate_gc_targets(txids)
79
+ audit.append({"event": "gc-intent", "txids": txids},
80
+ os.path.join(trash_root, AUDIT_NAME))
81
+ report = engine.gc_execute(txids)
82
+ audit.append({"event": "gc", "action": "PURGED",
83
+ "purged": report["purged"], "missing": report["missing"],
84
+ "plan_reasons": {e["txid"]: e["reason"]
85
+ for e in plan["eligible"]}},
86
+ os.path.join(trash_root, AUDIT_NAME))
87
+ if args.as_json:
88
+ print(json.dumps({"mode": "execute", **report}, ensure_ascii=False,
89
+ indent=2))
90
+ else:
91
+ for txid in report["purged"]:
92
+ print(f"purged: {txid}")
93
+ for txid in report["missing"]:
94
+ print(f"missing (skipped): {txid}", file=sys.stderr)
95
+ return 0
96
+
97
+
98
+ if __name__ == "__main__":
99
+ try:
100
+ sys.exit(main())
101
+ except Exception as exc:
102
+ print(f"agent-guard internal error: {exc}", file=sys.stderr)
103
+ sys.exit(1)
@@ -0,0 +1,98 @@
1
+ #!/usr/bin/env python3
2
+ """restore - undo a guarded deletion transaction.
3
+
4
+ restore.py list [--json]
5
+ restore.py TXID [--force] [--json]
6
+
7
+ Restore is non-destructive by default: it refuses to overwrite anything now
8
+ occupying an origin path. --force is an explicit human decision.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import os
15
+ import sys
16
+
17
+ import _bootstrap # noqa: F401
18
+
19
+ from core import AUDIT_NAME, TRASH_DIRNAME, audit
20
+ from core import classifier, policy, recovery
21
+
22
+
23
+ def context():
24
+ base = os.getcwd()
25
+ workspace = classifier.discover_workspace(base)
26
+ trash_root = os.environ.get(
27
+ "AGENT_GUARD_TRASH", os.path.join(workspace, TRASH_DIRNAME))
28
+ return recovery.RecoveryEngine(workspace, trash_root)
29
+
30
+
31
+ def main() -> int:
32
+ ap = argparse.ArgumentParser(description=__doc__)
33
+ sub = ap.add_subparsers(dest="cmd", required=True)
34
+ lp = sub.add_parser("list")
35
+ lp.add_argument("--json", action="store_true", dest="as_json")
36
+ rp = sub.add_parser("restore")
37
+ rp.add_argument("txid")
38
+ rp.add_argument("--force", action="store_true")
39
+ rp.add_argument("--json", action="store_true", dest="as_json")
40
+ # Allow the ergonomic form: restore.py <txid> == restore.py restore <txid>
41
+ argv = sys.argv[1:]
42
+ if argv and argv[0] not in ("list", "restore", "-h", "--help"):
43
+ argv = ["restore"] + argv
44
+ args = ap.parse_args(argv)
45
+
46
+ engine = context()
47
+
48
+ if args.cmd == "list":
49
+ txs = engine.transactions()
50
+ usage = engine.usage()
51
+ listing = [{"txid": t["txid"], "ts": t.get("ts"),
52
+ "items": len(t["items"]),
53
+ "restorable_items": t.get("restorable_items", 0),
54
+ "state": t.get("state", "EMPTY"),
55
+ "strategies": sorted({i.get("type") for i in t["items"]})}
56
+ for t in txs.values()]
57
+ if args.as_json:
58
+ print(json.dumps({"transactions": listing, "usage": usage},
59
+ ensure_ascii=False, indent=2))
60
+ else:
61
+ print(f"quarantine: {engine.trash_root}")
62
+ print(f"files={usage['files']} bytes={usage['bytes']} "
63
+ f"transactions={usage['transactions']}")
64
+ for item in listing[-20:]:
65
+ print(f" {item['txid']} {item['state']:<10} "
66
+ f"{item['restorable_items']:>3}/{item['items']} items "
67
+ f"{','.join(item['strategies'])}")
68
+ return 0
69
+
70
+ report = engine.restore(args.txid, force=args.force)
71
+ workspace = engine.workspace
72
+ audit.append({"event": "restore", "txid": args.txid, "force": args.force,
73
+ "ok": report.get("ok"), "restored": report.get("restored"),
74
+ "conflicts": report.get("conflicts"),
75
+ "errors": report.get("errors")},
76
+ os.path.join(engine.trash_root, AUDIT_NAME))
77
+ if args.as_json:
78
+ print(json.dumps(report, ensure_ascii=False, indent=2))
79
+ else:
80
+ for path in report.get("restored", []):
81
+ print(f"restored: {path}")
82
+ for path in report.get("conflicts", []):
83
+ print(f"conflict (exists; use --force): {path}")
84
+ for err in report.get("errors", []):
85
+ print(f"error: {err}", file=sys.stderr)
86
+ if report.get("errors"):
87
+ return 1
88
+ if report.get("conflicts"):
89
+ return 3
90
+ return 0 if report.get("ok") else 1
91
+
92
+
93
+ if __name__ == "__main__":
94
+ try:
95
+ sys.exit(main())
96
+ except Exception as exc:
97
+ print(f"agent-guard internal error: {exc}", file=sys.stderr)
98
+ sys.exit(1)