@cbartens/bkit 6.1.1 → 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 (313) 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 +42 -32
  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 +97 -36
  15. package/.bkit/core/.bkit/templates.md +162 -34
  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 +89 -37
  64. package/.bkit/core/engine/checks/after/index.ts +15 -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 +64 -11
  74. package/.bkit/core/engine/commands/ci/push-gate.ts +101 -43
  75. package/.bkit/core/engine/commands/install/install.ts +28 -25
  76. package/.bkit/core/engine/commands/install/uninstall.ts +42 -30
  77. package/.bkit/core/engine/commands/install/upgrade.ts +14 -2
  78. package/.bkit/core/engine/commands/land.ts +2 -3
  79. package/.bkit/core/engine/commands/lib.ts +394 -39
  80. package/.bkit/core/engine/commands/registry.ts +1 -1
  81. package/.bkit/core/engine/commands/workflow/branches.ts +351 -78
  82. package/.bkit/core/engine/commands/workflow/challenge.ts +63 -14
  83. package/.bkit/core/engine/commands/workflow/context.ts +71 -10
  84. package/.bkit/core/engine/commands/workflow/counters.ts +298 -23
  85. package/.bkit/core/engine/commands/workflow/decisions.ts +260 -125
  86. package/.bkit/core/engine/commands/workflow/disk.ts +2 -1
  87. package/.bkit/core/engine/commands/workflow/feature-base.ts +66 -0
  88. package/.bkit/core/engine/commands/workflow/issues.ts +312 -17
  89. package/.bkit/core/engine/commands/workflow/junit.ts +204 -0
  90. package/.bkit/core/engine/commands/workflow/ledgers.ts +904 -99
  91. package/.bkit/core/engine/commands/workflow/locks.ts +186 -29
  92. package/.bkit/core/engine/commands/workflow/loops.ts +87 -0
  93. package/.bkit/core/engine/commands/workflow/open-decision.ts +251 -0
  94. package/.bkit/core/engine/commands/workflow/plan-blocks.ts +8 -0
  95. package/.bkit/core/engine/commands/workflow/plans.ts +1 -1
  96. package/.bkit/core/engine/commands/workflow/prs.ts +311 -16
  97. package/.bkit/core/engine/commands/workflow/repo.ts +1 -1
  98. package/.bkit/core/engine/commands/workflow/run-facts.ts +6 -0
  99. package/.bkit/core/engine/commands/workflow/runs.ts +877 -174
  100. package/.bkit/core/engine/commands/workflow/runtime.ts +12 -4
  101. package/.bkit/core/engine/commands/workflow/status.ts +324 -11
  102. package/.bkit/core/engine/commands/workflow/step-table.ts +41 -15
  103. package/.bkit/core/engine/commands/workflow/steps.ts +604 -29
  104. package/.bkit/core/engine/commands/workflow/summary-findings.ts +1 -1
  105. package/.bkit/core/engine/commands/workflow/summary.ts +314 -8
  106. package/.bkit/core/engine/commands/workflow/tasks.ts +400 -27
  107. package/.bkit/core/engine/commands/workflow/tests-base.ts +319 -0
  108. package/.bkit/core/engine/commands/workflow/tests-changed.ts +138 -74
  109. package/.bkit/core/engine/commands/workflow/tests-jump.ts +93 -0
  110. package/.bkit/core/engine/commands/workflow/tests.ts +815 -182
  111. package/.bkit/core/engine/commands/workflow/tracker.ts +1134 -137
  112. package/.bkit/core/engine/commands/workflow/workflows.ts +100 -72
  113. package/.bkit/core/engine/commands/workflow/worktrees.ts +421 -57
  114. package/.bkit/core/engine/install/cloud-env.ts +38 -10
  115. package/.bkit/core/engine/install/managed-block.ts +105 -0
  116. package/.bkit/core/engine/install/manifest.ts +7 -1
  117. package/.bkit/core/engine/install/modules/claude.ts +6 -2
  118. package/.bkit/core/engine/install/modules/cloud.ts +84 -95
  119. package/.bkit/core/engine/install/modules/codex.ts +10 -2
  120. package/.bkit/core/engine/install/modules/core.ts +148 -14
  121. package/.bkit/core/engine/install/modules/opencode.ts +18 -23
  122. package/.bkit/core/engine/install/network-allowlist.ts +8 -3
  123. package/.bkit/core/engine/install/project-docs.ts +650 -0
  124. package/.bkit/core/engine/install/template-copies.ts +58 -5
  125. package/.bkit/core/engine/install/write.ts +128 -7
  126. package/.bkit/core/engine/ledgers/journal.ts +18 -10
  127. package/.bkit/core/engine/ledgers/migrate.ts +20 -8
  128. package/.bkit/core/engine/ledgers/status.ts +604 -8
  129. package/.bkit/core/engine/ledgers/telemetry.ts +115 -13
  130. package/.bkit/core/engine/render/trackers.ts +3 -1
  131. package/.bkit/core/engine/shared/package-manager.ts +7 -3
  132. package/.bkit/core/engine/shared/settings.ts +12 -1
  133. package/.bkit/core/engine/shared/text.ts +14 -0
  134. package/.bkit/core/engine/tools/instructions-sources.ts +1 -0
  135. package/.bkit/core/engine/tools/instructions.ts +116 -20
  136. package/.bkit/core/hooks/antigravity-hook.js +20 -4
  137. package/.bkit/core/hooks/gateguard-edit-payload.js +8 -5
  138. package/.bkit/core/hooks/gateguard-engine.js +249 -23
  139. package/.bkit/core/hooks/guardrails-deny.js +167 -0
  140. package/.bkit/core/hooks/guardrails-read.js +3 -3
  141. package/.bkit/core/hooks/guardrails-shell.js +1122 -167
  142. package/.bkit/core/hooks/guardrails-tiers.js +247 -176
  143. package/.bkit/core/hooks/preflight-tracker.sh +219 -0
  144. package/.bkit/core/prompts/bkit-audit-generate.md +23 -6
  145. package/.bkit/core/prompts/bkit-build-challenge-1.md +5 -4
  146. package/.bkit/core/prompts/bkit-build-challenge-2.md +6 -5
  147. package/.bkit/core/prompts/bkit-build-install-skills.md +2 -2
  148. package/.bkit/core/prompts/bkit-build-plan-convert.md +21 -7
  149. package/.bkit/core/prompts/bkit-build-plan-current.md +5 -4
  150. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +22 -17
  151. package/.bkit/core/prompts/bkit-build-plan-tasks.md +16 -12
  152. package/.bkit/core/prompts/bkit-build-plan-tests.md +14 -10
  153. package/.bkit/core/prompts/bkit-build-plan-verify.md +21 -8
  154. package/.bkit/core/prompts/bkit-debug-abort-handover.md +10 -5
  155. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +22 -6
  156. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +19 -3
  157. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +22 -6
  158. package/.bkit/core/prompts/bkit-debug-failure-soak.md +10 -7
  159. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +3 -3
  160. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +4 -4
  161. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +3 -3
  162. package/.bkit/core/prompts/bkit-design-generate.md +6 -4
  163. package/.bkit/core/prompts/bkit-design-organise.md +4 -3
  164. package/.bkit/core/prompts/bkit-design-review-1.md +5 -4
  165. package/.bkit/core/prompts/bkit-design-review-2.md +6 -5
  166. package/.bkit/core/prompts/bkit-design-spike.md +4 -3
  167. package/.bkit/core/prompts/bkit-design-update.md +6 -4
  168. package/.bkit/core/prompts/bkit-plan-generate.md +35 -14
  169. package/.bkit/core/prompts/bkit-plan-review-1.md +9 -7
  170. package/.bkit/core/prompts/bkit-plan-review-2.md +9 -7
  171. package/.bkit/core/prompts/bkit-plan-scope-check.md +8 -6
  172. package/.bkit/core/prompts/bkit-plan-update.md +22 -8
  173. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +11 -8
  174. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +9 -5
  175. package/.bkit/core/prompts/bkit-ship-update-docs.md +26 -4
  176. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +3 -3
  177. package/.bkit/core/prompts/bkit-utility-update-decisions.md +10 -7
  178. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +8 -5
  179. package/.bkit/core/prompts/bkit-utility-update-documentation.md +31 -7
  180. package/.bkit/core/prompts/bkit-utility-update-failures.md +8 -5
  181. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +10 -7
  182. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +4 -4
  183. package/.bkit/core/prompts/bkit-utility-update-tracker.md +4 -4
  184. package/.bkit/core/workflows/bkit-auto.md +23 -11
  185. package/.bkit/core/workflows/bkit-build.md +331 -100
  186. package/.bkit/core/workflows/bkit-debug.md +135 -64
  187. package/.bkit/core/workflows/bkit-design.md +58 -32
  188. package/.bkit/core/workflows/bkit-plan.md +73 -45
  189. package/.bkit/core/workflows/bkit-ship.md +233 -167
  190. package/.bkit/shared/.agents/plugins/bkit/hooks.json +1 -1
  191. package/.bkit/shared/.bkit/.env.example +5 -0
  192. package/.bkit/shared/.claude/bkit-cloud.md +7 -7
  193. package/.bkit/shared/.claude/settings.json +5 -1
  194. package/.bkit/shared/.cursor/bkit-cloud.md +1 -1
  195. package/.bkit/shared/.cursor/hooks.json +1 -1
  196. package/.bkit/shared/.opencode/opencode.json +11 -2
  197. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +27 -0
  198. package/.bkit/templates/.cursor/Dockerfile +7 -7
  199. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-idea.yml +1 -1
  200. package/.bkit/templates/.github/dependabot.yml +5 -0
  201. package/.bkit/templates/.github/renovate.json5 +5 -3
  202. package/.bkit/templates/.github/workflows/bkit-ci.yml +11 -11
  203. package/.bkit/templates/.github/workflows/bkit-cloud.yml +525 -161
  204. package/.bkit/templates/.github/workflows/bkit-renovate.yml +2 -2
  205. package/.bkit/templates/.husky/pre-push +123 -6
  206. package/.bkit/templates/context/bkit-serena.md +1 -1
  207. package/.bkit/templates/docs/architecture.md +98 -0
  208. package/.bkit/templates/docs/capabilities.md +33 -37
  209. package/.bkit/templates/docs/components.md +142 -0
  210. package/.bkit/templates/docs/data-schema.md +87 -0
  211. package/.bkit/{shared → templates}/docs/deployments.md +128 -142
  212. package/.bkit/templates/docs/design.md +117 -0
  213. package/.bkit/templates/docs/noise.md +54 -0
  214. package/.bkit/templates/docs/observability.md +99 -0
  215. package/.bkit/templates/docs/security.md +137 -0
  216. package/.bkit/templates/docs/setup.md +93 -0
  217. package/.bkit/templates/docs/technology.md +70 -0
  218. package/.bkit/{shared → templates}/docs/testing.md +200 -87
  219. package/.bkit/templates/scripts/ci/bkit-machine-lock.sh +511 -103
  220. package/.bkit/templates/scripts/ci/bkit-test-awake.mjs +228 -35
  221. package/.bkit/templates/scripts/ci/bkit-test-awake.test.mjs +270 -2
  222. package/.bkit/templates/scripts/graphify/bkit-graphify-graphml.py +1 -1
  223. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +92 -63
  224. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +59 -11
  225. package/.bkit/templates/slop-scan.config.json +2 -0
  226. package/CHANGELOG.md +64 -0
  227. package/DETAILS.md +24 -19
  228. package/README.md +1 -1
  229. package/dist/checks/after/auth.js +114 -46
  230. package/dist/checks/after/github.js +77 -35
  231. package/dist/checks/after/index.js +12 -3
  232. package/dist/checks/after/tools.js +224 -1
  233. package/dist/checks/before/files.js +59 -1
  234. package/dist/checks/before/index.js +7 -1
  235. package/dist/checks/status-holes.js +20 -21
  236. package/dist/checks/tips/catalogue.js +99 -10
  237. package/dist/checks/tips/detect.js +35 -3
  238. package/dist/checks/tips/index.js +1 -1
  239. package/dist/cli.js +13 -13
  240. package/dist/commands/ci/ci.js +56 -12
  241. package/dist/commands/ci/push-gate.js +79 -44
  242. package/dist/commands/install/install.js +23 -22
  243. package/dist/commands/install/uninstall.js +36 -30
  244. package/dist/commands/install/upgrade.js +10 -2
  245. package/dist/commands/land.js +2 -3
  246. package/dist/commands/lib.js +323 -25
  247. package/dist/commands/workflow/branches.js +312 -72
  248. package/dist/commands/workflow/challenge.js +66 -13
  249. package/dist/commands/workflow/context.js +46 -10
  250. package/dist/commands/workflow/counters.js +231 -23
  251. package/dist/commands/workflow/decisions.js +221 -106
  252. package/dist/commands/workflow/disk.js +2 -1
  253. package/dist/commands/workflow/feature-base.js +60 -0
  254. package/dist/commands/workflow/issues.js +243 -15
  255. package/dist/commands/workflow/junit.js +137 -0
  256. package/dist/commands/workflow/ledgers.js +726 -112
  257. package/dist/commands/workflow/locks.js +150 -29
  258. package/dist/commands/workflow/loops.js +67 -0
  259. package/dist/commands/workflow/open-decision.js +199 -0
  260. package/dist/commands/workflow/plan-blocks.js +6 -0
  261. package/dist/commands/workflow/plans.js +1 -1
  262. package/dist/commands/workflow/prs.js +272 -16
  263. package/dist/commands/workflow/repo.js +1 -1
  264. package/dist/commands/workflow/run-facts.js +6 -0
  265. package/dist/commands/workflow/runs.js +747 -155
  266. package/dist/commands/workflow/runtime.js +8 -4
  267. package/dist/commands/workflow/status.js +259 -13
  268. package/dist/commands/workflow/step-table.js +41 -15
  269. package/dist/commands/workflow/steps.js +530 -26
  270. package/dist/commands/workflow/summary-findings.js +1 -1
  271. package/dist/commands/workflow/summary.js +289 -8
  272. package/dist/commands/workflow/tasks.js +294 -27
  273. package/dist/commands/workflow/tests-base.js +266 -0
  274. package/dist/commands/workflow/tests-changed.js +130 -56
  275. package/dist/commands/workflow/tests-jump.js +77 -0
  276. package/dist/commands/workflow/tests.js +608 -131
  277. package/dist/commands/workflow/tracker.js +920 -112
  278. package/dist/commands/workflow/workflows.js +80 -59
  279. package/dist/commands/workflow/worktrees.js +387 -58
  280. package/dist/install/cloud-env.js +32 -10
  281. package/dist/install/managed-block.js +101 -0
  282. package/dist/install/manifest.js +7 -1
  283. package/dist/install/modules/claude.js +6 -2
  284. package/dist/install/modules/cloud.js +73 -86
  285. package/dist/install/modules/codex.js +9 -2
  286. package/dist/install/modules/core.js +133 -14
  287. package/dist/install/modules/opencode.js +18 -23
  288. package/dist/install/network-allowlist.js +8 -3
  289. package/dist/install/project-docs.js +551 -0
  290. package/dist/install/template-copies.js +55 -5
  291. package/dist/install/write.js +117 -5
  292. package/dist/ledgers/journal.js +10 -8
  293. package/dist/ledgers/migrate.js +20 -9
  294. package/dist/ledgers/status.js +461 -8
  295. package/dist/ledgers/telemetry.js +71 -13
  296. package/dist/render/trackers.js +3 -1
  297. package/dist/shared/package-manager.js +7 -2
  298. package/dist/shared/settings.js +8 -0
  299. package/dist/shared/text.js +13 -0
  300. package/dist/tools/instructions-sources.js +1 -0
  301. package/dist/tools/instructions.js +97 -24
  302. package/package.json +22 -15
  303. package/.bkit/core/hooks/preflight-linear.sh +0 -73
  304. package/.bkit/shared/docs/architecture.md +0 -16
  305. package/.bkit/shared/docs/data-schema.md +0 -16
  306. package/.bkit/shared/docs/design.md +0 -38
  307. package/.bkit/shared/docs/noise.md +0 -20
  308. package/.bkit/shared/docs/observability.md +0 -22
  309. package/.bkit/shared/docs/security.md +0 -62
  310. package/.bkit/shared/docs/setup.md +0 -52
  311. package/.bkit/shared/docs/technology.md +0 -15
  312. /package/.bkit/templates/{.lintstagedrc.json → lintstagedrc.example.json} +0 -0
  313. /package/.bkit/templates/{.prettierignore → prettierignore.example} +0 -0
