@mokuyoaxis/agent-guard 0.2.5 → 0.2.6

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/doctor.py CHANGED
@@ -22,6 +22,7 @@ from core.dialects import resolve_dialect
22
22
 
23
23
  ROOT = Path(__file__).resolve().parent
24
24
  KIMI_BRIDGE = ROOT / "adapters" / "kimi-code" / "hook_bridge.sh"
25
+ KIMI_FEEDBACK = ROOT / "adapters" / "kimi-code" / "stop_feedback.py"
25
26
  CLAUDE_BRIDGE = ROOT / "adapters" / "claude" / "hook_bridge.sh"
26
27
  PROFILE_PATHS = {
27
28
  "kimi": ROOT / "adapters" / "kimi-code" / "compatibility.json",
@@ -41,6 +42,29 @@ class HostProfile:
41
42
  path: Path
42
43
 
43
44
 
45
+ @dataclass
46
+ class FeedbackDiagnosis:
47
+ configured: Optional[bool]
48
+ configuration: str
49
+ local_probe: str
50
+ problems: list[str]
51
+ command: Optional[tuple[Path, Path, Path]] = None
52
+ fingerprint: Optional[str] = None
53
+
54
+ @property
55
+ def failed(self) -> bool:
56
+ return self.configuration == "FAIL" or self.local_probe == "FAIL"
57
+
58
+ def as_dict(self) -> dict:
59
+ return {
60
+ "configured": self.configured,
61
+ "configuration": self.configuration,
62
+ "local_probe": self.local_probe,
63
+ "model_delivery": "UNVERIFIED",
64
+ "problems": self.problems,
65
+ }
66
+
67
+
44
68
  @dataclass
45
69
  class Diagnosis:
46
70
  harness: str
@@ -55,9 +79,14 @@ class Diagnosis:
55
79
  runtime_fingerprint: Optional[str] = None
56
80
  drift_problems: Optional[list[str]] = None
57
81
  baseline_written: bool = False
82
+ feedback: Optional[FeedbackDiagnosis] = None
83
+
84
+ @property
85
+ def failed(self) -> bool:
86
+ return bool(self.problems or self.feedback and self.feedback.failed)
58
87
 
59
88
  def as_dict(self) -> dict:
60
- return {
89
+ report = {
61
90
  "harness": self.harness,
62
91
  "configuration": self.configuration,
63
92
  "local_probe": self.local_probe,
@@ -71,6 +100,9 @@ class Diagnosis:
71
100
  "drift_problems": self.drift_problems or [],
72
101
  "baseline_written": self.baseline_written,
73
102
  }
103
+ if self.feedback is not None:
104
+ report["feedback"] = self.feedback.as_dict()
105
+ return report
74
106
 
75
107
 
76
108
  def _load_profile(harness: str) -> HostProfile:
@@ -119,7 +151,9 @@ def _fingerprint(value: Any) -> str:
119
151
  return "sha256:" + hashlib.sha256(encoded).hexdigest()
120
152
 
121
153
 
122
- def _runtime_fingerprint(harness: str, profile: HostProfile) -> str:
154
+ def _runtime_fingerprint(
155
+ harness: str, profile: HostProfile, include_feedback: bool = False,
156
+ ) -> str:
123
157
  paths = {
124
158
  ROOT / "package.json",
125
159
  profile.path,
@@ -138,6 +172,8 @@ def _runtime_fingerprint(harness: str, profile: HostProfile) -> str:
138
172
  ROOT / "adapters" / "kimi-code" / "pre_tool_use.py",
139
173
  ROOT / "adapters" / "claude" / "pre_tool_use.py",
140
174
  })
175
+ if include_feedback:
176
+ paths.add(KIMI_FEEDBACK)
141
177
  digest = hashlib.sha256()
142
178
  for path in sorted(paths, key=lambda item: str(item.relative_to(ROOT))):
143
179
  relative = str(path.relative_to(ROOT)).encode("utf-8")
@@ -218,7 +254,7 @@ def _executable(path: Path) -> bool:
218
254
 
219
255
 
220
256
  def _bridge_command(
221
- command: object, expected_bridge: Path,
257
+ command: object, expected_bridge: Path, *, stop_feedback: bool = False,
222
258
  ) -> tuple[list[str], Optional[tuple[Path, Path, Path]]]:
223
259
  if not isinstance(command, str):
224
260
  return ["hook command must be a string"], None
@@ -226,6 +262,10 @@ def _bridge_command(
226
262
  tokens = _command_tokens(command)
227
263
  except ValueError:
228
264
  return ["hook command has invalid shell quoting"], None
265
+ if stop_feedback:
266
+ if len(tokens) != 4 or tokens[-1] != "--stop-feedback":
267
+ return ["Stop command must be: ABSOLUTE_SH ABSOLUTE_BRIDGE ABSOLUTE_PYTHON --stop-feedback"], None
268
+ tokens = tokens[:-1]
229
269
  if len(tokens) != 3 or not all(Path(part).is_absolute() for part in tokens):
230
270
  return ["hook command must be: ABSOLUTE_SH ABSOLUTE_BRIDGE ABSOLUTE_PYTHON"], None
231
271
 
@@ -257,10 +297,10 @@ def _probe(harness: str, shell: Path, bridge: Path, python: Path) -> list[str]:
257
297
  "tool_input": {"command": "touch .guard-doctor-ask && rm .guard-doctor-ask"},
258
298
  "cwd": cwd,
259
299
  })
