kimi-plugin-cc 2.5.9 → 2.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +19 -0
  4. package/README.md +29 -13
  5. package/agents/kimi-swarm-write.md +6 -4
  6. package/agents/kimi-swarm.md +5 -4
  7. package/commands/swarm.md +5 -3
  8. package/dist/cli-client.js +224 -31
  9. package/dist/commands/recover-swarm.js +4 -0
  10. package/dist/commands/setup.js +5 -1
  11. package/dist/commands/swarm.js +130 -41
  12. package/dist/hooks/approval-hook.js +3 -0
  13. package/dist/hooks/approval-policy.js +34 -12
  14. package/dist/hooks/config-safety.js +5 -4
  15. package/dist/kimi-engine.js +7 -4
  16. package/dist/kimi-timeouts.js +4 -4
  17. package/dist/mcp/operations.js +1 -1
  18. package/dist/process-tree.js +150 -43
  19. package/dist/swarm-activation.js +13 -8
  20. package/dist/swarm-policy.js +73 -0
  21. package/dist/swarm-recovery.js +41 -10
  22. package/dist/swarm-tool-policy.js +146 -0
  23. package/dist/version.js +1 -1
  24. package/docs/migration.md +13 -5
  25. package/docs/registry-releases.md +6 -0
  26. package/docs/safety.md +42 -17
  27. package/docs/swarm-recovery.md +4 -2
  28. package/docs/upstream-2.6.2-certification.md +93 -3
  29. package/docs/upstream-2.6.3-certification.md +88 -0
  30. package/package.json +3 -2
  31. package/plugins/kimi-codex/.codex-plugin/plugin.json +1 -1
  32. package/plugins/kimi-codex/dist/cli-client.js +224 -31
  33. package/plugins/kimi-codex/dist/commands/recover-swarm.js +4 -0
  34. package/plugins/kimi-codex/dist/commands/setup.js +5 -1
  35. package/plugins/kimi-codex/dist/commands/swarm.js +130 -41
  36. package/plugins/kimi-codex/dist/hooks/approval-hook.js +3 -0
  37. package/plugins/kimi-codex/dist/hooks/approval-policy.js +34 -12
  38. package/plugins/kimi-codex/dist/hooks/config-safety.js +5 -4
  39. package/plugins/kimi-codex/dist/kimi-engine.js +7 -4
  40. package/plugins/kimi-codex/dist/kimi-timeouts.js +4 -4
  41. package/plugins/kimi-codex/dist/mcp/operations.js +1 -1
  42. package/plugins/kimi-codex/dist/process-tree.js +150 -43
  43. package/plugins/kimi-codex/dist/swarm-activation.js +13 -8
  44. package/plugins/kimi-codex/dist/swarm-policy.js +73 -0
  45. package/plugins/kimi-codex/dist/swarm-recovery.js +41 -10
  46. package/plugins/kimi-codex/dist/swarm-tool-policy.js +146 -0
  47. package/plugins/kimi-codex/dist/version.js +1 -1
  48. package/plugins/kimi-codex/skills/kimi-swarm/SKILL.md +2 -0
  49. package/plugins/kimi-codex/skills/kimi-swarm-write/SKILL.md +2 -0
  50. package/plugins/kimi-dsh/dist/cli-client.js +224 -31
  51. package/plugins/kimi-dsh/dist/commands/recover-swarm.js +4 -0
  52. package/plugins/kimi-dsh/dist/commands/setup.js +5 -1
  53. package/plugins/kimi-dsh/dist/commands/swarm.js +130 -41
  54. package/plugins/kimi-dsh/dist/hooks/approval-hook.js +3 -0
  55. package/plugins/kimi-dsh/dist/hooks/approval-policy.js +34 -12
  56. package/plugins/kimi-dsh/dist/hooks/config-safety.js +5 -4
  57. package/plugins/kimi-dsh/dist/kimi-engine.js +7 -4
  58. package/plugins/kimi-dsh/dist/kimi-timeouts.js +4 -4
  59. package/plugins/kimi-dsh/dist/mcp/operations.js +1 -1
  60. package/plugins/kimi-dsh/dist/process-tree.js +150 -43
  61. package/plugins/kimi-dsh/dist/swarm-activation.js +13 -8
  62. package/plugins/kimi-dsh/dist/swarm-policy.js +73 -0
  63. package/plugins/kimi-dsh/dist/swarm-recovery.js +41 -10
  64. package/plugins/kimi-dsh/dist/swarm-tool-policy.js +146 -0
  65. package/plugins/kimi-dsh/dist/version.js +1 -1
  66. package/plugins/kimi-dsh/package.json +1 -1