@@ -7,8 +7,9 @@
7
7
  // - "byte-equal-text" : delete only if unchanged since bkit wrote it (canonicalHashes)
8
8
  // 2. package.json: the `bkit` install-state block (full/core uninstall). Scripts and
9
9
  // devDeps are the consumer's — the bkit:gate:* names included — and are left alone.
10
- // 2b. docs/ (full/core uninstall): bkit's managed block stripped from every installed
11
- // `docs/*.md`, the owned `docs/templates/bkit-*.md` deleted.
10
+ // 2b. docs/ (full/core uninstall): the owned `docs/templates/bkit-*.md` deleted. The ten
11
+ // project documents (`docs/architecture.md` …) and their `Project Documents` index rows
12
+ // belong to the project and stay.
12
13
  // 3. .agents/ mirror files (bkit-prefix .md files in .claude/ .cursor/)
13
14
  //
14
15
  // Flags:
@@ -28,15 +29,16 @@ import { getInstallManifest, ISSUE_TRACKERS, } from "../../install/manifest.js";
28
29
  import { OPENCODE_PROVIDERS } from "../../shared/egress.js";
29
30
  import { parseJson } from "../../shared/json.js";
30
31
  import { hashFile, isConsumerModified, mergeCanonicalHashes, readBkitVersion, writeBkitVersion, } from "../../install/version-file.js";
