kimi-plugin-cc 3.1.0 → 3.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,7 +5,7 @@
5
5
  },
6
6
  "metadata": {
7
7
  "description": "Universal Kimi Code connector for Claude Code: 4-tool MCP, progressive kimi skill, and canonical PreToolUse safety hook.",
8
- "version": "3.1.0"
8
+ "version": "3.1.2"
9
9
  },
10
10
  "plugins": [
11
11
  {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "kimi",
3
3
  "description": "Universal Kimi Code connector for Claude Code: 4-tool MCP (`kimi_read`, `kimi_write`, `kimi_job`, `kimi_setup`), progressive `kimi` skill, and canonical PreToolUse safety hook.",
4
- "version": "3.1.0",
4
+ "version": "3.1.2",
5
5
  "homepage": "https://github.com/linxule/kimi-plugin-cc",
6
6
  "repository": "https://github.com/linxule/kimi-plugin-cc",
7
7
  "license": "Apache-2.0",
package/README.md CHANGED
@@ -119,7 +119,7 @@ Run `/path/to/kimi-plugin-cc/scripts/companion.sh setup` and `setup --check` onc
119
119
  You can also install [`kimi-plugin-cc` from npm](https://www.npmjs.com/package/kimi-plugin-cc) into a dedicated package directory. Keep that directory separate from `~/.local/share/kimi-plugin-cc`, which stores shared runtime data:
120
120
 
121
121
  ```sh
122
- npm install --prefix ~/.local/share/kimi-plugin-cc-pkg kimi-plugin-cc@3.1.0
122
+ npm install --prefix ~/.local/share/kimi-plugin-cc-pkg kimi-plugin-cc@3.1.2
123
123
  claude --plugin-dir ~/.local/share/kimi-plugin-cc-pkg/node_modules/kimi-plugin-cc
124
124
  ```
125
125
 
@@ -190,7 +190,7 @@ To keep all 7 operations working on a certified binary across every host, run `k
190
190
 
191
191
  All 5 hosts share one data directory (`<data-dir>`) and one bundled PreToolUse safety hook at `<data-dir>/hook/approval-hook.js`. The default data directory is `~/.local/share/kimi-plugin-cc` (or `$XDG_DATA_HOME/kimi-plugin-cc`) on macOS and Linux, and `%LOCALAPPDATA%\kimi-plugin-cc` on Windows. You can override the base directory with `KIMI_PLUGIN_CC_DATA` so data lives in `$KIMI_PLUGIN_CC_DATA/kimi-plugin-cc`.
192
192
 
193
- Running `setup` once publishes the bundled hook and writes one `# === BEGIN kimi-plugin-cc-managed (v3.1.0) ===` block in `~/.kimi-code/config.toml`. It also replaces any older `:<host-id>` blocks from version 3.0. Hosts that use the same Node binary need only one setup run. If your hosts use different Node paths, point them to the same binary with `KIMI_PLUGIN_CC_NODE_BIN`.
193
+ Running `setup` once publishes the bundled hook and writes one `# === BEGIN kimi-plugin-cc-managed (v3.1.2) ===` block in `~/.kimi-code/config.toml`. It also replaces any older `:<host-id>` blocks from version 3.0. Hosts that use the same Node binary need only one setup run. If your hosts use different Node paths, point them to the same binary with `KIMI_PLUGIN_CC_NODE_BIN`.
194
194
 
195
195
  ## Manage sessions, models, and jobs
196
196
 
@@ -326,7 +326,7 @@ magpie library mcp add kimi /path/to/kimi-plugin-cc/scripts/companion.sh mcp age
326
326
  你也可以从 npm 安装 [`kimi-plugin-cc` 包](https://www.npmjs.com/package/kimi-plugin-cc) 到单独的包目录中。请将该目录与存放共享运行时数据的 `~/.local/share/kimi-plugin-cc` 分开:
327
327
 
328
328
  ```sh
329
- npm install --prefix ~/.local/share/kimi-plugin-cc-pkg kimi-plugin-cc@3.1.0
329
+ npm install --prefix ~/.local/share/kimi-plugin-cc-pkg kimi-plugin-cc@3.1.2
330
330
  claude --plugin-dir ~/.local/share/kimi-plugin-cc-pkg/node_modules/kimi-plugin-cc
331
331
  ```
332
332
 
@@ -397,7 +397,7 @@ Kimi 会收到每个会话主日志的路径,并按需读取内容。当你设
397
397
 
398
398
  全部 5 个宿主共享同一个数据目录(`<data-dir>`)和位于 `<data-dir>/hook/approval-hook.js` 的单一打包 PreToolUse 安全钩子。默认数据目录在 macOS 和 Linux 上为 `~/.local/share/kimi-plugin-cc`(或 `$XDG_DATA_HOME/kimi-plugin-cc`),在 Windows 上为 `%LOCALAPPDATA%\kimi-plugin-cc`。你可以用 `KIMI_PLUGIN_CC_DATA` 覆盖父级基础目录,使数据存放在 `$KIMI_PLUGIN_CC_DATA/kimi-plugin-cc` 下。
399
399
 
400
- 运行一次 `setup` 即可发布打包好的安全钩子,并在 `~/.kimi-code/config.toml` 中写入单一的 `# === BEGIN kimi-plugin-cc-managed (v3.1.0) ===` 配置块,同时自动合并 3.0 版本遗留的 `:<host-id>` 配置块。共享同一个 Node 二进制文件的宿主只需运行一次 `setup`。如果不同宿主解析到不同的 Node 路径,请通过 `KIMI_PLUGIN_CC_NODE_BIN` 将它们指向同一个 Node 可执行文件。
400
+ 运行一次 `setup` 即可发布打包好的安全钩子,并在 `~/.kimi-code/config.toml` 中写入单一的 `# === BEGIN kimi-plugin-cc-managed (v3.1.2) ===` 配置块,同时自动合并 3.0 版本遗留的 `:<host-id>` 配置块。共享同一个 Node 二进制文件的宿主只需运行一次 `setup`。如果不同宿主解析到不同的 Node 路径,请通过 `KIMI_PLUGIN_CC_NODE_BIN` 将它们指向同一个 Node 可执行文件。
401
401
 
402
402
  ## 管理会话、模型和任务
403
403
 
@@ -533,7 +533,7 @@ Exécutez ensuite `/path/to/kimi-plugin-cc/scripts/companion.sh setup` et `setup
533
533
  Vous pouvez aussi installer [`kimi-plugin-cc` depuis npm](https://www.npmjs.com/package/kimi-plugin-cc) dans un répertoire de paquet dédié. Gardez ce répertoire séparé de `~/.local/share/kimi-plugin-cc`, qui stocke les données d'exécution partagées :
534
534
 
535
535
  ```sh
536
- npm install --prefix ~/.local/share/kimi-plugin-cc-pkg kimi-plugin-cc@3.1.0
536
+ npm install --prefix ~/.local/share/kimi-plugin-cc-pkg kimi-plugin-cc@3.1.2
537
537
  claude --plugin-dir ~/.local/share/kimi-plugin-cc-pkg/node_modules/kimi-plugin-cc
538
538
  ```
539
539
 
@@ -604,7 +604,7 @@ Pour conserver les 7 opérations sur un binaire certifié partagé par tous les
604
604
 
605
605
  Les 5 hôtes partagent un seul répertoire de données (`<data-dir>`) et un seul hook de sécurité PreToolUse empaqueté dans `<data-dir>/hook/approval-hook.js`. Le répertoire de données par défaut est `~/.local/share/kimi-plugin-cc` (ou `$XDG_DATA_HOME/kimi-plugin-cc`) sous macOS et Linux, et `%LOCALAPPDATA%\kimi-plugin-cc` sous Windows. Vous pouvez remplacer le répertoire parent avec `KIMI_PLUGIN_CC_DATA` pour stocker les données dans `$KIMI_PLUGIN_CC_DATA/kimi-plugin-cc`.
606
606
 
607
- Exécuter `setup` une seule fois publie le hook empaqueté et écrit un bloc unique `# === BEGIN kimi-plugin-cc-managed (v3.1.0) ===` dans `~/.kimi-code/config.toml`. Cette commande remplace aussi automatiquement les anciens blocs `:<host-id>` de la version 3.0. Les hôtes qui partagent le même binaire Node n'ont besoin que d'une seule exécution de `setup`. Si vos hôtes utilisent des chemins Node différents, pointez-les vers le même binaire avec `KIMI_PLUGIN_CC_NODE_BIN`.
607
+ Exécuter `setup` une seule fois publie le hook empaqueté et écrit un bloc unique `# === BEGIN kimi-plugin-cc-managed (v3.1.2) ===` dans `~/.kimi-code/config.toml`. Cette commande remplace aussi automatiquement les anciens blocs `:<host-id>` de la version 3.0. Les hôtes qui partagent le même binaire Node n'ont besoin que d'une seule exécution de `setup`. Si vos hôtes utilisent des chemins Node différents, pointez-les vers le même binaire avec `KIMI_PLUGIN_CC_NODE_BIN`.
608
608
 
609
609
  ## Gérer les sessions, les modèles et les tâches
610
610
 
@@ -740,7 +740,7 @@ magpie library mcp add kimi /path/to/kimi-plugin-cc/scripts/companion.sh mcp age
740
740
  専用のパッケージディレクトリに [npm から `kimi-plugin-cc`](https://www.npmjs.com/package/kimi-plugin-cc) をインストールすることもできます。共有ランタイムデータを保存する `~/.local/share/kimi-plugin-cc` とは別のディレクトリを指定してください:
741
741
 
742
742
  ```sh
743
- npm install --prefix ~/.local/share/kimi-plugin-cc-pkg kimi-plugin-cc@3.1.0
743
+ npm install --prefix ~/.local/share/kimi-plugin-cc-pkg kimi-plugin-cc@3.1.2
744
744
  claude --plugin-dir ~/.local/share/kimi-plugin-cc-pkg/node_modules/kimi-plugin-cc
745
745
  ```
746
746
 
@@ -811,7 +811,7 @@ Kimi は各セッションのメインログへのパスを受け取り、必要
811
811
 
812
812
  全 5 ホストは、1 つのデータディレクトリ(`<data-dir>`)と `<data-dir>/hook/approval-hook.js` にある 1 つのバンドル済み PreToolUse 安全フックを共有します。既定のデータディレクトリは、macOS と Linux では `~/.local/share/kimi-plugin-cc`(または `$XDG_DATA_HOME/kimi-plugin-cc`)、Windows では `%LOCALAPPDATA%\kimi-plugin-cc` です。親ディレクトリを `KIMI_PLUGIN_CC_DATA` で上書きすると、データは `$KIMI_PLUGIN_CC_DATA/kimi-plugin-cc` に保存されます。
813
813
 
814
- `setup` を 1 回実行すると、バンドル済みフックが配置され、`~/.kimi-code/config.toml` に単一の `# === BEGIN kimi-plugin-cc-managed (v3.1.0) ===` ブロックが書き込まれます。バージョン 3.0 の古い `:<host-id>` ブロックも自動的に統合されます。同じ Node バイナリを使うホスト間では、`setup` の実行は 1 回だけで十分です。ホストごとに異なる Node パスが解決される場合は、`KIMI_PLUGIN_CC_NODE_BIN` で同じ Node バイナリを指定してください。
814
+ `setup` を 1 回実行すると、バンドル済みフックが配置され、`~/.kimi-code/config.toml` に単一の `# === BEGIN kimi-plugin-cc-managed (v3.1.2) ===` ブロックが書き込まれます。バージョン 3.0 の古い `:<host-id>` ブロックも自動的に統合されます。同じ Node バイナリを使うホスト間では、`setup` の実行は 1 回だけで十分です。ホストごとに異なる Node パスが解決される場合は、`KIMI_PLUGIN_CC_NODE_BIN` で同じ Node バイナリを指定してください。
815
815
 
816
816
  ## セッション、モデル、ジョブを管理する
817
817
 
@@ -382,6 +382,8 @@ export async function runCliPrompt(opts) {
382
382
  const escalationMs = opts.escalationMs ?? DEFAULT_ESCALATION_MS;
383
383
  const identityReader = opts.processIdentityReader;
384
384
  let processExited = false;
385
+ let processClosed = false;
386
+ child.once("close", () => { processClosed = true; });
385
387
  child.once("exit", () => {
386
388
  processExited = true;
387
389
  // A descendant may still hold stdout open. Start cleanup on exit rather
@@ -500,7 +502,12 @@ export async function runCliPrompt(opts) {
500
502
  const childPid = child.pid;
501
503
  if (childPid === undefined || process.platform === "win32")
502
504
  return;
503
- const reachable = !processExited ? await captureDescendantIdentities(childPid, undefined, noteFailure) : [];
505
+ // Read once: the checkpoint below reports whether the whole pass ran
506
+ // after the direct child's exit and pipe close, not whether they
507
+ // happened meanwhile.
508
+ const rootExited = processExited;
509
+ const rootClosed = processClosed;
510
+ const reachable = !rootExited ? await captureDescendantIdentities(childPid, undefined, noteFailure) : [];
504
511
  retainIdentities(reachable);
505
512
  const reachableKeys = new Set(reachable.map(identityKey));
506
513
  const validation = await revalidateProcessIdentities([...trackedIdentities.values()], {
@@ -532,7 +539,7 @@ export async function runCliPrompt(opts) {
532
539
  observationError = passError;
533
540
  lastPassComplete = passError === undefined;
534
541
  const current = [...trackedIdentities.values()];
535
- const signature = JSON.stringify([current.map((identity) => [identity.pid, identity.startToken, identity.processGroupId]), lastPassComplete]);
542
+ const signature = JSON.stringify([current.map((identity) => [identity.pid, identity.startToken, identity.processGroupId]), lastPassComplete, rootExited, rootClosed]);
536
543
  // Recovery stores the print root first. Capture starts immediately,
537
544
  // but descendant publication waits for that durable root checkpoint.
538
545
  if (spawnRecorded) {
@@ -541,7 +548,7 @@ export async function runCliPrompt(opts) {
541
548
  }
542
549
  else {
543
550
  try {
544
- await opts.onProcessIdentities?.(current, lastPassComplete);
551
+ await opts.onProcessIdentities?.(current, lastPassComplete, { exited: rootExited, closed: rootClosed });
545
552
  publishedIdentities = signature;
546
553
  checkpointError = undefined;
547
554
  lastPassCheckpointed = true;
@@ -374,6 +374,7 @@ async function runCheck(configPath, hookScriptPath, warnings, context) {
374
374
  const expectedCommand = buildHookShellCommand(hookScriptPath, context.env);
375
375
  const installedCheck = evaluateInstalled(existing, expectedCommand, {
376
376
  nodeExists: (binPath) => existsSync(binPath),
377
+ env: context.env,
377
378
  });
378
379
  const bareTables = findUnmanagedApprovalHookBlocks(existing);
379
380
  const staleBare = bareTables.filter((t) => t.command !== expectedCommand);
@@ -394,14 +395,16 @@ async function runCheck(configPath, hookScriptPath, warnings, context) {
394
395
  detailReason: installedCheck.reason ?? "block missing/invalid",
395
396
  nextStep: installedCheck.timeoutTooShort === true
396
397
  ? "Run setup (without --check) to rewrite the hook timeout."
397
- : installedCheck.state.kind === "absent"
398
- ? "Run setup (without --check) to install the managed block."
399
- : installedCheck.state.kind === "orphan"
400
- ? ORPHAN_MARKER_REMEDY
401
- : installedCheck.state.kind === "duplicate" &&
402
- parseManagedBlock(existing).blocks.some((entry) => entry.hostId !== null)
403
- ? 'Run `kimi_setup` (action "install") or `scripts/companion.sh setup` to consolidate legacy host-scoped blocks into one canonical block.'
404
- : "Run setup --uninstall, then setup to repair.",
398
+ : installedCheck.drift?.dataOverrideFromCanonical === true
399
+ ? "Unset KIMI_PLUGIN_CC_DATA in your host environment (for example in ~/.claude/settings.json), restart the host, and run setup --check again."
400
+ : installedCheck.state.kind === "absent"
401
+ ? "Run setup (without --check) to install the managed block."
402
+ : installedCheck.state.kind === "orphan"
403
+ ? ORPHAN_MARKER_REMEDY
404
+ : installedCheck.state.kind === "duplicate" &&
405
+ parseManagedBlock(existing).blocks.some((entry) => entry.hostId !== null)
406
+ ? 'Run `kimi_setup` (action "install") or `scripts/companion.sh setup` to consolidate legacy host-scoped blocks into one canonical block.'
407
+ : "Run setup --uninstall, then setup to repair.",
405
408
  });
406
409
  }
407
410
  collectPermissionRuleWarnings(existing, warnings);
@@ -1,6 +1,6 @@
1
1
  import { resolveKimiHome } from "../kimi-home.js";
2
2
  import { probeProcessIdentity } from "../process-tree.js";
3
- import { recordRecoveryEvent, finishRecoveryRecord } from "../swarm-recovery.js";
3
+ import { recordRecoveryEvent, recordPrintSnapshot, finishRecoveryRecord } from "../swarm-recovery.js";
4
4
  import { allocateJobId } from "../job-id.js";
5
5
  import { mkdir, realpath, writeFile } from "node:fs/promises";
6
6
  import path from "node:path";
@@ -605,6 +605,7 @@ writeMode, executionCwd) {
605
605
  store.updateRunningJob(job.job_id, { phase: "turn-running" });
606
606
  if (recovery)
607
607
  recordRecoveryEvent(store, recovery, { kind: "print-spawn" });
608
+ let printRootPid;
608
609
  const result = await runCliPromptWithBudget({
609
610
  ...spawnOptions,
610
611
  prefixArgs: [...executionPlan.prefixArgs],
@@ -612,6 +613,7 @@ writeMode, executionCwd) {
612
613
  resumeSessionId: preactivated?.sessionId,
613
614
  logPath: job.stream_log_path,
614
615
  onSpawn: async (pid) => {
616
+ printRootPid = pid;
615
617
  store.updateRunningJob(job.job_id, { kimi_pid: pid });
616
618
  const probe = await probeProcessIdentity(pid);
617
619
  if (probe.identity) {
@@ -622,10 +624,9 @@ writeMode, executionCwd) {
622
624
  }
623
625
  },
624
626
  onProcessIdentities: recovery
625
- ? (identities, complete) => recordRecoveryEvent(store, recovery, {
626
- kind: boundedSwarm ? "print-processes-snapshot" : "print-processes",
627
- identities: [...identities], complete,
628
- })
627
+ ? (identities, complete, root) => boundedSwarm
628
+ ? recordPrintSnapshot(store, recovery, { identities, complete, rootExited: root.exited, rootClosed: root.closed }, printRootPid)
629
+ : recordRecoveryEvent(store, recovery, { kind: "print-processes", identities: [...identities], complete })
629
630
  : undefined,
630
631
  signal: handlers.signal,
631
632
  }, promptBudgetMs, "swarm.prompt");
@@ -12,6 +12,7 @@ import path from "node:path";
12
12
  import { fileURLToPath } from "node:url";
13
13
  import { RuntimeError } from "../errors.js";
14
14
  import { resolvePluginPaths } from "../paths.js";
15
+ import { resolvePluginDataRoot } from "../plugin-data.js";
15
16
  /**
16
17
  * Prefer a stable, non-version-stamped path to the SAME Node binary.
17
18
  * Version-stamped interpreter paths change on upgrade and invalidate the
@@ -210,11 +211,35 @@ function defaultSameFile(a, b) {
210
211
  return false;
211
212
  }
212
213
  }
214
+ export function resolveDefaultCanonicalHookScriptPath(env) {
215
+ const baseEnv = { ...env };
216
+ delete baseEnv.KIMI_PLUGIN_CC_DATA;
217
+ try {
218
+ return path.join(resolvePluginDataRoot(baseEnv), "kimi-plugin-cc", "hook", "approval-hook.js");
219
+ }
220
+ catch {
221
+ return undefined;
222
+ }
223
+ }
224
+ export function isDataOverrideFromCanonicalHook(installedHookScript, expectedHookScript, env, sameFile = defaultSameFile) {
225
+ if (env === undefined ||
226
+ env.KIMI_PLUGIN_CC_DATA === undefined ||
227
+ (env.KIMI_PLUGIN_CC_HOOK_SCRIPT && env.KIMI_PLUGIN_CC_HOOK_SCRIPT.length > 0) ||
228
+ installedHookScript === expectedHookScript) {
229
+ return false;
230
+ }
231
+ const canonicalHook = resolveDefaultCanonicalHookScriptPath(env);
232
+ if (canonicalHook === undefined)
233
+ return false;
234
+ return path.normalize(installedHookScript) === path.normalize(canonicalHook) || sameFile(installedHookScript, canonicalHook);
235
+ }
213
236
  /**
214
237
  * Machine-readable classification of a canonical-command mismatch. Returns
215
238
  * which token moved and, for Node, whether both spellings name the same file.
216
239
  *
217
- * `"hook-script"` drift is recoverable by running setup on this host.
240
+ * `"hook-script"` drift is recoverable by running setup on this host unless it
241
+ * stems from an active `KIMI_PLUGIN_CC_DATA` override while the shared block
242
+ * points at the canonical hook (`dataOverrideFromCanonical: true`).
218
243
  * `"node-bin"`/`"both"` drift is also recoverable when
219
244
  * `nodeInterpreterUnchanged === true`; a token naming a different interpreter
220
245
  * is not automatically repairable. A hook that cannot spawn fails open upstream.
@@ -222,7 +247,7 @@ function defaultSameFile(a, b) {
222
247
  * Returns `undefined` for non-canonical commands or equal tokens. Classification
223
248
  * never changes the verifier's exact-equality decision.
224
249
  */
225
- export function classifyHookCommandDrift(installedCommand, expectedCommand, sameFile = defaultSameFile) {
250
+ export function classifyHookCommandDrift(installedCommand, expectedCommand, sameFile = defaultSameFile, env) {
226
251
  const installed = parseHookShellCommand(installedCommand);
227
252
  const expected = parseHookShellCommand(expectedCommand);
228
253
  if (installed === null || expected === null) {
@@ -234,6 +259,7 @@ export function classifyHookCommandDrift(installedCommand, expectedCommand, same
234
259
  return undefined;
235
260
  }
236
261
  const axis = nodeDrift && hookDrift ? "both" : nodeDrift ? "node-bin" : "hook-script";
262
+ const dataOverride = hookDrift && isDataOverrideFromCanonicalHook(installed.hookScript, expected.hookScript, env, sameFile);
237
263
  // A changed Node spelling that still names the same file is path drift, not
238
264
  // an interpreter move; callers use this to decide whether setup may retry.
239
265
  return {
@@ -241,6 +267,7 @@ export function classifyHookCommandDrift(installedCommand, expectedCommand, same
241
267
  installedCommand,
242
268
  expectedCommand,
243
269
  ...(nodeDrift ? { nodeInterpreterUnchanged: sameFile(installed.nodeBin, expected.nodeBin) } : {}),
270
+ ...(dataOverride ? { dataOverrideFromCanonical: true } : {}),
244
271
  };
245
272
  }
246
273
  /**
@@ -250,7 +277,7 @@ export function classifyHookCommandDrift(installedCommand, expectedCommand, same
250
277
  * message in place. Pure except for the injected filesystem predicates; never
251
278
  * changes the verifier's exact-equality decision.
252
279
  */
253
- export function describeHookCommandDrift(installedCommand, expectedCommand, nodeExists, sameFile = defaultSameFile) {
280
+ export function describeHookCommandDrift(installedCommand, expectedCommand, nodeExists, sameFile = defaultSameFile, env) {
254
281
  const installed = parseHookShellCommand(installedCommand);
255
282
  const expected = parseHookShellCommand(expectedCommand);
256
283
  if (installed === null || expected === null) {
@@ -261,6 +288,7 @@ export function describeHookCommandDrift(installedCommand, expectedCommand, node
261
288
  if (!nodeDrift && !hookDrift) {
262
289
  return undefined;
263
290
  }
291
+ const dataOverride = hookDrift && isDataOverrideFromCanonicalHook(installed.hookScript, expected.hookScript, env, sameFile);
264
292
  const parts = [];
265
293
  if (nodeDrift) {
266
294
  if (!nodeExists(installed.nodeBin)) {
@@ -283,10 +311,22 @@ export function describeHookCommandDrift(installedCommand, expectedCommand, node
283
311
  }
284
312
  }
285
313
  if (hookDrift) {
286
- parts.push(`Hook script path drift: the installed hook points at ${installed.hookScript}, but this companion's ` +
287
- `hook is ${expected.hookScript} (likely a plugin update or move — the install path is version-stamped).`);
314
+ if (dataOverride) {
315
+ parts.push(`Hook script path drift: the installed hook points at the shared canonical hook ${installed.hookScript}, ` +
316
+ `but KIMI_PLUGIN_CC_DATA=${JSON.stringify(env.KIMI_PLUGIN_CC_DATA)} directs this host to ` +
317
+ `${expected.hookScript} (likely a KIMI_PLUGIN_CC_DATA override left over from a 3.0 per-host setup).`);
318
+ }
319
+ else {
320
+ parts.push(`Hook script path drift: the installed hook points at ${installed.hookScript}, but this companion's ` +
321
+ `hook is ${expected.hookScript} (likely an upgrade from an earlier hook path or a moved data directory).`);
322
+ }
323
+ }
324
+ if (dataOverride) {
325
+ parts.push("Unset KIMI_PLUGIN_CC_DATA in your host environment (for example in ~/.claude/settings.json) and restart the host so it uses the shared canonical hook.");
326
+ }
327
+ else {
328
+ parts.push("Run `kimi_setup` (action \"install\") or `scripts/companion.sh setup` to re-pin the managed block to this companion's current paths.");
288
329
  }
289
- parts.push("Run `kimi_setup` (action \"install\") or `scripts/companion.sh setup` to re-pin the managed block to this companion's current paths.");
290
330
  return parts.join(" ");
291
331
  }
292
332
  /**
@@ -55,6 +55,7 @@ export async function verifyHookInstalled(env, options = {}) {
55
55
  }
56
56
  const check = evaluateInstalled(raw, expected.command, {
57
57
  nodeExists: (binPath) => existsSync(binPath),
58
+ env,
58
59
  });
59
60
  // Markers are bookkeeping, not the security boundary. At job time a
60
61
  // duplicate or orphan marker is tolerated when the real parser finds a clean,
@@ -161,7 +162,9 @@ export function hookRefusalDetails(status) {
161
162
  drift_axis: status.drift.axis,
162
163
  drift_installed_command: status.drift.installedCommand,
163
164
  drift_expected_command: status.drift.expectedCommand,
164
- retryable_after_setup: status.drift.axis === "hook-script" || status.drift.nodeInterpreterUnchanged === true,
165
+ retryable_after_setup: status.drift.dataOverrideFromCanonical === true
166
+ ? false
167
+ : status.drift.axis === "hook-script" || status.drift.nodeInterpreterUnchanged === true,
165
168
  }
166
169
  : {}),
167
170
  };
@@ -228,14 +231,32 @@ const HOOK_GATES = {
228
231
  export function hookGateRefusal(operation, status, env, stderr = process.stderr) {
229
232
  const gate = HOOK_GATES[operation];
230
233
  maybeWarnHookMissing(status, gate.warnLabel, stderr);
234
+ const repairParts = status.drift?.dataOverrideFromCanonical === true
235
+ ? [
236
+ "Unset KIMI_PLUGIN_CC_DATA in your host environment and restart the host, then retry.",
237
+ "KIMI_PLUGIN_CC_SKIP_HOOK_CHECK=1 is only for deliberate tests or diagnostics.",
238
+ ]
239
+ : [...gate.repair, hookRefusalRetryProtocol(env)];
231
240
  return new RuntimeError(gate.code, [
232
241
  ...gate.intro,
233
242
  `Hook check failed: ${status.reason ?? "unknown"}.`,
234
- ...gate.repair,
235
- hookRefusalRetryProtocol(env),
243
+ ...repairParts,
236
244
  ].join(" "), gate.stage, { details: hookRefusalDetails(status) });
237
245
  }
238
246
  export function formatHookMissingWarning(status, commandLabel) {
247
+ const fixLines = status.drift?.dataOverrideFromCanonical === true
248
+ ? [
249
+ " Fix: unset KIMI_PLUGIN_CC_DATA in your host environment (for example in",
250
+ " ~/.claude/settings.json) and restart the host so it uses the shared canonical",
251
+ " hook.",
252
+ ]
253
+ : [
254
+ " Fix: run `kimi_setup` (action \"install\") or `scripts/companion.sh setup`",
255
+ " to install or repair the canonical managed block in ~/.kimi-code/config.toml.",
256
+ " If you use nvm, asdf, mise, or fnm, re-run setup after any Node version",
257
+ " switch — the verifier pins the absolute Node binary path and a switch",
258
+ " invalidates the previously-installed block by design. See docs/safety.md.",
259
+ ];
239
260
  return [
240
261
  "",
241
262
  "WARNING: kimi-plugin-cc safety hook is NOT installed (or is invalid).",
@@ -250,11 +271,7 @@ export function formatHookMissingWarning(status, commandLabel) {
250
271
  " This command will not start a Kimi model run until enforcement is",
251
272
  " repaired.",
252
273
  "",
253
- " Fix: run `kimi_setup` (action \"install\") or `scripts/companion.sh setup`",
254
- " to install or repair the canonical managed block in ~/.kimi-code/config.toml.",
255
- " If you use nvm, asdf, mise, or fnm, re-run setup after any Node version",
256
- " switch — the verifier pins the absolute Node binary path and a switch",
257
- " invalidates the previously-installed block by design. See docs/safety.md.",
274
+ ...fixLines,
258
275
  "",
259
276
  " KIMI_PLUGIN_CC_SKIP_HOOK_CHECK=1 explicitly bypasses hook-verification",
260
277
  " refusals and restores un-enforced `permission: auto` execution. It does",
@@ -448,13 +448,15 @@ export function evaluateInstalled(contents, expectedCommand, opts = {}) {
448
448
  };
449
449
  }
450
450
  const staleOwn = findBareApprovalHookTables(contents).find((table) => table.command !== expectedCommand && isOurApprovalHookCommand(table.command));
451
+ const bareDrift = staleOwn !== undefined ? classifyHookCommandDrift(staleOwn.command, expectedCommand, undefined, opts.env) : undefined;
452
+ const bareOverrideReason = bareDrift?.dataOverrideFromCanonical === true && opts.nodeExists !== undefined
453
+ ? describeHookCommandDrift(staleOwn.command, expectedCommand, opts.nodeExists, undefined, opts.env)
454
+ : undefined;
451
455
  return {
452
456
  installed: false,
453
- reason: "managed block is not present",
457
+ reason: bareOverrideReason ?? "managed block is not present",
454
458
  state,
455
- ...(staleOwn !== undefined
456
- ? { drift: classifyHookCommandDrift(staleOwn.command, expectedCommand) }
457
- : {}),
459
+ ...(bareDrift !== undefined ? { drift: bareDrift } : {}),
458
460
  };
459
461
  }
460
462
  if (state.kind === "duplicate") {
@@ -487,14 +489,14 @@ export function evaluateInstalled(contents, expectedCommand, opts = {}) {
487
489
  }
488
490
  if (state.commandPath !== expectedCommand) {
489
491
  const classified = opts.nodeExists !== undefined
490
- ? describeHookCommandDrift(state.commandPath, expectedCommand, opts.nodeExists)
492
+ ? describeHookCommandDrift(state.commandPath, expectedCommand, opts.nodeExists, undefined, opts.env)
491
493
  : undefined;
492
494
  return {
493
495
  installed: false,
494
496
  reason: classified ??
495
497
  `installed block's command does not match the canonical command this companion would write. Run setup to refresh. expected ${expectedCommand}; got ${state.commandPath}.`,
496
498
  state,
497
- drift: classifyHookCommandDrift(state.commandPath, expectedCommand),
499
+ drift: classifyHookCommandDrift(state.commandPath, expectedCommand, undefined, opts.env),
498
500
  };
499
501
  }
500
502
  if (shortTimeout !== null)
@@ -52,6 +52,24 @@ export async function retryIncompleteCapture(capture, retryDelaysMs = INCOMPLETE
52
52
  }
53
53
  return snapshot;
54
54
  }
55
+ /**
56
+ * Ask the kernel whether a process group has any member. Signal 0 runs the
57
+ * existence and permission checks and delivers nothing, so this never signals
58
+ * the group. True only on ESRCH: a member (a zombie included), a permission
59
+ * error and any other failure all read as "not proven empty". Unlike a process
60
+ * listing, the answer cannot miss a member that exists when it is asked.
61
+ */
62
+ export function processGroupIsProvenEmpty(processGroupId) {
63
+ if (process.platform === "win32" || !Number.isInteger(processGroupId) || processGroupId <= 1)
64
+ return false;
65
+ try {
66
+ process.kill(-processGroupId, 0);
67
+ return false;
68
+ }
69
+ catch (error) {
70
+ return hasErrorCode(error, "ESRCH");
71
+ }
72
+ }
55
73
  /** Return current members of the selected process groups, or undefined when unreadable. */
56
74
  export async function collectProcessGroupsIdentities(processGroupIds) {
57
75
  if (process.platform === "win32")
@@ -1,6 +1,6 @@
1
1
  import { RuntimeError } from "./errors.js";
2
2
  import { sleep } from "./util.js";
3
- import { collectDescendantIdentities, collectProcessGroupsIdentities, probeProcessIdentity, revalidateProcessIdentities } from "./process-tree.js";
3
+ import { collectDescendantIdentities, collectProcessGroupsIdentities, probeProcessIdentity, processGroupIsProvenEmpty, revalidateProcessIdentities } from "./process-tree.js";
4
4
  export function recordRecoveryEvent(store, record, event) {
5
5
  record.complete = false;
6
6
  if (event.kind === "session") {
@@ -25,18 +25,36 @@ export function recordRecoveryEvent(store, record, event) {
25
25
  }
26
26
  else if (event.kind === "print-processes-snapshot") {
27
27
  const root = launch.identities[0];
28
- if (!root)
29
- throw recoveryError("The print root identity was not durably recorded before its process snapshot.");
30
- // The root remains the recovery anchor after exit. Complete bounded
31
- // snapshots replace historical descendants; an incomplete observation
32
- // cannot discard an identity whose exit has not been proven.
33
- const previous = new Map(launch.identities.map((identity) => [processIdentityKey(identity), identity]));
34
- const current = event.identities.map((identity) => previous.get(processIdentityKey(identity)) ?? identity);
35
- const all = event.complete ? [root, ...current] : [...launch.identities, ...current];
36
- launch.identities = [...new Map(all.map((identity) => [processIdentityKey(identity), identity])).values()];
37
- launch.pending = false;
38
- launch.uncertain = !event.complete;
39
- launch.boundedSnapshot = true;
28
+ if (!root) {
29
+ // The root can exit before its identity is read, and the read can fail
30
+ // or time out. With no anchor, settlement rests on four observations
31
+ // that need none: the launcher's own handle reported the exit; the
32
+ // launcher saw its pipes close; a complete pass tracks no process; and
33
+ // the kernel reports no process in the root's own group. Each one
34
+ // missing is a refusal, exactly as every rootless snapshot was refused
35
+ // before. A helper that left the group and keeps no pipe open is
36
+ // invisible here, as it is behind an identified root that has exited.
37
+ if (event.rootExited !== true || event.rootClosed !== true || event.rootGroupEmpty !== true ||
38
+ !event.complete || event.identities.length > 0) {
39
+ throw recoveryError("The print root identity was not durably recorded before its process snapshot.");
40
+ }
41
+ launch.pending = false;
42
+ launch.uncertain = false;
43
+ launch.boundedSnapshot = true;
44
+ launch.rootUnidentified = true;
45
+ }
46
+ else {
47
+ // The root remains the recovery anchor after exit. Complete bounded
48
+ // snapshots replace historical descendants; an incomplete observation
49
+ // cannot discard an identity whose exit has not been proven.
50
+ const previous = new Map(launch.identities.map((identity) => [processIdentityKey(identity), identity]));
51
+ const current = event.identities.map((identity) => previous.get(processIdentityKey(identity)) ?? identity);
52
+ const all = event.complete ? [root, ...current] : [...launch.identities, ...current];
53
+ launch.identities = [...new Map(all.map((identity) => [processIdentityKey(identity), identity])).values()];
54
+ launch.pending = false;
55
+ launch.uncertain = !event.complete;
56
+ launch.boundedSnapshot = true;
57
+ }
40
58
  }
41
59
  else if ("identities" in event) {
42
60
  const all = [...launch.identities, ...event.identities];
@@ -47,6 +65,23 @@ export function recordRecoveryEvent(store, record, event) {
47
65
  }
48
66
  store.saveSwarmRecovery(record.jobId, record);
49
67
  }
68
+ /**
69
+ * Record one bounded print snapshot. For a launch with no recorded root, and
70
+ * only then, probe the root's own process group once the other conditions
71
+ * hold. The child is spawned as the leader of its own group, so that group's
72
+ * id is the child's PID. The probe observes and never signals; anything short
73
+ * of the kernel's "no such process" is a refusal. A recorded root is never probed.
74
+ */
75
+ export function recordPrintSnapshot(store, record, snapshot, rootPid, groupIsProvenEmpty = processGroupIsProvenEmpty) {
76
+ const launch = [...record.launches].reverse().find((entry) => entry.kind === "print");
77
+ const rootGroupEmpty = launch !== undefined && launch.identities.length === 0 && rootPid !== undefined &&
78
+ snapshot.rootExited && snapshot.rootClosed && snapshot.complete && snapshot.identities.length === 0 &&
79
+ groupIsProvenEmpty(rootPid);
80
+ recordRecoveryEvent(store, record, {
81
+ kind: "print-processes-snapshot", identities: [...snapshot.identities], complete: snapshot.complete,
82
+ rootExited: snapshot.rootExited, rootClosed: snapshot.rootClosed, rootGroupEmpty,
83
+ });
84
+ }
50
85
  function processIdentityKey(identity) {
51
86
  // A changed process group is not a new ownership grant for the same process.
52
87
  return `${identity.pid}:${identity.startToken}`;
@@ -114,6 +149,14 @@ export async function inspectRecoveryLaunchProcesses(launch, validate = revalida
114
149
  export async function recoverLaunch(launch, persist, signal) {
115
150
  if (launch.quiescent)
116
151
  return;
152
+ // A rootless launch that settled already rests on the root's exit, closed
153
+ // pipes, an empty group and an empty complete pass. It records no identity to
154
+ // inspect or signal, so recovery finishes it without probing anything.
155
+ if (launch.rootUnidentified === true && !launch.pending && !launch.uncertain && launch.identities.length === 0) {
156
+ launch.quiescent = true;
157
+ persist();
158
+ return;
159
+ }
117
160
  if (launch.pending || launch.uncertain || launch.identities.length === 0) {
118
161
  throw recoveryError("Launch ownership was not fully recorded before interruption; manual inspection is required. No process was signalled.");
119
162
  }
package/dist/version.js CHANGED
@@ -4,4 +4,4 @@
4
4
  // and AGENTS.md on every release. A future improvement would read this from
5
5
  // package.json at build time, but that adds a build-step dependency we
6
6
  // don't want yet.
7
- export const KIMI_PLUGIN_CC_VERSION = "3.1.0";
7
+ export const KIMI_PLUGIN_CC_VERSION = "3.1.2";
package/docs/migration.md CHANGED
@@ -43,11 +43,12 @@ Plugin 3.1.0 includes 5 runtime behavior updates:
43
43
 
44
44
  ### Upgrade steps
45
45
 
46
- 1. Update Kimi Code CLI to `2.8.0` or newer, or let the plugin install a dedicated copy in step 4.
47
- 2. Update the plugin in each host you use. If you installed `plugins/kimi-dsh` in DSH, remove it and add the root package with `dsh plugin --profile web add kimi-plugin-cc`.
48
- 3. Run setup once from any host with `kimi_setup({ action: "install" })` or `./scripts/companion.sh setup`. Setup rejects symlinks under `pluginRoot` and `hook/`, probes the staged hook before activating `<pluginRoot>/hook/approval-hook.js`, and merges legacy `:<host-id>` blocks in `~/.kimi-code/config.toml`. If 2 hosts use different Node binaries, set `KIMI_PLUGIN_CC_NODE_BIN` to the same absolute Node `22.5` or newer path in both hosts.
49
- 4. Run `kimi_setup({ action: "install_kimi" })` or `./scripts/companion.sh setup --install-kimi` if you want a plugin-owned certified `2.8.0` binary shared across all hosts.
50
- 5. Run `kimi_setup({ action: "check" })` or `./scripts/companion.sh setup --check` and confirm that the output shows `Probe: ok`.
46
+ 1. Remove any `KIMI_PLUGIN_CC_DATA` override from your host environment (for example in the `env` block of `~/.claude/settings.json` for Claude Code), then restart the host. Version 3.1.0 treats `KIMI_PLUGIN_CC_DATA` as a strict directory override, so leaving a 3.0 per-host path set makes that host look for its hook under the old directory while the shared block points at the canonical data directory.
47
+ 2. Update Kimi Code CLI to `2.8.0` or newer, or let the plugin install a dedicated copy in step 5.
48
+ 3. Update the plugin in each host you use. If you installed `plugins/kimi-dsh` in DSH, remove it and add the root package with `dsh plugin --profile web add kimi-plugin-cc`.
49
+ 4. Run setup once from any host with `kimi_setup({ action: "install" })` or `./scripts/companion.sh setup`. Setup rejects symlinks under `pluginRoot` and `hook/`, probes the staged hook before activating `<pluginRoot>/hook/approval-hook.js`, and merges legacy `:<host-id>` blocks in `~/.kimi-code/config.toml`. If 2 hosts use different Node binaries, set `KIMI_PLUGIN_CC_NODE_BIN` to the same absolute Node `22.5` or newer path in both hosts.
50
+ 5. Run `kimi_setup({ action: "install_kimi" })` or `./scripts/companion.sh setup --install-kimi` if you want a plugin-owned certified `2.8.0` binary shared across all hosts.
51
+ 6. Run `kimi_setup({ action: "check" })` or `./scripts/companion.sh setup --check` and confirm that the output shows `Probe: ok`.
51
52
 
52
53
  ### Previous job databases
53
54
 
package/docs/safety.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Safety
2
2
 
3
- This guide explains how kimi-plugin-cc 3.1.0 constrains every Kimi session it starts. Read-only operations deny file writes and shell commands. Rescue and pursue edit files only inside your workspace and never mutate Git. Write-swarm (`swarm_patch`) edits inside a temporary Git worktree and returns an unapplied patch.
3
+ This guide explains how kimi-plugin-cc 3.1.2 constrains every Kimi session it starts. Read-only operations deny file writes and shell commands. Rescue and pursue edit files only inside your workspace and never mutate Git. Write-swarm (`swarm_patch`) edits inside a temporary Git worktree and returns an unapplied patch.
4
4
 
5
5
  The plugin makes promises about the sessions it launches. It does not police your own interactive Kimi configuration. One mechanism enforces every promise: a single bundled PreToolUse hook that denies every tool call outside the running operation's allowlist. Plan mode stays closed across every release as defense in depth even though Kimi Code 2.8.0 runs the hook before the plan guard. Where a Kimi setting would break a promise, the plugin neutralizes it for its own children or refuses before spawn; where it would not, the plugin runs and surfaces a launch warning.
6
6
 
@@ -37,7 +37,7 @@ If the hook is missing, drifted, or invalid, every model-spawning operation fail
37
37
  Running `kimi_setup({ action: "install" })` or `scripts/companion.sh setup` verifies `pluginRoot` and `hook/` via `lstat`/`realpath` (rejecting symlinks and non-directories), stages `package.json` (`{"type":"module"}`) and the self-contained bundled ESM `dist/hooks/approval-hook.js` in a unique staging subdirectory, probes the staged candidate before activating `<pluginRoot>/hook/approval-hook.js` (preserving any working hook on failure), and writes one canonical block in `~/.kimi-code/config.toml` inside the serialized config lock:
38
38
 
39
39
  ```toml
40
- # === BEGIN kimi-plugin-cc-managed (v3.1.0) ===
40
+ # === BEGIN kimi-plugin-cc-managed (v3.1.2) ===
41
41
  # DO NOT EDIT — managed by kimi-plugin-cc setup. Run `scripts/companion.sh setup --uninstall` to remove.
42
42
  # Purpose:
43
43
  # kimi-code's `kimi -p` mode hard-codes permission='auto' and
@@ -286,7 +286,7 @@ Every refusal below occurs before Kimi starts (or, for provenance mismatch, befo
286
286
 
287
287
  The verifier checks exact command equality against the canonical command built from the resolved Node binary and `<pluginRoot>/hook/approval-hook.js`. `preferStableNodePath` prefers `process.argv0` over `process.execPath` only when absolute and `realpath`-identical (preventing Homebrew Cellar upgrades from breaking the pin). If you switch Node versions with `nvm`, `asdf`, `mise`, or `fnm`, the pinned Node path changes and commands refuse until you run `setup` again.
288
288
 
289
- When a structurally valid block has a mismatched command, `HookInstallStatus.drift` classifies the axis (`hook-script`, `node-bin`, or `both`) and sets `retryable_after_setup: true` only when setup can safely re-pin it (a moved hook script, or a Node path spelling proven to name the same file). Agents may run setup and retry once only when `retryable_after_setup` is literally `true` and setup exits 0. `node-bin-not-executable` requires repairing the Node binary. The verifier never auto-repins `config.toml` itself (rejected due to lock deadlock, env-steering, downgrade, and spawn-window TOCTOU risks).
289
+ When a structurally valid block has a mismatched command, `HookInstallStatus.drift` classifies the axis (`hook-script`, `node-bin`, or `both`) and sets `retryable_after_setup: true` only when setup can safely re-pin it (a moved hook script, or a Node path spelling proven to name the same file). When `KIMI_PLUGIN_CC_DATA` overrides the data directory while the installed block already points at the default shared canonical hook, drift marks `retryable_after_setup: false` and instructs unsetting `KIMI_PLUGIN_CC_DATA` and restarting the host instead of re-pinning the shared block. Agents may run setup and retry once only when `retryable_after_setup` is literally `true` and setup exits 0. `node-bin-not-executable` requires repairing the Node binary. The verifier never auto-repins `config.toml` itself (rejected due to lock deadlock, env-steering, downgrade, and spawn-window TOCTOU risks).
290
290
 
291
291
  ## Hook-escape monitor (detection evidence)
292
292
 
@@ -2,7 +2,9 @@
2
2
 
3
3
  To stop a running swarm normally, run `scripts/companion.sh job cancel <job-id>` in your terminal or call `kimi_job({ action: "cancel", job_id: "..." })` over MCP. The compatibility alias `scripts/companion.sh cancel <job-id>` also works. Normal cancellation stops the active processes without starting a new cleanup server, while a hard `SIGKILL` skips cleanup entirely.
4
4
 
5
- For certified `2.8.0` and newer parallel swarms (`--max-concurrency` of `2` or more), job status includes a durable `swarm_recovery` record. This record stores the resolved home and workspace, companion identity, launch intent, verified process identities, and session identity. It never stores web tokens, credentials, prompts, or config contents, and it commits the session ID before enabling swarm mode. When `--max-concurrency` is `1`, the plugin runs one direct worker without swarm activation, so normal cancellation and patch capture handle cleanup.
5
+ For certified `2.8.0` and newer swarms, job status includes a durable `swarm_recovery` record. This record stores the resolved home and workspace, companion identity, launch intent, verified process identities, and session identity. It never stores web tokens, credentials, prompts, or config contents, and it commits the session ID before enabling swarm mode. When `--max-concurrency` is `1`, the plugin runs one direct worker without swarm activation. Its record tracks that worker's processes and has no session to deactivate.
6
+
7
+ A worker can exit before the plugin reads its process identity. Once such a launch settles, the record shows it with `rootUnidentified: true` and no identities, and the job keeps the worker's own result. On macOS and Linux, the plugin settles it only when 4 things hold: its own child handle reported the exit, it saw the worker's output pipes close, no process it had seen is still alive, and the operating system reports no process left in the worker's own process group. Until then each check is refused and retried. The teardown deadline bounds the retries; if none succeeds, settlement fails as before, the launch stays pending, and a write swarm captures no patch. Recovery finishes a settled launch of this kind without signalling anything, and refuses one that never settled.
6
8
 
7
9
  Parallel sessions on `2.8.0` and newer keep their `TaskStop`-disabled policy after normal deactivation or recovery. Recovery does not remove that policy. Certification covers the managed job lifecycle rather than interactive resumption of historical swarm sessions in another client.
8
10
 
@@ -33,7 +35,7 @@ Each recovery run uses a 30-second cancellation timeout with bounded identity pr
33
35
  Keep 5 boundaries in mind when inspecting or recovering an interrupted swarm:
34
36
 
35
37
  - a hard kill between process spawn and identity capture leaves an unrecorded launch that `--apply` refuses to guess
36
- - jobs without a recovery record (such as concurrency `1` runs or failures before activation) cannot use automatic recovery
38
+ - jobs that failed or stopped before saving a recovery record cannot use automatic recovery
37
39
  - Windows supports preview mode only and refuses `--apply` because it lacks durable process-identity verification
38
40
  - a changed Kimi home, missing worktree, invalid hook, uncertain process identity, or changed selected CLI binary causes recovery to refuse and preserve evidence
39
41
  - the plugin never deletes abandoned worktrees by age, so you can inspect and recover them before removing them manually
package/dsh/index.json CHANGED
@@ -39,8 +39,8 @@
39
39
  },
40
40
  "versions": [
41
41
  {
42
- "version": "3.1.0",
43
- "publishTimestamp": 1795723107,
42
+ "version": "3.1.2",
43
+ "publishTimestamp": 1795778071,
44
44
  "source": {
45
45
  "type": "npm"
46
46
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kimi-plugin-cc",
3
- "version": "3.1.0",
3
+ "version": "3.1.2",
4
4
  "description": "Universal Kimi Code connector for Claude Code, Codex, Antigravity, DeepSeek Harness, and Magpie: 4-tool MCP + SEP-2640 skills + canonical PreToolUse safety hook.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -24,7 +24,7 @@
24
24
  "check": "bun run build && bun run check:contracts && bun run check:surfaces && bunx tsc --noEmit && bun test --bail && git diff --exit-code -- dist plugins/kimi-codex dsh/index.json cordis.patch.yml && UNTRACKED=\"$(git ls-files --others --exclude-standard -- dist plugins/kimi-codex dsh/index.json cordis.patch.yml)\" && { [ -z \"$UNTRACKED\" ] || { echo \"drift gate: untracked generated files (stage them and re-run check):\"; echo \"$UNTRACKED\"; exit 1; }; }",
25
25
  "check:surfaces": "bun run scripts/generate-surfaces.ts --check",
26
26
  "generate:surfaces": "bun run scripts/generate-surfaces.ts",
27
- "build": "rm -rf dist && bunx tsc -p tsconfig.build.json && bun build runtime/hooks/approval-hook.ts --target=node --format=esm --outfile=dist/hooks/approval-hook.js && mkdir -p dist/vendor/shell-quote dist/vendor/smol-toml && cp runtime/vendor/shell-quote/LICENSE dist/vendor/shell-quote/LICENSE && cp runtime/vendor/smol-toml/*.js runtime/vendor/smol-toml/LICENSE dist/vendor/smol-toml/ && echo '{\"type\":\"module\"}' > dist/package.json && chmod 755 dist/companion.js",
27
+ "build": "node scripts/build.mjs",
28
28
  "companion": "node --import tsx runtime/companion.ts",
29
29
  "test": "bun test",
30
30
  "smoke:real": "KIMI_PLUGIN_CC_SMOKE=1 bun test tests/runtime/real-binary-smoke.test.ts --path-ignore-patterns '**/worktrees/**'",
package/plugin.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://antigravity.google/schemas/v1/plugin.json",
3
3
  "name": "kimi",
4
4
  "displayName": "Kimi",
5
- "version": "3.1.0",
5
+ "version": "3.1.2",
6
6
  "description": "Delegate read-only repository questions, diff reviews, adversarial challenges, bounded workspace fixes, autonomous goals, and parallel swarms to the local Kimi Code CLI via MCP and skills.",
7
7
  "logo": "assets/logo.svg",
8
8
  "suggestedPrompts": [
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kimi",
3
- "version": "3.1.0",
3
+ "version": "3.1.2",
4
4
  "description": "Universal Kimi Code connector for Codex: 4-tool MCP (kimi_read, kimi_write, kimi_job, kimi_setup), progressive kimi skill, and canonical PreToolUse safety hook.",
5
5
  "author": {
6
6
  "name": "linxule"
@@ -382,6 +382,8 @@ export async function runCliPrompt(opts) {
382
382
  const escalationMs = opts.escalationMs ?? DEFAULT_ESCALATION_MS;
383
383
  const identityReader = opts.processIdentityReader;
384
384
  let processExited = false;
385
+ let processClosed = false;
386
+ child.once("close", () => { processClosed = true; });
385
387
  child.once("exit", () => {
386
388
  processExited = true;
387
389
  // A descendant may still hold stdout open. Start cleanup on exit rather
@@ -500,7 +502,12 @@ export async function runCliPrompt(opts) {
500
502
  const childPid = child.pid;
501
503
  if (childPid === undefined || process.platform === "win32")
502
504
  return;
503
- const reachable = !processExited ? await captureDescendantIdentities(childPid, undefined, noteFailure) : [];
505
+ // Read once: the checkpoint below reports whether the whole pass ran
506
+ // after the direct child's exit and pipe close, not whether they
507
+ // happened meanwhile.
508
+ const rootExited = processExited;
509
+ const rootClosed = processClosed;
510
+ const reachable = !rootExited ? await captureDescendantIdentities(childPid, undefined, noteFailure) : [];
504
511
  retainIdentities(reachable);
505
512
  const reachableKeys = new Set(reachable.map(identityKey));
506
513
  const validation = await revalidateProcessIdentities([...trackedIdentities.values()], {
@@ -532,7 +539,7 @@ export async function runCliPrompt(opts) {
532
539
  observationError = passError;
533
540
  lastPassComplete = passError === undefined;
534
541
  const current = [...trackedIdentities.values()];
535
- const signature = JSON.stringify([current.map((identity) => [identity.pid, identity.startToken, identity.processGroupId]), lastPassComplete]);
542
+ const signature = JSON.stringify([current.map((identity) => [identity.pid, identity.startToken, identity.processGroupId]), lastPassComplete, rootExited, rootClosed]);
536
543
  // Recovery stores the print root first. Capture starts immediately,
537
544
  // but descendant publication waits for that durable root checkpoint.
538
545
  if (spawnRecorded) {
@@ -541,7 +548,7 @@ export async function runCliPrompt(opts) {
541
548
  }
542
549
  else {
543
550
  try {
544
- await opts.onProcessIdentities?.(current, lastPassComplete);
551
+ await opts.onProcessIdentities?.(current, lastPassComplete, { exited: rootExited, closed: rootClosed });
545
552
  publishedIdentities = signature;
546
553
  checkpointError = undefined;
547
554
  lastPassCheckpointed = true;
@@ -374,6 +374,7 @@ async function runCheck(configPath, hookScriptPath, warnings, context) {
374
374
  const expectedCommand = buildHookShellCommand(hookScriptPath, context.env);
375
375
  const installedCheck = evaluateInstalled(existing, expectedCommand, {
376
376
  nodeExists: (binPath) => existsSync(binPath),
377
+ env: context.env,
377
378
  });
378
379
  const bareTables = findUnmanagedApprovalHookBlocks(existing);
379
380
  const staleBare = bareTables.filter((t) => t.command !== expectedCommand);
@@ -394,14 +395,16 @@ async function runCheck(configPath, hookScriptPath, warnings, context) {
394
395
  detailReason: installedCheck.reason ?? "block missing/invalid",
395
396
  nextStep: installedCheck.timeoutTooShort === true
396
397
  ? "Run setup (without --check) to rewrite the hook timeout."
397
- : installedCheck.state.kind === "absent"
398
- ? "Run setup (without --check) to install the managed block."
399
- : installedCheck.state.kind === "orphan"
400
- ? ORPHAN_MARKER_REMEDY
401
- : installedCheck.state.kind === "duplicate" &&
402
- parseManagedBlock(existing).blocks.some((entry) => entry.hostId !== null)
403
- ? 'Run `kimi_setup` (action "install") or `scripts/companion.sh setup` to consolidate legacy host-scoped blocks into one canonical block.'
404
- : "Run setup --uninstall, then setup to repair.",
398
+ : installedCheck.drift?.dataOverrideFromCanonical === true
399
+ ? "Unset KIMI_PLUGIN_CC_DATA in your host environment (for example in ~/.claude/settings.json), restart the host, and run setup --check again."
400
+ : installedCheck.state.kind === "absent"
401
+ ? "Run setup (without --check) to install the managed block."
402
+ : installedCheck.state.kind === "orphan"
403
+ ? ORPHAN_MARKER_REMEDY
404
+ : installedCheck.state.kind === "duplicate" &&
405
+ parseManagedBlock(existing).blocks.some((entry) => entry.hostId !== null)
406
+ ? 'Run `kimi_setup` (action "install") or `scripts/companion.sh setup` to consolidate legacy host-scoped blocks into one canonical block.'
407
+ : "Run setup --uninstall, then setup to repair.",
405
408
  });
406
409
  }
407
410
  collectPermissionRuleWarnings(existing, warnings);
@@ -1,6 +1,6 @@
1
1
  import { resolveKimiHome } from "../kimi-home.js";
2
2
  import { probeProcessIdentity } from "../process-tree.js";
3
- import { recordRecoveryEvent, finishRecoveryRecord } from "../swarm-recovery.js";
3
+ import { recordRecoveryEvent, recordPrintSnapshot, finishRecoveryRecord } from "../swarm-recovery.js";
4
4
  import { allocateJobId } from "../job-id.js";
5
5
  import { mkdir, realpath, writeFile } from "node:fs/promises";
6
6
  import path from "node:path";
@@ -605,6 +605,7 @@ writeMode, executionCwd) {
605
605
  store.updateRunningJob(job.job_id, { phase: "turn-running" });
606
606
  if (recovery)
607
607
  recordRecoveryEvent(store, recovery, { kind: "print-spawn" });
608
+ let printRootPid;
608
609
  const result = await runCliPromptWithBudget({
609
610
  ...spawnOptions,
610
611
  prefixArgs: [...executionPlan.prefixArgs],
@@ -612,6 +613,7 @@ writeMode, executionCwd) {
612
613
  resumeSessionId: preactivated?.sessionId,
613
614
  logPath: job.stream_log_path,
614
615
  onSpawn: async (pid) => {
616
+ printRootPid = pid;
615
617
  store.updateRunningJob(job.job_id, { kimi_pid: pid });
616
618
  const probe = await probeProcessIdentity(pid);
617
619
  if (probe.identity) {
@@ -622,10 +624,9 @@ writeMode, executionCwd) {
622
624
  }
623
625
  },
624
626
  onProcessIdentities: recovery
625
- ? (identities, complete) => recordRecoveryEvent(store, recovery, {
626
- kind: boundedSwarm ? "print-processes-snapshot" : "print-processes",
627
- identities: [...identities], complete,
628
- })
627
+ ? (identities, complete, root) => boundedSwarm
628
+ ? recordPrintSnapshot(store, recovery, { identities, complete, rootExited: root.exited, rootClosed: root.closed }, printRootPid)
629
+ : recordRecoveryEvent(store, recovery, { kind: "print-processes", identities: [...identities], complete })
629
630
  : undefined,
630
631
  signal: handlers.signal,
631
632
  }, promptBudgetMs, "swarm.prompt");
@@ -12,6 +12,7 @@ import path from "node:path";
12
12
  import { fileURLToPath } from "node:url";
13
13
  import { RuntimeError } from "../errors.js";
14
14
  import { resolvePluginPaths } from "../paths.js";
15
+ import { resolvePluginDataRoot } from "../plugin-data.js";
15
16
  /**
16
17
  * Prefer a stable, non-version-stamped path to the SAME Node binary.
17
18
  * Version-stamped interpreter paths change on upgrade and invalidate the
@@ -210,11 +211,35 @@ function defaultSameFile(a, b) {
210
211
  return false;
211
212
  }
212
213
  }
214
+ export function resolveDefaultCanonicalHookScriptPath(env) {
215
+ const baseEnv = { ...env };
216
+ delete baseEnv.KIMI_PLUGIN_CC_DATA;
217
+ try {
218
+ return path.join(resolvePluginDataRoot(baseEnv), "kimi-plugin-cc", "hook", "approval-hook.js");
219
+ }
220
+ catch {
221
+ return undefined;
222
+ }
223
+ }
224
+ export function isDataOverrideFromCanonicalHook(installedHookScript, expectedHookScript, env, sameFile = defaultSameFile) {
225
+ if (env === undefined ||
226
+ env.KIMI_PLUGIN_CC_DATA === undefined ||
227
+ (env.KIMI_PLUGIN_CC_HOOK_SCRIPT && env.KIMI_PLUGIN_CC_HOOK_SCRIPT.length > 0) ||
228
+ installedHookScript === expectedHookScript) {
229
+ return false;
230
+ }
231
+ const canonicalHook = resolveDefaultCanonicalHookScriptPath(env);
232
+ if (canonicalHook === undefined)
233
+ return false;
234
+ return path.normalize(installedHookScript) === path.normalize(canonicalHook) || sameFile(installedHookScript, canonicalHook);
235
+ }
213
236
  /**
214
237
  * Machine-readable classification of a canonical-command mismatch. Returns
215
238
  * which token moved and, for Node, whether both spellings name the same file.
216
239
  *
217
- * `"hook-script"` drift is recoverable by running setup on this host.
240
+ * `"hook-script"` drift is recoverable by running setup on this host unless it
241
+ * stems from an active `KIMI_PLUGIN_CC_DATA` override while the shared block
242
+ * points at the canonical hook (`dataOverrideFromCanonical: true`).
218
243
  * `"node-bin"`/`"both"` drift is also recoverable when
219
244
  * `nodeInterpreterUnchanged === true`; a token naming a different interpreter
220
245
  * is not automatically repairable. A hook that cannot spawn fails open upstream.
@@ -222,7 +247,7 @@ function defaultSameFile(a, b) {
222
247
  * Returns `undefined` for non-canonical commands or equal tokens. Classification
223
248
  * never changes the verifier's exact-equality decision.
224
249
  */
225
- export function classifyHookCommandDrift(installedCommand, expectedCommand, sameFile = defaultSameFile) {
250
+ export function classifyHookCommandDrift(installedCommand, expectedCommand, sameFile = defaultSameFile, env) {
226
251
  const installed = parseHookShellCommand(installedCommand);
227
252
  const expected = parseHookShellCommand(expectedCommand);
228
253
  if (installed === null || expected === null) {
@@ -234,6 +259,7 @@ export function classifyHookCommandDrift(installedCommand, expectedCommand, same
234
259
  return undefined;
235
260
  }
236
261
  const axis = nodeDrift && hookDrift ? "both" : nodeDrift ? "node-bin" : "hook-script";
262
+ const dataOverride = hookDrift && isDataOverrideFromCanonicalHook(installed.hookScript, expected.hookScript, env, sameFile);
237
263
  // A changed Node spelling that still names the same file is path drift, not
238
264
  // an interpreter move; callers use this to decide whether setup may retry.
239
265
  return {
@@ -241,6 +267,7 @@ export function classifyHookCommandDrift(installedCommand, expectedCommand, same
241
267
  installedCommand,
242
268
  expectedCommand,
243
269
  ...(nodeDrift ? { nodeInterpreterUnchanged: sameFile(installed.nodeBin, expected.nodeBin) } : {}),
270
+ ...(dataOverride ? { dataOverrideFromCanonical: true } : {}),
244
271
  };
245
272
  }
246
273
  /**
@@ -250,7 +277,7 @@ export function classifyHookCommandDrift(installedCommand, expectedCommand, same
250
277
  * message in place. Pure except for the injected filesystem predicates; never
251
278
  * changes the verifier's exact-equality decision.
252
279
  */
253
- export function describeHookCommandDrift(installedCommand, expectedCommand, nodeExists, sameFile = defaultSameFile) {
280
+ export function describeHookCommandDrift(installedCommand, expectedCommand, nodeExists, sameFile = defaultSameFile, env) {
254
281
  const installed = parseHookShellCommand(installedCommand);
255
282
  const expected = parseHookShellCommand(expectedCommand);
256
283
  if (installed === null || expected === null) {
@@ -261,6 +288,7 @@ export function describeHookCommandDrift(installedCommand, expectedCommand, node
261
288
  if (!nodeDrift && !hookDrift) {
262
289
  return undefined;
263
290
  }
291
+ const dataOverride = hookDrift && isDataOverrideFromCanonicalHook(installed.hookScript, expected.hookScript, env, sameFile);
264
292
  const parts = [];
265
293
  if (nodeDrift) {
266
294
  if (!nodeExists(installed.nodeBin)) {
@@ -283,10 +311,22 @@ export function describeHookCommandDrift(installedCommand, expectedCommand, node
283
311
  }
284
312
  }
285
313
  if (hookDrift) {
286
- parts.push(`Hook script path drift: the installed hook points at ${installed.hookScript}, but this companion's ` +
287
- `hook is ${expected.hookScript} (likely a plugin update or move — the install path is version-stamped).`);
314
+ if (dataOverride) {
315
+ parts.push(`Hook script path drift: the installed hook points at the shared canonical hook ${installed.hookScript}, ` +
316
+ `but KIMI_PLUGIN_CC_DATA=${JSON.stringify(env.KIMI_PLUGIN_CC_DATA)} directs this host to ` +
317
+ `${expected.hookScript} (likely a KIMI_PLUGIN_CC_DATA override left over from a 3.0 per-host setup).`);
318
+ }
319
+ else {
320
+ parts.push(`Hook script path drift: the installed hook points at ${installed.hookScript}, but this companion's ` +
321
+ `hook is ${expected.hookScript} (likely an upgrade from an earlier hook path or a moved data directory).`);
322
+ }
323
+ }
324
+ if (dataOverride) {
325
+ parts.push("Unset KIMI_PLUGIN_CC_DATA in your host environment (for example in ~/.claude/settings.json) and restart the host so it uses the shared canonical hook.");
326
+ }
327
+ else {
328
+ parts.push("Run `kimi_setup` (action \"install\") or `scripts/companion.sh setup` to re-pin the managed block to this companion's current paths.");
288
329
  }
289
- parts.push("Run `kimi_setup` (action \"install\") or `scripts/companion.sh setup` to re-pin the managed block to this companion's current paths.");
290
330
  return parts.join(" ");
291
331
  }
292
332
  /**
@@ -55,6 +55,7 @@ export async function verifyHookInstalled(env, options = {}) {
55
55
  }
56
56
  const check = evaluateInstalled(raw, expected.command, {
57
57
  nodeExists: (binPath) => existsSync(binPath),
58
+ env,
58
59
  });
59
60
  // Markers are bookkeeping, not the security boundary. At job time a
60
61
  // duplicate or orphan marker is tolerated when the real parser finds a clean,
@@ -161,7 +162,9 @@ export function hookRefusalDetails(status) {
161
162
  drift_axis: status.drift.axis,
162
163
  drift_installed_command: status.drift.installedCommand,
163
164
  drift_expected_command: status.drift.expectedCommand,
164
- retryable_after_setup: status.drift.axis === "hook-script" || status.drift.nodeInterpreterUnchanged === true,
165
+ retryable_after_setup: status.drift.dataOverrideFromCanonical === true
166
+ ? false
167
+ : status.drift.axis === "hook-script" || status.drift.nodeInterpreterUnchanged === true,
165
168
  }
166
169
  : {}),
167
170
  };
@@ -228,14 +231,32 @@ const HOOK_GATES = {
228
231
  export function hookGateRefusal(operation, status, env, stderr = process.stderr) {
229
232
  const gate = HOOK_GATES[operation];
230
233
  maybeWarnHookMissing(status, gate.warnLabel, stderr);
234
+ const repairParts = status.drift?.dataOverrideFromCanonical === true
235
+ ? [
236
+ "Unset KIMI_PLUGIN_CC_DATA in your host environment and restart the host, then retry.",
237
+ "KIMI_PLUGIN_CC_SKIP_HOOK_CHECK=1 is only for deliberate tests or diagnostics.",
238
+ ]
239
+ : [...gate.repair, hookRefusalRetryProtocol(env)];
231
240
  return new RuntimeError(gate.code, [
232
241
  ...gate.intro,
233
242
  `Hook check failed: ${status.reason ?? "unknown"}.`,
234
- ...gate.repair,
235
- hookRefusalRetryProtocol(env),
243
+ ...repairParts,
236
244
  ].join(" "), gate.stage, { details: hookRefusalDetails(status) });
237
245
  }
238
246
  export function formatHookMissingWarning(status, commandLabel) {
247
+ const fixLines = status.drift?.dataOverrideFromCanonical === true
248
+ ? [
249
+ " Fix: unset KIMI_PLUGIN_CC_DATA in your host environment (for example in",
250
+ " ~/.claude/settings.json) and restart the host so it uses the shared canonical",
251
+ " hook.",
252
+ ]
253
+ : [
254
+ " Fix: run `kimi_setup` (action \"install\") or `scripts/companion.sh setup`",
255
+ " to install or repair the canonical managed block in ~/.kimi-code/config.toml.",
256
+ " If you use nvm, asdf, mise, or fnm, re-run setup after any Node version",
257
+ " switch — the verifier pins the absolute Node binary path and a switch",
258
+ " invalidates the previously-installed block by design. See docs/safety.md.",
259
+ ];
239
260
  return [
240
261
  "",
241
262
  "WARNING: kimi-plugin-cc safety hook is NOT installed (or is invalid).",
@@ -250,11 +271,7 @@ export function formatHookMissingWarning(status, commandLabel) {
250
271
  " This command will not start a Kimi model run until enforcement is",
251
272
  " repaired.",
252
273
  "",
253
- " Fix: run `kimi_setup` (action \"install\") or `scripts/companion.sh setup`",
254
- " to install or repair the canonical managed block in ~/.kimi-code/config.toml.",
255
- " If you use nvm, asdf, mise, or fnm, re-run setup after any Node version",
256
- " switch — the verifier pins the absolute Node binary path and a switch",
257
- " invalidates the previously-installed block by design. See docs/safety.md.",
274
+ ...fixLines,
258
275
  "",
259
276
  " KIMI_PLUGIN_CC_SKIP_HOOK_CHECK=1 explicitly bypasses hook-verification",
260
277
  " refusals and restores un-enforced `permission: auto` execution. It does",
@@ -448,13 +448,15 @@ export function evaluateInstalled(contents, expectedCommand, opts = {}) {
448
448
  };
449
449
  }
450
450
  const staleOwn = findBareApprovalHookTables(contents).find((table) => table.command !== expectedCommand && isOurApprovalHookCommand(table.command));
451
+ const bareDrift = staleOwn !== undefined ? classifyHookCommandDrift(staleOwn.command, expectedCommand, undefined, opts.env) : undefined;
452
+ const bareOverrideReason = bareDrift?.dataOverrideFromCanonical === true && opts.nodeExists !== undefined
453
+ ? describeHookCommandDrift(staleOwn.command, expectedCommand, opts.nodeExists, undefined, opts.env)
454
+ : undefined;
451
455
  return {
452
456
  installed: false,
453
- reason: "managed block is not present",
457
+ reason: bareOverrideReason ?? "managed block is not present",
454
458
  state,
455
- ...(staleOwn !== undefined
456
- ? { drift: classifyHookCommandDrift(staleOwn.command, expectedCommand) }
457
- : {}),
459
+ ...(bareDrift !== undefined ? { drift: bareDrift } : {}),
458
460
  };
459
461
  }
460
462
  if (state.kind === "duplicate") {
@@ -487,14 +489,14 @@ export function evaluateInstalled(contents, expectedCommand, opts = {}) {
487
489
  }
488
490
  if (state.commandPath !== expectedCommand) {
489
491
  const classified = opts.nodeExists !== undefined
490
- ? describeHookCommandDrift(state.commandPath, expectedCommand, opts.nodeExists)
492
+ ? describeHookCommandDrift(state.commandPath, expectedCommand, opts.nodeExists, undefined, opts.env)
491
493
  : undefined;
492
494
  return {
493
495
  installed: false,
494
496
  reason: classified ??
495
497
  `installed block's command does not match the canonical command this companion would write. Run setup to refresh. expected ${expectedCommand}; got ${state.commandPath}.`,
496
498
  state,
497
- drift: classifyHookCommandDrift(state.commandPath, expectedCommand),
499
+ drift: classifyHookCommandDrift(state.commandPath, expectedCommand, undefined, opts.env),
498
500
  };
499
501
  }
500
502
  if (shortTimeout !== null)
@@ -52,6 +52,24 @@ export async function retryIncompleteCapture(capture, retryDelaysMs = INCOMPLETE
52
52
  }
53
53
  return snapshot;
54
54
  }
55
+ /**
56
+ * Ask the kernel whether a process group has any member. Signal 0 runs the
57
+ * existence and permission checks and delivers nothing, so this never signals
58
+ * the group. True only on ESRCH: a member (a zombie included), a permission
59
+ * error and any other failure all read as "not proven empty". Unlike a process
60
+ * listing, the answer cannot miss a member that exists when it is asked.
61
+ */
62
+ export function processGroupIsProvenEmpty(processGroupId) {
63
+ if (process.platform === "win32" || !Number.isInteger(processGroupId) || processGroupId <= 1)
64
+ return false;
65
+ try {
66
+ process.kill(-processGroupId, 0);
67
+ return false;
68
+ }
69
+ catch (error) {
70
+ return hasErrorCode(error, "ESRCH");
71
+ }
72
+ }
55
73
  /** Return current members of the selected process groups, or undefined when unreadable. */
56
74
  export async function collectProcessGroupsIdentities(processGroupIds) {
57
75
  if (process.platform === "win32")
@@ -1,6 +1,6 @@
1
1
  import { RuntimeError } from "./errors.js";
2
2
  import { sleep } from "./util.js";
3
- import { collectDescendantIdentities, collectProcessGroupsIdentities, probeProcessIdentity, revalidateProcessIdentities } from "./process-tree.js";
3
+ import { collectDescendantIdentities, collectProcessGroupsIdentities, probeProcessIdentity, processGroupIsProvenEmpty, revalidateProcessIdentities } from "./process-tree.js";
4
4
  export function recordRecoveryEvent(store, record, event) {
5
5
  record.complete = false;
6
6
  if (event.kind === "session") {
@@ -25,18 +25,36 @@ export function recordRecoveryEvent(store, record, event) {
25
25
  }
26
26
  else if (event.kind === "print-processes-snapshot") {
27
27
  const root = launch.identities[0];
28
- if (!root)
29
- throw recoveryError("The print root identity was not durably recorded before its process snapshot.");
30
- // The root remains the recovery anchor after exit. Complete bounded
31
- // snapshots replace historical descendants; an incomplete observation
32
- // cannot discard an identity whose exit has not been proven.
33
- const previous = new Map(launch.identities.map((identity) => [processIdentityKey(identity), identity]));
34
- const current = event.identities.map((identity) => previous.get(processIdentityKey(identity)) ?? identity);
35
- const all = event.complete ? [root, ...current] : [...launch.identities, ...current];
36
- launch.identities = [...new Map(all.map((identity) => [processIdentityKey(identity), identity])).values()];
37
- launch.pending = false;
38
- launch.uncertain = !event.complete;
39
- launch.boundedSnapshot = true;
28
+ if (!root) {
29
+ // The root can exit before its identity is read, and the read can fail
30
+ // or time out. With no anchor, settlement rests on four observations
31
+ // that need none: the launcher's own handle reported the exit; the
32
+ // launcher saw its pipes close; a complete pass tracks no process; and
33
+ // the kernel reports no process in the root's own group. Each one
34
+ // missing is a refusal, exactly as every rootless snapshot was refused
35
+ // before. A helper that left the group and keeps no pipe open is
36
+ // invisible here, as it is behind an identified root that has exited.
37
+ if (event.rootExited !== true || event.rootClosed !== true || event.rootGroupEmpty !== true ||
38
+ !event.complete || event.identities.length > 0) {
39
+ throw recoveryError("The print root identity was not durably recorded before its process snapshot.");
40
+ }
41
+ launch.pending = false;
42
+ launch.uncertain = false;
43
+ launch.boundedSnapshot = true;
44
+ launch.rootUnidentified = true;
45
+ }
46
+ else {
47
+ // The root remains the recovery anchor after exit. Complete bounded
48
+ // snapshots replace historical descendants; an incomplete observation
49
+ // cannot discard an identity whose exit has not been proven.
50
+ const previous = new Map(launch.identities.map((identity) => [processIdentityKey(identity), identity]));
51
+ const current = event.identities.map((identity) => previous.get(processIdentityKey(identity)) ?? identity);
52
+ const all = event.complete ? [root, ...current] : [...launch.identities, ...current];
53
+ launch.identities = [...new Map(all.map((identity) => [processIdentityKey(identity), identity])).values()];
54
+ launch.pending = false;
55
+ launch.uncertain = !event.complete;
56
+ launch.boundedSnapshot = true;
57
+ }
40
58
  }
41
59
  else if ("identities" in event) {
42
60
  const all = [...launch.identities, ...event.identities];
@@ -47,6 +65,23 @@ export function recordRecoveryEvent(store, record, event) {
47
65
  }
48
66
  store.saveSwarmRecovery(record.jobId, record);
49
67
  }
68
+ /**
69
+ * Record one bounded print snapshot. For a launch with no recorded root, and
70
+ * only then, probe the root's own process group once the other conditions
71
+ * hold. The child is spawned as the leader of its own group, so that group's
72
+ * id is the child's PID. The probe observes and never signals; anything short
73
+ * of the kernel's "no such process" is a refusal. A recorded root is never probed.
74
+ */
75
+ export function recordPrintSnapshot(store, record, snapshot, rootPid, groupIsProvenEmpty = processGroupIsProvenEmpty) {
76
+ const launch = [...record.launches].reverse().find((entry) => entry.kind === "print");
77
+ const rootGroupEmpty = launch !== undefined && launch.identities.length === 0 && rootPid !== undefined &&
78
+ snapshot.rootExited && snapshot.rootClosed && snapshot.complete && snapshot.identities.length === 0 &&
79
+ groupIsProvenEmpty(rootPid);
80
+ recordRecoveryEvent(store, record, {
81
+ kind: "print-processes-snapshot", identities: [...snapshot.identities], complete: snapshot.complete,
82
+ rootExited: snapshot.rootExited, rootClosed: snapshot.rootClosed, rootGroupEmpty,
83
+ });
84
+ }
50
85
  function processIdentityKey(identity) {
51
86
  // A changed process group is not a new ownership grant for the same process.
52
87
  return `${identity.pid}:${identity.startToken}`;
@@ -114,6 +149,14 @@ export async function inspectRecoveryLaunchProcesses(launch, validate = revalida
114
149
  export async function recoverLaunch(launch, persist, signal) {
115
150
  if (launch.quiescent)
116
151
  return;
152
+ // A rootless launch that settled already rests on the root's exit, closed
153
+ // pipes, an empty group and an empty complete pass. It records no identity to
154
+ // inspect or signal, so recovery finishes it without probing anything.
155
+ if (launch.rootUnidentified === true && !launch.pending && !launch.uncertain && launch.identities.length === 0) {
156
+ launch.quiescent = true;
157
+ persist();
158
+ return;
159
+ }
117
160
  if (launch.pending || launch.uncertain || launch.identities.length === 0) {
118
161
  throw recoveryError("Launch ownership was not fully recorded before interruption; manual inspection is required. No process was signalled.");
119
162
  }
@@ -4,4 +4,4 @@
4
4
  // and AGENTS.md on every release. A future improvement would read this from
5
5
  // package.json at build time, but that adds a build-step dependency we
6
6
  // don't want yet.
7
- export const KIMI_PLUGIN_CC_VERSION = "3.1.0";
7
+ export const KIMI_PLUGIN_CC_VERSION = "3.1.2";