@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.
- package/CONTRIBUTING.md +101 -0
- package/LICENSE +21 -0
- package/README.md +558 -0
- package/README.zh-CN.md +488 -0
- package/adapters/INTEGRATION.md +94 -0
- package/adapters/claude/README.md +141 -0
- package/adapters/claude/compatibility.json +17 -0
- package/adapters/claude/harness/README.md +59 -0
- package/adapters/claude/harness/mock_anthropic_api.mjs +47 -0
- package/adapters/claude/harness/run_scenario.sh +79 -0
- package/adapters/claude/harness/run_scenario_no_python3.sh +49 -0
- package/adapters/claude/hook_bridge.sh +33 -0
- package/adapters/claude/pre_tool_use.py +264 -0
- package/adapters/claude/settings.example.json +16 -0
- package/adapters/codex/harness/README.md +53 -0
- package/adapters/codex/harness/acceptance.py +226 -0
- package/adapters/dsh/README.md +62 -0
- package/adapters/dsh/cordis.patch.yml +30 -0
- package/adapters/dsh/lib/index.js +500 -0
- package/adapters/kimi-code/README.md +169 -0
- package/adapters/kimi-code/compatibility.json +17 -0
- package/adapters/kimi-code/config.example.toml +26 -0
- package/adapters/kimi-code/hook_bridge.sh +32 -0
- package/adapters/kimi-code/pre_tool_use.py +72 -0
- package/core/__init__.py +47 -0
- package/core/audit.py +86 -0
- package/core/classifier.py +1175 -0
- package/core/dialects.py +898 -0
- package/core/policy.py +817 -0
- package/core/recovery.py +700 -0
- package/core/redaction.py +1096 -0
- package/core/safe_view.py +212 -0
- package/docs/architecture.md +223 -0
- package/docs/compatibility.md +142 -0
- package/docs/development-note-unguarded-deletion.md +187 -0
- package/docs/friction.md +266 -0
- package/docs/harness-capabilities.md +72 -0
- package/docs/host-drift.md +142 -0
- package/docs/publishing-from-ephemeral-environments.md +104 -0
- package/docs/release-notes-0.2.0-rc1.md +46 -0
- package/docs/release-notes-0.2.0.md +72 -0
- package/docs/release-notes-0.2.1.md +78 -0
- package/docs/release-notes-0.2.2.md +120 -0
- package/docs/secret-guard-analysis.md +416 -0
- package/docs/secret-guard-architecture.md +93 -0
- package/docs/secret-guard-design.md +649 -0
- package/docs/test-report-claude-code-harness.md +462 -0
- package/docs/test-report-codex-gpt-5.6-sol.md +335 -0
- package/docs/test-report-codex-gpt-6-astra-high.md +129 -0
- package/docs/test-report-dsh-0.1.5-rc.1.md +84 -0
- package/docs/test-report-dsh-v0.1.1.md +126 -0
- package/docs/test-report-kimi-code-block.md +198 -0
- package/docs/test-report-zcode-glm-flash.md +241 -0
- package/docs/threat-model.md +44 -0
- package/doctor.py +756 -0
- package/live_sentinel.py +339 -0
- package/package.json +69 -0
- package/skills/delete-guard/SKILL.md +109 -0
- package/skills/delete-guard/agents/openai.yaml +4 -0
- package/skills/delete-guard/references/policy.md +161 -0
- package/skills/delete-guard/scripts/_bootstrap.py +8 -0
- package/skills/delete-guard/scripts/check.py +370 -0
- package/skills/delete-guard/scripts/gc.py +103 -0
- package/skills/delete-guard/scripts/restore.py +98 -0
- package/skills/delete-guard/scripts/safe_delete.py +256 -0
- package/skills/delete-guard/scripts/status.py +130 -0
- package/skills/exfil-guard/SKILL.md +143 -0
- package/skills/exfil-guard/agents/openai.yaml +4 -0
- package/skills/exfil-guard/references/channels.md +58 -0
- package/skills/exfil-guard/references/rules.md +194 -0
- package/skills/exfil-guard/scripts/_bootstrap.py +8 -0
- package/skills/exfil-guard/scripts/check_span.py +250 -0
- package/skills/exfil-guard/scripts/sanitize.py +155 -0
- package/skills/exfil-guard/scripts/view.py +44 -0
- package/skills/recovery-audit/SKILL.md +283 -0
- package/skills/recovery-audit/agents/openai.yaml +4 -0
- package/skills/recovery-audit/references/evidence-records.md +85 -0
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""safe_delete - the recoverable deletion tool for AI agents.
|
|
3
|
+
|
|
4
|
+
safe_delete.py [--json] [--dry-run] [--reason TEXT] PATH...
|
|
5
|
+
|
|
6
|
+
Globs are expanded here, explicitly, before classification: an opaque
|
|
7
|
+
wildcard never reaches the filesystem unexamined. Every verdict is audited.
|
|
8
|
+
Blocked requests exit 2 and leave the filesystem untouched.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import glob as globlib
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import shutil
|
|
17
|
+
import sys
|
|
18
|
+
|
|
19
|
+
import _bootstrap # noqa: F401
|
|
20
|
+
|
|
21
|
+
from core import AUDIT_NAME, TRASH_DIRNAME, audit
|
|
22
|
+
from core import classifier, policy, recovery
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def expand_globs(patterns):
|
|
26
|
+
"""Expand globs explicitly. Returns (concrete_paths, unmatched_patterns).
|
|
27
|
+
|
|
28
|
+
A pattern with no matches is NOT passed on as an opaque wildcard - it is
|
|
29
|
+
reported as 'no matches' instead of triggering a misleading BLOCK.
|
|
30
|
+
"""
|
|
31
|
+
out = []
|
|
32
|
+
unmatched = []
|
|
33
|
+
for pattern in patterns:
|
|
34
|
+
matches = globlib.glob(os.path.expanduser(pattern), recursive=True)
|
|
35
|
+
if matches:
|
|
36
|
+
out.extend(sorted(matches))
|
|
37
|
+
elif any(c in pattern for c in ("*", "?", "[")):
|
|
38
|
+
unmatched.append(pattern)
|
|
39
|
+
else:
|
|
40
|
+
out.append(pattern) # literal path: let policy report the miss
|
|
41
|
+
return out, unmatched
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def delete_directly(spec):
|
|
45
|
+
"""Physically remove one concrete target (regenerable / trash GC only)."""
|
|
46
|
+
path = spec.resolved
|
|
47
|
+
if spec.is_symlink or spec.is_file:
|
|
48
|
+
os.unlink(path)
|
|
49
|
+
return "deleted"
|
|
50
|
+
if spec.is_dir:
|
|
51
|
+
shutil.rmtree(path)
|
|
52
|
+
return "deleted-tree"
|
|
53
|
+
return "absent"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def main() -> int:
|
|
57
|
+
ap = argparse.ArgumentParser(description=__doc__)
|
|
58
|
+
ap.add_argument("paths", nargs="+", help="paths or globs to delete")
|
|
59
|
+
ap.add_argument("--json", action="store_true", dest="as_json")
|
|
60
|
+
ap.add_argument("--dry-run", action="store_true")
|
|
61
|
+
ap.add_argument("--reason", default="", help="why this deletion is needed")
|
|
62
|
+
args = ap.parse_args()
|
|
63
|
+
|
|
64
|
+
base = os.getcwd()
|
|
65
|
+
workspace = classifier.discover_workspace(base)
|
|
66
|
+
trash_root = os.environ.get(
|
|
67
|
+
"AGENT_GUARD_TRASH", os.path.join(workspace, TRASH_DIRNAME))
|
|
68
|
+
mode = policy.load_mode(trash_root)["mode"]
|
|
69
|
+
ctx = policy.PolicyContext(
|
|
70
|
+
workspace=workspace, trash_root=trash_root, base_dir=base, mode=mode)
|
|
71
|
+
|
|
72
|
+
concrete, unmatched = expand_globs(args.paths)
|
|
73
|
+
specs = classifier.classify_paths(concrete, base, workspace, trash_root)
|
|
74
|
+
if not specs and unmatched:
|
|
75
|
+
result = {
|
|
76
|
+
"tool": "safe_delete",
|
|
77
|
+
"mode": mode,
|
|
78
|
+
"workspace": workspace,
|
|
79
|
+
"verdict": {"action": "ALLOW", "code": "ALLOW_NOOP",
|
|
80
|
+
"reasons": ["no matches for: " + ", ".join(unmatched)]},
|
|
81
|
+
"targets": list(args.paths),
|
|
82
|
+
"dry_run": args.dry_run,
|
|
83
|
+
"outcome": "nothing to do (no matches)",
|
|
84
|
+
"exit": 0,
|
|
85
|
+
}
|
|
86
|
+
print(json.dumps(result, ensure_ascii=False, indent=2) if args.as_json
|
|
87
|
+
else result["outcome"])
|
|
88
|
+
return 0
|
|
89
|
+
verdict = policy.decide_path_batch(specs, ctx, recursive=True)
|
|
90
|
+
engine = recovery.RecoveryEngine(workspace, trash_root)
|
|
91
|
+
|
|
92
|
+
result = {
|
|
93
|
+
"tool": "safe_delete",
|
|
94
|
+
"mode": mode,
|
|
95
|
+
"workspace": workspace,
|
|
96
|
+
"verdict": {"decision": verdict.decision, "code": verdict.code,
|
|
97
|
+
"explanation": verdict.explanation,
|
|
98
|
+
"reasons": verdict.reasons},
|
|
99
|
+
"targets": [s.raw for s in specs],
|
|
100
|
+
"no_match": unmatched,
|
|
101
|
+
"dry_run": args.dry_run,
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
def record(entry, required=False):
|
|
105
|
+
"""Append audit after safe layout setup.
|
|
106
|
+
|
|
107
|
+
Blocked requests retain their policy decision if audit storage is
|
|
108
|
+
unavailable. Mutation intents use `required=True` and fail closed.
|
|
109
|
+
"""
|
|
110
|
+
try:
|
|
111
|
+
engine.ensure_layout()
|
|
112
|
+
audit.append(entry, os.path.join(trash_root, AUDIT_NAME))
|
|
113
|
+
return True
|
|
114
|
+
except Exception as exc:
|
|
115
|
+
if required:
|
|
116
|
+
raise
|
|
117
|
+
result.setdefault("warnings", []).append(
|
|
118
|
+
f"audit unavailable: {exc}")
|
|
119
|
+
return False
|
|
120
|
+
|
|
121
|
+
if verdict.blocked:
|
|
122
|
+
record({"event": "decision", "tool": "safe_delete",
|
|
123
|
+
"decision": "BLOCK", "code": verdict.code,
|
|
124
|
+
"reasons": verdict.reasons, "targets": result["targets"],
|
|
125
|
+
"reason": args.reason})
|
|
126
|
+
result["exit"] = 2
|
|
127
|
+
print(json.dumps(result, ensure_ascii=False, indent=2) if args.as_json
|
|
128
|
+
else f"BLOCKED [{verdict.code}]: {verdict.reasons}")
|
|
129
|
+
return 2
|
|
130
|
+
|
|
131
|
+
# Preflight every real mutation before recording authorization or touching
|
|
132
|
+
# a target. In sandboxes where `.git` is read-only this either confirms an
|
|
133
|
+
# existing ignore rule or fails while all source paths are still intact.
|
|
134
|
+
if not args.dry_run and verdict.code != policy.CODE_ALLOW_NOOP:
|
|
135
|
+
try:
|
|
136
|
+
engine.ensure_layout()
|
|
137
|
+
except Exception as exc:
|
|
138
|
+
result["verdict"] = {
|
|
139
|
+
"decision": "BLOCK",
|
|
140
|
+
"code": policy.CODE_BLOCK_COMPENSATION_FAILED,
|
|
141
|
+
"explanation": policy.EXPLANATIONS[
|
|
142
|
+
policy.CODE_BLOCK_COMPENSATION_FAILED],
|
|
143
|
+
"reasons": [f"quarantine preflight failed: {exc}"],
|
|
144
|
+
}
|
|
145
|
+
result["outcome"] = "BLOCKED: quarantine preflight failed"
|
|
146
|
+
result["exit"] = 2
|
|
147
|
+
print(json.dumps(result, ensure_ascii=False, indent=2)
|
|
148
|
+
if args.as_json else result["outcome"])
|
|
149
|
+
return 2
|
|
150
|
+
|
|
151
|
+
# Authorization/intent must be durable before direct deletion. Dry-run
|
|
152
|
+
# assessments are best-effort audited but never fail for audit storage.
|
|
153
|
+
if args.dry_run:
|
|
154
|
+
record({"event": "decision", "tool": "safe_delete",
|
|
155
|
+
"decision": verdict.decision, "code": verdict.code,
|
|
156
|
+
"targets": result["targets"], "phase": "advisory",
|
|
157
|
+
"reason": args.reason})
|
|
158
|
+
elif verdict.code != policy.CODE_ALLOW_NOOP:
|
|
159
|
+
try:
|
|
160
|
+
record({"event": "decision", "tool": "safe_delete",
|
|
161
|
+
"decision": verdict.decision, "code": verdict.code,
|
|
162
|
+
"targets": result["targets"], "phase": "intent",
|
|
163
|
+
"reason": args.reason}, required=True)
|
|
164
|
+
except Exception as exc:
|
|
165
|
+
result["verdict"] = {
|
|
166
|
+
"decision": "BLOCK",
|
|
167
|
+
"code": policy.CODE_BLOCK_COMPENSATION_FAILED,
|
|
168
|
+
"explanation": policy.EXPLANATIONS[
|
|
169
|
+
policy.CODE_BLOCK_COMPENSATION_FAILED],
|
|
170
|
+
"reasons": [f"audit intent failed: {exc}"],
|
|
171
|
+
}
|
|
172
|
+
result["outcome"] = "BLOCKED: durable audit intent failed"
|
|
173
|
+
result["exit"] = 2
|
|
174
|
+
print(json.dumps(result, ensure_ascii=False, indent=2)
|
|
175
|
+
if args.as_json else result["outcome"])
|
|
176
|
+
return 2
|
|
177
|
+
|
|
178
|
+
if verdict.code == policy.CODE_ALLOW_NOOP:
|
|
179
|
+
result["outcome"] = "nothing to do"
|
|
180
|
+
elif args.dry_run:
|
|
181
|
+
result["outcome"] = f"would {verdict.decision.lower()} ({verdict.code})"
|
|
182
|
+
elif verdict.code == policy.CODE_ALLOW_REGENERABLE:
|
|
183
|
+
deleted = [delete_directly(s) for s in specs]
|
|
184
|
+
result["outcome"] = "deleted directly (provably regenerable)"
|
|
185
|
+
result["deleted"] = deleted
|
|
186
|
+
elif verdict.code == policy.CODE_ALLOW_TRASH_GC:
|
|
187
|
+
deleted = [delete_directly(s) for s in specs]
|
|
188
|
+
result["outcome"] = "deleted directly (quarantine housekeeping)"
|
|
189
|
+
result["deleted"] = deleted
|
|
190
|
+
else: # RELOCATE_*
|
|
191
|
+
report = engine.relocate(specs, meta={
|
|
192
|
+
"tool": "safe_delete", "code": verdict.code, "reason": args.reason})
|
|
193
|
+
if report.get("storage_failure"):
|
|
194
|
+
# Hard principle: capacity limits never downgrade to deletion.
|
|
195
|
+
result["verdict"] = {
|
|
196
|
+
"decision": "BLOCK",
|
|
197
|
+
"code": policy.CODE_BLOCK_RELOCATE_FAILED_STORAGE,
|
|
198
|
+
"reasons": ["quarantine storage unavailable; moved targets "
|
|
199
|
+
"(if any) stay restorable in quarantine"],
|
|
200
|
+
}
|
|
201
|
+
result["outcome"] = "BLOCKED: quarantine cannot accept relocation"
|
|
202
|
+
result["exit"] = 2
|
|
203
|
+
record({"event": "decision", "tool": "safe_delete",
|
|
204
|
+
"decision": "BLOCK",
|
|
205
|
+
"code": policy.CODE_BLOCK_RELOCATE_FAILED_STORAGE,
|
|
206
|
+
"targets": result["targets"], "reason": args.reason})
|
|
207
|
+
print(json.dumps(result, ensure_ascii=False, indent=2)
|
|
208
|
+
if args.as_json else result["outcome"])
|
|
209
|
+
return 2
|
|
210
|
+
if report.get("skipped"):
|
|
211
|
+
result["verdict"] = {
|
|
212
|
+
"decision": "BLOCK",
|
|
213
|
+
"code": policy.CODE_BLOCK_COMPENSATION_FAILED,
|
|
214
|
+
"explanation": policy.EXPLANATIONS[
|
|
215
|
+
policy.CODE_BLOCK_COMPENSATION_FAILED],
|
|
216
|
+
"reasons": ["relocation did not cover every target: " +
|
|
217
|
+
repr(report["skipped"][:3])],
|
|
218
|
+
}
|
|
219
|
+
result["outcome"] = (
|
|
220
|
+
"BLOCKED: partial relocation remains recoverable")
|
|
221
|
+
result["txid"] = report["txid"]
|
|
222
|
+
result["moved"] = report["moved"]
|
|
223
|
+
result["skipped"] = report["skipped"]
|
|
224
|
+
result["exit"] = 2
|
|
225
|
+
record({"event": "decision", "tool": "safe_delete",
|
|
226
|
+
"decision": "BLOCK",
|
|
227
|
+
"code": policy.CODE_BLOCK_COMPENSATION_FAILED,
|
|
228
|
+
"targets": result["targets"], "txid": report["txid"],
|
|
229
|
+
"reason": args.reason})
|
|
230
|
+
print(json.dumps(result, ensure_ascii=False, indent=2)
|
|
231
|
+
if args.as_json else result["outcome"])
|
|
232
|
+
return 2
|
|
233
|
+
result["outcome"] = "relocated to quarantine"
|
|
234
|
+
result["txid"] = report["txid"]
|
|
235
|
+
result["moved"] = report["moved"]
|
|
236
|
+
result["skipped"] = report["skipped"]
|
|
237
|
+
|
|
238
|
+
if not args.dry_run and verdict.code != policy.CODE_ALLOW_NOOP:
|
|
239
|
+
record({"event": "outcome", "tool": "safe_delete",
|
|
240
|
+
"targets": result["targets"], "txid": result.get("txid"),
|
|
241
|
+
"outcome": result.get("outcome"), "phase": "complete",
|
|
242
|
+
"reason": args.reason})
|
|
243
|
+
result["exit"] = 0
|
|
244
|
+
if args.as_json:
|
|
245
|
+
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
246
|
+
else:
|
|
247
|
+
print(result["outcome"] + (f" txid={result['txid']}" if result.get("txid") else ""))
|
|
248
|
+
return 0
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
if __name__ == "__main__":
|
|
252
|
+
try:
|
|
253
|
+
sys.exit(main())
|
|
254
|
+
except Exception as exc: # internal error: fail loudly, change nothing
|
|
255
|
+
print(f"agent-guard internal error: {exc}", file=sys.stderr)
|
|
256
|
+
sys.exit(1)
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""status - inspect guard state, quarantine usage, recent decisions.
|
|
3
|
+
|
|
4
|
+
status.py [--json] [--tail N]
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
|
|
14
|
+
import _bootstrap # noqa: F401
|
|
15
|
+
|
|
16
|
+
from core import AUDIT_NAME, TRASH_DIRNAME
|
|
17
|
+
from core import audit, classifier, policy, recovery
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def main() -> int:
|
|
21
|
+
ap = argparse.ArgumentParser(description=__doc__)
|
|
22
|
+
ap.add_argument("--json", action="store_true", dest="as_json")
|
|
23
|
+
ap.add_argument("--tail", type=int, default=10)
|
|
24
|
+
args = ap.parse_args()
|
|
25
|
+
|
|
26
|
+
base = os.getcwd()
|
|
27
|
+
workspace = classifier.discover_workspace(base)
|
|
28
|
+
trash_root = os.environ.get(
|
|
29
|
+
"AGENT_GUARD_TRASH", os.path.join(workspace, TRASH_DIRNAME))
|
|
30
|
+
engine = recovery.RecoveryEngine(workspace, trash_root)
|
|
31
|
+
state = policy.load_mode(trash_root)
|
|
32
|
+
usage = engine.usage()
|
|
33
|
+
|
|
34
|
+
stash_count = 0
|
|
35
|
+
try:
|
|
36
|
+
proc = subprocess.run(["git", "-C", workspace, "stash", "list"],
|
|
37
|
+
capture_output=True, text=True, timeout=10)
|
|
38
|
+
stash_count = sum(
|
|
39
|
+
1 for line in proc.stdout.splitlines() if "agent-guard:" in line)
|
|
40
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
41
|
+
pass
|
|
42
|
+
|
|
43
|
+
plan = engine.gc_plan()
|
|
44
|
+
info = {
|
|
45
|
+
"workspace": workspace,
|
|
46
|
+
"mode": state["mode"],
|
|
47
|
+
"mode_since": state["since"],
|
|
48
|
+
"mode_set_by": state["set_by"],
|
|
49
|
+
"trash_root": trash_root,
|
|
50
|
+
"usage": usage,
|
|
51
|
+
"retention": {
|
|
52
|
+
"soft_days": plan["retention_days"],
|
|
53
|
+
"soft_limit_bytes": plan["size_limit_bytes"],
|
|
54
|
+
"total_bytes": plan["total_bytes"],
|
|
55
|
+
"gc_eligible": [{"txid": e["txid"], "bytes": e["bytes"],
|
|
56
|
+
"reason": e["reason"]}
|
|
57
|
+
for e in plan["eligible"]],
|
|
58
|
+
},
|
|
59
|
+
"guard_snapshots": stash_count,
|
|
60
|
+
"decisions": decision_stats(engine.trash_root),
|
|
61
|
+
"recent_audit": audit_tail(engine.trash_root, args.tail),
|
|
62
|
+
}
|
|
63
|
+
if args.as_json:
|
|
64
|
+
print(json.dumps(info, ensure_ascii=False, indent=2))
|
|
65
|
+
return 0
|
|
66
|
+
|
|
67
|
+
print(f"workspace : {info['workspace']}")
|
|
68
|
+
print(f"mode : {info['mode']}"
|
|
69
|
+
+ (f" (since {state['since']} by {state['set_by']})" if state["since"] else ""))
|
|
70
|
+
print(f"quarantine: {trash_root}")
|
|
71
|
+
print(f"usage : {usage['files']} files, {usage['bytes']} bytes, "
|
|
72
|
+
f"{usage['transactions']} transactions "
|
|
73
|
+
f"({usage['restorable_transactions']} restorable)")
|
|
74
|
+
print(f"snapshots : {stash_count} agent-guard stashes")
|
|
75
|
+
ret = info["retention"]
|
|
76
|
+
print(f"retention : soft {ret['soft_days']}d / "
|
|
77
|
+
f"{ret['soft_limit_bytes'] // (1024**3)}GiB; "
|
|
78
|
+
f"{len(ret['gc_eligible'])} GC-eligible")
|
|
79
|
+
stats = info["decisions"]
|
|
80
|
+
if stats:
|
|
81
|
+
print(f"decisions : {top_codes(stats)}")
|
|
82
|
+
print("recent decisions:")
|
|
83
|
+
for record in info["recent_audit"]:
|
|
84
|
+
print(f" [{record.get('ts','')}] {record.get('action', record.get('event'))}"
|
|
85
|
+
f" {record.get('code','')} {record.get('targets', record.get('txid',''))}"
|
|
86
|
+
.rstrip())
|
|
87
|
+
return 0
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def audit_tail(trash_root, n):
|
|
91
|
+
# Historical append-only records can contain raw commands. Never copy
|
|
92
|
+
# their free-form fields into an agent-visible status result.
|
|
93
|
+
fields = ("ts", "event", "action", "decision", "code", "txid",
|
|
94
|
+
"check_id", "guard_latency_ms")
|
|
95
|
+
return [{key: record[key] for key in fields if key in record}
|
|
96
|
+
for record in audit.tail(os.path.join(trash_root, AUDIT_NAME), n)]
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
DECISION_EVENTS = {"check", "enforce-block", "enforce-proceed", "ask",
|
|
100
|
+
"decision"}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def decision_stats(trash_root):
|
|
104
|
+
"""Local-only aggregation of recorded decisions (nothing leaves the
|
|
105
|
+
machine). Counts reason codes across all decision-bearing events; ask
|
|
106
|
+
OUTCOMES are not visible to the guard and are therefore not claimed
|
|
107
|
+
here."""
|
|
108
|
+
import collections
|
|
109
|
+
counter = collections.Counter()
|
|
110
|
+
for record in audit.tail(os.path.join(trash_root, AUDIT_NAME), 5000):
|
|
111
|
+
if record.get("event") not in DECISION_EVENTS:
|
|
112
|
+
continue
|
|
113
|
+
code = record.get("code")
|
|
114
|
+
if code:
|
|
115
|
+
counter[code] += 1
|
|
116
|
+
elif record.get("event") == "enforce-proceed":
|
|
117
|
+
counter["PROCEED(compensated)"] += 1
|
|
118
|
+
return dict(counter)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def top_codes(stats, k=3):
|
|
122
|
+
return ", ".join(f"{c} x{n}" for c, n in
|
|
123
|
+
sorted(stats.items(), key=lambda kv: -kv[1])[:k])
|
|
124
|
+
|
|
125
|
+
if __name__ == "__main__":
|
|
126
|
+
try:
|
|
127
|
+
sys.exit(main())
|
|
128
|
+
except Exception as exc:
|
|
129
|
+
print(f"agent-guard internal error: {exc}", file=sys.stderr)
|
|
130
|
+
sys.exit(1)
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: exfil-guard
|
|
3
|
+
description: >-
|
|
4
|
+
Disclosure discipline for AI agents. Use before text leaves the machine:
|
|
5
|
+
writing files, sending model requests, posting forge comments, committing or
|
|
6
|
+
pushing, or when inspecting a JSON/dotenv config without exposing its values.
|
|
7
|
+
Scans payloads for credentials and host-identifying paths, and offers an
|
|
8
|
+
explicit read-only, value-free config view.
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
# exfil-guard
|
|
12
|
+
|
|
13
|
+
You operate where what leaves the machine cannot be recalled. This skill is
|
|
14
|
+
the egress side of the same promise `delete-guard` makes for destruction:
|
|
15
|
+
deletion asks "can we come back?", disclosure asks "was this supposed to
|
|
16
|
+
leave?". The four pillars, restated for egress:
|
|
17
|
+
|
|
18
|
+
- **Scope** - the egress boundary. The workspace is exempt; everything
|
|
19
|
+
outside it is a host identifier until proven otherwise.
|
|
20
|
+
- **Recoverability** - **weak, and do not pretend otherwise.** There is no
|
|
21
|
+
undo for a sent payload. The guard returns a *redaction plan* and an audit
|
|
22
|
+
record; it cannot un-send anything.
|
|
23
|
+
- **Authorization** - unchanged. `NORMAL`/`RESTRICTED` is reused; rule
|
|
24
|
+
configuration is host-side, so you cannot disable a rule.
|
|
25
|
+
- **Auditability** - every verdict is recorded as rule id, offsets and
|
|
26
|
+
length. **Never the matched bytes** - not even a hash, which would be
|
|
27
|
+
offline-crackable for a low-entropy secret.
|
|
28
|
+
|
|
29
|
+
## The one rule
|
|
30
|
+
|
|
31
|
+
**Never put a credential in an outbound payload, and never hand a raw host
|
|
32
|
+
path to anyone outside the workspace.**
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
# scan whatever you are about to emit:
|
|
36
|
+
python3 <repo>/skills/exfil-guard/scripts/check_span.py --channel file-write < draft.md
|
|
37
|
+
python3 <repo>/skills/exfil-guard/scripts/check_span.py --channel llm-request --json < prompt.txt
|
|
38
|
+
|
|
39
|
+
# apply the plan the guard returned:
|
|
40
|
+
python3 <repo>/skills/exfil-guard/scripts/sanitize.py --channel file-write < draft.md
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`check_span.py` reads the payload on **stdin** and is a pure function: it
|
|
44
|
+
never writes, never rewrites, and never prints the match. Exit codes are the
|
|
45
|
+
contract: `0` allow/sanitize, `2` block, `3` ask, `1` error.
|
|
46
|
+
|
|
47
|
+
## Safe config view
|
|
48
|
+
|
|
49
|
+
When you need to learn a JSON or dotenv config's shape, use the explicit
|
|
50
|
+
read-only view instead of printing the file:
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
python3 <repo>/skills/exfil-guard/scripts/view.py --workspace <workspace> .env
|
|
54
|
+
python3 <repo>/skills/exfil-guard/scripts/view.py --workspace <workspace> config.json
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
The argument is a workspace-relative path. The JSON result contains field
|
|
58
|
+
names, types, and `set`/`empty` states, **never scalar values**. Known
|
|
59
|
+
secret-shaped field names are hidden too; arbitrary field names are not a
|
|
60
|
+
proof of secrecy. The view accepts only small, valid UTF-8 JSON and a strict
|
|
61
|
+
single-line dotenv subset. It refuses symlinks, hardlinks, special files,
|
|
62
|
+
unsafe paths, and unsupported platforms instead of falling back to a raw
|
|
63
|
+
read. Exit `0` means a view was produced; `2` means refused; `1` is an
|
|
64
|
+
internal error. Do not write the value-free view back over the original
|
|
65
|
+
config: it is diagnostic output, not an editable copy. This CLI does not
|
|
66
|
+
intercept a harness's ordinary file-read tool.
|
|
67
|
+
|
|
68
|
+
## What you can receive
|
|
69
|
+
|
|
70
|
+
| Verdict | Meaning | Your move |
|
|
71
|
+
|---|---|---|
|
|
72
|
+
| `ALLOW` | nothing matched, a documented placeholder, or a workspace-relative path | proceed unchanged |
|
|
73
|
+
| `SANITIZE` | the guard produced a redaction plan (`SANITIZE_SECRET_REDACT` / `SANITIZE_PATH_REWRITE`) | apply the plan, then emit. Do not emit the original payload |
|
|
74
|
+
| `ASK` (`ASK_SECRET_EMISSION` / `ASK_PATH_EMISSION`) | the channel cannot be rewritten and cannot be taken back (a terminal transcript cannot be un-printed) | stop and ask a human; do not silently proceed |
|
|
75
|
+
| `BLOCK` (`BLOCK_SECRET_EMISSION` / `BLOCK_PATH_EMISSION`) | the channel is immutable or remote history (commit message, push payload) | **do not retry.** Remove the value and redo the message/commit |
|
|
76
|
+
| `BLOCK_SECRET_SOURCE_DUMP` | the payload reads a whole secret store (`cat .env`, `printenv`) whose content the guard never saw | stop; emit an explicit, reviewed value instead |
|
|
77
|
+
| `BLOCK_OUTPUT_UNSCANNABLE` | the payload was never scanned (too large, non-ASCII, unknown channel, scanner error) | an unscanned egress is not a clean egress. Do not route around it |
|
|
78
|
+
|
|
79
|
+
A `BLOCK` is not an obstacle to work around. Re-encoding a payload, splitting
|
|
80
|
+
a secret across lines, or piping through a tool the guard does not scan is a
|
|
81
|
+
violation of the authorization pillar and is recorded in the audit log.
|
|
82
|
+
|
|
83
|
+
## Applying a redaction plan
|
|
84
|
+
|
|
85
|
+
The guard deliberately does not rewrite your payload - you hold it. Apply
|
|
86
|
+
the plan back to front so offsets stay valid, or let `sanitize.py` do it.
|
|
87
|
+
Redaction **preserves format**: `sk-proj-Ab…` becomes `sk-proj-<REDACTED>`
|
|
88
|
+
(so a reviewer can still see *which kind* of credential leaked), and a host
|
|
89
|
+
path becomes `<PATH>`.
|
|
90
|
+
|
|
91
|
+
If you decline to apply a plan on a rewritable channel, the API contract is
|
|
92
|
+
"you were told": the audit records `sanitize-declined`. That is a choice
|
|
93
|
+
with a record, not a default.
|
|
94
|
+
|
|
95
|
+
## Value-free detection (why `echo "$TOKEN"` is caught)
|
|
96
|
+
|
|
97
|
+
The guard detects a secret *reference* without ever reading the secret. It
|
|
98
|
+
classifies a variable's **name** (`*KEY*`, `*TOKEN*`, `*SECRET*`,
|
|
99
|
+
`*PASSWORD*`, `*CRED*`, `*AUTH*`) and a secret-store **file name**
|
|
100
|
+
(`.env`, `*.pem`, `id_rsa*`, `.netrc`, `kubeconfig`, …), never a value.
|
|
101
|
+
This keeps this scanner from creating a second value copy; it does not
|
|
102
|
+
certify unrelated CLI output or existing audit records as secret-free.
|
|
103
|
+
|
|
104
|
+
Consequence you will notice: if `$OPENAI_API_KEY` actually holds `"test"`,
|
|
105
|
+
the guard still ASKs. That is intentional. The cost of a false ASK is one
|
|
106
|
+
keystroke; the cost of a false ALLOW is permanent. Do not attempt to
|
|
107
|
+
"resolve" the variable to reduce prompts.
|
|
108
|
+
|
|
109
|
+
## Path rules
|
|
110
|
+
|
|
111
|
+
A path is only a host identifier if it is **outside the workspace**:
|
|
112
|
+
`./src/main.py` says nothing about the machine, while
|
|
113
|
+
`/home/alice/work/agent-guard/src/main.py` does. System prefixes
|
|
114
|
+
(`/usr`, `/etc`, `C:\Windows`, …) are not host-identifying and are allowed.
|
|
115
|
+
Host paths are low severity by default - a bare absolute path with no host
|
|
116
|
+
correlation asks, it does not block.
|
|
117
|
+
|
|
118
|
+
## What this skill does NOT cover
|
|
119
|
+
|
|
120
|
+
State this plainly; it is the difference between a reliability tool and a
|
|
121
|
+
false security claim:
|
|
122
|
+
|
|
123
|
+
- **Adversarial exfiltration.** An agent that obfuscates a secret to evade
|
|
124
|
+
the scanner is out of scope. This catches *accidents*.
|
|
125
|
+
- **Channels with no hook.** A hosted model call with no proxy, the model's
|
|
126
|
+
own tool calls, content produced *inside* a program, and the human
|
|
127
|
+
clipboard are unreachable by construction.
|
|
128
|
+
- **At-rest secrecy.** The explicit safe view does not encrypt files or
|
|
129
|
+
prevent other tools from reading them. The text scanner is not a
|
|
130
|
+
repository-wide file scanner or a gitleaks replacement.
|
|
131
|
+
- **Rewriting history.** Detecting a secret already in git history is a
|
|
132
|
+
report at most; rewriting it is a human action with its own risks.
|
|
133
|
+
|
|
134
|
+
## Exemptions
|
|
135
|
+
|
|
136
|
+
`.agent-guard/exfil-allow.toml` at the workspace root declares reviewed false
|
|
137
|
+
positives (path globs, and literal values **by sha256 hash only**). It is a
|
|
138
|
+
host-side file: read from the workspace root, not settable per call. If a
|
|
139
|
+
scan hits something you believe is benign, report it - do not weaken the
|
|
140
|
+
rule, and do not route around the guard.
|
|
141
|
+
|
|
142
|
+
See `references/rules.md` for the frozen rule table, the exemption format and
|
|
143
|
+
the audit record shape; `references/channels.md` for the egress taxonomy.
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
interface:
|
|
2
|
+
display_name: "Exfil Guard"
|
|
3
|
+
short_description: "Disclosure discipline: no secrets or host paths in outbound payloads"
|
|
4
|
+
default_prompt: "Use $exfil-guard before any payload leaves the machine: scan it with check_span.py, apply the returned redaction plan, and stop when a channel blocks."
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# exfil-guard egress channel taxonomy (design 4.1)
|
|
2
|
+
|
|
3
|
+
A channel is defined by exactly **two** facts, and the decision table keys
|
|
4
|
+
off both. `rewritable` is what makes `SANITIZE` meaningful (the guard can
|
|
5
|
+
hand back a plan); `persistence` is what justifies `BLOCK` (the emission
|
|
6
|
+
cannot be taken back).
|
|
7
|
+
|
|
8
|
+
| Channel | `rewritable` | `persistence` | Reached via | Default |
|
|
9
|
+
|---|---|---|---|---|
|
|
10
|
+
| `llm-request` | yes (proxy/hook) | remote (third party) | pre-request hook | SANITIZE |
|
|
11
|
+
| `file-write` | yes | workspace | pre-write hook / tool arg | SANITIZE |
|
|
12
|
+
| `forge-comment` | yes (before send) | public | pre-request hook | SANITIZE |
|
|
13
|
+
| `issue-body` | yes | public | pre-request hook | SANITIZE |
|
|
14
|
+
| `pr-description` | yes | public | pre-request hook | SANITIZE |
|
|
15
|
+
| `git-commit-message` | yes (rewrite argv) | remote history | pre-command hook | **BLOCK** |
|
|
16
|
+
| `git-push-payload` | no | **remote** | pre-command hook | **BLOCK** |
|
|
17
|
+
| `shell-stdout` | **no** | local transcript/log | pre-command hook | ASK |
|
|
18
|
+
| `shell-file-redirect` | yes (file not yet written) | local | pre-command hook | ASK |
|
|
19
|
+
| `archive-upload` | yes | remote | pre-command hook | ASK |
|
|
20
|
+
| `process-argv` | yes | local (ps/logs) | pre-command hook | ASK |
|
|
21
|
+
|
|
22
|
+
Rules the table encodes:
|
|
23
|
+
|
|
24
|
+
1. **`BLOCK` outranks `rewritable`.** A commit message is technically
|
|
25
|
+
rewritable (rewrite the argv), but it lands in immutable history. Design
|
|
26
|
+
4.4 chooses refuse-and-explain over silent rewrite, because the emission
|
|
27
|
+
cannot be undone.
|
|
28
|
+
2. **A channel that is neither rewritable nor persistent can only ASK.** It
|
|
29
|
+
cannot un-print. `BLOCK` here would refuse `echo` on a variable a human
|
|
30
|
+
has every right to print.
|
|
31
|
+
3. **An unknown channel name is a configuration defect, not "no risk".**
|
|
32
|
+
`check_span.py` returns `BLOCK_OUTPUT_UNSCANNABLE`, never an implicit
|
|
33
|
+
ALLOW.
|
|
34
|
+
|
|
35
|
+
## Unreachable channels (never implied to be covered)
|
|
36
|
+
|
|
37
|
+
`hosted-llm-no-proxy`, `agent-tool-call`, `program-internal-output`,
|
|
38
|
+
`human-clipboard`. These are **not** in the table above on purpose. Naming
|
|
39
|
+
them here is the opposite of a claim: it is the coverage gap, stated so no
|
|
40
|
+
reader infers coverage the guard does not have.
|
|
41
|
+
|
|
42
|
+
Per `docs/threat-model.md`, the guard "may not claim" prevention of
|
|
43
|
+
adversarial exfiltration, and per design 4.4 an unreachable channel gets
|
|
44
|
+
**no verdict at all**.
|
|
45
|
+
|
|
46
|
+
## Adapter mapping (design 4.5)
|
|
47
|
+
|
|
48
|
+
| Core decision | Claude Code (`PreToolUse`) | DSH (`PreToolDecision`) | No-hook harness |
|
|
49
|
+
|---|---|---|---|
|
|
50
|
+
| ALLOW | exit 0 | run | run |
|
|
51
|
+
| SANITIZE | rewrite the tool arg, `permissionDecision: allow` + reason naming the rule (**never the value**) | rewrite the arg | **degrade to ASK/deny**, never silently proceed |
|
|
52
|
+
| ASK | `permissionDecision: ask` | native ask → deny | deny + explanation |
|
|
53
|
+
| BLOCK | exit 2, stderr to the model | deny + explanation | deny + explanation |
|
|
54
|
+
|
|
55
|
+
The last column is the honest degradation rule: a harness that cannot
|
|
56
|
+
rewrite must not be told it can. `SANITIZE` is not an adapter-mapped
|
|
57
|
+
decision the way `RELOCATE`/`SNAPSHOT` are - it applies to a *payload*, not
|
|
58
|
+
a command, and the caller holding the payload is the one that applies it.
|