@mokuyoaxis/agent-guard 0.2.5 → 0.2.7

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 (52) hide show
  1. package/README.md +61 -23
  2. package/README.zh-CN.md +51 -22
  3. package/adapters/INTEGRATION.md +90 -10
  4. package/adapters/claude/README.md +6 -0
  5. package/adapters/dsh/README.md +19 -8
  6. package/adapters/dsh/compatibility.json +14 -0
  7. package/adapters/dsh/harness/README.md +11 -0
  8. package/adapters/dsh/harness/guard_lab.py +42 -14
  9. package/adapters/kimi-code/README.md +154 -14
  10. package/adapters/kimi-code/compatibility.json +1 -1
  11. package/adapters/kimi-code/config.example.toml +18 -6
  12. package/adapters/kimi-code/hook_bridge.sh +19 -4
  13. package/adapters/kimi-code/pre_tool_use.py +1 -1
  14. package/adapters/kimi-code/stop_feedback.py +237 -0
  15. package/adapters/mcp/__init__.py +1 -0
  16. package/adapters/mcp/operations.py +174 -0
  17. package/adapters/mcp/requirements.txt +3 -0
  18. package/adapters/mcp/server.py +126 -0
  19. package/core/admission.py +388 -0
  20. package/core/audit.py +1 -1
  21. package/core/classifier.py +2 -1
  22. package/core/cleanup.py +297 -0
  23. package/core/delete_config.py +153 -0
  24. package/core/policy.py +35 -7
  25. package/core/recovery.py +10 -0
  26. package/docs/README.md +25 -7
  27. package/docs/design/architecture.md +16 -4
  28. package/docs/design/compatibility.md +230 -6
  29. package/docs/design/dsh-compatibility.md +65 -0
  30. package/docs/design/threat-model.md +53 -1
  31. package/docs/guides/cleanup-plan.md +227 -0
  32. package/docs/guides/deletion-limits.md +150 -0
  33. package/docs/guides/getting-started.md +72 -11
  34. package/docs/guides/harness-capabilities.md +37 -4
  35. package/docs/guides/host-drift.md +32 -0
  36. package/docs/guides/mcp.md +293 -0
  37. package/docs/guides/recovery-feedback.md +29 -1
  38. package/docs/history/friction.md +99 -1
  39. package/docs/releases/release-notes-0.2.6.md +167 -0
  40. package/docs/releases/release-notes-0.2.7.md +217 -0
  41. package/docs/releases/unreleased.md +275 -0
  42. package/docs/reports/test-report-dsh-alpha4.md +102 -0
  43. package/docs/reports/test-report-dsh-paired-lab.md +1 -1
  44. package/docs/reports/test-report-kimi-code-block.md +120 -7
  45. package/doctor.py +175 -28
  46. package/package.json +13 -2
  47. package/skills/delete-guard/SKILL.md +69 -1
  48. package/skills/delete-guard/references/policy.md +66 -3
  49. package/skills/delete-guard/scripts/check.py +39 -9
  50. package/skills/delete-guard/scripts/cleanup.py +164 -0
  51. package/skills/delete-guard/scripts/safe_delete.py +22 -4
  52. package/skills/delete-guard/scripts/status.py +77 -1
@@ -10,13 +10,28 @@ payload field names and decision contract are field-compatible with Claude
10
10
  Code's hooks, so `pre_tool_use.py` here delegates to
11
11
  `../claude/pre_tool_use.py` instead of reimplementing the mapping.
12
12
 
13
- Verified against **@moonshot-ai/kimi-code 0.42.0 and 2.1.1**. The detailed
13
+ Verified against **@moonshot-ai/kimi-code 0.42.0, 2.1.1 and 2.3.0**. The detailed
14
14
  contract comparison below was established against 0.42.0; the 2.1.1 trials
15
15
  independently observed authenticated root `Bash` blocks through the same
16
16
  exit-2 hook path on an OAuth official model and a second configured model
17
17
  route. Connection details and private route identifiers are omitted. See the
18
18
  [bounded report](../../docs/reports/test-report-kimi-code-block.md).
19
19
 