260
- probe_env = dict(os.environ)
261
- probe_env.pop("AGENT_GUARD_DIALECT", None)
262
- probe_env.pop("AGENT_GUARD_SESSION", None)
300
+ probe_env = {key: value for key, value in os.environ.items()
301
+ if not key.startswith("AGENT_GUARD_")}
263
302
  probe_env["AGENT_GUARD_WORKSPACE"] = cwd
303
+ probe_env["AGENT_GUARD_TRASH"] = str(Path(cwd) / ".agent-trash")
264
304
  cases = (
265
305
  (python, payload, 0, "valid Bash payload", None, None),
266
306
  (python, "{", 2, "malformed payload", None, "malformed hook payload"),
@@ -327,36 +367,85 @@ def _dialect_problems() -> list[str]:
327
367
  return []
328
368
 
329
369
 
370
+ def _probe_feedback(shell: Path, bridge: Path, python: Path) -> list[str]:
371
+ from core import AUDIT_NAME, audit
372
+
373
+ with tempfile.TemporaryDirectory(prefix="agent-guard-doctor-feedback-") as temporary:
374
+ workspace = Path(temporary)
375
+ home, trash = workspace / "home", workspace / "trash"
376
+ home.mkdir()
377
+ trash.mkdir()
378
+ env = {key: value for key, value in os.environ.items()
379
+ if not key.startswith("AGENT_GUARD_")}
380
+ env.update(HOME=str(home), KIMI_CODE_HOME=str(home / "kimi"),
381
+ AGENT_GUARD_WORKSPACE=temporary, AGENT_GUARD_TRASH=str(trash))
382
+ session = "agent-guard-doctor-feedback-probe"
383
+ txid = "20000101-000000-00000000"
384
+ record = json.dumps({
385
+ "event": "enforce-proceed", "session": audit.correlation_id(session),
386
+ "compensations": [{"strategy": "relocate", "txid": txid,
387
+ "status": "complete", "moved": 1, "skipped": 0}],
388
+ }) + "\n"
389
+ audit_path = trash / AUDIT_NAME
390
+ for label, active, expected in (
391
+ ("no records", False, 0), ("active Stop", True, 0),
392
+ ("synthetic recovery feedback", False, 2), ("repeat Stop", False, 0)):
393
+ if active:
394
+ audit_path.write_text(record, encoding="utf-8")
395
+ payload = json.dumps({"hook_event_name": "Stop", "cwd": temporary,
396
+ "session_id": session, "stop_hook_active": active})
397
+ try:
398
+ result = subprocess.run(
399
+ [str(shell), str(bridge), str(python), "--stop-feedback"],
400
+ input=payload, text=True, capture_output=True, cwd=temporary,
401
+ env=env, timeout=15, errors="replace")
402
+ except (OSError, subprocess.TimeoutExpired):
403
+ return [f"{label}: Stop bridge could not finish"]
404
+ if result.returncode != expected:
405
+ return [f"{label}: expected exit {expected}, got {result.returncode}"]
406
+ if result.stdout:
407
+ return [f"{label}: Stop wrote unexpected stdout"]
408
+ if expected == 0 and result.stderr:
409
+ return [f"{label}: expected silent Stop"]
410
+ if expected == 2 and not all(marker in result.stderr for marker in (
411
+ "[agent-guard] Recovery records", txid, "still use disk space",
412
+ "GC preview:", "--execute --txid " + txid)):
413
+ return [f"{label}: expected transaction, retained-space and complete GC guidance"]
414
+ if audit_path.read_text(encoding="utf-8") != record:
415
+ return ["Stop probe changed its synthetic recovery audit"]
416
+ return []
417
+
418
+
330
419
  def _check_kimi_config(
331
420
  config_path: Path,
332
- ) -> tuple[list[str], Optional[tuple[Path, Path, Path]], Optional[str]]:
421
+ ) -> tuple[list[str], Optional[tuple[Path, Path, Path]], Optional[str], Optional[dict]]:
333
422
  problems: list[str] = []
