kimi-plugin-cc 2.7.3 → 3.1.0

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 (317) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +3 -16
  3. package/README.md +428 -515
  4. package/assets/logo.svg +6 -0
  5. package/cordis.patch.yml +18 -0
  6. package/dist/background-spawn.js +14 -19
  7. package/dist/cli-client.js +163 -105
  8. package/dist/commands/ask.js +44 -96
  9. package/dist/commands/cancel.js +11 -59
  10. package/dist/commands/cli-helpers.js +102 -1
  11. package/dist/commands/models.js +2 -3
  12. package/dist/commands/pursue.js +8 -21
  13. package/dist/commands/registry.js +7 -26
  14. package/dist/commands/repair-sessions.js +121 -12
  15. package/dist/commands/replay.js +4 -3
  16. package/dist/commands/rescue.js +29 -87
  17. package/dist/commands/result.js +7 -1
  18. package/dist/commands/review.js +28 -18
  19. package/dist/commands/setup.js +813 -462
  20. package/dist/commands/status.js +2 -2
  21. package/dist/commands/swarm.js +112 -125
  22. package/dist/commands/worker.js +1 -2
  23. package/dist/companion.js +145 -19
  24. package/dist/git.js +1 -9
  25. package/dist/help.js +13 -9
  26. package/dist/hook-escape.js +7 -16
  27. package/dist/hooks/approval-hook.js +1766 -87
  28. package/dist/hooks/approval-policy.js +86 -19
  29. package/dist/hooks/config-safety.js +31 -64
  30. package/dist/hooks/hook-timing.js +48 -0
  31. package/dist/hooks/install-paths.js +179 -107
  32. package/dist/hooks/install.js +126 -53
  33. package/dist/hooks/managed-block.js +121 -127
  34. package/dist/job-store.js +206 -166
  35. package/dist/jobs.js +66 -19
  36. package/dist/kimi-command.js +74 -1
  37. package/dist/kimi-engine.js +198 -127
  38. package/dist/kimi-errors.js +15 -70
  39. package/dist/kimi-home.js +6 -0
  40. package/dist/kimi-journal.js +42 -0
  41. package/dist/kimi-releases.js +123 -0
  42. package/dist/kimi-timeouts.js +2 -16
  43. package/dist/kimi-version-probe.js +24 -108
  44. package/dist/logging.js +12 -7
  45. package/dist/mcp/binding.js +13 -4
  46. package/dist/mcp/job-control.js +390 -95
  47. package/dist/mcp/launcher.js +13 -7
  48. package/dist/mcp/operations.js +405 -179
  49. package/dist/mcp/protocol.js +124 -33
  50. package/dist/mcp/skills.js +130 -0
  51. package/dist/mcp/stdio.js +18 -4
  52. package/dist/model-command.js +5 -3
  53. package/dist/native-v2-preflight.js +243 -80
  54. package/dist/parsing.js +211 -243
  55. package/dist/paths.js +28 -10
  56. package/dist/plugin-data.js +28 -83
  57. package/dist/process-tree.js +35 -24
  58. package/dist/read-scope.js +435 -0
  59. package/dist/render.js +58 -46
  60. package/dist/rescue-approval.js +461 -84
  61. package/dist/session-references.js +216 -0
  62. package/dist/session-title.js +26 -6
  63. package/dist/stream-json.js +1 -3
  64. package/dist/surface-routing.js +108 -0
  65. package/dist/swarm-activation.js +74 -188
  66. package/dist/swarm-policy.js +2 -1
  67. package/dist/swarm-recovery.js +2 -1
  68. package/dist/util.js +28 -0
  69. package/dist/version.js +1 -1
  70. package/docs/migration.md +45 -206
  71. package/docs/models.md +24 -66
  72. package/docs/safety.md +198 -353
  73. package/docs/session-visibility.md +25 -13
  74. package/docs/swarm-recovery.md +26 -20
  75. package/dsh/index.json +54 -0
  76. package/mcp_config.json +10 -0
  77. package/package.json +23 -82
  78. package/plugin.json +19 -0
  79. package/plugins/kimi-codex/.codex-plugin/plugin.json +7 -7
  80. package/plugins/kimi-codex/.mcp.json +3 -3
  81. package/plugins/kimi-codex/dist/background-spawn.js +14 -19
  82. package/plugins/kimi-codex/dist/cli-client.js +163 -105
  83. package/plugins/kimi-codex/dist/commands/ask.js +44 -96
  84. package/plugins/kimi-codex/dist/commands/cancel.js +11 -59
  85. package/plugins/kimi-codex/dist/commands/cli-helpers.js +102 -1
  86. package/plugins/kimi-codex/dist/commands/models.js +2 -3
  87. package/plugins/kimi-codex/dist/commands/pursue.js +8 -21
  88. package/plugins/kimi-codex/dist/commands/registry.js +7 -26
  89. package/plugins/kimi-codex/dist/commands/repair-sessions.js +121 -12
  90. package/plugins/kimi-codex/dist/commands/replay.js +4 -3
  91. package/plugins/kimi-codex/dist/commands/rescue.js +29 -87
  92. package/plugins/kimi-codex/dist/commands/result.js +7 -1
  93. package/plugins/kimi-codex/dist/commands/review.js +28 -18
  94. package/plugins/kimi-codex/dist/commands/setup.js +813 -462
  95. package/plugins/kimi-codex/dist/commands/status.js +2 -2
  96. package/plugins/kimi-codex/dist/commands/swarm.js +112 -125
  97. package/plugins/kimi-codex/dist/commands/worker.js +1 -2
  98. package/plugins/kimi-codex/dist/companion.js +145 -19
  99. package/plugins/kimi-codex/dist/git.js +1 -9
  100. package/plugins/kimi-codex/dist/help.js +13 -9
  101. package/plugins/kimi-codex/dist/hook-escape.js +7 -16
  102. package/plugins/kimi-codex/dist/hooks/approval-hook.js +1766 -87
  103. package/plugins/kimi-codex/dist/hooks/approval-policy.js +86 -19
  104. package/plugins/kimi-codex/dist/hooks/config-safety.js +31 -64
  105. package/plugins/kimi-codex/dist/hooks/hook-timing.js +48 -0
  106. package/plugins/kimi-codex/dist/hooks/install-paths.js +179 -107
  107. package/plugins/kimi-codex/dist/hooks/install.js +126 -53
  108. package/plugins/kimi-codex/dist/hooks/managed-block.js +121 -127
  109. package/plugins/kimi-codex/dist/job-store.js +206 -166
  110. package/plugins/kimi-codex/dist/jobs.js +66 -19
  111. package/plugins/kimi-codex/dist/kimi-command.js +74 -1
  112. package/plugins/kimi-codex/dist/kimi-engine.js +198 -127
  113. package/plugins/kimi-codex/dist/kimi-errors.js +15 -70
  114. package/plugins/kimi-codex/dist/kimi-home.js +6 -0
  115. package/plugins/kimi-codex/dist/kimi-journal.js +42 -0
  116. package/plugins/kimi-codex/dist/kimi-releases.js +123 -0
  117. package/plugins/kimi-codex/dist/kimi-timeouts.js +2 -16
  118. package/plugins/kimi-codex/dist/kimi-version-probe.js +24 -108
  119. package/plugins/kimi-codex/dist/logging.js +12 -7
  120. package/plugins/kimi-codex/dist/mcp/binding.js +13 -4
  121. package/plugins/kimi-codex/dist/mcp/job-control.js +390 -95
  122. package/plugins/kimi-codex/dist/mcp/launcher.js +13 -7
  123. package/plugins/kimi-codex/dist/mcp/operations.js +405 -179
  124. package/plugins/kimi-codex/dist/mcp/protocol.js +124 -33
  125. package/plugins/kimi-codex/dist/mcp/skills.js +130 -0
  126. package/plugins/kimi-codex/dist/mcp/stdio.js +18 -4
  127. package/plugins/kimi-codex/dist/model-command.js +5 -3
  128. package/plugins/kimi-codex/dist/native-v2-preflight.js +243 -80
  129. package/plugins/kimi-codex/dist/parsing.js +211 -243
  130. package/plugins/kimi-codex/dist/paths.js +28 -10
  131. package/plugins/kimi-codex/dist/plugin-data.js +28 -83
  132. package/plugins/kimi-codex/dist/process-tree.js +35 -24
  133. package/plugins/kimi-codex/dist/read-scope.js +435 -0
  134. package/plugins/kimi-codex/dist/render.js +58 -46
  135. package/plugins/kimi-codex/dist/rescue-approval.js +461 -84
  136. package/plugins/kimi-codex/dist/session-references.js +216 -0
  137. package/plugins/kimi-codex/dist/session-title.js +26 -6
  138. package/plugins/kimi-codex/dist/stream-json.js +1 -3
  139. package/plugins/kimi-codex/dist/surface-routing.js +108 -0
  140. package/plugins/kimi-codex/dist/swarm-activation.js +74 -188
  141. package/plugins/kimi-codex/dist/swarm-policy.js +2 -1
  142. package/plugins/kimi-codex/dist/swarm-recovery.js +2 -1
  143. package/plugins/kimi-codex/dist/util.js +28 -0
  144. package/plugins/kimi-codex/dist/version.js +1 -1
  145. package/plugins/kimi-codex/scripts/companion.sh +4 -15
  146. package/plugins/kimi-codex/skills/kimi/SKILL.md +77 -0
  147. package/plugins/kimi-codex/skills/kimi/agents/openai.yaml +6 -0
  148. package/scripts/companion.sh +4 -15
  149. package/skills/kimi/SKILL.md +77 -0
  150. package/skills/kimi/agents/openai.yaml +6 -0
  151. package/CHANGELOG.md +0 -1333
  152. package/agents/kimi-ask.md +0 -89
  153. package/agents/kimi-challenge.md +0 -86
  154. package/agents/kimi-pursue.md +0 -93
  155. package/agents/kimi-rescue.md +0 -92
  156. package/agents/kimi-review.md +0 -86
  157. package/agents/kimi-swarm-write.md +0 -96
  158. package/agents/kimi-swarm.md +0 -86
  159. package/commands/README.md +0 -16
  160. package/commands/ask.md +0 -38
  161. package/commands/cancel.md +0 -17
  162. package/commands/challenge.md +0 -35
  163. package/commands/pursue.md +0 -41
  164. package/commands/replay.md +0 -13
  165. package/commands/rescue.md +0 -38
  166. package/commands/result.md +0 -13
  167. package/commands/review.md +0 -35
  168. package/commands/setup.md +0 -23
  169. package/commands/status.md +0 -13
  170. package/commands/swarm.md +0 -44
  171. package/dist/commands/not-implemented.js +0 -4
  172. package/dist/commands/review-gate.js +0 -390
  173. package/dist/config.js +0 -22
  174. package/dist/dsh/companion.js +0 -177
  175. package/dist/dsh/index.js +0 -169
  176. package/dist/hooks/review-gate-stop.js +0 -19
  177. package/dist/schemas/review-gate-output.js +0 -43
  178. package/docs/registry-releases.md +0 -228
  179. package/docs/upstream-2.4.1-certification.md +0 -54
  180. package/docs/upstream-2.5.0-certification.md +0 -52
  181. package/docs/upstream-2.5.1-certification.md +0 -47
  182. package/docs/upstream-2.5.2-certification.md +0 -40
  183. package/docs/upstream-2.5.3-certification.md +0 -73
  184. package/docs/upstream-2.6.0-certification.md +0 -65
  185. package/docs/upstream-2.6.2-certification.md +0 -144
  186. package/docs/upstream-2.6.3-certification.md +0 -100
  187. package/docs/upstream-2.7.2-certification.md +0 -113
  188. package/docs/upstream-2.7.3-certification.md +0 -83
  189. package/docs/windows-validation.md +0 -39
  190. package/hooks/README.md +0 -9
  191. package/hooks/hooks.json +0 -16
  192. package/plugins/kimi-codex/dist/commands/not-implemented.js +0 -4
  193. package/plugins/kimi-codex/dist/commands/review-gate.js +0 -390
  194. package/plugins/kimi-codex/dist/config.js +0 -22
  195. package/plugins/kimi-codex/dist/dsh/companion.js +0 -177
  196. package/plugins/kimi-codex/dist/dsh/index.js +0 -169
  197. package/plugins/kimi-codex/dist/hooks/review-gate-stop.js +0 -19
  198. package/plugins/kimi-codex/dist/schemas/review-gate-output.js +0 -43
  199. package/plugins/kimi-codex/scripts/review-gate-hook.sh +0 -32
  200. package/plugins/kimi-codex/skills/kimi-ask/SKILL.md +0 -35
  201. package/plugins/kimi-codex/skills/kimi-ask/agents/openai.yaml +0 -6
  202. package/plugins/kimi-codex/skills/kimi-cancel/SKILL.md +0 -25
  203. package/plugins/kimi-codex/skills/kimi-cancel/agents/openai.yaml +0 -6
  204. package/plugins/kimi-codex/skills/kimi-challenge/SKILL.md +0 -34
  205. package/plugins/kimi-codex/skills/kimi-challenge/agents/openai.yaml +0 -6
  206. package/plugins/kimi-codex/skills/kimi-pursue/SKILL.md +0 -32
  207. package/plugins/kimi-codex/skills/kimi-pursue/agents/openai.yaml +0 -6
  208. package/plugins/kimi-codex/skills/kimi-replay/SKILL.md +0 -25
  209. package/plugins/kimi-codex/skills/kimi-replay/agents/openai.yaml +0 -6
  210. package/plugins/kimi-codex/skills/kimi-rescue/SKILL.md +0 -34
  211. package/plugins/kimi-codex/skills/kimi-rescue/agents/openai.yaml +0 -6
  212. package/plugins/kimi-codex/skills/kimi-result/SKILL.md +0 -25
  213. package/plugins/kimi-codex/skills/kimi-result/agents/openai.yaml +0 -6
  214. package/plugins/kimi-codex/skills/kimi-review/SKILL.md +0 -34
  215. package/plugins/kimi-codex/skills/kimi-review/agents/openai.yaml +0 -6
  216. package/plugins/kimi-codex/skills/kimi-setup/SKILL.md +0 -34
  217. package/plugins/kimi-codex/skills/kimi-setup/agents/openai.yaml +0 -6
  218. package/plugins/kimi-codex/skills/kimi-status/SKILL.md +0 -25
  219. package/plugins/kimi-codex/skills/kimi-status/agents/openai.yaml +0 -6
  220. package/plugins/kimi-codex/skills/kimi-swarm/SKILL.md +0 -35
  221. package/plugins/kimi-codex/skills/kimi-swarm/agents/openai.yaml +0 -6
  222. package/plugins/kimi-codex/skills/kimi-swarm-write/SKILL.md +0 -36
  223. package/plugins/kimi-codex/skills/kimi-swarm-write/agents/openai.yaml +0 -6
  224. package/plugins/kimi-dsh/LICENSE +0 -201
  225. package/plugins/kimi-dsh/README.md +0 -83
  226. package/plugins/kimi-dsh/cordis.patch.yml +0 -45
  227. package/plugins/kimi-dsh/dist/background-spawn.js +0 -216
  228. package/plugins/kimi-dsh/dist/cli-cancellation.js +0 -43
  229. package/plugins/kimi-dsh/dist/cli-client.js +0 -1078
  230. package/plugins/kimi-dsh/dist/commands/ask.js +0 -336
  231. package/plugins/kimi-dsh/dist/commands/cancel.js +0 -216
  232. package/plugins/kimi-dsh/dist/commands/cli-helpers.js +0 -201
  233. package/plugins/kimi-dsh/dist/commands/models.js +0 -140
  234. package/plugins/kimi-dsh/dist/commands/not-implemented.js +0 -4
  235. package/plugins/kimi-dsh/dist/commands/pursue.js +0 -307
  236. package/plugins/kimi-dsh/dist/commands/recover-swarm.js +0 -140
  237. package/plugins/kimi-dsh/dist/commands/registry.js +0 -74
  238. package/plugins/kimi-dsh/dist/commands/repair-sessions.js +0 -160
  239. package/plugins/kimi-dsh/dist/commands/replay.js +0 -124
  240. package/plugins/kimi-dsh/dist/commands/rescue.js +0 -347
  241. package/plugins/kimi-dsh/dist/commands/result.js +0 -66
  242. package/plugins/kimi-dsh/dist/commands/review-gate.js +0 -390
  243. package/plugins/kimi-dsh/dist/commands/review.js +0 -220
  244. package/plugins/kimi-dsh/dist/commands/setup.js +0 -1129
  245. package/plugins/kimi-dsh/dist/commands/status.js +0 -27
  246. package/plugins/kimi-dsh/dist/commands/swarm.js +0 -849
  247. package/plugins/kimi-dsh/dist/commands/worker.js +0 -25
  248. package/plugins/kimi-dsh/dist/companion.js +0 -97
  249. package/plugins/kimi-dsh/dist/config.js +0 -22
  250. package/plugins/kimi-dsh/dist/dsh/companion.js +0 -177
  251. package/plugins/kimi-dsh/dist/dsh/index.js +0 -169
  252. package/plugins/kimi-dsh/dist/errors.js +0 -40
  253. package/plugins/kimi-dsh/dist/git.js +0 -224
  254. package/plugins/kimi-dsh/dist/help.js +0 -43
  255. package/plugins/kimi-dsh/dist/hook-escape.js +0 -71
  256. package/plugins/kimi-dsh/dist/hooks/approval-hook.js +0 -104
  257. package/plugins/kimi-dsh/dist/hooks/approval-policy.js +0 -233
  258. package/plugins/kimi-dsh/dist/hooks/config-safety.js +0 -665
  259. package/plugins/kimi-dsh/dist/hooks/install-paths.js +0 -428
  260. package/plugins/kimi-dsh/dist/hooks/install.js +0 -210
  261. package/plugins/kimi-dsh/dist/hooks/managed-block.js +0 -684
  262. package/plugins/kimi-dsh/dist/hooks/review-gate-stop.js +0 -19
  263. package/plugins/kimi-dsh/dist/job-id.js +0 -12
  264. package/plugins/kimi-dsh/dist/job-store.js +0 -659
  265. package/plugins/kimi-dsh/dist/jobs.js +0 -217
  266. package/plugins/kimi-dsh/dist/kimi-command.js +0 -71
  267. package/plugins/kimi-dsh/dist/kimi-engine.js +0 -675
  268. package/plugins/kimi-dsh/dist/kimi-errors.js +0 -260
  269. package/plugins/kimi-dsh/dist/kimi-home.js +0 -9
  270. package/plugins/kimi-dsh/dist/kimi-timeouts.js +0 -52
  271. package/plugins/kimi-dsh/dist/kimi-version-probe.js +0 -234
  272. package/plugins/kimi-dsh/dist/logging.js +0 -22
  273. package/plugins/kimi-dsh/dist/mcp/binding.js +0 -58
  274. package/plugins/kimi-dsh/dist/mcp/job-control.js +0 -345
  275. package/plugins/kimi-dsh/dist/mcp/launcher.js +0 -257
  276. package/plugins/kimi-dsh/dist/mcp/operations.js +0 -301
  277. package/plugins/kimi-dsh/dist/mcp/protocol.js +0 -275
  278. package/plugins/kimi-dsh/dist/mcp/server.js +0 -8
  279. package/plugins/kimi-dsh/dist/mcp/stdio.js +0 -78
  280. package/plugins/kimi-dsh/dist/mcp/supervised-child.js +0 -15
  281. package/plugins/kimi-dsh/dist/mcp/tool-result.js +0 -7
  282. package/plugins/kimi-dsh/dist/mcp/workspace.js +0 -34
  283. package/plugins/kimi-dsh/dist/model-command.js +0 -32
  284. package/plugins/kimi-dsh/dist/native-v2-preflight.js +0 -525
  285. package/plugins/kimi-dsh/dist/package.json +0 -1
  286. package/plugins/kimi-dsh/dist/parsing.js +0 -620
  287. package/plugins/kimi-dsh/dist/paths.js +0 -27
  288. package/plugins/kimi-dsh/dist/plugin-data.js +0 -98
  289. package/plugins/kimi-dsh/dist/process-tree.js +0 -586
  290. package/plugins/kimi-dsh/dist/prompt-size.js +0 -18
  291. package/plugins/kimi-dsh/dist/render.js +0 -177
  292. package/plugins/kimi-dsh/dist/rescue-approval.js +0 -865
  293. package/plugins/kimi-dsh/dist/schemas/review-gate-output.js +0 -43
  294. package/plugins/kimi-dsh/dist/session-recovery.js +0 -202
  295. package/plugins/kimi-dsh/dist/session-title.js +0 -293
  296. package/plugins/kimi-dsh/dist/stream-json.js +0 -346
  297. package/plugins/kimi-dsh/dist/swarm-activation.js +0 -1197
  298. package/plugins/kimi-dsh/dist/swarm-policy.js +0 -73
  299. package/plugins/kimi-dsh/dist/swarm-recovery.js +0 -165
  300. package/plugins/kimi-dsh/dist/swarm-tool-policy.js +0 -146
  301. package/plugins/kimi-dsh/dist/types.js +0 -1
  302. package/plugins/kimi-dsh/dist/vendor/shell-quote/LICENSE +0 -24
  303. package/plugins/kimi-dsh/dist/vendor/shell-quote/index.js +0 -1
  304. package/plugins/kimi-dsh/dist/vendor/shell-quote/parse.js +0 -229
  305. package/plugins/kimi-dsh/dist/vendor/smol-toml/LICENSE +0 -24
  306. package/plugins/kimi-dsh/dist/vendor/smol-toml/date.js +0 -156
  307. package/plugins/kimi-dsh/dist/vendor/smol-toml/error.js +0 -67
  308. package/plugins/kimi-dsh/dist/vendor/smol-toml/extract.js +0 -293
  309. package/plugins/kimi-dsh/dist/vendor/smol-toml/parse.js +0 -164
  310. package/plugins/kimi-dsh/dist/vendor/smol-toml/primitive.js +0 -151
  311. package/plugins/kimi-dsh/dist/vendor/smol-toml/struct.js +0 -156
  312. package/plugins/kimi-dsh/dist/vendor/smol-toml/util.js +0 -57
  313. package/plugins/kimi-dsh/dist/version.js +0 -7
  314. package/plugins/kimi-dsh/package.json +0 -78
  315. package/plugins/kimi-dsh/scripts/companion.sh +0 -37
  316. package/plugins/kimi-dsh/scripts/review-gate-hook.sh +0 -32
  317. package/scripts/review-gate-hook.sh +0 -32
