@cbartens/bkit 6.1.0 → 6.2.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/.bkit/README.md +14 -12
  2. package/.bkit/core/.agents/docs.md +1 -11
  3. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-gateguard.cjs +30 -9
  4. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-guardrails.cjs +25 -27
  5. package/.bkit/core/.agents/rules.md +22 -9
  6. package/.bkit/core/.bkit/README.md +13 -11
  7. package/.bkit/core/.bkit/authoring.md +58 -13
  8. package/.bkit/core/.bkit/cli.md +43 -33
  9. package/.bkit/core/.bkit/cloud.md +93 -30
  10. package/.bkit/core/.bkit/install.md +55 -16
  11. package/.bkit/core/.bkit/jsonl.md +24 -7
  12. package/.bkit/core/.bkit/pipeline.md +8 -8
  13. package/.bkit/core/.bkit/prompts.md +160 -43
  14. package/.bkit/core/.bkit/providers.md +99 -36
  15. package/.bkit/core/.bkit/templates.md +167 -37
  16. package/.bkit/core/.bkit/trackers.md +39 -6
  17. package/.bkit/core/.bkit/workflows.md +344 -136
  18. package/.bkit/core/.claude/hooks/bkit-guardrails.cjs +50 -27
  19. package/.bkit/core/.claude/hooks/bkit-preflight.sh +11 -11
  20. package/.bkit/core/.codex/hooks/bkit-gateguard.cjs +13 -8
  21. package/.bkit/core/.codex/hooks/bkit-guardrails.cjs +14 -25
  22. package/.bkit/core/.cursor/hooks/bkit-guardrails.cjs +20 -9
  23. package/.bkit/core/.cursor/hooks/bkit-preflight.sh +8 -8
  24. package/.bkit/core/.opencode/plugin/bkit-gateguard.js +14 -4
  25. package/.bkit/core/.opencode/plugin/bkit-guardrails.js +114 -0
  26. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +1 -1
  27. package/.bkit/core/docs/templates/bkit-audit-adoption.md +30 -6
  28. package/.bkit/core/docs/templates/bkit-audit-agents.md +1 -1
  29. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +1 -1
  30. package/.bkit/core/docs/templates/bkit-audit-analytics.md +1 -1
  31. package/.bkit/core/docs/templates/bkit-audit-annotations.md +1 -1
  32. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +1 -1
  33. package/.bkit/core/docs/templates/bkit-audit-app-store.md +1 -1
  34. package/.bkit/core/docs/templates/bkit-audit-architecture.md +1 -1
  35. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +2 -2
  36. package/.bkit/core/docs/templates/bkit-audit-config.md +3 -2
  37. package/.bkit/core/docs/templates/bkit-audit-cost.md +1 -1
  38. package/.bkit/core/docs/templates/bkit-audit-coverage.md +1 -1
  39. package/.bkit/core/docs/templates/bkit-audit-database.md +3 -3
  40. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +1 -1
  41. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +1 -1
  42. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +3 -3
  43. package/.bkit/core/docs/templates/bkit-audit-documentation.md +32 -2
  44. package/.bkit/core/docs/templates/bkit-audit-duplication.md +1 -1
  45. package/.bkit/core/docs/templates/bkit-audit-failures.md +1 -1
  46. package/.bkit/core/docs/templates/bkit-audit-flakes.md +2 -2
  47. package/.bkit/core/docs/templates/bkit-audit-gates.md +5 -3
  48. package/.bkit/core/docs/templates/bkit-audit-issues.md +1 -1
  49. package/.bkit/core/docs/templates/bkit-audit-llm.md +2 -2
  50. package/.bkit/core/docs/templates/bkit-audit-logs.md +1 -1
  51. package/.bkit/core/docs/templates/bkit-audit-models.md +2 -2
  52. package/.bkit/core/docs/templates/bkit-audit-privacy.md +1 -1
  53. package/.bkit/core/docs/templates/bkit-audit-prompts.md +1 -1
  54. package/.bkit/core/docs/templates/bkit-audit-red-team.md +2 -2
  55. package/.bkit/core/docs/templates/bkit-audit-reliability.md +3 -2
  56. package/.bkit/core/docs/templates/bkit-audit-repo.md +1 -1
  57. package/.bkit/core/docs/templates/bkit-audit-security.md +1 -1
  58. package/.bkit/core/docs/templates/bkit-audit-slop.md +1 -1
  59. package/.bkit/core/docs/templates/bkit-audit-testing.md +3 -2
  60. package/.bkit/core/docs/templates/bkit-audit-usability.md +1 -1
  61. package/.bkit/core/docs/templates/bkit-plan.md +38 -8
  62. package/.bkit/core/engine/checks/after/auth.ts +118 -47
  63. package/.bkit/core/engine/checks/after/github.ts +161 -37
  64. package/.bkit/core/engine/checks/after/index.ts +18 -3
  65. package/.bkit/core/engine/checks/after/tools.ts +245 -1
  66. package/.bkit/core/engine/checks/before/files.ts +59 -1
  67. package/.bkit/core/engine/checks/before/index.ts +8 -0
  68. package/.bkit/core/engine/checks/status-holes.ts +20 -26
  69. package/.bkit/core/engine/checks/tips/catalogue.ts +107 -10
  70. package/.bkit/core/engine/checks/tips/detect.ts +36 -3
  71. package/.bkit/core/engine/checks/tips/index.ts +1 -1
  72. package/.bkit/core/engine/cli.ts +13 -13
  73. package/.bkit/core/engine/commands/ci/ci.ts +124 -19
  74. package/.bkit/core/engine/commands/ci/push-gate.ts +101 -43
  75. package/.bkit/core/engine/commands/install/doctor.ts +5 -5
  76. package/.bkit/core/engine/commands/install/install.ts +28 -25
  77. package/.bkit/core/engine/commands/install/uninstall.ts +42 -30
  78. package/.bkit/core/engine/commands/install/upgrade.ts +14 -2
  79. package/.bkit/core/engine/commands/land.ts +2 -3
  80. package/.bkit/core/engine/commands/lib.ts +394 -39
  81. package/.bkit/core/engine/commands/registry.ts +1 -1
  82. package/.bkit/core/engine/commands/workflow/branches.ts +351 -78
  83. package/.bkit/core/engine/commands/workflow/challenge.ts +63 -14
  84. package/.bkit/core/engine/commands/workflow/context.ts +71 -10
  85. package/.bkit/core/engine/commands/workflow/counters.ts +298 -23
  86. package/.bkit/core/engine/commands/workflow/decisions.ts +260 -125
  87. package/.bkit/core/engine/commands/workflow/disk.ts +2 -1
  88. package/.bkit/core/engine/commands/workflow/feature-base.ts +66 -0
  89. package/.bkit/core/engine/commands/workflow/issues.ts +312 -17
  90. package/.bkit/core/engine/commands/workflow/junit.ts +204 -0
  91. package/.bkit/core/engine/commands/workflow/ledgers.ts +904 -99
  92. package/.bkit/core/engine/commands/workflow/locks.ts +186 -29
  93. package/.bkit/core/engine/commands/workflow/loops.ts +87 -0
  94. package/.bkit/core/engine/commands/workflow/open-decision.ts +251 -0
  95. package/.bkit/core/engine/commands/workflow/plan-blocks.ts +8 -0
  96. package/.bkit/core/engine/commands/workflow/plans.ts +1 -1
  97. package/.bkit/core/engine/commands/workflow/prs.ts +311 -16
  98. package/.bkit/core/engine/commands/workflow/repo.ts +1 -1
  99. package/.bkit/core/engine/commands/workflow/run-facts.ts +6 -0
  100. package/.bkit/core/engine/commands/workflow/runs.ts +877 -174
  101. package/.bkit/core/engine/commands/workflow/runtime.ts +12 -4
  102. package/.bkit/core/engine/commands/workflow/status.ts +324 -11
  103. package/.bkit/core/engine/commands/workflow/step-table.ts +41 -15
  104. package/.bkit/core/engine/commands/workflow/steps.ts +604 -29
  105. package/.bkit/core/engine/commands/workflow/summary-findings.ts +1 -1
  106. package/.bkit/core/engine/commands/workflow/summary.ts +314 -8
  107. package/.bkit/core/engine/commands/workflow/tasks.ts +400 -27
  108. package/.bkit/core/engine/commands/workflow/tests-base.ts +319 -0
  109. package/.bkit/core/engine/commands/workflow/tests-changed.ts +138 -74
  110. package/.bkit/core/engine/commands/workflow/tests-jump.ts +93 -0
  111. package/.bkit/core/engine/commands/workflow/tests.ts +815 -182
  112. package/.bkit/core/engine/commands/workflow/tracker.ts +1134 -137
  113. package/.bkit/core/engine/commands/workflow/workflows.ts +100 -72
  114. package/.bkit/core/engine/commands/workflow/worktrees.ts +421 -57
  115. package/.bkit/core/engine/install/cloud-env.ts +38 -10
  116. package/.bkit/core/engine/install/managed-block.ts +105 -0
  117. package/.bkit/core/engine/install/manifest.ts +7 -1
  118. package/.bkit/core/engine/install/modules/claude.ts +6 -2
  119. package/.bkit/core/engine/install/modules/cloud.ts +84 -95
  120. package/.bkit/core/engine/install/modules/codex.ts +10 -2
  121. package/.bkit/core/engine/install/modules/core.ts +202 -26
  122. package/.bkit/core/engine/install/modules/opencode.ts +18 -23
  123. package/.bkit/core/engine/install/network-allowlist.ts +8 -3
  124. package/.bkit/core/engine/install/project-docs.ts +650 -0
  125. package/.bkit/core/engine/install/template-copies.ts +58 -5
  126. package/.bkit/core/engine/install/write.ts +128 -7
  127. package/.bkit/core/engine/ledgers/journal.ts +18 -10
  128. package/.bkit/core/engine/ledgers/migrate.ts +20 -8
  129. package/.bkit/core/engine/ledgers/status.ts +604 -8
  130. package/.bkit/core/engine/ledgers/telemetry.ts +115 -13
  131. package/.bkit/core/engine/render/trackers.ts +46 -11
  132. package/.bkit/core/engine/shared/package-manager.ts +7 -3
  133. package/.bkit/core/engine/shared/settings.ts +12 -1
  134. package/.bkit/core/engine/shared/text.ts +14 -0
  135. package/.bkit/core/engine/tools/instructions-sources.ts +1 -0
  136. package/.bkit/core/engine/tools/instructions.ts +116 -20
  137. package/.bkit/core/hooks/antigravity-hook.js +20 -4
  138. package/.bkit/core/hooks/gateguard-edit-payload.js +8 -5
  139. package/.bkit/core/hooks/gateguard-engine.js +249 -23
  140. package/.bkit/core/hooks/guardrails-deny.js +167 -0
  141. package/.bkit/core/hooks/guardrails-read.js +3 -3
  142. package/.bkit/core/hooks/guardrails-shell.js +1122 -167
  143. package/.bkit/core/hooks/guardrails-tiers.js +247 -176
  144. package/.bkit/core/hooks/preflight-tracker.sh +219 -0
  145. package/.bkit/core/prompts/bkit-audit-generate.md +23 -6
  146. package/.bkit/core/prompts/bkit-build-challenge-1.md +5 -4
  147. package/.bkit/core/prompts/bkit-build-challenge-2.md +6 -5
  148. package/.bkit/core/prompts/bkit-build-install-skills.md +2 -2
  149. package/.bkit/core/prompts/bkit-build-plan-convert.md +21 -7
  150. package/.bkit/core/prompts/bkit-build-plan-current.md +5 -4
  151. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +22 -17
  152. package/.bkit/core/prompts/bkit-build-plan-tasks.md +16 -12
  153. package/.bkit/core/prompts/bkit-build-plan-tests.md +14 -10
  154. package/.bkit/core/prompts/bkit-build-plan-verify.md +21 -8
  155. package/.bkit/core/prompts/bkit-debug-abort-handover.md +10 -5
  156. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +22 -6
  157. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +19 -3
  158. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +22 -6
  159. package/.bkit/core/prompts/bkit-debug-failure-soak.md +10 -7
  160. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +3 -3
  161. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +4 -4
  162. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +3 -3
  163. package/.bkit/core/prompts/bkit-design-generate.md +6 -4
  164. package/.bkit/core/prompts/bkit-design-organise.md +4 -3
  165. package/.bkit/core/prompts/bkit-design-review-1.md +5 -4
  166. package/.bkit/core/prompts/bkit-design-review-2.md +6 -5
  167. package/.bkit/core/prompts/bkit-design-spike.md +4 -3
  168. package/.bkit/core/prompts/bkit-design-update.md +6 -4
  169. package/.bkit/core/prompts/bkit-plan-generate.md +35 -14
  170. package/.bkit/core/prompts/bkit-plan-review-1.md +9 -7
  171. package/.bkit/core/prompts/bkit-plan-review-2.md +9 -7
  172. package/.bkit/core/prompts/bkit-plan-scope-check.md +8 -6
  173. package/.bkit/core/prompts/bkit-plan-update.md +22 -8
  174. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +11 -8
  175. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +9 -5
  176. package/.bkit/core/prompts/bkit-ship-update-docs.md +26 -4
  177. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +3 -3
  178. package/.bkit/core/prompts/bkit-utility-update-decisions.md +10 -7
  179. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +8 -5
  180. package/.bkit/core/prompts/bkit-utility-update-documentation.md +31 -7
  181. package/.bkit/core/prompts/bkit-utility-update-failures.md +8 -5
  182. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +10 -7
  183. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +4 -4
  184. package/.bkit/core/prompts/bkit-utility-update-tracker.md +4 -4
  185. package/.bkit/core/workflows/bkit-auto.md +23 -11
  186. package/.bkit/core/workflows/bkit-build.md +331 -100
  187. package/.bkit/core/workflows/bkit-debug.md +135 -64
  188. package/.bkit/core/workflows/bkit-design.md +58 -32
  189. package/.bkit/core/workflows/bkit-plan.md +73 -45
  190. package/.bkit/core/workflows/bkit-ship.md +233 -167
  191. package/.bkit/shared/.agents/plugins/bkit/hooks.json +1 -1
  192. package/.bkit/shared/.bkit/.env.example +5 -0
  193. package/.bkit/shared/.claude/bkit-cloud.md +7 -7
  194. package/.bkit/shared/.claude/settings.json +5 -1
  195. package/.bkit/shared/.cursor/bkit-cloud.md +1 -1
  196. package/.bkit/shared/.cursor/hooks.json +1 -1
  197. package/.bkit/shared/.opencode/opencode.json +11 -2
  198. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +27 -0
  199. package/.bkit/templates/.cursor/Dockerfile +7 -7
  200. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-idea.yml +1 -1
  201. package/.bkit/templates/.github/dependabot.yml +5 -0
  202. package/.bkit/templates/.github/renovate.json5 +5 -3
  203. package/.bkit/templates/.github/workflows/bkit-ci.yml +11 -11
  204. package/.bkit/templates/.github/workflows/bkit-cloud.yml +525 -161
  205. package/.bkit/templates/.github/workflows/bkit-renovate.yml +2 -2
  206. package/.bkit/templates/.husky/pre-push +123 -6
  207. package/.bkit/templates/context/bkit-serena.md +1 -1
  208. package/.bkit/templates/context/bkit-vercel.md +103 -59
  209. package/.bkit/templates/docs/architecture.md +98 -0
  210. package/.bkit/templates/docs/capabilities.md +33 -37
  211. package/.bkit/templates/docs/components.md +142 -0
  212. package/.bkit/templates/docs/data-schema.md +87 -0
  213. package/.bkit/{shared → templates}/docs/deployments.md +128 -142
  214. package/.bkit/templates/docs/design.md +117 -0
  215. package/.bkit/templates/docs/noise.md +54 -0
  216. package/.bkit/templates/docs/observability.md +99 -0
  217. package/.bkit/templates/docs/security.md +137 -0
  218. package/.bkit/templates/docs/setup.md +93 -0
  219. package/.bkit/templates/docs/technology.md +70 -0
  220. package/.bkit/{shared → templates}/docs/testing.md +200 -87
  221. package/.bkit/templates/scripts/ci/bkit-check-accepted-divergences.mjs +1 -6
  222. package/.bkit/templates/scripts/ci/bkit-machine-lock.sh +511 -103
  223. package/.bkit/templates/scripts/ci/bkit-test-awake.mjs +314 -28
  224. package/.bkit/templates/scripts/ci/bkit-test-awake.test.mjs +500 -1
  225. package/.bkit/templates/scripts/graphify/bkit-graphify-graphml.py +1 -1
  226. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +91 -62
  227. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +59 -11
  228. package/.bkit/templates/slop-scan.config.json +2 -0
  229. package/CHANGELOG.md +79 -0
  230. package/DETAILS.md +661 -0
  231. package/README.md +73 -604
  232. package/dist/checks/after/auth.js +114 -46
  233. package/dist/checks/after/github.js +138 -35
  234. package/dist/checks/after/index.js +16 -4
  235. package/dist/checks/after/tools.js +224 -1
  236. package/dist/checks/before/files.js +59 -1
  237. package/dist/checks/before/index.js +7 -1
  238. package/dist/checks/status-holes.js +20 -21
  239. package/dist/checks/tips/catalogue.js +99 -10
  240. package/dist/checks/tips/detect.js +35 -3
  241. package/dist/checks/tips/index.js +1 -1
  242. package/dist/cli.js +13 -13
  243. package/dist/commands/ci/ci.js +113 -20
  244. package/dist/commands/ci/push-gate.js +79 -44
  245. package/dist/commands/install/doctor.js +5 -5
  246. package/dist/commands/install/install.js +23 -22
  247. package/dist/commands/install/uninstall.js +36 -30
  248. package/dist/commands/install/upgrade.js +10 -2
  249. package/dist/commands/land.js +2 -3
  250. package/dist/commands/lib.js +323 -25
  251. package/dist/commands/workflow/branches.js +312 -72
  252. package/dist/commands/workflow/challenge.js +66 -13
  253. package/dist/commands/workflow/context.js +46 -10
  254. package/dist/commands/workflow/counters.js +231 -23
  255. package/dist/commands/workflow/decisions.js +221 -106
  256. package/dist/commands/workflow/disk.js +2 -1
  257. package/dist/commands/workflow/feature-base.js +60 -0
  258. package/dist/commands/workflow/issues.js +243 -15
  259. package/dist/commands/workflow/junit.js +137 -0
  260. package/dist/commands/workflow/ledgers.js +726 -112
  261. package/dist/commands/workflow/locks.js +150 -29
  262. package/dist/commands/workflow/loops.js +67 -0
  263. package/dist/commands/workflow/open-decision.js +199 -0
  264. package/dist/commands/workflow/plan-blocks.js +6 -0
  265. package/dist/commands/workflow/plans.js +1 -1
  266. package/dist/commands/workflow/prs.js +272 -16
  267. package/dist/commands/workflow/repo.js +1 -1
  268. package/dist/commands/workflow/run-facts.js +6 -0
  269. package/dist/commands/workflow/runs.js +747 -155
  270. package/dist/commands/workflow/runtime.js +8 -4
  271. package/dist/commands/workflow/status.js +259 -13
  272. package/dist/commands/workflow/step-table.js +41 -15
  273. package/dist/commands/workflow/steps.js +530 -26
  274. package/dist/commands/workflow/summary-findings.js +1 -1
  275. package/dist/commands/workflow/summary.js +289 -8
  276. package/dist/commands/workflow/tasks.js +294 -27
  277. package/dist/commands/workflow/tests-base.js +266 -0
  278. package/dist/commands/workflow/tests-changed.js +130 -56
  279. package/dist/commands/workflow/tests-jump.js +77 -0
  280. package/dist/commands/workflow/tests.js +608 -131
  281. package/dist/commands/workflow/tracker.js +920 -112
  282. package/dist/commands/workflow/workflows.js +80 -59
  283. package/dist/commands/workflow/worktrees.js +387 -58
  284. package/dist/install/cloud-env.js +32 -10
  285. package/dist/install/managed-block.js +101 -0
  286. package/dist/install/manifest.js +7 -1
  287. package/dist/install/modules/claude.js +6 -2
  288. package/dist/install/modules/cloud.js +73 -86
  289. package/dist/install/modules/codex.js +9 -2
  290. package/dist/install/modules/core.js +190 -27
  291. package/dist/install/modules/opencode.js +18 -23
  292. package/dist/install/network-allowlist.js +8 -3
  293. package/dist/install/project-docs.js +551 -0
  294. package/dist/install/template-copies.js +55 -5
  295. package/dist/install/write.js +117 -5
  296. package/dist/ledgers/journal.js +10 -8
  297. package/dist/ledgers/migrate.js +20 -9
  298. package/dist/ledgers/status.js +461 -8
  299. package/dist/ledgers/telemetry.js +71 -13
  300. package/dist/render/trackers.js +21 -12
  301. package/dist/shared/package-manager.js +7 -2
  302. package/dist/shared/settings.js +8 -0
  303. package/dist/shared/text.js +13 -0
  304. package/dist/tools/instructions-sources.js +1 -0
  305. package/dist/tools/instructions.js +97 -24
  306. package/package.json +23 -15
  307. package/.bkit/core/hooks/preflight-linear.sh +0 -73
  308. package/.bkit/shared/docs/architecture.md +0 -16
  309. package/.bkit/shared/docs/data-schema.md +0 -16
  310. package/.bkit/shared/docs/design.md +0 -38
  311. package/.bkit/shared/docs/noise.md +0 -20
  312. package/.bkit/shared/docs/observability.md +0 -22
  313. package/.bkit/shared/docs/security.md +0 -62
  314. package/.bkit/shared/docs/setup.md +0 -52
  315. package/.bkit/shared/docs/technology.md +0 -15
  316. /package/.bkit/templates/{.lintstagedrc.json → lintstagedrc.example.json} +0 -0
  317. /package/.bkit/templates/{.prettierignore → prettierignore.example} +0 -0