20
+ Version 0.2.6 adds exact **2.3.0** after eight prompt-CLI and eight
21
+ ACP root-Bash trials with fixed loopback responses, including BLOCK, ASK
22
+ refusal, Python startup failure, recovery and Stop delivery. ACP hooks ran
23
+ in the session workspace even when the server started elsewhere. There were
24
+ no external model calls. See the [2.3.0 evidence and limits](../../docs/reports/test-report-kimi-code-block.md#kimi-230-acceptance).
25
+ This does not extend subagent, other-tool or real-model claims; the separate
26
+ [Lab helper](harness/README.md) remains pinned to 2.1.1. Published 0.2.5 keeps
27
+ its earlier tested-version list.
28
+
29
+ This README describes [0.2.6](../../docs/releases/release-notes-0.2.6.md).
30
+ The optional Stop helper, doctor checks and setup guidance ship in this version;
31
+ see the [maintenance details](../../docs/releases/unreleased.md).
32
+ Version 0.2.5 retains its recorded scope. Upgrade the selected installation
33
+ before configuring Stop.
34
+
20
35
  For the separate honeytoken experiment, see the
21
36
  [guard-lab pair and local follow-up](../../docs/reports/test-report-kimi-guard-lab.md).
22
37
  Its recorded tool-channel exposure and matched guarded observation are distinct
@@ -46,8 +61,12 @@ allowed. `blockDecision()` collects any hook result with `action === "block"`.
46
61
 
47
62
  ## Install
48
63
 
49
- 1. Add the hook and the skill root to `~/.kimi-code/config.toml` — see
50
- [`config.example.toml`](config.example.toml). `matcher` is a **regular
64
+ 1. Merge the hook and skill root into `~/.kimi-code/config.toml` — see
65
+ [`config.example.toml`](config.example.toml). Place the top-level
66
+ `extraSkillDirs` before the first TOML table, or extend its existing array;
67
+ append the `[[hooks]]` blocks separately. Appending the entire example
68
+ after an existing table puts `extraSkillDirs` inside that table.
69
+ `matcher` is a **regular
51
70
  expression** matched against the tool name; an empty string matches every
52
71
  tool. Use `^Bash$` to select only the shell tool. An unanchored `Bash`
53
72
  pattern can also match future tool names containing that word. The example
@@ -64,19 +83,30 @@ allowed. `blockDecision()` collects any hook result with `action === "block"`.
64
83
  extraSkillDirs = ["/absolute/path/to/agent-guard/skills"]
65
84
  ```
66
85
 
67
- 3. Restart the session. Hooks are read at session start.
86
+ 3. Set the PreToolUse hook's `timeout = 120`, then restart the session.
87
+ The adapter waits up to 90 seconds for the guard; the host needs additional
88
+ time for Python startup and the refusal to return. An outer 90-second
89
+ timeout races that inner deadline. Kimi allows the tool if the hook itself
90
+ times out, so this margin reduces the race without making host timeouts
91
+ fail-closed. Start a new Kimi process after editing hooks; a running
92
+ setup process keeps its earlier hook configuration.
68
93
 
69
94
  4. From the repository root, run `python3 doctor.py kimi --probe`. The doctor
70
95
  checks the configured matcher and command, then exercises the bridge with
71
96
  harmless Bash payloads, a Bash→Core policy refusal, the host-specific
72
97
  ASK→hard-refusal mapping, and a deliberately missing interpreter. `--json`
73
- reports `configuration`, `local_probe`, and
98
+ reports PreToolUse `configuration`, `local_probe`, and
74
99
  `host_interception` separately; the latter remains `UNVERIFIED` even when
75
100
  the local probe passes. The doctor also rejects an invalid
76
101
  `AGENT_GUARD_DIALECT` in the current process. It does **not** invoke a
77
102
  model, edit the configuration, inspect a running Kimi session, or prove
78
- host-level interception. The optional Kimi doctor uses Python 3.11+ for
103
+ host-level interception. It accepts the host's 1–600 second timeout range
104
+ and does not test deadline exhaustion; use the recommended 120 seconds
105
+ even when a shorter configuration passes the doctor.
106
+ The optional Kimi doctor uses Python 3.11+ for
79
107
  TOML parsing; the guard adapter itself continues to support Python 3.9+.
108
+ In 0.2.6, a separate `feedback` result checks the optional
109
+ Stop hook. See the [Stop doctor checks](#stop-doctor-checks-unreleased).
80
110
  Add `--check-drift` to compare the installed Kimi Code version with the
81
111
  shipped profile and compute privacy-safe configuration/runtime
82
112
  fingerprints. `CURRENT` still does not prove live interception; see the
@@ -88,6 +118,14 @@ allowed. `blockDecision()` collects any hook result with `action === "block"`.
88
118
  `--auto` or `--yolo` is neither needed nor valid alongside `--prompt` in
89
119
  Kimi 2.x.
90
120
 
121
+ For an npm installation, `tests/` is not shipped. The source unittest
122
+ references below apply to a full checkout; use the installed doctor for local
123
+ probes and report the unit suite as `NOT_INCLUDED`. Finish this configuration
124
+ stage with a handoff recording paths, probe results and pending fresh-process
125
+ verification. The doctor's `UNVERIFIED` host-interception/model-delivery fields
126
+ are expected. Repeat probes only to check a new change or investigate a
127
+ failure. If the setup hits a step limit, preserve that handoff for continuation.
128
+
91
129
  ## Decision mapping
92
130
 
93
131
  The shared Claude adapter supplies the Core call and normal mappings; Kimi
@@ -106,8 +144,107 @@ sets `ask_is_block=True` because this CLI cannot enforce a prompt:
106
144
  This table describes adapter output **when the adapter actually starts**.
107
145
  It does not describe a missing hook or a failed hook command.
108
146
 
147
+ <a id="optional-recovery-feedback-unreleased-checkout-addition"></a>
148
+
149
+ ## Optional recovery feedback
150
+
151
+ The tested 0.42.0, 2.1.1 and 2.3.0 success-hook paths do not include the hook's
152
+ recovery explanation in the next model request. A successful Bash result
153
+ alone can therefore hide that the guard already moved files to quarantine.
154
+ Version 0.2.6 adds a separate, opt-in **POSIX Stop hook**. It is not included
155
+ in the published 0.2.5 package. The existing PreToolUse installation keeps
156
+ its current behavior until this additional hook is configured.
157
+
158
+ ```toml
159
+ # Keep the existing PreToolUse hook. Add this only when the extra response is wanted.
160
+ [[hooks]]
161
+ event = "Stop"
162
+ command = "/bin/sh /absolute/path/to/agent-guard/adapters/kimi-code/hook_bridge.sh /absolute/path/to/python3 --stop-feedback"
163
+ timeout = 30
164
+ ```
165
+
166
+ Confirm the selected root contains [`stop_feedback.py`](stop_feedback.py)
167
+ before adding this hook. Replace and quote paths as in the PreToolUse
168
+ installation. Start a new
169
+ session after changing the configuration. This hook reads the existing audit
170
+ and, for incomplete compensations, correlates transaction headers in the
171
+ recovery journal. It reports actual txids, recorded moves, recovery-state
172
+ inspection and restore commands. File relocations include the retained-space
173
+ notice and complete GC commands with the recorded transaction IDs. Restoring
174
+ files moves them back without freeing total disk space; permanent GC removes
175
+ their recovery copies. Git snapshots are named
176
+ separately; GC does not remove their stash entries. No command, restore or
177
+ purge is executed by this hook, and deletion policy is unchanged.
178
+
179
+ **The initial answer appears first.** When new compensation records exist,
180
+ Stop asks the model for one additional response to supplement or correct it.
181
+ It cannot repair the earlier Bash tool result or prevent an inaccurate initial
182
+ answer. The feedback asks for a brief supplement with commands copied in full;
183
+ the model can still omit or misstate details. No compensation, direct regenerable deletion, an empty clean
184
+ enumeration and a clean Git snapshot with nothing to save produce no extra response. Partial failures identify incomplete
185
+ recovery records without claiming that Bash ran or every file is recoverable.
186
+
187
+ Emission cursors live in `$KIMI_CODE_HOME/agent-guard-feedback/` (default
188
+ `~/.kimi-code/agent-guard-feedback/`), scoped to the physical workspace,
189
+ trash location and session. A POSIX lock and atomic checkpoint prevent
190
+ concurrent Stop calls from emitting the same records again. Cursors record
191
+ emission, **not model acknowledgement**. Cancellation, exhausted model/step
192
+ budgets, failed hook launch or host changes can still prevent delivery.
193
+ Cursor corruption or replacement/truncation of the append-only audit produces
194
+ an explicit feedback-unavailable message; it does not rewind silently or
195
+ modify recovery data. Inspect `restore.py list` from the original workspace.
196
+
197
+ The scope is the session, not an authenticated agent identity. A parent and
198
+ child sharing a session/workspace may have their records emitted by whichever
199
+ Stop runs first. This does not guarantee a separate notice to every actor.
200
+ The local doctor checks below do not establish delivery to a running model.
201
+
202
+ <a id="stop-doctor-checks-unreleased"></a>
203
+
204
+ ### Stop doctor checks
205
+
206
+ Run `python3 doctor.py kimi --probe --json` from the checkout containing the
207
+ Stop helper. Existing top-level `configuration` and `local_probe` fields
208
+ describe PreToolUse. The separate `feedback` object reports:
209
+
210
+ | Field | Meaning |
211
+ |---|---|
212
+ | `configured` | `false` when no agent-guard Stop definition is found; `null` when the configuration cannot be checked. |
213
+ | `configuration` | `NOT_CONFIGURED`, `PASS`, `FAIL`, or `UNVERIFIED`. Checks the event, command, matcher, timeout, duplicate definitions and helper presence. |
214
+ | `local_probe` | `NOT_RUN` without `--probe`, or when absent/invalid; otherwise `PASS` or `FAIL`. |
215
+ | `model_delivery` | Always `UNVERIFIED`; local execution does not prove a live host loaded Stop or a model received it. |
216
+ | `problems` | Stop-specific configuration or local execution failures. |
217
+
218
+ The command must use this installation's absolute shell/bridge/Python paths
219
+ followed by `--stop-feedback`. Use `event = "Stop"`, omit `matcher` or leave
220
+ it empty, and choose an integer timeout from 1 to 600 seconds (recommended
221
+ 30). A Bash matcher would filter out Stop. Unrelated Stop commands are ignored.
222
+
223
+ `--probe` uses a temporary home, workspace, recovery audit and emission cursor.
224
+ It checks silent no-record/active-Stop cases, a synthetic transaction's
225
+ retained-space and complete GC guidance, then repeat-Stop silence. It performs
226
+ no real deletion, restore, GC or model call and leaves existing recovery records
227
+ alone. An executable Python path or an existing helper file alone is not a
228
+ successful runtime probe. The probe uses a fixed local deadline; it does not
229
+ exhaust the configured host timeout.
230
+
231
+ An absent optional Stop does not fail the doctor. A configured Stop that fails
232
+ configuration or a requested local probe makes the CLI exit 1, even when
233
+ PreToolUse passes. An unreadable config reports Stop as `UNVERIFIED`, rather
234
+ than claiming it is disabled. Neither local success nor a passing Bash live
235
+ sentinel changes `feedback.model_delivery`. These additions ship in
236
+ [0.2.6](../../docs/releases/release-notes-0.2.6.md) and are absent from 0.2.5.
237
+
109
238
  ## Known limitations — read before claiming interception
110
239
 
240
+ - **Hook launch and timeout are separate from adapter refusal.** A local
241
+ 0.42.0 / 2.1.1 audit confirmed that a nonexistent hook command or a started
242
+ hook exceeding its one-second test deadline still allowed an inert Bash
243
+ sentinel to run. The bridge blocked a missing Python interpreter when the
244
+ bridge itself started. A longer timeout does not protect a missing hook.
245
+ Stop Python startup failure produced one feedback-unavailable continuation;
246
+ it did not undo the preceding Bash call. These were fixed loopback-response
247
+ trials of the actual CLIs, not new real-model trials.
111
248
  - **ASK is not supported by this host's hook contract.** Even outside
112
249
  `kimi --auto`, Kimi 0.42.0 treats `permissionDecision: "ask"` as allow.
113
250
  This adapter therefore maps Core ASK to exit 2 (BLOCK). The failure class
@@ -122,6 +259,8 @@ It does not describe a missing hook or a failed hook command.
122
259
  the agent to split and retry instead of proceeding without compensation.
123
260
  The 2.1.1 live sentinel exercised a hard `BLOCK`, not a live ASK path, so
124
261
  this conservative mapping is not advertised as a 2.1.1 approval-UI test.
262
+ The 2.3.0 prompt/ACP trials observed ASK being hard-refused with fixed
263
+ responses; they do not establish native approval-UI behavior either.
125
264
  - **Subagent inheritance is observational, not a blanket guarantee.** In two
126
265
  isolated sandboxes using one configured model route, single and concurrent
127
266
  subagent Bash calls reached the native hook and produced recoverable audit
@@ -164,14 +303,15 @@ It does not describe a missing hook or a failed hook command.
164
303
 
165
304
  ## Verification
166
305
 
167
- ```sh
168
- # Should exit 2 with a BLOCK code (the string is data, never executed):
169
- printf '%s' '{"hook_event_name":"PreToolUse","session_id":"t","cwd":"/tmp/agent-guard-kimi-sandbox-20260921","tool_name":"Bash","tool_input":{"command":"rm -rf /"},"tool_call_id":"c1"}' \
170
- | python3 adapters/kimi-code/pre_tool_use.py; echo "exit=$?"
306
+ From the repository root:
171
307
 
172
- # Should exit 0 silently:
173
- printf '%s' '{"hook_event_name":"PreToolUse","session_id":"t","cwd":"/tmp/agent-guard-kimi-sandbox-20260921","tool_name":"Bash","tool_input":{"command":"ls -la"},"tool_call_id":"c2"}' \
174
- | python3 adapters/kimi-code/pre_tool_use.py; echo "exit=$?"
308
+ ```sh
309
+ python3 doctor.py kimi --probe --json
310
+ python3 -m unittest tests.test_doctor tests.test_kimi_adapter tests.test_kimi_feedback
175
311
  ```
176
312
 
177
- Set `AGENT_GUARD_DEBUG=1` to print the raw Core verdict JSON to stderr.
313
+ These are local checks. They do not certify a running session or the optional
314
+ Stop hook's delivery. See the [versioned host report](../../docs/reports/test-report-kimi-code-block.md)
315
+ for actual CLI trials and their limits. Set `AGENT_GUARD_DEBUG=1` in the Kimi
316
+ process environment for adapter troubleshooting; the TOML example does not
317
+ define a debug switch.
@@ -6,7 +6,7 @@
6
6
  "executable_candidates": ["kimi", "kimi-code"],
7
7
  "version_args": ["--version"],
8
8
  "version_pattern": "(?<![0-9])([0-9]+\\.[0-9]+\\.[0-9]+)(?![0-9])",
9
- "tested_versions": ["0.42.0", "2.1.1"],
9
+ "tested_versions": ["0.42.0", "2.1.1", "2.3.0"],
10
10
  "contract": {
11
11
  "event": "PreToolUse",
12
12
  "tools": ["Bash"],
@@ -1,7 +1,8 @@
1
1
  # Kimi Code adapter - agent-guard
2
2
  #
3
- # Append to ~/.kimi-code/config.toml. Hooks are read at session start, so
4
- # restart the session after editing.
3
+ # Merge into ~/.kimi-code/config.toml; do not append this whole file.
4
+ # Put extraSkillDirs before the first [table], or extend its existing array.
5
+ # The [[hooks]] blocks can go at the end. Restart the session after editing.
5
6
  #
6
7
  # `matcher` is a REGULAR EXPRESSION tested against the tool name
7
8
  # (`matches()` in the Kimi Code bundle uses `new RegExp(pattern).test(value)`;
@@ -19,8 +20,19 @@ matcher = "^Bash$"
19
20
  # Replace all three paths for your machine. Use an absolute POSIX sh and Python.
20
21
  # The shell bridge turns Python launch failures into Kimi's blocking exit 2.
21
22
  command = "/bin/sh /absolute/path/to/agent-guard/adapters/kimi-code/hook_bridge.sh /absolute/path/to/python3"
22
- timeout = 90
23
+ # The adapter waits up to 90s for the guard. Leave time for Python startup
24
+ # and returning exit 2: a host timeout allows the tool instead of blocking it.
25
+ timeout = 120
23
26
 
24
- # Optional: surface the raw Core verdict on stderr for troubleshooting.
25
- # [experimental]
26
- # agent_guard_debug = true
27
+ # Optional recovery feedback (unreleased checkout addition, POSIX only).
28
+ # Kimi ignores successful PreToolUse feedback. This Stop hook requests one
29
+ # extra model response AFTER the initial answer when new recovery records exist.
30
+ # Uncomment only if that extra response is wanted. The PreToolUse hook above
31
+ # remains required for interception; this Stop hook only reports saved data.
32
+ # [[hooks]]
33
+ # event = "Stop"
34
+ # command = "/bin/sh /absolute/path/to/agent-guard/adapters/kimi-code/hook_bridge.sh /absolute/path/to/python3 --stop-feedback"
35
+ # timeout = 30
36
+
37
+ # Optional debug: start Kimi with AGENT_GUARD_DEBUG=1 in its environment.
38
+ # There is no adapter-specific TOML debug option.
@@ -3,11 +3,26 @@
3
3
  # bridge alive long enough to turn a failed Python launch into an explicit 2.
4
4
  # A missing/unmatched hook or a host timeout is still fail-open.
5
5
 
6
- if [ "$#" -ne 1 ]; then
7
- printf '%s\n' '[agent-guard] Kimi hook bridge needs one absolute Python path' >&2
6
+ if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then
7
+ printf '%s\n' '[agent-guard] Kimi hook bridge needs one absolute Python path and optional --stop-feedback' >&2
8
8
  exit 2
9
9
  fi
10
10
 
11
+ hook_script=pre_tool_use.py
12
+ refusal='refusing tool call'
13
+ if [ "$#" -eq 2 ]; then
14
+ case "$2" in
15
+ --stop-feedback)
16
+ hook_script=stop_feedback.py
17
+ refusal='recovery feedback unavailable; inspect restore.py list'
18
+ ;;
19
+ *)
20
+ printf '%s\n' '[agent-guard] Kimi hook bridge: unknown option' >&2
21
+ exit 2
22
+ ;;
23
+ esac
24
+ fi
25
+
11
26
  case "$1" in