334
423
  problems.extend(_dialect_problems())
335
424
  try:
336
425
  import tomllib
337
426
  except ImportError:
338
- return ["doctor kimi requires Python 3.11+ (the hook adapter does not)"], None, None
427
+ return ["doctor kimi requires Python 3.11+ (the hook adapter does not)"], None, None, None
339
428
 
340
429
  try:
341
430
  with config_path.open("rb") as config_file:
342
431
  config = tomllib.load(config_file)
343
432
  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
433
+ return problems + [f"cannot read Kimi config: {config_path}"], None, None, None
434
+ except (tomllib.TOMLDecodeError, UnicodeError):
435
+ return problems + [f"Kimi config is not valid TOML: {config_path}"], None, None, None
347
436
 
348
437
  hooks = config.get("hooks", [])
349
438
  if not isinstance(hooks, list):
350
- return problems + ["Kimi config `hooks` must be an array"], None, None
439
+ return problems + ["Kimi config `hooks` must be an array"], None, None, config
351
440
  candidates = [hook for hook in hooks
352
441
  if isinstance(hook, dict)
353
442
  and hook.get("event") == "PreToolUse"
354
443
  and any(marker in str(hook.get("command", ""))
355
444
  for marker in ("hook_bridge.sh", "pre_tool_use.py"))]
356
445
  if not candidates:
357
- return problems + ["no agent-guard PreToolUse hook found in Kimi config"], None, None
446
+ return problems + ["no agent-guard PreToolUse hook found in Kimi config"], None, None, config
358
447
  if len(candidates) != 1:
359
- return problems + ["expected exactly one agent-guard PreToolUse hook"], None, None
448
+ return problems + ["expected exactly one agent-guard PreToolUse hook"], None, None, config
360
449
 
361
450
  hook = candidates[0]
362
451
  if hook.get("matcher") != "^Bash$":
@@ -382,7 +471,45 @@ def _check_kimi_config(
382
471
  "timeout": timeout,
383
472
  "dialect": dialect,
384
473
  })
385
- return problems, bridge_command, fingerprint
474
+ return problems, bridge_command, fingerprint, config
475
+
476
+
477
+ def _check_kimi_feedback(config: Optional[dict]) -> FeedbackDiagnosis:
478
+ if config is None or not isinstance(config.get("hooks", []), list):
479
+ return FeedbackDiagnosis(None, "UNVERIFIED", "NOT_RUN", [
480
+ "optional Stop could not be checked because the Kimi config is unreadable or invalid"])
481
+ candidates = [hook for hook in config.get("hooks", [])
482
+ if isinstance(hook, dict) and (
483
+ any(marker in str(hook.get("command", ""))
484
+ for marker in ("stop_feedback.py", "--stop-feedback"))
485
+ or hook.get("event") == "Stop"
486
+ and "hook_bridge.sh" in str(hook.get("command", "")))]
487
+ if not candidates:
488
+ return FeedbackDiagnosis(False, "NOT_CONFIGURED", "NOT_RUN", [])
489
+ if len(candidates) != 1:
490
+ return FeedbackDiagnosis(True, "FAIL", "NOT_RUN", [
491
+ "expected exactly one agent-guard Stop hook"])
492
+ hook = candidates[0]
493
+ problems, command = _bridge_command(
494
+ hook.get("command"), KIMI_BRIDGE, stop_feedback=True)
495
+ if hook.get("event") != "Stop":
496
+ problems.append("recovery feedback hook event must be exactly Stop")
497
+ if "matcher" in hook and hook["matcher"] != "":
498
+ problems.append("Stop matcher must be absent or empty; Bash filters do not cover Stop")
499
+ timeout = hook.get("timeout", 30)
500
+ if type(timeout) is not int or not 1 <= timeout <= 600:
501
+ problems.append("Stop timeout must be an integer from 1 to 600 seconds")
502
+ if not KIMI_FEEDBACK.is_file():
503
+ problems.append("stop_feedback.py is missing from this installation")
504
+ fingerprint = None
505
+ if not problems:
506
+ assert command is not None
507
+ fingerprint = _fingerprint({
508
+ "event": "Stop", "command_tokens": [str(part) for part in command] + ["--stop-feedback"],
509
+ "matcher": hook.get("matcher", ""), "timeout": timeout,
510
+ })
511
+ return FeedbackDiagnosis(True, "FAIL" if problems else "PASS", "NOT_RUN",
512
+ problems, command, fingerprint)
386
513
 