@@ -1,216 +1,1171 @@
1
1
  // --- Shell detection: identical in every host's guardrails hook (bkit renders it from
2
- // one source). Needs `fs` and `path` in scope; the host's own code above declares them.
2
+ // one source). Needs `fs` and `path` in scope; the host's own code above declares them. The
3
+ // git entry of `KNOWN_WRITERS` calls `parseGit` from `guardrails-deny.js`, spliced beside it.
3
4
 
4
5
  /** Wrappers that precede the real command; skipped when finding a command's program. */
5
- const CMD_WRAPPERS = new Set(["sudo", "env", "time", "nohup", "nice", "command", "exec", "xargs"]);
6
+ const CMD_WRAPPERS = new Set([
7
+ "sudo",
8
+ "env",
9
+ "time",
10
+ "nohup",
11
+ "nice",
12
+ "command",
13
+ "exec",
14
+ "xargs",
15
+ "timeout",
16
+ "stdbuf",
17
+ "builtin",
18
+ "noglob",
19
+ "doas",
20
+ "setsid",
21
+ "busybox",
22
+ ]);
6
23
 
7
- /** Split a command line into pipeline / list segments. */
8
- function shellSegments(cmd) {
9
- return String(cmd)
10
- .split(/\|\||&&|[|;\n]/)
11
- .map((s) => s.trim())
12
- .filter(Boolean);
24
+ /** Per program (wrappers too): the short letters and long options whose value is the next word. */
25
+ const VALUE_OPTIONS = {
26
+ grep: [
27
+ "ABCDdefm",
28
+ [
29
+ "--regexp",
30
+ "--file",
31
+ "--after-context",
32
+ "--before-context",
33
+ "--context",
34
+ "--max-count",
35
+ "--include",
36
+ "--exclude",
37
+ "--exclude-dir",
38
+ "--label",
39
+ ],
40
+ ],
41
+ rg: [
42
+ "ABCMTefgjmrt",
43
+ [
44
+ "--regexp",
45
+ "--file",
46
+ "--glob",
47
+ "--iglob",
48
+ "--type",
49
+ "--type-not",
50
+ "--max-count",
51
+ "--after-context",
52
+ "--before-context",
53
+ "--context",
54
+ "--replace",
55
+ "--max-depth",
56
+ "--threads",
57
+ ],
58
+ ],
59
+ ag: ["ABCGgm", ["--after", "--before", "--context", "--max-count", "--file-search-regex"]],
60
+ sed: ["efl", ["--expression", "--file", "--line-length"]],
61
+ awk: ["Ffv", ["--file", "--assign", "--field-separator"]],
62
+ sort: ["kotST", ["--key", "--output", "--field-separator"]],
63
+ cut: ["bcdf", ["--bytes", "--characters", "--delimiter", "--fields"]],
64
+ head: ["cn", ["--bytes", "--lines"]],
65
+ tail: ["cn", ["--bytes", "--lines"]],
66
+ scp: ["cFiJloPS", []],
67
+ rsync: ["e", ["--rsh"]],
68
+ xargs: ["InPLsdEaJ", []],
69
+ sudo: ["ughpCDRTUrt", []],
70
+ doas: ["uC", []],
71
+ nice: ["n", []],
72
+ env: ["uCS", []],
73
+ timeout: ["ks", []],
74
+ exec: ["a", []],
75
+ stdbuf: ["ioe", []],
76
+ };
77
+ VALUE_OPTIONS.egrep = VALUE_OPTIONS.fgrep = VALUE_OPTIONS.grep;
78
+
79
+ /** Whether option word `w` takes the next word as its value by `spec`, a `VALUE_OPTIONS` row. */
80
+ function takesValue(spec, w) {
81
+ if (!spec || w.includes("=")) return false;
82
+ if (w.startsWith("--")) return spec[1].includes(w);
83
+ // The first value letter of a cluster takes the rest of the word (`-uroot`), so the next
84
+ // word is its value only when that letter ends the cluster (`-Eu root`).
85
+ return [...w.slice(1)].findIndex((ch) => spec[0].includes(ch)) === w.length - 2;
13
86
  }
14
87
 
88
+ const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh"]);
89
+
90
+ /** A word that is safe to pass to a shell unquoted. */
91
+ const PLAIN_WORD_RE = /^[A-Za-z0-9_\/.,:=+@%-]+$/;
92
+
15
93
  /**
16
- * A segment's words: single / double quotes group and are dropped, a backslash escapes
17
- * the next character, an unquoted `#` at a word start ends the segment (comment). An
18
- * unterminated quote runs to the end of the segment.
94
+ * A host's command field as shell text: a string as is; an argv array with each element
95
+ * shell-quoted, so `["bash", "-lc", "git push -f"]` reads its script as one word. Else null.
19
96
  */
20
- function shellWords(seg) {
21
- const words = [];
22
- let cur = "";
23
- let started = false;
24
- let quote = "";
25
- for (let i = 0; i < seg.length; i++) {
26
- const ch = seg[i];
27
- if (quote) {
28
- if (ch === quote) quote = "";
29
- else if (ch === "\\" && quote === '"' && i + 1 < seg.length) cur += seg[++i];
30
- else cur += ch;
31
- continue;
32
- }
33
- if (ch === "#" && !started) break;
34
- if (ch === "'" || ch === '"') {
35
- quote = ch;
36
- started = true;
37
- } else if (ch === "\\" && i + 1 < seg.length) {
38
- cur += seg[++i];
39
- started = true;
40
- } else if (/\s/.test(ch)) {
41
- if (started) words.push(cur);
42
- cur = "";
43
- started = false;
44
- } else {
45
- cur += ch;
46
- started = true;
47
- }
48
- }
49
- if (started) words.push(cur);
50
- return words;
51
- }
52
-
53
- /** The words a segment runs: subshell punctuation, `VAR=val` and wrappers skipped. */
54
- function commandWords(seg) {
55
- const words = shellWords(seg.replace(/^(?:\$\(|[({`!\s])+/, "").replace(/[)}`\s]+$/, ""));
56
- let i = 0;
57
- while (
58
- i < words.length &&
59
- (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]) || CMD_WRAPPERS.has(words[i]))
60
- )
61
- i++;
62
- return words.slice(i);
97
+ function shellCommandText(command) {
98
+ if (typeof command === "string") return command;
99
+ if (!Array.isArray(command) || !command.every((w) => typeof w === "string")) return null;
100
+ return command
101
+ .map((w) => (PLAIN_WORD_RE.test(w) ? w : "'" + w.split("'").join("'\\''") + "'"))
102
+ .join(" ");
63
103
  }
64
104
 
65
- const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh"]);
66
-
67
105
  /**
68
- * Every command line the input runs: each list / pipeline segment, the script of a
69
- * `sh -c '…'`, and the body of each `$(…)` / backtick substitution, recursively.
106
+ * A shell's script source: `{ script }` for the operand of `-c`, `{ stdin: true }` when it reads
107
+ * stdin (no operand, `-s`, `-`), or `{ operand }` for a script file. Options are read the way
108
+ * bash reads them: every option word before the first operand, `-o` / `-O` take a value, and
109
+ * `--` or `-` ends the options.
70
110
  */
71
- function commandLines(cmd, depth = 0) {
72
- const lines = [];
73
- if (depth < 3) {
74
- for (const m of String(cmd).matchAll(/\$\(([^()]*)\)|`([^`]*)`/g)) {
75
- lines.push(...commandLines(m[1] ?? m[2] ?? "", depth + 1));
111
+ function shellScriptSource(words) {
112
+ let dashC = false;
113
+ let dashS = false;
114
+ let i = 1;
115
+ for (; i < words.length; i++) {
116
+ const w = words[i];
117
+ if (w === "--" || w === "-") {
118
+ i++;
119
+ break;
76
120
  }
121
+ if (!/^[-+]/.test(w)) break;
122
+ if (w.startsWith("--")) {
123
+ if (w === "--rcfile" || w === "--init-file") i++;
124
+ continue;
125
+ }
126
+ if (w[0] === "-" && w.includes("c")) dashC = true;
127
+ if (w[0] === "-" && w.includes("s")) dashS = true;
128
+ if (/[oO]/.test(w)) i++;
129
+ }
130
+ if (dashC) return { script: words[i] };
131
+ if (dashS || i >= words.length) return { stdin: true };
132
+ return { operand: words[i] };
133
+ }
134
+
135
+ /** The text a command prints when it only prints literal text (`echo`, `printf`, `cat <<`), else null. */
136
+ function literalOutput(item, words) {
137
+ const program = (words[0] || "").replace(/^.*\//, "");
138
+ if (program === "cat" && words.length === 1) {
139
+ if (item.heredoc) return item.heredoc.body;
140
+ if (item.hereString !== null) return item.hereString;
141
+ return null;
142
+ }
143
+ const args = words.slice(1).map((w) => w.replace(/\u0000/g, ""));
144
+ if (program === "echo") {
145
+ while (/^-[neE]+$/.test(args[0] || "")) args.shift();
146
+ return args.join(" ");
147
+ }
148
+ if (program === "printf" && args.length > 0) {
149
+ return args.length > 1 ? args.slice(1).join("\n") : args[0].replace(/\\n/g, "\n");
77
150
  }
78
- for (const seg of shellSegments(cmd)) {
79
- lines.push(seg);
80
- if (depth >= 3) continue;
81
- const words = commandWords(seg);
82
- const head = (words[0] || "").replace(/^.*\//, "");
83
- if (!SHELLS.has(head)) continue;
84
- const c = words.findIndex((w, i) => i > 0 && /^-[a-z]*c$/.test(w));
85
- if (c > 0 && words[c + 1]) lines.push(...commandLines(words[c + 1], depth + 1));
151
+ return null;
152
+ }
153
+
154
+ /** `text` cut to at most `limit` bytes of UTF-8, at the last whole character. */
155
+ function cutUtf8(text, limit) {
156
+ const buf = Buffer.from(text, "utf8");
157
+ if (buf.length <= limit) return text;
158
+ let end = limit;
159
+ // A continuation byte (10xxxxxx) at the cut belongs to a character that does not fit.
160
+ while (end > 0 && (buf[end] & 0xc0) === 0x80) end--;
161
+ return buf.subarray(0, end).toString("utf8");
162
+ }
163
+
164
+ /** Each `$(…)` and backtick body in an unquoted heredoc body, which the shell expands. */
165
+ function heredocSubstitutions(body) {
166
+ const out = [];
167
+ for (let i = 0; i < body.length; i++) {
168
+ if (body[i] === "\\") i++;
169
+ else if (body[i] === "$" && body[i + 1] === "(" && body[i + 2] !== "(") {
170
+ const end = matchParen(body, i + 2);
171
+ out.push(body.slice(i + 2, end));
172
+ i = end;
173
+ } else if (body[i] === "`") {
174
+ const end = body.indexOf("`", i + 1);
175
+ out.push(body.slice(i + 1, end < 0 ? body.length : end));
176
+ i = end < 0 ? body.length : end;
177
+ }
86
178
  }
87
- return lines;
179
+ return out;
88
180
  }
89
181
 
90
- /** The program a command line runs, path stripped (`/usr/bin/curl` -> `curl`). */
91
- function commandProgram(words) {
92
- return (words[0] || "").replace(/^.*\//, "");
182
+ /**
183
+ * The simple commands a shell text runs, quote-aware (`lexShell`): each list and pipeline
184
+ * member, the bodies of `$(…)`, backticks, subshells and `<(…)`, the script of a `sh -c '…'`,
185
+ * the words of `eval`, the string of `env -S`, the command of `find -exec`, a heredoc or
186
+ * here-string fed to a shell, the literal text `echo`, `printf` or `cat <<` pipes into a shell
187
+ * or a `<(…)` hands to a shell or `source`, and the substitutions of an unquoted heredoc,
188
+ * to depth 3. Each is `{ program, words, prefix, redirects, stdinFile, dyn, scope }`: `words` is
189
+ * the program and its arguments, `prefix` the assignments, wrappers and reserved words
190
+ * stripped ahead of it (so `sudo` stays visible), `program` the first word with its path
191
+ * stripped, `redirects` the output targets, `stdinFile` the `<` input file, `dyn` the
192
+ * words whose value is computed (`$VAR`, `$(…)`, a glob) and `scope` the ids of the
193
+ * subshell scopes it runs in, outermost first (a `cd` moves only its own scope). Text over
194
+ * 256 KiB of UTF-8 is cut at the last whole character first. Quoted text and data heredoc
195
+ * bodies are never commands. A text the parser cannot finish is judged on what was read.
196
+ * `st` (`newEvidence`) collects the analysis limits reached, the cut included.
197
+ */
198
+ function shellCommands(text, st = newEvidence()) {
199
+ const out = [];
200
+ let nextScope = 0;
201
+ const collect = (src, depth, outer) => {
202
+ const scope = [...outer, nextScope++];
203
+ let prev = null;
204
+ for (const item of lexShell(src, st, depth)) {
205
+ if (item.kind === "open") scope.push(nextScope++);
206
+ else if (item.kind === "close" && scope.length > outer.length + 1) scope.pop();
207
+ if (item.kind !== "cmd") continue;
208
+ const before = prev;
209
+ prev = item;
210
+ judge(item, item.words, depth, scope, before);
211
+ }
212
+ };
213
+ // One simple command, then the scripts it runs: a shell's script, `eval`'s words, `env -S`'s
214
+ // string, a `find -exec` command, and text piped or process-substituted into a shell.
215
+ const judge = (item, rawWords, depth, scope, before) => {
216
+ const { words, prefix } = stripCommandPrefix(rawWords);
217
+ const program = (words[0] || "").replace(/^.*\//, "");
218
+ out.push({
219
+ program,
220
+ words,
221
+ prefix,
222
+ redirects: item.redirects,
223
+ stdinFile: item.stdinFile,
224
+ dyn: [...item.dyn],
225
+ scope: [...scope],
226
+ });
227
+ if (item.heredoc && !item.heredoc.quoted && depth < EVIDENCE_LIMITS.depth) {
228
+ for (const body of heredocSubstitutions(item.heredoc.body)) collect(body, depth + 1, scope);
229
+ }
230
+ const scripts = [];
231
+ const split = prefix.findIndex((w, i) => w === "-S" && prefix.slice(0, i).includes("env"));
232
+ if (split >= 0) scripts.push([prefix[split + 1], ...words].join(" "));
233
+ // `eval` joins its words with spaces and runs the result as a script.
234
+ if (program === "eval")
235
+ scripts.push(
236
+ words
237
+ .slice(1)
238
+ .join(" ")
239
+ .replace(/\u0000/g, ""),
240
+ );
241
+ if (program === "find") {
242
+ for (let i = 1; i < words.length; i++) {
243
+ if (!/^-(exec|execdir|ok|okdir)$/.test(words[i])) continue;
244
+ let end = i + 1;
245
+ while (end < words.length && words[end] !== ";" && words[end] !== "+") end++;
246
+ // `{}` stands for each found path: a target the hook cannot name.
247
+ const run = { ...item, redirects: [], stdinFile: null, heredoc: null, hereString: null };
248
+ Object.assign(run, { piped: false, procSubs: [], dyn: new Set([...item.dyn, "{}"]) });
249
+ judge(run, words.slice(i + 1, end), depth, scope, null);
250
+ i = end;
251
+ }
252
+ }
253
+ if (SHELLS.has(program) || program === "source" || program === ".") {
254
+ const src = SHELLS.has(program) ? shellScriptSource(words) : { operand: words[1] };
255
+ if (src.script !== undefined && !item.dyn.has(src.script)) scripts.push(src.script);
256
+ else if (src.operand === "\u0000" && item.procSubs.length > 0) {
257
+ for (const body of item.procSubs) {
258
+ const inner = lexShell(body, st, depth + 1).filter((c) => c.kind === "cmd");
259
+ const last = inner[inner.length - 1];
260
+ const text = last && literalOutput(last, stripCommandPrefix(last.words).words);
261
+ if (text) scripts.push(text);
262
+ }
263
+ } else if (src.stdin) {
264
+ if (item.heredoc) scripts.push(item.heredoc.body);
265
+ else if (item.hereString !== null) scripts.push(item.hereString);
266
+ else if (item.piped && before) {
267
+ const text = literalOutput(before, stripCommandPrefix(before.words).words);
268
+ if (text) scripts.push(text);
269
+ }
270
+ }
271
+ }
272
+ if (!scripts.some(Boolean)) return;
273
+ if (depth >= EVIDENCE_LIMITS.depth) {
274
+ evidenceLimit(st, "depth", false);
275
+ return;
276
+ }
277
+ for (const script of scripts.filter(Boolean)) collect(script, depth + 1, scope);
278
+ };
279
+ const cut = cutUtf8(String(text), EVIDENCE_LIMITS.commandBytes);
280
+ if (cut.length < String(text).length) evidenceLimit(st, "command-size", false);
281
+ collect(cut, 0, []);
282
+ return out;
93
283
  }
94
284
 
95
285
  /**
96
- * True when some command line actually INVOKES curl or wget, including inside
286
+ * True when some parsed command (`shellCommands`) INVOKES curl or wget, including inside
97
287
  * `sh -c '…'`, `$(…)`, backticks and `( … )`.
98
288
  *
99
289
  * A token that only appears as an argument (`grep -n 'curl' file`) is not a program.
100
290
  */
101
- function usesFetch(cmd) {
102
- return commandLines(cmd).some((line) => {
103
- const p = commandProgram(commandWords(line));
104
- return p === "curl" || p === "wget";
105
- });
291
+ function usesFetch(cmds) {
292
+ return cmds.some((c) => c.program === "curl" || c.program === "wget");
106
293
  }
107
294
 
108
- /** Source-ish extensions: a redirect into one of these is plausibly a file edit. */
295
+ // --- Shell edit evidence -----------------------------------------------------
296
+ //
297
+ // Lexical evidence for "this command edits files", read only from the commands that match
298
+ // `KNOWN_WRITERS` or redirect output: ordered unique exact targets, an independent
299
+ // uncertainty set and at most one analysis limit. Nothing is executed and no file is read.
300
+
301
+ /** Source-ish extensions: a write into one of these is plausibly a file edit. */
109
302
  const SOURCE_EXT_RE =
110
- /\.(ts|tsx|js|jsx|cjs|mjs|json|md|sh|bash|py|rb|go|rs|java|css|scss|html|ya?ml|toml|sql)$/i;
303
+ /\.(ts|tsx|js|jsx|cjs|mjs|json|jsonl|md|sh|bash|py|rb|go|rs|java|css|scss|html|ya?ml|toml|sql)$/i;
304
+
305
+ /** Agent-read locations an edit reaches even without a source extension. */
306
+ const EVIDENCE_AGENT_READ_RE =
307
+ /(?:^|\/)(?:\.agents|\.bkit)\/|(?:^|\/)(?:AGENTS|CLAUDE|GEMINI)\.md$/;
308
+
309
+ const EVIDENCE_LIMITS = {
310
+ commandBytes: 256 * 1024,
311
+ depth: 3,
312
+ targets: 64,
313
+ targetChars: 160,
314
+ deadlineMs: 200,
315
+ };
111
316
 
112
317
  /**
113
- * Targets of every unquoted `>` / `>>` redirect in a command line. A `>` inside single
114
- * or double quotes is text (`rg 'a > b.ts'`), a backslash-escaped `>` is a literal, and
115
- * `2>`, `&>` and `>&` forms (fd redirects) are not file targets.
318
+ * The call context a hook passes: the effective directory, the workspace root, and `dirs`,
319
+ * the directories that locate the network allowlist, most authoritative first: the workspace
320
+ * roots (Cursor `workspace_roots`; Antigravity `workspacePaths`, carried over by its payload
321
+ * adapter), the payload `cwd` (Claude, Codex, Cursor), then the hook process's own cwd —
322
+ * which on Antigravity is the plugin dir, not the repo.
116
323
  */
117
- function redirectTargets(text) {
118
- const targets = [];
324
+ function hookContext(payload) {
325
+ const p = payload && typeof payload === "object" ? payload : {};
326
+ const roots = Array.isArray(p.workspace_roots) ? p.workspace_roots : [];
327
+ const root = roots.find((r) => typeof r === "string" && r) || undefined;
328
+ const cwd = typeof p.cwd === "string" && p.cwd ? p.cwd : undefined;
329
+ const dirs = [...roots, cwd, process.cwd()].filter((d) => typeof d === "string" && d !== "");
330
+ return { cwd, root, dirs };
331
+ }
332
+
333
+ /** This process's own CPU time in ms; scheduler contention does not inflate it. */
334
+ function cpuMs() {
335
+ const u = process.cpuUsage();
336
+ return (u.user + u.system) / 1000;
337
+ }
338
+
339
+ function newEvidence(ctx) {
340
+ const cwd = path.resolve((ctx && ctx.cwd) || process.cwd());
341
+ const root = path.resolve((ctx && ctx.root) || (ctx && ctx.cwd) || process.cwd());
342
+ return {
343
+ root,
344
+ baseCwd: cwd,
345
+ targets: [],
346
+ seen: new Set(),
347
+ uncertain: new Set(),
348
+ limit: null,
349
+ halted: false,
350
+ startWall: Date.now(),
351
+ startCpu: cpuMs(),
352
+ };
353
+ }
354
+
355
+ /** Record the first limit; `halt` stops all further analysis (a prefix is kept). */
356
+ function evidenceLimit(st, reason, halt = true) {
357
+ if (!st.limit) st.limit = reason;
358
+ if (halt) st.halted = true;
359
+ }
360
+
361
+ function evidenceExpired(st) {
362
+ if (st.halted) return true;
363
+ // The deadline counts the process's own CPU time, so machine load cannot trip it;
364
+ // a wall-clock backstop (4x) still bounds a stalled process.
365
+ if (
366
+ cpuMs() - st.startCpu > EVIDENCE_LIMITS.deadlineMs ||
367
+ Date.now() - st.startWall > EVIDENCE_LIMITS.deadlineMs * 4
368
+ ) {
369
+ evidenceLimit(st, "deadline");
370
+ return true;
371
+ }
372
+ return false;
373
+ }
374
+
375
+ function isQuietLiteral(literal) {
376
+ return (
377
+ /^\/(dev|tmp|var\/folders|var\/tmp)\//.test(literal) ||
378
+ /\.(log|bak|tmp|out|err|orig)$/i.test(literal)
379
+ );
380
+ }
381
+
382
+ function insideRoot(st, abs) {
383
+ const rel = path.relative(st.root, abs);
384
+ return rel !== ".." && !rel.startsWith(".." + path.sep) && !path.isAbsolute(rel);
385
+ }
386
+
387
+ /**
388
+ * Add one literal target. `force` skips the source-extension filter (in-place editors and
389
+ * formatters name files whatever their extension); a forced target that is a directory is
390
+ * uncertainty. A relative target under an unresolved directory is uncertainty, never a
391
+ * guessed path.
392
+ */
393
+ function addEvidenceTarget(st, literal, cwd, force) {
394
+ if (evidenceExpired(st) || !literal) return;
395
+ if (!force && !SOURCE_EXT_RE.test(literal) && !EVIDENCE_AGENT_READ_RE.test(literal)) return;
396
+ if (/\.(log|bak|tmp|out|err|orig)$/i.test(literal)) return;
397
+ if (cwd === null && !path.isAbsolute(literal)) {
398
+ st.uncertain.add("unresolved-directory");
399
+ return;
400
+ }
401
+ const abs = path.resolve(cwd === null ? path.sep : cwd, literal);
402
+ if (isQuietLiteral(literal) && !insideRoot(st, abs)) return;
403
+ const shown = insideRoot(st, abs) ? path.relative(st.root, abs).split(path.sep).join("/") : abs;
404
+ // A target reaches hook output: control characters, backticks, overlong names and
405
+ // directories become uncertainty instead of text.
406
+ if (
407
+ shown === "" ||
408
+ shown.length > EVIDENCE_LIMITS.targetChars ||
409
+ (force && fs.statSync(abs, { throwIfNoEntry: false })?.isDirectory()) ||
410
+ /[\u0000-\u001f\u007f-\u009f\u2028\u2029`]/.test(shown)
411
+ ) {
412
+ st.uncertain.add("unresolved-target");
413
+ return;
414
+ }
415
+ if (st.seen.has(shown)) return;
416
+ if (st.targets.length >= EVIDENCE_LIMITS.targets) {
417
+ evidenceLimit(st, "target-count");
418
+ return;
419
+ }
420
+ st.seen.add(shown);
421
+ st.targets.push(shown);
422
+ }
423
+
424
+ /** A target word: dynamic ones are uncertain when they could name a source file. */
425
+ function addWordTarget(st, cmd, text, cwd, force) {
426
+ if (cmd.dyn.includes(text)) {
427
+ if (force || SOURCE_EXT_RE.test(text.replace(/\u0000/g, ""))) {
428
+ if (!/^\$[A-Za-z_{][A-Za-z0-9_}]*$/.test(text) || force)
429
+ st.uncertain.add("unresolved-target");
430
+ }
431
+ return;
432
+ }
433
+ addEvidenceTarget(st, text, cwd, force);
434
+ }
435
+
436
+ // --- Lexer -------------------------------------------------------------------
437
+
438
+ /** Matching `)` of a `$(` whose body starts at `from`; quotes and nesting aware. */
439
+ function matchParen(text, from) {
440
+ let depth = 1;
119
441
  let quote = "";
120
- for (let i = 0; i < text.length; i++) {
442
+ const heredocs = [];
443
+ for (let i = from; i < text.length; i++) {
121
444
  const ch = text[i];
122
445
  if (quote) {
123
- if (ch === quote) quote = "";
124
- else if (ch === "\\" && quote === '"') i++;
446
+ if (ch === "\\" && quote === '"') i++;
447
+ else if (ch === quote) quote = "";
448
+ continue;
449
+ }
450
+ if (ch === "<" && text[i + 1] === "<" && text[i + 2] !== "<" && text[i + 2] !== "(") {
451
+ const m = /^<<(-?)[ \t]*(?:'([^'\n]*)'|"([^"\n]*)"|\\?([A-Za-z0-9_.-]+))/.exec(
452
+ text.slice(i, i + 200),
453
+ );
454
+ if (m) {
455
+ heredocs.push({ delim: m[2] ?? m[3] ?? m[4], strip: m[1] === "-" });
456
+ i += m[0].length - 1;
457
+ continue;
458
+ }
459
+ }
460
+ if (ch === "\n" && heredocs.length > 0) {
461
+ // Heredoc bodies are data: skip to the line holding each delimiter.
462
+ let pos = i + 1;
463
+ for (const h of heredocs) {
464
+ while (pos < text.length) {
465
+ let eol = text.indexOf("\n", pos);
466
+ if (eol < 0) eol = text.length;
467
+ let line = text.slice(pos, eol);
468
+ if (h.strip) line = line.replace(/^\t+/, "");
469
+ pos = eol + 1;
470
+ if (line === h.delim) break;
471
+ }
472
+ }
473
+ heredocs.length = 0;
474
+ i = pos - 2;
475
+ continue;
476
+ }
477
+ if (ch === "\\") i++;
478
+ else if (ch === "'" || ch === '"') quote = ch;
479
+ else if (ch === "(") depth++;
480
+ else if (ch === ")" && --depth === 0) return i;
481
+ }
482
+ return text.length;
483
+ }
484
+
485
+ /**
486
+ * Parse `text` into command items: `{ kind: "cmd", words, dyn, redirects, heredoc,
487
+ * stdinFile, hereString, piped }` plus `open` / `close` scope markers around subshells and
488
+ * substitutions. Quotes, escapes, comments, heredoc bodies and substitutions are honoured.
489
+ */
490
+ function lexShell(text, st, depth) {
491
+ const items = [];
492
+ let cmd = newLexCommand();
493
+ let cur = newLexWord();
494
+ let pending = null;
495
+ let pipedFromPrev = false;
496
+ const heredocs = [];
497
+
498
+ function newLexCommand() {
499
+ return {
500
+ kind: "cmd",
501
+ words: [],
502
+ dyn: new Set(),
503
+ redirects: [],
504
+ heredoc: null,
505
+ stdinFile: null,
506
+ hereString: null,
507
+ piped: false,
508
+ procSubs: [],
509
+ };
510
+ }
511
+ function newLexWord() {
512
+ return { t: "", started: false, dyn: false, quoted: false, digits: true };
513
+ }
514
+ function pushWord() {
515
+ if (!cur.started) return;
516
+ const word = cur;
517
+ cur = newLexWord();
518
+ if (word.dyn) cmd.dyn.add(word.t);
519
+ if (pending) {
520
+ const r = pending;
521
+ pending = null;
522
+ if (r.op === "<<") heredocs.push({ cmd, delim: word.t, quoted: word.quoted, strip: r.strip });
523
+ else if (r.op === "<") cmd.stdinFile = word.t;
524
+ else if (r.op === "<<<") cmd.hereString = word.t;
525
+ else if (r.op === ">" && !r.ignore) cmd.redirects.push(word.t);
526
+ else if (r.op === ">" && r.dup && !/^(\d+|-)$/.test(word.t)) cmd.redirects.push(word.t);
527
+ return;
528
+ }
529
+ cmd.words.push(word.t);
530
+ }
531
+ function endCommand(pipe) {
532
+ pushWord();
533
+ pending = null;
534
+ if (cmd.words.length > 0 || cmd.redirects.length > 0 || cmd.stdinFile || cmd.heredoc) {
535
+ cmd.piped = pipedFromPrev;
536
+ items.push(cmd);
537
+ }
538
+ pipedFromPrev = pipe;
539
+ cmd = newLexCommand();
540
+ }
541
+ function subshell(body) {
542
+ if (depth + 1 > EVIDENCE_LIMITS.depth) {
543
+ // Too deep a nesting skips that body only: the commands after it are still judged.
544
+ evidenceLimit(st, "depth", false);
545
+ return;
546
+ }
547
+ items.push({ kind: "open" });
548
+ items.push(...lexShell(body, st, depth + 1));
549
+ items.push({ kind: "close" });
550
+ }
551
+ function add(ch) {
552
+ cur.t += ch;
553
+ cur.started = true;
554
+ if (!/\d/.test(ch)) cur.digits = false;
555
+ }
556
+ function expansion(i) {
557
+ // text[i] === "$"; returns the index of the last consumed char.
558
+ const next = text[i + 1];
559
+ if (next === "(") {
560
+ const end = matchParen(text, i + 2);
561
+ if (text[i + 2] !== "(") subshell(text.slice(i + 2, end));
562
+ cur.dyn = true;
563
+ cur.t += "\u0000";
564
+ cur.started = true;
565
+ cur.digits = false;
566
+ return end;
567
+ }
568
+ if (next === "{") {
569
+ const end = text.indexOf("}", i + 2);
570
+ cur.dyn = true;
571
+ cur.t += text.slice(i, end < 0 ? text.length : end + 1);
572
+ cur.started = true;
573
+ cur.digits = false;
574
+ return end < 0 ? text.length : end;
575
+ }
576
+ if (next && /[A-Za-z0-9_@*#?!-]/.test(next)) cur.dyn = true;
577
+ add("$");
578
+ return i;
579
+ }
580
+ function backtick(i) {
581
+ const end = text.indexOf("`", i + 1);
582
+ subshell(text.slice(i + 1, end < 0 ? text.length : end));
583
+ cur.dyn = true;
584
+ cur.t += "\u0000";
585
+ cur.started = true;
586
+ cur.digits = false;
587
+ return end < 0 ? text.length : end;
588
+ }
589
+ function readHeredocBodies(from) {
590
+ let i = from;
591
+ for (const h of heredocs.splice(0)) {
592
+ const lines = [];
593
+ while (i < text.length) {
594
+ let eol = text.indexOf("\n", i);
595
+ if (eol < 0) eol = text.length;
596
+ const line = text.slice(i, eol);
597
+ i = Math.min(eol + 1, text.length);
598
+ if ((h.strip ? line.replace(/^\t+/, "") : line) === h.delim) break;
599
+ lines.push(line);
600
+ }
601
+ h.cmd.heredoc = { body: lines.join("\n"), quoted: h.quoted };
602
+ }
603
+ return i;
604
+ }
605
+
606
+ for (let i = 0; i < text.length; i++) {
607
+ if (i % 512 === 0 && evidenceExpired(st)) break;
608
+ const ch = text[i];
609
+ if (ch === "\\") {
610
+ if (text[i + 1] === "\n") {
611
+ i++;
612
+ continue;
613
+ }
614
+ if (i + 1 < text.length) add(text[++i]);
615
+ cur.quoted = true;
125
616
  continue;
126
617
  }
127
- if (ch === "'" || ch === '"') quote = ch;
128
- else if (ch === "\\") i++;
129
- else if (ch === ">") {
130
- const prev = text[i - 1] ?? "";
618
+ if (ch === "'") {
619
+ const end = text.indexOf("'", i + 1);
620
+ cur.t += text.slice(i + 1, end < 0 ? text.length : end);
621
+ cur.started = true;
622
+ cur.quoted = true;
623
+ cur.digits = false;
624
+ i = end < 0 ? text.length : end;
625
+ continue;
626
+ }
627
+ if (ch === '"') {
628
+ cur.started = true;
629
+ cur.quoted = true;
630
+ cur.digits = false;
131
631
  let j = i + 1;
132
- if (text[j] === ">") j++;
133
- const fdOrAmp = /[>&\d]/.test(prev);
134
- i = j - 1;
135
- if (fdOrAmp) continue;
136
- while (/\s/.test(text[j] ?? "")) j++;
137
- const open = text[j];
138
- let target = "";
139
- if (open === '"' || open === "'") {
140
- const end = text.indexOf(open, j + 1);
141
- target = end < 0 ? "" : text.slice(j + 1, end);
142
- i = end < 0 ? text.length : end;
632
+ for (; j < text.length && text[j] !== '"'; j++) {
633
+ const c = text[j];
634
+ if (c === "\\" && j + 1 < text.length) {
635
+ const n = text[j + 1];
636
+ if (n === "\n") j++;
637
+ else if (/["\\$`]/.test(n)) cur.t += text[++j];
638
+ else cur.t += c;
639
+ } else if (c === "$") j = expansion(j);
640
+ else if (c === "`") j = backtick(j);
641
+ else cur.t += c;
642
+ }
643
+ i = j;
644
+ continue;
645
+ }
646
+ if (ch === "`") {
647
+ i = backtick(i);
648
+ continue;
649
+ }
650
+ if (ch === "$") {
651
+ i = expansion(i);
652
+ continue;
653
+ }
654
+ if (ch === "#" && !cur.started) {
655
+ const eol = text.indexOf("\n", i);
656
+ i = eol < 0 ? text.length : eol - 1;
657
+ continue;
658
+ }
659
+ if (ch === "\n") {
660
+ endCommand(false);
661
+ i = readHeredocBodies(i + 1) - 1;
662
+ continue;
663
+ }
664
+ if (/\s/.test(ch)) {
665
+ pushWord();
666
+ continue;
667
+ }
668
+ if (ch === ";") {
669
+ endCommand(false);
670
+ continue;
671
+ }
672
+ if (ch === "&") {
673
+ if (text[i + 1] === "&") {
674
+ endCommand(false);
675
+ i++;
676
+ } else if (text[i + 1] === ">") {
677
+ pushWord();
678
+ pending = { op: ">", ignore: false };
679
+ i += text[i + 2] === ">" ? 2 : 1;
143
680
  } else {
144
- const m = /^[^\s;|&<>]+/.exec(text.slice(j));
145
- target = m ? m[0] : "";
146
- i = j + target.length - 1;
681
+ endCommand(false);
147
682
  }
148
- if (target.trim()) targets.push(target.trim());
683
+ continue;
149
684
  }
685
+ if (ch === "|") {
686
+ endCommand(true);
687
+ if (text[i + 1] === "|") {
688
+ pipedFromPrev = false;
689
+ i++;
690
+ } else if (text[i + 1] === "&") i++;
691
+ continue;
692
+ }
693
+ if (ch === "(" || ch === ")") {
694
+ endCommand(false);
695
+ items.push({ kind: ch === "(" ? "open" : "close" });
696
+ continue;
697
+ }
698
+ if ((ch === "<" || ch === ">") && text[i + 1] === "(") {
699
+ // Process substitution: its body runs, and the word is a path to its output.
700
+ const end = matchParen(text, i + 2);
701
+ subshell(text.slice(i + 2, end));
702
+ cmd.procSubs.push(text.slice(i + 2, end));
703
+ cur.dyn = true;
704
+ cur.t += "\u0000";
705
+ cur.started = true;
706
+ cur.digits = false;
707
+ i = end;
708
+ continue;
709
+ }
710
+ if (ch === ">" || ch === "<") {
711
+ let fd = false;
712
+ let stdoutFd = false;
713
+ if (cur.started && cur.digits && !cur.quoted) {
714
+ fd = true;
715
+ stdoutFd = ch === ">" && cur.t === "1";
716
+ cur = newLexWord();
717
+ } else pushWord();
718
+ let op = ch;
719
+ let strip = false;
720
+ let ignore = fd && !stdoutFd;
721
+ let dup = false;
722
+ let j = i + 1;
723
+ if (ch === ">") {
724
+ if (text[j] === ">" || text[j] === "|") j++;
725
+ else if (text[j] === "&") {
726
+ ignore = true;
727
+ dup = !fd || stdoutFd;
728
+ j++;
729
+ }
730
+ } else if (text[j] === "<") {
731
+ j++;
732
+ if (text[j] === "<") {
733
+ op = "<<<";
734
+ j++;
735
+ } else {
736
+ op = "<<";
737
+ if (text[j] === "-") {
738
+ strip = true;
739
+ j++;
740
+ }
741
+ }
742
+ } else if (text[j] === "&") {
743
+ op = ">";
744
+ ignore = true;
745
+ j++;
746
+ } else if (text[j] === ">") {
747
+ j++;
748
+ }
749
+ i = j - 1;
750
+ pending = { op, strip, ignore, dup };
751
+ continue;
752
+ }
753
+ if (!cur.started && ch === "~") cur.dyn = true;
754
+ if (ch === "*" || ch === "?" || ch === "[") cur.dyn = true;
755
+ add(ch);
150
756
  }
151
- return targets;
757
+ endCommand(false);
758
+ readHeredocBodies(text.length);
759
+ return items;
152
760
  }
153
761
 
762
+ // --- Command prefix ----------------------------------------------------------
763
+
764
+ const KEYWORD_PREFIX = new Set([
765
+ "then",
766
+ "do",
767
+ "else",
768
+ "elif",
769
+ "if",
770
+ "while",
771
+ "until",
772
+ "!",
773
+ "{",
774
+ "}",
775
+ "time",
776
+ ]);
777
+
154
778
  /**
155
- * Detect a shell command being used as an edit channel. Returns a list of human
156
- * descriptions, empty when the command edits nothing.
157
- *
158
- * Quiet on `> /dev/null`, `>> "$GITHUB_ENV"`, `mktemp` handoff files and log capture.
159
- * Only a redirect whose target both looks like a repo path AND carries a source
160
- * extension is reported.
779
+ * Strip assignments, wrappers (with their options, the arguments those options take and
780
+ * the `timeout` duration), reserved words and a `function NAME` head ahead of the real program. `prefix` is the
781
+ * stripped words.
782
+ */
783
+ function stripCommandPrefix(words) {
784
+ let i = 0;
785
+ while (
786
+ i < words.length &&
787
+ (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]) ||
788
+ CMD_WRAPPERS.has(words[i]) ||
789
+ KEYWORD_PREFIX.has(words[i]) ||
790
+ words[i] === "function")
791
+ ) {
792
+ const wrapper = words[i];
793
+ // `function NAME` heads a definition; its body is the command.
794
+ i += wrapper === "function" ? 2 : 1;
795
+ if (!CMD_WRAPPERS.has(wrapper)) continue;
796
+ while (i < words.length && words[i].startsWith("-") && words[i].length > 1) {
797
+ const opt = words[i++];
798
+ if (opt === "--") break;
799
+ if (takesValue(VALUE_OPTIONS[wrapper], opt)) i++;
800
+ }
801
+ if (wrapper === "timeout" && i < words.length) i++;
802
+ }
803
+ return { words: words.slice(i), prefix: words.slice(0, i) };
804
+ }
805
+
806
+ function resolveCwd(cwd, dir) {
807
+ if (cwd === null) return path.isAbsolute(dir) ? path.resolve(dir) : null;
808
+ return path.resolve(cwd, dir);
809
+ }
810
+
811
+ /**
812
+ * Positional operands of `args` (a command's words after its program): non-option words and
813
+ * everything after `--`, skipping the value of each option `spec` (`VALUE_OPTIONS`) names.
814
+ */
815
+ function operands(args, spec) {
816
+ const out = [];
817
+ for (let i = 0; i < args.length; i++) {
818
+ if (args[i] === "--") return out.concat(args.slice(i + 1));
819
+ if (args[i] === "-" || !args[i].startsWith("-")) out.push(args[i]);
820
+ else if (takesValue(spec, args[i])) i++;
821
+ }
822
+ return out;
823
+ }
824
+
825
+ // --- Known writers -------------------------------------------------------------
826
+
827
+ /**
828
+ * In-place operands of an editor call, or null when it does not edit in place. `flag(a)` reads
829
+ * one option word: `"in-place"`, `"script"` (the program is an option value, so the first
830
+ * operand is a file), `"script+1"` / `"value"` (the next word is that value) or null. Without
831
+ * a script option the first operand is the program.
161
832
  */
162
- function shellEditTargets(cmd) {
163
- const hits = [];
164
- const lines = commandLines(cmd);
165
- for (const line of lines) {
166
- const words = commandWords(line);
167
- const program = commandProgram(words);
168
- const args = words.slice(1);
169
- if ((program === "sed" || program === "perl") && args.some((w) => /^-i(?:\..*)?$/.test(w))) {
170
- hits.push("in-place sed/perl (-i)");
833
+ function inPlaceOperands(args, flag) {
834
+ let inPlace = false;
835
+ let script = false;
836
+ const pos = [];
837
+ for (let i = 0; i < args.length; i++) {
838
+ const a = args[i];
839
+ if (a === "--") {
840
+ pos.push(...args.slice(i + 1));
841
+ break;
171
842
  }
172
- if (program === "awk" && args.some((w, i) => w === "-i" && args[i + 1] === "inplace")) {
173
- hits.push("awk -i inplace");
843
+ if (!a.startsWith("-") || a === "-") {
844
+ pos.push(a);
845
+ continue;
174
846
  }
847
+ const kind = flag(a, args[i + 1]);
848
+ if (kind === "in-place") inPlace = true;
849
+ else if (kind === "in-place+1") {
850
+ inPlace = true;
851
+ i++;
852
+ } else if (kind === "script") script = true;
853
+ else if (kind === "script+1") {
854
+ script = true;
855
+ i++;
856
+ } else if (kind === "value") i++;
175
857
  }
176
- for (const text of [String(cmd), ...lines]) {
177
- for (const target of redirectTargets(text)) {
178
- // Scratch and env sinks — never a source edit.
179
- if (target.startsWith("$") || target.startsWith("&")) continue;
180
- if (/^\/(dev|tmp|var\/folders|var\/tmp)\//.test(target)) continue;
181
- if (/\.(log|bak|tmp|out|err|orig)$/i.test(target)) continue;
182
- if (!SOURCE_EXT_RE.test(target)) continue;
183
- hits.push(`redirect into ${target}`);
858
+ if (!inPlace) return null;
859
+ if (!script) pos.shift();
860
+ return pos;
861
+ }
862
+
863
+ /** sed / gsed: `-i[SUFFIX]` (BSD `-i ''`), `--in-place`; `-e` / `-f` supply the script. */
864
+ function sedFlag(a, next) {
865
+ if (/^--in-place(=|$)/.test(a)) return "in-place";
866
+ if (/^--(expression|file)=/.test(a)) return "script";
867
+ if (a === "--expression" || a === "--file") return "script+1";
868
+ const m = /^-[A-Za-z]*?([ief])/.exec(a);
869
+ if (!m) return null;
870
+ if (m[1] === "i") return a.endsWith("i") && next === "" ? "in-place+1" : "in-place";
871
+ return a.endsWith(m[1]) ? "script+1" : "script";
872
+ }
873
+
874
+ /** perl / ruby: `-i[SUFFIX]` in a cluster (`-pi`); `-e` / `-E` supply the script. */
875
+ function perlFlag(a) {
876
+ if (a.startsWith("--")) return null;
877
+ for (let k = 1; k < a.length; k++) {
878
+ const c = a[k];
879
+ if (c === "i") return "in-place";
880
+ if (c === "e" || c === "E") return k === a.length - 1 ? "script+1" : "script";
881
+ // `-l` / `-0` take only octal digits; the others take the rest of the cluster.
882
+ if (c === "l" || c === "0") k += a.slice(k + 1).match(/^[0-7]*/)[0].length;
883
+ else if ("IMmFx".includes(c)) return null;
884
+ }
885
+ return null;
886
+ }
887
+
888
+ /** awk / gawk: `-i inplace`; `-f` / `-e` supply the program; `-v`, `-F` take a value. */
889
+ function awkFlag(a, next) {
890
+ if (a === "-i") return next === "inplace" ? "in-place+1" : "value";
891
+ if (a === "-f" || a === "-e" || a === "--file" || a === "--source") return "script+1";
892
+ if (a === "-v" || a === "-F") return "value";
893
+ return null;
894
+ }
895
+
896
+ /** Operands a formatter writes when one of `flags` is given; `values` take the next word. */
897
+ function fixerTargets(args, flags, values) {
898
+ if (!args.some((a) => flags.includes(a))) return null;
899
+ const out = [];
900
+ for (let i = 0; i < args.length; i++) {
901
+ const a = args[i];
902
+ if (a === "--") {
903
+ out.push(...args.slice(i + 1));
904
+ break;
184
905
  }
906
+ if (!a.startsWith("-")) out.push(a);
907
+ else if (values.has(a)) i++;
185
908
  }
186
- return [...new Set(hits)];
909
+ return out;
187
910
  }
188
911
 
189
- /** Shared advisory string, identical on every host. */
190
- function shellEditAdvisory(hits) {
191
- return (
192
- `bkit guardrails: this command edits files through the shell (${hits.join("; ")}). The command is allowed. ` +
193
- "Pre-edit gates see only the edit and write tools, so a shell edit gets past every one of them.\n" +
194
- "Use the edit or write tool instead.\n" +
195
- "If this is one of the exceptions in .agents/rules.md (generating files from a script, a bulk mechanical rewrite, or appending a log line to your own step output file with `>>`), proceed."
196
- );
912
+ const PRETTIER_VALUE_OPTS = new Set([
913
+ "--config",
914
+ "--ignore-path",
915
+ "--plugin",
916
+ "--parser",
917
+ "--log-level",
918
+ "--cache-location",
919
+ "--cache-strategy",
920
+ "--stdin-filepath",
921
+ "--print-width",
922
+ "--tab-width",
923
+ ]);
924
+ const ESLINT_VALUE_OPTS = new Set([
925
+ "-c",
926
+ "--config",
927
+ "-f",
928
+ "--format",
929
+ "-o",
930
+ "--output-file",
931
+ "--ext",
932
+ "--rule",
933
+ "--parser",
934
+ "--plugin",
935
+ "--ignore-path",
936
+ "--ignore-pattern",
937
+ "--max-warnings",
938
+ "--cache-location",
939
+ "--fix-type",
940
+ ]);
941
+ const YQ_VALUE_OPTS = new Set([
942
+ "-o",
943
+ "--output-format",
944
+ "-p",
945
+ "--input-format",
946
+ "-I",
947
+ "--indent",
948
+ "-s",
949
+ "--split-exp",
950
+ "--front-matter",
951
+ ]);
952
+
953
+ /** yq: `-i` / `--inplace`; files follow the expression (`yq eval -i EXPR FILE`). */
954
+ function yqTargets(args) {
955
+ if (!args.some((a) => a === "-i" || /^--inplace(=|$)/.test(a))) return null;
956
+ const rest = ["e", "eval", "ea", "eval-all"].includes(args[0]) ? args.slice(1) : args;
957
+ let expression = false;
958
+ const pos = [];
959
+ for (let i = 0; i < rest.length; i++) {
960
+ const a = rest[i];
961
+ if (a === "--expression") {
962
+ expression = true;
963
+ i++;
964
+ } else if (a.startsWith("--expression=")) expression = true;
965
+ else if (!a.startsWith("-")) pos.push(a);
966
+ else if (YQ_VALUE_OPTS.has(a)) i++;
967
+ }
968
+ if (!expression) pos.shift();
969
+ return pos;
197
970
  }
198
971
 
199
- /** Repo-relative path of the install-written network allowlist every host's hook reads. */
200
- const NETWORK_ALLOWLIST_FILE = path.join(".bkit", "allowlist.json");
972
+ /** cp / mv: the target is an option value (`-t DIR`) the table does not name. */
973
+ function hasTargetDir(args) {
974
+ return args.some((a) => a === "-t" || a.startsWith("--target-directory"));
975
+ }
976
+
977
+ /** git: `apply` (its files are in the patch body) and `checkout -- <file>`, via `parseGit`. */
978
+ function gitTargets(args, words) {
979
+ const g = parseGit(words);
980
+ if (!g) return null;
981
+ if (g.sub === "apply") {
982
+ const report = ["--check", "--stat", "--numstat", "--summary"].some((o) => g.long.has(o));
983
+ return report && !g.long.has("--apply") ? null : "patch-body";
984
+ }
985
+ if (g.sub !== "checkout") return null;
986
+ const end = words.indexOf("--");
987
+ return end > 0 ? words.slice(end + 1) : null;
988
+ }
201
989
 
202
990
  /**
203
- * Directories a hook call names, most authoritative first: the workspace roots (Cursor
204
- * `workspace_roots`; Antigravity `workspacePaths`, carried over by its payload adapter),
205
- * the payload `cwd` (Claude, Codex, Cursor), then the hook process's own cwd — which on
206
- * Antigravity is the plugin dir, not the repo.
991
+ * The commands known to write files: the only ones the "may edit files" advice names. bkit
992
+ * owns the list; it is not extensible. Each entry is keyed by program and gives `form`, the
993
+ * flag or form that makes it write, and `read(args, words)`, which returns the target words,
994
+ * null when this call writes nothing, or a reason code when the targets are not on the command
995
+ * line. `force` names a target whatever its extension; otherwise only source and agent-read
996
+ * files count, so `cp a.png b.png` and `tee out.txt` stay quiet. The `>` and `>>` redirects
997
+ * of any command are writers too (`shellEditTargets`). Every other command is silent: script
998
+ * runners (`node`, `python3`) are never read. `prettier` and `eslint` are also matched behind
999
+ * `npx`, `pnpm exec`, `pnpm dlx`, `yarn` and `bunx` (`unwrapRunner`).
207
1000
  */
208
- function hookDirs(payload) {
209
- const p = payload && typeof payload === "object" ? payload : {};
210
- const roots = Array.isArray(p.workspace_roots) ? p.workspace_roots : [];
211
- return [...roots, p.cwd, process.cwd()].filter((d) => typeof d === "string" && d !== "");
1001
+ const KNOWN_WRITERS = {
1002
+ sed: { form: "-i", force: true, read: (args) => inPlaceOperands(args, sedFlag) },
1003
+ gsed: { form: "-i", force: true, read: (args) => inPlaceOperands(args, sedFlag) },
1004
+ perl: { form: "-i", force: true, read: (args) => inPlaceOperands(args, perlFlag) },
1005
+ ruby: { form: "-i", force: true, read: (args) => inPlaceOperands(args, perlFlag) },
1006
+ awk: { form: "-i inplace", force: true, read: (args) => inPlaceOperands(args, awkFlag) },
1007
+ gawk: { form: "-i inplace", force: true, read: (args) => inPlaceOperands(args, awkFlag) },
1008
+ tee: { form: "its file operands", force: false, read: (args) => operands(args) },
1009
+ cp: {
1010
+ form: "its last operand",
1011
+ force: false,
1012
+ read: (args) => {
1013
+ if (hasTargetDir(args)) return "unresolved-target";
1014
+ const ops = operands(args);
1015
+ return ops.length > 1 ? ops.slice(-1) : null;
1016
+ },
1017
+ },
1018
+ mv: {
1019
+ form: "both operands",
1020
+ force: false,
1021
+ read: (args) =>
1022
+ hasTargetDir(args) ? "unresolved-target" : operands(args).length > 1 ? operands(args) : null,
1023
+ },
1024
+ patch: {
1025
+ form: "any call but a dry run",
1026
+ read: (args) => (args.some((a) => /^(--dry-run|--check|-C)$/.test(a)) ? null : "patch-body"),
1027
+ },
1028
+ git: { form: "apply, checkout -- <file>", force: true, read: gitTargets },
1029
+ prettier: {
1030
+ form: "--write or -w",
1031
+ force: true,
1032
+ read: (args) => fixerTargets(args, ["--write", "-w"], PRETTIER_VALUE_OPTS),
1033
+ },
1034
+ eslint: {
1035
+ form: "--fix",
1036
+ force: true,
1037
+ read: (args) => fixerTargets(args, ["--fix"], ESLINT_VALUE_OPTS),
1038
+ },
1039
+ yq: { form: "-i or --inplace", force: true, read: yqTargets },
1040
+ dd: {
1041
+ form: "of=FILE",
1042
+ force: false,
1043
+ read: (args) => {
1044
+ const out = args.filter((a) => a.startsWith("of=")).map((a) => a.slice(3));
1045
+ return out.length > 0 ? out : null;
1046
+ },
1047
+ },
1048
+ };
1049
+
1050
+ /** The tool a package runner starts (`npx -y prettier@3 …` -> `prettier …`), else `words`. */
1051
+ function unwrapRunner(words) {
1052
+ const p = (words[0] || "").replace(/^.*\//, "");
1053
+ let rest;
1054
+ if (p === "npx" || p === "bunx") rest = words.slice(1);
1055
+ else if (p === "pnpm" && (words[1] === "exec" || words[1] === "dlx")) rest = words.slice(2);
1056
+ else if (p === "yarn")
1057
+ rest = ["exec", "dlx"].includes(words[1]) ? words.slice(2) : words.slice(1);
1058
+ else return words;
1059
+ let i = 0;
1060
+ while (i < rest.length && rest[i].startsWith("-")) i += /^(-p|--package)$/.test(rest[i]) ? 2 : 1;
1061
+ rest = rest.slice(i);
1062
+ return rest.length > 0 ? [rest[0].replace(/(.)@[^/]*$/, "$1"), ...rest.slice(1)] : rest;
1063
+ }
1064
+
1065
+ /** Record what one parsed command writes, from its redirects and `KNOWN_WRITERS`. */
1066
+ function addCommandEdits(st, c, cwd) {
1067
+ for (const t of c.redirects) if (!t.startsWith("&")) addWordTarget(st, c, t, cwd, false);
1068
+ const words = unwrapRunner(c.words);
1069
+ const program = (words[0] || "").replace(/^.*\//, "");
1070
+ if (!Object.hasOwn(KNOWN_WRITERS, program) || c.dyn.includes(words[0])) return;
1071
+ const writer = KNOWN_WRITERS[program];
1072
+ const hit = writer.read(words.slice(1), words);
1073
+ if (hit === null) return;
1074
+ // A reason code, or operands `xargs` extends from its input: no file can be named.
1075
+ if (typeof hit === "string") st.uncertain.add(hit);
1076
+ else if (c.prefix.some((w) => w.replace(/^.*\//, "") === "xargs"))
1077
+ st.uncertain.add("unresolved-target");
1078
+ else for (const w of hit) addWordTarget(st, c, w, cwd, writer.force);
1079
+ }
1080
+
1081
+ const EVIDENCE_REASONS = {
1082
+ "unresolved-directory": "the working directory is not a literal path",
1083
+ "unresolved-target": "a target path is computed, not literal, or a directory",
1084
+ "patch-body": "a patch names its files in its body, which is not read",
1085
+ };
1086
+ const LIMIT_REASONS = {
1087
+ "command-size": "the command is longer than 256 KiB",
1088
+ depth: "nesting is deeper than 3 levels",
1089
+ "target-count": "more than 64 targets",
1090
+ deadline: "analysis took longer than 200 ms",
1091
+ };
1092
+
1093
+ /**
1094
+ * Edit evidence for a shell command: `{ targets, uncertain, limit }`. Each parsed command
1095
+ * in `cmds` is matched against its redirects and `KNOWN_WRITERS`; nothing else counts.
1096
+ * `targets` are ordered unique paths (workspace-relative where inside it), `uncertain` lists
1097
+ * reason codes for writes whose targets cannot be named, and `limit` is the first analysis
1098
+ * limit reached (the targets found before it are kept). A literal `cd` moves the directory
1099
+ * relative targets resolve against, within its own subshell scope. A command that matches no
1100
+ * writer returns empty `targets` and `uncertain` and a null `limit`.
1101
+ *
1102
+ * Quiet on `> /dev/null`, `>> "$GITHUB_ENV"`, `mktemp` handoff files and log capture.
1103
+ * `st` is the `newEvidence(ctx)` state `shellCommands` filled while it parsed `cmds`.
1104
+ */
1105
+ function shellEditTargets(cmds, st) {
1106
+ // The directory of each scope: a scope starts in its parent's directory.
1107
+ const cwds = new Map();
1108
+ for (const c of cmds) {
1109
+ if (evidenceExpired(st)) break;
1110
+ let cwd = st.baseCwd;
1111
+ for (const id of c.scope) {
1112
+ if (cwds.has(id)) cwd = cwds.get(id);
1113
+ else cwds.set(id, cwd);
1114
+ }
1115
+ if (c.program === "cd" || c.program === "pushd" || c.program === "popd") {
1116
+ const arg = c.program === "popd" ? undefined : operands(c.words.slice(1))[0];
1117
+ const known = arg !== undefined && arg !== "-" && !c.dyn.includes(arg);
1118
+ cwds.set(c.scope[c.scope.length - 1], known ? resolveCwd(cwd, arg) : null);
1119
+ }
1120
+ addCommandEdits(st, c, cwd);
1121
+ }
1122
+ return { targets: st.targets, uncertain: [...st.uncertain], limit: st.limit };
212
1123
  }
213
1124
 
1125
+ /** True when the evidence has anything to report. */
1126
+ function hasEditEvidence(ev) {
1127
+ return Boolean(ev) && (ev.targets.length > 0 || ev.uncertain.length > 0 || Boolean(ev.limit));
1128
+ }
1129
+
1130
+ /** Shared advisory string, identical on every host. */
1131
+ function shellEditAdvisory(ev) {
1132
+ const named = ev.targets.length > 0;
1133
+ // The introduction counts against the host's response budget, so it names only as many
1134
+ // targets as fit a fixed character cap; the per-file blocks carry the full list.
1135
+ const shown = [];
1136
+ let used = 0;
1137
+ for (const t of ev.targets) {
1138
+ if (shown.length > 0 && used + JSON.stringify(t).length > 200) break;
1139
+ shown.push(JSON.stringify(t));
1140
+ used += JSON.stringify(t).length + 2;
1141
+ }
1142
+ const more = ev.targets.length - shown.length;
1143
+ const lines = [
1144
+ named
1145
+ ? `bkit guardrails: this command edits files through the shell (targets: ${shown.join(", ")}${more > 0 ? ` and ${more} more` : ""}). The command is allowed.`
1146
+ : "bkit guardrails: this command may edit files through the shell. The command is allowed.",
1147
+ "Pre-edit gates see only the edit and write tools, so a shell edit gets past every one of them.",
1148
+ ];
1149
+ if (ev.uncertain.length > 0) {
1150
+ lines.push(
1151
+ `Some targets cannot be determined (${ev.uncertain.map((r) => EVIDENCE_REASONS[r] || r).join("; ")}). The authoring rules in .bkit/authoring.md still apply to every file this command may write.`,
1152
+ );
1153
+ }
1154
+ if (ev.limit) {
1155
+ lines.push(
1156
+ `Analysis limit reached (${LIMIT_REASONS[ev.limit] || ev.limit}); the targets listed were found before it, and later ones were not examined.`,
1157
+ );
1158
+ }
1159
+ lines.push(
1160
+ "Use the edit or write tool instead.",
1161
+ "If this is one of the exceptions in .agents/rules.md (generating files from a script, a bulk mechanical rewrite, or appending a log line to your own step output file with `>>`), proceed.",
1162
+ );
1163
+ return lines.join("\n");
1164
+ }
1165
+
1166
+ /** Repo-relative path of the install-written network allowlist every host's hook reads. */
1167
+ const NETWORK_ALLOWLIST_FILE = path.join(".bkit", "allowlist.json");
1168
+
214
1169
  /**
215
1170
  * The network allowlist file for a hook call: walking up from each of `dirs` in turn,
216
1171
  * the first `.bkit/allowlist.json` found. A directory holding `.git` (the repo root)
@@ -234,7 +1189,7 @@ function findNetworkAllowlist(dirs) {
234
1189
  * Hosts come from `.bkit/allowlist.json`, the one install-written artifact carrying the
235
1190
  * resolved network allowlist (the shipped egress registry union the consumer's
236
1191
  * `allowed-domains`); every host's hook reads it, found from the hook call's
237
- * directories (`hookDirs`). There is NO hardcoded fallback list: absent or unreadable,
1192
+ * directories (`hookContext`). There is NO hardcoded fallback list: absent or unreadable,
238
1193
  * this returns empty and every host is treated as unknown.
239
1194
  */
240
1195
  function loadNetworkAllowlistBases(dirs) {
@@ -256,16 +1211,16 @@ function loadNetworkAllowlistBases(dirs) {
256
1211
  }
257
1212
 
258
1213
  /**
259
- * Pull the HOST out of every `http(s)://…` URL in a command.
1214
+ * The HOST of every `http(s)://…` URL in the words of the parsed curl / wget commands
1215
+ * (`usesFetch`); a URL in another command or inside its quoted text is not fetched.
260
1216
  *
261
1217
  * Strict: only an explicit scheme counts; a scheme-less token (`./deploy.sh`,
262
1218
  * `pkg.json`) is never read as a URL.
263
1219
  */
264
- function extractUrlHosts(cmd) {
1220
+ function extractUrlHosts(cmds) {
265
1221
  const hosts = [];
266
- const re = /\bhttps?:\/\/([^\s"'`\\|;&<>()]+)/gi;
267
- let m;
268
- while ((m = re.exec(cmd)) !== null) {
1222
+ const words = cmds.filter((c) => usesFetch([c])).flatMap((c) => c.words);
1223
+ for (const m of words.join(" ").matchAll(/\bhttps?:\/\/([^\s"'`\\|;&<>()]+)/gi)) {
269
1224
  // Authority ends at the first /, ? or #.
270
1225
  let authority = m[1].split(/[/?#]/)[0];
271
1226
  // Strip userinfo — `https://github.com@evil.tld/` is a request to evil.tld.
@@ -285,14 +1240,14 @@ function hostMatchesBase(host, base) {
285
1240
  }
286
1241
 
287
1242
  /**
288
- * True when EVERY URL in the command targets an allowlisted host.
1243
+ * True when EVERY URL the parsed commands fetch targets an allowlisted host.
289
1244
  *
290
- * Only each URL's host is consulted, never the rest of the command string (query
291
- * params, headers). No parseable URL, or any host off the list → false. `dirs` locate
292
- * the allowlist (`hookDirs`).
1245
+ * Only each URL's host is consulted, never the rest of the command (query params,
1246
+ * headers). No parseable URL, or any host off the list → false. `dirs` locate the
1247
+ * allowlist (`hookContext`).
293
1248
  */
294
- function curlWgetHostAllowed(cmd, dirs) {
295
- const hosts = extractUrlHosts(cmd);
1249
+ function curlWgetHostAllowed(cmds, dirs) {
1250
+ const hosts = extractUrlHosts(cmds);
296
1251
  if (hosts.length === 0) return false;
297
1252
  const bases = loadNetworkAllowlistBases(dirs);
298
1253
  return hosts.every((h) => [...bases].some((b) => hostMatchesBase(h, b)));