kimi-plugin-cc 3.0.0 → 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 (281) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +3 -14
  3. package/README.md +428 -572
  4. package/assets/logo.svg +6 -0
  5. package/cordis.patch.yml +18 -0
  6. package/dist/background-spawn.js +4 -2
  7. package/dist/cli-client.js +105 -66
  8. package/dist/commands/ask.js +27 -12
  9. package/dist/commands/cancel.js +4 -13
  10. package/dist/commands/cli-helpers.js +1 -1
  11. package/dist/commands/pursue.js +3 -2
  12. package/dist/commands/registry.js +7 -26
  13. package/dist/commands/repair-sessions.js +7 -4
  14. package/dist/commands/replay.js +4 -3
  15. package/dist/commands/rescue.js +17 -5
  16. package/dist/commands/review.js +18 -5
  17. package/dist/commands/setup.js +277 -262
  18. package/dist/commands/swarm.js +20 -7
  19. package/dist/companion.js +142 -18
  20. package/dist/help.js +11 -7
  21. package/dist/hook-escape.js +7 -16
  22. package/dist/hooks/approval-hook.js +1762 -124
  23. package/dist/hooks/approval-policy.js +15 -10
  24. package/dist/hooks/config-safety.js +15 -24
  25. package/dist/hooks/hook-timing.js +1 -1
  26. package/dist/hooks/install-paths.js +179 -107
  27. package/dist/hooks/install.js +44 -166
  28. package/dist/hooks/managed-block.js +44 -95
  29. package/dist/job-store.js +117 -49
  30. package/dist/jobs.js +53 -1
  31. package/dist/kimi-engine.js +68 -92
  32. package/dist/kimi-errors.js +1 -1
  33. package/dist/kimi-journal.js +3 -2
  34. package/dist/kimi-releases.js +28 -49
  35. package/dist/kimi-timeouts.js +1 -15
  36. package/dist/kimi-version-probe.js +24 -72
  37. package/dist/logging.js +12 -7
  38. package/dist/mcp/binding.js +13 -4
  39. package/dist/mcp/job-control.js +386 -89
  40. package/dist/mcp/launcher.js +1 -1
  41. package/dist/mcp/operations.js +387 -193
  42. package/dist/mcp/protocol.js +116 -27
  43. package/dist/mcp/skills.js +130 -0
  44. package/dist/mcp/stdio.js +15 -2
  45. package/dist/native-v2-preflight.js +127 -35
  46. package/dist/parsing.js +45 -11
  47. package/dist/paths.js +20 -10
  48. package/dist/plugin-data.js +28 -83
  49. package/dist/read-scope.js +2 -2
  50. package/dist/render.js +13 -38
  51. package/dist/session-references.js +216 -0
  52. package/dist/session-title.js +1 -1
  53. package/dist/surface-routing.js +92 -5
  54. package/dist/swarm-activation.js +26 -137
  55. package/dist/version.js +1 -1
  56. package/docs/migration.md +45 -227
  57. package/docs/models.md +24 -66
  58. package/docs/safety.md +195 -400
  59. package/docs/session-visibility.md +24 -14
  60. package/docs/swarm-recovery.md +26 -20
  61. package/dsh/index.json +54 -0
  62. package/mcp_config.json +10 -0
  63. package/package.json +23 -82
  64. package/plugin.json +19 -0
  65. package/plugins/kimi-codex/.codex-plugin/plugin.json +7 -7
  66. package/plugins/kimi-codex/.mcp.json +2 -3
  67. package/plugins/kimi-codex/dist/background-spawn.js +4 -2
  68. package/plugins/kimi-codex/dist/cli-client.js +105 -66
  69. package/plugins/kimi-codex/dist/commands/ask.js +27 -12
  70. package/plugins/kimi-codex/dist/commands/cancel.js +4 -13
  71. package/plugins/kimi-codex/dist/commands/cli-helpers.js +1 -1
  72. package/plugins/kimi-codex/dist/commands/pursue.js +3 -2
  73. package/plugins/kimi-codex/dist/commands/registry.js +7 -26
  74. package/plugins/kimi-codex/dist/commands/repair-sessions.js +7 -4
  75. package/plugins/kimi-codex/dist/commands/replay.js +4 -3
  76. package/plugins/kimi-codex/dist/commands/rescue.js +17 -5
  77. package/plugins/kimi-codex/dist/commands/review.js +18 -5
  78. package/plugins/kimi-codex/dist/commands/setup.js +277 -262
  79. package/plugins/kimi-codex/dist/commands/swarm.js +20 -7
  80. package/plugins/kimi-codex/dist/companion.js +142 -18
  81. package/plugins/kimi-codex/dist/help.js +11 -7
  82. package/plugins/kimi-codex/dist/hook-escape.js +7 -16
  83. package/plugins/kimi-codex/dist/hooks/approval-hook.js +1762 -124
  84. package/plugins/kimi-codex/dist/hooks/approval-policy.js +15 -10
  85. package/plugins/kimi-codex/dist/hooks/config-safety.js +15 -24
  86. package/plugins/kimi-codex/dist/hooks/hook-timing.js +1 -1
  87. package/plugins/kimi-codex/dist/hooks/install-paths.js +179 -107
  88. package/plugins/kimi-codex/dist/hooks/install.js +44 -166
  89. package/plugins/kimi-codex/dist/hooks/managed-block.js +44 -95
  90. package/plugins/kimi-codex/dist/job-store.js +117 -49
  91. package/plugins/kimi-codex/dist/jobs.js +53 -1
  92. package/plugins/kimi-codex/dist/kimi-engine.js +68 -92
  93. package/plugins/kimi-codex/dist/kimi-errors.js +1 -1
  94. package/plugins/kimi-codex/dist/kimi-journal.js +3 -2
  95. package/plugins/kimi-codex/dist/kimi-releases.js +28 -49
  96. package/plugins/kimi-codex/dist/kimi-timeouts.js +1 -15
  97. package/plugins/kimi-codex/dist/kimi-version-probe.js +24 -72
  98. package/plugins/kimi-codex/dist/logging.js +12 -7
  99. package/plugins/kimi-codex/dist/mcp/binding.js +13 -4
  100. package/plugins/kimi-codex/dist/mcp/job-control.js +386 -89
  101. package/plugins/kimi-codex/dist/mcp/launcher.js +1 -1
  102. package/plugins/kimi-codex/dist/mcp/operations.js +387 -193
  103. package/plugins/kimi-codex/dist/mcp/protocol.js +116 -27
  104. package/plugins/kimi-codex/dist/mcp/skills.js +130 -0
  105. package/plugins/kimi-codex/dist/mcp/stdio.js +15 -2
  106. package/plugins/kimi-codex/dist/native-v2-preflight.js +127 -35
  107. package/plugins/kimi-codex/dist/parsing.js +45 -11
  108. package/plugins/kimi-codex/dist/paths.js +20 -10
  109. package/plugins/kimi-codex/dist/plugin-data.js +28 -83
  110. package/plugins/kimi-codex/dist/read-scope.js +2 -2
  111. package/plugins/kimi-codex/dist/render.js +13 -38
  112. package/plugins/kimi-codex/dist/session-references.js +216 -0
  113. package/plugins/kimi-codex/dist/session-title.js +1 -1
  114. package/plugins/kimi-codex/dist/surface-routing.js +92 -5
  115. package/plugins/kimi-codex/dist/swarm-activation.js +26 -137
  116. package/plugins/kimi-codex/dist/version.js +1 -1
  117. package/plugins/kimi-codex/scripts/companion.sh +4 -15
  118. package/plugins/kimi-codex/skills/kimi/SKILL.md +77 -0
  119. package/plugins/kimi-codex/skills/kimi/agents/openai.yaml +6 -0
  120. package/scripts/companion.sh +4 -15
  121. package/skills/kimi/SKILL.md +77 -0
  122. package/skills/kimi/agents/openai.yaml +6 -0
  123. package/CHANGELOG.md +0 -1402
  124. package/agents/kimi-pursue.md +0 -93
  125. package/agents/kimi-review.md +0 -86
  126. package/agents/kimi-swarm.md +0 -88
  127. package/agents/kimi-task.md +0 -93
  128. package/commands/README.md +0 -14
  129. package/commands/cancel.md +0 -17
  130. package/commands/pursue.md +0 -41
  131. package/commands/replay.md +0 -13
  132. package/commands/result.md +0 -13
  133. package/commands/review.md +0 -40
  134. package/commands/setup.md +0 -25
  135. package/commands/status.md +0 -13
  136. package/commands/swarm.md +0 -45
  137. package/commands/task.md +0 -40
  138. package/dist/commands/review-gate.js +0 -391
  139. package/dist/config.js +0 -22
  140. package/dist/dsh/companion.js +0 -177
  141. package/dist/dsh/index.js +0 -167
  142. package/dist/hooks/review-gate-stop.js +0 -19
  143. package/dist/schemas/review-gate-output.js +0 -41
  144. package/docs/registry-releases.md +0 -228
  145. package/docs/upstream-2.4.1-certification.md +0 -54
  146. package/docs/upstream-2.5.0-certification.md +0 -52
  147. package/docs/upstream-2.5.1-certification.md +0 -47
  148. package/docs/upstream-2.5.2-certification.md +0 -40
  149. package/docs/upstream-2.5.3-certification.md +0 -73
  150. package/docs/upstream-2.6.0-certification.md +0 -65
  151. package/docs/upstream-2.6.2-certification.md +0 -144
  152. package/docs/upstream-2.6.3-certification.md +0 -100
  153. package/docs/upstream-2.7.2-certification.md +0 -113
  154. package/docs/upstream-2.7.3-certification.md +0 -95
  155. package/docs/windows-validation.md +0 -39
  156. package/hooks/README.md +0 -9
  157. package/hooks/hooks.json +0 -16
  158. package/plugins/kimi-codex/dist/commands/review-gate.js +0 -391
  159. package/plugins/kimi-codex/dist/config.js +0 -22
  160. package/plugins/kimi-codex/dist/dsh/companion.js +0 -177
  161. package/plugins/kimi-codex/dist/dsh/index.js +0 -167
  162. package/plugins/kimi-codex/dist/hooks/review-gate-stop.js +0 -19
  163. package/plugins/kimi-codex/dist/schemas/review-gate-output.js +0 -41
  164. package/plugins/kimi-codex/scripts/review-gate-hook.sh +0 -32
  165. package/plugins/kimi-codex/skills/kimi-cancel/SKILL.md +0 -25
  166. package/plugins/kimi-codex/skills/kimi-cancel/agents/openai.yaml +0 -6
  167. package/plugins/kimi-codex/skills/kimi-pursue/SKILL.md +0 -32
  168. package/plugins/kimi-codex/skills/kimi-pursue/agents/openai.yaml +0 -6
  169. package/plugins/kimi-codex/skills/kimi-replay/SKILL.md +0 -25
  170. package/plugins/kimi-codex/skills/kimi-replay/agents/openai.yaml +0 -6
  171. package/plugins/kimi-codex/skills/kimi-result/SKILL.md +0 -25
  172. package/plugins/kimi-codex/skills/kimi-result/agents/openai.yaml +0 -6
  173. package/plugins/kimi-codex/skills/kimi-review/SKILL.md +0 -35
  174. package/plugins/kimi-codex/skills/kimi-review/agents/openai.yaml +0 -6
  175. package/plugins/kimi-codex/skills/kimi-setup/SKILL.md +0 -35
  176. package/plugins/kimi-codex/skills/kimi-setup/agents/openai.yaml +0 -6
  177. package/plugins/kimi-codex/skills/kimi-status/SKILL.md +0 -25
  178. package/plugins/kimi-codex/skills/kimi-status/agents/openai.yaml +0 -6
  179. package/plugins/kimi-codex/skills/kimi-swarm/SKILL.md +0 -37
  180. package/plugins/kimi-codex/skills/kimi-swarm/agents/openai.yaml +0 -6
  181. package/plugins/kimi-codex/skills/kimi-task/SKILL.md +0 -37
  182. package/plugins/kimi-codex/skills/kimi-task/agents/openai.yaml +0 -6
  183. package/plugins/kimi-dsh/LICENSE +0 -201
  184. package/plugins/kimi-dsh/README.md +0 -84
  185. package/plugins/kimi-dsh/cordis.patch.yml +0 -45
  186. package/plugins/kimi-dsh/dist/background-spawn.js +0 -209
  187. package/plugins/kimi-dsh/dist/cli-cancellation.js +0 -43
  188. package/plugins/kimi-dsh/dist/cli-client.js +0 -1097
  189. package/plugins/kimi-dsh/dist/commands/ask.js +0 -269
  190. package/plugins/kimi-dsh/dist/commands/cancel.js +0 -177
  191. package/plugins/kimi-dsh/dist/commands/cli-helpers.js +0 -302
  192. package/plugins/kimi-dsh/dist/commands/models.js +0 -139
  193. package/plugins/kimi-dsh/dist/commands/pursue.js +0 -293
  194. package/plugins/kimi-dsh/dist/commands/recover-swarm.js +0 -140
  195. package/plugins/kimi-dsh/dist/commands/registry.js +0 -74
  196. package/plugins/kimi-dsh/dist/commands/repair-sessions.js +0 -266
  197. package/plugins/kimi-dsh/dist/commands/replay.js +0 -124
  198. package/plugins/kimi-dsh/dist/commands/rescue.js +0 -277
  199. package/plugins/kimi-dsh/dist/commands/result.js +0 -72
  200. package/plugins/kimi-dsh/dist/commands/review-gate.js +0 -391
  201. package/plugins/kimi-dsh/dist/commands/review.js +0 -217
  202. package/plugins/kimi-dsh/dist/commands/setup.js +0 -1465
  203. package/plugins/kimi-dsh/dist/commands/status.js +0 -27
  204. package/plugins/kimi-dsh/dist/commands/swarm.js +0 -823
  205. package/plugins/kimi-dsh/dist/commands/worker.js +0 -24
  206. package/plugins/kimi-dsh/dist/companion.js +0 -99
  207. package/plugins/kimi-dsh/dist/config.js +0 -22
  208. package/plugins/kimi-dsh/dist/dsh/companion.js +0 -177
  209. package/plugins/kimi-dsh/dist/dsh/index.js +0 -167
  210. package/plugins/kimi-dsh/dist/errors.js +0 -40
  211. package/plugins/kimi-dsh/dist/git.js +0 -216
  212. package/plugins/kimi-dsh/dist/help.js +0 -43
  213. package/plugins/kimi-dsh/dist/hook-escape.js +0 -71
  214. package/plugins/kimi-dsh/dist/hooks/approval-hook.js +0 -145
  215. package/plugins/kimi-dsh/dist/hooks/approval-policy.js +0 -295
  216. package/plugins/kimi-dsh/dist/hooks/config-safety.js +0 -641
  217. package/plugins/kimi-dsh/dist/hooks/hook-timing.js +0 -48
  218. package/plugins/kimi-dsh/dist/hooks/install-paths.js +0 -428
  219. package/plugins/kimi-dsh/dist/hooks/install.js +0 -405
  220. package/plugins/kimi-dsh/dist/hooks/managed-block.js +0 -729
  221. package/plugins/kimi-dsh/dist/hooks/review-gate-stop.js +0 -19
  222. package/plugins/kimi-dsh/dist/job-id.js +0 -12
  223. package/plugins/kimi-dsh/dist/job-store.js +0 -631
  224. package/plugins/kimi-dsh/dist/jobs.js +0 -212
  225. package/plugins/kimi-dsh/dist/kimi-command.js +0 -144
  226. package/plugins/kimi-dsh/dist/kimi-engine.js +0 -770
  227. package/plugins/kimi-dsh/dist/kimi-errors.js +0 -205
  228. package/plugins/kimi-dsh/dist/kimi-home.js +0 -15
  229. package/plugins/kimi-dsh/dist/kimi-journal.js +0 -41
  230. package/plugins/kimi-dsh/dist/kimi-releases.js +0 -144
  231. package/plugins/kimi-dsh/dist/kimi-timeouts.js +0 -52
  232. package/plugins/kimi-dsh/dist/kimi-version-probe.js +0 -198
  233. package/plugins/kimi-dsh/dist/logging.js +0 -22
  234. package/plugins/kimi-dsh/dist/mcp/binding.js +0 -58
  235. package/plugins/kimi-dsh/dist/mcp/job-control.js +0 -343
  236. package/plugins/kimi-dsh/dist/mcp/launcher.js +0 -263
  237. package/plugins/kimi-dsh/dist/mcp/operations.js +0 -333
  238. package/plugins/kimi-dsh/dist/mcp/protocol.js +0 -277
  239. package/plugins/kimi-dsh/dist/mcp/server.js +0 -8
  240. package/plugins/kimi-dsh/dist/mcp/stdio.js +0 -79
  241. package/plugins/kimi-dsh/dist/mcp/supervised-child.js +0 -15
  242. package/plugins/kimi-dsh/dist/mcp/tool-result.js +0 -7
  243. package/plugins/kimi-dsh/dist/mcp/workspace.js +0 -34
  244. package/plugins/kimi-dsh/dist/model-command.js +0 -34
  245. package/plugins/kimi-dsh/dist/native-v2-preflight.js +0 -596
  246. package/plugins/kimi-dsh/dist/package.json +0 -1
  247. package/plugins/kimi-dsh/dist/parsing.js +0 -554
  248. package/plugins/kimi-dsh/dist/paths.js +0 -35
  249. package/plugins/kimi-dsh/dist/plugin-data.js +0 -98
  250. package/plugins/kimi-dsh/dist/process-tree.js +0 -597
  251. package/plugins/kimi-dsh/dist/prompt-size.js +0 -18
  252. package/plugins/kimi-dsh/dist/read-scope.js +0 -435
  253. package/plugins/kimi-dsh/dist/render.js +0 -214
  254. package/plugins/kimi-dsh/dist/rescue-approval.js +0 -1242
  255. package/plugins/kimi-dsh/dist/schemas/review-gate-output.js +0 -41
  256. package/plugins/kimi-dsh/dist/session-recovery.js +0 -202
  257. package/plugins/kimi-dsh/dist/session-title.js +0 -313
  258. package/plugins/kimi-dsh/dist/stream-json.js +0 -344
  259. package/plugins/kimi-dsh/dist/surface-routing.js +0 -21
  260. package/plugins/kimi-dsh/dist/swarm-activation.js +0 -1194
  261. package/plugins/kimi-dsh/dist/swarm-policy.js +0 -74
  262. package/plugins/kimi-dsh/dist/swarm-recovery.js +0 -166
  263. package/plugins/kimi-dsh/dist/swarm-tool-policy.js +0 -146
  264. package/plugins/kimi-dsh/dist/types.js +0 -1
  265. package/plugins/kimi-dsh/dist/util.js +0 -28
  266. package/plugins/kimi-dsh/dist/vendor/shell-quote/LICENSE +0 -24
  267. package/plugins/kimi-dsh/dist/vendor/shell-quote/index.js +0 -1
  268. package/plugins/kimi-dsh/dist/vendor/shell-quote/parse.js +0 -229
  269. package/plugins/kimi-dsh/dist/vendor/smol-toml/LICENSE +0 -24
  270. package/plugins/kimi-dsh/dist/vendor/smol-toml/date.js +0 -156
  271. package/plugins/kimi-dsh/dist/vendor/smol-toml/error.js +0 -67
  272. package/plugins/kimi-dsh/dist/vendor/smol-toml/extract.js +0 -293
  273. package/plugins/kimi-dsh/dist/vendor/smol-toml/parse.js +0 -164
  274. package/plugins/kimi-dsh/dist/vendor/smol-toml/primitive.js +0 -151
  275. package/plugins/kimi-dsh/dist/vendor/smol-toml/struct.js +0 -156
  276. package/plugins/kimi-dsh/dist/vendor/smol-toml/util.js +0 -57
  277. package/plugins/kimi-dsh/dist/version.js +0 -7
  278. package/plugins/kimi-dsh/package.json +0 -78
  279. package/plugins/kimi-dsh/scripts/companion.sh +0 -37
  280. package/plugins/kimi-dsh/scripts/review-gate-hook.sh +0 -32
  281. package/scripts/review-gate-hook.sh +0 -32