387
514
 
388
515
  def _check_claude_config(
@@ -484,7 +611,7 @@ def _load_baseline(path: Path, harness: str) -> tuple[Optional[dict], list[str]]
484
611
 
485
612
 
486
613
  def _write_baseline(path: Path, diagnosis: Diagnosis) -> Optional[str]:
487
- if (diagnosis.drift_status != "CURRENT"
614
+ if (diagnosis.failed or diagnosis.drift_status != "CURRENT"
488
615
  or diagnosis.local_probe != "PASS"
489
616
  or not diagnosis.profile
490
617
  or not diagnosis.host_version
@@ -514,11 +641,22 @@ def _diagnose(
514
641
  harness: str, config_path: Path, run_probe: bool,
515
642
  check_drift: bool = False, host_executable: Optional[str] = None,
516
643
  baseline_path: Optional[Path] = None,
644
+ *, include_feedback: bool = True,
517
645
  ) -> Diagnosis:
518
- problems, bridge_command, configuration_fingerprint = (
519
- _check_kimi_config(config_path) if harness == "kimi"
520
- else _check_claude_config(config_path)
521
- )
646
+ feedback = None
647
+ if harness == "kimi":
648
+ problems, bridge_command, configuration_fingerprint, config = _check_kimi_config(config_path)
649
+ if include_feedback:
650
+ feedback = _check_kimi_feedback(config)
651
+ if feedback.configuration == "PASS" and configuration_fingerprint:
652
+ configuration_fingerprint = _fingerprint({
653
+ "pre_tool_use": configuration_fingerprint, "feedback": feedback.fingerprint})
654
+ if feedback.configuration == "PASS" and run_probe:
655
+ assert feedback.command is not None
656
+ feedback.problems = _probe_feedback(*feedback.command)
657
+ feedback.local_probe = "FAIL" if feedback.problems else "PASS"
658
+ else:
659
+ problems, bridge_command, configuration_fingerprint = _check_claude_config(config_path)
522
660
  if problems:
523
661
  diagnosis = Diagnosis(
524
662
  harness, config_path, "FAIL", "NOT_RUN", problems,
@@ -534,6 +672,7 @@ def _diagnose(
534
672
  harness, config_path, "PASS",
535
673
  "FAIL" if probe_problems else "PASS", probe_problems,
536
674
  configuration_fingerprint=configuration_fingerprint)
675
+ diagnosis.feedback = feedback
537
676
 
538
677
  if not check_drift:
539
678
  return diagnosis
@@ -549,7 +688,8 @@ def _diagnose(
549
688
 
550
689
  diagnosis.profile = profile.profile_id
551
690
  try:
552
- diagnosis.runtime_fingerprint = _runtime_fingerprint(harness, profile)
691
+ diagnosis.runtime_fingerprint = _runtime_fingerprint(
692
+ harness, profile, bool(feedback and feedback.configured))
553
693
  except OSError:
554
694
  drift_problems.append("runtime fingerprint could not be computed")
555
695
 
@@ -565,7 +705,7 @@ def _diagnose(
565
705
  drift_problems.extend(baseline_problems)
566
706
  baseline_invalid = baseline is None
567
707
 
568
- if diagnosis.problems:
708
+ if diagnosis.failed:
569
709
  diagnosis.drift_status = "BROKEN"
570
710
  elif baseline_invalid:
571
711
  diagnosis.drift_status = "UNVERIFIED"
@@ -599,8 +739,8 @@ def _diagnose(
599
739
 
600
740
 
601
741
  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
742
+ """Compatibility wrapper retaining the original PreToolUse-only check."""
743
+ return _diagnose("kimi", config_path, run_probe, include_feedback=False).problems
604
744
 
605
745
 
606
746
  def check_claude(config_path: Path, run_probe: bool = False) -> list[str]:
@@ -682,7 +822,7 @@ def main(argv: Optional[list[str]] = None) -> int:
682
822
  sentinel_result = None
683
823
  sentinel_report = None
684
824
  if args.live_sentinel:
685
- if (diagnosis.configuration != "PASS"
825
+ if (diagnosis.failed or diagnosis.configuration != "PASS"
686
826
  or diagnosis.local_probe != "PASS"):
687
827
  sentinel_report = {
688
828
  "status": "INCONCLUSIVE", "alarm": "WARNING",
@@ -718,18 +858,25 @@ def main(argv: Optional[list[str]] = None) -> int:
718
858
  print(json.dumps(report, ensure_ascii=False))
719
859
  if sentinel_report is not None:
720
860
  return {"PASS": 0, "FAIL": 2}.get(sentinel_report["status"], 1)
721
- return 1 if (diagnosis.problems or write_error or (
861
+ return 1 if (diagnosis.failed or write_error or (
722
862
  check_drift and diagnosis.drift_status != "CURRENT")) else 0
723
863
  if diagnosis.problems:
724
864
  for problem in diagnosis.problems:
725
865
  print(f"FAIL: {problem}", file=sys.stderr)
726
866
  else:
727
- print(f"PASS: {args.harness} selected hook configuration shape checked ({config_path})")
867
+ scope = "PreToolUse" if args.harness == "kimi" else "selected hook"
868
+ print(f"PASS: {args.harness} {scope} configuration shape checked ({config_path})")
728
869
  if diagnosis.local_probe == "PASS":
729
870
  print("PASS: local Bash allow, malformed refusal, Core policy refusal, "
730
871
  "ASK mapping, and failed-interpreter probes")
731
872
  else:
732
873
  print(f"LOCAL_PROBE: {diagnosis.local_probe}")
874
+ if diagnosis.feedback is not None:
875
+ print(f"FEEDBACK_CONFIGURATION: {diagnosis.feedback.configuration} (optional Kimi Stop)")
876
+ print(f"FEEDBACK_LOCAL_PROBE: {diagnosis.feedback.local_probe}")
877
+ for problem in diagnosis.feedback.problems:
878
+ print(f"FEEDBACK_FAIL: {problem}", file=sys.stderr)
879
+ print("MODEL_DELIVERY: UNVERIFIED (local Stop checks do not prove model receipt)")
733
880
  print("HOST_INTERCEPTION: UNVERIFIED (the selected file and local bridge "
734
881
  "do not prove a live host loaded or enforced this hook)")
735
882
  if check_drift:
@@ -748,7 +895,7 @@ def main(argv: Optional[list[str]] = None) -> int:
748
895
  if sentinel_report["status"] != "PASS":
749
896
  print("WARNING: live host protection was not verified", file=sys.stderr)
750
897
  return {"PASS": 0, "FAIL": 2}.get(sentinel_report["status"], 1)
751
- return 1 if (diagnosis.problems or write_error or (
898
+ return 1 if (diagnosis.failed or write_error or (
752
899
  check_drift and diagnosis.drift_status != "CURRENT")) else 0
753
900
 
754
901
 
package/package.json CHANGED
@@ -1,8 +1,17 @@
1
1
  {
2
2
  "name": "@mokuyoaxis/agent-guard",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
4
4
  "description": "Harness-neutral reliability infrastructure for AI coding agents: recoverable destructive actions, disclosure checks, controlled synthetic behaviour experiments, and a shared Core with optional native adapters.",
5
5
  "type": "module",
6
+ "engines": {
7
+ "dsh": "0.1.5-rc.1 || 0.2.0-rc.2 || 0.2.1-alpha.4"
8
+ },
9
+ "peerDependencies": {
10
+ "@deepseek-ai/dsh": "0.1.5-rc.1 || 0.2.0-rc.2 || 0.2.1-alpha.4"
11
+ },
12
+ "peerDependenciesMeta": {
13
+ "@deepseek-ai/dsh": { "optional": true }
14
+ },
6
15
  "main": "./adapters/dsh/lib/index.js",
7
16
  "exports": {
8
17
  ".": "./adapters/dsh/lib/index.js",
@@ -46,7 +55,7 @@
46
55
  ],
47
56
  "dsh": {
48
57
  "engines": {
49
- "dsh": "0.1.5-rc.1 || 0.2.0-rc.2"
58
+ "dsh": "0.1.5-rc.1 || 0.2.0-rc.2 || 0.2.1-alpha.4"
50
59
  },
51
60
  "bundle": {
52
61
  "patch": "./adapters/dsh/cordis.patch.yml"