12
27
  /*) python_bin=$1 ;;
13
28
  *)
@@ -21,12 +36,12 @@ bridge_dir=$(CDPATH= cd -P "$(dirname "$0")" 2>/dev/null && pwd -P) || {
21
36
  exit 2
22
37
  }
23
38
 
24
- "$python_bin" "$bridge_dir/pre_tool_use.py"
39
+ "$python_bin" "$bridge_dir/$hook_script"
25
40
  status=$?
26
41
  case "$status" in
27
42
  0|2) exit "$status" ;;
28
43
  *)
29
- printf '[agent-guard] Kimi hook process failed (exit %s); refusing tool call\n' "$status" >&2
44
+ printf '[agent-guard] Kimi hook process failed (exit %s); %s\n' "$status" "$refusal" >&2
30
45
  exit 2
31
46
  ;;
32
47
  esac
@@ -33,7 +33,7 @@ to the observed root Bash call recorded in the public test report.
33
33
  event = "PreToolUse"
34
34
  matcher = "^Bash$" # regular expression over the tool name
35
35
  command = "/bin/sh /path/to/agent-guard/adapters/kimi-code/hook_bridge.sh /absolute/path/to/python3"
36
- timeout = 90
36
+ timeout = 120 # outer hook timeout; the inner guard deadline is 90s
37
37
 
38
38
  Because the two contracts match, this adapter **delegates to the shared
39
39
  Claude adapter** rather than reimplementing the payload -> core -> decision
@@ -0,0 +1,237 @@
1
+ #!/usr/bin/env python3
2
+ """Optional POSIX Kimi Stop hook: report this session's recovery records once.
3
+
4
+ Reads existing guard audit metadata; never authorizes or executes a command.
5
+ Exit 2 asks Kimi for one additional answer after its initial response. The
6
+ cursor records emission, not acknowledgement by the model or the user.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import os
13
+ from pathlib import Path
14
+ import re
15
+ import shlex
16
+ import stat
17
+ import sys
18
+ import tempfile
19
+
20
+ ROOT = Path(__file__).resolve().parents[2]
21
+ if str(ROOT) not in sys.path:
22
+ sys.path.insert(0, str(ROOT))
23
+
24
+ from core import AUDIT_NAME, MANIFEST_NAME, TRASH_DIRNAME, audit, classifier # noqa: E402
25
+ from core.messages import QUARANTINE_NOTICE # noqa: E402
26
+
27
+ _TXID = re.compile(r"[0-9]{8}-[0-9]{6}-[0-9a-f]{8}\Z")
28
+
29
+
30
+ def incomplete_compensations(trash, check_ids):
31
+ """Failed audit records omit compensations; correlate existing journal IDs.
32
+
33
+ Read only transaction headers and count journal events. Exact target paths,
34
+ commands and failure reasons never enter the feedback projection.
35
+ """
36
+ if not check_ids:
37
+ return {}
38
+ try:
39
+ manifest = (trash / MANIFEST_NAME).open("rb")
40
+ except FileNotFoundError:
41
+ return {}
42
+ records = {}
43
+ with manifest:
44
+ for line in manifest:
45
+ if not line.endswith(b"\n"):
46
+ break
47
+ try:
48
+ row = json.loads(line)
49
+ except (json.JSONDecodeError, UnicodeDecodeError):
50
+ continue
51
+ if not isinstance(row, dict):
52
+ continue
53
+ txid = row.get("txid")
54
+ if not isinstance(txid, str) or not _TXID.fullmatch(txid):
55
+ continue
56
+ meta = row.get("meta")
57
+ check_id = meta.get("check_id") if isinstance(meta, dict) else None
58
+ related = isinstance(check_id, str) and check_id in check_ids
59
+ if row.get("type") == "tx-start" and related and row.get("strategy") == "relocate":
60
+ records[txid] = {"txid": txid, "strategy": "relocate", "status": "incomplete", "moved": 0}
61
+ elif row.get("type") == "snapshot" and related:
62
+ records[txid] = {"txid": txid, "strategy": "snapshot", "status": "incomplete"}
63
+ elif txid in records:
64
+ if row.get("type") == "relocate":
65
+ records[txid]["moved"] += 1
66
+ return records
67
+
68
+
69
+ def recovery_message(records):
70
+ """Only projected IDs/counts/statuses, never commands or target paths."""
71
+ lines = ["[agent-guard] Recovery records for this session:"]
72
+ has_files = False
73
+ has_snapshot = False
74
+ incomplete = False
75
+ restore = [sys.executable, str(ROOT / "skills/delete-guard/scripts/restore.py")]
76
+ gc = [sys.executable, str(ROOT / "skills/delete-guard/scripts/gc.py")]
77
+ for item in records:
78
+ snapshot = item["strategy"] == "snapshot"
79
+ incomplete |= item.get("status") != "complete"
80
+ label = "Git snapshot" if snapshot else "File relocation"
81
+ line = f"- {label}: txid={item['txid']}; status={item.get('status', 'unknown')}"
82
+ if not snapshot:
83
+ line += f"; moved={item.get('moved', 0)}; skipped={item.get('skipped', 'not recorded')}"
84
+ has_files |= item.get("moved", 0) > 0
85
+ has_snapshot |= snapshot
86
+ lines.append(line)
87
+ lines.append(" Restore after checking its current state: " +
88
+ shlex.join(restore + [item["txid"]]))
89
+ if not snapshot and item.get("moved", 0) > 0:
90
+ lines.append(" GC permanent purge after preview: " +
91
+ shlex.join(gc + ["--execute", "--txid", item["txid"]]))
92
+ lines += [
93
+ "Recorded before Bash, not confirmation that Bash ran.",
94
+ "Inspect current recovery state: " + shlex.join(restore + ["list", "--json"]),
95
+ ]
96
+ if incomplete:
97
+ lines.append("Incomplete or failed records do not guarantee a recoverable copy.")
98
+ if has_files:
99
+ lines += [
100
+ QUARANTINE_NOTICE,
101
+ "Restoring files moves them back; it does not free total disk space.",
102
+ "Already restored or purged records may no longer have a copy in quarantine.",
103
+ "GC preview: " + shlex.join(gc),
104
+ ]
105
+ if has_snapshot:
106
+ lines.append("GC does not remove Git stash snapshots.")
107
+ lines += [
108
+ "Use the same working directory and AGENT_GUARD_WORKSPACE / AGENT_GUARD_TRASH settings.",
109
+ "Supplement or correct the previous answer in at most three short bullets: "
110
+ "recovery result and txid, disk space, and the commands. "
111
+ "Copy commands verbatim on separate lines; do not abbreviate paths or replace txids. "
112
+ "Do not repeat the destructive command or restore/purge data for this feedback.",
113
+ ]
114
+ return "\n".join(lines)
115
+
116
+
117
+ def save_cursor(path, state):
118
+ """Replace the checkpoint atomically while its separate lock stays held."""
119
+ with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent,
120
+ prefix=path.stem + ".", suffix=".tmp", delete=False) as temporary:
121
+ temporary_path = Path(temporary.name)
122
+ try:
123
+ json.dump(state, temporary)
124
+ temporary.flush()
125
+ os.fsync(temporary.fileno())
126
+ os.replace(temporary_path, path)
127
+ finally:
128
+ temporary_path.unlink(missing_ok=True)
129
+
130
+
131
+ def pending_feedback(cwd, session):
132
+ """Consume complete audit lines under a per-workspace/session cursor lock."""
133
+ workspace = classifier.discover_workspace(cwd)
134
+ trash = Path(os.environ.get("AGENT_GUARD_TRASH", str(Path(workspace) / TRASH_DIRNAME)))
135
+ if not trash.is_absolute():
136
+ trash = Path(cwd) / trash
137
+ audit_path = trash / AUDIT_NAME
138
+ try:
139
+ source = audit_path.open("rb")
140
+ except FileNotFoundError:
141
+ return None
142
+
143
+ session_key = audit.correlation_id(session)
144
+ identity = json.dumps([os.path.realpath(workspace), str(trash.resolve()), session_key])
145
+ name = hashlib.sha256(identity.encode("utf-8")).hexdigest() + ".json"
146
+ home = Path(os.environ.get("KIMI_CODE_HOME", str(Path.home() / ".kimi-code")))
147
+ cursors = home / "agent-guard-feedback"
148
+ with source:
149
+ # This optional integration is POSIX-only, matching its shell bridge.
150
+ import fcntl
151
+
152
+ cursors.mkdir(mode=0o700, parents=True, exist_ok=True)
153
+ flags = os.O_RDWR | getattr(os, "O_NOFOLLOW", 0)
154
+ descriptor = os.open(cursors / (name + ".lock"), flags | os.O_CREAT, 0o600)
155
+ with os.fdopen(descriptor, "r+", encoding="utf-8") as lock:
156
+ if not stat.S_ISREG(os.fstat(lock.fileno()).st_mode):
157
+ raise ValueError("feedback lock is not a regular file")
158
+ fcntl.flock(lock, fcntl.LOCK_EX)
159
+ info = os.fstat(source.fileno())
160
+ try:
161
+ descriptor = os.open(cursors / name, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
162
+ except FileNotFoundError:
163
+ offset = 0
164
+ else:
165
+ with os.fdopen(descriptor, "r", encoding="utf-8") as cursor:
166
+ if not stat.S_ISREG(os.fstat(cursor.fileno()).st_mode):
167
+ raise ValueError("feedback cursor is not a regular file")
168
+ saved = json.load(cursor)
169
+ if (not isinstance(saved, dict)
170
+ or set(saved) != {"device", "inode", "offset"}
171
+ or any(type(saved[key]) is not int or saved[key] < 0 for key in saved)
172
+ or saved["device"] != info.st_dev or saved["inode"] != info.st_ino
173
+ or saved["offset"] > info.st_size):
174
+ raise ValueError("feedback cursor does not match the append-only audit")
175
+ offset = saved["offset"]
176
+ source.seek(offset)
177
+ records = {}
178
+ failed_checks = set()
179
+ while True:
180
+ line = source.readline()
181
+ if not line or not line.endswith(b"\n"):
182
+ break # An incomplete append must be read again next time.
183
+ offset = source.tell()
184
+ try:
185
+ raw = json.loads(line)
186
+ except (json.JSONDecodeError, UnicodeDecodeError):
187
+ continue # Same malformed-line rule as the shared audit reader.
188
+ if not isinstance(raw, dict):
189
+ continue
190
+ record = audit.project(raw)
191
+ if (record.get("session") != session_key
192
+ or record.get("event") not in {"enforce-proceed", "enforce-error", "enforce-block"}):
193
+ continue
194
+ if (not record.get("compensations") and record.get("check_id")
195
+ and record.get("event") in {"enforce-error", "enforce-block"}):
196
+ failed_checks.add(record["check_id"])
197
+ for item in record.get("compensations", []):
198
+ txid = item.get("txid", "")
199
+ if not _TXID.fullmatch(txid):
200
+ continue
201
+ strategy = item.get("strategy")
202
+ if (strategy == "snapshot" and (item.get("sha") or item.get("status") != "complete")
203
+ or strategy in {"relocate", "clean-enumerate"}
204
+ and (item.get("moved", 0) > 0 or item.get("status") != "complete")):
205
+ records[txid] = item
206
+ for txid, item in incomplete_compensations(trash, failed_checks).items():
207
+ records.setdefault(txid, item)
208
+ message = recovery_message(records.values()) if records else None
209
+ save_cursor(cursors / name, {"device": info.st_dev, "inode": info.st_ino, "offset": offset})
210
+ return message
211
+
212
+
213
+ def main():
214
+ payload = json.load(sys.stdin)
215
+ if (not isinstance(payload, dict) or payload.get("hook_event_name") != "Stop"
216
+ or not isinstance(payload.get("cwd"), str) or not payload["cwd"].strip()
217
+ or not isinstance(payload.get("session_id"), str) or not payload["session_id"].strip()
218
+ or type(payload.get("stop_hook_active")) is not bool):
219
+ raise ValueError("invalid Stop hook payload")
220
+ if payload["stop_hook_active"]:
221
+ return 0
222
+ message = pending_feedback(payload["cwd"], payload["session_id"])
223
+ if message:
224
+ sys.stderr.write(message + "\n")
225
+ return 2
226
+ return 0
227
+
228
+
229
+ if __name__ == "__main__":
230
+ try:
231
+ sys.exit(main())
232
+ except (OSError, ValueError, ImportError) as error:
233
+ sys.stderr.write(
234
+ f"[agent-guard] Recovery feedback unavailable ({type(error).__name__}). "
235
+ "Inspect restore.py list from the original workspace; "
236
+ "this does not mean no files were preserved.\n")
237
+ sys.exit(2)
@@ -0,0 +1 @@
1
+ """Optional MCP adapter; importing its operations does not require an MCP SDK."""