@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
package/doctor.py ADDED
@@ -0,0 +1,756 @@
1
+ #!/usr/bin/env python3
2
+ """Local agent-guard installation checks; never edits harness configuration."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from dataclasses import dataclass
8
+ import hashlib
9
+ import json
10
+ import os
11
+ from pathlib import Path
12
+ import re
13
+ import shlex
14
+ import shutil
15
+ import subprocess
16
+ import sys
17
+ import tempfile
18
+ from typing import Any, Optional
19
+
20
+ from core.dialects import resolve_dialect
21
+
22
+
23
+ ROOT = Path(__file__).resolve().parent
24
+ KIMI_BRIDGE = ROOT / "adapters" / "kimi-code" / "hook_bridge.sh"
25
+ CLAUDE_BRIDGE = ROOT / "adapters" / "claude" / "hook_bridge.sh"
26
+ PROFILE_PATHS = {
27
+ "kimi": ROOT / "adapters" / "kimi-code" / "compatibility.json",
28
+ "claude": ROOT / "adapters" / "claude" / "compatibility.json",
29
+ }
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class HostProfile:
34
+ profile_id: str
35
+ harness: str
36
+ display_name: str
37
+ executable_candidates: tuple[str, ...]
38
+ version_args: tuple[str, ...]
39
+ version_pattern: str
40
+ tested_versions: tuple[str, ...]
41
+ path: Path
42
+
43
+
44
+ @dataclass
45
+ class Diagnosis:
46
+ harness: str
47
+ config_path: Path
48
+ configuration: str
49
+ local_probe: str
50
+ problems: list[str]
51
+ profile: Optional[str] = None
52
+ host_version: Optional[str] = None
53
+ drift_status: str = "NOT_CHECKED"
54
+ configuration_fingerprint: Optional[str] = None
55
+ runtime_fingerprint: Optional[str] = None
56
+ drift_problems: Optional[list[str]] = None
57
+ baseline_written: bool = False
58
+
59
+ def as_dict(self) -> dict:
60
+ return {
61
+ "harness": self.harness,
62
+ "configuration": self.configuration,
63
+ "local_probe": self.local_probe,
64
+ "host_interception": "UNVERIFIED",
65
+ "problems": self.problems,
66
+ "profile": self.profile,
67
+ "host_version": self.host_version,
68
+ "drift_status": self.drift_status,
69
+ "configuration_fingerprint": self.configuration_fingerprint,
70
+ "runtime_fingerprint": self.runtime_fingerprint,
71
+ "drift_problems": self.drift_problems or [],
72
+ "baseline_written": self.baseline_written,
73
+ }
74
+
75
+
76
+ def _load_profile(harness: str) -> HostProfile:
77
+ path = PROFILE_PATHS[harness]
78
+ try:
79
+ data = json.loads(path.read_text(encoding="utf-8"))
80
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
81
+ raise ValueError("compatibility profile cannot be read") from exc
82
+ required = {
83
+ "schema_version", "profile_id", "harness", "display_name",
84
+ "executable_candidates", "version_args", "version_pattern",
85
+ "tested_versions", "contract",
86
+ }
87
+ if (not isinstance(data, dict) or not required.issubset(data)
88
+ or data.get("schema_version") != 1
89
+ or data.get("harness") != harness
90
+ or not all(isinstance(data.get(key), str) and data[key]
91
+ for key in ("profile_id", "display_name", "version_pattern"))
92
+ or not isinstance(data.get("contract"), dict)):
93
+ raise ValueError("compatibility profile has an invalid shape")
94
+ list_keys = ("executable_candidates", "version_args", "tested_versions")
95
+ if any(not isinstance(data.get(key), list)
96
+ or not all(isinstance(item, str) and item for item in data[key])
97
+ for key in list_keys):
98
+ raise ValueError("compatibility profile has invalid command/version fields")
99
+ if not data["executable_candidates"] or not data["tested_versions"]:
100
+ raise ValueError("compatibility profile has no executable or tested version")
101
+ try:
102
+ re.compile(data["version_pattern"])
103
+ except re.error as exc:
104
+ raise ValueError("compatibility profile has an invalid version pattern") from exc
105
+ return HostProfile(
106
+ profile_id=data["profile_id"], harness=harness,
107
+ display_name=data["display_name"],
108
+ executable_candidates=tuple(data["executable_candidates"]),
109
+ version_args=tuple(data["version_args"]),
110
+ version_pattern=data["version_pattern"],
111
+ tested_versions=tuple(data["tested_versions"]), path=path,
112
+ )
113
+
114
+
115
+ def _fingerprint(value: Any) -> str:
116
+ encoded = json.dumps(
117
+ value, sort_keys=True, separators=(",", ":"),
118
+ ensure_ascii=True).encode("utf-8")
119
+ return "sha256:" + hashlib.sha256(encoded).hexdigest()
120
+
121
+
122
+ def _runtime_fingerprint(harness: str, profile: HostProfile) -> str:
123
+ paths = {
124
+ ROOT / "package.json",
125
+ profile.path,
126
+ ROOT / "skills" / "delete-guard" / "scripts" / "check.py",
127
+ ROOT / "skills" / "delete-guard" / "scripts" / "_bootstrap.py",
128
+ }
129
+ paths.update((ROOT / "core").glob("*.py"))
130
+ if harness == "claude":
131
+ paths.update({
132
+ CLAUDE_BRIDGE,
133
+ ROOT / "adapters" / "claude" / "pre_tool_use.py",
134
+ })
135
+ else:
136
+ paths.update({
137
+ KIMI_BRIDGE,
138
+ ROOT / "adapters" / "kimi-code" / "pre_tool_use.py",
139
+ ROOT / "adapters" / "claude" / "pre_tool_use.py",
140
+ })
141
+ digest = hashlib.sha256()
142
+ for path in sorted(paths, key=lambda item: str(item.relative_to(ROOT))):
143
+ relative = str(path.relative_to(ROOT)).encode("utf-8")
144
+ content = path.read_bytes()
145
+ digest.update(len(relative).to_bytes(8, "big"))
146
+ digest.update(relative)
147
+ digest.update(len(content).to_bytes(8, "big"))
148
+ digest.update(content)
149
+ return "sha256:" + digest.hexdigest()
150
+
151
+
152
+ def _detect_host_version(
153
+ profile: HostProfile, explicit: Optional[str],
154
+ ) -> tuple[Optional[str], Optional[str]]:
155
+ executable: Optional[str] = None
156
+ if explicit:
157
+ executable = shutil.which(explicit)
158
+ else:
159
+ for candidate in profile.executable_candidates:
160
+ executable = shutil.which(candidate)
161
+ if executable:
162
+ break
163
+ if not executable:
164
+ return None, f"{profile.display_name} executable was not found"
165
+ try:
166
+ result = subprocess.run(
167
+ [executable, *profile.version_args], capture_output=True, text=True,
168
+ cwd=ROOT, timeout=5, errors="replace",
169
+ )
170
+ except (OSError, subprocess.TimeoutExpired):
171
+ return None, f"{profile.display_name} version command could not finish"
172
+ if result.returncode != 0:
173
+ return None, f"{profile.display_name} version command exited non-zero"
174
+ match = re.search(profile.version_pattern, result.stdout + "\n" + result.stderr)
175
+ if not match:
176
+ return None, f"{profile.display_name} version output was not recognized"
177
+ return match.group(1), None
178
+
179
+
180
+ def _kimi_config_path(explicit: Optional[str]) -> Path:
181
+ if explicit:
182
+ return Path(explicit).expanduser()
183
+ kimi_home = os.environ.get("KIMI_CODE_HOME")
184
+ if kimi_home:
185
+ return Path(kimi_home).expanduser() / "config.toml"
186
+ return Path.home() / ".kimi-code" / "config.toml"
187
+
188
+
189
+ def _claude_config_path(explicit: Optional[str]) -> Path:
190
+ # A selected settings file is not Claude's effective merged configuration.
191
+ # Global, local, managed, plugin and session sources may alter the result.
192
+ if explicit:
193
+ return Path(explicit).expanduser()
194
+ return Path.cwd() / ".claude" / "settings.json"
195
+
196
+
197
+ def _command_tokens(command: str) -> list[str]:
198
+ # Preserve shell operators as tokens so `cmd; other_cmd` cannot pass as a
199
+ # simple three-argument bridge command. Quoted spaces in paths still work.
200
+ lexer = shlex.shlex(command, posix=True, punctuation_chars="();<>|&")
201
+ lexer.whitespace_split = True
202
+ lexer.commenters = ""
203
+ return list(lexer)
204
+
205
+
206
+ def _same_file(left: Path, right: Path) -> bool:
207
+ try:
208
+ return left.samefile(right)
209
+ except (OSError, ValueError):
210
+ return False
211
+
212
+
213
+ def _executable(path: Path) -> bool:
214
+ try:
215
+ return path.is_file() and os.access(path, os.X_OK)
216
+ except (OSError, ValueError):
217
+ return False
218
+
219
+
220
+ def _bridge_command(
221
+ command: object, expected_bridge: Path,
222
+ ) -> tuple[list[str], Optional[tuple[Path, Path, Path]]]:
223
+ if not isinstance(command, str):
224
+ return ["hook command must be a string"], None
225
+ try:
226
+ tokens = _command_tokens(command)
227
+ except ValueError:
228
+ return ["hook command has invalid shell quoting"], None
229
+ if len(tokens) != 3 or not all(Path(part).is_absolute() for part in tokens):
230
+ return ["hook command must be: ABSOLUTE_SH ABSOLUTE_BRIDGE ABSOLUTE_PYTHON"], None
231
+
232
+ shell, bridge, python = map(Path, tokens)
233
+ problems = []
234
+ if not _executable(shell):
235
+ problems.append(f"POSIX shell is missing or not executable: {shell}")
236
+ if not _same_file(bridge, expected_bridge):
237
+ problems.append(f"bridge does not point to this checkout: {expected_bridge}")
238
+ if not _executable(python):
239
+ problems.append(f"Python is missing or not executable: {python}")
240
+ return problems, (shell, bridge, python)
241
+
242
+
243
+ def _probe(harness: str, shell: Path, bridge: Path, python: Path) -> list[str]:
244
+ problems: list[str] = []
245
+ with tempfile.TemporaryDirectory(prefix=f"agent-guard-doctor-{harness}-") as cwd:
246
+ sentinel = Path(cwd) / ".guard-doctor-denied"
247
+ payload = json.dumps({
248
+ "hook_event_name": "PreToolUse", "tool_name": "Bash",
249
+ "tool_input": {"command": "printf guard-doctor-local-probe"}, "cwd": cwd,
250
+ })
251
+ core_payload = json.dumps({
252
+ "hook_event_name": "PreToolUse", "tool_name": "Bash",
253
+ "tool_input": {"command": "touch .guard-doctor-denied"}, "cwd": cwd,
254
+ })
255
+ ask_payload = json.dumps({
256
+ "hook_event_name": "PreToolUse", "tool_name": "Bash",
257
+ "tool_input": {"command": "touch .guard-doctor-ask && rm .guard-doctor-ask"},
258
+ "cwd": cwd,
259
+ })
260
+ probe_env = dict(os.environ)
261
+ probe_env.pop("AGENT_GUARD_DIALECT", None)
262
+ probe_env.pop("AGENT_GUARD_SESSION", None)
263
+ probe_env["AGENT_GUARD_WORKSPACE"] = cwd
264
+ cases = (
265
+ (python, payload, 0, "valid Bash payload", None, None),
266
+ (python, "{", 2, "malformed payload", None, "malformed hook payload"),
267
+ (python, core_payload, 2, "Core policy refusal",
268
+ "fish", "BLOCK_DIALECT_UNKNOWN"),
269
+ (Path(cwd) / "missing-python", payload, 2,
270
+ "missing interpreter", None, "hook process failed"),
271
+ )
272
+ for interpreter, data, expected, label, dialect, marker in cases:
273
+ env = dict(probe_env)
274
+ if dialect:
275
+ env["AGENT_GUARD_DIALECT"] = dialect
276
+ try:
277
+ result = subprocess.run(
278
+ [str(shell), str(bridge), str(interpreter)],
279
+ input=data, text=True, capture_output=True,
280
+ cwd=cwd, timeout=15, env=env,
281
+ )
282
+ except (OSError, subprocess.TimeoutExpired):
283
+ problems.append(f"{label}: bridge could not finish")
284
+ continue
285
+ if result.returncode != expected:
286
+ problems.append(
287
+ f"{label}: expected exit {expected}, got {result.returncode}")
288
+ if marker and marker not in result.stderr:
289
+ problems.append(f"{label}: expected {marker} in hook refusal")
290
+ if label == "valid Bash payload" and (result.stdout or result.stderr):
291
+ problems.append("valid Bash payload: expected a silent allow")
292
+ if expected == 2 and result.stdout:
293
+ problems.append(f"{label}: refusal wrote unexpected stdout")
294
+ try:
295
+ ask = subprocess.run(
296
+ [str(shell), str(bridge), str(python)],
297
+ input=ask_payload, text=True, capture_output=True,
298
+ cwd=cwd, timeout=15, env=probe_env,
299
+ )
300
+ except (OSError, subprocess.TimeoutExpired):
301
+ problems.append("ASK mapping: bridge could not finish")
302
+ else:
303
+ if harness == "kimi":
304
+ if ask.returncode != 2 or "host cannot enforce ASK" not in ask.stderr:
305
+ problems.append("ASK mapping: Kimi did not hard-refuse")
306
+ else:
307
+ try:
308
+ decision = json.loads(ask.stdout)["hookSpecificOutput"]["permissionDecision"]
309
+ except (ValueError, KeyError, TypeError):
310
+ decision = None
311
+ if ask.returncode != 0 or decision != "ask":
312
+ problems.append("ASK mapping: Claude did not request approval")
313
+ # The hook only returns a verdict; no Bash command is executed here.
314
+ # In particular, an absent file is not host-enforcement evidence.
315
+ if sentinel.exists():
316
+ problems.append("Core policy refusal: local hook executed probe command")
317
+ if (Path(cwd) / ".guard-doctor-ask").exists():
318
+ problems.append("ASK mapping: local hook executed probe command")
319
+ return problems
320
+
321
+
322
+ def _dialect_problems() -> list[str]:
323
+ selected_dialect = os.environ.get("AGENT_GUARD_DIALECT")
324
+ if selected_dialect is not None and not resolve_dialect(
325
+ selected_dialect, source="env AGENT_GUARD_DIALECT").ok:
326
+ return ["AGENT_GUARD_DIALECT is invalid for this process"]
327
+ return []
328
+
329
+
330
+ def _check_kimi_config(
331
+ config_path: Path,
332
+ ) -> tuple[list[str], Optional[tuple[Path, Path, Path]], Optional[str]]:
333
+ problems: list[str] = []
334
+ problems.extend(_dialect_problems())
335
+ try:
336
+ import tomllib
337
+ except ImportError:
338
+ return ["doctor kimi requires Python 3.11+ (the hook adapter does not)"], None, None
339
+
340
+ try:
341
+ with config_path.open("rb") as config_file:
342
+ config = tomllib.load(config_file)
343
+ except OSError:
344
+ return problems + [f"cannot read Kimi config: {config_path}"], None, None
345
+ except tomllib.TOMLDecodeError:
346
+ return problems + [f"Kimi config is not valid TOML: {config_path}"], None, None
347
+
348
+ hooks = config.get("hooks", [])
349
+ if not isinstance(hooks, list):
350
+ return problems + ["Kimi config `hooks` must be an array"], None, None
351
+ candidates = [hook for hook in hooks
352
+ if isinstance(hook, dict)
353
+ and hook.get("event") == "PreToolUse"
354
+ and any(marker in str(hook.get("command", ""))
355
+ for marker in ("hook_bridge.sh", "pre_tool_use.py"))]
356
+ if not candidates:
357
+ return problems + ["no agent-guard PreToolUse hook found in Kimi config"], None, None
358
+ if len(candidates) != 1:
359
+ return problems + ["expected exactly one agent-guard PreToolUse hook"], None, None
360
+
361
+ hook = candidates[0]
362
+ if hook.get("matcher") != "^Bash$":
363
+ problems.append("matcher must be exactly ^Bash$ for this checked installation")
364
+ command_problems, bridge_command = _bridge_command(hook.get("command"), KIMI_BRIDGE)
365
+ problems.extend(command_problems)
366
+ timeout = hook.get("timeout", 30)
367
+ if (not isinstance(timeout, int) or isinstance(timeout, bool)
368
+ or not 1 <= timeout <= 600):
369
+ problems.append("hook timeout must be an integer from 1 to 600 seconds")
370
+
371
+ fingerprint = None
372
+ if not problems and bridge_command is not None:
373
+ dialect = resolve_dialect(
374
+ os.environ.get("AGENT_GUARD_DIALECT"),
375
+ source="env AGENT_GUARD_DIALECT").dialect
376
+ fingerprint = _fingerprint({
377
+ "schema_version": 1,
378
+ "harness": "kimi",
379
+ "event": hook.get("event"),
380
+ "matcher": hook.get("matcher"),
381
+ "command_tokens": [str(part) for part in bridge_command],
382
+ "timeout": timeout,
383
+ "dialect": dialect,
384
+ })
385
+ return problems, bridge_command, fingerprint
386
+
387
+
388
+ def _check_claude_config(
389
+ config_path: Path,
390
+ ) -> tuple[list[str], Optional[tuple[Path, Path, Path]], Optional[str]]:
391
+ problems = _dialect_problems()
392
+ try:
393
+ config = json.loads(config_path.read_text(encoding="utf-8"))
394
+ except (OSError, UnicodeError):
395
+ return problems + [f"cannot read Claude settings: {config_path}"], None, None
396
+ except json.JSONDecodeError:
397
+ return problems + [f"Claude settings is not valid JSON: {config_path}"], None, None
398
+ if not isinstance(config, dict):
399
+ return problems + ["Claude settings must be a JSON object"], None, None
400
+ if ("disableAllHooks" in config
401
+ and not isinstance(config["disableAllHooks"], bool)):
402
+ problems.append("selected Claude settings has invalid disableAllHooks value")
403
+ if config.get("disableAllHooks") is True:
404
+ problems.append("selected Claude settings has disableAllHooks=true")
405
+ hooks = config.get("hooks")
406
+ if not isinstance(hooks, dict):
407
+ return problems + ["Claude settings `hooks` must be an object"], None, None
408
+ pre_tool = hooks.get("PreToolUse")
409
+ if not isinstance(pre_tool, list):
410
+ return problems + ["Claude settings `hooks.PreToolUse` must be an array"], None, None
411
+
412
+ candidates = []
413
+ for group in pre_tool:
414
+ if not isinstance(group, dict) or not isinstance(group.get("hooks"), list):
415
+ continue
416
+ for handler in group["hooks"]:
417
+ if (isinstance(handler, dict)
418
+ and isinstance(handler.get("command"), str)
419
+ and any(marker in handler["command"]
420
+ for marker in ("hook_bridge.sh", "pre_tool_use.py"))):
421
+ candidates.append((group, handler))
422
+ if not candidates:
423
+ return problems + [
424
+ "no agent-guard PreToolUse hook found in selected Claude settings"], None, None
425
+ if len(candidates) != 1:
426
+ return problems + [
427
+ "expected exactly one agent-guard PreToolUse hook in selected Claude settings"], None, None
428
+
429
+ group, handler = candidates[0]
430
+ if group.get("matcher") != "Bash":
431
+ problems.append("Claude matcher must be exactly Bash for this checked installation")
432
+ if handler.get("type") != "command":
433
+ problems.append("Claude hook handler must have type=command")
434
+ if handler.get("async", False) is not False:
435
+ problems.append("Claude hook must be synchronous; async hooks cannot block")
436
+ if "if" in handler:
437
+ problems.append("Claude hook must not have an `if` filter that can skip Bash calls")
438
+ if handler.get("args"):
439
+ problems.append("Claude hook must not add separate `args` to the checked shell command")
440
+ timeout = handler.get("timeout", 600)
441
+ if not isinstance(timeout, int) or isinstance(timeout, bool) or timeout < 1:
442
+ problems.append("Claude hook timeout must be a positive integer")
443
+ command_problems, bridge_command = _bridge_command(handler.get("command"), CLAUDE_BRIDGE)
444
+ problems.extend(command_problems)
445
+ fingerprint = None
446
+ if not problems and bridge_command is not None:
447
+ dialect = resolve_dialect(
448
+ os.environ.get("AGENT_GUARD_DIALECT"),
449
+ source="env AGENT_GUARD_DIALECT").dialect
450
+ fingerprint = _fingerprint({
451
+ "schema_version": 1,
452
+ "harness": "claude",
453
+ "disable_all_hooks": bool(config.get("disableAllHooks", False)),
454
+ "event": "PreToolUse",
455
+ "matcher": group.get("matcher"),
456
+ "handler_type": handler.get("type"),
457
+ "async": bool(handler.get("async", False)),
458
+ "command_tokens": [str(part) for part in bridge_command],
459
+ "timeout": timeout,
460
+ "dialect": dialect,
461
+ })
462
+ return problems, bridge_command, fingerprint
463
+
464
+
465
+ def _load_baseline(path: Path, harness: str) -> tuple[Optional[dict], list[str]]:
466
+ try:
467
+ data = json.loads(path.read_text(encoding="utf-8"))
468
+ except (OSError, UnicodeError, json.JSONDecodeError):
469
+ return None, ["drift baseline cannot be read as JSON"]
470
+ required = {
471
+ "schema_version", "harness", "profile", "host_version",
472
+ "configuration_fingerprint", "runtime_fingerprint",
473
+ }
474
+ if (not isinstance(data, dict) or not required.issubset(data)
475
+ or data.get("schema_version") != 1
476
+ or data.get("harness") != harness
477
+ or not all(isinstance(data.get(key), str) and data[key]
478
+ for key in required - {"schema_version"})):
479
+ return None, ["drift baseline has an invalid shape or harness"]
480
+ for key in ("configuration_fingerprint", "runtime_fingerprint"):
481
+ if not re.fullmatch(r"sha256:[0-9a-f]{64}", data[key]):
482
+ return None, ["drift baseline has an invalid fingerprint"]
483
+ return data, []
484
+
485
+
486
+ def _write_baseline(path: Path, diagnosis: Diagnosis) -> Optional[str]:
487
+ if (diagnosis.drift_status != "CURRENT"
488
+ or diagnosis.local_probe != "PASS"
489
+ or not diagnosis.profile
490
+ or not diagnosis.host_version
491
+ or not diagnosis.configuration_fingerprint
492
+ or not diagnosis.runtime_fingerprint):
493
+ return "baseline requires CURRENT drift status and a passing local probe"
494
+ payload = {
495
+ "schema_version": 1,
496
+ "harness": diagnosis.harness,
497
+ "profile": diagnosis.profile,
498
+ "host_version": diagnosis.host_version,
499
+ "configuration_fingerprint": diagnosis.configuration_fingerprint,
500
+ "runtime_fingerprint": diagnosis.runtime_fingerprint,
501
+ }
502
+ try:
503
+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
504
+ with os.fdopen(descriptor, "w", encoding="utf-8") as baseline_file:
505
+ json.dump(payload, baseline_file, ensure_ascii=True, indent=2)
506
+ baseline_file.write("\n")
507
+ except OSError:
508
+ return "baseline path must have an existing parent and must not exist"
509
+ diagnosis.baseline_written = True
510
+ return None
511
+
512
+
513
+ def _diagnose(
514
+ harness: str, config_path: Path, run_probe: bool,
515
+ check_drift: bool = False, host_executable: Optional[str] = None,
516
+ baseline_path: Optional[Path] = None,
517
+ ) -> Diagnosis:
518
+ problems, bridge_command, configuration_fingerprint = (
519
+ _check_kimi_config(config_path) if harness == "kimi"
520
+ else _check_claude_config(config_path)
521
+ )
522
+ if problems:
523
+ diagnosis = Diagnosis(
524
+ harness, config_path, "FAIL", "NOT_RUN", problems,
525
+ configuration_fingerprint=configuration_fingerprint)
526
+ elif not run_probe:
527
+ diagnosis = Diagnosis(
528
+ harness, config_path, "PASS", "NOT_RUN", [],
529
+ configuration_fingerprint=configuration_fingerprint)
530
+ else:
531
+ assert bridge_command is not None
532
+ probe_problems = _probe(harness, *bridge_command)
533
+ diagnosis = Diagnosis(
534
+ harness, config_path, "PASS",
535
+ "FAIL" if probe_problems else "PASS", probe_problems,
536
+ configuration_fingerprint=configuration_fingerprint)
537
+
538
+ if not check_drift:
539
+ return diagnosis
540
+
541
+ drift_problems: list[str] = []
542
+ diagnosis.drift_problems = drift_problems
543
+ try:
544
+ profile = _load_profile(harness)
545
+ except ValueError as exc:
546
+ drift_problems.append(str(exc))
547
+ diagnosis.drift_status = "UNVERIFIED"
548
+ return diagnosis
549
+
550
+ diagnosis.profile = profile.profile_id
551
+ try:
552
+ diagnosis.runtime_fingerprint = _runtime_fingerprint(harness, profile)
553
+ except OSError:
554
+ drift_problems.append("runtime fingerprint could not be computed")
555
+
556
+ version, version_problem = _detect_host_version(profile, host_executable)
557
+ diagnosis.host_version = version
558
+ if version_problem:
559
+ drift_problems.append(version_problem)
560
+
561
+ baseline = None
562
+ baseline_invalid = False
563
+ if baseline_path is not None:
564
+ baseline, baseline_problems = _load_baseline(baseline_path, harness)
565
+ drift_problems.extend(baseline_problems)
566
+ baseline_invalid = baseline is None
567
+
568
+ if diagnosis.problems:
569
+ diagnosis.drift_status = "BROKEN"
570
+ elif baseline_invalid:
571
+ diagnosis.drift_status = "UNVERIFIED"
572
+ elif (not diagnosis.configuration_fingerprint
573
+ or not diagnosis.runtime_fingerprint):
574
+ diagnosis.drift_status = "UNVERIFIED"
575
+ elif baseline is not None and (
576
+ baseline["profile"] != diagnosis.profile
577
+ or baseline["configuration_fingerprint"]
578
+ != diagnosis.configuration_fingerprint
579
+ or baseline["runtime_fingerprint"] != diagnosis.runtime_fingerprint):
580
+ diagnosis.drift_status = "DRIFTED"
581
+ if baseline["profile"] != diagnosis.profile:
582
+ drift_problems.append("compatibility profile changed since baseline")
583
+ if (baseline["configuration_fingerprint"]
584
+ != diagnosis.configuration_fingerprint):
585
+ drift_problems.append("hook configuration changed since baseline")
586
+ if baseline["runtime_fingerprint"] != diagnosis.runtime_fingerprint:
587
+ drift_problems.append("guard runtime changed since baseline")
588
+ elif version is None:
589
+ diagnosis.drift_status = "UNVERIFIED"
590
+ elif (baseline is not None and baseline["host_version"] != version):
591
+ diagnosis.drift_status = "STALE"
592
+ drift_problems.append("host version changed since baseline")
593
+ elif version not in profile.tested_versions:
594
+ diagnosis.drift_status = "STALE"
595
+ drift_problems.append("host version is outside the tested profile")
596
+ else:
597
+ diagnosis.drift_status = "CURRENT"
598
+ return diagnosis
599
+
600
+
601
+ def check_kimi(config_path: Path, run_probe: bool = False) -> list[str]:
602
+ """Compatibility wrapper for callers using the original Kimi checker."""
603
+ return _diagnose("kimi", config_path, run_probe).problems
604
+
605
+
606
+ def check_claude(config_path: Path, run_probe: bool = False) -> list[str]:
607
+ return _diagnose("claude", config_path, run_probe).problems
608
+
609
+
610
+ def main(argv: Optional[list[str]] = None) -> int:
611
+ parser = argparse.ArgumentParser(description=__doc__)
612
+ subcommands = parser.add_subparsers(dest="harness", required=True)
613
+ kimi = subcommands.add_parser("kimi", help="check the local Kimi hook")
614
+ kimi.add_argument(
615
+ "--config", help="Kimi config.toml (defaults to KIMI_CODE_HOME or ~/.kimi-code)")
616
+ claude = subcommands.add_parser("claude", help="check a selected Claude settings file")
617
+ claude.add_argument(
618
+ "--config", help="Claude settings.json (defaults to .claude/settings.json in cwd)")
619
+ for command in (kimi, claude):
620
+ command.add_argument(
621
+ "--probe", action="store_true",
622
+ help="exercise the local bridge on harmless payloads; no model call",
623
+ )
624
+ command.add_argument("--json", action="store_true", help="print machine-readable status")
625
+ command.add_argument(
626
+ "--check-drift", action="store_true",
627
+ help="query the local host version and compute privacy-safe fingerprints",
628
+ )
629
+ command.add_argument(
630
+ "--host-executable",
631
+ help="host executable name/path for --check-drift (defaults to profile candidates)",
632
+ )
633
+ command.add_argument(
634
+ "--baseline", type=Path,
635
+ help="compare --check-drift fingerprints with an existing baseline JSON",
636
+ )
637
+ command.add_argument(
638
+ "--write-baseline", type=Path,
639
+ help="create a new 0600 baseline (requires --probe and CURRENT status)",
640
+ )
641
+ command.add_argument(
642
+ "--live-sentinel", action="store_true",
643
+ help="run one real-host model/tool probe; may consume configured provider quota",
644
+ )
645
+ command.add_argument(
646
+ "--sentinel-output", type=Path,
647
+ help="new evidence directory for --live-sentinel (default: private temp dir)",
648
+ )
649
+ command.add_argument(
650
+ "--sentinel-timeout", type=int, default=180, metavar="SECONDS",
651
+ help="live sentinel timeout, 15..600 seconds (default: 180)",
652
+ )
653
+ args = parser.parse_args(argv)
654
+ if args.write_baseline is not None and not args.probe:
655
+ parser.error("--write-baseline requires --probe")
656
+ if args.live_sentinel and args.write_baseline is not None:
657
+ parser.error("--live-sentinel and --write-baseline must be separate runs")
658
+ if args.sentinel_output is not None and not args.live_sentinel:
659
+ parser.error("--sentinel-output requires --live-sentinel")
660
+ if not 15 <= args.sentinel_timeout <= 600:
661
+ parser.error("--sentinel-timeout must be from 15 to 600 seconds")
662
+ check_drift = bool(
663
+ args.check_drift or args.host_executable
664
+ or args.baseline is not None or args.write_baseline is not None
665
+ or args.live_sentinel)
666
+ config_path = (
667
+ _kimi_config_path(args.config) if args.harness == "kimi"
668
+ else _claude_config_path(args.config)
669
+ )
670
+ diagnosis = _diagnose(
671
+ args.harness, config_path, args.probe or args.live_sentinel, check_drift,
672
+ args.host_executable,
673
+ args.baseline.expanduser() if args.baseline is not None else None,
674
+ )
675
+ write_error = None
676
+ if args.write_baseline is not None:
677
+ write_error = _write_baseline(args.write_baseline.expanduser(), diagnosis)
678
+ if write_error:
679
+ if diagnosis.drift_problems is None:
680
+ diagnosis.drift_problems = []
681
+ diagnosis.drift_problems.append(write_error)
682
+ sentinel_result = None
683
+ sentinel_report = None
684
+ if args.live_sentinel:
685
+ if (diagnosis.configuration != "PASS"
686
+ or diagnosis.local_probe != "PASS"):
687
+ sentinel_report = {
688
+ "status": "INCONCLUSIVE", "alarm": "WARNING",
689
+ "reason": "LOCAL_PREFLIGHT_FAILED",
690
+ }
691
+ elif diagnosis.host_version is None:
692
+ sentinel_report = {
693
+ "status": "INCONCLUSIVE", "alarm": "WARNING",
694
+ "reason": "HOST_VERSION_UNVERIFIED",
695
+ }
696
+ else:
697
+ try:
698
+ from live_sentinel import run_live_sentinel
699
+ profile = _load_profile(args.harness)
700
+ sentinel_result = run_live_sentinel(
701
+ args.harness, config_path, profile.executable_candidates,
702
+ host_executable=args.host_executable,
703
+ output_dir=(args.sentinel_output.expanduser()
704
+ if args.sentinel_output is not None else None),
705
+ timeout=args.sentinel_timeout,
706
+ drift_status=diagnosis.drift_status,
707
+ )
708
+ sentinel_report = sentinel_result.as_dict()
709
+ except (OSError, ValueError):
710
+ sentinel_report = {
711
+ "status": "INCONCLUSIVE", "alarm": "WARNING",
712
+ "reason": "SENTINEL_SETUP_FAILED",
713
+ }
714
+ if args.json:
715
+ report = diagnosis.as_dict()
716
+ if sentinel_report is not None:
717
+ report["live_sentinel"] = sentinel_report
718
+ print(json.dumps(report, ensure_ascii=False))
719
+ if sentinel_report is not None:
720
+ return {"PASS": 0, "FAIL": 2}.get(sentinel_report["status"], 1)
721
+ return 1 if (diagnosis.problems or write_error or (
722
+ check_drift and diagnosis.drift_status != "CURRENT")) else 0
723
+ if diagnosis.problems:
724
+ for problem in diagnosis.problems:
725
+ print(f"FAIL: {problem}", file=sys.stderr)
726
+ else:
727
+ print(f"PASS: {args.harness} selected hook configuration shape checked ({config_path})")
728
+ if diagnosis.local_probe == "PASS":
729
+ print("PASS: local Bash allow, malformed refusal, Core policy refusal, "
730
+ "ASK mapping, and failed-interpreter probes")
731
+ else:
732
+ print(f"LOCAL_PROBE: {diagnosis.local_probe}")
733
+ print("HOST_INTERCEPTION: UNVERIFIED (the selected file and local bridge "
734
+ "do not prove a live host loaded or enforced this hook)")
735
+ if check_drift:
736
+ print(f"HOST_VERSION: {diagnosis.host_version or 'UNVERIFIED'}")
737
+ print(f"DRIFT_STATUS: {diagnosis.drift_status}")
738
+ for problem in diagnosis.drift_problems or []:
739
+ print(f"DRIFT: {problem}", file=sys.stderr)
740
+ if diagnosis.baseline_written:
741
+ print("BASELINE: WRITTEN (fingerprints only; not host interception proof)")
742
+ if sentinel_report is not None:
743
+ print(f"LIVE_SENTINEL: {sentinel_report['status']}")
744
+ print(f"ALARM: {sentinel_report['alarm']}")
745
+ print(f"SENTINEL_REASON: {sentinel_report['reason']}")
746
+ if sentinel_result is not None:
747
+ print(f"EVIDENCE_DIR: {sentinel_result.evidence_dir}")
748
+ if sentinel_report["status"] != "PASS":
749
+ print("WARNING: live host protection was not verified", file=sys.stderr)
750
+ return {"PASS": 0, "FAIL": 2}.get(sentinel_report["status"], 1)
751
+ return 1 if (diagnosis.problems or write_error or (
752
+ check_drift and diagnosis.drift_status != "CURRENT")) else 0
753
+
754
+
755
+ if __name__ == "__main__":
756
+ sys.exit(main())