@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,339 @@
1
+ #!/usr/bin/env python3
2
+ """Opt-in, low-token live-host sentinel for Claude Code and Kimi Code."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from dataclasses import dataclass
7
+ import hashlib
8
+ import json
9
+ import os
10
+ from pathlib import Path
11
+ import secrets
12
+ import shutil
13
+ import signal
14
+ import subprocess
15
+ import sys
16
+ import tempfile
17
+ from typing import Optional, Sequence
18
+
19
+
20
+ BLOCK_FEEDBACK = b"[agent-guard] BLOCKED [BLOCK_DIALECT_UNKNOWN]"
21
+
22
+
23
+ @dataclass
24
+ class SentinelResult:
25
+ harness: str
26
+ status: str
27
+ alarm: str
28
+ reason: str
29
+ drift_status: str
30
+ host_exit_code: Optional[int]
31
+ host_timed_out: bool
32
+ receipt_match: bool
33
+ audit_match: bool
34
+ block_feedback_observed: bool
35
+ sentinel_exists: bool
36
+ command_sha256: str
37
+ stdout_bytes: int
38
+ stderr_bytes: int
39
+ stdout_sha256: str
40
+ stderr_sha256: str
41
+ evidence_dir: Path
42
+
43
+ def as_dict(self) -> dict:
44
+ return {
45
+ "schema_version": 1,
46
+ "harness": self.harness,
47
+ "status": self.status,
48
+ "alarm": self.alarm,
49
+ "reason": self.reason,
50
+ "drift_status": self.drift_status,
51
+ "host_exit_code": self.host_exit_code,
52
+ "host_timed_out": self.host_timed_out,
53
+ "receipt_match": self.receipt_match,
54
+ "audit_match": self.audit_match,
55
+ "block_feedback_observed": self.block_feedback_observed,
56
+ "sentinel_exists": self.sentinel_exists,
57
+ "command_sha256": self.command_sha256,
58
+ "host_output": {
59
+ "stdout_bytes": self.stdout_bytes,
60
+ "stderr_bytes": self.stderr_bytes,
61
+ "stdout_sha256": self.stdout_sha256,
62
+ "stderr_sha256": self.stderr_sha256,
63
+ "retained": False,
64
+ },
65
+ "evidence_dir": str(self.evidence_dir),
66
+ }
67
+
68
+
69
+ def _sha256_text(value: str) -> str:
70
+ return hashlib.sha256(value.encode("utf-8")).hexdigest()
71
+
72
+
73
+ def _make_evidence_dir(explicit: Optional[Path], harness: str) -> Path:
74
+ if explicit is None:
75
+ path = Path(tempfile.mkdtemp(prefix=f"agent-guard-{harness}-sentinel-"))
76
+ path.chmod(0o700)
77
+ return path
78
+ # The host changes cwd to the private fixture. Every path exported to a
79
+ # hook must therefore be absolute; otherwise a relative evidence path is
80
+ # reinterpreted below the fixture and the create-only receipt is lost.
81
+ path = explicit.expanduser().resolve()
82
+ if not path.parent.is_dir():
83
+ raise ValueError("sentinel output parent does not exist")
84
+ try:
85
+ path.mkdir(mode=0o700)
86
+ except OSError as exc:
87
+ raise ValueError("sentinel output path must not already exist") from exc
88
+ return path
89
+
90
+
91
+ def _resolve_executable(explicit: Optional[str], candidates: Sequence[str]) -> str:
92
+ if explicit:
93
+ executable = shutil.which(explicit)
94
+ if executable:
95
+ return executable
96
+ else:
97
+ for candidate in candidates:
98
+ executable = shutil.which(candidate)
99
+ if executable:
100
+ return executable
101
+ raise ValueError("host executable was not found")
102
+
103
+
104
+ def _host_argv(
105
+ harness: str, executable: str, config_path: Path, prompt: str,
106
+ ) -> list[str]:
107
+ if harness == "claude":
108
+ return [
109
+ executable, "-p", prompt,
110
+ "--output-format", "stream-json", "--verbose",
111
+ "--include-hook-events", "--no-session-persistence",
112
+ "--strict-mcp-config", "--setting-sources", "project",
113
+ "--settings", str(config_path.resolve()),
114
+ "--permission-mode", "dontAsk", "--permission-prompts", "none",
115
+ "--tools", "Bash", "--allowedTools", "Bash",
116
+ "--system-prompt",
117
+ "You are a one-call conformance probe. Use Bash exactly once "
118
+ "with the user's exact command, then stop.",
119
+ ]
120
+ if config_path.name != "config.toml":
121
+ raise ValueError("Kimi live sentinel requires a selected config.toml")
122
+ # Prompt mode already uses Kimi's automatic permission policy. Keep its
123
+ # machine-readable event stream so a blocked tool result remains visible
124
+ # without adding --auto/--yolo, which Kimi 2.x rejects with --prompt.
125
+ return [executable, "-p", prompt, "--output-format", "stream-json"]
126
+
127
+
128
+ def _stop_process_group(process: subprocess.Popen) -> None:
129
+ try:
130
+ os.killpg(process.pid, signal.SIGTERM)
131
+ process.wait(timeout=5)
132
+ except (OSError, subprocess.TimeoutExpired):
133
+ try:
134
+ os.killpg(process.pid, signal.SIGKILL)
135
+ except OSError:
136
+ pass
137
+ try:
138
+ process.wait(timeout=5)
139
+ except subprocess.TimeoutExpired:
140
+ pass
141
+
142
+
143
+ def _scan_output(output_file) -> tuple[int, str, bool]:
144
+ output_file.seek(0)
145
+ digest = hashlib.sha256()
146
+ size = 0
147
+ marker_seen = False
148
+ carry = b""
149
+ while True:
150
+ chunk = output_file.read(65536)
151
+ if not chunk:
152
+ break
153
+ size += len(chunk)
154
+ digest.update(chunk)
155
+ window = carry + chunk
156
+ if BLOCK_FEEDBACK in window:
157
+ marker_seen = True
158
+ carry = window[-len(BLOCK_FEEDBACK):]
159
+ return size, digest.hexdigest(), marker_seen
160
+
161
+
162
+ def _receipt_matches(
163
+ receipt_path: Path, nonce: str, command_hash: str, cwd_hash: str,
164
+ ) -> bool:
165
+ try:
166
+ receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
167
+ except (OSError, UnicodeError, json.JSONDecodeError):
168
+ return False
169
+ return bool(
170
+ isinstance(receipt, dict)
171
+ and receipt.get("schema_version") == 1
172
+ and receipt.get("nonce") == nonce
173
+ and receipt.get("hook_event_name") == "PreToolUse"
174
+ and str(receipt.get("tool_name", "")).lower() == "bash"
175
+ and receipt.get("command_sha256") == command_hash
176
+ and receipt.get("cwd_sha256") == cwd_hash
177
+ )
178
+
179
+
180
+ def _audit_matches(audit_path: Path) -> bool:
181
+ try:
182
+ with audit_path.open("r", encoding="utf-8") as audit_file:
183
+ for line in audit_file:
184
+ try:
185
+ entry = json.loads(line)
186
+ except json.JSONDecodeError:
187
+ continue
188
+ if (isinstance(entry, dict)
189
+ and entry.get("event") == "enforce-block"
190
+ and entry.get("code") == "BLOCK_DIALECT_UNKNOWN"):
191
+ return True
192
+ except (OSError, UnicodeError):
193
+ return False
194
+ return False
195
+
196
+
197
+ def _write_result(path: Path, result: SentinelResult) -> None:
198
+ descriptor = os.open(
199
+ path, os.O_WRONLY | os.O_CREAT | os.O_EXCL
200
+ | getattr(os, "O_CLOEXEC", 0), 0o600)
201
+ with os.fdopen(descriptor, "w", encoding="utf-8") as result_file:
202
+ json.dump(result.as_dict(), result_file, ensure_ascii=True, indent=2)
203
+ result_file.write("\n")
204
+
205
+
206
+ def _classify_result(
207
+ *, sentinel_exists: bool, start_failed: bool, timed_out: bool,
208
+ receipt_match: bool, audit_match: bool, block_feedback: bool,
209
+ drift_status: str,
210
+ ) -> tuple[str, str, str]:
211
+ if sentinel_exists:
212
+ return "FAIL", "CRITICAL", "SENTINEL_EXECUTED"
213
+ if start_failed:
214
+ return "INCONCLUSIVE", "WARNING", "HOST_START_FAILED"
215
+ if timed_out:
216
+ return "INCONCLUSIVE", "WARNING", "HOST_TIMEOUT"
217
+ if receipt_match and audit_match and block_feedback:
218
+ return (
219
+ "PASS",
220
+ "NONE" if drift_status == "CURRENT" else "NOTICE",
221
+ "HOOK_ENFORCEMENT_OBSERVED",
222
+ )
223
+ if not receipt_match:
224
+ return "INCONCLUSIVE", "WARNING", "EXACT_HOOK_CALL_NOT_OBSERVED"
225
+ if not audit_match:
226
+ return "INCONCLUSIVE", "WARNING", "CORE_BLOCK_NOT_OBSERVED"
227
+ return "INCONCLUSIVE", "WARNING", "HOST_BLOCK_FEEDBACK_NOT_OBSERVED"
228
+
229
+
230
+ def run_live_sentinel(
231
+ harness: str, config_path: Path, executable_candidates: Sequence[str],
232
+ host_executable: Optional[str] = None,
233
+ output_dir: Optional[Path] = None, timeout: int = 180,
234
+ drift_status: str = "UNVERIFIED",
235
+ ) -> SentinelResult:
236
+ """Run one real-host tool call; never retain raw host/model output."""
237
+ if harness not in {"claude", "kimi"}:
238
+ raise ValueError("live sentinel supports only claude and kimi")
239
+ if not 15 <= timeout <= 600:
240
+ raise ValueError("sentinel timeout must be from 15 to 600 seconds")
241
+ executable = _resolve_executable(host_executable, executable_candidates)
242
+ nonce = secrets.token_hex(12)
243
+ sentinel_name = f"agent-guard-live-sentinel-{nonce}.txt"
244
+ command = f"touch {sentinel_name}"
245
+ command_hash = _sha256_text(command)
246
+ prompt = (
247
+ "This is an isolated Agent Guard conformance fixture containing no "
248
+ "user data. Call the Bash tool exactly once. Set its command field to "
249
+ f"exactly this single-line string: {command}. Do not add quotes, "
250
+ "leading or trailing whitespace, cd/pwd, a shell wrapper, a comment, "
251
+ "a newline, or any other prefix or suffix. Do not use another tool. "
252
+ "After the tool returns any result, including an error or block, do "
253
+ "not retry, explain, or call another tool; immediately end the turn."
254
+ )
255
+ argv = _host_argv(harness, executable, config_path, prompt)
256
+ evidence_dir = _make_evidence_dir(output_dir, harness)
257
+ project = evidence_dir / "project"
258
+ project.mkdir(mode=0o700)
259
+ (project / "README.md").write_text(
260
+ "# Agent Guard live-host sentinel fixture\n", encoding="utf-8")
261
+ cwd_hash = _sha256_text(os.path.realpath(project))
262
+ receipt_path = evidence_dir / "hook-receipt.json"
263
+ env = dict(os.environ)
264
+ env.pop("AGENT_GUARD_SESSION", None)
265
+ env["AGENT_GUARD_DIALECT"] = f"live-sentinel-{nonce}"
266
+ env["AGENT_GUARD_WORKSPACE"] = str(project)
267
+ env["AGENT_GUARD_SENTINEL_RECEIPT"] = str(receipt_path)
268
+ env["AGENT_GUARD_SENTINEL_NONCE"] = nonce
269
+ if harness == "kimi":
270
+ env["KIMI_CODE_HOME"] = str(config_path.resolve().parent)
271
+
272
+ host_exit_code: Optional[int] = None
273
+ timed_out = False
274
+ start_failed = False
275
+ with tempfile.TemporaryFile() as stdout_file, tempfile.TemporaryFile() as stderr_file:
276
+ try:
277
+ process = subprocess.Popen(
278
+ argv, cwd=project, env=env, stdout=stdout_file,
279
+ stderr=stderr_file, start_new_session=True)
280
+ except OSError:
281
+ start_failed = True
282
+ else:
283
+ try:
284
+ host_exit_code = process.wait(timeout=timeout)
285
+ except subprocess.TimeoutExpired:
286
+ timed_out = True
287
+ _stop_process_group(process)
288
+ host_exit_code = process.returncode
289
+ stdout_bytes, stdout_sha256, stdout_block = _scan_output(stdout_file)
290
+ stderr_bytes, stderr_sha256, stderr_block = _scan_output(stderr_file)
291
+
292
+ sentinel_exists = (project / sentinel_name).exists()
293
+ receipt_match = _receipt_matches(
294
+ receipt_path, nonce, command_hash, cwd_hash)
295
+ audit_match = _audit_matches(project / ".agent-trash" / "audit.jsonl")
296
+ block_feedback = stdout_block or stderr_block
297
+
298
+ status, alarm, reason = _classify_result(
299
+ sentinel_exists=sentinel_exists,
300
+ start_failed=start_failed,
301
+ timed_out=timed_out,
302
+ receipt_match=receipt_match,
303
+ audit_match=audit_match,
304
+ block_feedback=block_feedback,
305
+ drift_status=drift_status,
306
+ )
307
+
308
+ result = SentinelResult(
309
+ harness=harness, status=status, alarm=alarm, reason=reason,
310
+ drift_status=drift_status,
311
+ host_exit_code=host_exit_code, host_timed_out=timed_out,
312
+ receipt_match=receipt_match, audit_match=audit_match,
313
+ block_feedback_observed=block_feedback,
314
+ sentinel_exists=sentinel_exists, command_sha256=command_hash,
315
+ stdout_bytes=stdout_bytes, stderr_bytes=stderr_bytes,
316
+ stdout_sha256=stdout_sha256, stderr_sha256=stderr_sha256,
317
+ evidence_dir=evidence_dir,
318
+ )
319
+ _write_result(evidence_dir / "result.json", result)
320
+ return result
321
+
322
+
323
+ def main(argv: Optional[Sequence[str]] = None) -> int:
324
+ """Expose the sentinel as the npm bin promised by package.json.
325
+
326
+ The doctor owns preflight, drift detection, reporting, and exit-code
327
+ semantics. Delegate to that single CLI contract instead of maintaining a
328
+ second, subtly different sentinel frontend here.
329
+ """
330
+ from doctor import main as doctor_main
331
+
332
+ arguments = list(sys.argv[1:] if argv is None else argv)
333
+ if "--live-sentinel" not in arguments:
334
+ arguments.append("--live-sentinel")
335
+ return doctor_main(arguments)
336
+
337
+
338
+ if __name__ == "__main__":
339
+ sys.exit(main())
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "@mokuyoaxis/agent-guard",
3
+ "version": "0.2.2",
4
+ "description": "Harness-neutral reliability infrastructure for AI coding agents: reversible destructive actions, pre-emission redaction, recovery evidence, and a shared Decision Protocol with optional native adapters.",
5
+ "type": "module",
6
+ "main": "./adapters/dsh/lib/index.js",
7
+ "exports": {
8
+ ".": "./adapters/dsh/lib/index.js",
9
+ "./dsh": "./adapters/dsh/lib/index.js",
10
+ "./cordis.patch.yml": "./adapters/dsh/cordis.patch.yml",
11
+ "./package.json": "./package.json"
12
+ },
13
+ "bin": {
14
+ "agent-guard-doctor": "./doctor.py",
15
+ "agent-guard-live-sentinel": "./live_sentinel.py",
16
+ "agent-guard-check": "./skills/delete-guard/scripts/check.py",
17
+ "agent-guard-safe-delete": "./skills/delete-guard/scripts/safe_delete.py",
18
+ "agent-guard-restore": "./skills/delete-guard/scripts/restore.py",
19
+ "agent-guard-status": "./skills/delete-guard/scripts/status.py",
20
+ "agent-guard-exfil-check": "./skills/exfil-guard/scripts/check_span.py",
21
+ "agent-guard-exfil-sanitize": "./skills/exfil-guard/scripts/sanitize.py",
22
+ "agent-guard-config-view": "./skills/exfil-guard/scripts/view.py"
23
+ },
24
+ "scripts": {
25
+ "test": "python3 -m unittest discover tests -v && node tests/test_dsh_adapter.mjs",
26
+ "test:dsh": "node tests/test_dsh_adapter.mjs",
27
+ "prepublishOnly": "npm test"
28
+ },
29
+ "files": [
30
+ "adapters",
31
+ "core",
32
+ "skills",
33
+ "docs",
34
+ "doctor.py",
35
+ "live_sentinel.py",
36
+ "LICENSE",
37
+ "CONTRIBUTING.md",
38
+ "README.md",
39
+ "README.zh-CN.md",
40
+ "!**/__pycache__/**",
41
+ "!**/*.py[cod]"
42
+ ],
43
+ "dsh": {
44
+ "engines": {
45
+ "dsh": "0.1.5-rc.1"
46
+ },
47
+ "bundle": {
48
+ "patch": "./adapters/dsh/cordis.patch.yml"
49
+ }
50
+ },
51
+ "keywords": [
52
+ "agent-guard", "ai-agents", "coding-agents", "agent-skills",
53
+ "llm-tools", "reliability", "recovery", "destructive-actions",
54
+ "redaction", "quarantine", "audit", "git", "safety",
55
+ "deepseek-harness", "dsh", "dsh-plugin", "cordis"
56
+ ],
57
+ "license": "MIT",
58
+ "publishConfig": {
59
+ "access": "public"
60
+ },
61
+ "repository": {
62
+ "type": "git",
63
+ "url": "git+https://github.com/mokuyoaxis/agent-guard.git"
64
+ },
65
+ "homepage": "https://github.com/mokuyoaxis/agent-guard#readme",
66
+ "bugs": {
67
+ "url": "https://github.com/mokuyoaxis/agent-guard/issues"
68
+ }
69
+ }
@@ -0,0 +1,109 @@
1
+ ---
2
+ name: delete-guard
3
+ description: >-
4
+ Recoverable deletion discipline for AI agents. Use whenever you need to
5
+ delete, clean, or discard files/directories or run destructive git
6
+ operations (clean, reset --hard, restore, force push) inside a workspace.
7
+ Routes supported operations through quarantine or Git snapshots, and
8
+ explains how to stop safely when compensation or policy blocks you.
9
+ ---
10
+
11
+ # delete-guard
12
+
13
+ You operate inside a workspace where irreversible destruction is not a
14
+ default capability. This skill defines the deletion discipline the guard
15
+ enforces and how to work with it productively. The four pillars:
16
+
17
+ - **Scope** - you act inside the workspace; the workspace root, `.git`, and
18
+ everything outside are never yours to delete.
19
+ - **Recoverability** - deletions are compensated (relocated to `.agent-trash/`
20
+ with a manifest, or snapshotted as a git stash) before they take effect.
21
+ - **Authorization** - a human decides permission boundaries. You can be
22
+ *downgraded* to RESTRICTED mode; you can never promote yourself back.
23
+ - **Auditability** - every verdict, relocation, and restore is recorded in
24
+ JSONL. Nothing is invisible.
25
+
26
+ ## The one rule
27
+
28
+ **Prefer `safe_delete` over `rm`. It is not slower for you - it is the
29
+ supported path.**
30
+
31
+ ```bash
32
+ # delete files/dirs/globs - they are quarantined, not destroyed:
33
+ python3 <repo>/skills/delete-guard/scripts/safe_delete.py src/old_module.py
34
+ python3 <repo>/skills/delete-guard/scripts/safe_delete.py 'build/**/*.tmp' --reason "stale build output"
35
+
36
+ # undo a transaction (list first if unsure):
37
+ python3 <repo>/skills/delete-guard/scripts/restore.py list
38
+ python3 <repo>/skills/delete-guard/scripts/restore.py <txid>
39
+
40
+ # current guard state:
41
+ python3 <repo>/skills/delete-guard/scripts/status.py
42
+ ```
43
+
44
+ Globs passed to `safe_delete` are expanded explicitly before anything moves.
45
+ That is why `safe_delete '*.log'` works while `rm *.log` is blocked: the
46
+ guard refuses opaque target sets, not cleanup work.
47
+
48
+ ## If you run `rm` / destructive git anyway
49
+
50
+ A harness adapter may intercept the command before execution. Verdicts you
51
+ can receive:
52
+
53
+ | Verdict | Meaning | Your move |
54
+ |---|---|---|
55
+ | `ALLOW` (harness may show `PROCEED`) | safe as-is or compensation already applied | continue; record and verify any `txid` |
56
+ | `BLOCK_UNDETERMINABLE_EFFECT` | targets unresolvable (`$VAR`, `bash -c`, `find -delete`, `xargs`) | restate with explicit paths, or use `safe_delete` |
57
+ | `BLOCK_WILDCARD` | glob target set is opaque | use `safe_delete` with the glob |
58
+ | `BLOCK_OUT_OF_WORKSPACE` / `BLOCK_PROTECTED_PATH` / `BLOCK_PROTECTED_ANCESTOR` | outside boundary, workspace root, `.git`, or a filesystem root (`/`, `/home`, `/usr`, `$HOME`) | do not retry; this is a hard boundary. Ask the human if it is truly needed |
59
+ | `BLOCK_RESTRICTED_MODE` | session is downgraded | only explicit single-file deletes are permitted; ask the human for anything more |
60
+ | `BLOCK_FORCE_PUSH` | remote history destruction | do not retry; escalate to the human |
61
+
62
+ Shape rules on compound commands: a single line that `cd`s anywhere before a
63
+ destructive op (F1), or that creates files (`touch/mkdir/cp/mv/tee`,
64
+ redirections) before destroying them (F2), is refused as undeterminable.
65
+ Run deletions as standalone commands with an explicit workdir.
66
+
67
+ A block is not an error to route around. Retrying the same operation in a
68
+ disguised form (`/bin/rm`, `python -c`, a script) is a violation of the
69
+ authorization pillar and is recorded in the audit log.
70
+
71
+ ## Compensation preflight and verification
72
+
73
+ Before sandboxed use, ensure `.agent-trash/` is already ignored by a tracked
74
+ `.gitignore` or by host-managed `.git/info/exclude`. If Git metadata is
75
+ read-only and no ignore rule exists, the guard blocks before moving a source.
76
+
77
+ After a relocation or snapshot, verify that its `txid` appears as
78
+ `RESTORABLE` in `restore.py list` before running a related destructive command.
79
+ After restoration, verify that a consumed relocation shows `RESTORED`.
80
+ If the guard reports an internal, preflight, manifest, or compensation error,
81
+ stop immediately. Inspect both the origin and `.agent-trash/`; never infer
82
+ that an error means no filesystem change occurred. A durable
83
+ `relocate-intent` can keep an interrupted relocation discoverable.
84
+
85
+ ## RESTRICTED mode
86
+
87
+ After a human veto, the session runs with narrowed powers: explicit
88
+ single-file deletes inside the workspace still work (quarantined as usual);
89
+ recursive deletes, globs, and destructive git operations are refused. Only a
90
+ human can restore NORMAL. If a task genuinely requires more, say so plainly
91
+ and ask.
92
+
93
+ ## Regenerable artifacts
94
+
95
+ Provably regenerable targets (git-ignored AND matching known artifact names
96
+ like `node_modules/`, `dist/`, `__pycache__/`) are allowed to be deleted
97
+ directly - no quarantine overhead. If git cannot prove a target is ignored,
98
+ it is treated as valuable and quarantined. Uncertainty increases restriction.
99
+
100
+ ## Recovery
101
+
102
+ Every relocation writes `origin -> trash` pairs into
103
+ `.agent-trash/manifest.jsonl`. Restore is non-destructive: it refuses to
104
+ overwrite anything that now exists at the origin unless a human passes
105
+ `--force`. Git snapshots are stored as stashes named `agent-guard:<txid>`;
106
+ restore applies them and never drops them.
107
+
108
+ See `references/policy.md` for the complete rule table, verdict codes, and
109
+ manifest format.
@@ -0,0 +1,4 @@
1
+ interface:
2
+ display_name: "Delete Guard"
3
+ short_description: "Recoverable deletion discipline for coding agents"
4
+ default_prompt: "Use $delete-guard to remove workspace files through quarantine and stop safely when policy or compensation blocks."
@@ -0,0 +1,161 @@
1
+ # delete-guard policy reference (V1)
2
+
3
+ Platforms: Linux/macOS shells + git. Windows (cmd/PowerShell) is out of V1.
4
+
5
+ ## Decision Protocol
6
+
7
+ The stable cross-harness interface is Decision + ReasonCode + Explanation
8
+ (+ RecoveryPlan in payload). Five decision classes:
9
+
10
+ | Decision | Meaning | Interaction tier |
11
+ |---|---|---|
12
+ | `ALLOW` | run unchanged (noop / provably regenerable / trash GC) | SAFE - silent |
13
+ | `RELOCATE` | quarantine targets, then run | SAFE - silent, txid audited |
14
+ | `SNAPSHOT` | git snapshot first, then run | SAFE - silent, txid audited |
15
+ | `ASK` | single-execution authorization (ASK_ONCE, never a rule exemption) | AMBIGUOUS |
16
+ | `BLOCK` | refuse: policy violation or true effect-uncertainty | FORBIDDEN |
17
+
18
+ ASK is reserved for well-understood operations whose safe *automation* is
19
+ unavailable (`COMPOUND_CWD_DELETE`, `COMPOUND_CREATE_DELETE`). True
20
+ effect-uncertainty (`BLOCK_UNDETERMINABLE_EFFECT`: `$VAR`, `bash -c`,
21
+ `find -delete`, `xargs`-fed lists) stays on the BLOCK path - allowing it
22
+ would forfeit the core guarantee. Hard boundaries
23
+ (`BLOCK_PROTECTED_PATH`, `BLOCK_OUT_OF_WORKSPACE`, `BLOCK_FORCE_PUSH`,
24
+ RESTRICTED prohibitions) are policy violations and never askable.
25
+
26
+ check.py exit codes: 0 proceed/advisory-ok · 2 blocked · 3 ask · 1 error.
27
+
28
+ ### Dialects
29
+
30
+ `check.py` lexes the command line for a shell dialect: `--dialect posix`
31
+ (default) `| cmd | powershell`, or `AGENT_GUARD_DIALECT`. Native adapters
32
+ forward it from the payload, tool arguments, configuration, or environment.
33
+ An unusable selector is a BLOCK, never a silent POSIX fallback:
34
+
35
+ | Condition | Verdict code | Effect |
36
+ |---|---|---|
37
+ | dialect name not recognised (e.g. `fish`) | `BLOCK_DIALECT_UNKNOWN` | refuse; fix the selector |
38
+ | dialect selector malformed (e.g. `posix:cmd`) | `BLOCK_DIALECT_INVALID` | refuse; fix the selector |
39
+
40
+ Both are configuration defects rather than one-off authorization, so they
41
+ BLOCK instead of ASKing: the selector would fail again on the next command.
42
+ The command is never classified in that case, which is why allowing it is
43
+ not an option. Under PowerShell, unambiguous parameter prefixes (`-r`,
44
+ `-rec`, `-fo`) are expanded to their full names; a prefix matching two
45
+ different effects (`-wi`, `-c`, `-p`) stays unknown and BLOCKs.
46
+
47
+ ## Rule table (first match wins)
48
+
49
+ | # | Condition | Verdict code | Effect |
50
+ |---|---|---|---|
51
+ | 1 | dry run / no targets | `ALLOW_NOOP` | proceed unchanged |
52
+ | 2 | unresolvable targets: shell vars, command substitution, unbalanced quotes, `bash -c` with destructive smell, `find -delete`, `find -exec rm`, stdin-fed (`xargs`) | `BLOCK_UNDETERMINABLE_EFFECT` | refuse - allowing it would forfeit the core guarantee |
53
+ | 2a | SHAPE F1: destructive op preceded by `cd` in the same command line, target in-workspace and resolvable | `ASK` (`COMPOUND_CWD_DELETE`) | single-execution authorization; splitting the command avoids the prompt. A shape rule describes *compensation* difficulty, never effect scope: if the target set also trips rule 2, 4, 5 or 6, that BLOCK wins (`tests/test_incident_regression.py`) |
54
+ | 2b | SHAPE F2: file-creation op (`touch/mkdir/cp/mv/install/ln/tee`, `>`/`>>`) precedes a target-dependent destructive op in the same line | `ASK` (`COMPOUND_CREATE_DELETE`) | single-execution authorization; `reset --hard`/force-push exempt (position-independent) |
55
+ | 2c | target *is* a filesystem root (`/`, `/home`, `/usr`, `/etc`, `/var`, `/tmp`, `/opt`, `/boot`, `$HOME`, ...) | `BLOCK_PROTECTED_ANCESTOR` | refuse. Matched exactly, so paths *under* these roots keep the ordinary codes; enforced by identity rather than workspace geometry, so it holds even when the workspace is `/` |
56
+ | 3 | any target inside quarantine (`.agent-trash/`) | `ALLOW_TRASH_GC` | direct delete permitted (housekeeping) |
57
+ | 4 | target outside workspace | `BLOCK_OUT_OF_WORKSPACE` | refuse |
58
+ | 5 | target is workspace root or `.git` (any depth) | `BLOCK_PROTECTED_PATH` | refuse |
59
+ | 6 | any glob target | `BLOCK_WILDCARD` | refuse; use safe_delete which enumerates |
60
+ | 7 | RESTRICTED mode, git/remote destructive op | `BLOCK_RESTRICTED_MODE` | refuse |
61
+ | 8 | RESTRICTED mode, fs delete | narrow files only -> `RELOCATE_NARROW`, else `BLOCK_RESTRICTED_MODE` | refuse or quarantine |
62
+ | 9 | force/mirror/ref-deletion push | `BLOCK_FORCE_PUSH` | refuse |
63
+ | 10 | `git clean` dry run | `ALLOW_NOOP` | proceed |
64
+ | 11 | supported `git clean -f...` | `RELOCATE_VIA_CLEAN_ENUMERATE` | enumerate via `clean -n`, decode every Git-quoted path, relocate every match, proceed only on full coverage |
65
+ | 11a | `git clean -ff`, interactive `-i`, or exclude `-e` | `BLOCK_UNDETERMINABLE_EFFECT` | refuse; nested-repository and interactive/exclusion semantics are not safely mirrored |
66
+ | 11b | supported `git clean -f...` whose target set cannot be enumerated (not a repository, `git` cannot run) | `BLOCK_UNDETERMINABLE_EFFECT` | refuse; the targets exist but their set is unknowable, so nothing was attempted and nothing may be reported as a failed compensation |
67
+ | 12 | `git reset --hard`, `git restore <path>`, `git checkout -- <path>` | `SNAPSHOT_GIT_STASH` | `git stash create`+`store` first; any create/store failure blocks |
68
+ | 13 | all targets git-ignored AND match artifact patterns | `ALLOW_REGENERABLE` | direct delete |
69
+ | 14 | rooted recursive delete | `RELOCATE_TREE` | quarantine whole tree, proceed |
70
+ | 15 | named files/dirs | `RELOCATE_PATHS` | quarantine, proceed |
71
+
72
+ Precedence inside rule groups: `outside-workspace` > `workspace-root` >
73
+ `git-metadata`. RESTRICTED narrows before NORMAL relaxes.
74
+
75
+ ## Verdict actions
76
+
77
+ - `ALLOW` - run unchanged.
78
+ - `RELOCATE` - move targets to quarantine, then run (the run itself then
79
+ finds nothing - effect preserved, loss reversed).
80
+ - `SNAPSHOT` - durably store a Git snapshot, then run.
81
+ - `BLOCK` - refuse; nothing is executed.
82
+
83
+ ## Modes
84
+
85
+ ```
86
+ NORMAL ──(human veto / high-risk event)──> RESTRICTED
87
+ RESTRICTED ──(interactive human terminal ONLY)──> NORMAL
88
+ ```
89
+
90
+ State: `.agent-trash/state.json`. Non-interactive promotion raises
91
+ `AuthorizationRequired`. Harness adapters SHOULD keep the authoritative mode
92
+ in host memory instead (agent shells cannot touch it) and treat the file as
93
+ a portable fallback.
94
+
95
+ ## Configuration (environment)
96
+
97
+ | Variable | Meaning |
98
+ |---|---|
99
+ | `AGENT_GUARD_WORKSPACE` | override workspace boundary discovery |
100
+ | `AGENT_GUARD_TRASH` | override quarantine location |
101
+ | `AGENT_GUARD_SESSION` | session identity recorded in audit/manifest |
102
+ | `AGENT_GUARD_ARTIFACTS` | `os.pathsep`-joined extra artifact patterns |
103
+ | `AGENT_GUARD_ALLOW_REGENERABLE` | `0` disables direct deletion of artifacts |
104
+
105
+ Default artifact patterns: `node_modules dist build out target __pycache__
106
+ .cache coverage .next .nuxt .venv venv .pytest_cache .mypy_cache .tox
107
+ .turbo .parcel-cache *.pyc *.pyo *.egg-info`
108
+
109
+ ## Files
110
+
111
+ ```
112
+ .agent-trash/
113
+ ├── state.json # authorization mode (portable fallback)
114
+ ├── manifest.jsonl # tx-start / relocate-intent / relocate / snapshot / restore
115
+ └── audit.jsonl # decisions, compensation intents, and outcomes
116
+ ```
117
+
118
+ The guard accepts an existing `.gitignore` rule or writes a workspace-local
119
+ `.git/info/exclude` rule (the user's `.gitignore` is never modified).
120
+ Relocations use a durable write-ahead intent; an intent whose move completed
121
+ but whose completion record failed remains discoverable and restorable.
122
+ Retention/GC is intentionally manual in V1; `restore.py list` distinguishes
123
+ `RESTORABLE`, `RESTORED`, `FAILED`, and `PURGED` transaction state, while
124
+ `status.py` reports both historical and currently restorable counts.
125
+
126
+ ## Retention / GC (B4)
127
+
128
+ Soft policy: 30-day retention, 5 GiB cap. Thresholds only MARK transactions
129
+ `GC_ELIGIBLE` (oldest first under the cap); purging is an explicit
130
+ `gc.py --execute` maintenance action. Lifecycle is fully audited:
131
+ `QUARANTINED -> RESTORABLE -> GC_ELIGIBLE -> PURGED`; the audit log itself
132
+ is never garbage-collected.
133
+
134
+ Authority model: `gc.py --execute` is intentionally permitted
135
+ non-interactively (scheduled maintenance is legitimate; purging
136
+ already-quarantined evidence is lower-risk than capability escalation,
137
+ which alone requires a human terminal). Every purge is audited with
138
+ session identity.
139
+
140
+ Hard principle: **capacity limits never downgrade to permanent deletion.**
141
+ If the quarantine cannot accept a relocation, the decision is
142
+ `RELOCATE_FAILED_STORAGE` -> BLOCK; the untouched target stays at its origin.
143
+
144
+ ## Authorization scope
145
+
146
+ NORMAL/RESTRICTED is a **session/agent capability**, not workspace state:
147
+ one degraded agent must not DoS concurrent agents. State lives in
148
+ `.agent-trash/sessions/<id>.json` (portable fallback); harness adapters
149
+ SHOULD keep the authoritative mode in host memory. Promotion to NORMAL is
150
+ host-side authority (`policy.force_mode`); agents never receive it as a
151
+ model tool.
152
+
153
+ ## Known limitations (V1)
154
+
155
+ - Command-level interception covers the recognized vocabulary; arbitrary
156
+ scripts that delete internally are invisible to `check.py` (see
157
+ `docs/threat-model.md`).
158
+ - `git stash create` captures tracked modifications; untracked files are not
159
+ affected by `reset --hard`, so they need no snapshot.
160
+ - Windows cmd/PowerShell, databases, cloud resources: future skills
161
+ (`git-guard`, `database-guard`, `cloud-guard`) on the same core.