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,6 +1,8 @@
1
- import { access, lstat, realpath } from "node:fs/promises";
1
+ import { realpathSync } from "node:fs";
2
+ import { access, lstat, readdir, realpath } from "node:fs/promises";
2
3
  import path from "node:path";
3
4
  import { parse } from "./vendor/shell-quote/index.js";
5
+ import { READ_ONLY_TOOLS } from "./hooks/approval-policy.js";
4
6
  // Tool-owned output flags write without shell redirection and therefore bypass
5
7
  // path checks unless treated as mutating. The `-o` short form is not banned
6
8
  // globally because tools such as rg and grep use it for read-only behavior;
@@ -18,16 +20,9 @@ const MUTATING_FLAGS_EXACT = new Set([
18
20
  "--output-directory",
19
21
  "--output-dir",
20
22
  ]);
21
- const MUTATING_FLAG_PREFIXES = [
22
- "--fix=",
23
- "--write=",
24
- "--apply=",
25
- "--in-place=",
26
- "--output=",
27
- "--output-file=",
28
- "--output-directory=",
29
- "--output-dir=",
30
- ];
23
+ const MUTATING_FLAG_PREFIXES = [...MUTATING_FLAGS_EXACT]
24
+ .filter((flag) => flag.startsWith("--"))
25
+ .map((flag) => `${flag}=`);
31
26
  // Flags whose VALUE is executed as a command or external tool are rejected for
32
27
  // every tool: Git pager overrides and Go -vettool/-exec/-toolexec are direct
33
28
  // command-execution escapes. Git's -O short form is handled in its own branch
@@ -46,16 +41,10 @@ const EXEC_DELEGATING_FLAGS_EXACT = new Set([
46
41
  "--hostname-bin",
47
42
  "--compress-program",
48
43
  ]);
49
- const EXEC_DELEGATING_FLAG_PREFIXES = [
50
- "--open-files-in-pager=",
51
- "-vettool=",
52
- "--vettool=",
53
- "-toolexec=",
54
- "--toolexec=",
55
- "--pre=",
56
- "--hostname-bin=",
57
- "--compress-program=",
58
- ];
44
+ // -exec and -execdir are matched exactly only; they get no `=` prefix form.
45
+ const EXEC_DELEGATING_FLAG_PREFIXES = [...EXEC_DELEGATING_FLAGS_EXACT]
46
+ .filter((flag) => flag !== "-exec" && flag !== "-execdir")
47
+ .map((flag) => `${flag}=`);
59
48
  // Pytest report flags write to arbitrary paths. Test runners execute repo code
60
49
  // by design, so these checks block known runner-owned report outputs rather
61
50
  // than every possible write. Match argparse allow_abbrev prefixes as well.