@@ -1,1242 +0,0 @@
1
- import { realpathSync } from "node:fs";
2
- import { access, lstat, readdir, realpath } from "node:fs/promises";
3
- import path from "node:path";
4
- import { parse } from "./vendor/shell-quote/index.js";
5
- import { READ_ONLY_TOOLS } from "./hooks/approval-policy.js";
6
- // Tool-owned output flags write without shell redirection and therefore bypass
7
- // path checks unless treated as mutating. The `-o` short form is not banned
8
- // globally because tools such as rg and grep use it for read-only behavior;
9
- // per-tool checks handle it. Exact `--output` also rejects the two-argument
10
- // form because this scanner intentionally does not pair arguments.
11
- const MUTATING_FLAGS_EXACT = new Set([
12
- "--fix",
13
- "--write",
14
- "-w",
15
- "--apply",
16
- "--in-place",
17
- "-i",
18
- "--output",
19
- "--output-file",
20
- "--output-directory",
21
- "--output-dir",
22
- ]);
23
- const MUTATING_FLAG_PREFIXES = [...MUTATING_FLAGS_EXACT]
24
- .filter((flag) => flag.startsWith("--"))
25
- .map((flag) => `${flag}=`);
26
- // Flags whose VALUE is executed as a command or external tool are rejected for
27
- // every tool: Git pager overrides and Go -vettool/-exec/-toolexec are direct
28
- // command-execution escapes. Git's -O short form is handled in its own branch
29
- // because it collides with find's read-only -O<level> syntax.
30
- const EXEC_DELEGATING_FLAGS_EXACT = new Set([
31
- "--open-files-in-pager",
32
- "-vettool",
33
- "--vettool",
34
- "-toolexec",
35
- "--toolexec",
36
- "-exec",
37
- "-execdir",
38
- // rg --pre/--hostname-bin and GNU sort --compress-program also execute their
39
- // values as commands.
40
- "--pre",
41
- "--hostname-bin",
42
- "--compress-program",
43
- ]);
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}=`);
48
- // Pytest report flags write to arbitrary paths. Test runners execute repo code
49
- // by design, so these checks block known runner-owned report outputs rather
50
- // than every possible write. Match argparse allow_abbrev prefixes as well.
51
- const PYTEST_REPORT_FLAGS = [
52
- "--junitxml",
53
- "--junit-xml",
54
- "--result-log",
55
- "--report-log",
56
- ];
57
- const PIPELINE_PLUMBING = new Set(["head", "tail", "wc", "sort", "uniq"]);
58
- const GIT_READONLY_SUBCOMMANDS = new Set(["status", "diff", "show", "log", "grep", "blame"]);
59
- const CARGO_SUBCOMMANDS = new Set(["check", "clippy", "test"]);
60
- const GO_SUBCOMMANDS = new Set(["build", "vet", "test"]);
61
- const BANNED_FIND_ACTIONS = new Set([
62
- "-exec",
63
- "-execdir",
64
- "-ok",
65
- "-okdir",
66
- "-delete",
67
- "-fprint",
68
- "-fprintf",
69
- "-fprint0",
70
- "-fls",
71
- ]);
72
- // Per-tool flags that write to an arbitrary path even in the tool's read/check
73
- // mode. Each takes a path value (space- or =-separated);
74
- // `hasFlagFromSet` matches both spellings.
75
- const GO_WRITE_FLAGS = new Set([
76
- "-coverprofile",
77
- "-cpuprofile",
78
- "-memprofile",
79
- "-blockprofile",
80
- "-mutexprofile",
81
- "-trace",
82
- "-outputdir",
83
- ]);
84
- const CARGO_WRITE_FLAGS = new Set(["--target-dir", "--out-dir"]);
85
- // tsc matches option names case-INSENSITIVELY (the compiler lowercases them via
86
- // optionsNameMap), so `--outdir` == `--outDir`. Stored lowercase; matched
87
- // against lowercased arg names.
88
- const TSC_WRITE_FLAGS_LC = new Set([
89
- "--generatecpuprofile",
90
- "--generatetrace",
91
- "--tsbuildinfofile",
92
- "--outfile",
93
- "--outdir",
94
- "--out",
95
- "--declarationdir",
96
- ]);
97
- // ruff --config accepts an inline `key=value` override (`--config 'fix=true'`
98
- // flips ruff into file-rewriting mode) or an arbitrary config path — reject it
99
- // alongside the direct write flags.
100
- const RUFF_WRITE_FLAGS = new Set(["--add-noqa", "--fix-only", "--cache-dir", "--output-file", "--config"]);
101
- const ESLINT_WRITE_FLAGS = new Set(["--cache-location", "--output-file"]);
102
- // ESLint loads and executes the module named by these flags, so an arbitrary
103
- // parser/rules/plugin path is a code-execution escape. Normal linting uses the
104
- // project's own config instead of these overrides.
105
- const ESLINT_CODELOAD_FLAGS = new Set(["--parser", "--rulesdir", "--resolve-plugins-relative-to"]);
106
- // By default mypy does not execute repo code, but config plugins are imported
107
- // (the --config-file exception denied below). Reports/cache can target arbitrary
108
- // paths and --install-types runs pip. Match argparse allow_abbrev prefixes.
109
- const MYPY_WRITE_FLAGS_ABBREV = [
110
- "--junit-xml",
111
- "--cache-dir",
112
- "--install-types",
113
- // A mypy config file can import plugins, so an arbitrary --config-file is a
114
- // code-execution escape; normal checks use the workspace mypy.ini.
115
- "--config-file",
116
- "--any-exprs-report",
117
- "--cobertura-xml-report",
118
- "--html-report",
119
- "--linecount-report",
120
- "--linecoverage-report",
121
- "--lineprecision-report",
122
- "--memory-xml-report",
123
- "--txt-report",
124
- "--xml-report",
125
- "--xslt-html-report",
126
- "--xslt-txt-report",
127
- ];
128
- /**
129
- * True if any arg is exactly a flag in `flags` or its `--flag=value` form.
130
- * Handles both `--flag value` (arg === "--flag") and `--flag=value`.
131
- */
132
- function hasFlagFromSet(args, flags) {
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);
139
- }
140
- /**
141
- * True if `arg` matches any flag in `flags` accounting for argparse-style prefix
142
- * ABBREVIATION (`allow_abbrev`, the default for mypy/pytest): argparse accepts
143
- * any unambiguous prefix of a registered option, so `--jun` resolves to
144
- * `--junit-xml`. Matches when the arg name (before any `=`) is a prefix of a
145
- * dangerous flag (abbreviation) OR a dangerous flag is a prefix of the name
146
- * (exact + trailing). This is a SUPERSET of the argparse-acceptable forms —
147
- * genuinely ambiguous prefixes that argparse would reject are harmlessly denied
148
- * too. Min length 3 (`--` + 1 char) avoids matching a bare `--`.
149
- */
150
- function matchesAbbreviatedFlag(args, flags) {
151
- return args.some((arg) => {
152
- const name = flagName(arg);
153
- if (name.length < 3)
154
- return false;
155
- return flags.some((flag) => flag.startsWith(name) || name.startsWith(flag));
156
- });
157
- }
158
- /**
159
- * Evaluate a PreToolUse hook request under the rescue policy.
160
- *
161
- * `workspaceRoot` is the plugin-owned KIMI_PLUGIN_CC_WORKSPACE_ROOT passed by
162
- * the hook entry, never the payload cwd; the model cannot forge that per-spawn
163
- * environment value. `toolName` and `toolInput` are the raw upstream tool call.
164
- */
165
- export async function evaluateRescueHookRequest(workspaceRoot, toolName, toolInput) {
166
- if (READ_ONLY_TOOLS.has(toolName)) {
167
- return { decision: "allow" };
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
- }
175
- let root;
176
- try {
177
- root = await realpath(workspaceRoot);
178
- }
179
- catch (err) {
180
- return {
181
- decision: "deny",
182
- reason: `rescue cannot resolve workspace root: ${err.message}`,
183
- };
184
- }
185
- if (posix && root.includes("\\")) {
186
- return { decision: "deny", reason: backslashRootReason(root, toolName) };
187
- }
188
- if (toolName === "Bash") {
189
- const command = extractBashCommand(toolInput);
190
- if (command === null) {
191
- return {
192
- decision: "deny",
193
- reason: "rescue cannot evaluate Bash input with no command field",
194
- };
195
- }
196
- const cwd = isObject(toolInput) ? toolInput.cwd : undefined;
197
- if (cwd !== undefined) {
198
- if (typeof cwd !== "string" || cwd.length === 0) {
199
- return { decision: "deny", reason: "rescue requires Bash cwd to be a non-empty string" };
200
- }
201
- if (hasAmbiguousPathSpelling(cwd))
202
- return ambiguousPathDenial(cwd, root);
203
- try {
204
- const outcome = await checkApprovedDirectory(root, cwd);
205
- if (outcome === "symlink") {
206
- return { decision: "deny", reason: `rescue rejects Bash cwd symlinks: ${cwd}` };
207
- }
208
- if (outcome === "missing") {
209
- return { decision: "deny", reason: `rescue rejects Bash cwd that is missing or not a directory: ${cwd}` };
210
- }
211
- if (outcome === "reject") {
212
- return { decision: "deny", reason: `rescue rejects Bash cwd outside the workspace or inside .git: ${cwd}` };
213
- }
214
- }
215
- catch (err) {
216
- return { decision: "deny", reason: `rescue cannot inspect Bash cwd ${cwd}: ${err.message}` };
217
- }
218
- }
219
- const result = await validateWorkspaceShellCommand(command, root);
220
- return result.response === "approve"
221
- ? { decision: "allow" }
222
- : { decision: "deny", reason: result.feedback ?? "rescue rejected the shell command" };
223
- }
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
- }
231
- const filePath = extractFilePath(toolInput);
232
- if (filePath === null) {
233
- return {
234
- decision: "deny",
235
- reason: `rescue cannot evaluate ${toolName} input with no path field`,
236
- };
237
- }
238
- try {
239
- return pathDecision(await checkApprovedPath(root, filePath), filePath);
240
- }
241
- catch (err) {
242
- return {
243
- decision: "deny",
244
- reason: `rescue cannot inspect ${filePath} (outside the workspace, inside .git or unreadable): ${err.message}`,
245
- };
246
- }
247
- }
248
- return {
249
- decision: "deny",
250
- reason: `rescue does not allow tool "${toolName}" — only Bash, Write, Edit, MultiEdit (with allowlist checks) and read-only tools are permitted.`,
251
- };
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
- }
302
- function pathDecision(outcome, filePath) {
303
- if (outcome === "allow")
304
- return { decision: "allow" };
305
- if (outcome === "hardlink")
306
- return { decision: "deny", reason: `${HARD_LINK_REASON}: ${filePath}` };
307
- if (outcome === "symlink") {
308
- return {
309
- decision: "deny",
310
- reason: `rescue does not overwrite symlinks: ${filePath}`,
311
- };
312
- }
313
- return {
314
- decision: "deny",
315
- reason: `rescue rejects file edits outside the workspace or inside .git: ${filePath}`,
316
- };
317
- }
318
- function extractBashCommand(toolInput) {
319
- if (!isObject(toolInput))
320
- return null;
321
- const command = toolInput.command;
322
- return typeof command === "string" && command.length > 0 ? command : null;
323
- }
324
- function extractFilePath(toolInput) {
325
- if (!isObject(toolInput))
326
- return null;
327
- // kimi-code Write/Edit/MultiEdit call this field `path`, not Claude Code's
328
- // `file_path`. Prefer the native key and accept the alias for compatibility.
329
- const candidate = toolInput.path ?? toolInput.file_path;
330
- return typeof candidate === "string" && candidate.length > 0 ? candidate : null;
331
- }
332
- function isObject(value) {
333
- return typeof value === "object" && value !== null && !Array.isArray(value);
334
- }
335
- /**
336
- * TOCTOU residual: this check runs before kimi-code writes. An attacker with
337
- * workspace write access could replace the approved path with an escaping
338
- * symlink before that write. The plugin cannot open-by-fd or recheck inside the
339
- * Write tool, so the explicit trust boundary is the workspace's existing write
340
- * controls: such an attacker can already mutate workspace files directly, and
341
- * rescue is intentionally write-capable.
342
- */
343
- export async function checkApprovedPath(workspaceRoot, rawTargetPath) {
344
- const absoluteTarget = path.isAbsolute(rawTargetPath)
345
- ? path.resolve(rawTargetPath)
346
- : path.resolve(workspaceRoot, rawTargetPath);
347
- const targetStats = await statIfExists(absoluteTarget);
348
- if (targetStats?.isSymbolicLink()) {
349
- return "symlink";
350
- }
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;
373
- }
374
- const HARD_LINK_REASON = "rescue does not write through hard links";
375
- async function checkApprovedDirectory(workspaceRoot, rawCwd) {
376
- const candidate = path.resolve(workspaceRoot, rawCwd);
377
- const stats = await statIfExists(candidate);
378
- if (stats?.isSymbolicLink())
379
- return "symlink";
380
- if (!stats?.isDirectory())
381
- return "missing";
382
- const resolved = await realpath(candidate);
383
- return isWithinWorkspaceOutsideAnyGit(workspaceRoot, resolved) ? "allow" : "reject";
384
- }
385
- async function statIfExists(targetPath) {
386
- try {
387
- return await lstat(targetPath);
388
- }
389
- catch (error) {
390
- if (error.code === "ENOENT") {
391
- return null;
392
- }
393
- throw error;
394
- }
395
- }
396
- async function findNearestExistingAncestor(targetDirectory) {
397
- let candidate = targetDirectory;
398
- while (true) {
399
- try {
400
- await access(candidate);
401
- return candidate;
402
- }
403
- catch {
404
- const parent = path.dirname(candidate);
405
- if (parent === candidate) {
406
- return candidate;
407
- }
408
- candidate = parent;
409
- }
410
- }
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
- */
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
- }
465
- // shell-quote collapses raw newline/carriage-return separators into adjacent tokens, which
466
- // hides a second command from per-stage validation (`git status\nrm -rf /` parses as
467
- // ['git','status','rm','-rf','/']). Reject any line-break characters up front so every
468
- // approved command maps to a single shell invocation.
469
- if (/[\r\n]/.test(command)) {
470
- return rejectShell(`Rescue rejects multi-line shell commands: ${JSON.stringify(command)}`);
471
- }
472
- if (hasUnsafeShellSyntax(command)) {
473
- return rejectShell(`Rescue rejects command substitution, process substitution, or backticks: ${command}`);
474
- }
475
- const parsed = parse(command);
476
- const stages = [[]];
477
- for (const token of parsed) {
478
- if (typeof token === "string") {
479
- stages.at(-1).push(token);
480
- continue;
481
- }
482
- if ("op" in token && token.op === "|") {
483
- stages.push([]);
484
- continue;
485
- }
486
- return rejectShell(`Rescue rejects shell syntax outside simple pipelines: ${command}`);
487
- }
488
- if (stages.some((stage) => stage.length === 0)) {
489
- return rejectShell(`Rescue rejects malformed shell pipelines: ${command}`);
490
- }
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;
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);
559
- }
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";
706
- }
707
- export function validateShellStage(tokens, pipelineMode) {
708
- const [command, ...args] = tokens;
709
- if (!command || path.isAbsolute(command) || command.includes(path.sep)) {
710
- return { ok: false, reason: `Rescue rejects non-standard shell entrypoints: ${tokens.join(" ")}` };
711
- }
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)) {
714
- return { ok: false, reason: `Rescue rejects mutating shell flags: ${tokens.join(" ")}` };
715
- }
716
- if (hasExecDelegatingFlag(args)) {
717
- return {
718
- ok: false,
719
- reason: `Rescue rejects flags that execute an external command/tool (e.g. --open-files-in-pager, -vettool, -exec, -toolexec): ${tokens.join(" ")}`,
720
- };
721
- }
722
- if (command === "git") {
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] ?? "";
727
- // Pre-subcommand git flags shift where the subcommand lives in argv. The `-c` form in
728
- // particular can smuggle pager overrides: `git -c core.pager=bash show HEAD:exfil.sh`
729
- // makes git pipe blob contents through bash without any shell metacharacters. Any
730
- // legitimate "find first non-flag arg then check allowlist" refactor would accidentally
731
- // admit that class of attack, so we preemptively reject every pre-subcommand flag here
732
- // with an unambiguous error.
733
- if (firstArg.startsWith("-")) {
734
- return {
735
- ok: false,
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\`.`,
737
- };
738
- }
739
- // git grep -O/--open-files-in-pager executes its pager value. The long form
740
- // is caught globally; reject -O here because find uses that spelling for a
741
- // read-only optimization level.
742
- if (args.some((arg) => arg === "-O" || /^-O./.test(arg))) {
743
- return {
744
- ok: false,
745
- reason: `Rescue rejects git -O/--open-files-in-pager (executes the pager value as a command): ${tokens.join(" ")}.`,
746
- };
747
- }
748
- return GIT_READONLY_SUBCOMMANDS.has(firstArg)
749
- ? { ok: true }
750
- : { ok: false, reason: `Rescue rejects git mutation commands: ${tokens.join(" ")}` };
751
- }
752
- if (command === "find") {
753
- return args.some((arg) => BANNED_FIND_ACTIONS.has(arg))
754
- ? {
755
- ok: false,
756
- reason: `Rescue rejects find actions that execute or write files: ${tokens.join(" ")}`,
757
- }
758
- : { ok: true };
759
- }
760
- if (command === "tsc") {
761
- // tsc option names are case-INSENSITIVE (compiler lowercases them), so match
762
- // lowercased. `--noemit`/`--noEmit` both suppress JS emit; `--outdir` is the
763
- // same write flag as `--outDir`.
764
- const tscLowerNames = args.map((arg) => flagName(arg).toLowerCase());
765
- if (!tscLowerNames.includes("--noemit")) {
766
- return { ok: false, reason: "Rescue allows tsc only with --noEmit." };
767
- }
768
- // --noEmit suppresses JS emit but NOT the profile/trace/buildinfo/declaration
769
- // writers, which write to arbitrary paths.
770
- if (tscLowerNames.some((name) => TSC_WRITE_FLAGS_LC.has(name))) {
771
- return {
772
- ok: false,
773
- reason: `Rescue rejects tsc write flags (--generateCpuProfile, --generateTrace, --tsBuildInfoFile, --outFile, --outDir, --out, --declarationDir — case-insensitive): ${tokens.join(" ")}.`,
774
- };
775
- }
776
- return { ok: true };
777
- }
778
- if (command === "biome") {
779
- if (args[0] !== "check") {
780
- return { ok: false, reason: "Rescue allows biome only in check mode." };
781
- }
782
- // biome check applies fixes for every --apply/--write/--fix variant,
783
- // including -unsafe/-only suffixes missed by the global mutating-flag set.
784
- if (args.some((arg) => /^--(apply|write|fix)/.test(arg))) {
785
- return {
786
- ok: false,
787
- reason: `Rescue rejects biome check write flags (--apply, --apply-unsafe, --write, --fix, and -unsafe/-only variants): ${tokens.join(" ")}.`,
788
- };
789
- }
790
- return { ok: true };
791
- }
792
- if (command === "ruff") {
793
- if (args[0] === "check") {
794
- if (hasWriteShortFlag(args)) {
795
- return {
796
- ok: false,
797
- reason: `Rescue rejects ruff -o (writes the report to a file): ${tokens.join(" ")}.`,
798
- };
799
- }
800
- // --add-noqa/--fix-only rewrite source; --cache-dir/--output-file write
801
- // outside the workspace (--fix-only dodges the global --fix check).
802
- if (hasFlagFromSet(args, RUFF_WRITE_FLAGS)) {
803
- return {
804
- ok: false,
805
- reason: `Rescue rejects ruff write flags (--add-noqa, --fix-only, --cache-dir, --output-file): ${tokens.join(" ")}.`,
806
- };
807
- }
808
- return { ok: true };
809
- }
810
- if (args[0] === "format") {
811
- return args.some((arg) => arg === "--check" || arg === "--diff")
812
- ? { ok: true }
813
- : { ok: false, reason: "Rescue allows ruff format only with --check or --diff." };
814
- }
815
- return { ok: false, reason: `Rescue rejects ruff subcommand: ${tokens.join(" ")}` };
816
- }
817
- if (command === "cargo") {
818
- if (args[0] === "fmt") {
819
- return args.includes("--check")
820
- ? { ok: true }
821
- : { ok: false, reason: "Rescue allows cargo fmt only with --check." };
822
- }
823
- if (!CARGO_SUBCOMMANDS.has(args[0] ?? "")) {
824
- return { ok: false, reason: `Rescue rejects cargo subcommand: ${tokens.join(" ")}` };
825
- }
826
- // --target-dir/--out-dir redirect the whole artifact tree to an arbitrary
827
- // path outside the workspace.
828
- if (hasFlagFromSet(args, CARGO_WRITE_FLAGS)) {
829
- return {
830
- ok: false,
831
- reason: `Rescue rejects cargo --target-dir/--out-dir (writes artifacts to an arbitrary path): ${tokens.join(" ")}.`,
832
- };
833
- }
834
- return { ok: true };
835
- }
836
- if (command === "go") {
837
- if (!GO_SUBCOMMANDS.has(args[0] ?? "")) {
838
- return { ok: false, reason: `Rescue rejects go subcommand: ${tokens.join(" ")}` };
839
- }
840
- // go build/test -o writes a binary to an arbitrary path. Exec-delegating
841
- // -vettool/-exec/-toolexec values are already rejected globally.
842
- if (hasWriteShortFlag(args)) {
843
- return {
844
- ok: false,
845
- reason: `Rescue rejects go -o (writes a binary to an arbitrary path): ${tokens.join(" ")}.`,
846
- };
847
- }
848
- // Profile/trace/output-dir flags on `go test`/`go build` write to arbitrary
849
- // paths without `-o`.
850
- if (hasFlagFromSet(args, GO_WRITE_FLAGS)) {
851
- return {
852
- ok: false,
853
- reason: `Rescue rejects go profile/output flags (-coverprofile, -cpuprofile, -memprofile, -blockprofile, -mutexprofile, -trace, -outputdir write to arbitrary paths): ${tokens.join(" ")}.`,
854
- };
855
- }
856
- return { ok: true };
857
- }
858
- if (command === "python" || command === "python3") {
859
- if (args[0] !== "-m" || args[1] !== "pytest") {
860
- return { ok: false, reason: `Rescue rejects ${command} shell command: ${tokens.join(" ")}` };
861
- }
862
- if (hasPytestReportFlag(args.slice(2))) {
863
- return pytestReportFlagRejection(tokens);
864
- }
865
- return { ok: true };
866
- }
867
- if (command === "npm" || command === "pnpm" || command === "yarn" || command === "bun" || command === "uv") {
868
- return validatePackageManagerCommand(command, args);
869
- }
870
- if (command === "eslint") {
871
- // Block ESLint's runner-owned report/cache paths. `-o` and joined
872
- // `-o<path>` need a tool-specific check because rg/grep use `-o` read-only;
873
- // the long --output-file form is already caught globally. These checks do
874
- // not make linting read-only: project config and linter code still execute
875
- // within rescue's repository trust boundary.
876
- if (hasWriteShortFlag(args)) {
877
- return {
878
- ok: false,
879
- reason: `Rescue rejects eslint -o (writes report to a file): ${tokens.join(" ")}. Drop the flag or use a path-checked Write tool call.`,
880
- };
881
- }
882
- // --output-file (long form) is caught globally; --cache-location writes the
883
- // cache tree to an arbitrary path.
884
- if (hasFlagFromSet(args, ESLINT_WRITE_FLAGS)) {
885
- return {
886
- ok: false,
887
- reason: `Rescue rejects eslint --cache-location/--output-file (writes to an arbitrary path): ${tokens.join(" ")}.`,
888
- };
889
- }
890
- // --parser/--rulesdir/--resolve-plugins-relative-to LOAD AND EXECUTE a module
891
- // from the given path — a code-exec escape.
892
- if (hasFlagFromSet(args, ESLINT_CODELOAD_FLAGS)) {
893
- return {
894
- ok: false,
895
- reason: `Rescue rejects eslint --parser/--rulesdir/--resolve-plugins-relative-to (loads and executes a module from the given path): ${tokens.join(" ")}.`,
896
- };
897
- }
898
- return { ok: true };
899
- }
900
- if (command === "mypy") {
901
- // By default mypy does not execute repo code, but --config-file can import
902
- // plugins and is denied below. Block report/cache/install outputs and their
903
- // argparse allow_abbrev prefixes.
904
- if (matchesAbbreviatedFlag(args, MYPY_WRITE_FLAGS_ABBREV)) {
905
- return {
906
- ok: false,
907
- reason: `Rescue rejects mypy report/cache/install flags (--junit-xml, --*-report, --cache-dir, --install-types — incl. argparse abbreviations — write outside the workspace or run pip): ${tokens.join(" ")}.`,
908
- };
909
- }
910
- return { ok: true };
911
- }
912
- if (command === "pytest") {
913
- // pytest executes repo code by design. Block its known runner-owned report
914
- // flags, not every write that test code itself can perform.
915
- if (hasPytestReportFlag(args)) {
916
- return pytestReportFlagRejection(tokens);
917
- }
918
- return { ok: true };
919
- }
920
- if (["rg", "grep", "ls", "cat", "pwd", "pyright"].includes(command)) {
921
- return { ok: true };
922
- }
923
- if (pipelineMode && PIPELINE_PLUMBING.has(command)) {
924
- // sort -o and uniq's second positional are output writes, unnecessary for
925
- // pipeline stages that read stdin.
926
- if (hasWriteShortFlag(args) || args.includes("--output")) {
927
- return {
928
- ok: false,
929
- reason: `Rescue rejects ${command} -o/--output (writes to an arbitrary file): ${tokens.join(" ")}.`,
930
- };
931
- }
932
- // `sort -o FILE` / `-T DIR` write to an arbitrary path — including BUNDLED
933
- // short-flag clusters (`sort -rT /tmp`, `-ro file`) that the generic `-o`
934
- // check above misses because the cluster starts with `-r` (Opus review
935
- // 2026-07-17). `sortShortClusterWrites` scans the cluster with getopt
936
- // semantics; the long `--temporary-directory` form is matched separately.
937
- if (command === "sort" &&
938
- (args.some((arg) => sortShortClusterWrites(arg)) ||
939
- args.includes("--temporary-directory") ||
940
- args.some((arg) => arg.startsWith("--temporary-directory=")))) {
941
- return {
942
- ok: false,
943
- reason: `Rescue rejects sort -o/-T (incl. bundled short clusters like -rT) and --temporary-directory (write to an arbitrary path): ${tokens.join(" ")}.`,
944
- };
945
- }
946
- // `uniq IN OUT` writes OUT; `-` (stdin) counts as an operand, so
947
- // `uniq - /tmp/out` is a write. Two+ operands ⇒ an output file is present.
948
- if (command === "uniq" &&
949
- args.filter((arg) => arg === "-" || !arg.startsWith("-")).length >= 2) {
950
- return {
951
- ok: false,
952
- reason: `Rescue rejects uniq with an output-file argument (uniq IN OUT writes OUT): ${tokens.join(" ")}.`,
953
- };
954
- }
955
- return { ok: true };
956
- }
957
- return { ok: false, reason: `Rescue rejects shell command: ${tokens.join(" ")}` };
958
- }
959
- class ShellExpansionError extends Error {
960
- }
961
- /**
962
- * Env callback for `parse(command, env)`. shell-quote invokes it ONLY for a
963
- * `$VAR`/`${…}` expansion that bash would actually perform — i.e. OUTSIDE single
964
- * quotes (single-quoted `$` is literal). Throwing on any non-empty key rejects
965
- * every real reference — including `$IFS`, `$HOME`, and double-quoted `"$PAT"` —
966
- * quote-aware and for free. An EMPTY key is a trailing/literal `$` (`grep 'end$'`,
967
- * `awk '{print $}'`), which bash does not expand, so it returns a literal `$`.
968
- */
969
- function throwingExpansionEnv(key) {
970
- if (key !== "")
971
- throw new ShellExpansionError(key);
972
- return "$";
973
- }
974
- /**
975
- * True if the command performs any `$VAR`/`${…}` parameter expansion. Uses the
976
- * vendored parser's own quote tracking (via the throwing env), so it is immune
977
- * to the two ways the default empty-env parse DIVERGES from bash and hides a
978
- * smuggled flag from every per-flag check:
979
- * - `${VAR:-flag}` collapsed to an empty token (no `:-`-default modelling), and
980
- * - `$IFS`-gluing (`rg x$IFS--pre$IFS'sh'` → one token here, but bash splits it
981
- * into `rg x --pre sh` — an RCE).
982
- * A malformed substitution (`${}`, unterminated) throws a plain parser Error;
983
- * that is itself unsafe to pass through, so any throw ⇒ unsafe (fail closed).
984
- */
985
- function hasShellExpansion(command) {
986
- try {
987
- parse(command, throwingExpansionEnv);
988
- return false;
989
- }
990
- catch {
991
- return true;
992
- }
993
- }
994
- /**
995
- * True if `s[open]` opens a bash BRACE EXPANSION (`{a,b}` / `{a..b}`): a matching
996
- * `}` with a top-level `,` or `..` between. bash expands it into multiple words
997
- * BEFORE the allowlist sees them (`find . {-delete,}` → `find . -delete`), while
998
- * shell-quote keeps it as one literal token — so a smuggled flag/action hides in
999
- * the group. `${…}` (param expansion, handled by `hasShellExpansion`) and a
1000
- * quoted group are not brace expansion.
1001
- */
1002
- function isBraceExpansion(s, open) {
1003
- if (open > 0 && s[open - 1] === "$")
1004
- return false;
1005
- let depth = 0;
1006
- let sawSeparator = false;
1007
- for (let j = open; j < s.length; j += 1) {
1008
- const ch = s[j];
1009
- if (ch === "\\") {
1010
- j += 1;
1011
- continue;
1012
- }
1013
- if (ch === "'" || ch === '"')
1014
- return false;
1015
- if (ch === "{") {
1016
- depth += 1;
1017
- }
1018
- else if (ch === "}") {
1019
- depth -= 1;
1020
- if (depth === 0)
1021
- return sawSeparator;
1022
- }
1023
- else if (depth === 1 && (ch === "," || (ch === "." && s[j + 1] === "."))) {
1024
- sawSeparator = true;
1025
- }
1026
- }
1027
- return false;
1028
- }
1029
- /**
1030
- * Quote-aware scan for dangerous constructs the vendored parser does NOT surface
1031
- * as a `$VAR` expansion (so `hasShellExpansion` can't see them): backticks,
1032
- * command/process substitution, the `$'…'`/`$"…"` quoting openers (bash decodes
1033
- * `\xNN` etc. into bytes that can form a flag — shell-quote does not), and brace
1034
- * expansion. SINGLE-quoted spans are fully inert (bash suppresses everything), so
1035
- * a `` ` ``/`$`/`{` inside them is never flagged — that removes the blind-regex
1036
- * false positives (`grep 'foo $'`, `grep '$(x)'`, `find -name '*.{a,b}'`). DOUBLE
1037
- * quotes are NOT inert: `$(…)` and backticks stay ACTIVE inside them (only `$VAR`
1038
- * detection is delegated to `hasShellExpansion`), so the double-quote span is
1039
- * scanned for those two. A backslash escapes the next char in either context.
1040
- */
1041
- function scanUnsafeUnquoted(command) {
1042
- const n = command.length;
1043
- let i = 0;
1044
- while (i < n) {
1045
- const c = command[i];
1046
- if (c === "\\") {
1047
- i += 2;
1048
- continue;
1049
- }
1050
- if (c === "'") {
1051
- const end = command.indexOf("'", i + 1);
1052
- if (end === -1)
1053
- return true; // unterminated quote → unsafe
1054
- i = end + 1;
1055
- continue;
1056
- }
1057
- if (c === '"') {
1058
- // Double quotes keep command substitution active (`"$(id)"` runs `id`;
1059
- // `` "`id`" `` too), so scan the span for them. `"\$(x)"` / `` "\`x`" `` are
1060
- // escaped → literal → allowed. `$VAR`/`${…}` are caught by hasShellExpansion.
1061
- i += 1;
1062
- while (i < n && command[i] !== '"') {
1063
- if (command[i] === "\\") {
1064
- i += 2;
1065
- continue;
1066
- }
1067
- if (command[i] === "`")
1068
- return true; // backtick cmd-sub (active in "…")
1069
- if (command[i] === "$" && command[i + 1] === "(")
1070
- return true; // $(…) cmd-sub (active in "…")
1071
- i += 1;
1072
- }
1073
- if (i >= n)
1074
- return true; // unterminated quote → unsafe
1075
- i += 1;
1076
- continue;
1077
- }
1078
- if (c === "`")
1079
- return true; // backtick command substitution
1080
- if (c === "$" && (command[i + 1] === "'" || command[i + 1] === '"'))
1081
- return true; // $'…' / $"…"
1082
- if (c === "$" && command[i + 1] === "(")
1083
- return true; // $(…) command substitution
1084
- if ((c === "<" || c === ">") && command[i + 1] === "(")
1085
- return true; // <(…) / >(…)
1086
- if (c === "{" && isBraceExpansion(command, i))
1087
- return true;
1088
- i += 1;
1089
- }
1090
- return false;
1091
- }
1092
- /**
1093
- * Syntax gate before the per-flag allowlist. Reject the expansion/substitution
1094
- * classes shell-quote does not model: backticks, command/process substitution,
1095
- * `$'…'`/`$"…"` openers, brace expansion, and `$VAR`/`${…}` parameter expansion
1096
- * including `$IFS` gluing and default-value forms. Two complementary quote-aware
1097
- * passes prevent these forms from smuggling flags or commands downstream.
1098
- */
1099
- export function hasUnsafeShellSyntax(command) {
1100
- return scanUnsafeUnquoted(command) || hasShellExpansion(command);
1101
- }
1102
- export function hasMutatingFlag(args) {
1103
- for (const arg of args) {
1104
- if (MUTATING_FLAGS_EXACT.has(arg)) {
1105
- return true;
1106
- }
1107
- if (MUTATING_FLAG_PREFIXES.some((prefix) => arg.startsWith(prefix))) {
1108
- return true;
1109
- }
1110
- // sed's -i accepts an optional suffix like -i.bak or --in-place=.bak. Match only the
1111
- // punctuation-suffix shapes so we don't collide with read-only short-flag clusters
1112
- // such as `find -iname`, `grep -il`, or `rg -iw`.
1113
- if (/^-i[.=]/.test(arg)) {
1114
- return true;
1115
- }
1116
- }
1117
- return false;
1118
- }
1119
- /** True if any argument delegates execution to a command or external tool. */
1120
- export function hasExecDelegatingFlag(args) {
1121
- return args.some((arg) => EXEC_DELEGATING_FLAGS_EXACT.has(arg) ||
1122
- EXEC_DELEGATING_FLAG_PREFIXES.some((prefix) => arg.startsWith(prefix)));
1123
- }
1124
- /**
1125
- * Per-tool check for `-o`, joined `-ofile`, and `-o=file` where that flag writes
1126
- * output (go, sort, ruff, and ESLint). It is not global because rg/grep use `-o`
1127
- * for read-only matching. Long --output forms are covered by the mutating set.
1128
- */
1129
- export function hasWriteShortFlag(args) {
1130
- return args.some((arg) => arg === "-o" || /^-o./.test(arg));
1131
- }
1132
- /**
1133
- * True if a GNU `sort` short-flag token writes a file — including a BUNDLED
1134
- * cluster (`-rT DIR`, `-ro FILE`) the plain `-o` check misses. getopt consumes a
1135
- * cluster left to right; the first argument-taking option grabs the rest as its
1136
- * value, so an `o`/`T` AFTER a `-t`/`-k`/`-S` (sort's other arg-taking options)
1137
- * is that option's value, not a write flag.
1138
- */
1139
- function sortShortClusterWrites(token) {
1140
- if (token.length < 2 || token[0] !== "-" || token[1] === "-")
1141
- return false;
1142
- for (let i = 1; i < token.length; i += 1) {
1143
- const ch = token[i];
1144
- if (ch === "o" || ch === "T")
1145
- return true; // -o output / -T temp dir → write
1146
- if (ch === "t" || ch === "k" || ch === "S")
1147
- return false; // arg-taking: rest is its value
1148
- }
1149
- return false;
1150
- }
1151
- function hasPytestReportFlag(args) {
1152
- return matchesAbbreviatedFlag(args, PYTEST_REPORT_FLAGS);
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
- }
1160
- export function validatePackageManagerCommand(command, args) {
1161
- // Direct <pm> test executes the repository's test script by design, like
1162
- // pytest/go test/cargo test, and remains inside the documented test-runner
1163
- // trust boundary. `run <arbitrary-script>` is instead a general script
1164
- // executor (dev/deploy/publish), so this deliberate test/run asymmetry stays.
1165
- if (args[0] === "test") {
1166
- return { ok: true };
1167
- }
1168
- // `<pm> run <script>` is opaque: a malicious package.json can redefine any script to do anything.
1169
- // Rescue requires users to invoke direct check/build tools (tsc, pyright, mypy, eslint, etc.).
1170
- return {
1171
- ok: false,
1172
- reason: `Rescue rejects ${command} ${args.join(" ")}. Use direct tools (tsc --noEmit, pyright, mypy, ruff check, eslint, pytest) instead of package.json scripts.`,
1173
- };
1174
- }
1175
- function isWithin(root, target) {
1176
- return target === root || target.startsWith(`${root}${path.sep}`);
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
- }
1240
- function rejectShell(feedback) {
1241
- return { response: "reject", feedback };
1242
- }