31
- import { getBkitDocsRoot, getPkgRoot, getSharedRoot, findTemplateSource, TEMPLATE_COPIES_DIR, } from "../../shared/package-roots.js";
32
+ import { getBkitDocsRoot, getPkgRoot, findTemplateSource, TEMPLATE_COPIES_DIR, } from "../../shared/package-roots.js";
32
33
  import { PAYLOAD_LINKS } from "../../install/payload-links.js";
33
34
  import { removeOpencodeProviderBlock, renderOpencodeAgentsCommands, renderOpencodeJson, } from "../../install/modules/opencode.js";
34
35
  import { applyModelOverrides, buildOpencodeModelLookup, parseEffortMap, } from "../../render/models.js";
35
36
  import { readInstallingVersion } from "../../shared/package-json.js";
36
37
  import { readBkitConfig } from "../../shared/settings.js";
37
38
  import { SEEDED_BKIT_DEFAULTS } from "../../install/modules/core.js";
38
- import { CLAUDE_CLOUD_RELPATH, CODEX_CLOUD_RELPATH, CURSOR_CLOUD_RELPATH, resolveClaudeDerivedAllows, } from "../../install/cloud-env.js";
39
+ import { CLAUDE_CLOUD_RELPATH, CODEX_CLOUD_RELPATH, CURSOR_CLOUD_RELPATH, } from "../../install/cloud-env.js";
39
40
  import { LOG_PREFIX, setLogPrefix } from "../../shared/log-prefix.js";
41
+ import { isOpencodeSubstringFetchKey, redactUrlParts } from "../../checks/before/files.js";
40
42
  import { unusedTrackerMcpServers } from "../../checks/before/mcp.js";
41
43
  // ---------------------------------------------------------------------------
42
44
  // stripTier2JsonScope — remove bkit-owned JSON scope from consumer doc (BAR-167 Phase 1)