@@ -0,0 +1,88 @@
1
+ # Exact CLI 2.6.3 certification — plugin 2.6.3
2
+
3
+ ## Scope and decision
4
+
5
+ **Status: certified for all eight operations; plugin 2.6.3 release candidate.** Exact `@moonshot-ai/kimi-code@2.6.3` passed the source, exact-binary, real-provider candidate, deterministic stock-binary, production-table operation, full repository, package, consumer-security and post-edit review gates on the final implementation. The production operation table contains 2.6.3 for review, challenge, ask, rescue, review_gate, pursue, swarm and swarm-write. Release CI, tagging and npm publication remain pending.
6
+
7
+ This release candidate does not change an installed host cache or move an operator CLI pin. Plugin 2.6.2 remains the latest published plugin release until plugin 2.6.3 publication completes.
8
+
9
+ Exact source: `@moonshot-ai/kimi-code@2.6.3`, commit `b0de2fbd2de04d87689225aafd3912e5d193b62d` (annotated tag object `a9df46689649824abfdfff1528d7708a23fd3cf3`). The isolated npm binary reports 2.6.3; `dist/main.mjs` SHA-256 is `a360023b6814ffdf05bc87e40925df5e0442ae3076ad9e7b6ea6f771e2a1857c`.
10
+
11
+ ## Monitor correction and candidate-harness diagnosis
12
+
13
+ The November 18 monitor correctly held certification after its candidate smoke failed three swarm lanes. The failure was not positive evidence of an upstream swarm regression:
14
+
15
+ - Candidate admission added 2.6.3 to the in-memory operation map, but `requiresSwarmPreactivation()` and `usesBoundedSwarmPolicy()` still recognized only 2.6.2.
16
+ - A deterministic retained control reproduced zero child journals. Its main journal showed every `AgentSwarm` call receiving the same-call `Swarm mode is off` result, so the engine was never asked to start children.
17
+ - Adding exact candidate activation/policy integration without adding the production certification row made the same read control pass with six children, peak four at width four. The write control passed with four children and a 600-byte patch.
18
+ - The real candidate matrix then passed all three originally failed lanes, including distinct child journals, child-authored work and out-of-root denials.
19
+
20
+ The monitor's seven scoped diffs also omitted changed loop, subagent, shell-command, tool-selection and agent-lifecycle files outside those filters. The full exact-tag diff was reviewed for this certification; those omissions are corrected in the evidence rather than treated as upstream defects.
21
+
22
+ The pre-diagnosis monitor log is retained as `.claude/kimi-code-research/cert-2.6.3-live/monitor-candidate-initial.log`. The corrected candidate log is `daily-monitor/smoke/2026-11-18-2.6.3-candidate.log`.
23
+
24
+ ## Source audit
25
+
26
+ The pristine exact-tag clone has no uncommitted files or sync-conflict copies. The exact 2.6.3 scan passed **31 tests / 404 assertions / no skips**; the exact 2.6.2 regression scan passed **31 tests / 393 assertions / no skips**.
27
+
28
+ The 2.6.3 pin row inherits the reviewed 2.6.2 pins and replaces all 15 changed pinned file hashes. The scan proves:
29
+
30
+ - the plan-file guard remains the sole final `allow()` in the engine, CLI and SDK;
31
+ - the before-execute subscriber set, 2.6 executor ordering and managed veto path remain intact;
32
+ - restore still folds only the same two views of the wire journal, with no second durable plan source;
33
+ - fresh print cancels the default plan and EnterPlanMode remains absent;
34
+ - the external-hooks agent service remains eager in every agent scope and hook aggregation remains first-block-wins;
35
+ - tool schemas retain `path`, `command` and `cwd` where the managed policy reads them;
36
+ - fresh children remain swarm-off, owned resumes retain their session boundary, and native TaskStop disablement still closes Bash backgrounding.
37
+
38
+ `features/swarm/session/agentRunBatch.ts` is byte-identical to 2.6.2, SHA-256 `339dbd7962c3b9bac145aff83aee06d6e5f3c6b9e8c472d4f4f94d7fb26390fc`. No swarm scheduler, swarm web endpoint, DI child-scope or OS backend diff exists between exact 2.6.2 and 2.6.3. The upstream scheduler is not represented as fixed.
39
+
40
+ The additional lifecycle changes add tool origins, queued Stop hooks and task reconciliation. In 2.6.3, child fresh/retry completion shares `awaitRunCompletion`; `awaitQuiescent` waits for loop settlement and active tasks, while cancellation stops child tasks and suppresses their notifications. The tag scan asserts this implementation separately from 2.6.2 rather than merely accepting new hashes.
41
+
42
+ ## Exact-binary controls
43
+
44
+ All controls ran sequentially against the isolated exact binary. Real-model controls used the dedicated Agent Keys environment-model route and empty temporary homes; personal config and credential stores were neither read nor linked.
45
+
46
+ - **Plan OFF:** ordinary Write reached the deny hook, returned `cert-control: denied` on the same call, created no file and recorded no plan state.
47
+ - **Deliberately armed plan ON:** Glob reached the deny hook; Write created a 1,678-byte plan file without a plan-Write hook. No workspace file was created. This proves the no-plan closures remain load-bearing; plugin execution never arms this path.
48
+ - **Forced EnterPlanMode:** the scripted call was absent from offered tools, returned `Tool "EnterPlanMode" not found` on `call_enter_forced` before any hook, returned that result to the provider, and created no plan journal/file.
49
+ - **Local execution:** real activation/deactivation passed. A configured remote default refused before its launcher ran, disabled workspace trust refused, and a resumed nonlocal binding refused.
50
+
51
+ Receipts are `write-off/summary.json`, `plan-on/summary.json`, `enter-off-forced/summary.json` and `environment-controls/summary.json` under the evidence root.
52
+
53
+ ## Candidate operation and bounded-swarm evidence
54
+
55
+ The corrected real-provider candidate matrix passed **30 tests / 2 intentional narrowed-refusal skips / 0 failures / 390 assertions in 564.04 seconds**, terminal exit 0 at `2026-11-18T18:53:07Z`. The two skipped tests assert narrowed non-swarm production refusals that do not apply to a full-scope candidate; no execution lane skipped.
56
+
57
+ Evidence includes:
58
+
59
+ - same-call managed Write denials for review, challenge, ask and review_gate;
60
+ - real confined rescue writing and separate absolute out-of-root `Bash.cwd` denial;
61
+ - unsafe experimental, default-plan and plan-tainted resume refusals;
62
+ - 2,534 started goal turns, 2,533 turns with managed denials and no target file, plus both pursue terminal controls;
63
+ - real read-only child denials and write-swarm child edits with a 306-byte patch, clean user tree and cleaned worktree;
64
+ - real out-of-worktree child Write denials;
65
+ - direct single-worker read/write with no children or activation, including a 348-byte write patch;
66
+ - directed recovery from an oversized wave, then two bounded waves with four children and a 596-byte patch;
67
+ - uncoached five-target production work at width four: two accepted waves, five children, peak three, zero coordinator-authored targets and a 759-byte patch.
68
+
69
+ The deterministic untouched-binary suite passed **23 tests / 0 failures / 138 assertions in 616.19 seconds**. It covers new/resumed waves, odd target grouping, both nested profiles, invalid resumes, read/write cancellation, active HTTP/tool budget expiry, native background-policy closure, direct-worker background behavior and 429/context recovery beyond the native 180-second interval. Every case runs in an isolated process with a scripted local provider and verifies process/provider quiescence before teardown.
70
+
71
+ The expanded activation fixture initially timed out all new 2.6.3 cases because the mock still routed 2.6.3 to the older hello/`subscribe_v2` protocol. Updating the fixture to the reviewed direct-subscription protocol passed all **24 focused 2.6.3 tests / 76 assertions**. This was a test-fixture correction, not a runtime workaround.
72
+
73
+ ## Production and release validation
74
+
75
+ The production-table matrix passed **30 tests / 2 intentional narrowed-refusal skips / 0 failures / 390 assertions in 529.18 seconds**, terminal exit 0 at `2026-11-18T19:31:03Z`. It ran with `candidate=(production table)` and no `KIMI_PLUGIN_CC_SMOKE_V2_CANDIDATE` override. Real evidence includes a 278-byte child-authored patch, out-of-root child denials, direct-worker read/write, two directed bounded waves, and an uncoached five-target run with two grouped children, peak two, no coordinator-authored targets and an 899-byte patch. Grouping multiple targets into one child is valid; it is not a requirement that each target have a separate child. The log is `daily-monitor/smoke/2026-11-18-2.6.3-production.log`.
76
+
77
+ Final validation receipts:
78
+
79
+ - **Frozen install and full repository gate:** PASS. `bun install --frozen-lockfile` exited 0. The definitive `bun run check` passed **1,797 tests / 76 expected opt-in or platform skips / 0 failures / 23,469 assertions**, covering 1,873 tests across 96 files in 623.26 seconds, including emitted-JavaScript and generated-drift gates. The first workspace attempt stopped on 23 ignored iCloud-style ` 3.js`/`LICENSE 3` generated-output conflict copies; they were reversibly quarantined under the evidence root and the same standard gate rerun. No assertion was removed or skipped to obtain the final result.
80
+ - **Package and DSH:** PASS. The 341-file package contains the new certification record, all three compiled distributions, isolated setup/check, unsupported-version refusal and MCP checks. Patched DSH host/profile auditing, seven providers/tools and Web boot passed.
81
+ - **Consumer security:** PASS. `bun run check:consumer-security` verified an isolated npm consumer installation without host credentials or model calls.
82
+ - **Post-edit review:** PASS. The independent runtime/test reviewer returned NO FINDINGS. The documentation reviewer returned two major and three minor findings; all were verified and corrected, and narrow re-review found all five resolved with no new must-fix. Final source/docs diff review preserved the pre-existing user edit in the 2.6.2 historical record.
83
+
84
+ The release commit must pass CI and the exact-release-commit production matrix before tagging. No installed-host setup or operator pin change is implied by certification or publication.
85
+
86
+ ## Residual boundaries
87
+
88
+ The bound covers simultaneous Kimi child-agent turns, excluding the coordinator and OS subprocess counts. `--cap` remains a soft lifetime-total hint and a finite time budget is not a spend cap. Parallel sessions retain the native TaskStop restriction after deactivation; later external interactive resume is outside the managed-job certification. Stream-json still lacks a general execution-outcome field, so hook-escape findings remain detection evidence rather than a failure signal.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kimi-plugin-cc",
3
- "version": "2.5.9",
3
+ "version": "2.6.3",
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",
@@ -14,7 +14,7 @@
14
14
  }
