@mokuyoaxis/agent-guard 0.2.5-rc3 → 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.
Files changed (44) hide show
  1. package/README.md +64 -34
  2. package/README.zh-CN.md +53 -27
  3. package/SECURITY.md +5 -3
  4. package/adapters/INTEGRATION.md +84 -10
  5. package/adapters/claude/README.md +6 -0
  6. package/adapters/dsh/README.md +51 -7
  7. package/adapters/dsh/compatibility.json +14 -0
  8. package/adapters/dsh/harness/README.md +11 -0
  9. package/adapters/dsh/harness/guard_lab.py +42 -14
  10. package/adapters/dsh/lib/index.js +127 -33
  11. package/adapters/kimi-code/README.md +154 -14
  12. package/adapters/kimi-code/compatibility.json +1 -1
  13. package/adapters/kimi-code/config.example.toml +18 -6
  14. package/adapters/kimi-code/hook_bridge.sh +19 -4
  15. package/adapters/kimi-code/pre_tool_use.py +1 -1
  16. package/adapters/kimi-code/stop_feedback.py +237 -0
  17. package/core/messages.py +40 -0
  18. package/core/policy.py +2 -1
  19. package/docs/README.md +30 -8
  20. package/docs/design/architecture.md +13 -6
  21. package/docs/design/compatibility.md +87 -4
  22. package/docs/design/dsh-compatibility.md +65 -0
  23. package/docs/design/threat-model.md +2 -2
  24. package/docs/guides/getting-started.md +76 -17
  25. package/docs/guides/harness-capabilities.md +24 -5
  26. package/docs/guides/host-drift.md +32 -0
  27. package/docs/guides/recovery-feedback.md +126 -0
  28. package/docs/history/friction.md +21 -1
  29. package/docs/lab/blue-team-calibration.md +1 -1
  30. package/docs/lab/guard-lab.md +6 -2
  31. package/docs/releases/release-notes-0.2.5-rc3.md +8 -0
  32. package/docs/releases/release-notes-0.2.5.md +123 -0
  33. package/docs/releases/release-notes-0.2.6.md +167 -0
  34. package/docs/releases/unreleased.md +141 -0
  35. package/docs/reports/test-report-dsh-alpha4.md +102 -0
  36. package/docs/reports/test-report-kimi-code-block.md +119 -6
  37. package/doctor.py +175 -28
  38. package/package.json +11 -2
  39. package/skills/delete-guard/SKILL.md +30 -13
  40. package/skills/delete-guard/references/policy.md +16 -3
  41. package/skills/delete-guard/scripts/check.py +13 -0
  42. package/skills/delete-guard/scripts/gc.py +4 -2
  43. package/skills/delete-guard/scripts/safe_delete.py +20 -14
  44. package/skills/delete-guard/scripts/status.py +9 -0
@@ -46,6 +46,17 @@ the shipped baseline overlay is always last.
46
46
  Use `--node-executable /absolute/path/to/node` to select the decoder runtime
47
47
  explicitly. This option does not change the runtime chosen by the DSH launcher.
48
48
 
49
+ In [0.2.6](../../../docs/releases/release-notes-0.2.6.md), version/config
50
+ process failures report `START_FAILED`, `TIMEOUT`, `OUTPUT_LIMIT`,
51
+ `NONZERO_EXIT`, or `EMPTY_STDOUT`; an unreviewed version reports
52
+ `UNSUPPORTED_VERSION`. The error includes the exit code (negative for a POSIX
53
+ signal; null if startup failed), capture flags, elapsed/deadline seconds, and
54
+ captured stdout/stderr byte counts. Timeout/limit reasons take precedence over
55
+ the signal used to stop the child. These diagnostics omit raw output, command
56
+ arguments, environment values and paths. Version/config deadlines remain
57
+ 10/15 seconds, with no automatic retries. Published 0.2.5 retains the older
58
+ generic preflight errors; use a reviewed checkout/package for these diagnostics.
59
+
49
60
  ## Capture and review the clean control
