kimi-plugin-cc 2.5.4 → 2.5.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/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +14 -0
- package/dist/cli-client.js +1 -1
- package/dist/commands/setup.js +57 -6
- package/dist/hooks/config-safety.js +4 -2
- package/dist/hooks/managed-block.js +70 -71
- package/dist/kimi-engine.js +1 -0
- package/dist/kimi-version-probe.js +25 -7
- package/dist/swarm-activation.js +7 -7
- package/dist/version.js +1 -1
- package/docs/migration.md +4 -4
- package/docs/registry-releases.md +6 -2
- package/docs/safety.md +9 -9
- package/docs/swarm-recovery.md +2 -2
- package/docs/upstream-2.5.0-certification.md +2 -0
- package/docs/upstream-2.5.1-certification.md +2 -0
- package/docs/upstream-2.5.2-certification.md +40 -0
- package/package.json +2 -1
- package/plugins/kimi-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/kimi-codex/dist/cli-client.js +1 -1
- package/plugins/kimi-codex/dist/commands/setup.js +57 -6
- package/plugins/kimi-codex/dist/hooks/config-safety.js +4 -2
- package/plugins/kimi-codex/dist/hooks/managed-block.js +70 -71
- package/plugins/kimi-codex/dist/kimi-engine.js +1 -0
- package/plugins/kimi-codex/dist/kimi-version-probe.js +25 -7
- package/plugins/kimi-codex/dist/swarm-activation.js +7 -7
- package/plugins/kimi-codex/dist/version.js +1 -1
- package/plugins/kimi-dsh/dist/cli-client.js +1 -1
- package/plugins/kimi-dsh/dist/commands/setup.js +57 -6
- package/plugins/kimi-dsh/dist/hooks/config-safety.js +4 -2
- package/plugins/kimi-dsh/dist/hooks/managed-block.js +70 -71
- package/plugins/kimi-dsh/dist/kimi-engine.js +1 -0
- package/plugins/kimi-dsh/dist/kimi-version-probe.js +25 -7
- package/plugins/kimi-dsh/dist/swarm-activation.js +7 -7
- package/plugins/kimi-dsh/dist/version.js +1 -1
- package/plugins/kimi-dsh/package.json +1 -1
package/docs/safety.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
This guide describes the current checkout runtime. Read-only tasks deny file writes and shell commands. Rescue and pursue can edit your workspace. Write-swarm returns a patch from a temporary Git worktree.
|
|
4
4
|
|
|
5
|
-
Native agent-core-v2 is certified at exact CLI versions `0.42.0`, `0.43.0`, `0.43.1`, `2.0.0`, `2.0.1`, `2.0.2`, `2.1.0`, `2.1.1`, `2.2.0`, `2.3.0`, `2.3.1`, `2.3.2`, `2.3.3`, `2.4.0`, `2.4.1`, `2.5.0`, and `2.5.
|
|
5
|
+
Native agent-core-v2 is certified at exact CLI versions `0.42.0`, `0.43.0`, `0.43.1`, `2.0.0`, `2.0.1`, `2.0.2`, `2.1.0`, `2.1.1`, `2.2.0`, `2.3.0`, `2.3.1`, `2.3.2`, `2.3.3`, `2.4.0`, `2.4.1`, `2.5.0`, `2.5.1`, and `2.5.2`, with plan mode disabled. The [runtime certification table](../runtime/kimi-engine.ts) controls routing. The hook is not an operating-system sandbox.
|
|
6
6
|
|
|
7
7
|
## Why the safety story is hook-based
|
|
8
8
|
|
|
@@ -220,17 +220,17 @@ If another installed host still points to an older hook, that hook may veto thes
|
|
|
220
220
|
- **Resume is intentionally not exposed yet.** In goal mode `goal.summary` emits a *goalId* distinct from the resume-hint *sessionId*; `kimi -r <sessionId>` re-enters the session but not necessarily the goal continuation. The plugin captures and surfaces the goalId but does not offer `--resume` for pursue until that split is reconciled upstream — exposing it now would be a silent-failure trap. **Re-verified against kimi-code 0.26.0 (2026-07-16):** the headless CLI still has no argv, prompt syntax, or session-resume path that calls `resumeGoal()`. `parseHeadlessGoalCreate` (`apps/kimi-code/src/cli/goal-prompt.ts`) accepts only the `/goal <objective>` *create* shape on both the v1 and experimental-v2 drivers, and upstream's own docs (`docs/en/guides/goals.md`, § "Use goal mode carefully") state that in non-interactive prompt mode *only goal creation is supported* — goal management is a TUI/kimi-web control. PR #552 makes a plain `-r <sessionId>` correctly *restore* the paused goal snapshot, but nothing in the headless path *acts* on it; the real `resumeGoal()` is wired only to the TUI (`/goal resume`) and kimi-web RPC (PR #1693, web-only). Implementing `--resume` would therefore require either prompt-injected model compliance (rejected — the plugin bounds autonomy with hard limits, not model goodwill) or abandoning the subprocess model for kimi-web's RPC. Re-check if upstream ever ships a headless `goal resume` verb.
|
|
221
221
|
- **A model-invocable `kimi-pursue` agent (v1.3) wraps this command.** The main thread can dispatch autonomous goal mode, not just the human-typed `/kimi:pursue` — the same command↔agent mirror as rescue/review/swarm. Auto-dispatch does NOT widen the blast radius: pursue runs under `commandLabel: "rescue"`, so the managed PreToolUse hook + workspace allowlist gate every tool call on every continuation turn (no git mutation), and the mandatory `--budget` wall-clock ceiling bounds the autonomy regardless of who launched it. Because it is write-capable AND autonomous — the plugin's highest blast radius — the agent's description requires an explicit user request for hands-off multi-turn pursuit, steers single bounded tasks to `kimi-rescue`, and never auto-promotes a fix or a question into a goal loop. Like the command, it refuses without the hook and offers no `--resume`.
|
|
222
222
|
|
|
223
|
-
## Swarm activation on CLI 2.3.2, 2.3.3, 2.4.0, 2.4.1, 2.5.0 and 2.5.
|
|
223
|
+
## Swarm activation on CLI 2.3.2, 2.3.3, 2.4.0, 2.4.1, 2.5.0, 2.5.1 and 2.5.2
|
|
224
224
|
|
|
225
225
|
For interrupted runs, see [durable recovery and its explicit limits](swarm-recovery.md).
|
|
226
226
|
|
|
227
227
|
Upstream 2.3.2 removes model self-activation of `AgentSwarm` in fresh print sessions. A rejected call can therefore coexist with zero child journals and a successful exit; a tool-call record, aggregate denial, or coordinator-produced patch does not prove fan-out. The plugin does not use prompt workarounds or replace its print transport with general RPC.
|
|
228
228
|
|
|
229
|
-
For versions requiring activation (currently exact 2.3.2, 2.3.3, 2.4.0, 2.4.1, 2.5.0 and 2.5.
|
|
229
|
+
For versions requiring activation (currently exact 2.3.2, 2.3.3, 2.4.0, 2.4.1, 2.5.0, 2.5.1 and 2.5.2), both slash-command and MCP swarm operations use the same `runSwarm` implementation and one ordinary `kimi -p -r` prompt runner per job, bracketed by short-lived host-managed web lifecycles:
|
|
230
230
|
|
|
231
|
-
1. The exact planned CLI starts `web --no-open --host 127.0.0.1 --port 0 --log-level error`. The child environment sets `KIMI_CODE_SESSION_IDLE_RECLAIM_MS=0`, so ambient idle-session reclamation cannot disrupt the plugin-owned lifecycle. The plugin accepts only the expected loopback ready URL, uses a supplied token for authenticated REST requests, and keeps that token in memory, never writing it to logs. `/api/v1/meta` must confirm backend v2, the exact planned version, and no dangerous authentication bypass. The plugin uses the explicit model or environment-model alias, otherwise reading the default alias from `/api/v1/config`; creates a session in the job cwd; on exact 2.5.0/2.5.1 explicitly binds `environment_id:"local"` and the job cwd, then verifies that binding through authenticated `/environment` before either profile mutation; binds the selected model with `permission_mode:auto` and `swarm_mode:true`; verifies those settings and `plan_mode:false` through `/status` on earlier versions or protocol-v2 authenticated WebSocket main-agent state on 2.5.0/2.5.1, closing that channel before validating the latest frame; verifies clean shutdown; and requires the main journal's manual `swarm_mode.enter` record.
|
|
231
|
+
1. The exact planned CLI starts `web --no-open --host 127.0.0.1 --port 0 --log-level error`. The child environment sets `KIMI_CODE_SESSION_IDLE_RECLAIM_MS=0`, so ambient idle-session reclamation cannot disrupt the plugin-owned lifecycle. The plugin accepts only the expected loopback ready URL, uses a supplied token for authenticated REST requests, and keeps that token in memory, never writing it to logs. `/api/v1/meta` must confirm backend v2, the exact planned version, and no dangerous authentication bypass. The plugin uses the explicit model or environment-model alias, otherwise reading the default alias from `/api/v1/config`; creates a session in the job cwd; on exact 2.5.0/2.5.1/2.5.2 explicitly binds `environment_id:"local"` and the job cwd, then verifies that binding through authenticated `/environment` before either profile mutation; binds the selected model with `permission_mode:auto` and `swarm_mode:true`; verifies those settings and `plan_mode:false` through `/status` on earlier versions or protocol-v2 authenticated WebSocket main-agent state on 2.5.0/2.5.1/2.5.2, closing that channel before validating the latest frame; verifies clean shutdown; and requires the main journal's manual `swarm_mode.enter` record.
|
|
232
232
|
2. The ordinary stream-json print runner resumes that session with `kimi -p -r`. The job records `kimi_session_id_source:"preactivated"`, and the session returned by print must exactly match the preactivated id. Every coordinator and child tool call remains governed by the same managed PreToolUse hook and operation allowlist.
|
|
233
|
-
3. After the print run, a second web lifecycle rechecks the local binding on 2.5.0/2.5.1, sets `swarm_mode:false`, verifies the version-appropriate state proof, shuts down cleanly, and requires `swarm_mode.exit` in the main journal. Activation consumes part of the same finite job budget rather than extending it. `runSwarm` solely owns session deactivation: normal cleanup uses the remaining budget, while failure recovery has a separate two-second cancellation-aware bound and is never retried. Print/session failures stay primary, with exit codes and cleanup diagnostics preserved. Cancellation aborts the owned lifecycle and never starts a fresh cleanup server. Every post-mutation failure retains the session identity; process/group uncertainty is marked without inventing an ID; process groups are rechecked after teardown, unknown survivors are unverified, unproven groups are never signalled, and a same-PID/start-token process that changes PGID remains active but is not a validated signal target. Root loss requires a previously observed matching identity; first-missing roots and actual probe errors/timeouts remain unverified. Reparenting and PGID moves preserve the current verified child identity for revalidation rather than treating it as exited. Unverified cleanup prevents success and preserves raw output, structured diagnostics, and the write worktree for recovery.
|
|
233
|
+
3. After the print run, a second web lifecycle rechecks the local binding on 2.5.0/2.5.1/2.5.2, sets `swarm_mode:false`, verifies the version-appropriate state proof, shuts down cleanly, and requires `swarm_mode.exit` in the main journal. Activation consumes part of the same finite job budget rather than extending it. `runSwarm` solely owns session deactivation: normal cleanup uses the remaining budget, while failure recovery has a separate two-second cancellation-aware bound and is never retried. Print/session failures stay primary, with exit codes and cleanup diagnostics preserved. Cancellation aborts the owned lifecycle and never starts a fresh cleanup server. Every post-mutation failure retains the session identity; process/group uncertainty is marked without inventing an ID; process groups are rechecked after teardown, unknown survivors are unverified, unproven groups are never signalled, and a same-PID/start-token process that changes PGID remains active but is not a validated signal target. Root loss requires a previously observed matching identity; first-missing roots and actual probe errors/timeouts remain unverified. Reparenting and PGID moves preserve the current verified child identity for revalidation rather than treating it as exited. Unverified cleanup prevents success and preserves raw output, structured diagnostics, and the write worktree for recovery.
|
|
234
234
|
|
|
235
235
|
Older certified versions keep the direct `kimi -p` path. The web processes are narrow, planned lifecycle helpers, not a second model runner and not a general RPC transport.
|
|
236
236
|
|
|
@@ -239,7 +239,7 @@ Older certified versions keep the direct `kimi -p` path. The web processes are n
|
|
|
239
239
|
`/kimi:swarm` (v1.2) fans a **read-only** review out across subagents using kimi-code's `AgentSwarm` tool (kimi-code 0.12.0+). The coordinator launches one subagent per target (file/module/question); each inspects the workspace with read tools and reports findings, which the coordinator consolidates into one markdown report. It opens **zero new write surface**.
|
|
240
240
|
|
|
241
241
|
- **The hook label is `swarm`, and it allows the read-only tool set PLUS `AgentSwarm`.** The coordinator must be allowed to call `AgentSwarm` (else the swarm never launches), but no write/edit/shell tool is allowed. The exact allowed tool name is `AgentSwarm` (verified at 0.42.0 against `packages/agent-core-v2/src/features/swarm/tools/agent-swarm/agentSwarmTool.ts`: `'AgentSwarm'`, strict schema). The singular `Agent` tool is deliberately *not* allowed — swarm is the fan-out surface, not arbitrary delegation.
|
|
242
|
-
- **Every subagent inherits the `swarm` label and fires the same hook.** On native v2 (0.42.0) `AgentSwarm` children run in-process in a child DI scope with their OWN eager external-hooks service, so every child tool call passes the same before-execute channel and the same managed hook — there is no sub-vs-main branch and no deny-all shortcut on the swarm route. So a subagent's `Write`/`Edit`/`Bash` is denied exactly like a single-turn review's. The swarm listener in that channel is non-terminal and nothing auto-approves `AgentSwarm` ahead of the hook. (Legacy-v1 ≤ 0.41 reached the same result by placing the hook policy at index 0 of every agent's permission stack.) **Required for final certification evidence** (`tests/runtime/real-binary-smoke.test.ts`, run via `bun run smoke:real`): distinct child journals must exist, and each assigned Write/Edit `path` must be correlated through its `toolCallId` with the managed denial in that exact tool result; unrelated denials and coordinator-only reports are insufficient. On 2.3.2, 2.3.3, 2.4.0, 2.4.1, 2.5.0 and 2.5.
|
|
242
|
+
- **Every subagent inherits the `swarm` label and fires the same hook.** On native v2 (0.42.0) `AgentSwarm` children run in-process in a child DI scope with their OWN eager external-hooks service, so every child tool call passes the same before-execute channel and the same managed hook — there is no sub-vs-main branch and no deny-all shortcut on the swarm route. So a subagent's `Write`/`Edit`/`Bash` is denied exactly like a single-turn review's. The swarm listener in that channel is non-terminal and nothing auto-approves `AgentSwarm` ahead of the hook. (Legacy-v1 ≤ 0.41 reached the same result by placing the hook policy at index 0 of every agent's permission stack.) **Required for final certification evidence** (`tests/runtime/real-binary-smoke.test.ts`, run via `bun run smoke:real`): distinct child journals must exist, and each assigned Write/Edit `path` must be correlated through its `toolCallId` with the managed denial in that exact tool result; unrelated denials and coordinator-only reports are insufficient. On 2.3.2, 2.3.3, 2.4.0, 2.4.1, 2.5.0, 2.5.1 and 2.5.2, targeted controls also prove that direct OFF produces no children while the preactivated ON path produces the real child journals and denials.
|
|
243
243
|
- **The managed hook is the read-only boundary; no `explore`-profile second layer is assumed.** Production deliberately omits `subagent_type` for read-only swarm rather than selecting kimi-code's `explore` profile. Every coordinator and subagent tool call is enforced by the same managed hook.
|
|
244
244
|
- **Swarm refuses without the hook, like every model-spawning command.** A swarm makes the reason especially acute: it asks for up to `--cap` subagents, but this total-count hint is advisory, so a missing hook would remove enforcement from all of them at once. `KIMI_PLUGIN_CC_SKIP_HOOK_CHECK=1` remains an explicit tests/diagnostics escape hatch, not a recovery path.
|
|
245
245
|
- **The only new risk is COST, and the plugin bounds it.** Read-only swarm writes nothing, so the new risk is runaway cost from N parallel model runs (and possible nested `AgentSwarm`). `/kimi:swarm` enforces a **mandatory finite wall-clock ceiling** via its AbortController (`--budget`, default 30m); the SIGTERM→SIGKILL descendant-reaping cancellation reaps the whole subagent process tree. Two **distinct** subagent bounds: `--cap N` is a *soft* prompt-injected hint on TOTAL subagent count (the hook is stateless and cannot enforce a count, so the model may exceed it), and `--max-concurrency N` is a *hard* ceiling on how many subagents kimi-code's `SubagentBatch` runs concurrently — exported as `KIMI_CODE_AGENT_SWARM_MAX_CONCURRENCY` (PR #888) on **kimi-code 0.18.0+** (older binaries ignore the unknown env var, so on < 0.18 only the soft hint applies). It **defaults to 4** when the user passes none (`resolveSwarmMaxConcurrency` in swarm.ts), so every swarm run — agent-dispatched or human-typed — carries an enforced peak-parallelism ceiling on 0.18.0+ rather than falling back to kimi-code's internal ramp; pass an explicit value to widen or throttle. **Never merge them into one flag:** concurrency ≠ total count — a hard concurrency cap of N still permits more than N subagents over the life of the run, just never more than N at once. The `--budget` bounds elapsed time, not a dollar amount or total token count; `--max-concurrency` bounds *peak* parallelism (the spike in simultaneous model spend), and `--cap` is only an advisory total-count nudge. Folding both onto one flag would create the "cap-as-total-count illusion" — a user reading `--cap N` would expect a total bound but receive only a peak-parallelism one.
|
|
@@ -298,7 +298,7 @@ worktree. A directory the operator trusted interactively in the Kimi TUI still
|
|
|
298
298
|
has that property; that persisted-trust route is a documented residual, not
|
|
299
299
|
something the plugin can close.
|
|
300
300
|
|
|
301
|
-
Plugin-managed execution must remain local. Unused remote declarations can remain in operator config, but a configured remote default refuses before spawn. Disabling workspace trust through `[workspace] require_trust = false` also refuses, because it would enable project MCP outside the managed hook. Launcher environment selectors are reserved. Fresh exact 2.5.0/2.5.1 print selects `--environment local`; resume instead inspects persisted metadata and every agent journal and refuses nonlocal or wrong-root records against the expected execution root (the isolated worktree for swarm-write); older sessions without environment records do not fail this check merely for lacking them.
|
|
301
|
+
Plugin-managed execution must remain local. Unused remote declarations can remain in operator config, but a configured remote default refuses before spawn. Disabling workspace trust through `[workspace] require_trust = false` also refuses, because it would enable project MCP outside the managed hook. Launcher environment selectors are reserved. Fresh exact 2.5.0/2.5.1/2.5.2 print selects `--environment local`; resume instead inspects persisted metadata and every agent journal and refuses nonlocal or wrong-root records against the expected execution root (the isolated worktree for swarm-write); older sessions without environment records do not fail this check merely for lacking them.
|
|
302
302
|
|
|
303
303
|
## Running a newer Kimi than the plugin certifies
|
|
304
304
|
|
|
@@ -310,9 +310,9 @@ at it (the runtime resolves that path instead of `kimi` on `PATH`; every spawn
|
|
|
310
310
|
still exports `KIMI_CODE_NO_AUTO_UPDATE=1`, so the pinned copy never drifts).
|
|
311
311
|
|
|
312
312
|
```sh
|
|
313
|
-
PIN=~/.local/share/kimi-plugin-cc/kimi-bin/2.5.
|
|
313
|
+
PIN=~/.local/share/kimi-plugin-cc/kimi-bin/2.5.2
|
|
314
314
|
mkdir -p "$PIN" && cd "$PIN" && printf '{"name":"kimi-plugin-cc-pin","private":true}\n' > package.json
|
|
315
|
-
npm install @moonshot-ai/kimi-code@2.5.
|
|
315
|
+
npm install @moonshot-ai/kimi-code@2.5.2
|
|
316
316
|
export KIMI_PLUGIN_CC_KIMI_BIN="$PIN/node_modules/.bin/kimi" # e.g. in ~/.zshenv
|
|
317
317
|
```
|
|
318
318
|
|
package/docs/swarm-recovery.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Normal stop: use `scripts/companion.sh cancel` for a shell-owned run, or the MCP job cancel tool for an MCP-owned run. A hard kill cannot execute cleanup. Cancellation still starts no fresh cleanup server.
|
|
4
4
|
|
|
5
|
-
For exact CLI 2.3.2, 2.3.3, 2.4.0, 2.4.1 and 2.5.0/2.5.1 swarm runs created by this runtime, status includes a durable `swarm_recovery` record. It contains the resolved home/workspace, companion identity, launch intent, verified process identities and session identity. It never contains the web authentication token, credentials, prompt or config contents. Session identity is committed before the request enabling swarm mode.
|
|
5
|
+
For exact CLI 2.3.2, 2.3.3, 2.4.0, 2.4.1 and 2.5.0/2.5.1/2.5.2 swarm runs created by this runtime, status includes a durable `swarm_recovery` record. It contains the resolved home/workspace, companion identity, launch intent, verified process identities and session identity. It never contains the web authentication token, credentials, prompt or config contents. Session identity is committed before the request enabling swarm mode.
|
|
6
6
|
|
|
7
7
|
## Preview, then recover
|
|
8
8
|
|
|
@@ -17,7 +17,7 @@ Preview does not signal processes, modify sessions, or capture patches. Apply:
|
|
|
17
17
|
|
|
18
18
|
1. Requires the original companion to be gone and acquires an identity-checked recovery claim. A second recovery cannot race the first; a dead recovery owner can be reclaimed by compare-and-swap.
|
|
19
19
|
2. Revalidates recorded processes and groups. It stops only verified individual identities, never a guessed PID or unproven group. An unknown surviving group member, changed group, incomplete probe or unrecorded launch refuses recovery.
|
|
20
|
-
3. If session cleanup is pending, requires the selected exact certified CLI and valid managed hook. It starts one bounded authenticated web lifecycle, disables the recorded session's swarm mode, verifies the version-appropriate state proof and exit journal, then verifies process quiescence. On 2.5.0/2.5.1 this includes the local environment binding and protocol-v2 WebSocket main-agent state rather than `/status`. It does not resume a prompt, generate model output, install hooks or retry failed cleanup automatically. New recovery web launches are themselves journaled.
|
|
20
|
+
3. If session cleanup is pending, requires the selected exact certified CLI and valid managed hook. It starts one bounded authenticated web lifecycle, disables the recorded session's swarm mode, verifies the version-appropriate state proof and exit journal, then verifies process quiescence. On 2.5.0/2.5.1/2.5.2 this includes the local environment binding and protocol-v2 WebSocket main-agent state rather than `/status`. It does not resume a prompt, generate model output, install hooks or retry failed cleanup automatically. New recovery web launches are themselves journaled.
|
|
21
21
|
4. Captures a binary patch from a retained write worktree. It does not apply the patch or delete the tree. The result names both paths for inspection.
|
|
22
22
|
|
|
23
23
|
The recovery attempt has a 30-second cancellation signal, with bounded identity probes and normal teardown. Interrupting recovery retains its journal. An already-recovered record is an idempotent no-op. Failed/cancelled/completed job outcomes are immutable; a previously running abandoned job becomes failed, never completed. Recovery status is separate from task success.
|
|
@@ -48,3 +48,5 @@ After the original certification, Linux release CI exposed a platform-specific e
|
|
|
48
48
|
A subsequent CI attempt showed that native WebSocket close scheduling and `wasClean` semantics vary by platform and cannot supply a deterministic no-close-event precondition. That timeout case now uses a controlled socket which completes the protocol exchange but never emits `close`, and asserts the exact `Kimi web agent-state verification timed out.` message. The refusal is therefore tested without relying on incidental host close timing; production behavior is unchanged by this test-only follow-up.
|
|
49
49
|
|
|
50
50
|
**Follow-up correction:** a later normal activation/deactivation fixture showed that `wasClean` can also reject a valid close. The production condition has been reverted on `main`, restoring the original certified bounded-close settlement; the controlled no-close-event test and protocol-correct mock handshake remain. The immutable 2.5.3 artifact contains the trial condition, so carrying this revert requires a new patch artifact rather than a re-tag or republish.
|
|
51
|
+
|
|
52
|
+
The correction ships as plugin 2.5.4 ([release](https://github.com/linxule/kimi-plugin-cc/releases/tag/v2.5.4)), with registry artifact and fresh-install verification recorded in [registry releases](registry-releases.md).
|
|
@@ -43,3 +43,5 @@ After the original certification and independent review, Linux release CI expose
|
|
|
43
43
|
A subsequent CI attempt showed that native WebSocket close scheduling and `wasClean` semantics vary by platform and cannot supply a deterministic no-close-event precondition. That timeout case now uses a controlled socket which completes the protocol exchange but never emits `close`, and asserts the exact `Kimi web agent-state verification timed out.` message. The refusal is therefore tested without relying on incidental host close timing; production behavior is unchanged by this test-only follow-up.
|
|
44
44
|
|
|
45
45
|
**Follow-up correction:** a later normal activation/deactivation fixture showed that `wasClean` can also reject a valid close. The production condition has been reverted on `main`, restoring the original certified bounded-close settlement; the controlled no-close-event test and protocol-correct mock handshake remain. The immutable 2.5.3 artifact contains the trial condition, so carrying this revert requires a new patch artifact rather than a re-tag or republish.
|
|
46
|
+
|
|
47
|
+
The correction ships as plugin 2.5.4 ([release](https://github.com/linxule/kimi-plugin-cc/releases/tag/v2.5.4)), with registry artifact and fresh-install verification recorded in [registry releases](registry-releases.md).
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Kimi Code 2.5.2 certification evidence — 2026-11-07
|
|
2
|
+
|
|
3
|
+
## Status and exact source
|
|
4
|
+
|
|
5
|
+
**Exact CLI 2.5.2 is certified for all eight operations by plugin 2.5.6.** The exact-source audit, non-vacuous plan/environment/swarm controls, candidate matrix, production-table matrix, frozen install, full repository check, package validation and isolated consumer-security audit passed. An independent read-only Codex review raised no safety or bypass finding. It caught a too-strong sentence about pending tools, stale activation lists in `docs/ci.md` and `docs/safety.md`, and regenerated distributions still pending at review time; all are corrected here.
|
|
6
|
+
|
|
7
|
+
Candidate: `@moonshot-ai/kimi-code@2.5.2`, release commit `1c142a007c10e881602690def96057c23a2baa12`, compared with certified 2.5.1 (`1b02030d8c2c6b00131b23ebb67a231614877827`). npm publication: 2026-11-06T07:54:31.132Z. An isolated npm installation and its executable both report 2.5.2; its `dist/main.mjs` SHA-256 is `b158343c177414e2a615116a96e193b333ca183bb0ee9569e51b0f4569e3a23e`. The seven scoped 2.5.1→2.5.2 diffs and the out-of-scope diffs are retained under `.claude/kimi-code-research/daily-monitor/2026-11-07-2.5.2-diffs/`.
|
|
8
|
+
|
|
9
|
+
## Source and integration review
|
|
10
|
+
|
|
11
|
+
- All seven playbook scopes are empty: print/CLI, before-execute and permission gates, external hooks, plan/restore, session bootstrap/config/workspace, tools/fan-out/SDK, and swarm/web activation.
|
|
12
|
+
- Outside those scopes, 2.5.2 changes six agent-core-v2 files: MCP tool registration (`agent/mcp/mcpService.ts`), the tool registry's new active/pending split (`agent/toolRegistry/*`), tool-select reconciliation with a `tool_update_pending` reminder (`agent/toolSelect/*`), and signature helpers moved into `tool/toolContract.ts`. Web assets and the package version also change.
|
|
13
|
+
- A new name registers as active immediately. A registration becomes pending only when an active tool with the same name exists and its definition signature differs; a same-signature replacement swaps in place. The pending replacement is held outside the active map, and `ToolRegistryService.resolve()` reads only active tools, so a call by that name runs the existing active implementation until reconciliation promotes the replacement. Every active tool runs through the unchanged executor and its single `fireBeforeExecute` emitter, so the PreToolUse payload still carries the original call name. Tool names, and the field names the approval policy reads, are unchanged.
|
|
14
|
+
- All 40 pinned files are byte-identical to 2.5.1. The exact-tag scan passed **18 tests and 153 assertions** on 2.5.2, with the print, environment/workspace-trust and WebSocket checks executing. The 2.5.1 and 2.5.0 source scans pass again with the same counts.
|
|
15
|
+
- The exact-version branches now include 2.5.2: the production table, swarm preactivation and protocol-v2 agent state, fresh `--environment local`, and the reviewed hook schema. 2.5.3, prerelease and build-suffixed versions stay refused. Focused engine, activation, CLI, setup and version-probe tests passed **331 tests with 0 failures**.
|
|
16
|
+
|
|
17
|
+
## Exact-binary controls
|
|
18
|
+
|
|
19
|
+
Controls used the read-only Agent Keys API key, resolved only into each process, and empty isolated homes with absolute paths. The forced removed-tool control instead used a loopback scripted provider. No personal config or OAuth store was read, copied or symlinked. Controls ran sequentially, and a scan of the evidence tree found no key material. Raw evidence is under `.claude/kimi-code-research/cert-2.5.2-live/`.
|
|
20
|
+
|
|
21
|
+
- **Plan OFF Write:** the exact 2.5.2 marker came first. Write reached the custom deny-all hook and was denied; no target file or plan state was created.
|
|
22
|
+
- **Plan ON:** an armed plan journal let Glob reach the deny hook, and a **1,656-byte** plan file was written without a plan-Write hook invocation. This shows the bypass the no-plan closures exist to prevent. The workspace stayed empty.
|
|
23
|
+
- **Removed EnterPlanMode:** EnterPlanMode was absent from the offered tools. A forced call was rejected on the same call ID before any hook ran, and the rejection was returned to the provider. No plan state or files appeared.
|
|
24
|
+
- **Environment:** real activation and deactivation passed with the explicit local binding. A remote default, disabled workspace trust and a resumed remote binding each refused before spawn.
|
|
25
|
+
- **Swarm OFF:** a real AgentSwarm call returned the inactive-mode result with zero child journals and no probe files.
|
|
26
|
+
- **Swarm ON:** preactivation produced `agent-0` and `agent-1`. Each child's assigned Write was matched to a managed-denial result on the same toolCallId, no probes landed, and deactivation was verified with ambient idle reclamation set to 1 ms.
|
|
27
|
+
- **Out-of-root control:** child Writes outside the root were denied on their own call IDs, created no files, and deactivation was verified.
|
|
28
|
+
|
|
29
|
+
## Candidate and production matrices
|
|
30
|
+
|
|
31
|
+
Both matrices ran through the new pre-authorized monitor route, `~/.local/bin/kimi-plugin-cc-monitor-smoke`. It installs the exact binary once under `~/.cache/kimi-plugin-cc-monitor/` (same `dist/main.mjs` SHA-256 as above), uses the read-only Agent Keys API key, seeds from an empty temp home and redacts the log.
|
|
32
|
+
|
|
33
|
+
- **Candidate** (`candidate-smoke.log`, `KIMI_PLUGIN_CC_SMOKE_V2_CANDIDATE=2.5.2`): **24 tests with 167 assertions and no skips in 391.42 seconds**. Review, challenge, ask and review_gate each received a same-call managed Write denial. Real rescue confinement, the Bash.cwd denial, resume and plan-taint refusal, and both pursue outcomes passed. Six goal turns each had a managed Write denial, and the goal workspace was empty at settlement. Write-swarm captured a **278-byte** child-authored patch with a clean user tree and removed worktree, and denied the out-of-root write.
|
|
34
|
+
- **Production table** (`production-smoke.log`, candidate override unset): **24 tests with 167 assertions and no skips in 399.68 seconds**. It independently repeated the same evidence. Six of seven goal turns carried managed denials; the seventh was cut by the budget abort, and the workspace was empty at settlement. Write-swarm again captured a 278-byte patch.
|
|
35
|
+
|
|
36
|
+
A scan of both logs found no key material.
|
|
37
|
+
|
|
38
|
+
## Repository and package gates
|
|
39
|
+
|
|
40
|
+
Frozen dependency installation made no changes. The full `bun run check` passed **1,429 tests with 33 expected opt-in skips, 0 failures and 18,662 assertions across 82 files in 356.03 seconds**, including the generated-distribution drift gate. Package validation passed **331 files**, all three compiled distributions, isolated hook setup/check and version refusal, and a patched DSH host/profile with seven live providers/tools and Web boot. The isolated npm consumer-security audit passed. Logs: `check-standard.log`, `package-standard.log`, `consumer-security.log`, `tag-scan*.log` and `binary-sha256.txt` under `.claude/kimi-code-research/cert-2.5.2-live/`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "kimi-plugin-cc",
|
|
3
|
-
"version": "2.5.
|
|
3
|
+
"version": "2.5.6",
|
|
4
4
|
"description": "Kimi for Claude Code, Codex, and DeepSeek Harness: code questions, independent reviews, bounded fixes, autonomous goals, parallel tasks, and MCP tools through the local Kimi Code CLI.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/dsh/index.js",
|
|
@@ -136,6 +136,7 @@
|
|
|
136
136
|
"docs/upstream-2.4.1-certification.md",
|
|
137
137
|
"docs/upstream-2.5.0-certification.md",
|
|
138
138
|
"docs/upstream-2.5.1-certification.md",
|
|
139
|
+
"docs/upstream-2.5.2-certification.md",
|
|
139
140
|
"README.md",
|
|
140
141
|
"LICENSE",
|
|
141
142
|
"CHANGELOG.md",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "kimi",
|
|
3
|
-
"version": "2.5.
|
|
3
|
+
"version": "2.5.6",
|
|
4
4
|
"description": "Kimi for Codex: code questions, independent reviews, bounded fixes, autonomous goals, parallel tasks, and MCP job controls through the local Kimi Code CLI.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "linxule"
|
|
@@ -786,7 +786,7 @@ function buildArgs(opts) {
|
|
|
786
786
|
? opts.env.KIMI_PLUGIN_CC_SMOKE_V2_CANDIDATE
|
|
787
787
|
: undefined;
|
|
788
788
|
if (opts.resumeSessionId === undefined &&
|
|
789
|
-
["2.5.0", "2.5.1"].includes(opts.executionPlan.kimiVersion ?? smokeCandidate ?? "")) {
|
|
789
|
+
["2.5.0", "2.5.1", "2.5.2"].includes(opts.executionPlan.kimiVersion ?? smokeCandidate ?? "")) {
|
|
790
790
|
args.push("--environment", "local");
|
|
791
791
|
}
|
|
792
792
|
if (opts.resumeSessionId !== undefined) {
|
|
@@ -26,9 +26,9 @@ import { readPluginConfig, writePluginConfig } from "../config.js";
|
|
|
26
26
|
import { RuntimeError } from "../errors.js";
|
|
27
27
|
import { normalizeTopLevelInlineHooks, validateKimiHookSetForEnvironment, withKimiConfigLock, } from "../hooks/config-safety.js";
|
|
28
28
|
import { buildHookShellCommand, hostIdFromHookCommand, resolveHookScriptPath, resolveHostId, resolveNodeBinary, } from "../hooks/install-paths.js";
|
|
29
|
-
import { decodeManagedCommandLine, effectiveHost, evaluateInstalled, findUnmanagedApprovalHookBlocks, markerCommentLines, MARKERS, parseManagedBlock, } from "../hooks/managed-block.js";
|
|
29
|
+
import { decodeManagedCommandLine, effectiveHost, evaluateInstalled, findUnmanagedApprovalHookBlocks, markerCommentLines, MARKERS, ORPHAN_MARKER_REMEDY, parseManagedBlock, } from "../hooks/managed-block.js";
|
|
30
30
|
import { formatVersionOutOfRangeWarning, probeKimiVersion, } from "../kimi-version-probe.js";
|
|
31
|
-
import { isNativeV2CertifiedVersion } from "../kimi-engine.js";
|
|
31
|
+
import { isNativeV2CertifiedVersion, NATIVE_V2_CERTIFIED_VERSIONS } from "../kimi-engine.js";
|
|
32
32
|
import { resolveKimiHome } from "../kimi-home.js";
|
|
33
33
|
import { ensurePluginPaths, resolvePluginPaths } from "../paths.js";
|
|
34
34
|
import { KIMI_PLUGIN_CC_VERSION } from "../version.js";
|
|
@@ -180,7 +180,7 @@ async function runInstall(configPath, hookScriptPath, hostId, reviewGateEnabled,
|
|
|
180
180
|
const block = buildManagedBlock(hookScriptPath, context.env, lineEnding, hostId);
|
|
181
181
|
const next = state.kind === "found"
|
|
182
182
|
? spliceBlock(existing, state.beginLine, state.endLine, block, lineEnding)
|
|
183
|
-
:
|
|
183
|
+
: insertBlockNearManagedBlocks(existing, blocks, block, lineEnding);
|
|
184
184
|
await assertKimiHookSetValid(next, configPath, "setup.install", context.env);
|
|
185
185
|
const blockWritten = next !== original;
|
|
186
186
|
if (blockWritten)
|
|
@@ -256,7 +256,10 @@ async function runCheck(configPath, hookScriptPath, hostId, reviewGateEnabled, w
|
|
|
256
256
|
nodeExists: (binPath) => existsSync(binPath),
|
|
257
257
|
});
|
|
258
258
|
// Non-blocking coexistence + cruft notices.
|
|
259
|
-
const { blocks: allBlocks } = parseManagedBlock(existing, hostId);
|
|
259
|
+
const { blocks: allBlocks, foreignOrphans } = parseManagedBlock(existing, hostId);
|
|
260
|
+
for (const orphan of foreignOrphans) {
|
|
261
|
+
warnings.push(`Host "${orphan.hostId}" has an orphaned ${orphan.detail} managed marker at line ${orphan.line + 1}; that host's commands refuse until it is repaired. ${ORPHAN_MARKER_REMEDY}`);
|
|
262
|
+
}
|
|
260
263
|
const otherHosts = [
|
|
261
264
|
...new Set(allBlocks.map((b) => effectiveHost(b, hostId)).filter((h) => h !== hostId)),
|
|
262
265
|
];
|
|
@@ -303,7 +306,9 @@ async function runCheck(configPath, hookScriptPath, hostId, reviewGateEnabled, w
|
|
|
303
306
|
reviewGateEnabled,
|
|
304
307
|
nextStep: installedCheck.state.kind === "absent"
|
|
305
308
|
? "Run /kimi:setup (without --check) to install the managed block."
|
|
306
|
-
:
|
|
309
|
+
: installedCheck.state.kind === "orphan"
|
|
310
|
+
? ORPHAN_MARKER_REMEDY
|
|
311
|
+
: "Run /kimi:setup --uninstall, then /kimi:setup to repair.",
|
|
307
312
|
details: buildDetails({
|
|
308
313
|
configPath,
|
|
309
314
|
hookScriptPath,
|
|
@@ -535,6 +540,52 @@ function spliceBlock(contents, beginLine, endLine, replacement, lineEnding) {
|
|
|
535
540
|
const replacementWithEnding = replacement.endsWith(lineEnding) ? replacement : `${replacement}${lineEnding}`;
|
|
536
541
|
return `${beforeWithSep}${replacementWithEnding}${after}`;
|
|
537
542
|
}
|
|
543
|
+
// Keep every host's block in one contiguous run. Magpie's table rewrite drops
|
|
544
|
+
// comments that follow a table it owns (yetone/magpie#5614): a block appended
|
|
545
|
+
// after such a table loses its BEGIN marker and header, leaving an orphan END.
|
|
546
|
+
// Insert after the last managed END only when nothing but blanks/comments
|
|
547
|
+
// precedes the next header AND the real parser proves the result equals the
|
|
548
|
+
// appended form apart from hook order, so no field can rebind and no value can
|
|
549
|
+
// be split; otherwise append.
|
|
550
|
+
function insertBlockNearManagedBlocks(contents, blocks, block, lineEnding) {
|
|
551
|
+
if (blocks.length === 0)
|
|
552
|
+
return appendBlock(contents, block, lineEnding);
|
|
553
|
+
const anchor = Math.max(...blocks.map((b) => b.endLine));
|
|
554
|
+
const lines = splitPreservingEnding(contents);
|
|
555
|
+
for (let i = anchor + 1; i < lines.length; i += 1) {
|
|
556
|
+
const trimmed = lines[i].trim();
|
|
557
|
+
if (trimmed.startsWith("["))
|
|
558
|
+
break;
|
|
559
|
+
if (trimmed.length > 0 && !trimmed.startsWith("#"))
|
|
560
|
+
return appendBlock(contents, block, lineEnding);
|
|
561
|
+
}
|
|
562
|
+
const rawLines = contents.split(/(?<=\n)/);
|
|
563
|
+
const head = rawLines.slice(0, anchor + 1).join("");
|
|
564
|
+
const tail = rawLines.slice(anchor + 1).join("");
|
|
565
|
+
const appended = appendBlock(contents, block, lineEnding);
|
|
566
|
+
if (tail.length === 0)
|
|
567
|
+
return appended;
|
|
568
|
+
const headWithEnding = head.endsWith("\n") ? head : `${head}${lineEnding}`;
|
|
569
|
+
const body = block.endsWith(lineEnding) ? block : `${block}${lineEnding}`;
|
|
570
|
+
const tailSeparator = /^\r?\n/.test(tail) ? "" : lineEnding;
|
|
571
|
+
const inserted = `${headWithEnding}${lineEnding}${body}${tailSeparator}${tail}`;
|
|
572
|
+
return sameTomlIgnoringHookOrder(inserted, appended) ? inserted : appended;
|
|
573
|
+
}
|
|
574
|
+
function sameTomlIgnoringHookOrder(a, b) {
|
|
575
|
+
const canonical = (text) => {
|
|
576
|
+
const parsed = parseToml(text);
|
|
577
|
+
const hooks = Array.isArray(parsed.hooks)
|
|
578
|
+
? parsed.hooks.map((entry) => JSON.stringify(entry)).sort()
|
|
579
|
+
: parsed.hooks;
|
|
580
|
+
return JSON.stringify({ ...parsed, hooks });
|
|
581
|
+
};
|
|
582
|
+
try {
|
|
583
|
+
return canonical(a) === canonical(b);
|
|
584
|
+
}
|
|
585
|
+
catch {
|
|
586
|
+
return false;
|
|
587
|
+
}
|
|
588
|
+
}
|
|
538
589
|
function appendBlock(contents, block, lineEnding) {
|
|
539
590
|
const base = contents.length === 0 || contents.endsWith(lineEnding) ? contents : `${contents}${lineEnding}`;
|
|
540
591
|
const separator = base.length === 0 ? "" : lineEnding;
|
|
@@ -928,7 +979,7 @@ async function collectKimiVersionWarnings(env, warnings) {
|
|
|
928
979
|
// v2-certified binary would wrongly warn "not certified, commands will refuse".
|
|
929
980
|
if (probe.inTestedRange || isNativeV2CertifiedVersion(probe.version))
|
|
930
981
|
return;
|
|
931
|
-
warnings.push(formatVersionOutOfRangeWarning(probe, KIMI_PLUGIN_CC_VERSION));
|
|
982
|
+
warnings.push(formatVersionOutOfRangeWarning(probe, KIMI_PLUGIN_CC_VERSION, NATIVE_V2_CERTIFIED_VERSIONS));
|
|
932
983
|
}
|
|
933
984
|
/**
|
|
934
985
|
* Non-blocking notice for kimi-code's own enabled plugins from
|
|
@@ -595,7 +595,8 @@ function validateVersionSensitiveEvents(events, version) {
|
|
|
595
595
|
// Exact schemas reviewed at 2.0.0 (1b89e4b0), 2.0.1 (caf7d4e2),
|
|
596
596
|
// 2.0.2 (9d07f634), 2.1.0 (52437299), 2.1.1 (f67e6398), 2.2.0 (472192c3),
|
|
597
597
|
// 2.3.0 (b5e28fd6), 2.3.1 (684bae9e), 2.3.2 (b8dd3a13), 2.3.3 (ec495f0c),
|
|
598
|
-
// 2.4.0 (f26e4d91), 2.4.1 (2c73f3f5), 2.5.0 (41c34143),
|
|
598
|
+
// 2.4.0 (f26e4d91), 2.4.1 (2c73f3f5), 2.5.0 (41c34143), 2.5.1 (1b02030d), and
|
|
599
|
+
// 2.5.2 (1c142a00):
|
|
599
600
|
// the additive events and HookDefSchema are unchanged.
|
|
600
601
|
// Require the full version string AND matching components; no inferred 2.x compatibility.
|
|
601
602
|
if (version.major === 2 && ((version.minor === 0 && ((version.version === "2.0.0" && version.patch === 0) ||
|
|
@@ -611,7 +612,8 @@ function validateVersionSensitiveEvents(events, version) {
|
|
|
611
612
|
(version.minor === 4 && ((version.version === "2.4.0" && version.patch === 0) ||
|
|
612
613
|
(version.version === "2.4.1" && version.patch === 1))) ||
|
|
613
614
|
(version.minor === 5 && ((version.version === "2.5.0" && version.patch === 0) ||
|
|
614
|
-
(version.version === "2.5.1" && version.patch === 1)
|
|
615
|
+
(version.version === "2.5.1" && version.patch === 1) ||
|
|
616
|
+
(version.version === "2.5.2" && version.patch === 2))))) {
|
|
615
617
|
return { valid: true };
|
|
616
618
|
}
|
|
617
619
|
if (version.major !== 0) {
|
|
@@ -26,6 +26,12 @@
|
|
|
26
26
|
import { parse as parseToml } from "../vendor/smol-toml/parse.js";
|
|
27
27
|
import { classifyHookCommandDrift, describeHookCommandDrift, hostIdFromHookCommand, isOurApprovalHookCommand, } from "./install-paths.js";
|
|
28
28
|
const MARKER_TAG = "kimi-plugin-cc-managed";
|
|
29
|
+
/**
|
|
30
|
+
* Plain install removes unpaired marker comments for every host and leaves each
|
|
31
|
+
* host's hook table in place. A scoped uninstall removes only this host's
|
|
32
|
+
* markers, so it would disarm a healthy block and keep another host's orphan.
|
|
33
|
+
*/
|
|
34
|
+
export const ORPHAN_MARKER_REMEDY = "Run /kimi:setup (without --uninstall or --check) to repair: install removes orphaned managed marker comments for every host and keeps each host's hook table. A scoped --uninstall does not remove another host's orphan marker. Another tool rewriting ~/.kimi-code/config.toml usually causes this.";
|
|
29
35
|
/**
|
|
30
36
|
* Strict BEGIN matcher. Accepts `# === BEGIN kimi-plugin-cc-managed`
|
|
31
37
|
* with an optional `:<host-id>` suffix, an optional ` (vX.Y.Z)` suffix,
|
|
@@ -135,40 +141,41 @@ function findMarkers(lines) {
|
|
|
135
141
|
return hits;
|
|
136
142
|
}
|
|
137
143
|
/**
|
|
138
|
-
* Pair BEGIN/END markers into well-formed blocks.
|
|
139
|
-
* (
|
|
144
|
+
* Pair BEGIN/END markers into well-formed blocks. A block is a BEGIN followed
|
|
145
|
+
* immediately (in marker order) by an END with the same host suffix; every
|
|
146
|
+
* other marker is an orphan. Nested or interleaved markers therefore orphan
|
|
147
|
+
* both sides rather than being guessed into a block. Callers decide which
|
|
148
|
+
* orphans fail closed (see `parseManagedBlock`).
|
|
140
149
|
*/
|
|
141
150
|
function pairBlocks(lines) {
|
|
142
151
|
const markers = findMarkers(lines);
|
|
143
152
|
const blocks = [];
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
153
|
+
const orphans = [];
|
|
154
|
+
let i = 0;
|
|
155
|
+
while (i < markers.length) {
|
|
156
|
+
const marker = markers[i];
|
|
157
|
+
const next = markers[i + 1];
|
|
158
|
+
if (marker.kind === "begin" && next !== undefined && next.kind === "end" && next.hostId === marker.hostId) {
|
|
159
|
+
const body = validateBlockBody(lines.slice(marker.index + 1, next.index));
|
|
160
|
+
blocks.push({
|
|
161
|
+
hostId: marker.hostId,
|
|
162
|
+
beginLine: marker.index,
|
|
163
|
+
endLine: next.index,
|
|
164
|
+
commandPath: body.commandPath,
|
|
165
|
+
valid: body.valid,
|
|
166
|
+
invalidReason: body.invalidReason,
|
|
167
|
+
});
|
|
168
|
+
i += 2;
|
|
151
169
|
continue;
|
|
152
170
|
}
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
return { orphan: "BEGIN-without-END" };
|
|
158
|
-
const body = validateBlockBody(lines.slice(open.index + 1, marker.index));
|
|
159
|
-
blocks.push({
|
|
160
|
-
hostId: open.hostId,
|
|
161
|
-
beginLine: open.index,
|
|
162
|
-
endLine: marker.index,
|
|
163
|
-
commandPath: body.commandPath,
|
|
164
|
-
valid: body.valid,
|
|
165
|
-
invalidReason: body.invalidReason,
|
|
171
|
+
orphans.push({
|
|
172
|
+
line: marker.index,
|
|
173
|
+
detail: marker.kind === "begin" ? "BEGIN-without-END" : "END-without-BEGIN",
|
|
174
|
+
hostId: marker.hostId,
|
|
166
175
|
});
|
|
167
|
-
|
|
176
|
+
i += 1;
|
|
168
177
|
}
|
|
169
|
-
|
|
170
|
-
return { orphan: "BEGIN-without-END" };
|
|
171
|
-
return { blocks };
|
|
178
|
+
return { blocks, orphans };
|
|
172
179
|
}
|
|
173
180
|
/** Validate the lines BETWEEN a BEGIN/END pair against the safety grammar. */
|
|
174
181
|
function validateBlockBody(rawBody) {
|
|
@@ -274,24 +281,30 @@ function validateBlockBody(rawBody) {
|
|
|
274
281
|
export function parseManagedBlock(contents, hostId) {
|
|
275
282
|
const rawLines = contents.split("\n");
|
|
276
283
|
const lines = rawLines.map((line) => line.replace(/\r$/, ""));
|
|
277
|
-
const
|
|
278
|
-
|
|
279
|
-
|
|
284
|
+
const { blocks, orphans } = pairBlocks(lines);
|
|
285
|
+
// An orphan suffixed for ANOTHER host cannot be part of this host's block:
|
|
286
|
+
// this host's verdict still rests on its own well-formed pair, the whole-file
|
|
287
|
+
// hook-set validation, and the real-parser cleanliness check. Legacy and own
|
|
288
|
+
// orphans stay fail-closed because they may be this host's damaged block.
|
|
289
|
+
const ownOrphan = orphans.find((o) => o.hostId === null || o.hostId === hostId);
|
|
290
|
+
const foreignOrphans = orphans.filter((o) => o.hostId !== null && o.hostId !== hostId);
|
|
291
|
+
if (ownOrphan !== undefined) {
|
|
292
|
+
return { state: { kind: "orphan", detail: ownOrphan.detail }, blocks: [], lines, foreignOrphans };
|
|
280
293
|
}
|
|
281
|
-
const blocks = paired.blocks;
|
|
282
294
|
// A block belongs to this host when its marker suffix matches or, for a
|
|
283
295
|
// legacy un-suffixed block, its command derives to this host. An unattributable
|
|
284
296
|
// legacy command is claimable by the next installer; a command attributed to
|
|
285
297
|
// another host is ignored so its block remains untouched.
|
|
286
298
|
const relevant = blocks.filter((b) => effectiveHost(b, hostId) === hostId);
|
|
287
299
|
if (relevant.length === 0) {
|
|
288
|
-
return { state: { kind: "absent" }, blocks, lines };
|
|
300
|
+
return { state: { kind: "absent" }, blocks, lines, foreignOrphans };
|
|
289
301
|
}
|
|
290
302
|
if (relevant.length > 1) {
|
|
291
303
|
return {
|
|
292
304
|
state: { kind: "duplicate", beginLines: relevant.map((b) => b.beginLine) },
|
|
293
305
|
blocks,
|
|
294
306
|
lines,
|
|
307
|
+
foreignOrphans,
|
|
295
308
|
};
|
|
296
309
|
}
|
|
297
310
|
const block = relevant[0];
|
|
@@ -307,6 +320,7 @@ export function parseManagedBlock(contents, hostId) {
|
|
|
307
320
|
},
|
|
308
321
|
blocks,
|
|
309
322
|
lines,
|
|
323
|
+
foreignOrphans,
|
|
310
324
|
};
|
|
311
325
|
}
|
|
312
326
|
/**
|
|
@@ -335,27 +349,6 @@ export function decodeManagedCommandLine(trimmedLine) {
|
|
|
335
349
|
return literal[1];
|
|
336
350
|
return null;
|
|
337
351
|
}
|
|
338
|
-
/**
|
|
339
|
-
* Return `contents` with every well-formed managed BEGIN/END block removed
|
|
340
|
-
* (inclusive), so what remains is only the bare/root TOML. Used by
|
|
341
|
-
* `hasCleanEnforcingHookEntry` to enforce host isolation. If the markers are
|
|
342
|
-
* unbalanced (orphan), returns the input unchanged — the caller is only reached
|
|
343
|
-
* in the `absent` state, where a well-formed foreign block is the norm.
|
|
344
|
-
*/
|
|
345
|
-
function stripManagedBlockLines(contents) {
|
|
346
|
-
const lines = contents.split("\n").map((line) => line.replace(/\r$/, ""));
|
|
347
|
-
const paired = pairBlocks(lines);
|
|
348
|
-
if (!("blocks" in paired))
|
|
349
|
-
return contents;
|
|
350
|
-
const inBlock = new Set();
|
|
351
|
-
for (const block of paired.blocks) {
|
|
352
|
-
for (let i = block.beginLine; i <= block.endLine; i += 1)
|
|
353
|
-
inBlock.add(i);
|
|
354
|
-
}
|
|
355
|
-
if (inBlock.size === 0)
|
|
356
|
-
return contents;
|
|
357
|
-
return lines.filter((_, i) => !inBlock.has(i)).join("\n");
|
|
358
|
-
}
|
|
359
352
|
/**
|
|
360
353
|
* True if a parsed `hooks[]` array contains a clean enforcing entry for
|
|
361
354
|
* `expectedCommand`: `event="PreToolUse"`, byte-exact `command`, NO `matcher`
|
|
@@ -364,10 +357,11 @@ function stripManagedBlockLines(contents) {
|
|
|
364
357
|
* kimi-code's strict schema). Each host's hook path is distinct, so the command
|
|
365
358
|
* uniquely identifies this host's entry.
|
|
366
359
|
*/
|
|
367
|
-
function
|
|
360
|
+
function countCleanEntries(hooks, expectedCommand) {
|
|
368
361
|
if (!Array.isArray(hooks))
|
|
369
|
-
return
|
|
362
|
+
return 0;
|
|
370
363
|
const allowedKeys = new Set(["event", "command", "timeout"]);
|
|
364
|
+
let count = 0;
|
|
371
365
|
for (const entry of hooks) {
|
|
372
366
|
if (entry === null || typeof entry !== "object")
|
|
373
367
|
continue;
|
|
@@ -380,29 +374,37 @@ function hooksArrayHasCleanEntry(hooks, expectedCommand) {
|
|
|
380
374
|
continue;
|
|
381
375
|
if (!Object.keys(rec).every((k) => allowedKeys.has(k)))
|
|
382
376
|
continue;
|
|
383
|
-
|
|
377
|
+
count += 1;
|
|
384
378
|
}
|
|
385
|
-
return
|
|
379
|
+
return count;
|
|
380
|
+
}
|
|
381
|
+
function hooksArrayHasCleanEntry(hooks, expectedCommand) {
|
|
382
|
+
return countCleanEntries(hooks, expectedCommand) > 0;
|
|
386
383
|
}
|
|
387
384
|
/**
|
|
388
|
-
* Parser-based fallback used only in the absent state.
|
|
389
|
-
*
|
|
390
|
-
*
|
|
391
|
-
*
|
|
392
|
-
*
|
|
393
|
-
*
|
|
385
|
+
* Parser-based fallback used only in the absent state. Parse the WHOLE file
|
|
386
|
+
* exactly as kimi-code does: deleting managed-block lines first would change
|
|
387
|
+
* which table their keys bind to (a `matcher` written before another host's
|
|
388
|
+
* `[[hooks]]` header belongs to the preceding table, possibly this host's bare
|
|
389
|
+
* one). Host isolation is kept by counting: every managed block whose body
|
|
390
|
+
* carries this exact command may account for one clean entry, so only a clean
|
|
391
|
+
* entry beyond those can be this host's marker-less table. Requires the exact
|
|
392
|
+
* event and command, no matcher in any spelling, and no foreign keys. Parse
|
|
393
|
+
* errors fail closed. Callers run whole-file schema validation first.
|
|
394
394
|
*/
|
|
395
395
|
export function hasCleanEnforcingHookEntry(contents, expectedCommand) {
|
|
396
396
|
let parsed;
|
|
397
397
|
try {
|
|
398
|
-
parsed = parseToml(
|
|
398
|
+
parsed = parseToml(contents);
|
|
399
399
|
}
|
|
400
400
|
catch {
|
|
401
401
|
return false;
|
|
402
402
|
}
|
|
403
403
|
if (parsed === null || typeof parsed !== "object")
|
|
404
404
|
return false;
|
|
405
|
-
|
|
405
|
+
const lines = contents.split("\n").map((line) => line.replace(/\r$/, ""));
|
|
406
|
+
const managedWithCommand = pairBlocks(lines).blocks.filter((block) => block.commandPath === expectedCommand).length;
|
|
407
|
+
return countCleanEntries(parsed.hooks, expectedCommand) > managedWithCommand;
|
|
406
408
|
}
|
|
407
409
|
/**
|
|
408
410
|
* Whole-file parser check for the FOUND (marked-block present) path. The line
|
|
@@ -468,7 +470,7 @@ export function evaluateInstalled(contents, expectedCommand, opts) {
|
|
|
468
470
|
if (state.kind === "orphan") {
|
|
469
471
|
return {
|
|
470
472
|
installed: false,
|
|
471
|
-
reason: `${state.detail} marker.
|
|
473
|
+
reason: `${state.detail} marker. ${ORPHAN_MARKER_REMEDY}`,
|
|
472
474
|
state,
|
|
473
475
|
};
|
|
474
476
|
}
|
|
@@ -516,12 +518,9 @@ export function findBareApprovalHookTables(contents) {
|
|
|
516
518
|
const lines = contents.split("\n").map((line) => line.replace(/\r$/, ""));
|
|
517
519
|
const tableLines = scanTomlLines(contents).tables;
|
|
518
520
|
const managed = new Set();
|
|
519
|
-
const
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
for (let i = block.beginLine; i <= block.endLine; i += 1)
|
|
523
|
-
managed.add(i);
|
|
524
|
-
}
|
|
521
|
+
for (const block of pairBlocks(lines).blocks) {
|
|
522
|
+
for (let i = block.beginLine; i <= block.endLine; i += 1)
|
|
523
|
+
managed.add(i);
|
|
525
524
|
}
|
|
526
525
|
const ranges = [];
|
|
527
526
|
for (let i = 0; i < lines.length; i += 1) {
|