@@ -263,26 +265,6 @@ const CORE_TEMPLATE_DOCTRINE = [
263
265
  // Retired `.bkit/lite.md` (5.2.5 – 6.0.0), for an install never upgraded since.
264
266
  { path: ".bkit/lite.md", format: "markered-text", module: "core" },
265
267
  ];
266
- /**
267
- * The top-level `docs/*.md` the core payload pass installs: each carries bkit's managed
268
- * block (`bkit:start` / `bkit:end`, managed marker inside), so uninstall strips the block
269
- * and keeps the consumer's content, exactly like `.agents/*.md`. The payload's
270
- * `shared/docs/` holds only these block docs; `docs/capabilities.md` is a template
271
- * (copied, never installed) and is left alone.
272
- */
273
- function coreDocEntries() {
274
- const dir = path.join(getSharedRoot(), "docs");
275
- if (!fs.existsSync(dir))
276
- return [];
277
- return fs
278
- .readdirSync(dir, { withFileTypes: true })
279
- .filter((e) => e.isFile() && e.name.endsWith(".md"))
280
- .map((e) => ({
281
- path: path.join("docs", e.name),
282
- format: "markered-text",
283
- module: "core",
284
- }));
285
- }
286
268
  /** Prefix of the bkit-owned files under `docs/templates/`; uninstall deletes them whole. */
287
269
  const DOCS_TEMPLATES_DIR = path.join("docs", "templates");
288
270
  const isOwnedDocsTemplate = (name) => name.startsWith("bkit-") && name.endsWith(".md");
@@ -294,7 +276,7 @@ export function buildDecisionTable(modules, ctx) {
294
276
  : modules;
295
277
  const entries = [
296
278
  ...getInstallManifest(moduleList),
297
- ...(moduleList.includes("core") ? [...CORE_TEMPLATE_DOCTRINE, ...coreDocEntries()] : []),
279
+ ...(moduleList.includes("core") ? CORE_TEMPLATE_DOCTRINE : []),
298
280
  ];
299
281
  // The hash of every owned file as bkit last wrote it.
300
282
  const versionFilePath = path.join(ctx.cwd, ".bkit", "version");
@@ -495,6 +477,9 @@ export async function runUninstall(modules, ctx) {
495
477
  return result;
496
478
  }
497
479
  }
480
+ // The grants bkit wrote into `.claude/settings.json`, read before the loop below deletes
481
+ // `.bkit/version` on a full or core uninstall.
482
+ const claudeAllowDerived = readBkitVersion(path.join(ctx.cwd, ".bkit", "version"))?.claudeAllowDerived ?? [];
498
483
  const table = buildDecisionTable(moduleList, ctx);
499
484
  result.decisions = table;