15
15
  },
16
16
  "scripts": {
17
- "check": "bun run build && bun run check:contracts && bun run check:surfaces && bunx tsc --noEmit && bun test && git diff --exit-code -- dist plugins/kimi-codex plugins/kimi-dsh && UNTRACKED=\"$(git ls-files --others --exclude-standard -- dist plugins/kimi-codex plugins/kimi-dsh)\" && { [ -z \"$UNTRACKED\" ] || { echo \"drift gate: untracked dist/codex/dsh files (stage them and re-run check):\"; echo \"$UNTRACKED\"; exit 1; }; }",
17
+ "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 plugins/kimi-dsh && UNTRACKED=\"$(git ls-files --others --exclude-standard -- dist plugins/kimi-codex plugins/kimi-dsh)\" && { [ -z \"$UNTRACKED\" ] || { echo \"drift gate: untracked dist/codex/dsh files (stage them and re-run check):\"; echo \"$UNTRACKED\"; exit 1; }; }",
18
18
  "check:surfaces": "bun run scripts/generate-surfaces.ts --check",
19
19
  "generate:surfaces": "bun run scripts/generate-surfaces.ts",
20
20
  "build": "rm -rf dist && bunx tsc -p tsconfig.build.json && 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",
@@ -140,6 +140,7 @@
140
140
  "docs/upstream-2.5.3-certification.md",
141
141
  "docs/upstream-2.6.0-certification.md",
142
142
  "docs/upstream-2.6.2-certification.md",
143
+ "docs/upstream-2.6.3-certification.md",
143
144
  "README.md",
144
145
  "LICENSE",
145
146
  "CHANGELOG.md",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kimi",
3
- "version": "2.5.9",
3
+ "version": "2.6.3",
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"
@@ -15,8 +15,9 @@ import { assertPrefixArgsSafe } from "./kimi-command.js";
15
15
  import { resolveKimiHome } from "./kimi-home.js";
16
16
  import { assertNativeV2Preflight } from "./native-v2-preflight.js";
17
17
  import { parseVersionLine } from "./kimi-version-probe.js";
18
+ import { BOUNDED_SWARM_POLICY, SWARM_CHILD_TIMEOUT_MS, SWARM_POLICY_ENV, SWARM_WAVE_SIZE_ENV, usesBoundedSwarmPolicy, } from "./swarm-policy.js";
18
19
  import { StreamJsonParser, extractSessionIdFromStderr, } from "./stream-json.js";
19
- import { collectDescendantIdentities, revalidateProcessIdentities, waitForProcessTreeExit, } from "./process-tree.js";
20
+ import { collectDescendantIdentities, collectDescendantIdentitiesForRoots, revalidateProcessIdentities, waitForProcessTreeExit, } from "./process-tree.js";
20
21
  /** Bytes of stderr retained for diagnostics on completion. Rolling buffer. */
21
22
  const STDERR_TAIL_BYTES = 8192;
22
23
  /** Hard cap on awaiting diagnostics log drain before resolving the result. */
@@ -29,6 +30,8 @@ const POST_KILL_QUIESCENCE_MS = 500;
29
30
  const DESCENDANT_SNAPSHOT_TIMEOUT_MS = 1_000;
30
31
  /** Hard bound for each batched identity revalidation pass. */
31
32
  const IDENTITY_REVALIDATION_TIMEOUT_MS = 250;
33
+ /** Keep ownership evidence before a native Bash shell can exit ahead of its children. */
34
+ const BOUNDED_DESCENDANT_POLL_MS = 100;
32
35
  const DESCENDANT_SNAPSHOT_TIMEOUT = Symbol("descendant-snapshot-timeout");
33
36
  function spawnErrorDetails(error) {
34
37
  const cause = error;
@@ -72,6 +75,7 @@ export async function runCliPrompt(opts) {
72
75
  const args = buildArgs(opts);
73
76
  assertPromptFitsCommandLine(opts.command, args);
74
77
  const env = buildKimiCliEnvironment(opts);
78
+ const boundedSwarm = usesBoundedSwarmPolicy(opts.executionPlan);
75
79
  if (opts.logPath !== undefined) {
76
80
  await mkdir(path.dirname(opts.logPath), { recursive: true }).catch(() => {
77
81
  // Best-effort; if mkdir fails the appendFile below will error and be
@@ -123,7 +127,8 @@ export async function runCliPrompt(opts) {
123
127
  let announcedCliError;
124
128
  let announcedSystemVersion;
125
129
  const hookMonitor = createHookEscapeMonitor({ commandLabel: opts.commandLabel,
126
- operationKind: opts.executionPlan.operationKind, trustedWorkspaceRoot: opts.trustedWorkspaceRoot, cwd: opts.cwd });
130
+ operationKind: opts.executionPlan.operationKind, trustedWorkspaceRoot: opts.trustedWorkspaceRoot, cwd: opts.cwd,
131
+ swarmPolicy: env[SWARM_POLICY_ENV], swarmWaveSize: env[SWARM_WAVE_SIZE_ENV] });
127
132
  const hookEscapes = [];
128
133
  const noteHookEscape = (escape) => {
129
134
  hookEscapes.push(escape);
@@ -319,10 +324,13 @@ export async function runCliPrompt(opts) {
319
324
  return await new Promise(async (resolve, reject) => {
320
325
  let aborted = false;
321
326
  let cancellationTeardown;
327
+ let processCleanupUnverified = false;
322
328
  let settlementStarted = false;
323
329
  const settle = (kind, payload) => {
324
330
  if (settlementStarted)
325
331
  return;
332
+ if (boundedSwarm)
333
+ beginTeardown();
326
334
  // Denied calls still without a result (a cancel/budget race, an abnormal
327
335
  // exit, or a turn that ended without the denial the hook owes) are reported
328
336
  // alongside the real outcome, never instead of it.
@@ -337,13 +345,21 @@ export async function runCliPrompt(opts) {
337
345
  // expose a result/error until that one owned teardown path completes.
338
346
  void (cancellationTeardown ?? Promise.resolve({ ok: true })).then((teardown) => {
339
347
  if (!teardown.ok) {
348
+ const details = {
349
+ ...errorDetails(),
350
+ ...(boundedSwarm || processCleanupUnverified ? { process_cleanup_unverified: true } : {}),
351
+ ...(boundedSwarm && kind === "resolve" ? {
352
+ process_exit_code: payload.exitCode,
353
+ process_signal: payload.signal,
354
+ } : {}),
355
+ };
340
356
  appendLogLine({
341
357
  event: "cancellation_teardown_error",
342
358
  message: formatError(teardown.error),
343
359
  });
344
- reject(new RuntimeError("CLI_CANCELLATION_TEARDOWN_FAILED", `kimi cancellation teardown failed: ${formatError(teardown.error)}`, "cli-client.cancellation", teardown.error instanceof Error
345
- ? { cause: teardown.error, details: errorDetails() }
346
- : { details: errorDetails() }));
360
+ reject(new RuntimeError(boundedSwarm ? "CLI_PROCESS_SETTLEMENT_FAILED" : "CLI_CANCELLATION_TEARDOWN_FAILED", `kimi ${boundedSwarm ? "process settlement" : "cancellation teardown"} failed: ${formatError(teardown.error)}`, boundedSwarm ? "cli-client.settlement" : "cli-client.cancellation", teardown.error instanceof Error
361
+ ? { cause: teardown.error, details }
362
+ : { details }));
347
363
  return;
348
364
  }
349
365
  if (kind === "resolve")
@@ -357,16 +373,21 @@ export async function runCliPrompt(opts) {
357
373
  let processExited = false;
358
374
  child.once("exit", () => {
359
375
  processExited = true;
376
+ // A descendant may still hold stdout open. Start cleanup on exit rather
377
+ // than waiting for close, which cannot arrive until that tail is gone.
378
+ if (boundedSwarm)
379
+ beginTeardown();
360
380
  });
361
- const captureDescendantIdentities = async (childPid) => {
381
+ const captureProcessIdentities = async (collect, excludedPid, onFailure) => {
362
382
  let snapshot;
363
383
  try {
364
- const collected = await raceWithValueTimeout((opts.descendantIdentityCollector ?? collectDescendantIdentities)(childPid), DESCENDANT_SNAPSHOT_TIMEOUT_MS, DESCENDANT_SNAPSHOT_TIMEOUT);
384
+ const collected = await raceWithValueTimeout(collect(), DESCENDANT_SNAPSHOT_TIMEOUT_MS, DESCENDANT_SNAPSHOT_TIMEOUT);
365
385
  if (collected === DESCENDANT_SNAPSHOT_TIMEOUT) {
366
386
  appendLogLine({
367
387
  event: "descendant_collection_timeout",
368
388
  timeout_ms: DESCENDANT_SNAPSHOT_TIMEOUT_MS,
369
389
  });
390
+ onFailure?.(new Error("descendant ownership snapshot timed out"));
370
391
  return [];
371
392
  }
372
393
  snapshot = collected;
@@ -376,6 +397,7 @@ export async function runCliPrompt(opts) {
376
397
  event: "descendant_collection_error",
377
398
  message: formatError(err),
378
399
  });
400
+ onFailure?.(err);
379
401
  return [];
380
402
  }
381
403
  const identities = [];
@@ -384,7 +406,7 @@ export async function runCliPrompt(opts) {
384
406
  const key = `${identity.pid}:${identity.startToken}:${identity.processGroupId}`;
385
407
  if (Number.isInteger(identity.pid) &&
386
408
  identity.pid > 0 &&
387
- identity.pid !== childPid &&
409
+ identity.pid !== excludedPid &&
388
410
  Number.isInteger(identity.processGroupId) &&
389
411
  identity.processGroupId > 0 &&
390
412
  identity.startToken.length > 0 &&
@@ -395,6 +417,7 @@ export async function runCliPrompt(opts) {
395
417
  }
396
418
  return identities;
397
419
  };
420
+ const captureDescendantIdentities = (childPid, expectedRoot, onFailure) => captureProcessIdentities(() => (opts.descendantIdentityCollector ?? collectDescendantIdentities)(childPid, expectedRoot), childPid, onFailure);
398
421
  const trySignalPid = (pid, signal) => {
399
422
  try {
400
423
  process.kill(pid, signal);
@@ -437,7 +460,131 @@ export async function runCliPrompt(opts) {
437
460
  trySignalPid(-processGroupId, signal);
438
461
  }
439
462
  };
463
+ const trackedIdentities = new Map();
464
+ const identityKey = (identity) => `${identity.pid}:${identity.startToken}`;
465
+ let trackerTimer;
466
+ let trackerPass;
467
+ let publishedIdentities = "";
468
+ let spawnRecorded = opts.onSpawn === undefined;
469
+ let observationError;
470
+ let checkpointError;
471
+ let lastPassComplete = false;
472
+ let lastPassCheckpointed = false;
473
+ const retainIdentities = (identities) => {
474
+ for (const identity of identities) {
475
+ // A changed PGID is not a new ownership grant. Keep the first identity
476
+ // so revalidation refuses to signal a process that moved groups.
477
+ if (!trackedIdentities.has(identityKey(identity))) {
478
+ trackedIdentities.set(identityKey(identity), identity);
479
+ }
480
+ }
481
+ };
482
+ const refreshTrackedIdentities = () => {
483
+ if (trackerPass)
484
+ return trackerPass;
485
+ trackerPass = (async () => {
486
+ lastPassComplete = false;
487
+ lastPassCheckpointed = false;
488
+ let passError;
489
+ const noteFailure = (error) => { passError ??= error; };
490
+ const childPid = child.pid;
491
+ if (childPid === undefined || process.platform === "win32")
492
+ return;
493
+ const reachable = !processExited ? await captureDescendantIdentities(childPid, undefined, noteFailure) : [];
494
+ retainIdentities(reachable);
495
+ const reachableKeys = new Set(reachable.map(identityKey));
496
+ const validation = await revalidateProcessIdentities([...trackedIdentities.values()], {
497
+ identityReader, timeoutMs: IDENTITY_REVALIDATION_TIMEOUT_MS,
498
+ });
499
+ if (!validation.complete) {
500
+ noteFailure(new Error("descendant ownership could not be revalidated"));
501
+ }
502
+ // Once a shell exits its surviving children are no longer under the
503
+ // print root. Reuse their pinned identities as anchors, never bare PIDs.
504
+ // Dead anchors provide no discovery evidence. Incomplete validation
505
+ // retains earlier identities without multiplying full-table probes.
506
+ const orphanedAnchors = validation.complete
507
+ ? validation.identities.filter((identity) => !reachableKeys.has(identityKey(identity)))
508
+ : [];
509
+ const additional = orphanedAnchors.length === 0 ? [] : await captureProcessIdentities(() => (opts.descendantIdentityBatchCollector ?? collectDescendantIdentitiesForRoots)(orphanedAnchors), childPid, noteFailure);
510
+ retainIdentities(additional);
511
+ if (passError === undefined) {
512
+ const liveKeys = new Set([
513
+ ...validation.identities, ...(validation.groupChanged ?? []), ...additional,
514
+ ].map(identityKey));
515
+ for (const key of trackedIdentities.keys()) {
516
+ if (!liveKeys.has(key))
517
+ trackedIdentities.delete(key);
518
+ }
519
+ }
520
+ // Observation failures describe this pass. A later complete pass can
521
+ // recover; incomplete passes retain every earlier ownership identity.
522
+ observationError = passError;
523
+ lastPassComplete = passError === undefined;
524
+ const current = [...trackedIdentities.values()];
525
+ const signature = JSON.stringify([current.map((identity) => [identity.pid, identity.startToken, identity.processGroupId]), lastPassComplete]);
526
+ // Recovery stores the print root first. Capture starts immediately,
527
+ // but descendant publication waits for that durable root checkpoint.
528
+ if (spawnRecorded) {
529
+ if (signature === publishedIdentities && checkpointError === undefined) {
530
+ lastPassCheckpointed = true;
531
+ }
532
+ else {
533
+ try {
534
+ await opts.onProcessIdentities?.(current, lastPassComplete);
535
+ publishedIdentities = signature;
536
+ checkpointError = undefined;
537
+ lastPassCheckpointed = true;
538
+ }
539
+ catch (error) {
540
+ checkpointError = error;
541
+ }
542
+ }
543
+ }
544
+ })().catch((error) => {
545
+ observationError = error;
546
+ lastPassComplete = false;
547
+ }).finally(() => {
548
+ trackerPass = undefined;
549
+ });
550
+ return trackerPass;
551
+ };
552
+ const waitForTrackedExit = async (timeoutMs) => {
553
+ const deadline = Date.now() + Math.max(0, timeoutMs);
554
+ while (true) {
555
+ await refreshTrackedIdentities();
556
+ if (processExited && trackedIdentities.size === 0 && lastPassComplete && lastPassCheckpointed)
557
+ return true;
558
+ if (Date.now() >= deadline)
559
+ return false;
560
+ await new Promise((resolve) => setTimeout(resolve, Math.min(BOUNDED_DESCENDANT_POLL_MS, deadline - Date.now())));
561
+ }
562
+ };
563
+ const teardownBoundedTree = async () => {
564
+ const childPid = child.pid;
565
+ try {
566
+ await opts.cancellationTeardownHook?.();
567
+ if (childPid === undefined)
568
+ return;
569
+ await refreshTrackedIdentities();
570
+ await signalCapturedTree(childPid, [...trackedIdentities.values()], "SIGTERM");
571
+ let quiescent = await waitForTrackedExit(escalationMs);
572
+ if (!quiescent && Number.isFinite(escalationMs)) {
573
+ await signalCapturedTree(childPid, [...trackedIdentities.values()], "SIGKILL");
574
+ quiescent = await waitForTrackedExit(POST_KILL_QUIESCENCE_MS);
575
+ }
576
+ if (!quiescent)
577
+ throw checkpointError ?? observationError ?? new Error("owned descendants did not reach verified quiescence");
578
+ }
579
+ finally {
580
+ if (trackerTimer)
581
+ clearInterval(trackerTimer);
582
+ await trackerPass;
583
+ }
584
+ };
440
585
  const teardownChildTree = async () => {
586
+ if (boundedSwarm && process.platform !== "win32")
587
+ return teardownBoundedTree();
441
588
  await opts.cancellationTeardownHook?.();
442
589
  const childPid = child.pid;
443
590
  if (childPid === undefined || processExited)
@@ -465,7 +612,11 @@ export async function runCliPrompt(opts) {
465
612
  }
466
613
  return;
467
614
  }
468
- const identities = await captureDescendantIdentities(childPid);
615
+ let snapshotFailure;
616
+ const identities = await captureDescendantIdentities(childPid, undefined, (error) => {
617
+ snapshotFailure ??= { error };
618
+ processCleanupUnverified = true;
619
+ });
469
620
  await signalCapturedTree(childPid, identities, "SIGTERM");
470
621
  // The grace interval starts only after SIGTERM has reached every
471
622
  // revalidated target. Slow process enumeration never consumes the grace.
@@ -487,10 +638,48 @@ export async function runCliPrompt(opts) {
487
638
  });
488
639
  }
489
640
  }
641
+ // An unreadable snapshot is not evidence of an empty descendant tree.
642
+ // Finish the owned-root cleanup before exposing the original failure.
643
+ if (snapshotFailure !== undefined)
644
+ throw snapshotFailure.error;
645
+ };
646
+ const beginTeardown = () => {
647
+ // Assign the shared promise before invoking callbacks that can abort.
648
+ cancellationTeardown ??= Promise.resolve().then(teardownChildTree).then(() => ({ ok: true }), (error) => ({ ok: false, error }));
649
+ void cancellationTeardown.then((outcome) => {
650
+ if (outcome.ok)
651
+ return;
652
+ // Failure cannot strand the live owned root or wait forever for a
653
+ // descendant that still holds its pipes. Surface uncertainty instead.
654
+ const childPid = child.pid;
655
+ if (childPid !== undefined && !processExited) {
656
+ if (process.platform !== "win32")
657
+ trySignalPid(-childPid, "SIGKILL");
658
+ try {
659
+ child.kill("SIGKILL");
660
+ }
661
+ catch { /* Best effort. */ }
662
+ }
663
+ if (boundedSwarm || processCleanupUnverified) {
664
+ // An unverified tail may still hold inherited pipes. Release our
665
+ // handles so reporting failure does not wait on that tail.
666
+ for (const stream of [child.stdin, child.stdout, child.stderr]) {
667
+ try {
668
+ stream.destroy();
669
+ }
670
+ catch { /* Preserve the settlement error. */ }
671
+ }
672
+ try {
673
+ child.unref();
674
+ }
675
+ catch { /* Preserve the settlement error. */ }
676
+ }
677
+ settle("reject", new RuntimeError(boundedSwarm ? "CLI_PROCESS_SETTLEMENT_FAILED" : "CLI_CANCELLATION_TEARDOWN_FAILED", "kimi owned process teardown failed", boundedSwarm ? "cli-client.settlement" : "cli-client.cancellation"));
678
+ });
490
679
  };
491
680
  const stopForPolicyFailure = (error) => {
492
681
  engineMismatchDetected = true; // Stops all further consumer output.
493
- cancellationTeardown ??= teardownChildTree().then(() => ({ ok: true }), (error) => ({ ok: false, error }));
682
+ beginTeardown();
494
683
  settle("reject", error);
495
684
  };
496
685
  let engineMismatchError;
@@ -520,26 +709,13 @@ export async function runCliPrompt(opts) {
520
709
  if (aborted)
521
710
  return;
522
711
  aborted = true;
523
- cancellationTeardown = teardownChildTree().then(() => ({ ok: true }), (error) => ({ ok: false, error }));
524
- void cancellationTeardown.then((outcome) => {
525
- if (outcome.ok)
526
- return;
527
- // A bug in teardown must neither strand the outer promise nor leave the
528
- // owned root running. The controlled child anchors this emergency kill.
529
- const childPid = child.pid;
530
- if (childPid !== undefined && !processExited) {
531
- if (process.platform !== "win32")
532
- trySignalPid(-childPid, "SIGKILL");
533
- try {
534
- child.kill("SIGKILL");
535
- }
536
- catch {
537
- // Best-effort; settlement still surfaces the teardown failure.
538
- }
539
- }
540
- settle("reject", new RuntimeError("CLI_CANCELLATION_TEARDOWN_FAILED", "kimi cancellation teardown failed", "cli-client.cancellation"));
541
- });
712
+ beginTeardown();
542
713
  };
714
+ if (boundedSwarm && process.platform !== "win32" && child.pid !== undefined) {
715
+ void refreshTrackedIdentities();
716
+ trackerTimer = setInterval(() => { void refreshTrackedIdentities(); }, BOUNDED_DESCENDANT_POLL_MS);
717
+ trackerTimer.unref();
718
+ }
543
719
  opts.signal?.addEventListener("abort", onAbort, { once: true });
544
720
  // Abort may occur during any pre-spawn await, and addEventListener does not
545
721
  // replay an already-aborted signal. Re-check after attaching the listener so
@@ -550,10 +726,14 @@ export async function runCliPrompt(opts) {
550
726
  if (child.pid !== undefined && opts.onSpawn) {
551
727
  try {
552
728
  await opts.onSpawn(child.pid);
729
+ spawnRecorded = true;
553
730
  }
554
731
  catch (error) {
732
+ const spawnError = new RuntimeError("CLI_SPAWN_CALLBACK_FAILED", `Failed to record the spawned kimi process: ${formatError(error)}`, "cli-client.spawn", error instanceof Error ? { cause: error, details: errorDetails() } : { details: errorDetails() });
733
+ if (boundedSwarm)
734
+ checkpointError = spawnError;
555
735
  onAbort();
556
- settle("reject", new RuntimeError("CLI_SPAWN_CALLBACK_FAILED", `Failed to record the spawned kimi process: ${formatError(error)}`, "cli-client.spawn", error instanceof Error ? { cause: error, details: errorDetails() } : { details: errorDetails() }));
736
+ settle("reject", spawnError);
557
737
  return;
558
738
  }
559
739
  }
@@ -786,7 +966,7 @@ function buildArgs(opts) {
786
966
  ? opts.env.KIMI_PLUGIN_CC_SMOKE_V2_CANDIDATE
787
967
  : undefined;
788
968
  if (opts.resumeSessionId === undefined &&
789
- ["2.5.0", "2.5.1", "2.5.2", "2.5.3", "2.6.0", "2.6.2"].includes(opts.executionPlan.kimiVersion ?? smokeCandidate ?? "")) {
969
+ ["2.5.0", "2.5.1", "2.5.2", "2.5.3", "2.6.0", "2.6.2", "2.6.3"].includes(opts.executionPlan.kimiVersion ?? smokeCandidate ?? "")) {
790
970
  args.push("--environment", "local");
791
971
  }
792
972
  if (opts.resumeSessionId !== undefined) {
@@ -808,6 +988,19 @@ function buildArgs(opts) {
808
988
  }
809
989
  export function buildKimiCliEnvironment(opts) {
810
990
  const env = { ...opts.env };
991
+ // A previous host/job cannot opt another operation into a swarm policy or
992
+ // choose its bound. Only this immutable execution plan grants the policy.
993
+ delete env[SWARM_POLICY_ENV];
994
+ delete env[SWARM_WAVE_SIZE_ENV];
995
+ if (usesBoundedSwarmPolicy(opts.executionPlan)) {
996
+ if (opts.commandLabel !== opts.executionPlan.operationKind ||
997
+ !Number.isSafeInteger(opts.swarmMaxConcurrency) || (opts.swarmMaxConcurrency ?? 0) < 1) {
998
+ throw new RuntimeError("SWARM_POLICY_INVALID", "Bounded swarm requires its exact operation label and a positive safe-integer concurrency limit.", "cli-client.environment");
999
+ }
1000
+ env[SWARM_POLICY_ENV] = BOUNDED_SWARM_POLICY;
1001
+ env[SWARM_WAVE_SIZE_ENV] = String(opts.swarmMaxConcurrency);
1002
+ env.KIMI_CODE_SWARM_TIMEOUT_MS = String(SWARM_CHILD_TIMEOUT_MS);
1003
+ }
811
1004
  if (opts.thinkingEffort !== undefined)
812
1005
  env.KIMI_MODEL_THINKING_EFFORT = opts.thinkingEffort;
813
1006
  // Ambient workspace trust starts project MCP stdio servers outside PreToolUse.
@@ -106,6 +106,10 @@ export async function runRecoverSwarm(argv, context) {
106
106
  const recoveryExecutionCwd = await realpath(record.cwd);
107
107
  await deactivateSwarmSession({ cwd: recoveryExecutionCwd, env: context.env, command: current.command,
108
108
  prefixArgs: current.prefixArgs, executionPlan: current, commandLabel: expectedRoot ? "swarm-write" : "swarm",
109
+ // Recovery only deactivates the stopped session; it never starts a model
110
+ // turn. Use the strictest admission policy rather than reconstructing a
111
+ // prior wave limit that recovery records do not need to retain.
112
+ swarmMaxConcurrency: 1,
109
113
  trustedWorkspaceRoot: expectedRoot ?? undefined, ...record.session, signal,
110
114
  onRecoveryEvent: (event) => recordRecoveryEvent(store, record, event) });
111
115
  }
@@ -977,8 +977,12 @@ async function collectKimiVersionWarnings(env, warnings) {
977
977
  warnings.push(formatVersionOutOfRangeWarning(probe, KIMI_PLUGIN_CC_VERSION, NATIVE_V2_ANY_OPERATION_VERSIONS));
978
978
  return;
979
979
  }
980
+ if (probe.version === "2.6.2" || probe.version === "2.6.3") {
981
+ warnings.push(`NOTE: kimi-code ${probe.version} is certified for all operations. Swarm uses bounded waves with concurrency 2 or more, and one direct worker at concurrency 1. The finite job budget stops the whole run.`);
982
+ return;
983
+ }
980
984
  if (NATIVE_V2_NON_SWARM_VERSIONS.includes(probe.version)) {
981
- warnings.push(`NOTE: kimi-code ${probe.version} is certified for review, challenge, ask, rescue, review gate, and pursue only. Read-only swarm and write swarm refuse before model spawn because upstream rate-limit recovery can exceed maxConcurrency.`);
985
+ warnings.push(`NOTE: kimi-code ${probe.version} is certified for review, challenge, ask, rescue, review gate, and pursue only. Read-only swarm and write swarm refuse before model spawn on this exact release. Select exact kimi-code 2.6.2 or 2.6.3 for this plugin's certified bounded waves and single-worker path.`);
982
986
  }
983
987
  }
984
988
  /**