@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,264 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Claude Code PreToolUse hook - agent-guard adapter (Decision Protocol).
|
|
3
|
+
|
|
4
|
+
Reads the hook payload from stdin, runs the shared core (check.py), and
|
|
5
|
+
maps decisions onto Claude Code's native hook semantics:
|
|
6
|
+
|
|
7
|
+
ALLOW, no compensations -> exit 0, silent
|
|
8
|
+
ALLOW, compensations applied -> exit 0 + permissionDecision "allow"
|
|
9
|
+
(reason surfaces what was quarantined)
|
|
10
|
+
ASK -> exit 0 + permissionDecision "ask"
|
|
11
|
+
(ASK_ONCE: reason shown to the user)
|
|
12
|
+
BLOCK -> exit 2; stderr is fed back to Claude so
|
|
13
|
+
the model can self-correct
|
|
14
|
+
guard failure -> exit 2 (fail-closed)
|
|
15
|
+
|
|
16
|
+
Install - project .claude/settings.json:
|
|
17
|
+
|
|
18
|
+
{
|
|
19
|
+
"hooks": {
|
|
20
|
+
"PreToolUse": [
|
|
21
|
+
{
|
|
22
|
+
"matcher": "Bash",
|
|
23
|
+
"hooks": [
|
|
24
|
+
{
|
|
25
|
+
"type": "command",
|
|
26
|
+
"command": "/bin/sh /path/to/agent-guard/adapters/claude/hook_bridge.sh /absolute/path/to/python3"
|
|
27
|
+
}
|
|
28
|
+
]
|
|
29
|
+
}
|
|
30
|
+
]
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
The shell bridge is for POSIX hosts. On Windows, use an absolute `python`
|
|
35
|
+
path (there is no `python3` alias in a stock install); this direct form does
|
|
36
|
+
not protect against interpreter startup failure. The adapter itself
|
|
37
|
+
spawns the guard with `sys.executable`, so the interpreter that runs the
|
|
38
|
+
hook is the interpreter that runs the guard.
|
|
39
|
+
|
|
40
|
+
Also copy skills/delete-guard into the project (or reference it) so the
|
|
41
|
+
model learns the discipline. Set AGENT_GUARD_DEBUG=1 to print the raw core
|
|
42
|
+
verdict JSON to stderr (used by conformance tests).
|
|
43
|
+
"""
|
|
44
|
+
from __future__ import annotations
|
|
45
|
+
|
|
46
|
+
import hashlib
|
|
47
|
+
import json
|
|
48
|
+
import os
|
|
49
|
+
import subprocess
|
|
50
|
+
import sys
|
|
51
|
+
|
|
52
|
+
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
53
|
+
_REPO_ROOT = os.path.dirname(os.path.dirname(_HERE))
|
|
54
|
+
if _REPO_ROOT not in sys.path:
|
|
55
|
+
sys.path.insert(0, _REPO_ROOT)
|
|
56
|
+
|
|
57
|
+
from core.classifier import ( # noqa: E402
|
|
58
|
+
DESTRUCTIVE_PREFILTER_RE, DESTRUCTIVE_PREFILTER_RE_WINDOWS)
|
|
59
|
+
from core.dialects import DIALECT_POSIX, resolve_dialect # noqa: E402
|
|
60
|
+
|
|
61
|
+
# Payload keys checked (in order) for a dialect selector. Claude Code does
|
|
62
|
+
# not define a dialect field today, so this is an extension point: a host
|
|
63
|
+
# that grows one takes effect without an adapter change.
|
|
64
|
+
_DIALECT_PAYLOAD_KEYS = ("dialect", "shell_dialect", "shellDialect")
|
|
65
|
+
|
|
66
|
+
CHECK = os.path.join(_REPO_ROOT, "skills", "delete-guard",
|
|
67
|
+
"scripts", "check.py")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def emit(payload: dict) -> None:
|
|
71
|
+
print(json.dumps(payload))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def allow_reason(code: str, compensations: list) -> str:
|
|
75
|
+
return (f"[agent-guard] {code}: compensated automatically "
|
|
76
|
+
f"({len(compensations)} relocation(s)); restorable via txid")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _write_sentinel_receipt(payload: dict, command: str) -> None:
|
|
80
|
+
"""Record an opt-in live-probe observation without retaining command text.
|
|
81
|
+
|
|
82
|
+
The doctor supplies both variables only for an explicit live sentinel.
|
|
83
|
+
Receipt failure must not change the policy decision, and O_EXCL prevents
|
|
84
|
+
an adapter call from overwriting any existing file.
|
|
85
|
+
"""
|
|
86
|
+
path = os.environ.get("AGENT_GUARD_SENTINEL_RECEIPT")
|
|
87
|
+
nonce = os.environ.get("AGENT_GUARD_SENTINEL_NONCE")
|
|
88
|
+
if (not path or not nonce or len(nonce) > 64
|
|
89
|
+
or not all(char.isalnum() or char in "-_" for char in nonce)):
|
|
90
|
+
return
|
|
91
|
+
cwd = payload.get("cwd")
|
|
92
|
+
if not isinstance(cwd, str) or not cwd:
|
|
93
|
+
return
|
|
94
|
+
receipt = {
|
|
95
|
+
"schema_version": 1,
|
|
96
|
+
"nonce": nonce,
|
|
97
|
+
"hook_event_name": payload.get("hook_event_name"),
|
|
98
|
+
"tool_name": payload.get("tool_name"),
|
|
99
|
+
"command_sha256": hashlib.sha256(command.encode("utf-8")).hexdigest(),
|
|
100
|
+
"cwd_sha256": hashlib.sha256(
|
|
101
|
+
os.path.realpath(cwd).encode("utf-8")).hexdigest(),
|
|
102
|
+
}
|
|
103
|
+
try:
|
|
104
|
+
descriptor = os.open(
|
|
105
|
+
path, os.O_WRONLY | os.O_CREAT | os.O_EXCL
|
|
106
|
+
| getattr(os, "O_CLOEXEC", 0), 0o600)
|
|
107
|
+
with os.fdopen(descriptor, "w", encoding="utf-8") as receipt_file:
|
|
108
|
+
json.dump(receipt, receipt_file, ensure_ascii=True, separators=(",", ":"))
|
|
109
|
+
receipt_file.write("\n")
|
|
110
|
+
except (OSError, TypeError, ValueError):
|
|
111
|
+
return
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def main(ask_is_block: bool = False, strict_payload: bool = True) -> int:
|
|
115
|
+
# Both native Bash hook entrypoints reject malformed event envelopes.
|
|
116
|
+
# A valid non-Bash payload remains out of this adapter's scope.
|
|
117
|
+
def malformed_payload() -> int:
|
|
118
|
+
sys.stderr.write("[agent-guard] malformed hook payload (fail-closed)\n")
|
|
119
|
+
return 2
|
|
120
|
+
|
|
121
|
+
raw = sys.stdin.read()
|
|
122
|
+
try:
|
|
123
|
+
payload = json.loads(raw)
|
|
124
|
+
except json.JSONDecodeError:
|
|
125
|
+
if strict_payload:
|
|
126
|
+
return malformed_payload()
|
|
127
|
+
return 0
|
|
128
|
+
if strict_payload:
|
|
129
|
+
if not isinstance(payload, dict):
|
|
130
|
+
return malformed_payload()
|
|
131
|
+
if payload.get("hook_event_name") != "PreToolUse":
|
|
132
|
+
return malformed_payload()
|
|
133
|
+
if (not isinstance(payload.get("tool_name"), str)
|
|
134
|
+
or not payload["tool_name"]):
|
|
135
|
+
return malformed_payload()
|
|
136
|
+
if str(payload.get("tool_name", "")).lower() != "bash":
|
|
137
|
+
return 0
|
|
138
|
+
if strict_payload:
|
|
139
|
+
if not isinstance(payload.get("tool_input"), dict):
|
|
140
|
+
return malformed_payload()
|
|
141
|
+
if (not isinstance(payload.get("cwd"), str)
|
|
142
|
+
or not payload["cwd"].strip()):
|
|
143
|
+
return malformed_payload()
|
|
144
|
+
tool_input = payload.get("tool_input") or {}
|
|
145
|
+
command = tool_input.get("command")
|
|
146
|
+
if not isinstance(command, str) or not command:
|
|
147
|
+
if strict_payload:
|
|
148
|
+
return malformed_payload()
|
|
149
|
+
return 0
|
|
150
|
+
_write_sentinel_receipt(payload, command)
|
|
151
|
+
# Dialect resolution must happen BEFORE the prefilter: the POSIX regex
|
|
152
|
+
# cannot see `ri build -r -fo`, so a Windows-native payload would be
|
|
153
|
+
# skipped as harmless. Precedence: payload -> AGENT_GUARD_DIALECT ->
|
|
154
|
+
# posix (the documented default). An unusable selector is NOT swallowed
|
|
155
|
+
# here; it is handed to check.py, which BLOCKs with an explicit code.
|
|
156
|
+
dialect_raw = None
|
|
157
|
+
for key in _DIALECT_PAYLOAD_KEYS:
|
|
158
|
+
candidate = payload.get(key)
|
|
159
|
+
if isinstance(candidate, str) and candidate.strip():
|
|
160
|
+
dialect_raw = candidate
|
|
161
|
+
break
|
|
162
|
+
resolution = resolve_dialect(
|
|
163
|
+
dialect_raw if dialect_raw is not None
|
|
164
|
+
else os.environ.get("AGENT_GUARD_DIALECT"),
|
|
165
|
+
source="payload" if dialect_raw is not None
|
|
166
|
+
else "env AGENT_GUARD_DIALECT")
|
|
167
|
+
|
|
168
|
+
# The fast path screens on BOTH vocabularies. It is a cost filter only:
|
|
169
|
+
# a `del`/`rd`/`erase` line must reach check.py even when the session
|
|
170
|
+
# never configured a dialect (default posix), or it would execute with
|
|
171
|
+
# no verdict and no audit record. Selecting the lexer by dialect stays
|
|
172
|
+
# the core's job - deciding whether to look at all does not.
|
|
173
|
+
if resolution.ok and not (
|
|
174
|
+
DESTRUCTIVE_PREFILTER_RE.search(command)
|
|
175
|
+
or DESTRUCTIVE_PREFILTER_RE_WINDOWS.search(command)):
|
|
176
|
+
return 0 # fast path: regex cost only
|
|
177
|
+
|
|
178
|
+
cwd = payload.get("cwd") or os.getcwd()
|
|
179
|
+
env = dict(os.environ)
|
|
180
|
+
session_id = payload.get("session_id")
|
|
181
|
+
if session_id:
|
|
182
|
+
env["AGENT_GUARD_SESSION"] = str(session_id)
|
|
183
|
+
# Forward the *requested* selector verbatim rather than the resolved
|
|
184
|
+
# value: check.py owns the "is this usable?" verdict, so an unknown
|
|
185
|
+
# dialect becomes BLOCK_DIALECT_UNKNOWN instead of a silent posix
|
|
186
|
+
# fallback. The payload selector travels on argv; the environment
|
|
187
|
+
# variable is inherited by the child as-is.
|
|
188
|
+
argv = [sys.executable, CHECK, "--enforce", "--json"]
|
|
189
|
+
if dialect_raw is not None:
|
|
190
|
+
argv += ["--dialect", dialect_raw]
|
|
191
|
+
elif resolution.ok:
|
|
192
|
+
argv += ["--dialect", resolution.dialect]
|
|
193
|
+
argv += ["--", command]
|
|
194
|
+
|
|
195
|
+
try:
|
|
196
|
+
proc = subprocess.run(
|
|
197
|
+
argv, capture_output=True, text=True, timeout=90, cwd=cwd, env=env,
|
|
198
|
+
)
|
|
199
|
+
except Exception:
|
|
200
|
+
sys.stderr.write(
|
|
201
|
+
"[agent-guard] guard infrastructure error (fail-closed)\n")
|
|
202
|
+
return 2
|
|
203
|
+
|
|
204
|
+
try:
|
|
205
|
+
verdict = json.loads(proc.stdout)
|
|
206
|
+
except json.JSONDecodeError:
|
|
207
|
+
verdict = None
|
|
208
|
+
if not isinstance(verdict, dict) or not verdict.get("decision"):
|
|
209
|
+
sys.stderr.write(
|
|
210
|
+
"[agent-guard] unparseable guard output (fail-closed)\n")
|
|
211
|
+
return 2
|
|
212
|
+
|
|
213
|
+
if os.environ.get("AGENT_GUARD_DEBUG"):
|
|
214
|
+
sys.stderr.write(json.dumps(verdict, ensure_ascii=False) + "\n")
|
|
215
|
+
|
|
216
|
+
code = verdict.get("code", "")
|
|
217
|
+
explanation = verdict.get("explanation", "")
|
|
218
|
+
reasons = "; ".join(verdict.get("reasons") or [])
|
|
219
|
+
decision = verdict["decision"]
|
|
220
|
+
|
|
221
|
+
if decision == "ALLOW":
|
|
222
|
+
compensations = verdict.get("compensations") or []
|
|
223
|
+
if compensations:
|
|
224
|
+
emit({"hookSpecificOutput": {
|
|
225
|
+
"hookEventName": "PreToolUse",
|
|
226
|
+
"permissionDecision": "allow",
|
|
227
|
+
"permissionDecisionReason": allow_reason(code, compensations),
|
|
228
|
+
}})
|
|
229
|
+
return 0
|
|
230
|
+
|
|
231
|
+
if decision == "ASK":
|
|
232
|
+
if ask_is_block:
|
|
233
|
+
# Kimi Code 0.42.0 ignores permissionDecision="ask" and treats
|
|
234
|
+
# it as allow. Its adapter opts into this conservative mapping.
|
|
235
|
+
sys.stderr.write(
|
|
236
|
+
f"[agent-guard] BLOCKED [{code}] host cannot enforce ASK: "
|
|
237
|
+
"split the destructive operation into a standalone command "
|
|
238
|
+
"and retry; no approval was granted.\n")
|
|
239
|
+
return 2
|
|
240
|
+
# ASK_ONCE: Claude Code prompts the user; the reason is shown to
|
|
241
|
+
# the human. Splitting the command avoids future prompts.
|
|
242
|
+
emit({"hookSpecificOutput": {
|
|
243
|
+
"hookEventName": "PreToolUse",
|
|
244
|
+
"permissionDecision": "ask",
|
|
245
|
+
"permissionDecisionReason": f"[agent-guard] {code}: {explanation}",
|
|
246
|
+
}})
|
|
247
|
+
return 0
|
|
248
|
+
|
|
249
|
+
# BLOCK: exit 2 feeds stderr back to Claude - the model sees WHY and
|
|
250
|
+
# the remediation, which is the teaching channel.
|
|
251
|
+
message = (f"[agent-guard] BLOCKED [{code}] {explanation}"
|
|
252
|
+
+ (f" ({reasons})" if reasons else "")
|
|
253
|
+
+ " | Restate with explicit workspace-relative paths, or use "
|
|
254
|
+
"the safe-delete flow. Do NOT circumvent the guard.")
|
|
255
|
+
sys.stderr.write(message + "\n")
|
|
256
|
+
return 2
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
if __name__ == "__main__":
|
|
260
|
+
try:
|
|
261
|
+
sys.exit(main())
|
|
262
|
+
except Exception: # never fail open on adapter bugs
|
|
263
|
+
sys.stderr.write("[agent-guard] adapter error (fail-closed)\n")
|
|
264
|
+
sys.exit(2)
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"hooks": {
|
|
3
|
+
"PreToolUse": [
|
|
4
|
+
{
|
|
5
|
+
"matcher": "Bash",
|
|
6
|
+
"hooks": [
|
|
7
|
+
{
|
|
8
|
+
"type": "command",
|
|
9
|
+
"command": "/bin/sh /absolute/path/to/agent-guard/adapters/claude/hook_bridge.sh /absolute/path/to/python3",
|
|
10
|
+
"timeout": 120
|
|
11
|
+
}
|
|
12
|
+
]
|
|
13
|
+
}
|
|
14
|
+
]
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# Codex acceptance harness
|
|
2
|
+
|
|
3
|
+
Reproduces the 20-check acceptance run recorded in
|
|
4
|
+
[`docs/test-report-codex-gpt-6-astra-high.md`](../../../docs/test-report-codex-gpt-6-astra-high.md)
|
|
5
|
+
(2026-09-19, baseline `de5a00e`, `gpt-6-astra` / `high`).
|
|
6
|
+
|
|
7
|
+
Unlike [`adapters/claude/harness/`](../../claude/harness/), there is no Codex
|
|
8
|
+
adapter behind this directory. Codex has no native PreToolUse hook in this
|
|
9
|
+
repository, so nothing here implies automatic interception: the driver
|
|
10
|
+
exercises the guard through the production CLI (`check.py`, `safe_delete.py`,
|
|
11
|
+
`restore.py`, `status.py`, `gc.py`) exactly the way a skill-guided agent would.
|
|
12
|
+
|
|
13
|
+
## Provenance
|
|
14
|
+
|
|
15
|
+
Recovered 2026-09-21 from the Codex session cache. The original driver lived in
|
|
16
|
+
`/tmp/agent-guard-astra-high-20260919-HxRpvY/acceptance.py` together with its
|
|
17
|
+
`events.jsonl` and `summary.json`; that directory was temporary storage and did
|
|
18
|
+
not survive. The recovered driver was subsequently made portable by replacing
|
|
19
|
+
its hard-coded checkout path with `AGENT_GUARD_PROJECT`; before that edit, its
|
|
20
|
+
SHA-256 was `b667c9ad8683516cf79fc60d6bf7c85bd7ef7dd7e6d872ae6ca5b7a6927a91f6`.
|
|
21
|
+
|
|
22
|
+
## Run
|
|
23
|
+
|
|
24
|
+
The driver requires the checkout path and refuses an existing run directory.
|
|
25
|
+
Run it from a fresh directory; `AGENT_GUARD_PROJECT` must be absolute:
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
run=$(mktemp -d /tmp/agent-guard-astra-XXXXXX)
|
|
29
|
+
cp adapters/codex/harness/acceptance.py "$run"/
|
|
30
|
+
cd "$run" && AGENT_GUARD_PROJECT=/absolute/path/to/agent-guard python3 acceptance.py
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
The driver uses `AGENT_GUARD_SESSION=astra-high-acceptance` and clears any
|
|
34
|
+
inherited `AGENT_GUARD_*` variables, so the audit trail is attributable.
|
|
35
|
+
|
|
36
|
+
## Outputs
|
|
37
|
+
|
|
38
|
+
| File | Contents |
|
|
39
|
+
|---|---|
|
|
40
|
+
| `events.jsonl` | one record per subprocess call: `cwd`, `argv`, `exit`, `stdout`, `stderr`, `elapsed_s` |
|
|
41
|
+
| `summary.json` | `{"passed": N, "checks": [...], "commands": N}` |
|
|
42
|
+
|
|
43
|
+
## Scope and limits
|
|
44
|
+
|
|
45
|
+
BLOCK and ASK commands are submitted as data to `check.py`; they are never
|
|
46
|
+
executed. The fixture `git reset` and `git clean` run only after compensation
|
|
47
|
+
succeeded and the transaction was independently listed `RESTORABLE`. Permission
|
|
48
|
+
probes touch only newly created fixture files.
|
|
49
|
+
|
|
50
|
+
Passing this driver means the deliberate skill/CLI path works on the host it
|
|
51
|
+
ran on. It does not establish a Codex interception hook, an OS sandbox
|
|
52
|
+
boundary, or portability beyond the recorded environment (Android 16 / Termux /
|
|
53
|
+
PRoot Debian 13.6, aarch64).
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
ROOT = Path(__file__).resolve().parent
|
|
10
|
+
project_arg = os.environ.get('AGENT_GUARD_PROJECT')
|
|
11
|
+
if not project_arg:
|
|
12
|
+
raise SystemExit('set AGENT_GUARD_PROJECT to the agent-guard checkout path')
|
|
13
|
+
PROJECT = Path(project_arg).expanduser().resolve(strict=True)
|
|
14
|
+
SCRIPTS = PROJECT / 'skills/delete-guard/scripts'
|
|
15
|
+
if not (SCRIPTS / 'check.py').is_file():
|
|
16
|
+
raise SystemExit('AGENT_GUARD_PROJECT has no delete-guard check.py')
|
|
17
|
+
ENV = {k: v for k, v in os.environ.items() if not k.startswith('AGENT_GUARD_')}
|
|
18
|
+
ENV['AGENT_GUARD_SESSION'] = 'astra-high-acceptance'
|
|
19
|
+
EVENTS = []
|
|
20
|
+
PASSED = []
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def run(cwd, argv, expected=0):
|
|
24
|
+
started = time.monotonic()
|
|
25
|
+
p = subprocess.run([str(x) for x in argv], cwd=cwd, env=ENV,
|
|
26
|
+
capture_output=True, text=True, timeout=45)
|
|
27
|
+
event = dict(cwd=str(cwd), argv=[str(x) for x in argv], exit=p.returncode,
|
|
28
|
+
stdout=p.stdout, stderr=p.stderr,
|
|
29
|
+
elapsed_s=round(time.monotonic() - started, 3))
|
|
30
|
+
EVENTS.append(event)
|
|
31
|
+
with (ROOT / 'events.jsonl').open('a') as fh:
|
|
32
|
+
fh.write(json.dumps(event, ensure_ascii=True) + '\n')
|
|
33
|
+
assert p.returncode == expected, event
|
|
34
|
+
return p.stdout
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def cli(cwd, name, *args, expected=0):
|
|
38
|
+
return json.loads(run(cwd, [sys.executable, SCRIPTS / (name + '.py'),
|
|
39
|
+
*args, '--json'], expected))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def check(cwd, command, expected=0, enforce=True):
|
|
43
|
+
args = [sys.executable, SCRIPTS / 'check.py', '--json']
|
|
44
|
+
if enforce:
|
|
45
|
+
args.append('--enforce')
|
|
46
|
+
return json.loads(run(cwd, [*args, '--', command], expected))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def write(cwd, name, content):
|
|
50
|
+
p = cwd / name
|
|
51
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
52
|
+
p.write_bytes(content)
|
|
53
|
+
return p
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def digest(p):
|
|
57
|
+
return hashlib.sha256(p.read_bytes()).hexdigest()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def repo(name, ignored=True):
|
|
61
|
+
p = ROOT / name
|
|
62
|
+
p.mkdir()
|
|
63
|
+
run(p, ['git', 'init', '-q'])
|
|
64
|
+
for key, value in [('user.name', 'Guard Fixture'), ('user.email', 'fixture@local'),
|
|
65
|
+
('commit.gpgsign', 'false')]:
|
|
66
|
+
run(p, ['git', 'config', key, value])
|
|
67
|
+
write(p, '.gitignore', b'node_modules/\n*.log\n' +
|
|
68
|
+
(b'.agent-trash/\n' if ignored else b''))
|
|
69
|
+
write(p, 'src/main.txt', b'baseline\n')
|
|
70
|
+
run(p, ['git', 'add', '.'])
|
|
71
|
+
run(p, ['git', 'commit', '-qm', 'fixture baseline'])
|
|
72
|
+
return p
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def state(cwd, txid):
|
|
76
|
+
return next(t['state'] for t in cli(cwd, 'restore', 'list')['transactions']
|
|
77
|
+
if t['txid'] == txid)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def passed(name):
|
|
81
|
+
PASSED.append(name)
|
|
82
|
+
print('PASS ' + name, flush=True)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def roundtrip(cwd, names):
|
|
86
|
+
before = {n: digest(cwd / n) for n in names}
|
|
87
|
+
result = cli(cwd, 'safe_delete', *names)
|
|
88
|
+
assert result['verdict']['decision'] == 'RELOCATE', result
|
|
89
|
+
txid = result['txid']
|
|
90
|
+
assert all(not (cwd / n).exists() for n in names)
|
|
91
|
+
assert state(cwd, txid) == 'RESTORABLE'
|
|
92
|
+
restored = cli(cwd, 'restore', txid)
|
|
93
|
+
assert restored['ok'], restored
|
|
94
|
+
assert {n: digest(cwd / n) for n in names} == before
|
|
95
|
+
assert state(cwd, txid) == 'RESTORED'
|
|
96
|
+
return txid
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def main():
|
|
100
|
+
p = repo('workflow')
|
|
101
|
+
outside = write(ROOT, 'outside.txt', b'outside sentinel\n')
|
|
102
|
+
before = digest(p / 'src/main.txt')
|
|
103
|
+
for command, code in [
|
|
104
|
+
('rm -rf .', 'BLOCK_PROTECTED_PATH'),
|
|
105
|
+
('rm -rf .git', 'BLOCK_PROTECTED_PATH'),
|
|
106
|
+
('rm ../outside.txt', 'BLOCK_OUT_OF_WORKSPACE'),
|
|
107
|
+
('rm -rf $CLEAN_TARGET', 'BLOCK_UNDETERMINABLE_EFFECT'),
|
|
108
|
+
('rm *.log', 'BLOCK_WILDCARD'),
|
|
109
|
+
('git push --force', 'BLOCK_FORCE_PUSH'),
|
|
110
|
+
('bash -c "rm -rf src"', 'BLOCK_UNDETERMINABLE_EFFECT'),
|
|
111
|
+
]:
|
|
112
|
+
result = check(p, command, expected=2)
|
|
113
|
+
assert (result['decision'], result['code']) == ('BLOCK', code), result
|
|
114
|
+
assert digest(p / 'src/main.txt') == before and outside.exists()
|
|
115
|
+
passed('block: ' + code + ' / ' + command)
|
|
116
|
+
result = check(p, 'cd src && rm main.txt', expected=3)
|
|
117
|
+
assert result['decision'] == 'ASK' and digest(p / 'src/main.txt') == before
|
|
118
|
+
passed('compound command asks without execution')
|
|
119
|
+
result = check(p, 'rm -rf .', enforce=False)
|
|
120
|
+
assert result['decision'] == 'BLOCK' and result['exit'] == 0
|
|
121
|
+
passed('advisory verdict differs from enforcement exit status')
|
|
122
|
+
roundtrip(p, ['src/main.txt'])
|
|
123
|
+
passed('tracked file hash and RESTORABLE -> RESTORED lifecycle')
|
|
124
|
+
write(p, 'build/nested/output.bin', bytes(range(256)))
|
|
125
|
+
result = check(p, 'rm -rf build')
|
|
126
|
+
txid = result['compensations'][0]['txid']
|
|
127
|
+
assert result['decision'] == 'ALLOW' and state(p, txid) == 'RESTORABLE'
|
|
128
|
+
assert not (p / 'build').exists()
|
|
129
|
+
cli(p, 'restore', txid)
|
|
130
|
+
assert (p / 'build/nested/output.bin').read_bytes() == bytes(range(256))
|
|
131
|
+
passed('check --enforce quarantines nonignored directory')
|
|
132
|
+
write(p, 'session.log', b'valuable ignored log\n')
|
|
133
|
+
roundtrip(p, ['session.log'])
|
|
134
|
+
passed('ignored log is recoverable rather than regenerable')
|
|
135
|
+
write(p, 'node_modules/fixture/index.js', b'fixture dependency\n')
|
|
136
|
+
result = cli(p, 'safe_delete', 'node_modules')
|
|
137
|
+
assert result['verdict']['code'] == 'ALLOW_REGENERABLE'
|
|
138
|
+
assert not (p / 'node_modules').exists() and 'txid' not in result
|
|
139
|
+
passed('ignored dependency artifact deletes through safe_delete')
|
|
140
|
+
write(p, 'notes.txt', b'original notes\n')
|
|
141
|
+
result = cli(p, 'safe_delete', 'notes.txt')
|
|
142
|
+
txid = result['txid']
|
|
143
|
+
write(p, 'notes.txt', b'new content\n')
|
|
144
|
+
result = cli(p, 'restore', txid, expected=3)
|
|
145
|
+
assert result['conflicts'] and (p / 'notes.txt').read_bytes() == b'new content\n'
|
|
146
|
+
assert state(p, txid) == 'RESTORABLE'
|
|
147
|
+
passed('restore conflict preserves new content and quarantine')
|
|
148
|
+
p = repo('clean')
|
|
149
|
+
names = ['\u4e2d\u6587\u7b14\u8bb0.txt', 'space name.txt', 'line\nbreak.txt',
|
|
150
|
+
'tab\tname.txt', 'quote"name.txt', 'back\\slash.txt']
|
|
151
|
+
hashes = {n: digest(write(p, n, ('valuable ' + n).encode())) for n in names}
|
|
152
|
+
result = check(p, 'git clean -fd')
|
|
153
|
+
txid = result['compensations'][0]['txid']
|
|
154
|
+
assert result['compensations'][0]['moved'] == len(names)
|
|
155
|
+
assert state(p, txid) == 'RESTORABLE'
|
|
156
|
+
run(p, ['git', 'clean', '-fd'])
|
|
157
|
+
cli(p, 'restore', txid)
|
|
158
|
+
assert {n: digest(p / n) for n in names} == hashes
|
|
159
|
+
passed('git clean special filenames and SHA-256 restoration')
|
|
160
|
+
p = repo('snapshot')
|
|
161
|
+
dirty = write(p, 'src/main.txt', b'uncommitted valuable edit\n')
|
|
162
|
+
before = digest(dirty)
|
|
163
|
+
result = check(p, 'git reset --hard')
|
|
164
|
+
snapshot = result['compensations'][0]
|
|
165
|
+
assert snapshot['strategy'] == 'snapshot' and snapshot['sha']
|
|
166
|
+
assert state(p, snapshot['txid']) == 'RESTORABLE'
|
|
167
|
+
assert digest(dirty) == before
|
|
168
|
+
run(p, ['git', 'reset', '--hard', 'HEAD'])
|
|
169
|
+
assert dirty.read_bytes() == b'baseline\n'
|
|
170
|
+
cli(p, 'restore', snapshot['txid'])
|
|
171
|
+
assert digest(dirty) == before
|
|
172
|
+
assert snapshot['sha'] in run(p, ['git', 'stash', 'list', '--format=%H'])
|
|
173
|
+
passed('git snapshot before reset and hash-verified restore; stash retained')
|
|
174
|
+
p = repo('audit-failure')
|
|
175
|
+
check(p, 'git status')
|
|
176
|
+
target = write(p, 'node_modules/fixture/index.js', b'keep on audit failure\n')
|
|
177
|
+
audit = p / '.agent-trash/audit.jsonl'
|
|
178
|
+
audit.chmod(0o400)
|
|
179
|
+
try:
|
|
180
|
+
result = cli(p, 'safe_delete', 'node_modules', expected=2)
|
|
181
|
+
assert result['verdict']['decision'] == 'BLOCK' and target.exists()
|
|
182
|
+
assert 'audit intent failed' in result['verdict']['reasons'][0]
|
|
183
|
+
finally:
|
|
184
|
+
audit.chmod(0o600)
|
|
185
|
+
passed('audit intent failure blocks regenerable deletion')
|
|
186
|
+
p = repo('readonly-preignored')
|
|
187
|
+
info = p / '.git/info'
|
|
188
|
+
exclude = info / 'exclude'
|
|
189
|
+
info.chmod(0o500)
|
|
190
|
+
exclude.chmod(0o400)
|
|
191
|
+
try:
|
|
192
|
+
roundtrip(p, ['src/main.txt'])
|
|
193
|
+
finally:
|
|
194
|
+
info.chmod(0o700)
|
|
195
|
+
exclude.chmod(0o600)
|
|
196
|
+
passed('preignored quarantine works with readonly Git exclude metadata')
|
|
197
|
+
p = repo('readonly-unignored', ignored=False)
|
|
198
|
+
info = p / '.git/info'
|
|
199
|
+
exclude = info / 'exclude'
|
|
200
|
+
info.chmod(0o500)
|
|
201
|
+
exclude.chmod(0o400)
|
|
202
|
+
before = digest(p / 'src/main.txt')
|
|
203
|
+
try:
|
|
204
|
+
result = cli(p, 'safe_delete', 'src/main.txt', expected=2)
|
|
205
|
+
assert result['verdict']['decision'] == 'BLOCK'
|
|
206
|
+
assert digest(p / 'src/main.txt') == before
|
|
207
|
+
assert not (p / '.agent-trash').exists()
|
|
208
|
+
finally:
|
|
209
|
+
info.chmod(0o700)
|
|
210
|
+
exclude.chmod(0o600)
|
|
211
|
+
passed('unignored quarantine fails before move with readonly Git metadata')
|
|
212
|
+
assert outside.read_bytes() == b'outside sentinel\n'
|
|
213
|
+
for folder in ROOT.iterdir():
|
|
214
|
+
if not folder.is_dir() or not (folder / '.git').exists():
|
|
215
|
+
continue
|
|
216
|
+
assert '.agent-trash' not in run(folder, ['git', 'status', '--porcelain'])
|
|
217
|
+
for file in (folder / '.agent-trash').glob('*.jsonl'):
|
|
218
|
+
assert all(isinstance(json.loads(line), dict) for line in file.read_text().splitlines())
|
|
219
|
+
passed('all audit and manifest records parse; quarantine stays ignored')
|
|
220
|
+
(ROOT / 'summary.json').write_text(json.dumps(
|
|
221
|
+
{'passed': len(PASSED), 'checks': PASSED, 'commands': len(EVENTS)}, indent=2) + '\n')
|
|
222
|
+
print('Completed: ' + str(len(PASSED)) + ' checks', flush=True)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
if __name__ == '__main__':
|
|
226
|
+
main()
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# agent-guard adapter for DeepSeek Harness
|
|
2
|
+
|
|
3
|
+
Official DSH integration, shipped as a first-class `dsh-plugin` bundle.
|
|
4
|
+
The decision rules are NOT implemented here - this adapter translates the
|
|
5
|
+
Decision Protocol onto DSH's native mechanisms and delegates every verdict
|
|
6
|
+
to the shared Python core (`skills/delete-guard/scripts/check.py`) that
|
|
7
|
+
ships inside this very package.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
dsh plugin --profile <your-profile> add @mokuyoaxis/agent-guard
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## What gets registered
|
|
16
|
+
|
|
17
|
+
| Contribution | Mechanism | Behavior |
|
|
18
|
+
|---|---|---|
|
|
19
|
+
| Interception | `tools/pre-execute` waterfall | destructive-looking bash runs through `check.py --enforce` first; ALLOW proceeds (compensation applied), ASK escalates once to the human, BLOCK denies with explanation and remediation |
|
|
20
|
+
| `agent_guard_safe_delete` | model tool | recoverable delete with explicit glob expansion and manifest |
|
|
21
|
+
| `agent_guard_restore` | model tool | list / non-overwriting restore of quarantine transactions; forced overwrite remains human-only CLI functionality |
|
|
22
|
+
| `agent_guard_status` | model tool | mode, usage, retention view, recent decisions |
|
|
23
|
+
| Prompt section | system prompt (order 105) | deletion discipline for the model |
|
|
24
|
+
|
|
25
|
+
## Configuration (cordis.patch.yml row)
|
|
26
|
+
|
|
27
|
+
| Key | Default | Meaning |
|
|
28
|
+
|---|---|---|
|
|
29
|
+
| `repoRoot` | `""` (this package) | absolute path to a live agent-guard checkout for development |
|
|
30
|
+
| `defaultCwd` | executor default | working directory for guard invocations |
|
|
31
|
+
| `promptSection` | `true` | register the deletion-discipline section |
|
|
32
|
+
| `sectionOrder` | `105` | system-prompt section order |
|
|
33
|
+
| `dialect` | `""` (posix) | shell dialect for guard invocations: `posix`, `cmd`, or `powershell` |
|
|
34
|
+
|
|
35
|
+
## Shell dialect
|
|
36
|
+
|
|
37
|
+
Interception forwards a shell dialect to `check.py` so Windows-native
|
|
38
|
+
command lines are lexed with the right rules. Explicitly invalid plugin
|
|
39
|
+
configuration (including unknown field names) is rejected by Standard Schema
|
|
40
|
+
validation; only omitted fields receive defaults. Precedence for valid
|
|
41
|
+
configuration: the tool argument (`dialect`), then `AGENT_GUARD_DIALECT`,
|
|
42
|
+
then the `dialect` config
|
|
43
|
+
key, then `posix`. The fast prefilter screens both POSIX and Windows
|
|
44
|
+
vocabularies regardless of dialect. An unrecognised tool/environment selector
|
|
45
|
+
is forwarded verbatim rather than swapped for POSIX, so `check.py` returns
|
|
46
|
+
`BLOCK_DIALECT_UNKNOWN` and the call is denied with that code.
|
|
47
|
+
|
|
48
|
+
## Notes
|
|
49
|
+
|
|
50
|
+
- The caller's sandbox policy is inherited per-invocation (`exec.agent.session`), so guard subprocesses never gain privileges the calling agent lacks.
|
|
51
|
+
- Once the adapter has registered its pre-execute listener, Core process and
|
|
52
|
+
output failures fail closed (deny). An absent/disabled bundle, a changed host
|
|
53
|
+
event contract, or failure before listener registration cannot deny a call
|
|
54
|
+
the adapter never receives.
|
|
55
|
+
- The Python core requires `python3` and `git` on PATH.
|
|
56
|
+
- Until the scoped npm package is actually published, install from a GitHub
|
|
57
|
+
checkout or release tarball rather than treating the registry command above
|
|
58
|
+
as available.
|
|
59
|
+
- DSH `0.1.5-rc.1` package loading and one harmless execution-level `bash`
|
|
60
|
+
block are independently verified in the
|
|
61
|
+
[bounded host report](../../docs/test-report-dsh-0.1.5-rc.1.md). Model,
|
|
62
|
+
subagent, concurrency, ASK UI and non-`bash` paths remain separate tests.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# agent-guard - bundle patch layer.
|
|
2
|
+
#
|
|
3
|
+
# Appends one composition row to the launcher composition: registers the
|
|
4
|
+
# agent_guard_safe_delete / agent_guard_restore / agent_guard_status model
|
|
5
|
+
# tools, a PreToolUse-style interception on the bash entry (via the
|
|
6
|
+
# tools/pre-execute waterfall), and prompt guidance. The decision rules
|
|
7
|
+
# themselves live in ONE Python core (skills/delete-guard/scripts/check.py)
|
|
8
|
+
# shipped inside this package - this adapter never re-implements them.
|
|
9
|
+
#
|
|
10
|
+
# config:
|
|
11
|
+
# repoRoot empty = resolve Python core from this package (default).
|
|
12
|
+
# Set an absolute path to point at a live agent-guard
|
|
13
|
+
# checkout instead (development mode).
|
|
14
|
+
# defaultCwd empty = executor default (the session workspace).
|
|
15
|
+
# promptSection register the deletion-discipline system-prompt section.
|
|
16
|
+
# sectionOrder ascending; persona is 0, tool guidance conventionally
|
|
17
|
+
# 100-199.
|
|
18
|
+
# dialect shell dialect the session issues commands in: posix
|
|
19
|
+
# (default), cmd, or powershell. Callers may also set it
|
|
20
|
+
# per call (tools) or via AGENT_GUARD_DIALECT; an unusable
|
|
21
|
+
# value is refused by the guard with an explicit BLOCK code.
|
|
22
|
+
- insert:
|
|
23
|
+
- id: agent_guard
|
|
24
|
+
name: '@mokuyoaxis/agent-guard'
|
|
25
|
+
config:
|
|
26
|
+
repoRoot: ''
|
|
27
|
+
defaultCwd: ''
|
|
28
|
+
promptSection: true
|
|
29
|
+
sectionOrder: 105
|
|
30
|
+
dialect: ''
|