500
485
  if (ctx.dryRun) {
@@ -567,19 +552,18 @@ export async function runUninstall(modules, ctx) {
567
552
  // the resolved network allowlist and `mcp__…` grants per declared MCP
568
553
  // server (enrichClaudeSettingsAllows). Stripping
569
554
  // against the RAW template leaves those grants behind as if the consumer
570
- // had added them. Recompute the same set — the very function that produced
571
- // them — and treat it as part of the template, exactly as the opencode.json
572
- // sentinel render above does.
555
+ // had added them. `.bkit/version` records exactly the rows install wrote
556
+ // (`claudeAllowDerived`); treat them as part of the template. A derived-looking
557
+ // row the record lacks has unknown ownership: it stays and is listed for review.
573
558
  if (summary.file === path.join(".claude", "settings.json")) {
574
559
  const perms = templateDoc.permissions;
575
560
  if (perms !== null && typeof perms === "object" && !Array.isArray(perms)) {
576
561
  const permsObj = perms;
577
562
  const allow = permsObj.allow;
578
563
  if (Array.isArray(allow)) {
579
- const enriched = resolveClaudeDerivedAllows(ctx.cwd);
580
564
  permsObj.allow = [
581
565
  ...allow,
582
- ...enriched.filter((e) => !allow.includes(e)),
566
+ ...claudeAllowDerived.filter((e) => !allow.includes(e)),
583
567
  ];
584
568
  }
585
569
  }
@@ -589,6 +573,28 @@ export async function runUninstall(modules, ctx) {
589
573
  : isOpencodeJson
590
574
  ? stripOpencodeJsonScope(consumerDoc, templatePath, ctx.cwd)
591
575
  : stripTier2JsonScope(consumerDoc, templateDoc);
576
+ if (summary.file === path.join(".claude", "settings.json")) {
577
+ const remaining = stripped.permissions?.allow;
578
+ if (Array.isArray(remaining)) {
579
+ for (const row of remaining) {
580
+ if (typeof row === "string" &&
581
+ /^(WebFetch\(domain:|mcp__)/.test(row) &&
582
+ !claudeAllowDerived.includes(row)) {
583
+ console.log(`${ctx.logPrefix} review: ${summary.file} keeps ${row} — .bkit/version does not record it as bkit-written; remove it by hand if bkit added it`);
584
+ }
585
+ }
586
+ }
587
+ }
588
+ if (isOpencodeJson) {
589
+ const bash = stripped.permission?.bash;
590
+ if (bash !== null && typeof bash === "object" && !Array.isArray(bash)) {
591
+ for (const [key, value] of Object.entries(bash)) {
592
+ if (value === "allow" && isOpencodeSubstringFetchKey(key)) {
593
+ console.log(`${ctx.logPrefix} review: ${summary.file} keeps legacy substring grant \`${redactUrlParts(key)}\` in permission.bash — remove it by hand if you did not add it`);
594
+ }
595
+ }
596
+ }
597
+ }
592
598
  const strippedJson = JSON.stringify(stripped, null, 2) + "\n";
593
599
  if (Object.keys(stripped).length === 0) {
594
600
  // All keys were bkit-owned → delete file
@@ -37,8 +37,9 @@ import { readBkitConfig } from "../../shared/settings.js";
37
37
  import { detectInstalledHostModules } from "../../install/hosts.js";
38
38
  import { detectInstalledModules } from "./check.js";
39
39
  import { remapTemplateDest } from "../../install/template-copies.js";
40
+ import { syncProjectDocs } from "../../install/project-docs.js";
40
41
  import { CLAUDE_CLOUD_RELPATH, CODEX_CLOUD_RELPATH, CURSOR_CLOUD_RELPATH, writeClaudeCloudDoc, writeCodexCloudDoc, writeCursorCloudDoc, writeCursorCliPermissionsArtifact, } from "../../install/cloud-env.js";
41
- import { syncTemplateCopies, formatTemplateChanges } from "../../install/template-copies.js";
42
+ import { syncTemplateCopies, formatTemplateChanges, warnMissingLintStagedConfig, } from "../../install/template-copies.js";
42
43
  import { formatPayloadLinkChanges, syncPayloadLinks } from "../../install/payload-links.js";
43
44
  import { renderOpencodeJson, reconcileOpencodeJson } from "../../install/modules/opencode.js";
44
45
  import { renderManagedOutputs } from "../../install/modules/index.js";
@@ -580,7 +581,7 @@ export async function runUpgradeCommand(upgradeFlags) {
580
581
  dryRun: upgradeFlags.dryRun,
581
582
  ws: { writes: [] },
582
583
  });
583
- const templateReport = formatTemplateChanges(templateChanges);
584
+ const templateReport = formatTemplateChanges(templateChanges, process.cwd());
584
585
  if (templateReport)
585
586
  console.log(`${LOG_PREFIX} ${templateReport}`);
586
587
  // Payload view links — the same sync install runs (`.bkit/core` + `.bkit/shared`
@@ -763,6 +764,10 @@ export async function runUpgradeCommand(upgradeFlags) {
763
764
  }
764
765
  }
765
766
  }
767
+ // Project documents belong to the project: remove a legacy ownership wrapper and register each
768
+ // present document in `Project Documents` (a dry run only prints the preview). They carry no
769
+ // hash, so nothing here feeds `.bkit/version`.
770
+ syncProjectDocs(process.cwd(), { dryRun: upgradeFlags.dryRun });
766
771
  // Refresh canonicalHashes (from resulting on-disk content) AND bump pinnedVersion
767
772
  // to the version we just upgraded TO, so the next `bkit check` has nothing to write.
768
773
  // Called unconditionally (non-dry-run) so the pin bumps even when every file was a
@@ -793,6 +798,9 @@ export async function runUpgradeCommand(upgradeFlags) {
793
798
  }
794
799
  console.log(`${LOG_PREFIX} Done. updated: ${result.updated.length}, skipped: ${result.skipped.length}, conflicts: ${result.conflicts.length}, re-rendered: ${rendered.length}`);
795
800
  // `.bkit/advisories.md` describes the upgraded repo, not the last install or check.
801
+ // A real upgrade prints the missing-lint-staged line through the advisories; a dry run prints it here.
802
+ if (upgradeFlags.dryRun)
803
+ warnMissingLintStagedConfig(process.cwd(), LOG_PREFIX);
796
804
  if (!upgradeFlags.dryRun)
797
805
  await runUpgradeAdvisories();
798
806
  // Non-interactive mode: exit non-zero on conflicts
@@ -16,9 +16,8 @@ import { gitEnv } from "../ledgers/telemetry.js";
16
16
  import { readBkitConfig } from "../shared/settings.js";
17
17
  import { readPackageJson } from "../shared/package-json.js";
18
18
  import { installCommand } from "../shared/package-manager.js";
19
- import { minPushPathspecs } from "./ci/ci.js";
19
+ import { minPushOutside, minPushPathspecs } from "./ci/ci.js";
20
20
  import { requiredPushGate, runPushGate } from "./ci/push-gate.js";
21
- import { changedOutside } from "./workflow/ledgers.js";
22
21
  const REMOTE = "origin";
23
22
  const UPSTREAM = `${REMOTE}/${DEV}`;
24
23
  /** dev moved before git sent anything: git compared the remote's dev and stopped. */
@@ -169,7 +168,7 @@ function checkLanding(root, dir, base, log) {
169
168
  throw new CommandError(EXIT.NO, "landing checkout is not clean — nothing pushed");
170
169
  if (!readPackageJson(dir).ok)
171
170
  throw new CommandError(EXIT.NO, "landing package.json is unreadable — nothing pushed");
172
- const diff = changedOutside(dir, base, head, minPushPathspecs(readBkitConfig(dir)));
171
+ const diff = minPushOutside(dir, base, head, minPushPathspecs(readBkitConfig(dir)));
173
172
  if (!diff.ok)
174
173
  throw new CommandError(EXIT.NO, `cannot classify landing: ${diff.stderr}`);
175
174
  const gate = diff.outside.length === 0 ? "bkit:gate:min" : requiredPushGate(dir);
@@ -8,11 +8,12 @@
8
8
  // output keys and exit codes in its spec; `--help` and the convention test both read
9
9
  // that spec, so the help text cannot drift from what the command accepts.
10
10
  import { spawnSync } from "node:child_process";
11
+ import { createHash, randomUUID } from "node:crypto";
11
12
  import * as fs from "node:fs";
12
13
  import * as os from "node:os";
13
14
  import * as path from "node:path";
14
15
  import { appendFrictionRow, appendJournalRow, engineCallRow, frictionRow, journalEnabled, launchedByGit, rebasePaused, shouldRecordFriction, } from "../ledgers/journal.js";
15
- import { fold } from "../ledgers/status.js";
16
+ import { fold, isInvocationEvent } from "../ledgers/status.js";
16
17
  import { gitEnv, resolveGitSha } from "../ledgers/telemetry.js";
17
18
  import { parseJson } from "../shared/json.js";
18
19
  import { renderText } from "../shared/text.js";
@@ -52,6 +53,56 @@ export class CommandError extends Error {
52
53
  this.code = code;
53
54
  }
54
55
  }
56
+ /**
57
+ * A refusal the receiving handler declares as pre-effect validation: nothing was written,
58
+ * so a corrected retry of the same sub-step is permitted within its correction budget.
59
+ * Only this class (never a generic `CommandError`) carries that permission.
60
+ */
61
+ export class NoWriteRejection extends CommandError {
62
+ detail;
63
+ constructor(code, message, detail) {
64
+ super(code, message);
65
+ this.detail = detail;
66
+ }
67
+ }
68
+ /** A failure after an effect may have begun: the state must be reconciled, never auto-retried. */
69
+ export class UncertainEffect extends CommandError {
70
+ }
71
+ /** The correction budget of `scope` is spent: nothing was written and no further retry is allowed. */
72
+ export class CorrectionExhausted extends CommandError {
73
+ scope;
74
+ constructor(code, message, scope) {
75
+ super(code, message);
76
+ this.scope = scope;
77
+ }
78
+ }
79
+ /** The structured `--json` error for the declared classes; every other error prints none. */
80
+ function structuredError(err) {
81
+ if (err instanceof CorrectionExhausted) {
82
+ return {
83
+ code: err.code,
84
+ message: err.message,
85
+ effects: "none",
86
+ correctable: false,
87
+ exhausted: true,
88
+ scope: err.scope,
89
+ };
90
+ }
91
+ if (err instanceof NoWriteRejection) {
92
+ return {
93
+ code: err.code,
94
+ message: err.message,
95
+ effects: "none",
96
+ correctable: true,
97
+ scope: err.detail.scope,
98
+ substep: err.detail.substep,
99
+ };
100
+ }
101
+ if (err instanceof UncertainEffect) {
102
+ return { code: err.code, message: err.message, effects: "uncertain", correctable: false };
103
+ }
104
+ return null;
105
+ }
55
106
  /** Parse a whole-number flag, using its fallback only when absent. */
56
107
  export const wholeNumber = (v, flag, fallback, min = 0) => {
57
108
  if (v === undefined)
@@ -62,25 +113,60 @@ export const wholeNumber = (v, flag, fallback, min = 0) => {
62
113
  }
63
114
  return Number(s);
64
115
  };
65
- /** The holder named by this run when its tests-lock wait gave up. */
66
- export function testsLockHolder(log, who) {
67
- const prefix = `[machine-lock] ❌ ${who} gave up after `;
68
- for (const line of log.split(/\r?\n/)) {
69
- if (!line.startsWith(prefix))
70
- continue;
71
- const holder = /^\d+s waiting for tests, in use by (.+)$/.exec(line.slice(prefix.length));
72
- if (holder)
73
- return holder[1];
116
+ /** The env var naming the file the machine-lock `run` wrapper writes its give-up or refusal to. */
117
+ export const LOCK_STATUS_FILE_ENV = "LOCAL_STACK_LOCK_STATUS_FILE";
118
+ /** A fresh status file path for one gate run, in the OS temp folder; the file is not created. */
119
+ export function lockStatusFile() {
120
+ return path.join(os.tmpdir(), `bkit-lock-status-${process.pid}-${randomUUID()}`);
121
+ }
122
+ /**
123
+ * Read and delete a status file. Null when it is absent, empty, not a regular file or
124
+ * unreadable: the wrapper took its lock, or it never wrote the file.
125
+ */
126
+ export function readLockStatus(file) {
127
+ const stat = fs.statSync(file, { throwIfNoEntry: false });
128
+ if (stat === undefined || !stat.isFile())
129
+ return null;
130
+ let text;
131
+ try {
132
+ text = fs.readFileSync(file, "utf-8");
74
133
  }
75
- return null;
134
+ catch (err) {
135
+ const code = err.code;
136
+ if (code !== "EACCES" && code !== "EPERM")
137
+ throw err;
138
+ return null;
139
+ }
140
+ finally {
141
+ fs.rmSync(file, { force: true });
142
+ }
143
+ const fields = new Map();
144
+ for (const line of text.split("\n")) {
145
+ const eq = line.indexOf("=");
146
+ if (eq > 0)
147
+ fields.set(line.slice(0, eq), line.slice(eq + 1));
148
+ }
149
+ const lock = fields.get("lock");
150
+ const outcome = fields.get("outcome");
151
+ if (lock === undefined || outcome === undefined)
152
+ return null;
153
+ return { lock, outcome, holder: fields.get("holder") ?? "" };
76
154
  }
77
- /** Classify only a tests-lock outcome, leaving gate and nested-lock failures intact. */
78
- export function classifyLockExit({ exitCode, log, who, }) {
79
- const lines = log.split(/\r?\n/);
80
- if (exitCode === 75 && testsLockHolder(log, who) !== null)
155
+ /**
156
+ * Classify a wrapped gate's result from its exit code and the status file only. `exitCode`
157
+ * is null when a caller in between (git running a pre-push hook) collapsed the status, so
158
+ * the file alone decides. Anything but a tests-lock give-up, refusal or hold-limit stop is
159
+ * the gate's own.
160
+ */
161
+ export function classifyLockOutcome(exitCode, status) {
162
+ if (status === null || status.lock !== "tests")
163
+ return "gate";
164
+ const matches = (code) => exitCode === null || exitCode === code;
165
+ if (status.outcome === "gave-up" && matches(75))
81
166
  return "lock-wait";
82
- if (exitCode === 73 &&
83
- lines.some((line) => /^\[machine-lock\] ❌ (?:could not take the lock for tests:|cannot take tests while holding )/.test(line)))
167
+ if (status.outcome === "refused" && matches(73))
168
+ return "could-not-run";
169
+ if (status.outcome === "held-too-long" && matches(124))
84
170
  return "could-not-run";
85
171
  return "gate";
86
172
  }
@@ -91,17 +177,17 @@ const camel = (kebab) => kebab.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase()
91
177
  /** An orchestrator placeholder (`{FID}`, `{STATUS}`) the workflow should have substituted. */
92
178
  const PLACEHOLDER = /\{[A-Z][A-Z0-9_]*\}/;
93
179
  /** Refuse a flag value still carrying a literal `{UPPER}` placeholder. */
94
- function refuseUnsubstituted(flag, value) {
180
+ function refuseUnsubstituted(spec, value) {
95
181
  const hit = PLACEHOLDER.exec(value);
96
182
  if (hit) {
97
- throw new CommandError(EXIT.USAGE, `--${flag} carries the unsubstituted placeholder ${hit[0]} — substitute it before running`);
183
+ throw new CommandError(spec.placeholderExit ?? EXIT.USAGE, `--${spec.name} carries the unsubstituted placeholder ${hit[0]} — substitute it before running`);
98
184
  }
99
185
  }
100
186
  /**
101
187
  * Parse `--flag=value` / `--flag value` / `--bool` against the verb's spec. Keys
102
188
  * are filled in argv order, so a verb may render repeated or free-form flags in
103
189
  * the order the caller gave them. A value holding a literal `{UPPER}` placeholder
104
- * is refused (exit 2): the workflow passed it through unsubstituted.
190
+ * is refused (exit 2, or the flag's `placeholderExit`): the workflow passed it through unsubstituted.
105
191
  */
106
192
  export function parseFlags(argv, specs) {
107
193
  const byName = new Map(specs.map((s) => [s.name, s]));
@@ -114,7 +200,7 @@ export function parseFlags(argv, specs) {
114
200
  if (!key || out[key] !== undefined) {
115
201
  throw new CommandError(EXIT.USAGE, `unexpected argument "${arg}" — commands take flags only`);
116
202
  }
117
- refuseUnsubstituted(positional.name, arg);
203
+ refuseUnsubstituted(positional, arg);
118
204
  out[key] = arg;
119
205
  continue;
120
206
  }
@@ -141,7 +227,7 @@ export function parseFlags(argv, specs) {
141
227
  i++;
142
228
  }
143
229
  if (typeof value === "string")
144
- refuseUnsubstituted(name, value);
230
+ refuseUnsubstituted(spec, value);
145
231
  const key = camel(name);
146
232
  if (spec.repeatable) {
147
233
  const prior = out[key];
@@ -347,6 +433,181 @@ export function resolveActiveRun(opts) {
347
433
  }
348
434
  return found.length === 1 ? found[0] : undefined;
349
435
  }
436
+ export const INVOCATION_FLAG = {
437
+ name: "invocation",
438
+ type: "string",
439
+ help: "invocation id from `bkit status invocation`; must be issued by this checkout, and any --workflow, --step, --agent or --file given must agree with it",
440
+ };
441
+ const INVOCATION_ID = /^inv-[0-9a-f]{32}$/;
442
+ /** `<git common dir>/bkit-outbox/invocation-context`: one receipt per issued invocation. */
443
+ export function invocationDir(cwd) {
444
+ const root = outboxRoot(cwd);
445
+ return root === null ? null : path.join(root, "invocation-context");
446
+ }
447
+ /** Persist an issued invocation; returns its receipt path. */
448
+ export function writeInvocation(cwd, inv) {
449
+ const dir = invocationDir(cwd);
450
+ if (dir === null)
451
+ throw new CommandError(EXIT.USAGE, `not inside a git repository: ${cwd}`);
452
+ fs.mkdirSync(dir, { recursive: true });
453
+ const file = path.join(dir, `${inv.id}.json`);
454
+ fs.writeFileSync(file, `${JSON.stringify(inv)}\n`, { mode: 0o600, flag: "wx" });
455
+ return file;
456
+ }
457
+ /** A one-way fingerprint of a checkout's top: the committed `invocation` event never holds its path. */
458
+ export function worktreeFingerprint(top) {
459
+ return createHash("sha256").update(top).digest("hex").slice(0, 16);
460
+ }
461
+ /**
462
+ * Whether `file` resolves, symlinks included, to a path inside the checkout `top` and not in
463
+ * a worktree nested under it. A file that does not exist yet resolves through its parent.
464
+ */
465
+ function resolvesInside(top, file) {
466
+ try {
467
+ const realTop = fs.realpathSync(top);
468
+ let real;
469
+ if (fs.existsSync(file) || fs.lstatSync(file, { throwIfNoEntry: false }) !== undefined) {
470
+ real = fs.realpathSync(file);
471
+ }
472
+ else {
473
+ real = path.join(fs.realpathSync(path.dirname(file)), path.basename(file));
474
+ }
475
+ if (real !== realTop && !real.startsWith(realTop + path.sep))
476
+ return false;
477
+ const owner = git(path.dirname(real), ["rev-parse", "--show-toplevel"]);
478
+ return owner === null || fs.realpathSync(owner) === realTop;
479
+ }
480
+ catch {
481
+ return false;
482
+ }
483
+ }
484
+ /**
485
+ * Rebuild the outbox receipt of run-scoped invocation `id` from its `invocation` event in a
486
+ * `status.jsonl` under this checkout. Reads only this checkout's books, so another
487
+ * worktree's run is never found. Returns whether a receipt now exists.
488
+ */
489
+ function rebuildInvocation(cwd, id) {
490
+ const top = git(cwd, ["rev-parse", "--show-toplevel"]);
491
+ if (top === null)
492
+ return false;
493
+ let read = 0;
494
+ for (const month of subdirs(path.join(top, "docs", "plans"))) {
495
+ for (const fid of subdirs(path.join(top, "docs", "plans", month, "logs"))) {
496
+ if (++read > ACTIVE_RUN_SCAN_CAP)
497
+ return false;
498
+ const statusPath = path.join(top, statusRelPath(month, fid));
499
+ if (!fs.existsSync(statusPath))
500
+ continue;
501
+ // A status file symlinked out of the checkout is not this checkout's book.
502
+ if (!resolvesInside(top, statusPath))
503
+ continue;
504
+ for (const line of fs.readFileSync(statusPath, "utf-8").split("\n")) {
505
+ if (!line.includes(id))
506
+ continue;
507
+ const row = parseJson(line);
508
+ if (!row.ok || !isInvocationEvent(row.value) || row.value.id !== id)
509
+ continue;
510
+ const e = row.value;
511
+ // The event holds checkout-relative paths; they resolve against this top only.
512
+ if (e.worktree !== worktreeFingerprint(top) || path.join(top, e.statusPath) !== statusPath)
513
+ return false;
514
+ try {
515
+ writeInvocation(cwd, {
516
+ id,
517
+ version: 1,
518
+ scope: "run",
519
+ workflow: e.workflow,
520
+ step: e.step,
521
+ number: e.number,
522
+ title: e.title,
523
+ run: e.run,
524
+ statusPath,
525
+ bookRoot: path.join(top, e.bookRoot),
526
+ group: e.group,
527
+ attempt: e.attempt,
528
+ agent: e.agent,
529
+ host: e.host,
530
+ configuredModel: e.configuredModel,
531
+ observedModel: e.observedModel,
532
+ standalone: null,
533
+ name: null,
534
+ declaredStep: null,
535
+ allowedAgent: null,
536
+ worktree: top,
537
+ issuedAt: e.at,
538
+ });
539
+ }
540
+ catch {
541
+ // A concurrent rebuild may already have written the receipt; report whether one exists.
542
+ const dir = invocationDir(cwd);
543
+ return dir !== null && fs.existsSync(path.join(dir, `${id}.json`));
544
+ }
545
+ return true;
546
+ }
547
+ }
548
+ }
549
+ return false;
550
+ }
551
+ /**
552
+ * Resolve `--invocation` against the outbox and refuse (exit 2) a forged, unissued,
553
+ * other-checkout or stale id, and any asserted `--workflow`, `--step`, `--agent` or
554
+ * `--file` that disagrees with it. A run-scoped id is stale once a newer run of its
555
+ * workflow has started.
556
+ */
557
+ export function resolveInvocation(cwd, id, flags) {
558
+ const refuse = (why) => {
559
+ throw new CommandError(EXIT.USAGE, `invocation ${id}: ${why}`);
560
+ };
561
+ if (!INVOCATION_ID.test(id))
562
+ return refuse("not an id issued by `bkit status invocation`");
563
+ const dir = invocationDir(cwd);
564
+ const file = dir === null ? null : path.join(dir, `${id}.json`);
565
+ if (file === null)
566
+ return refuse("not issued in this repository");
567
+ // The run's status log is the authority; a missing receipt is rebuilt from its event.
568
+ if (!fs.existsSync(file) && !rebuildInvocation(cwd, id))
569
+ return refuse("not issued in this repository");
570
+ const parsed = parseJson(fs.readFileSync(file, "utf-8"));
571
+ const inv = parsed.ok ? parsed.value : null;
572
+ if (inv === null || typeof inv !== "object" || inv.id !== id || inv.version !== 1)
573
+ return refuse("receipt is unreadable");
574
+ const top = git(cwd, ["rev-parse", "--show-toplevel"]);
575
+ if (top === null || top !== inv.worktree)
576
+ return refuse(`issued in another checkout (${inv.worktree})`);
577
+ if (inv.scope === "run") {
578
+ if (inv.statusPath === null || inv.workflow === null || inv.run === null)
579
+ return refuse("run receipt lacks its status file");
580
+ if (!fs.existsSync(inv.statusPath))
581
+ return refuse(`stale: ${inv.statusPath} is gone`);
582
+ if (!resolvesInside(top, inv.statusPath))
583
+ return refuse(`${inv.statusPath} resolves outside this checkout`);
584
+ const events = [];
585
+ for (const line of fs.readFileSync(inv.statusPath, "utf-8").split("\n")) {
586
+ const row = line.trim() === "" ? null : parseJson(line);
587
+ if (row?.ok && row.value !== null && typeof row.value === "object") {
588
+ const type = row.value.type;
589
+ if (typeof type === "string" && FOLD_TYPES.has(type))
590
+ events.push(row.value);
591
+ }
592
+ }
593
+ const started = fold(events).filter((r) => r.workflow === inv.workflow).length;
594
+ if (started > inv.run)
595
+ return refuse(`stale: a newer ${inv.workflow} run has started`);
596
+ if (started < inv.run - 1)
597
+ return refuse("stale: its run is gone");
598
+ }
599
+ const text = (v) => (typeof v === "string" ? v : undefined);
600
+ const conflict = (flag, given, bound) => refuse(`conflict: --${flag}=${given} disagrees with the invocation (${bound ?? "none"})`);
601
+ for (const flag of ["workflow", "step", "agent"]) {
602
+ const given = text(flags[flag]);
603
+ if (given !== undefined && given !== inv[flag])
604
+ conflict(flag, given, inv[flag]);
605
+ }
606
+ const file2 = text(flags["file"]);
607
+ if (file2 !== undefined && path.resolve(cwd, file2) !== inv.statusPath)
608
+ conflict("file", file2, inv.statusPath);
609
+ return inv;
610
+ }
350
611
  /** The journal `runCommand` uses unless a caller injects one: writes into the active run's own books. */
351
612
  function engineJournal() {
352
613
  let resolved = false;
@@ -428,6 +689,22 @@ export async function runCommand(argv, commands, options) {
428
689
  }
429
690
  const rest = argv.slice(2);
430
691
  if (rest.some(isHelp)) {
692
+ if (rest.includes("--json")) {
693
+ const s = cmd.verbs[verb];
694
+ io.stdout(`${JSON.stringify({
695
+ noun: cmd.noun,
696
+ verb,
697
+ summary: s.summary,
698
+ flags: s.flags.map((f) => ({
699
+ name: f.name,
700
+ type: f.type,
701
+ required: f.required === true,
702
+ })),
703
+ output: s.output,
704
+ exitCodes: s.exitCodes ?? {},
705
+ })}\n`);
706
+ return EXIT.OK;
707
+ }
431
708
  io.stdout(verbHelp(cmd, verb));
432
709
  return EXIT.OK;
433
710
  }
@@ -471,9 +748,24 @@ export async function runCommand(argv, commands, options) {
471
748
  }
472
749
  ctx.json = own.length !== rest.length;
473
750
  ctx.flags = parseFlags(own, spec.flags);
751
+ const invocationId = ctx.flags["invocation"];
752
+ if (typeof invocationId === "string" &&
753
+ spec.flags.some((f) => f.name === INVOCATION_FLAG.name && f.unresolved !== true)) {
754
+ ctx.invocation = resolveInvocation(ctx.cwd, invocationId, ctx.flags);
755
+ }
474
756
  input = { noun: cmd.noun, verb, argv: rest, flags: ctx.flags, cwd: ctx.cwd };
475
757
  const entered = input;
476
- guarded(() => journal.call(entered));
758
+ // An invocation-bound call writes its engine-call row into the issuing run's own status
759
+ // log (never another worktree's); a runless call has no run to write to.
760
+ // `status invocation` records itself as the run's `invocation` event, so it adds no second row.
761
+ const bound = ctx.invocation;
762
+ const selfRecorded = cmd.noun === "status" && verb === "invocation";
763
+ if (bound === undefined && !selfRecorded)
764
+ guarded(() => journal.call(entered));
765
+ else if (bound?.scope === "run" && bound.statusPath !== null) {
766
+ const own = { ...entered, flags: { ...entered.flags, file: bound.statusPath } };
767
+ guarded(() => journal.call(own));
768
+ }
477
769
  outcome = null;
478
770
  const code = await spec.run(ctx);
479
771
  outcome = code;
@@ -483,6 +775,9 @@ export async function runCommand(argv, commands, options) {
483
775
  if (!(err instanceof CommandError))
484
776
  throw err;
485
777
  io.stderr(`${tag} ${err.message}\n`);
778
+ const structured = ctx.json ? structuredError(err) : null;
779
+ if (structured !== null)
780
+ io.stdout(`${JSON.stringify({ error: structured })}\n`);
486
781
  outcome = err.code;
487
782
  return err.code;
488
783
  }
@@ -552,6 +847,9 @@ export function runTool(cmd, args, cwd, opts = {}) {
552
847
  env: { ...gitEnv(), ...opts.env },
553
848
  input: opts.input,
554
849
  maxBuffer: OUTPUT_LIMIT,
850
+ ...(opts.timeoutMs === undefined
851
+ ? {}
852
+ : { timeout: Math.max(1, Math.ceil(opts.timeoutMs)), killSignal: "SIGKILL" }),
555
853
  });
556
854
  if (res.error && res.pid === 0) {
557
855
  return { found: false, status: 127, stdout: "", stderr: `${cmd} not found on PATH` };
@@ -569,8 +867,8 @@ export function runTool(cmd, args, cwd, opts = {}) {
569
867
  }
570
868
  const signalNumber = (signal) => (signal ? os.constants.signals[signal] : undefined) ?? 1;
571
869
  /** `gh <args>` in `cwd`, never throwing; `input` goes to stdin; `env` is added to the child's. */
572
- export function runGh(cwd, args, input, env) {
573
- const res = runTool("gh", args, cwd, { input, env });
870
+ export function runGh(cwd, args, input, env, opts = {}) {
871
+ const res = runTool("gh", args, cwd, { input, env, ...opts });
574
872
  return {
575
873
  ok: res.found && res.status === 0,
576
874
  stdout: res.stdout.trim(),