50
61
 
51
62
  Every `--output-dir` must be new, with an existing parent. The task file is
@@ -14,6 +14,7 @@ from pathlib import Path
14
14
  import shutil
15
15
  import subprocess
16
16
  import sys
17
+ import time
17
18
  from typing import Optional, Sequence
18
19
 
19
20
 
@@ -111,19 +112,48 @@ def _host_options(
111
112
  return argv, _environment(home)
112
113
 
113
114
 
115
+ def _preflight_error(stage, reason, result, streams, elapsed, timeout):
116
+ # Keep diagnostics useful without echoing configuration, argv or stderr.
117
+ details = {
118
+ "reason": reason, "exit_code": result["exit_code"],
119
+ "start_failed": result["start_failed"], "timed_out": result["timed_out"],
120
+ "output_limit_exceeded": result["output_limit_exceeded"],
121
+ "elapsed_seconds": round(elapsed, 3), "timeout_seconds": timeout,
122
+ "stdout_captured_bytes": len(streams["stdout"]),
123
+ "stderr_captured_bytes": len(streams["stderr"]),
124
+ }
125
+ return LabError("DSH " + stage + " preflight failed: "
126
+ + json.dumps(details, sort_keys=True))
127
+
128
+
129
+ def _capture_preflight(stage, argv, cwd, environment, timeout):
130
+ started = time.monotonic()
131
+ result, streams = _capture_process(argv, cwd, environment, timeout)
132
+ elapsed = time.monotonic() - started
133
+ # A deadline/limit may cause a negative exit code when capture stops the child.
134
+ if result["start_failed"]:
135
+ reason = "START_FAILED"
136
+ elif result["timed_out"]:
137
+ reason = "TIMEOUT"
138
+ elif result["output_limit_exceeded"]:
139
+ reason = "OUTPUT_LIMIT"
140
+ elif result["exit_code"] != 0:
141
+ reason = "NONZERO_EXIT"
142
+ elif not streams["stdout"].strip():
143
+ reason = "EMPTY_STDOUT"
144
+ else:
145
+ return result, streams, elapsed
146
+ raise _preflight_error(stage, reason, result, streams, elapsed, timeout)
147
+
148
+
114
149
  def _config_dump(
115
150
  argv: Sequence[str], cwd: Path, environment: dict[str, str],
116
151
  guard_state: str = "off",
117
152
  *, guard_profile="deletion-v1", workspace=None, dsh_root=None,
118
153
  ) -> bytes:
119
- result, output = _capture_process(
120
- [*argv, "--dump-config"], cwd, environment, 15,
154
+ _, output, _ = _capture_preflight(
155
+ "config", [*argv, "--dump-config"], cwd, environment, 15,
121
156
  )
122
- if (
123
- result["exit_code"] != 0 or result["timed_out"]
124
- or result["output_limit_exceeded"] or not output["stdout"].strip()
125
- ):
126
- raise LabError("DSH config preflight failed; raw diagnostics are not printed")
127
157
  normalize_composition(output["stdout"], guard_state,
128
158
  **_profile_options(guard_profile, workspace, dsh_root))
129
159
  return output["stdout"]
@@ -138,14 +168,12 @@ def check_host(
138
168
  home = home.expanduser().resolve()
139
169
  context = dict(guard_profile=guard_profile, workspace=workspace, dsh_root=dsh_root)
140
170
  argv, environment = _host_options(executable, home, patches, guard_state, guard_patch_file, **context)
141
- result, output = _capture_process([argv[0], "--version"], home.resolve(), environment, 10)
171
+ result, output, elapsed = _capture_preflight(
172
+ "version", [argv[0], "--version"], home.resolve(), environment, 10,
173
+ )
142
174
  version = output["stdout"].strip().decode("ascii", errors="replace")
143
- if (
144
- result["exit_code"] != 0 or result["timed_out"]
145
- or result["output_limit_exceeded"]
146
- or version not in HOST_CONTRACTS
147
- ):
148
- raise LabError("DSH version preflight requires a reviewed exact host version")
175
+ if version not in HOST_CONTRACTS:
176
+ raise _preflight_error("version", "UNSUPPORTED_VERSION", result, output, elapsed, 10)
149
177
  if guard_profile == "read-redaction-v1" and _launcher_root(argv[0], version) != Path(dsh_root).resolve():
150
178
  raise LabError("read profile root must match the selected DSH launcher")
151
179
  configuration = _config_dump(argv, home.resolve(), environment, guard_state, **context)
@@ -27,8 +27,12 @@
27
27
 
28
28
  import fs from "node:fs";
29
29
  import path from "node:path";
30
+ import { execFile } from "node:child_process";
31
+ import { promisify } from "node:util";
30
32
  import { fileURLToPath } from "node:url";
31
33
 
34
+ const runFile = promisify(execFile);
35
+
32
36
  export const name = "agent_guard";
33
37
 
34
38
  /** Services that must resolve before apply() runs. */
@@ -217,7 +221,13 @@ function dialectSelector(args, config, env) {
217
221
  function buildRuntime(ctx, config, shell, systemPrompt) {
218
222
  const repoRoot = config.repoRoot || PACKAGE_ROOT;
219
223
  const scriptsDir = path.join(repoRoot, "skills", "delete-guard", "scripts");
220
- const pythonReady = fs.existsSync(path.join(scriptsDir, "check.py"));
224
+ const diagnostics = {
225
+ startup_check: "NOT_RUN",
226
+ startup_scope: "plugin_process",
227
+ hook_registered: false,
228
+ last_checker_result: "NOT_RUN",
229
+ host_interception: "UNVERIFIED",
230
+ };
221
231
 
222
232
  // The caller's sandbox policy travels with the session so guard
223
233
  // invocations inherit exactly what the calling agent already has.
@@ -277,7 +287,7 @@ function buildRuntime(ctx, config, shell, systemPrompt) {
277
287
  systemPrompt,
278
288
  repoRoot,
279
289
  scriptsDir,
280
- pythonReady,
290
+ diagnostics,
281
291
  shQuote,
282
292
  runScript,
283
293
  outText,
@@ -288,21 +298,37 @@ function buildRuntime(ctx, config, shell, systemPrompt) {
288
298
  // Async functions cannot be mistaken for constructor plugins by Cordis.
289
299
  // The host must await optional read-guard startup before admitting work.
290
300
  export async function apply(ctx, config) {
301
+ function refuseStartup(detail) {
302
+ const code = config.readResultGuard ? "READ_GUARD_STARTUP_REFUSED" : "GUARD_STARTUP_FAILED";
303
+ throw new Error(`[agent-guard] ${code}: ${detail} No guard hook or tools were registered. Other host tools may still run.`);
304
+ }
291
305
  const shell = ctx.get ? ctx.get("shell") : undefined;
292
306
  if (shell === undefined) {
293
- if (config.readResultGuard) throw new Error("[agent-guard] READ_GUARD_STARTUP_REFUSED");
294
- console.error("[agent-guard] shell service unavailable; adapter disabled");
295
- return;
307
+ refuseStartup("The shell service is unavailable.");
296
308
  }
297
309
  const systemPrompt = ctx.get ? ctx.get("systemPrompt") : undefined;
298
310
  const rt = buildRuntime(ctx, config, shell, systemPrompt);
299
311
 
300
- if (!rt.pythonReady) {
301
- if (config.readResultGuard) throw new Error("[agent-guard] READ_GUARD_STARTUP_REFUSED");
302
- console.error("[agent-guard] check.py not found under", rt.repoRoot);
303
- return;
312
+ if (!fs.existsSync(path.join(rt.scriptsDir, "check.py"))) {
313
+ refuseStartup("check.py was not found. Check the package or repoRoot setting.");
304
314
  }
305
315
 
316
+ // --help loads Python and the checker imports without assessing a command
317
+ // or writing guard metadata. This checks the plugin process environment;
318
+ // the caller's shell/sandbox environment is only exercised by actual tools.
319
+ try {
320
+ await runFile("python3", [path.join(rt.scriptsDir, "check.py"), "--help"], {
321
+ timeout: 10000,
322
+ maxBuffer: 65536,
323
+ });
324
+ } catch (error) {
325
+ refuseStartup(error.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" ?
326
+ "The local checker startup check exceeded its output limit. Check the package and checker entry point." :
327
+ error.killed ? "The local checker startup check timed out." :
328
+ "The local Python checker could not run. Check python3 on the plugin process PATH and the checker imports.");
329
+ }
330
+ rt.diagnostics.startup_check = "PASSED";
331
+
306
332
  if (config.readResultGuard) {
307
333
  return import("./read_result_guard.js").then(async ({ installReadResultGuard }) => {
308
334
  await installReadResultGuard(ctx, config, rt.repoRoot);
@@ -319,6 +345,13 @@ function contribute(ctx, config, rt) {
319
345
  ctx.effect(() => {
320
346
  const disposers = [];
321
347
 
348
+ function checkerFailure(code, detail) {
349
+ rt.diagnostics.last_checker_result = code;
350
+ const reason = `[agent-guard] ${code}: ${detail} Command denied (fail-closed).`;
351
+ console.error(reason);
352
+ return { kind: "deny", reason };
353
+ }
354
+
322
355
  // ---- 1) interception -------------------------------------------------
323
356
  disposers.push(
324
357
  ctx.on("tools/pre-execute", async (exec, next) => {
@@ -352,20 +385,23 @@ function contribute(ctx, config, rt) {
352
385
  exec
353
386
  );
354
387
  } catch (_err) {
355
- console.error("[agent-guard] check.py infrastructure error");
356
- return {
357
- kind: "deny",
358
- reason: "[agent-guard] guard infrastructure error (fail-closed)",
359
- };
388
+ return checkerFailure("CHECKER_EXECUTION_FAILED",
389
+ "The checker could not start or finish. Check Python and the caller's shell environment; inspect recovery state before retrying.");
390
+ }
391
+ if (result.timedOut) {
392
+ return checkerFailure("CHECKER_TIMEOUT",
393
+ "The checker timed out. Inspect recovery state before retrying.");
394
+ }
395
+ if (![0, 2, 3].includes(result.exitCode)) {
396
+ return checkerFailure("CHECKER_PROCESS_FAILED",
397
+ "The checker did not complete with a supported exit status. Check the Python runtime and recovery state.");
360
398
  }
361
399
  const verdict = rt.parseJson(rt.outText(result.stdout));
362
- if (!verdict || !verdict.decision) {
363
- console.error("[agent-guard] unparseable guard output");
364
- return {
365
- kind: "deny",
366
- reason: "[agent-guard] unparseable guard output (fail-closed)",
367
- };
400
+ if (!verdict || !["ALLOW", "ASK", "BLOCK"].includes(verdict.decision)) {
401
+ return checkerFailure("CHECKER_INVALID_OUTPUT",
402
+ "The checker returned no usable decision. Check the package and recovery state.");
368
403
  }
404
+ rt.diagnostics.last_checker_result = "OK";
369
405
  if (verdict.decision === "ALLOW") {
370
406
  const comps = verdict.compensations || [];
371
407
  if (comps.length > 0) {
@@ -375,6 +411,8 @@ function contribute(ctx, config, rt) {
375
411
  "check_id=" + (verdict.check_id || "unknown")
376
412
  );
377
413
  }
414
+ if (verdict.storage_notice) console.log("[agent-guard]", verdict.storage_notice,
415
+ "Use agent_guard_status for usage and GC commands.");
378
416
  return next();
379
417
  }
380
418
  const reasons = Array.isArray(verdict.reasons)
@@ -403,11 +441,22 @@ function contribute(ctx, config, rt) {
403
441
  };
404
442
  })
405
443
  );
444
+ rt.diagnostics.hook_registered = true;
406
445
 
407
446
  // ---- 2) model tools --------------------------------------------------
408
447
  function renderJson(_args, value) {
448
+ // Keep diagnostics and storage guidance visible before long target/audit
449
+ // arrays consume the existing model-facing preview budget.
450
+ const display = {
451
+ ...(value.adapter ? { adapter: value.adapter } : {}),
452
+ ...(value.report?.storage_notice ? {
453
+ storage_notice: value.report.storage_notice,
454
+ gc: value.report.gc,
455
+ } : {}),
456
+ ...value,
457
+ };
409
458
  return [
410
- { type: "text", text: JSON.stringify(value, null, 2).slice(0, 4000) },
459
+ { type: "text", text: JSON.stringify(display, null, 2).slice(0, 4000) },
411
460
  ];
412
461
  }
413
462
 
@@ -417,6 +466,24 @@ function contribute(ctx, config, rt) {
417
466
  "Working directory (repo root) for this operation; defaults to the session workspace.",
418
467
  };
419
468
 
469
+ function adapterStatus() {
470
+ return {
471
+ ...rt.diagnostics,
472
+ note: "Startup checks the plugin process Python only. Hook registration and a local status result do not verify live host interception or every shell environment.",
473
+ };
474
+ }
475
+
476
+ function statusFailure(diagnostic, detail, exitCode = null) {
477
+ return {
478
+ ok: false,
479
+ exitCode,
480
+ report: null,
481
+ diagnostic,
482
+ stderr: detail,
483
+ adapter: adapterStatus(),
484
+ };
485
+ }
486
+
420
487
  function makeTool(name, description, parameterSpec, buildArgs) {
421
488
  return {
422
489
  name,
@@ -429,19 +496,44 @@ function contribute(ctx, config, rt) {
429
496
  execute: async (args, exec) => {
430
497
  assertToolArgs(name, parameterSpec, args);
431
498
  const plan = buildArgs(args);
432
- const result = await rt.runScript(
433
- plan.script,
434
- plan.argString,
435
- plan.workdir,
436
- 120000,
437
- exec
438
- );
499
+ let result;
500
+ try {
501
+ result = await rt.runScript(
502
+ plan.script,
503
+ plan.argString,
504
+ plan.workdir,
505
+ 120000,
506
+ exec
507
+ );
508
+ } catch (error) {
509
+ if (name !== "agent_guard_status") throw error;
510
+ return statusFailure("STATUS_EXECUTION_FAILED",
511
+ "Status could not run in the caller's shell environment. Check Python and the package; adapter diagnostics below remain available.");
512
+ }
439
513
  const parsed = rt.parseJson(rt.outText(result.stdout));
514
+ if (name === "agent_guard_status") {
515
+ if (result.timedOut) {
516
+ return statusFailure("STATUS_TIMEOUT",
517
+ "Status timed out. No recovery report is available; inspect the workspace before retrying.", result.exitCode);
518
+ }
519
+ if (result.exitCode !== 0) {
520
+ return statusFailure("STATUS_PROCESS_FAILED",
521
+ "Status exited unsuccessfully. Check Python, the package and recovery data.", result.exitCode);
522
+ }
523
+ if (typeof parsed?.workspace !== "string" || typeof parsed?.mode !== "string" ||
524
+ !Number.isFinite(parsed?.usage?.bytes)) {
525
+ return statusFailure("STATUS_INVALID_OUTPUT",
526
+ "Status returned no usable recovery report. Check the package and caller's shell environment.", result.exitCode);
527
+ }
528
+ }
440
529
  return {
441
530
  ok: result.exitCode === 0,
442
531
  exitCode: result.exitCode,
443
532
  report: parsed === undefined ? rt.outText(result.stdout) : parsed,
444
533
  stderr: rt.outText(result.stderr).slice(0, 2000),
534
+ ...(name === "agent_guard_status" ? {
535
+ adapter: adapterStatus(),
536
+ } : {}),
445
537
  };
446
538
  },
447
539
  };
@@ -451,7 +543,7 @@ function contribute(ctx, config, rt) {
451
543
  ctx.tools.register(
452
544
  makeTool(
453
545
  "agent_guard_status",
454
- "Show agent-guard state: authorization mode, quarantine usage, retention/GC view, recent decisions.",
546
+ "Show adapter diagnostics, recovery mode, quarantine usage and GC commands. Local status does not verify live host interception.",
455
547
  { cwd: CWD_PROP },
456
548
  (args) => ({ script: "status.py", argString: "--json", workdir: args.cwd })
457
549
  )
@@ -461,7 +553,7 @@ function contribute(ctx, config, rt) {
461
553
  ctx.tools.register(
462
554
  makeTool(
463
555
  "agent_guard_safe_delete",
464
- "Recoverable delete: globs expanded explicitly, targets quarantined to .agent-trash/ with a manifest. Preferred over raw rm.",
556
+ "Delete with the existing recovery policy: valuable targets go to quarantine and still use disk space; eligible generated artifacts may be deleted directly. Accepts paths and globs.",
465
557
  {
466
558
  paths: {
467
559
  type: "array",
@@ -512,22 +604,24 @@ function contribute(ctx, config, rt) {
512
604
  text: [
513
605
  "## Deletion discipline (agent-guard)",
514
606
  "",
515
- "This workspace runs agent-guard: an automatic recovery system with human escalation - not an approval system. Irreversible destruction is not a default capability.",
607
+ "Agent Guard checks supported destructive-looking Bash commands and provides recovery tools. Other tools and scripts may be outside its coverage.",
516
608
  "",
517
- "- To delete files/directories/globs, prefer the agent_guard_safe_delete tool: targets are quarantined under .agent-trash/ with a manifest and stay restorable. Pass cwd when operating in a repo below the workspace root.",
609
+ "- To delete files/directories/globs, prefer agent_guard_safe_delete. Valuable targets move to quarantine and still use disk space; eligible generated artifacts may be deleted directly. Pass cwd for the intended repo. Status includes GC planning and explicit purge commands.",
518
610
  "- Raw rm / git clean / git reset --hard are intercepted before execution. Most are compensated automatically (relocate or snapshot) and simply proceed; note the txid.",
519
611
  "- Shape rules: a command line that cds before deleting (COMPOUND_CWD_DELETE), or creates files and then deletes them (COMPOUND_CREATE_DELETE), triggers a single-execution user authorization. Splitting the deletion into its own standalone command avoids the prompt entirely.",
520
612
  "- True effect-uncertainty ($VAR targets, bash -c, find -delete, xargs-fed lists) stays hard-BLOCKED: restating with explicit concrete paths is the only remedy.",
521
613
  "- BLOCK_OUT_OF_WORKSPACE, BLOCK_PROTECTED_PATH (.git, workspace root) and BLOCK_FORCE_PUSH are policy violations and never askable: do not retry variants; ask the human if truly needed.",
522
614
  "- In RESTRICTED mode only explicit single-file deletes inside the workspace are permitted; only a human can restore NORMAL.",
523
- "- Never circumvent the guard (no /bin/rm, python os.unlink, node fs.rmSync, relocated scripts). Every decision is audit-logged; circumvention is a violation.",
615
+ "- Never circumvent the guard (no /bin/rm, python os.unlink, node fs.rmSync, relocated scripts). Calls outside the covered path may have no recovery or audit record.",
524
616
  "- Undo with agent_guard_restore(txid). Inspect state with agent_guard_status().",
525
617
  ].join("\n"),
526
618
  })
527
619
  );
528
620
  }
529
621
 
622
+ console.log("[agent-guard] Hook registered; local Python checker passed. Live host interception is unverified. Inspect agent_guard_status for diagnostics.");
530
623
  return () => {
624
+ rt.diagnostics.hook_registered = false;
531
625
  while (disposers.length) {
532
626
  const d = disposers.pop();
533
627
  try {
@@ -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"],