@@ -1,38 +1,47 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { RuntimeError, formatError } from "./errors.js";
3
- export class JobStore {
4
- db;
5
- constructor(paths) {
6
- // Open the adapter into a local before assigning to this.db so the
7
- // catch can release the handle even if pragma throws AFTER the
8
- // adapter opened — `journal_mode = WAL` on a read-only mount, for
9
- // example, would otherwise leak the handle because the constructor
10
- // exits via throw before any caller reference exists for cleanup.
3
+ const JOB_STORE_SCHEMA_VERSION = 310;
4
+ const BUSY_OPEN_WAIT = new Int32Array(new SharedArrayBuffer(4));
5
+ function openAndInitializeJobStore(paths) {
6
+ // Retry transient SQLITE_BUSY / SQLITE_PROTOCOL contention during concurrent
7
+ // process open/WAL setup because PRAGMA journal_mode = WAL ignores busy_timeout.
8
+ for (let attempt = 0; attempt < 8; attempt += 1) {
11
9
  let db;
12
10
  try {
13
11
  db = createSqliteAdapter(paths.stateDbPath);
14
- // busy_timeout FIRST: switching the journal mode takes a brief write lock,
15
- // and a second opener (status/result racing a worker) otherwise fails
16
- // immediately with SQLITE_BUSY instead of waiting (seen 2026-10-14).
12
+ // busy_timeout FIRST: switching the journal mode or migrating schema takes a write lock.
17
13
  db.pragma("busy_timeout = 5000");
18
- db.pragma("journal_mode = WAL");
14
+ const mode = db.all("PRAGMA journal_mode")[0]?.journal_mode?.toLowerCase();
15
+ if (mode !== "wal") {
16
+ db.pragma("journal_mode = WAL");
17
+ }
18
+ const userVersion = db.all("PRAGMA user_version")[0]?.user_version ?? 0;
19
+ if (userVersion < JOB_STORE_SCHEMA_VERSION) {
20
+ initializeJobStoreSchema(db);
21
+ db.pragma(`user_version = ${JOB_STORE_SCHEMA_VERSION}`);
22
+ }
23
+ return db;
19
24
  }
20
25
  catch (error) {
26
+ // Release the OS handle before backoff or propagation; swallow close errors
27
+ // so the original SQLite failure takes priority.
21
28
  try {
22
29
  db?.close();
23
30
  }
24
31
  catch {
25
- // Best-effort — original error takes priority over close failure.
32
+ // intentionally swallow — original error takes priority
33
+ }
34
+ if (attempt < 7 && isSqliteBusyError(error)) {
35
+ Atomics.wait(BUSY_OPEN_WAIT, 0, 0, 25 * (attempt + 1));
36
+ continue;
26
37
  }
27
38
  throw translateSqliteError(error);
28
39
  }
29
- this.db = db;
30
- // Every `this.db.exec` / `tableHasColumn` below can throw on a
31
- // corrupt DB, full disk, mid-migration failure, etc. Catch
32
- // internally, close the adapter, and rethrow the translated error
33
- // so the SQLite handle never leaks past a failed migration.
34
- try {
35
- this.db.exec(`
40
+ }
41
+ throw translateSqliteError(new Error("database is locked"));
42
+ }
43
+ function initializeJobStoreSchema(db) {
44
+ db.exec(`
36
45
  CREATE TABLE IF NOT EXISTS jobs (
37
46
  job_id TEXT PRIMARY KEY,
38
47
  repo_id TEXT NOT NULL,
@@ -67,38 +76,13 @@ export class JobStore {
67
76
  error TEXT
68
77
  );
69
78
  `);
70
- if (!tableHasColumn(this.db, "phase")) {
71
- this.db.exec(`ALTER TABLE jobs ADD COLUMN phase TEXT;`);
72
- }
73
- if (!tableHasColumn(this.db, "budget_ms")) {
74
- this.db.exec(`ALTER TABLE jobs ADD COLUMN budget_ms INTEGER;`);
75
- }
76
- for (const column of ["kimi_session_id_source", "budget_source", "thinking_effort", "hook_escapes"]) {
77
- if (!tableHasColumn(this.db, column)) {
78
- this.db.exec("ALTER TABLE jobs ADD COLUMN " + column + " TEXT;");
79
- }
80
- }
81
- // Additive provenance migration. Existing rows deliberately remain NULL:
82
- // v1.9.5 plus kimi-code 0.33/0.34 could have routed to native v2 before the
83
- // legacy pin landed, so a blanket historical v1 backfill would invent fact.
84
- const provenanceColumns = [
85
- "operation_kind",
86
- "intended_engine",
87
- "observed_engine",
88
- "kimi_version",
89
- "system_version",
90
- "kimi_command",
91
- "kimi_prefix_args",
92
- "plan_certification",
93
- "resumed_from_job_id",
94
- "safety_profile",
95
- ];
96
- for (const column of provenanceColumns) {
97
- if (!tableHasColumn(this.db, column)) {
98
- this.db.exec(`ALTER TABLE jobs ADD COLUMN ${column} TEXT;`);
99
- }
100
- }
101
- this.db.exec(`
79
+ for (const [column, type] of ADDED_JOB_COLUMNS) {
80
+ // Re-read per column: another process may be migrating the same store.
81
+ if (!existingColumns(db, "jobs").has(column)) {
82
+ db.exec(`ALTER TABLE jobs ADD COLUMN ${column} ${type};`);
83
+ }
84
+ }
85
+ db.exec(`
102
86
  CREATE TABLE IF NOT EXISTS mcp_tasks (
103
87
  task_id TEXT PRIMARY KEY,
104
88
  operation_kind TEXT NOT NULL,
@@ -171,22 +155,14 @@ export class JobStore {
171
155
  -- 0.1.6 migration: rename adversarial_review to challenge
172
156
  UPDATE jobs SET command_type = 'challenge' WHERE command_type = 'adversarial_review';
173
157
  `);
174
- if (!mcpTableHasColumn(this.db, "kimi_identity")) {
175
- this.db.exec("ALTER TABLE mcp_tasks ADD COLUMN kimi_identity TEXT;");
176
- }
177
- }
178
- catch (error) {
179
- // Migration failed — close the adapter so the OS handle is released
180
- // before propagating. Wrap close() in its own try so a double-fault
181
- // doesn't mask the original migration error.
182
- try {
183
- this.db.close();
184
- }
185
- catch {
186
- // intentionally swallow — original error takes priority
187
- }
188
- throw translateSqliteError(error);
189
- }
158
+ if (!existingColumns(db, "mcp_tasks").has("kimi_identity")) {
159
+ db.exec("ALTER TABLE mcp_tasks ADD COLUMN kimi_identity TEXT;");
160
+ }
161
+ }
162
+ export class JobStore {
163
+ db;
164
+ constructor(paths) {
165
+ this.db = openAndInitializeJobStore(paths);
190
166
  }
191
167
  getSwarmRecovery(jobId) {
192
168
  const row = this.db.get("SELECT payload, recovery_owner FROM swarm_recovery WHERE job_id = ?", jobId);
@@ -205,22 +181,7 @@ export class JobStore {
205
181
  createJob(input) {
206
182
  const now = new Date().toISOString();
207
183
  try {
208
- this.db.run(`
209
- INSERT INTO jobs (
210
- job_id, repo_id, command_type, created_at, updated_at, cwd, model, thinking, thinking_effort,
211
- background, pid, kimi_pid, status, kimi_session_id, kimi_session_id_source, budget_source,
212
- operation_kind, intended_engine, observed_engine, kimi_version, system_version,
213
- kimi_command, kimi_prefix_args, plan_certification, resumed_from_job_id, safety_profile,
214
- agent_profile, prompt_digest, summary, phase, budget_ms, final_output_path, stream_log_path, error
215
- )
216
- VALUES (
217
- @job_id, @repo_id, @command_type, @created_at, @updated_at, @cwd, @model, @thinking, @thinking_effort,
218
- @background, @pid, @kimi_pid, @status, @kimi_session_id, @kimi_session_id_source, @budget_source,
219
- @operation_kind, @intended_engine, @observed_engine, @kimi_version, @system_version,
220
- @kimi_command, @kimi_prefix_args, @plan_certification, @resumed_from_job_id, @safety_profile,
221
- @agent_profile, @prompt_digest, @summary, @phase, @budget_ms, @final_output_path, @stream_log_path, @error
222
- )
223
- `, {
184
+ this.db.run(INSERT_JOB_SQL, {
224
185
  ...serializeRecord(input),
225
186
  created_at: now,
226
187
  updated_at: now,
@@ -247,6 +208,10 @@ export class JobStore {
247
208
  hasSessionId(sessionId, exceptJobId = "") {
248
209
  return Boolean(this.db.get("SELECT 1 FROM jobs WHERE kimi_session_id = ? AND job_id != ? LIMIT 1", sessionId, exceptJobId));
249
210
  }
211
+ /** Every job recorded for a Kimi session, across repos and states, oldest first. */
212
+ listJobsBySessionId(sessionId) {
213
+ return this.db.all("SELECT * FROM jobs WHERE kimi_session_id = ? ORDER BY created_at", sessionId).map(hydrateRow);
214
+ }
250
215
  findLatestJob(options) {
251
216
  const conditions = ["repo_id = @repo_id"];
252
217
  const params = {
@@ -265,32 +230,68 @@ export class JobStore {
265
230
  const row = this.db.get(`SELECT * FROM jobs WHERE ${conditions.join(" AND ")} ORDER BY updated_at DESC LIMIT 1`, params);
266
231
  return row ? hydrateRow(row) : null;
267
232
  }
233
+ listJobs(options) {
234
+ const conditions = ["repo_id = @repo_id"];
235
+ const params = {
236
+ repo_id: options.repoId,
237
+ };
238
+ if (options.status) {
239
+ conditions.push("status = @status");
240
+ params.status = options.status;
241
+ }
242
+ if (options.operationKind) {
243
+ conditions.push("operation_kind = @operation_kind");
244
+ params.operation_kind = options.operationKind;
245
+ }
246
+ if (options.limit === null) {
247
+ return this.db
248
+ .all(`SELECT * FROM jobs WHERE ${conditions.join(" AND ")} ORDER BY created_at DESC, rowid DESC`, params)
249
+ .map(hydrateRow);
250
+ }
251
+ params.limit = Math.max(1, Math.min(100, Math.trunc(options.limit ?? 20)));
252
+ return this.db
253
+ .all(`SELECT * FROM jobs WHERE ${conditions.join(" AND ")} ORDER BY created_at DESC, rowid DESC LIMIT @limit`, params)
254
+ .map(hydrateRow);
255
+ }
256
+ listJobsByUpdated(options) {
257
+ const conditions = ["repo_id = @repo_id"];
258
+ const params = {
259
+ repo_id: options.repoId,
260
+ };
261
+ if (options.commandType) {
262
+ conditions.push("command_type = @command_type");
263
+ params.command_type = options.commandType;
264
+ }
265
+ if (options.terminalOnly) {
266
+ conditions.push("status IN ('completed', 'failed', 'cancelled')");
267
+ }
268
+ if (options.runningOnly) {
269
+ conditions.push("status = 'running'");
270
+ }
271
+ return this.db
272
+ .all(`SELECT * FROM jobs WHERE ${conditions.join(" AND ")} ORDER BY updated_at DESC, rowid DESC`, params)
273
+ .map(hydrateRow);
274
+ }
268
275
  listRunningJobsWithProcessHints() {
269
276
  const rows = this.db.all(`SELECT * FROM jobs WHERE status = 'running' AND (pid IS NOT NULL OR kimi_pid IS NOT NULL)`);
270
277
  return rows.map(hydrateRow);
271
278
  }
272
279
  findRescueJobBySession(repoId, sessionId) {
273
- const row = this.db.get(`
274
- SELECT *
275
- FROM jobs
276
- WHERE repo_id = ?
277
- AND command_type = 'rescue'
278
- AND kimi_session_id = ?
279
- ORDER BY updated_at DESC
280
- LIMIT 1
281
- `, repoId, sessionId);
282
- return row ? hydrateRow(row) : null;
280
+ return this.findJobBySession("rescue", repoId, sessionId);
283
281
  }
284
282
  findAskJobBySession(repoId, sessionId) {
283
+ return this.findJobBySession("ask", repoId, sessionId);
284
+ }
285
+ findJobBySession(commandType, repoId, sessionId) {
285
286
  const row = this.db.get(`
286
287
  SELECT *
287
288
  FROM jobs
288
289
  WHERE repo_id = ?
289
- AND command_type = 'ask'
290
+ AND command_type = ?
290
291
  AND kimi_session_id = ?
291
292
  ORDER BY updated_at DESC
292
293
  LIMIT 1
293
- `, repoId, sessionId);
294
+ `, repoId, commandType, sessionId);
294
295
  return row ? hydrateRow(row) : null;
295
296
  }
296
297
  createMcpTask(input) {
@@ -327,8 +328,25 @@ export class JobStore {
327
328
  this.db.run(`UPDATE mcp_tasks SET ${updates.join(", ")} WHERE task_id = @task_id`, params);
328
329
  return this.getMcpTask(taskId);
329
330
  }
331
+ /** Terminal states are permanent: every update is guarded by status = 'running'. */
330
332
  updateRunningJob(jobId, patch) {
331
- return this.updateWhere(jobId, patch, "status = 'running'");
333
+ const updates = ["updated_at = @updated_at"];
334
+ const params = {
335
+ job_id: jobId,
336
+ updated_at: new Date().toISOString(),
337
+ };
338
+ for (const [key, value] of Object.entries(serializePatch(patch))) {
339
+ if (value === undefined || !UPDATABLE_JOB_COLUMNS.has(key))
340
+ continue;
341
+ updates.push(`${key} = @${key}`);
342
+ params[key] = value;
343
+ }
344
+ this.db.run(`
345
+ UPDATE jobs
346
+ SET ${updates.join(", ")}
347
+ WHERE job_id = @job_id AND status = 'running'
348
+ `, params);
349
+ return this.getJob(jobId);
332
350
  }
333
351
  /** Recheck uniqueness atomically: another worker can claim an ID during the
334
352
  * asynchronous directory scan. Ordinary announced/resumed IDs may be shared. */
@@ -366,73 +384,98 @@ export class JobStore {
366
384
  return this.getJob(jobId);
367
385
  }
368
386
  markCompleted(jobId, patch) {
369
- return this.updateWhere(jobId, { ...patch, status: "completed", pid: null, kimi_pid: null }, "status = 'running'");
387
+ return this.updateRunningJob(jobId, {
388
+ ...patch,
389
+ status: "completed",
390
+ pid: null,
391
+ kimi_pid: null,
392
+ companion_identity: null,
393
+ kimi_identity: null,
394
+ });
370
395
  }
371
396
  markFailed(jobId, patch) {
372
- return this.updateWhere(jobId, { ...patch, status: "failed", pid: null, kimi_pid: null }, "status = 'running'");
397
+ return this.updateRunningJob(jobId, {
398
+ ...patch,
399
+ status: "failed",
400
+ pid: null,
401
+ kimi_pid: null,
402
+ companion_identity: null,
403
+ kimi_identity: null,
404
+ });
373
405
  }
374
406
  markCancelled(jobId, patch) {
375
- return this.updateWhere(jobId, { ...patch, status: "cancelled", pid: null, kimi_pid: null }, "status = 'running'");
376
- }
377
- static JOBS_COLUMNS = new Set([
378
- "status", "summary", "phase", "budget_ms", "budget_source", "kimi_session_id_source", "pid", "kimi_pid",
379
- "final_output_path", "stream_log_path", "kimi_session_id",
380
- "error", "command_type", "prompt_digest", "repo_id",
381
- "cwd", "model", "thinking", "thinking_effort", "hook_escapes", "background", "agent_profile",
382
- "operation_kind", "intended_engine", "observed_engine", "kimi_version",
383
- "system_version", "kimi_command", "kimi_prefix_args", "plan_certification",
384
- "resumed_from_job_id", "safety_profile",
385
- ]);
386
- updateWhere(jobId, patch, whereClause) {
387
- const updates = ["updated_at = @updated_at"];
388
- const params = {
389
- job_id: jobId,
390
- updated_at: new Date().toISOString(),
391
- };
392
- for (const [key, value] of Object.entries(serializePatch(patch))) {
393
- if (key === "job_id" || key === "created_at" || key === "updated_at" || value === undefined) {
394
- continue;
395
- }
396
- if (!JobStore.JOBS_COLUMNS.has(key))
397
- continue;
398
- updates.push(`${key} = @${key}`);
399
- params[key] = value;
400
- }
401
- const statement = `
402
- UPDATE jobs
403
- SET ${updates.join(", ")}
404
- WHERE job_id = @job_id${whereClause ? ` AND ${whereClause}` : ""}
405
- `;
406
- this.db.run(statement, params);
407
- return this.getJob(jobId);
407
+ return this.updateRunningJob(jobId, {
408
+ ...patch,
409
+ status: "cancelled",
410
+ pid: null,
411
+ kimi_pid: null,
412
+ companion_identity: null,
413
+ kimi_identity: null,
414
+ });
408
415
  }
409
416
  }
417
+ /** Columns added after the first schema, in the order older stores receive them. */
418
+ const ADDED_JOB_COLUMNS = [
419
+ ["phase", "TEXT"],
420
+ ["budget_ms", "INTEGER"],
421
+ ["kimi_session_id_source", "TEXT"],
422
+ ["budget_source", "TEXT"],
423
+ ["thinking_effort", "TEXT"],
424
+ ["hook_escapes", "TEXT"],
425
+ // Additive provenance migration. Existing rows deliberately remain NULL:
426
+ // v1.9.5 plus kimi-code 0.33/0.34 could have routed to native v2 before the
427
+ // legacy pin landed, so a blanket historical v1 backfill would invent fact.
428
+ ["operation_kind", "TEXT"],
429
+ ["intended_engine", "TEXT"],
430
+ ["observed_engine", "TEXT"],
431
+ ["kimi_version", "TEXT"],
432
+ ["system_version", "TEXT"],
433
+ ["kimi_command", "TEXT"],
434
+ ["kimi_prefix_args", "TEXT"],
435
+ ["plan_certification", "TEXT"],
436
+ ["resumed_from_job_id", "TEXT"],
437
+ ["safety_profile", "TEXT"],
438
+ ["warnings", "TEXT"],
439
+ ["read_scope", "TEXT"],
440
+ ["companion_identity", "TEXT"],
441
+ ["kimi_identity", "TEXT"],
442
+ ];
443
+ /** Columns createJob writes, in INSERT order. hook_escapes is written only by updates. */
444
+ const INSERT_JOB_COLUMNS = [
445
+ "job_id", "repo_id", "command_type", "created_at", "updated_at", "cwd", "model", "thinking", "thinking_effort",
446
+ "background", "pid", "kimi_pid", "companion_identity", "kimi_identity", "status", "kimi_session_id", "kimi_session_id_source", "budget_source",
447
+ "operation_kind", "intended_engine", "observed_engine", "kimi_version", "system_version",
448
+ "kimi_command", "kimi_prefix_args", "plan_certification", "resumed_from_job_id", "safety_profile", "warnings",
449
+ "read_scope", "agent_profile", "prompt_digest", "summary", "phase", "budget_ms", "final_output_path", "stream_log_path", "error",
450
+ ];
451
+ const INSERT_JOB_SQL = `INSERT INTO jobs (${INSERT_JOB_COLUMNS.join(", ")}) VALUES (${INSERT_JOB_COLUMNS.map((column) => `@${column}`).join(", ")})`;
452
+ /** Columns an update may set; identity and timestamps are store-owned. */
453
+ const UPDATABLE_JOB_COLUMNS = new Set([
454
+ ...INSERT_JOB_COLUMNS.filter((column) => column !== "job_id" && column !== "created_at" && column !== "updated_at"),
455
+ "hook_escapes",
456
+ ]);
410
457
  function hydrateRow(row) {
458
+ // A warning-free row keeps its historical shape, so every JSON surface that
459
+ // spreads a JobRecord stays byte-identical.
460
+ const { warnings, read_scope, companion_identity, kimi_identity, ...rest } = row;
411
461
  return {
412
- ...row,
462
+ ...rest,
463
+ ...(warnings !== null && warnings !== undefined ? { warnings } : {}),
464
+ ...(read_scope !== null && read_scope !== undefined ? { read_scope } : {}),
465
+ ...(companion_identity !== null && companion_identity !== undefined ? { companion_identity } : {}),
466
+ ...(kimi_identity !== null && kimi_identity !== undefined ? { kimi_identity } : {}),
413
467
  thinking: row.thinking === null ? null : Boolean(row.thinking),
414
468
  background: Boolean(row.background),
415
469
  error: row.error ? JSON.parse(row.error) : null,
416
470
  };
417
471
  }
472
+ // Spreads the whole input so node:sqlite still rejects keys that are not INSERT parameters.
418
473
  function serializeRecord(record) {
474
+ const row = { ...record };
475
+ for (const column of INSERT_JOB_COLUMNS)
476
+ row[column] ??= null;
419
477
  return {
420
- ...record,
421
- thinking_effort: record.thinking_effort ?? null,
422
- phase: record.phase ?? null,
423
- budget_ms: record.budget_ms ?? null,
424
- budget_source: record.budget_source ?? null,
425
- kimi_session_id_source: record.kimi_session_id_source ?? null,
426
- operation_kind: record.operation_kind ?? null,
427
- intended_engine: record.intended_engine ?? null,
428
- observed_engine: record.observed_engine ?? null,
429
- kimi_version: record.kimi_version ?? null,
430
- system_version: record.system_version ?? null,
431
- kimi_command: record.kimi_command ?? null,
432
- kimi_prefix_args: record.kimi_prefix_args ?? null,
433
- plan_certification: record.plan_certification ?? null,
434
- resumed_from_job_id: record.resumed_from_job_id ?? null,
435
- safety_profile: record.safety_profile ?? null,
478
+ ...row,
436
479
  thinking: record.thinking === null ? null : Number(record.thinking),
437
480
  background: Number(record.background),
438
481
  error: record.error ? JSON.stringify(record.error) : null,
@@ -589,12 +632,8 @@ function rewriteNamedParamsForBun(statement) {
589
632
  function rewriteNamedBindingsForBun(bindings) {
590
633
  return Object.fromEntries(Object.entries(bindings).map(([key, value]) => [`$${key}`, value]));
591
634
  }
592
- function tableHasColumn(db, columnName) {
593
- const columns = db.all(`PRAGMA table_info(jobs)`);
594
- return columns.some((column) => column.name === columnName);
595
- }
596
- function mcpTableHasColumn(db, columnName) {
597
- return db.all("PRAGMA table_info(mcp_tasks)").some((column) => column.name === columnName);
635
+ function existingColumns(db, table) {
636
+ return new Set(db.all(`PRAGMA table_info(${table})`).map((column) => column.name));
598
637
  }
599
638
  function isSqliteConstraintError(error) {
600
639
  const message = formatError(error).toLowerCase();
@@ -602,7 +641,7 @@ function isSqliteConstraintError(error) {
602
641
  }
603
642
  function isSqliteBusyError(error) {
604
643
  const message = formatError(error).toLowerCase();
605
- return message.includes("database is locked") || message.includes("busy");
644
+ return message.includes("database is locked") || message.includes("busy") || message.includes("locking protocol");
606
645
  }
607
646
  function translateSqliteError(error) {
608
647
  if (isSqliteBusyError(error)) {
@@ -630,24 +669,25 @@ export async function withJobStore(paths, fn) {
630
669
  store?.close();
631
670
  }
632
671
  }
633
- /** Synchronous companion to `withJobStore` for callers that don't await inside. */
634
- export function withJobStoreSync(paths, fn) {
635
- let store;
672
+ /** Parsed `hook_escapes` column for JSON envelopes: [] when NULL or unreadable. */
673
+ export function parseHookEscapes(raw) {
674
+ if (!raw)
675
+ return [];
636
676
  try {
637
- store = new JobStore(paths);
638
- return fn(store);
677
+ const parsed = JSON.parse(raw);
678
+ return Array.isArray(parsed) ? parsed : [];
639
679
  }
640
- finally {
641
- store?.close();
680
+ catch {
681
+ return [];
642
682
  }
643
683
  }
644
- /** Parsed `hook_escapes` column for JSON envelopes: [] when NULL or unreadable. */
645
- export function parseHookEscapes(raw) {
684
+ /** Parsed `warnings` column: [] when NULL or unreadable. */
685
+ export function parseJobWarnings(raw) {
646
686
  if (!raw)
647
687
  return [];
648
688
  try {
649
689
  const parsed = JSON.parse(raw);
650
- return Array.isArray(parsed) ? parsed : [];
690
+ return Array.isArray(parsed) ? parsed.filter((entry) => typeof entry === "string") : [];
651
691
  }
652
692
  catch {
653
693
  return [];
@@ -1,8 +1,50 @@
1
- import { createHash } from "node:crypto";
1
+ import { realpath } from "node:fs/promises";
2
+ import path from "node:path";
2
3
  import { RuntimeError } from "./errors.js";
3
- import { formatBudgetDuration, renderTerminalJobArtifact, writeArtifact } from "./render.js";
4
- export function digestPrompt(prompt) {
5
- return createHash("sha256").update(prompt).digest("hex");
4
+ import { readProcessIdentity } from "./process-tree.js";
5
+ import { capitalize, formatBudgetDuration, renderTerminalJobArtifact, writeArtifact } from "./render.js";
6
+ import { sleep } from "./util.js";
7
+ export { sha256 as digestPrompt } from "./git.js";
8
+ export async function serializedProcessIdentity(pid) {
9
+ const identity = await readProcessIdentity(pid);
10
+ return identity ? JSON.stringify(identity) : null;
11
+ }
12
+ export async function recordKimiSpawnIdentity(store, jobId, pid) {
13
+ store.updateRunningJob(jobId, { kimi_pid: pid });
14
+ const identity = await serializedProcessIdentity(pid);
15
+ if (identity) {
16
+ store.updateRunningJob(jobId, { kimi_identity: identity });
17
+ }
18
+ }
19
+ export async function canonicalizeMaybeDeletedPath(target) {
20
+ if (!path.isAbsolute(target))
21
+ return null;
22
+ let current = path.resolve(target);
23
+ const tail = [];
24
+ for (;;) {
25
+ try {
26
+ const resolved = await realpath(current);
27
+ return tail.length === 0 ? resolved : path.join(resolved, ...tail.reverse());
28
+ }
29
+ catch (error) {
30
+ const code = error.code;
31
+ if (code !== "ENOENT" && code !== "ENOTDIR")
32
+ return null;
33
+ const parent = path.dirname(current);
34
+ if (parent === current)
35
+ return null;
36
+ tail.push(path.basename(current));
37
+ current = parent;
38
+ }
39
+ }
40
+ }
41
+ export function isPathWithinCanonicalRoot(canonicalRoot, canonicalCandidate) {
42
+ const relative = path.relative(canonicalRoot, canonicalCandidate);
43
+ return relative === "" || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
44
+ }
45
+ export async function isCwdWithinWorkspace(candidateCwd, canonicalWorkspaceCwd) {
46
+ const resolved = await canonicalizeMaybeDeletedPath(candidateCwd);
47
+ return resolved !== null && isPathWithinCanonicalRoot(canonicalWorkspaceCwd, resolved);
6
48
  }
7
49
  export function normalizeJobError(error) {
8
50
  if (error instanceof RuntimeError) {
@@ -34,13 +76,12 @@ export async function markJobFailed(store, paths, job, error, summary = "Job fai
34
76
  if (current.status !== "running")
35
77
  return current;
36
78
  if (options?.partialOutput) {
37
- const label = job.command_type[0].toUpperCase() + job.command_type.slice(1);
38
- summary = `${label} timed out after ${formatBudgetDuration(options.partialOutput.budgetMs)}; partial output captured (${options.partialOutput.text.trim().length} chars).`;
79
+ summary = `${capitalize(job.command_type)} timed out after ${formatBudgetDuration(options.partialOutput.budgetMs)}; partial output captured (${options.partialOutput.text.trim().length} chars).`;
39
80
  }
40
81
  const normalized = normalizeJobError(error);
41
82
  const phase = options?.phase;
42
83
  const artifactJob = {
43
- ...(store.getJob(job.job_id) ?? job),
84
+ ...current,
44
85
  status: "failed",
45
86
  summary,
46
87
  error: normalized,
@@ -81,8 +122,16 @@ export async function markJobCancelled(store, paths, job, summary, error, option
81
122
  ...(phase !== undefined ? { phase } : {}),
82
123
  }) ?? artifactJob);
83
124
  }
84
- export async function sweepStaleJobs(store, paths) {
125
+ export async function sweepStaleJobs(store, paths, scope) {
126
+ const canonicalScopeCwd = scope?.workspaceCwd
127
+ ? await canonicalizeMaybeDeletedPath(scope.workspaceCwd)
128
+ : null;
85
129
  for (const job of store.listRunningJobsWithProcessHints()) {
130
+ if (scope?.repoId !== undefined && job.repo_id !== scope.repoId)
131
+ continue;
132
+ if (canonicalScopeCwd !== null && !(await isCwdWithinWorkspace(job.cwd, canonicalScopeCwd))) {
133
+ continue;
134
+ }
86
135
  if (store.getMcpTask(job.job_id))
87
136
  continue;
88
137
  // Recovery owns orphaned swarm resources; PID-only sweeping must not signal replacements.
@@ -102,7 +151,7 @@ export async function sweepStaleJobs(store, paths) {
102
151
  ? `Background worker pid ${job.pid} is no longer running.`
103
152
  : `Kimi pid ${job.kimi_pid} is no longer running while background worker pid ${job.pid} is still recorded.`, "jobs.sweep"), companionMissing
104
153
  ? "Background worker disappeared before reporting a terminal state."
105
- : "Kimi process disappeared before reporting a terminal state.", job.command_type === "ask" || job.command_type === "rescue" ? { phase: "failed" } : undefined);
154
+ : "Kimi process disappeared before reporting a terminal state.", lineagePhase(job, "failed"));
106
155
  continue;
107
156
  }
108
157
  if (!companionMissing && !kimiMissing) {
@@ -117,10 +166,14 @@ export async function sweepStaleJobs(store, paths) {
117
166
  continue;
118
167
  }
119
168
  terminateRecordedProcesses(job);
120
- await markJobFailed(store, paths, job, new RuntimeError("FOREGROUND_PROCESS_DISAPPEARED", describeMissingForegroundProcess(job, companionMissing, kimiMissing), "jobs.sweep"), "Foreground Kimi job disappeared before reporting a terminal state.", job.command_type === "ask" || job.command_type === "rescue" ? { phase: "failed" } : undefined);
169
+ await markJobFailed(store, paths, job, new RuntimeError("FOREGROUND_PROCESS_DISAPPEARED", describeMissingForegroundProcess(job, companionMissing, kimiMissing), "jobs.sweep"), "Foreground Kimi job disappeared before reporting a terminal state.", lineagePhase(job, "failed"));
121
170
  }
122
171
  }
123
172
  export const STALE_SWEEP_GRACE_MS = 15_000;
173
+ /** Ask and rescue rows track a phase; the other lineages leave it untouched. */
174
+ export function lineagePhase(job, phase) {
175
+ return job.command_type === "ask" || job.command_type === "rescue" ? { phase } : undefined;
176
+ }
124
177
  function isStaleEnoughToSweep(job) {
125
178
  const updatedAt = Date.parse(job.updated_at);
126
179
  return Number.isFinite(updatedAt) && Date.now() - updatedAt >= STALE_SWEEP_GRACE_MS;
@@ -158,7 +211,7 @@ function terminateRecordedProcesses(job) {
158
211
  timer.unref();
159
212
  }
160
213
  }
161
- function killPid(pid, signal) {
214
+ export function killPid(pid, signal) {
162
215
  try {
163
216
  process.kill(pid, signal);
164
217
  }
@@ -171,7 +224,7 @@ function killPid(pid, signal) {
171
224
  }
172
225
  }
173
226
  }
174
- function isPidAlive(pid) {
227
+ export function isPidAlive(pid) {
175
228
  try {
176
229
  process.kill(pid, 0);
177
230
  return true;
@@ -185,8 +238,7 @@ function isPidAlive(pid) {
185
238
  // pid in v0.2.2+; under normal usage we should always have permission
186
239
  // to signal our own descendants. Returning true here lets stale jobs
187
240
  // hide forever (the sweeper relies on isPidAlive=false to flip them to
188
- // failed). signalJobProcesses and killPid already swallow EPERM
189
- // consistently — this brings the read path in line with the write path.
241
+ // failed). killPid swallows EPERM the same way.
190
242
  if (code === "ESRCH" || code === "EPERM") {
191
243
  return false;
192
244
  }
@@ -210,8 +262,3 @@ export async function waitForTerminalJob(storeFactory, jobId, timeoutMs = 60_000
210
262
  }
211
263
  throw new RuntimeError("JOB_WAIT_TIMEOUT", `Timed out after ${timeoutMs}ms while waiting for job ${jobId} to finish. The worker may still be running; use /kimi:status ${jobId} to check progress or /kimi:result ${jobId} once it completes.`, "jobs.wait");
212
264
  }
213
- function sleep(ms) {
214
- return new Promise((resolve) => {
215
- setTimeout(resolve, ms);
216
- });
217
- }