@@ -141,11 +130,12 @@ const MYPY_WRITE_FLAGS_ABBREV = [
141
130
  * Handles both `--flag value` (arg === "--flag") and `--flag=value`.
142
131
  */
143
132
  function hasFlagFromSet(args, flags) {
144
- return args.some((arg) => {
145
- const eq = arg.indexOf("=");
146
- const name = eq === -1 ? arg : arg.slice(0, eq);
147
- return flags.has(name);
148
- });
133
+ return args.some((arg) => flags.has(flagName(arg)));
134
+ }
135
+ /** The part of `arg` before its first `=`, or all of it. */
136
+ function flagName(arg) {
137
+ const eq = arg.indexOf("=");
138
+ return eq === -1 ? arg : arg.slice(0, eq);
149
139
  }
150
140
  /**
151
141
  * True if `arg` matches any flag in `flags` accounting for argparse-style prefix
@@ -159,25 +149,12 @@ function hasFlagFromSet(args, flags) {
159
149
  */
160
150
  function matchesAbbreviatedFlag(args, flags) {
161
151
  return args.some((arg) => {
162
- const eq = arg.indexOf("=");
163
- const name = eq === -1 ? arg : arg.slice(0, eq);
152
+ const name = flagName(arg);
164
153
  if (name.length < 3)
165
154
  return false;
166
155
  return flags.some((flag) => flag.startsWith(name) || name.startsWith(flag));
167
156
  });
168
157
  }
169
- /**
170
- * Direct-read bypass for rescue. Keep this set identical to READ_ONLY_TOOLS in
171
- * approval-policy.ts; the deliberate duplication must be updated in both places.
172
- */
173
- const RESCUE_READ_ONLY_TOOLS = new Set([
174
- "Read",
175
- "Grep",
176
- "Glob",
177
- "ReadMediaFile",
178
- "TaskList",
179
- "TaskOutput",
180
- ]);
181
158
  /**
182
159
  * Evaluate a PreToolUse hook request under the rescue policy.
183
160
  *
@@ -186,9 +163,15 @@ const RESCUE_READ_ONLY_TOOLS = new Set([
186
163
  * environment value. `toolName` and `toolInput` are the raw upstream tool call.
187
164
  */
188
165
  export async function evaluateRescueHookRequest(workspaceRoot, toolName, toolInput) {
189
- if (RESCUE_READ_ONLY_TOOLS.has(toolName)) {
166
+ if (READ_ONLY_TOOLS.has(toolName)) {
190
167
  return { decision: "allow" };
191
168
  }
169
+ // The spelling is judged before and after resolution: the given root is
170
+ // refused even where realpath cannot resolve a backslash path.
171
+ const posix = process.platform !== "win32";
172
+ if (posix && workspaceRoot.includes("\\")) {
173
+ return { decision: "deny", reason: backslashRootReason(workspaceRoot, toolName) };
174
+ }
192
175
  let root;
193
176
  try {
194
177
  root = await realpath(workspaceRoot);
@@ -199,6 +182,9 @@ export async function evaluateRescueHookRequest(workspaceRoot, toolName, toolInp
199
182
  reason: `rescue cannot resolve workspace root: ${err.message}`,
200
183
  };
201
184
  }
185
+ if (posix && root.includes("\\")) {
186
+ return { decision: "deny", reason: backslashRootReason(root, toolName) };
187
+ }
202
188
  if (toolName === "Bash") {
203
189
  const command = extractBashCommand(toolInput);
204
190
  if (command === null) {
@@ -212,6 +198,8 @@ export async function evaluateRescueHookRequest(workspaceRoot, toolName, toolInp
212
198
  if (typeof cwd !== "string" || cwd.length === 0) {
213
199
  return { decision: "deny", reason: "rescue requires Bash cwd to be a non-empty string" };
214
200
  }
201
+ if (hasAmbiguousPathSpelling(cwd))
202
+ return ambiguousPathDenial(cwd, root);
215
203
  try {
216
204
  const outcome = await checkApprovedDirectory(root, cwd);
217
205
  if (outcome === "symlink") {
@@ -228,12 +216,18 @@ export async function evaluateRescueHookRequest(workspaceRoot, toolName, toolInp
228
216
  return { decision: "deny", reason: `rescue cannot inspect Bash cwd ${cwd}: ${err.message}` };
229
217
  }
230
218
  }
231
- const result = validateShellCommand(command);
219
+ const result = await validateWorkspaceShellCommand(command, root);
232
220
  return result.response === "approve"
233
221
  ? { decision: "allow" }
234
222
  : { decision: "deny", reason: result.feedback ?? "rescue rejected the shell command" };
235
223
  }
236
- if (toolName === "Write" || toolName === "Edit") {
224
+ if (toolName === "Write" || toolName === "Edit" || toolName === "MultiEdit") {
225
+ for (const key of ["path", "file_path"]) {
226
+ const candidate = isObject(toolInput) ? toolInput[key] : undefined;
227
+ if (typeof candidate === "string" && hasAmbiguousPathSpelling(candidate)) {
228
+ return ambiguousPathDenial(candidate, root);
229
+ }
230
+ }
237
231
  const filePath = extractFilePath(toolInput);
238
232
  if (filePath === null) {
239
233
  return {
@@ -241,26 +235,75 @@ export async function evaluateRescueHookRequest(workspaceRoot, toolName, toolInp
241
235
  reason: `rescue cannot evaluate ${toolName} input with no path field`,
242
236
  };
243
237
  }
244
- return pathDecision(await checkApprovedPath(root, filePath), filePath);
245
- }
246
- if (toolName === "MultiEdit") {
247
- const filePath = extractFilePath(toolInput);
248
- if (filePath === null) {
238
+ try {
239
+ return pathDecision(await checkApprovedPath(root, filePath), filePath);
240
+ }
241
+ catch (err) {
249
242
  return {
250
243
  decision: "deny",
251
- reason: "rescue cannot evaluate MultiEdit input with no path field",
244
+ reason: `rescue cannot inspect ${filePath} (outside the workspace, inside .git or unreadable): ${err.message}`,
252
245
  };
253
246
  }
254
- return pathDecision(await checkApprovedPath(root, filePath), filePath);
255
247
  }
256
248
  return {
257
249
  decision: "deny",
258
250
  reason: `rescue does not allow tool "${toolName}" — only Bash, Write, Edit, MultiEdit (with allowlist checks) and read-only tools are permitted.`,
259
251
  };
260
252
  }
253
+ /**
254
+ * The first of `paths` (or its realpath) that holds a literal backslash on a
255
+ * POSIX host. kimi-code resolves its work dir with `pathe`, which reads `\` as
256
+ * a separator, so even a relative file name would land elsewhere.
257
+ */
258
+ export function backslashWorkspacePath(paths) {
259
+ if (process.platform === "win32")
260
+ return undefined;
261
+ for (const candidate of paths) {
262
+ if (candidate === undefined)
263
+ continue;
264
+ if (candidate.includes("\\"))
265
+ return candidate;
266
+ try {
267
+ const real = realpathSync.native(candidate);
268
+ if (real.includes("\\"))
269
+ return real;
270
+ }
271
+ catch {
272
+ // A missing directory fails later at spawn; only spelling is judged here.
273
+ }
274
+ }
275
+ return undefined;
276
+ }
277
+ export function backslashRootReason(root, toolName) {
278
+ return (`kimi-plugin-cc safety hook: writes cannot be confined to ${root}: it contains a backslash, ` +
279
+ `which kimi-code reads as a path separator; tool "${toolName}" denied.`);
280
+ }
281
+ /**
282
+ * kimi-code resolves tool paths with `pathe` after home expansion: `~/x` is
283
+ * `<home>/x`, backslashes become `/`, and `\x`, `\\host\share` and `C:/x`
284
+ * count as absolute. Node's `path` reads all of these as relative names inside
285
+ * the workspace, so the two resolvers can disagree about which file is
286
+ * written. Refuse every such spelling instead of reimplementing `pathe`.
287
+ */
288
+ function hasAmbiguousPathSpelling(candidate) {
289
+ return (candidate.includes("\\") ||
290
+ candidate.includes("\0") ||
291
+ candidate.startsWith("~") ||
292
+ /^[A-Za-z]:/.test(candidate) ||
293
+ /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(candidate));
294
+ }
295
+ function ambiguousPathDenial(candidate, root) {
296
+ return {
297
+ decision: "deny",
298
+ reason: `rescue rejects the path ${JSON.stringify(candidate)}: a backslash, leading ~, drive letter, NUL or URL ` +
299
+ `scheme can resolve differently in kimi-code; use a plain POSIX path under ${root}`,
300
+ };
301
+ }
261
302
  function pathDecision(outcome, filePath) {
262
303
  if (outcome === "allow")
263
304
  return { decision: "allow" };
305
+ if (outcome === "hardlink")
306
+ return { decision: "deny", reason: `${HARD_LINK_REASON}: ${filePath}` };
264
307
  if (outcome === "symlink") {
265
308
  return {
266
309
  decision: "deny",
@@ -305,15 +348,30 @@ export async function checkApprovedPath(workspaceRoot, rawTargetPath) {
305
348
  if (targetStats?.isSymbolicLink()) {
306
349
  return "symlink";
307
350
  }
308
- const nearestExistingAncestor = await findNearestExistingAncestor(path.dirname(absoluteTarget));
309
- const ancestorRealPath = await realpath(nearestExistingAncestor);
310
- const candidatePath = path.resolve(ancestorRealPath, path.relative(nearestExistingAncestor, absoluteTarget));
311
- const relativeToRoot = path.relative(workspaceRoot, candidatePath);
312
- return (isWithin(workspaceRoot, candidatePath) &&
313
- !relativeToRoot.split(path.sep).includes(".git"))
314
- ? "allow"
315
- : "reject";
351
+ // An existing leaf is canonicalised too, so a case or short-name alias of
352
+ // `.git` is compared under its on-disk name.
353
+ let candidatePath;
354
+ if (targetStats !== null) {
355
+ candidatePath = await realpath(absoluteTarget);
356
+ }
357
+ else {
358
+ const nearestExistingAncestor = await findNearestExistingAncestor(path.dirname(absoluteTarget));
359
+ const ancestorRealPath = await realpath(nearestExistingAncestor);
360
+ candidatePath = path.resolve(ancestorRealPath, path.relative(nearestExistingAncestor, absoluteTarget));
361
+ }
362
+ if (!isWithinWorkspaceOutsideAnyGit(workspaceRoot, candidatePath))
363
+ return "reject";
364
+ return isHardLinkedFile(targetStats) ? "hardlink" : "allow";
365
+ }
366
+ /**
367
+ * A regular file with more than one link may share its inode with a file
368
+ * outside the workspace (hard-linked package caches), and writing it in place
369
+ * changes that file too. Replacing the directory entry (mv, rm) does not.
370
+ */
371
+ function isHardLinkedFile(stats) {
372
+ return stats !== null && stats.isFile() && stats.nlink > 1;
316
373
  }
374
+ const HARD_LINK_REASON = "rescue does not write through hard links";
317
375
  async function checkApprovedDirectory(workspaceRoot, rawCwd) {
318
376
  const candidate = path.resolve(workspaceRoot, rawCwd);
319
377
  const stats = await statIfExists(candidate);
@@ -322,10 +380,7 @@ async function checkApprovedDirectory(workspaceRoot, rawCwd) {
322
380
  if (!stats?.isDirectory())
323
381
  return "missing";
324
382
  const resolved = await realpath(candidate);
325
- return isWithin(workspaceRoot, resolved) &&
326
- !path.relative(workspaceRoot, resolved).split(path.sep).includes(".git")
327
- ? "allow"
328
- : "reject";
383
+ return isWithinWorkspaceOutsideAnyGit(workspaceRoot, resolved) ? "allow" : "reject";
329
384
  }
330
385
  async function statIfExists(targetPath) {
331
386
  try {
@@ -354,7 +409,59 @@ async function findNearestExistingAncestor(targetDirectory) {
354
409
  }
355
410
  }
356
411
  }
412
+ /**
413
+ * Path-free shell policy. File operations (rm/mv/cp/mkdir) need the trusted
414
+ * root and the validated working directory, so this entry point rejects them;
415
+ * the hook uses `validateWorkspaceShellCommand`.
416
+ */
357
417
  export function validateShellCommand(command) {
418
+ const parsed = parseShellPipeline(command);
419
+ if ("response" in parsed)
420
+ return parsed;
421
+ for (let index = 0; index < parsed.stages.length; index += 1) {
422
+ const allowed = validateShellStage(parsed.stages[index], parsed.stages.length > 1);
423
+ if (!allowed.ok) {
424
+ return rejectShell(allowed.reason);
425
+ }
426
+ }
427
+ return { response: "approve" };
428
+ }
429
+ /**
430
+ * Shell policy with workspace context. `workspaceRoot` must be a realpath.
431
+ * Every rm/mv/cp/mkdir operand passes the write containment rules before the
432
+ * command is approved.
433
+ */
434
+ export async function validateWorkspaceShellCommand(command, workspaceRoot) {
435
+ const parsed = parseShellPipeline(command);
436
+ if ("response" in parsed)
437
+ return parsed;
438
+ // Pipeline stages run concurrently after every check has passed, so one
439
+ // file operation could change what another's already-checked path names.
440
+ if (parsed.stages.filter((stage) => FILE_OPERATION_FLAGS.has(stage[0])).length > 1) {
441
+ return rejectShell(`Rescue allows only one rm, mv, cp or mkdir per command: ${command}`);
442
+ }
443
+ for (let index = 0; index < parsed.stages.length; index += 1) {
444
+ const stage = parsed.stages[index];
445
+ const allowed = FILE_OPERATION_FLAGS.has(stage[0])
446
+ ? await validateFileOperationStage(stage, workspaceRoot)
447
+ : validateShellStage(stage, parsed.stages.length > 1);
448
+ if (!allowed.ok) {
449
+ return rejectShell(allowed.reason);
450
+ }
451
+ }
452
+ return { response: "approve" };
453
+ }
454
+ /**
455
+ * Longest Bash command the policy evaluates. The hook's deny timer shares the
456
+ * evaluation thread and kimi-code treats a hook timeout as allow, so input size
457
+ * must bound evaluation time: brace-expansion detection is quadratic, and
458
+ * measured worst cases are about 0.2 s at this length and 3 s at 64 KiB.
459
+ */
460
+ export const MAX_SHELL_COMMAND_LENGTH = 16_384;
461
+ function parseShellPipeline(command) {
462
+ if (command.length > MAX_SHELL_COMMAND_LENGTH) {
463
+ return rejectShell(`Rescue rejects shell commands longer than ${MAX_SHELL_COMMAND_LENGTH} characters (this one has ${command.length}); split the work into shorter commands.`);
464
+ }
358
465
  // shell-quote collapses raw newline/carriage-return separators into adjacent tokens, which
359
466
  // hides a second command from per-stage validation (`git status\nrm -rf /` parses as
360
467
  // ['git','status','rm','-rf','/']). Reject any line-break characters up front so every
@@ -381,21 +488,229 @@ export function validateShellCommand(command) {
381
488
  if (stages.some((stage) => stage.length === 0)) {
382
489
  return rejectShell(`Rescue rejects malformed shell pipelines: ${command}`);
383
490
  }
384
- for (let index = 0; index < stages.length; index += 1) {
385
- const stage = stages[index];
386
- const allowed = validateShellStage(stage, index > 0 || stages.length > 1);
387
- if (!allowed.ok) {
388
- return rejectShell(allowed.reason);
491
+ return { stages };
492
+ }
493
+ // Exact flag tokens only: bundles other than rm's -rf/-fr are refused.
494
+ const FILE_OPERATION_FLAGS = new Map([
495
+ ["rm", new Set(["-f", "-r", "-R", "-rf", "-fr"])],
496
+ ["mkdir", new Set(["-p"])],
497
+ ["mv", new Set(["-f", "-n"])],
498
+ ["cp", new Set(["-R", "-r", "-p", "-f", "-n"])],
499
+ ]);
500
+ // Positive operand alphabet. Everything a POSIX shell could expand (globs,
501
+ // brackets, braces, tilde, `$`, `=`) is outside it, and the parser has already
502
+ // removed quoting, so a token cannot tell whether bash would expand it.
503
+ const FILE_OPERAND = /^[\p{L}\p{N}._+@%,:/ -]+$/u;
504
+ /**
505
+ * rm/mv/cp/mkdir inside the trusted root. Operands must be absolute, so the
506
+ * check never depends on the shell's working directory, and get the write
507
+ * containment (inside the root after symlink resolution, never `.git` in any
508
+ * letter case, never a symlink as the final component); `..` segments are
509
+ * refused because the kernel resolves them physically where `path.resolve`
510
+ * would not.
511
+ */
512
+ async function validateFileOperationStage(tokens, workspaceRoot) {
513
+ const [command, ...args] = tokens;
514
+ const allowedFlags = FILE_OPERATION_FLAGS.get(command);
515
+ const shown = tokens.join(" ");
516
+ // Windows runs Git Bash behind a path bridge whose mapping (`/c/...`, `/`
517
+ // as the Git install root, `:` stream names) Node's win32 resolution does
518
+ // not reproduce, so containment cannot be proven there.
519
+ if (process.platform === "win32") {
520
+ return { ok: false, reason: `Rescue does not allow ${command} on Windows: ${shown}` };
521
+ }
522
+ const flags = new Set();
523
+ const operands = [];
524
+ let endOfFlags = false;
525
+ for (const arg of args) {
526
+ if (!endOfFlags && arg === "--") {
527
+ endOfFlags = true;
528
+ continue;
529
+ }
530
+ if (!endOfFlags && arg.startsWith("-")) {
531
+ if (!allowedFlags.has(arg)) {
532
+ return {
533
+ ok: false,
534
+ reason: `Rescue allows ${command} only with ${[...allowedFlags].join(", ")} and --: ${shown}`,
535
+ };
536
+ }
537
+ flags.add(arg);
538
+ continue;
389
539
  }
540
+ // BSD getopt stops at the first operand (`rm /x -f` also removes a file
541
+ // named `-f`), so every later token, `--` included, is an operand.
542
+ endOfFlags = true;
543
+ if (!FILE_OPERAND.test(arg)) {
544
+ return {
545
+ ok: false,
546
+ reason: `Rescue rejects ${command} operands with glob, expansion or other special characters: ${shown}`,
547
+ };
548
+ }
549
+ if (!path.isAbsolute(arg)) {
550
+ return {
551
+ ok: false,
552
+ reason: `Rescue requires absolute paths for ${command}; use paths under ${workspaceRoot}: ${shown}`,
553
+ };
554
+ }
555
+ if (arg.split("/").includes("..")) {
556
+ return { ok: false, reason: `Rescue rejects ${command} operands containing "..": ${shown}` };
557
+ }
558
+ operands.push(arg);
390
559
  }
391
- return { response: "approve" };
560
+ const minimum = command === "mv" || command === "cp" ? 2 : 1;
561
+ if (operands.length < minimum) {
562
+ return { ok: false, reason: `Rescue requires ${command} to name at least ${minimum} path operand(s): ${shown}` };
563
+ }
564
+ try {
565
+ const resolved = [];
566
+ for (const operand of operands) {
567
+ const outcome = await resolveFileOperand(workspaceRoot, operand);
568
+ if (outcome === "symlink") {
569
+ return { ok: false, reason: `Rescue rejects ${command} on a symlink operand: ${operand}` };
570
+ }
571
+ if (outcome === "reject") {
572
+ return {
573
+ ok: false,
574
+ reason: `Rescue rejects ${command} operands outside the workspace or inside .git: ${operand}`,
575
+ };
576
+ }
577
+ resolved.push(outcome);
578
+ }
579
+ const sources = command === "mv" || command === "cp" ? resolved.slice(0, -1) : resolved;
580
+ if (command !== "mkdir" && sources.some((operand) => operand.path === workspaceRoot)) {
581
+ return { ok: false, reason: `Rescue rejects ${command} on the workspace root itself: ${shown}` };
582
+ }
583
+ if (command === "mv" || command === "cp") {
584
+ // Every operand is checked before mv/cp runs, so an operand must not
585
+ // depend on what an earlier source does: a missing source could be
586
+ // created by an earlier move (and resolve through a symlink it carries),
587
+ // and a source inside another source's destination changes underfoot.
588
+ // rm only removes and mkdir only creates plain directories, so neither
589
+ // can make a later operand name a different file.
590
+ const missing = sources.find((source) => source.stats === null);
591
+ if (missing !== undefined) {
592
+ return { ok: false, reason: `Rescue requires every ${command} source to exist: ${missing.path}` };
593
+ }
594
+ const destination = resolved.at(-1);
595
+ const landing = sources.map((source) => destination.stats?.isDirectory() ? path.join(destination.path, path.basename(source.path)) : destination.path);
596
+ for (const [index, source] of sources.entries()) {
597
+ if (landing.some((target, other) => other !== index && isWithin(target, source.path))) {
598
+ return { ok: false, reason: `Rescue rejects ${command} where a source lies under another source's destination: ${shown}` };
599
+ }
600
+ // Landing on itself is a no-op mv/cp refuses; strictly inside is not.
601
+ const inside = (target) => target !== source.path && isWithin(source.path, target);
602
+ if (inside(destination.path) || inside(landing[index])) {
603
+ return { ok: false, reason: `Rescue rejects ${command} whose destination lies under one of its sources: ${shown}` };
604
+ }
605
+ }
606
+ }
607
+ const recursive = flags.has("-r") || flags.has("-R") || flags.has("-rf") || flags.has("-fr");
608
+ // rm -r deletes, mv relocates and cp -R duplicates whole trees, so a nested
609
+ // repository would be affected without `.git` ever being named.
610
+ const treeOperation = command === "rm" && recursive ? { label: "rm -r", remedy: "delete" }
611
+ : command === "mv" ? { label: "mv", remedy: "move" }
612
+ : command === "cp" && recursive ? { label: "cp -R", remedy: "copy" }
613
+ : null;
614
+ if (treeOperation !== null) {
615
+ const scan = await scanTreesForGit(sources.filter((operand) => operand.stats?.isDirectory()).map((operand) => operand.path));
616
+ if (scan === "git") {
617
+ return {
618
+ ok: false,
619
+ reason: `Rescue rejects ${treeOperation.label} of a tree that holds a .git entry at any depth: ${shown}`,
620
+ };
621
+ }
622
+ if (scan !== "clean") {
623
+ return {
624
+ ok: false,
625
+ reason: `Rescue could not prove ${treeOperation.label} leaves every .git intact (${scan}); ` +
626
+ `${treeOperation.remedy} in smaller pieces: ${shown}`,
627
+ };
628
+ }
629
+ }
630
+ if (command === "mv" || command === "cp") {
631
+ const destination = resolved.at(-1);
632
+ // Recursive cp into an existing tree merges into it and writes through
633
+ // any symlink already there, so a directory copy must create its target.
634
+ if (command === "cp" &&
635
+ recursive &&
636
+ destination.stats !== null &&
637
+ sources.some((source) => source.stats?.isDirectory())) {
638
+ return {
639
+ ok: false,
640
+ reason: `Rescue allows cp -R of a directory only to a destination that does not exist yet: ${shown}`,
641
+ };
642
+ }
643
+ if (command === "cp" && isHardLinkedFile(destination.stats)) {
644
+ return { ok: false, reason: `${HARD_LINK_REASON}: ${destination.path}` };
645
+ }
646
+ if (destination.stats?.isDirectory()) {
647
+ for (const source of sources) {
648
+ const target = path.join(destination.path, path.basename(source.path));
649
+ const targetStats = await statIfExists(target);
650
+ if (targetStats?.isSymbolicLink()) {
651
+ return { ok: false, reason: `Rescue rejects ${command} onto a symlink: ${target}` };
652
+ }
653
+ if (command === "cp" && isHardLinkedFile(targetStats)) {
654
+ return { ok: false, reason: `${HARD_LINK_REASON}: ${target}` };
655
+ }
656
+ if (!isWithinWorkspaceOutsideAnyGit(workspaceRoot, target)) {
657
+ return { ok: false, reason: `Rescue rejects ${command} into .git: ${target}` };
658
+ }
659
+ }
660
+ }
661
+ }
662
+ }
663
+ catch (err) {
664
+ return { ok: false, reason: `Rescue cannot inspect ${command} operands: ${err.message}` };
665
+ }
666
+ return { ok: true };
667
+ }
668
+ /**
669
+ * Resolve one operand the way the kernel will (no `..` reaches here). An
670
+ * existing target is canonicalised through realpath so letter case matches the
671
+ * directory entry; a missing one is placed under its nearest existing
672
+ * ancestor's realpath, and a dangling symlink on the way is refused.
673
+ */
674
+ async function resolveFileOperand(workspaceRoot, operand) {
675
+ const absolute = path.resolve(operand);
676
+ const stats = await statIfExists(absolute);
677
+ if (stats?.isSymbolicLink())
678
+ return "symlink";
679
+ let candidate;
680
+ if (stats !== null) {
681
+ candidate = await realpath(absolute);
682
+ }
683
+ else {
684
+ let ancestor = path.dirname(absolute);
685
+ let ancestorReal = null;
686
+ while (ancestorReal === null) {
687
+ try {
688
+ ancestorReal = await realpath(ancestor);
689
+ }
690
+ catch (err) {
691
+ if (err.code !== "ENOENT")
692
+ throw err;
693
+ if ((await statIfExists(ancestor)) !== null)
694
+ return "reject";
695
+ const parent = path.dirname(ancestor);
696
+ if (parent === ancestor)
697
+ return "reject";
698
+ ancestor = parent;
699
+ }
700
+ }
701
+ candidate = path.join(ancestorReal, path.relative(ancestor, absolute));
702
+ }
703
+ return isWithinWorkspaceOutsideAnyGit(workspaceRoot, candidate)
704
+ ? { path: candidate, stats }
705
+ : "reject";
392
706
  }
393
707
  export function validateShellStage(tokens, pipelineMode) {
394
708
  const [command, ...args] = tokens;
395
709
  if (!command || path.isAbsolute(command) || command.includes(path.sep)) {
396
710
  return { ok: false, reason: `Rescue rejects non-standard shell entrypoints: ${tokens.join(" ")}` };
397
711
  }
398
- if (hasMutatingFlag(args)) {
712
+ // grep's exact `-i` is --ignore-case; the global `-i` entry exists for sed.
713
+ if (hasMutatingFlag(command === "grep" ? args.filter((arg) => arg !== "-i") : args)) {
399
714
  return { ok: false, reason: `Rescue rejects mutating shell flags: ${tokens.join(" ")}` };
400
715
  }
401
716
  if (hasExecDelegatingFlag(args)) {
@@ -405,7 +720,10 @@ export function validateShellStage(tokens, pipelineMode) {
405
720
  };
406
721
  }
407
722
  if (command === "git") {
408
- const firstArg = args[0] ?? "";
723
+ // A single leading --no-pager only disables paging; no other
724
+ // pre-subcommand flag is admitted, before or after it.
725
+ const gitArgs = args[0] === "--no-pager" ? args.slice(1) : args;
726
+ const firstArg = gitArgs[0] ?? "";
409
727
  // Pre-subcommand git flags shift where the subcommand lives in argv. The `-c` form in
410
728
  // particular can smuggle pager overrides: `git -c core.pager=bash show HEAD:exfil.sh`
411
729
  // makes git pipe blob contents through bash without any shell metacharacters. Any
@@ -415,7 +733,7 @@ export function validateShellStage(tokens, pipelineMode) {
415
733
  if (firstArg.startsWith("-")) {
416
734
  return {
417
735
  ok: false,
418
- reason: `Rescue rejects git pre-subcommand flags (e.g. -c/-C/-p/--no-pager/--exec-path): ${tokens.join(" ")}. Put the read-only subcommand immediately after \`git\`.`,
736
+ reason: `Rescue rejects git pre-subcommand flags (e.g. -c/-C/-p/--exec-path): ${tokens.join(" ")}. Put the read-only subcommand immediately after \`git\` or \`git --no-pager\`.`,
419
737
  };
420
738
  }
421
739
  // git grep -O/--open-files-in-pager executes its pager value. The long form
@@ -443,10 +761,7 @@ export function validateShellStage(tokens, pipelineMode) {
443
761
  // tsc option names are case-INSENSITIVE (compiler lowercases them), so match
444
762
  // lowercased. `--noemit`/`--noEmit` both suppress JS emit; `--outdir` is the
445
763
  // same write flag as `--outDir`.
446
- const tscLowerNames = args.map((arg) => {
447
- const eq = arg.indexOf("=");
448
- return (eq === -1 ? arg : arg.slice(0, eq)).toLowerCase();
449
- });
764
+ const tscLowerNames = args.map((arg) => flagName(arg).toLowerCase());
450
765
  if (!tscLowerNames.includes("--noemit")) {
451
766
  return { ok: false, reason: "Rescue allows tsc only with --noEmit." };
452
767
  }
@@ -545,10 +860,7 @@ export function validateShellStage(tokens, pipelineMode) {
545
860
  return { ok: false, reason: `Rescue rejects ${command} shell command: ${tokens.join(" ")}` };
546
861
  }
547
862
  if (hasPytestReportFlag(args.slice(2))) {
548
- return {
549
- ok: false,
550
- reason: `Rescue rejects pytest report-writing flags (--junitxml, --result-log, --report-log): ${tokens.join(" ")}.`,
551
- };
863
+ return pytestReportFlagRejection(tokens);
552
864
  }
553
865
  return { ok: true };
554
866
  }
@@ -561,7 +873,7 @@ export function validateShellStage(tokens, pipelineMode) {
561
873
  // the long --output-file form is already caught globally. These checks do
562
874
  // not make linting read-only: project config and linter code still execute
563
875
  // within rescue's repository trust boundary.
564
- if (args.some((arg) => arg === "-o" || /^-o./.test(arg))) {
876
+ if (hasWriteShortFlag(args)) {
565
877
  return {
566
878
  ok: false,
567
879
  reason: `Rescue rejects eslint -o (writes report to a file): ${tokens.join(" ")}. Drop the flag or use a path-checked Write tool call.`,
@@ -601,10 +913,7 @@ export function validateShellStage(tokens, pipelineMode) {
601
913
  // pytest executes repo code by design. Block its known runner-owned report
602
914
  // flags, not every write that test code itself can perform.
603
915
  if (hasPytestReportFlag(args)) {
604
- return {
605
- ok: false,
606
- reason: `Rescue rejects pytest report-writing flags (--junitxml, --result-log, --report-log): ${tokens.join(" ")}.`,
607
- };
916
+ return pytestReportFlagRejection(tokens);
608
917
  }
609
918
  return { ok: true };
610
919
  }
@@ -842,6 +1151,12 @@ function sortShortClusterWrites(token) {
842
1151
  function hasPytestReportFlag(args) {
843
1152
  return matchesAbbreviatedFlag(args, PYTEST_REPORT_FLAGS);
844
1153
  }
1154
+ function pytestReportFlagRejection(tokens) {
1155
+ return {
1156
+ ok: false,
1157
+ reason: `Rescue rejects pytest report-writing flags (--junitxml, --result-log, --report-log): ${tokens.join(" ")}.`,
1158
+ };
1159
+ }
845
1160
  export function validatePackageManagerCommand(command, args) {
846
1161
  // Direct <pm> test executes the repository's test script by design, like
847
1162
  // pytest/go test/cargo test, and remains inside the documented test-runner
@@ -860,6 +1175,68 @@ export function validatePackageManagerCommand(command, args) {
860
1175
  function isWithin(root, target) {
861
1176
  return target === root || target.startsWith(`${root}${path.sep}`);
862
1177
  }
1178
+ // Case-insensitive, trailing-dot/space tolerant: case-insensitive and Windows
1179
+ // filesystems open `.GIT` or `.git.` as the repository's `.git`.
1180
+ function isGitName(segment) {
1181
+ return segment.replace(/[. ]+$/, "").toLowerCase() === ".git";
1182
+ }
1183
+ function isWithinWorkspaceOutsideAnyGit(root, target) {
1184
+ return isWithin(root, target) && !path.relative(root, target).split(path.sep).some(isGitName);
1185
+ }
1186
+ /** Total directory entries one rm -r may inspect before the hook gives up. */
1187
+ export const RM_RECURSIVE_SCAN_ENTRY_CAP = 20_000;
1188
+ /** Wall-clock budget for one scan; kimi-code treats a hook timeout as allow. */
1189
+ export const GIT_SCAN_DEADLINE_MS = 3_000;
1190
+ /**
1191
+ * Walk the trees a recursive operation would touch, without following
1192
+ * symlinks or leaving each tree's filesystem, looking for a `.git` file or
1193
+ * directory at any depth (a nested repository or submodule). One entry budget
1194
+ * and one deadline cover all trees so the hook cannot stall.
1195
+ */
1196
+ export async function scanTreesForGit(roots, { cap = RM_RECURSIVE_SCAN_ENTRY_CAP, deadlineMs = GIT_SCAN_DEADLINE_MS } = {}) {
1197
+ const deadline = Date.now() + deadlineMs;
1198
+ const late = () => Date.now() >= deadline;
1199
+ const pending = [];
1200
+ for (const root of roots) {
1201
+ pending.push({ directory: root, device: (await lstat(root)).dev });
1202
+ }
1203
+ let seen = 0;
1204
+ while (pending.length > 0) {
1205
+ if (late())
1206
+ return `took longer than ${deadlineMs} ms`;
1207
+ const { directory, device } = pending.pop();
1208
+ let entries;
1209
+ try {
1210
+ entries = await readdir(directory, { withFileTypes: true });
1211
+ }
1212
+ catch (err) {
1213
+ return `cannot read ${directory}: ${err.code ?? err.message}`;
1214
+ }
1215
+ for (const entry of entries) {
1216
+ seen += 1;
1217
+ if (seen > cap)
1218
+ return `more than ${cap} entries`;
1219
+ if (isGitName(entry.name))
1220
+ return "git";
1221
+ if (!entry.isDirectory())
1222
+ continue;
1223
+ const child = path.join(directory, entry.name);
1224
+ let childDevice;
1225
+ try {
1226
+ childDevice = (await lstat(child)).dev;
1227
+ }
1228
+ catch (err) {
1229
+ return `cannot read ${child}: ${err.code ?? err.message}`;
1230
+ }
1231
+ if (childDevice !== device)
1232
+ return `crosses a filesystem boundary at ${child}`;
1233
+ if (late())
1234
+ return `took longer than ${deadlineMs} ms`;
1235
+ pending.push({ directory: child, device });
1236
+ }
1237
+ }
1238
+ return "clean";
1239
+ }
863
1240
  function rejectShell(feedback) {
864
1241
  return { response: "reject", feedback };
865
1242
  }