@cbartens/bkit 5.5.1 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (425) hide show
  1. package/.bkit/README.md +167 -154
  2. package/.bkit/core/.agents/context.md +95 -29
  3. package/.bkit/core/.agents/docs.md +18 -15
  4. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-gateguard.cjs +1 -0
  5. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-guardrails.cjs +6 -5
  6. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-readguard.cjs +1 -0
  7. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-rules.cjs +65 -0
  8. package/.bkit/core/.agents/rules.md +112 -102
  9. package/.bkit/core/.agents/skills.md +63 -15
  10. package/.bkit/core/.bkit/README.md +167 -154
  11. package/.bkit/core/.bkit/authoring.md +747 -0
  12. package/.bkit/core/.bkit/cli.md +407 -0
  13. package/.bkit/core/.bkit/cloud.md +283 -195
  14. package/.bkit/core/.bkit/comparison.md +45 -43
  15. package/.bkit/core/.bkit/install.md +166 -95
  16. package/.bkit/core/.bkit/jsonl.md +339 -196
  17. package/.bkit/core/.bkit/pipeline.md +142 -145
  18. package/.bkit/core/.bkit/prompts.md +295 -264
  19. package/.bkit/core/.bkit/providers.md +460 -277
  20. package/.bkit/core/.bkit/router.md +69 -0
  21. package/.bkit/core/.bkit/templates.md +530 -256
  22. package/.bkit/core/.bkit/trackers.md +116 -65
  23. package/.bkit/core/.bkit/workflows.md +742 -618
  24. package/.bkit/core/.claude/hooks/bkit-gateguard.cjs +2 -2
  25. package/.bkit/core/.claude/hooks/bkit-guardrails.cjs +3 -3
  26. package/.bkit/core/.claude/hooks/bkit-preflight.sh +45 -14
  27. package/.bkit/core/.codex/hooks/bkit-guardrails.cjs +3 -3
  28. package/.bkit/core/.codex/hooks/bkit-rules.cjs +57 -0
  29. package/.bkit/core/.cursor/hooks/bkit-guardrails.cjs +7 -7
  30. package/.bkit/core/.cursor/hooks/bkit-preflight.sh +47 -12
  31. package/.bkit/core/.opencode/plugin/bkit-rules.js +89 -0
  32. package/.bkit/core/AGENTS.md +6 -80
  33. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +128 -130
  34. package/.bkit/core/docs/templates/bkit-audit-adoption.md +104 -94
  35. package/.bkit/core/docs/templates/bkit-audit-agents.md +96 -98
  36. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +100 -103
  37. package/.bkit/core/docs/templates/bkit-audit-analytics.md +141 -107
  38. package/.bkit/core/docs/templates/bkit-audit-annotations.md +99 -97
  39. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +122 -121
  40. package/.bkit/core/docs/templates/bkit-audit-app-store.md +158 -101
  41. package/.bkit/core/docs/templates/bkit-audit-architecture.md +114 -96
  42. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +76 -97
  43. package/.bkit/core/docs/templates/bkit-audit-config.md +123 -101
  44. package/.bkit/core/docs/templates/bkit-audit-cost.md +86 -99
  45. package/.bkit/core/docs/templates/bkit-audit-coverage.md +76 -93
  46. package/.bkit/core/docs/templates/bkit-audit-database.md +102 -95
  47. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +165 -108
  48. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +115 -109
  49. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +265 -113
  50. package/.bkit/core/docs/templates/bkit-audit-documentation.md +119 -118
  51. package/.bkit/core/docs/templates/bkit-audit-duplication.md +140 -111
  52. package/.bkit/core/docs/templates/bkit-audit-failures.md +111 -106
  53. package/.bkit/core/docs/templates/bkit-audit-flakes.md +100 -99
  54. package/.bkit/core/docs/templates/bkit-audit-gates.md +107 -103
  55. package/.bkit/core/docs/templates/bkit-audit-issues.md +105 -105
  56. package/.bkit/core/docs/templates/bkit-audit-llm.md +134 -85
  57. package/.bkit/core/docs/templates/bkit-audit-logs.md +124 -125
  58. package/.bkit/core/docs/templates/bkit-audit-models.md +99 -78
  59. package/.bkit/core/docs/templates/bkit-audit-privacy.md +56 -76
  60. package/.bkit/core/docs/templates/bkit-audit-prompts.md +63 -78
  61. package/.bkit/core/docs/templates/bkit-audit-red-team.md +125 -93
  62. package/.bkit/core/docs/templates/bkit-audit-reliability.md +97 -96
  63. package/.bkit/core/docs/templates/bkit-audit-repo.md +170 -98
  64. package/.bkit/core/docs/templates/bkit-audit-security.md +207 -121
  65. package/.bkit/core/docs/templates/bkit-audit-slop.md +78 -95
  66. package/.bkit/core/docs/templates/bkit-audit-testing.md +163 -139
  67. package/.bkit/core/docs/templates/bkit-audit-usability.md +114 -96
  68. package/.bkit/core/docs/templates/bkit-plan.md +158 -281
  69. package/.bkit/core/engine/checks/after/auth.ts +40 -37
  70. package/.bkit/core/engine/checks/after/ci-yml.ts +104 -31
  71. package/.bkit/core/engine/checks/after/github.ts +95 -17
  72. package/.bkit/core/engine/checks/after/index.ts +21 -8
  73. package/.bkit/core/engine/checks/after/suppression.ts +8 -5
  74. package/.bkit/core/engine/checks/after/tools.ts +125 -123
  75. package/.bkit/core/engine/checks/before/context-fetch.ts +227 -33
  76. package/.bkit/core/engine/checks/before/env.ts +3 -3
  77. package/.bkit/core/engine/checks/before/files.ts +5 -4
  78. package/.bkit/core/engine/checks/before/index.ts +25 -1
  79. package/.bkit/core/engine/checks/before/repo.ts +208 -2
  80. package/.bkit/core/engine/checks/status-holes.ts +916 -123
  81. package/.bkit/core/engine/checks/tips/catalogue.ts +82 -20
  82. package/.bkit/core/engine/checks/tips/detect.ts +66 -0
  83. package/.bkit/core/engine/checks/tips/index.ts +52 -11
  84. package/.bkit/core/engine/cli.ts +251 -130
  85. package/.bkit/core/engine/commands/analysis.ts +282 -199
  86. package/.bkit/core/engine/commands/ci/ci.ts +363 -29
  87. package/.bkit/core/engine/commands/ci/pins.ts +172 -0
  88. package/.bkit/core/engine/commands/ci/push-gate.ts +223 -0
  89. package/.bkit/core/engine/commands/comply.ts +77 -103
  90. package/.bkit/core/engine/commands/install/doctor.ts +2 -2
  91. package/.bkit/core/engine/commands/install/install.ts +57 -18
  92. package/.bkit/core/engine/commands/install/uninstall.ts +86 -55
  93. package/.bkit/core/engine/commands/install/upgrade.ts +32 -15
  94. package/.bkit/core/engine/commands/land.ts +139 -18
  95. package/.bkit/core/engine/commands/lib.ts +381 -22
  96. package/.bkit/core/engine/commands/registry.ts +10 -2
  97. package/.bkit/core/engine/commands/setup/setup.ts +8 -7
  98. package/.bkit/core/engine/commands/stats.ts +260 -0
  99. package/.bkit/core/engine/commands/tips.ts +10 -5
  100. package/.bkit/core/engine/commands/workflow/branches.ts +2215 -176
  101. package/.bkit/core/engine/commands/workflow/challenge.ts +748 -0
  102. package/.bkit/core/engine/commands/workflow/completeness.ts +109 -0
  103. package/.bkit/core/engine/commands/workflow/context.ts +1249 -47
  104. package/.bkit/core/engine/commands/workflow/counters.ts +483 -95
  105. package/.bkit/core/engine/commands/workflow/decisions.ts +585 -0
  106. package/.bkit/core/engine/commands/workflow/disk.ts +238 -56
  107. package/.bkit/core/engine/commands/workflow/fids.ts +811 -33
  108. package/.bkit/core/engine/commands/workflow/issues.ts +413 -64
  109. package/.bkit/core/engine/commands/workflow/ledgers.ts +1333 -36
  110. package/.bkit/core/engine/commands/workflow/locks.ts +28 -2
  111. package/.bkit/core/engine/commands/workflow/plan-blocks.ts +691 -0
  112. package/.bkit/core/engine/commands/workflow/plan-versions.ts +21 -0
  113. package/.bkit/core/engine/commands/workflow/plans.ts +257 -0
  114. package/.bkit/core/engine/commands/workflow/prs.ts +178 -33
  115. package/.bkit/core/engine/commands/workflow/repo.ts +66 -8
  116. package/.bkit/core/engine/commands/workflow/roadmap.ts +72 -22
  117. package/.bkit/core/engine/commands/workflow/run-facts.ts +492 -0
  118. package/.bkit/core/engine/commands/workflow/runs.ts +827 -79
  119. package/.bkit/core/engine/commands/workflow/runtime.ts +25 -1
  120. package/.bkit/core/engine/commands/workflow/skills.ts +1 -0
  121. package/.bkit/core/engine/commands/workflow/status.ts +329 -33
  122. package/.bkit/core/engine/commands/workflow/step-table.ts +381 -0
  123. package/.bkit/core/engine/commands/workflow/steps.ts +841 -105
  124. package/.bkit/core/engine/commands/workflow/summary-findings.ts +177 -0
  125. package/.bkit/core/engine/commands/workflow/summary.ts +544 -0
  126. package/.bkit/core/engine/commands/workflow/tasks.ts +409 -0
  127. package/.bkit/core/engine/commands/workflow/test-blocks.ts +254 -0
  128. package/.bkit/core/engine/commands/workflow/tests-changed.ts +201 -0
  129. package/.bkit/core/engine/commands/workflow/tests.ts +2124 -330
  130. package/.bkit/core/engine/commands/workflow/tracker.ts +1195 -0
  131. package/.bkit/core/engine/commands/workflow/workflows.ts +1197 -235
  132. package/.bkit/core/engine/commands/workflow/worktrees.ts +543 -24
  133. package/.bkit/core/engine/install/cloud-env.ts +251 -121
  134. package/.bkit/core/engine/install/context-ci-workflow.ts +102 -0
  135. package/.bkit/core/engine/install/manifest.ts +67 -17
  136. package/.bkit/core/engine/install/modules/antigravity.ts +3 -2
  137. package/.bkit/core/engine/install/modules/cloud.ts +24 -16
  138. package/.bkit/core/engine/install/modules/codex.ts +15 -2
  139. package/.bkit/core/engine/install/modules/core.ts +1196 -45
  140. package/.bkit/core/engine/install/modules/cursor.ts +6 -6
  141. package/.bkit/core/engine/install/modules/opencode.ts +18 -6
  142. package/.bkit/core/engine/install/template-notes.ts +130 -0
  143. package/.bkit/core/engine/install/version-file.ts +9 -4
  144. package/.bkit/core/engine/install/write.ts +5 -0
  145. package/.bkit/core/engine/ledgers/compact.ts +124 -0
  146. package/.bkit/core/engine/ledgers/journal.ts +291 -0
  147. package/.bkit/core/engine/ledgers/migrate.ts +92 -0
  148. package/.bkit/core/engine/ledgers/status.ts +249 -21
  149. package/.bkit/core/engine/ledgers/telemetry.ts +1397 -253
  150. package/.bkit/core/engine/render/hosts.ts +118 -14
  151. package/.bkit/core/engine/render/models.ts +12 -0
  152. package/.bkit/core/engine/shared/bkit-latest.ts +26 -4
  153. package/.bkit/core/engine/shared/branches.ts +4 -1
  154. package/.bkit/core/engine/shared/dep-updater.ts +60 -0
  155. package/.bkit/core/engine/shared/egress.ts +8 -1
  156. package/.bkit/core/engine/shared/json.ts +25 -7
  157. package/.bkit/core/engine/shared/package-manager.ts +9 -0
  158. package/.bkit/core/engine/shared/settings.ts +243 -31
  159. package/.bkit/core/engine/shared/text.ts +361 -0
  160. package/.bkit/core/engine/shared/timeouts.ts +2 -0
  161. package/.bkit/core/engine/tools/cli-doc.ts +111 -0
  162. package/.bkit/core/engine/tools/grammar-density.ts +215 -0
  163. package/.bkit/core/engine/tools/instructions-sources.ts +832 -0
  164. package/.bkit/core/engine/tools/instructions.ts +1802 -0
  165. package/.bkit/core/hooks/antigravity-hook.js +25 -10
  166. package/.bkit/core/hooks/gateguard-engine.js +54 -29
  167. package/.bkit/core/hooks/guardrails-shell.js +4 -5
  168. package/.bkit/core/hooks/guardrails-tiers.js +10 -4
  169. package/.bkit/core/hooks/preflight-linear.sh +9 -9
  170. package/.bkit/core/hooks/preflight-rules.sh +8 -0
  171. package/.bkit/core/hooks/readguard-engine.js +29 -10
  172. package/.bkit/core/hooks/session-rules-advisory.js +61 -0
  173. package/.bkit/core/prompts/bkit-audit-generate.md +202 -94
  174. package/.bkit/core/prompts/bkit-build-challenge-1.md +76 -34
  175. package/.bkit/core/prompts/bkit-build-challenge-2.md +85 -38
  176. package/.bkit/core/prompts/bkit-build-install-skills.md +50 -28
  177. package/.bkit/core/prompts/bkit-build-plan-convert.md +85 -0
  178. package/.bkit/core/prompts/bkit-build-plan-current.md +59 -36
  179. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +101 -36
  180. package/.bkit/core/prompts/bkit-build-plan-tasks.md +149 -0
  181. package/.bkit/core/prompts/bkit-build-plan-tests.md +120 -0
  182. package/.bkit/core/prompts/bkit-build-plan-verify.md +104 -43
  183. package/.bkit/core/prompts/bkit-debug-abort-handover.md +47 -32
  184. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +109 -57
  185. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +65 -39
  186. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +53 -31
  187. package/.bkit/core/prompts/bkit-debug-failure-soak.md +65 -34
  188. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +46 -31
  189. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +45 -31
  190. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +43 -30
  191. package/.bkit/core/prompts/bkit-design-generate.md +80 -46
  192. package/.bkit/core/prompts/bkit-design-organise.md +83 -32
  193. package/.bkit/core/prompts/bkit-design-review-1.md +70 -50
  194. package/.bkit/core/prompts/bkit-design-review-2.md +65 -46
  195. package/.bkit/core/prompts/bkit-design-spike.md +64 -40
  196. package/.bkit/core/prompts/bkit-design-update.md +53 -28
  197. package/.bkit/core/prompts/bkit-plan-generate.md +101 -29
  198. package/.bkit/core/prompts/bkit-plan-review-1.md +78 -41
  199. package/.bkit/core/prompts/bkit-plan-review-2.md +78 -35
  200. package/.bkit/core/prompts/bkit-plan-scope-check.md +116 -0
  201. package/.bkit/core/prompts/bkit-plan-update.md +86 -31
  202. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +94 -50
  203. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +91 -41
  204. package/.bkit/core/prompts/bkit-ship-update-docs.md +45 -24
  205. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +65 -49
  206. package/.bkit/core/prompts/bkit-utility-update-decisions.md +87 -42
  207. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +81 -37
  208. package/.bkit/core/prompts/bkit-utility-update-documentation.md +43 -25
  209. package/.bkit/core/prompts/bkit-utility-update-failures.md +84 -37
  210. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +88 -42
  211. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +92 -39
  212. package/.bkit/core/prompts/bkit-utility-update-tracker.md +159 -60
  213. package/.bkit/core/workflows/bkit-auto.md +89 -58
  214. package/.bkit/core/workflows/bkit-build.md +967 -517
  215. package/.bkit/core/workflows/bkit-debug.md +555 -387
  216. package/.bkit/core/workflows/bkit-design.md +319 -283
  217. package/.bkit/core/workflows/bkit-plan.md +319 -342
  218. package/.bkit/core/workflows/bkit-ship.md +525 -328
  219. package/.bkit/shared/.agents/plugins/bkit/hooks.json +10 -0
  220. package/.bkit/shared/.bkit/.env.example +2 -2
  221. package/.bkit/shared/.claude/bkit-cloud.md +12 -10
  222. package/.bkit/shared/.claude/settings.json +14 -0
  223. package/.bkit/shared/.codex/bkit-cloud.md +98 -0
  224. package/.bkit/shared/.codex/hooks.json +20 -0
  225. package/.bkit/shared/.cursor/bkit-cloud.md +3 -3
  226. package/.bkit/shared/.cursor/mcp.json +1 -1
  227. package/.bkit/shared/.cursor/rules/bkit-rules.mdc +1 -1
  228. package/.bkit/shared/.gitattributes +1 -1
  229. package/.bkit/shared/.mcp.json +1 -1
  230. package/.bkit/shared/.opencode/opencode.json +12 -1
  231. package/.bkit/shared/CLAUDE.md +6 -2
  232. package/.bkit/shared/GEMINI.md +5 -2
  233. package/.bkit/shared/docs/architecture.md +4 -7
  234. package/.bkit/shared/docs/data-schema.md +4 -7
  235. package/.bkit/shared/docs/deployments.md +241 -168
  236. package/.bkit/shared/docs/design.md +11 -12
  237. package/.bkit/shared/docs/noise.md +8 -7
  238. package/.bkit/shared/docs/observability.md +5 -8
  239. package/.bkit/shared/docs/security.md +35 -17
  240. package/.bkit/shared/docs/setup.md +29 -18
  241. package/.bkit/shared/docs/technology.md +3 -6
  242. package/.bkit/shared/docs/testing.md +289 -174
  243. package/.bkit/shared/gitignore +6 -2
  244. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +15 -16
  245. package/.bkit/templates/.cursor/Dockerfile +12 -8
  246. package/.bkit/templates/.cursor/environment.json +1 -1
  247. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-bug.yml +10 -8
  248. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-change.yml +45 -12
  249. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-idea.yml +3 -3
  250. package/.bkit/templates/.github/renovate.json5 +34 -6
  251. package/.bkit/templates/.github/workflows/bkit-ci.yml +54 -51
  252. package/.bkit/templates/.github/workflows/bkit-cloud.yml +34 -33
  253. package/.bkit/templates/.github/workflows/bkit-health.yml +97 -0
  254. package/.bkit/templates/.github/workflows/bkit-renovate.yml +5 -4
  255. package/.bkit/templates/.github/workflows/bkit-trivy.yml +5 -4
  256. package/.bkit/templates/.husky/pre-commit +2 -2
  257. package/.bkit/templates/.husky/pre-push +96 -36
  258. package/.bkit/templates/.prettierignore +6 -0
  259. package/.bkit/templates/.vale.ini +27 -27
  260. package/.bkit/templates/context/bkit-cloudrun.md +23 -15
  261. package/.bkit/templates/context/bkit-expo.md +70 -52
  262. package/.bkit/templates/context/bkit-github.md +93 -56
  263. package/.bkit/templates/context/bkit-inngest.md +21 -15
  264. package/.bkit/templates/context/bkit-maestro.md +22 -16
  265. package/.bkit/templates/context/bkit-playwright.md +23 -17
  266. package/.bkit/templates/context/bkit-resend.md +12 -10
  267. package/.bkit/templates/context/bkit-sentry.md +30 -20
  268. package/.bkit/templates/context/bkit-serena.md +8 -7
  269. package/.bkit/templates/context/bkit-stripe.md +14 -13
  270. package/.bkit/templates/context/bkit-supabase.md +16 -13
  271. package/.bkit/templates/context/bkit-tavily.md +14 -11
  272. package/.bkit/templates/context/bkit-vercel.md +27 -18
  273. package/.bkit/templates/docs/capabilities.md +15 -14
  274. package/.bkit/templates/scripts/ci/{check-accepted-divergences.mjs → bkit-check-accepted-divergences.mjs} +6 -3
  275. package/.bkit/templates/scripts/ci/{check-accepted-divergences.test.mjs → bkit-check-accepted-divergences.test.mjs} +3 -3
  276. package/.bkit/templates/scripts/ci/{check-capstone.mjs → bkit-check-capstone.mjs} +2 -2
  277. package/.bkit/templates/scripts/ci/{check-capstone.test.mjs → bkit-check-capstone.test.mjs} +4 -4
  278. package/.bkit/templates/scripts/ci/{check-dependency-audit.mjs → bkit-check-dependency-audit.mjs} +103 -18
  279. package/.bkit/templates/scripts/ci/{check-dependency-audit.test.mjs → bkit-check-dependency-audit.test.mjs} +31 -3
  280. package/.bkit/templates/scripts/ci/bkit-machine-lock.sh +387 -0
  281. package/.bkit/templates/scripts/ci/bkit-test-awake.mjs +75 -0
  282. package/.bkit/templates/scripts/ci/bkit-test-awake.test.mjs +160 -0
  283. package/.bkit/templates/scripts/ci/lanes/{resolve-push-base.mjs → bkit-resolve-push-base.mjs} +3 -3
  284. package/.bkit/templates/scripts/ci/lanes/{resolve-push-base.test.mjs → bkit-resolve-push-base.test.mjs} +4 -4
  285. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.mjs +10 -2
  286. package/.bkit/templates/scripts/graphify/bkit-graph-drift.py +1 -1
  287. package/.bkit/templates/scripts/graphify/bkit-graph-eager.py +3 -3
  288. package/.bkit/templates/scripts/graphify/bkit-graph-embed.py +63 -0
  289. package/.bkit/templates/scripts/graphify/bkit-graph-imports.py +2 -2
  290. package/.bkit/templates/scripts/graphify/bkit-graph-pre-push.sh +69 -18
  291. package/.bkit/templates/scripts/graphify/bkit-graph-repair.py +3 -3
  292. package/.bkit/templates/scripts/graphify/bkit-graph-surface.py +1 -1
  293. package/.bkit/templates/scripts/graphify/bkit-graphify-graphml.py +1 -1
  294. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +197 -126
  295. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +64 -41
  296. package/.bkit/templates/scripts/slop/bkit-slop-type-suppression.mjs +23 -7
  297. package/.bkit/templates/slop-scan.config.json +9 -2
  298. package/CHANGELOG.md +231 -0
  299. package/README.md +278 -89
  300. package/dist/checks/after/auth.js +36 -33
  301. package/dist/checks/after/ci-yml.js +91 -30
  302. package/dist/checks/after/github.js +91 -17
  303. package/dist/checks/after/index.js +22 -11
  304. package/dist/checks/after/suppression.js +8 -5
  305. package/dist/checks/after/tools.js +111 -114
  306. package/dist/checks/before/context-fetch.js +218 -33
  307. package/dist/checks/before/env.js +3 -3
  308. package/dist/checks/before/files.js +5 -3
  309. package/dist/checks/before/index.js +20 -3
  310. package/dist/checks/before/repo.js +197 -2
  311. package/dist/checks/status-holes.js +739 -114
  312. package/dist/checks/tips/catalogue.js +70 -19
  313. package/dist/checks/tips/detect.js +62 -0
  314. package/dist/checks/tips/index.js +51 -9
  315. package/dist/cli.js +234 -124
  316. package/dist/commands/analysis.js +174 -141
  317. package/dist/commands/ci/ci.js +302 -25
  318. package/dist/commands/ci/pins.js +142 -0
  319. package/dist/commands/ci/push-gate.js +194 -0
  320. package/dist/commands/comply.js +54 -91
  321. package/dist/commands/install/doctor.js +2 -2
  322. package/dist/commands/install/install.js +50 -19
  323. package/dist/commands/install/uninstall.js +82 -55
  324. package/dist/commands/install/upgrade.js +21 -11
  325. package/dist/commands/land.js +137 -17
  326. package/dist/commands/lib.js +295 -21
  327. package/dist/commands/registry.js +10 -2
  328. package/dist/commands/setup/setup.js +8 -7
  329. package/dist/commands/stats.js +175 -0
  330. package/dist/commands/tips.js +7 -3
  331. package/dist/commands/workflow/branches.js +1873 -152
  332. package/dist/commands/workflow/challenge.js +609 -0
  333. package/dist/commands/workflow/completeness.js +97 -0
  334. package/dist/commands/workflow/context.js +1045 -46
  335. package/dist/commands/workflow/counters.js +385 -86
  336. package/dist/commands/workflow/decisions.js +484 -0
  337. package/dist/commands/workflow/disk.js +214 -56
  338. package/dist/commands/workflow/fids.js +706 -33
  339. package/dist/commands/workflow/issues.js +349 -59
  340. package/dist/commands/workflow/ledgers.js +1123 -37
  341. package/dist/commands/workflow/locks.js +26 -2
  342. package/dist/commands/workflow/plan-blocks.js +501 -0
  343. package/dist/commands/workflow/plan-versions.js +22 -0
  344. package/dist/commands/workflow/plans.js +205 -0
  345. package/dist/commands/workflow/prs.js +154 -35
  346. package/dist/commands/workflow/repo.js +58 -8
  347. package/dist/commands/workflow/roadmap.js +58 -23
  348. package/dist/commands/workflow/run-facts.js +421 -0
  349. package/dist/commands/workflow/runs.js +670 -72
  350. package/dist/commands/workflow/runtime.js +15 -1
  351. package/dist/commands/workflow/skills.js +1 -0
  352. package/dist/commands/workflow/status.js +282 -34
  353. package/dist/commands/workflow/step-table.js +308 -0
  354. package/dist/commands/workflow/steps.js +703 -96
  355. package/dist/commands/workflow/summary-findings.js +117 -0
  356. package/dist/commands/workflow/summary.js +388 -0
  357. package/dist/commands/workflow/tasks.js +378 -0
  358. package/dist/commands/workflow/test-blocks.js +231 -0
  359. package/dist/commands/workflow/tests-changed.js +172 -0
  360. package/dist/commands/workflow/tests.js +1695 -305
  361. package/dist/commands/workflow/tracker.js +983 -0
  362. package/dist/commands/workflow/workflows.js +1014 -222
  363. package/dist/commands/workflow/worktrees.js +432 -26
  364. package/dist/install/cloud-env.js +233 -99
  365. package/dist/install/context-ci-workflow.js +85 -0
  366. package/dist/install/manifest.js +64 -17
  367. package/dist/install/modules/antigravity.js +3 -2
  368. package/dist/install/modules/cloud.js +25 -16
  369. package/dist/install/modules/codex.js +12 -2
  370. package/dist/install/modules/core.js +1090 -48
  371. package/dist/install/modules/cursor.js +6 -6
  372. package/dist/install/modules/opencode.js +13 -7
  373. package/dist/install/template-notes.js +116 -0
  374. package/dist/install/version-file.js +9 -4
  375. package/dist/ledgers/compact.js +87 -0
  376. package/dist/ledgers/journal.js +233 -0
  377. package/dist/ledgers/migrate.js +81 -0
  378. package/dist/ledgers/status.js +176 -13
  379. package/dist/ledgers/telemetry.js +1010 -125
  380. package/dist/render/hosts.js +104 -14
  381. package/dist/render/models.js +12 -0
  382. package/dist/shared/bkit-latest.js +26 -4
  383. package/dist/shared/branches.js +3 -1
  384. package/dist/shared/dep-updater.js +49 -0
  385. package/dist/shared/egress.js +8 -1
  386. package/dist/shared/json.js +20 -7
  387. package/dist/shared/package-manager.js +6 -0
  388. package/dist/shared/settings.js +181 -24
  389. package/dist/shared/text.js +333 -0
  390. package/dist/shared/timeouts.js +2 -0
  391. package/dist/tools/cli-doc.js +97 -0
  392. package/dist/tools/grammar-density.js +183 -0
  393. package/dist/tools/instructions-sources.js +720 -0
  394. package/dist/tools/instructions.js +1623 -0
  395. package/package.json +156 -51
  396. package/.bkit/core/.bkit/lite.md +0 -73
  397. package/.bkit/core/engine/commands/harvest.ts +0 -459
  398. package/.bkit/core/engine/commands/workflow/workstreams.ts +0 -166
  399. package/.bkit/core/engine/tools/wording.ts +0 -748
  400. package/.bkit/core/prompts/bkit-build-challenge-reconcile.md +0 -69
  401. package/.bkit/core/prompts/bkit-build-challenge-remediate.md +0 -71
  402. package/.bkit/core/prompts/bkit-build-challenge-tests.md +0 -74
  403. package/.bkit/core/prompts/bkit-build-plan-execute.md +0 -76
  404. package/.bkit/core/prompts/bkit-build-summary.md +0 -94
  405. package/.bkit/core/prompts/bkit-debug-summary.md +0 -96
  406. package/.bkit/core/prompts/bkit-design-summary.md +0 -107
  407. package/.bkit/core/prompts/bkit-plan-complexity-check.md +0 -67
  408. package/.bkit/core/prompts/bkit-plan-complexity-split.md +0 -88
  409. package/.bkit/core/prompts/bkit-plan-review-3.md +0 -93
  410. package/.bkit/core/prompts/bkit-plan-scope-check-1.md +0 -85
  411. package/.bkit/core/prompts/bkit-plan-scope-check-2.md +0 -85
  412. package/.bkit/core/prompts/bkit-plan-summary.md +0 -107
  413. package/.bkit/core/prompts/bkit-ship-summary.md +0 -78
  414. package/.bkit/templates/scripts/ci/bkit-local-stack-lock.sh +0 -194
  415. package/dist/commands/harvest.js +0 -353
  416. package/dist/commands/workflow/workstreams.js +0 -143
  417. package/dist/tools/wording.js +0 -680
  418. /package/.bkit/templates/.vale/styles/{House → Bkit}/Filler.yml +0 -0
  419. /package/.bkit/templates/.vale/styles/{House → Bkit}/Hedging.yml +0 -0
  420. /package/.bkit/templates/.vale/styles/{House → Bkit}/LLMSlop.yml +0 -0
  421. /package/.bkit/templates/.vale/styles/{House → Bkit}/Verbose.yml +0 -0
  422. /package/.bkit/templates/scripts/ci/{accepted-advisories.json → bkit-accepted-advisories.json} +0 -0
  423. /package/.bkit/templates/scripts/ci/{accepted-divergences.json → bkit-accepted-divergences.json} +0 -0
  424. /package/.bkit/templates/scripts/launchd/{launchd.env.example → bkit-launchd.env.example} +0 -0
  425. /package/.bkit/templates/scripts/launchd/{ai.bkit.launchd.plist → bkit-launchd.plist} +0 -0
@@ -1,5 +1,7 @@
1
- // bkit ledgers commit|union|only-bookkeeping — stage and commit bookkeeping by
2
- // an allow-list, never `git add -A`.
1
+ // bkit ledgers commit|union|only-bookkeeping|append|check|triage|compact — stage and
2
+ // commit bookkeeping by an allow-list, never `git add -A`; append validated rows with
3
+ // a minted `ts`; check that the ledger rows a plan names are on disk; drop superseded
4
+ // rows from the keyed ledgers.
3
5
  //
4
6
  // The pathspec is built by `git ls-files` against quoted globs, so git does the
5
7
  // matching and an unmatched glob is empty output, never a shell abort. Staging
@@ -12,9 +14,40 @@ import * as fs from "node:fs";
12
14
  import * as os from "node:os";
13
15
  import * as path from "node:path";
14
16
 
15
- import { gitEnv } from "../../ledgers/telemetry.js";
16
- import { CommandError, EXIT, type CommandSpec, type FlagSpec, type RunContext } from "../lib.js";
17
+ import { readBkitVersion } from "../../install/version-file.js";
18
+ import { readBkitConfig } from "../../shared/settings.js";
19
+ import {
20
+ APPEND_LEDGERS,
21
+ SCHEMA,
22
+ UNJUSTIFIED_REASON,
23
+ gitEnv,
24
+ parse,
25
+ mintTs,
26
+ resolveRepoSlug,
27
+ validate,
28
+ withLineage,
29
+ writerProblem,
30
+ type AppendLedger,
31
+ } from "../../ledgers/telemetry.js";
32
+ import { COMPACT_LEDGERS, compactLedgers, type CompactLedger } from "../../ledgers/compact.js";
33
+ import {
34
+ CommandError,
35
+ EXIT,
36
+ isIgnoredPath,
37
+ isSharedBranch,
38
+ parseJson,
39
+ type CommandSpec,
40
+ type FlagSpec,
41
+ type RunContext,
42
+ } from "../lib.js";
17
43
  import { str } from "./status.js";
44
+ import {
45
+ NO_MARKERS_REASON,
46
+ outOfScope,
47
+ parsePlanBlocks,
48
+ reuseInventory,
49
+ type OutOfScopeRow,
50
+ } from "./plan-blocks.js";
18
51
 
19
52
  /** Root is not a directory or repo, git is too old, or a ref does not resolve. */
20
53
  export const EXIT_ROOT = 3;
@@ -26,16 +59,30 @@ export const EXIT_COMMIT = 5;
26
59
  export const EXIT_EMPTY = 6;
27
60
  /** only-bookkeeping: a non-bookkeeping path changed, or from is not an ancestor of to. */
28
61
  export const EXIT_NOT_BOOKKEEPING = 7;
62
+ /** append: a row was refused (supplied `ts`, wrong kind, invalid, unlisted writer). */
63
+ export const EXIT_ROW_REFUSED = 8;
29
64
 
30
65
  const SCOPES = ["core", "full", "pr"] as const;
31
66
  export type Scope = (typeof SCOPES)[number];
32
67
  const MODES = ["stage", "commit", "commit-allow-empty"];
33
68
 
69
+ /** `package.json` globs as git pathspecs: `:(glob)` unless an entry carries its own magic. */
70
+ export const globPathspecs = (paths: readonly string[]): string[] =>
71
+ paths.map((p) => (p.startsWith(":") ? p : `:(glob)${p}`));
72
+
34
73
  /**
35
74
  * The bookkeeping allow-list. Plain git pathspec `*` crosses `/`, so the
36
- * top-level-only entry uses the `:(glob)` magic.
75
+ * top-level-only entries use the `:(glob)` magic. `extra` is
76
+ * `bkit.testing.ciSkipPaths` (`ciSkipPaths`), the project docs a repo
77
+ * keeps outside `docs/*.md` (bkit's own: `CHANGELOG.md`, `README.md`); it reaches
78
+ * the `pr` scope only.
37
79
  */
38
- export function bookPathspecs(month: string, fid: string, scope: Scope): string[] {
80
+ export function bookPathspecs(
81
+ month: string,
82
+ fid: string,
83
+ scope: Scope,
84
+ extra: readonly string[] = [],
85
+ ): string[] {
39
86
  const specs = [
40
87
  `docs/plans/${month}/logs/${fid}/*`,
41
88
  ".bkit/friction.jsonl",
@@ -59,10 +106,14 @@ export function bookPathspecs(month: string, fid: string, scope: Scope): string[
59
106
  ".opencode/skills/*",
60
107
  );
61
108
  }
62
- // `pr` adds the project docs ship's docs sync edits, for the commit that rides
63
- // the PR. Kept out of `full` so a close on a laptop's dev checkout never sweeps
64
- // unrelated dirty docs into its commit.
65
- if (scope === "pr") specs.push(":(glob)docs/*.md");
109
+ // `pr` adds the project docs ship's docs sync edits, for the commit that rides the
110
+ // PR: top-level `docs/*.md`, plus whatever the repo names in `ciSkipPaths` (the
111
+ // engine hardcodes no file name; a glob nothing matches selects nothing). Kept out
112
+ // of `full` so a close on a laptop's dev checkout never sweeps unrelated dirty docs
113
+ // into its commit.
114
+ if (scope === "pr") {
115
+ specs.push(":(glob)docs/*.md", ...globPathspecs(extra));
116
+ }
66
117
  return specs;
67
118
  }
68
119
 
@@ -84,12 +135,18 @@ interface GitResult {
84
135
  }
85
136
 
86
137
  /** `git <args>` in `cwd`, never throwing and never trimming (NUL-delimited output). */
87
- function gitRaw(cwd: string, args: string[]): GitResult {
138
+ function gitRaw(
139
+ cwd: string,
140
+ args: string[],
141
+ env: NodeJS.ProcessEnv = {},
142
+ input?: string,
143
+ ): GitResult {
88
144
  const res = spawnSync("git", args, {
89
145
  cwd,
90
146
  encoding: "utf-8",
91
- env: gitEnv(),
147
+ env: { ...gitEnv(), ...env },
92
148
  maxBuffer: 1 << 28,
149
+ ...(input === undefined ? {} : { input }),
93
150
  });
94
151
  // A spawn error is never a success: the child can exit 0 before ENOBUFS kills it.
95
152
  const status = res.error && res.status === 0 ? 1 : res.status;
@@ -152,6 +209,479 @@ function dirtyTracked(root: string): string[] {
152
209
  .filter((l) => l !== "" && !l.startsWith("??"));
153
210
  }
154
211
 
212
+ // ---------------------------------------------------------------------------
213
+ // Shared-checkout record — the one home
214
+ // ---------------------------------------------------------------------------
215
+ //
216
+ // An in-place run on `dev` shares its checkout with whatever else is dirty or
217
+ // committed there. At `worktrees setup` the run snapshots which paths were
218
+ // already dirty (and the HEAD it started from) into a per-clone file under the
219
+ // git dir, never committed. Every commit the run makes goes through
220
+ // `ownPathCommit`, which leaves those paths alone, and records its SHA so the
221
+ // push sends exactly the run's commits. Nothing else reads or writes the file.
222
+
223
+ /** Exit code: a path that was dirty before the run changed during it, so no commit was made. */
224
+ export const EXIT_FOREIGN_PATH = 10;
225
+
226
+ /** check: the plan has no `**Ledger rows:**` line, it is unfilled, or a key it names is on no ledger. */
227
+ export const EXIT_ROWS_MISSING = 11;
228
+
229
+ /** commit --scope=pr: the checkout is on `dev`, `main` or a detached HEAD, so nothing is committed. */
230
+ export const EXIT_SHARED_BRANCH = 12;
231
+
232
+ /** A path dirty at the run's start: its content hash (null when deleted) and, for an append-only ledger, its line count. */
233
+ export interface RecordedPath {
234
+ path: string;
235
+ hash: string | null;
236
+ lines?: number;
237
+ }
238
+
239
+ export interface SharedCheckoutRecord {
240
+ fid: string;
241
+ branch: string;
242
+ startSha: string;
243
+ originSha: string | null;
244
+ aheadAtStart: number;
245
+ paths: RecordedPath[];
246
+ /** SHAs of the commits the run made, in order. */
247
+ commits: string[];
248
+ /** Run commits already landed on origin/dev as replayed copies (different SHAs there). */
249
+ pushed?: string[];
250
+ }
251
+
252
+ const RECORD_DIR = "bkit/shared-checkout";
253
+ const RECORD_FID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
254
+
255
+ /** The checkout's top: git status and pathspecs are relative to it, whatever `cwd` is. */
256
+ function topOf(cwd: string): string {
257
+ const top = gitRaw(cwd, ["rev-parse", "--show-toplevel"]);
258
+ return top.status === 0 ? top.stdout.trim() : cwd;
259
+ }
260
+
261
+ /** `$(git rev-parse --git-path bkit/shared-checkout/{sub})`, absolute; null outside a repo. */
262
+ function recordPathOf(cwd: string, sub: string): string | null {
263
+ const res = gitRaw(cwd, ["rev-parse", "--git-path", `${RECORD_DIR}/${sub}`]);
264
+ return res.status === 0 && res.stdout.trim() !== "" ? path.resolve(cwd, res.stdout.trim()) : null;
265
+ }
266
+
267
+ const recordFile = (cwd: string, fid: string): string | null =>
268
+ RECORD_FID.test(fid) && !fid.includes("..") ? recordPathOf(cwd, `${fid}.json`) : null;
269
+
270
+ function asRecord(value: unknown): SharedCheckoutRecord | null {
271
+ if (typeof value !== "object" || value === null) return null;
272
+ const r = value as Record<string, unknown>;
273
+ if (
274
+ typeof r.fid !== "string" ||
275
+ typeof r.branch !== "string" ||
276
+ typeof r.startSha !== "string" ||
277
+ typeof r.aheadAtStart !== "number" ||
278
+ !Array.isArray(r.paths) ||
279
+ !Array.isArray(r.commits)
280
+ )
281
+ return null;
282
+ return {
283
+ fid: r.fid,
284
+ branch: r.branch,
285
+ startSha: r.startSha,
286
+ originSha: typeof r.originSha === "string" ? r.originSha : null,
287
+ aheadAtStart: r.aheadAtStart,
288
+ paths: (r.paths as RecordedPath[]).filter((p) => typeof p?.path === "string"),
289
+ commits: (r.commits as unknown[]).filter((c): c is string => typeof c === "string"),
290
+ ...(Array.isArray(r.pushed)
291
+ ? { pushed: (r.pushed as unknown[]).filter((c): c is string => typeof c === "string") }
292
+ : {}),
293
+ };
294
+ }
295
+
296
+ /** The FID's record, or null when absent or unreadable. */
297
+ export function readRecord(cwd: string, fid: string): SharedCheckoutRecord | null {
298
+ const file = recordFile(cwd, fid);
299
+ if (file === null || !fs.existsSync(file)) return null;
300
+ const parsed = parseJson(fs.readFileSync(file, "utf-8"));
301
+ return parsed.ok ? asRecord(parsed.value) : null;
302
+ }
303
+
304
+ /** Note run commits that now sit on origin/dev as replayed copies, so a later push skips them. */
305
+ export function markRecordPushed(cwd: string, fid: string, shas: string[]): void {
306
+ const rec = readRecord(cwd, fid);
307
+ if (rec === null) return;
308
+ writeRecord(cwd, { ...rec, pushed: [...new Set([...(rec.pushed ?? []), ...shas])] });
309
+ }
310
+
311
+ /** Every record in this clone. */
312
+ export function listRecords(cwd: string): SharedCheckoutRecord[] {
313
+ const dir = recordPathOf(cwd, "");
314
+ if (dir === null || !fs.existsSync(dir)) return [];
315
+ return fs
316
+ .readdirSync(dir)
317
+ .filter((f) => f.endsWith(".json"))
318
+ .map((f) => readRecord(cwd, f.slice(0, -".json".length)))
319
+ .filter((r): r is SharedCheckoutRecord => r !== null);
320
+ }
321
+
322
+ export function writeRecord(cwd: string, rec: SharedCheckoutRecord): void {
323
+ const file = recordFile(cwd, rec.fid);
324
+ if (file === null) throw new CommandError(EXIT_ROOT, `cannot place a record for "${rec.fid}"`);
325
+ fs.mkdirSync(path.dirname(file), { recursive: true });
326
+ fs.writeFileSync(file, `${JSON.stringify(rec, null, 2)}\n`);
327
+ }
328
+
329
+ /** A setup guard older than this is a crashed setup's leftover. */
330
+ const SETUP_GUARD_STALE_MS = 30_000;
331
+
332
+ /**
333
+ * Run `fn` as the only record-setup in this clone: an exclusive-create guard file
334
+ * next to the records makes the busy check and the record write one step. Returns
335
+ * null, without running `fn`, when another setup holds a fresh guard.
336
+ */
337
+ export function withSetupGuard<T>(cwd: string, fn: () => T): { value: T } | null {
338
+ const guard = recordPathOf(cwd, ".setup.lock");
339
+ if (guard === null) return { value: fn() };
340
+ fs.mkdirSync(path.dirname(guard), { recursive: true });
341
+ const take = (): boolean => {
342
+ try {
343
+ fs.closeSync(fs.openSync(guard, "wx"));
344
+ return true;
345
+ } catch (err) {
346
+ if ((err as NodeJS.ErrnoException).code === "EEXIST") return false;
347
+ throw err;
348
+ }
349
+ };
350
+ if (!take()) {
351
+ const age = fs.existsSync(guard) ? Date.now() - fs.statSync(guard).mtimeMs : Infinity;
352
+ if (age < SETUP_GUARD_STALE_MS) return null;
353
+ fs.rmSync(guard, { force: true });
354
+ if (!take()) return null;
355
+ }
356
+ try {
357
+ return { value: fn() };
358
+ } finally {
359
+ fs.rmSync(guard, { force: true });
360
+ }
361
+ }
362
+
363
+ /** Remove the FID's record; false when there was none. */
364
+ export function removeRecord(cwd: string, fid: string): boolean {
365
+ const file = recordFile(cwd, fid);
366
+ if (file === null || !fs.existsSync(file)) return false;
367
+ fs.rmSync(file, { force: true });
368
+ return true;
369
+ }
370
+
371
+ /** The FID's record, only while its branch is still the one checked out. */
372
+ export function activeRecord(cwd: string, fid: string): SharedCheckoutRecord | null {
373
+ const rec = readRecord(cwd, fid);
374
+ if (rec === null) return null;
375
+ const here = gitRaw(cwd, ["branch", "--show-current"]).stdout.trim();
376
+ return here === rec.branch ? rec : null;
377
+ }
378
+
379
+ /**
380
+ * The record of the run in place on `branch`, for a command that is not told
381
+ * its FID (the push). Setup keeps one live record per clone; if several are left
382
+ * over, the one written last wins.
383
+ */
384
+ export function recordOnBranch(cwd: string, branch: string): SharedCheckoutRecord | null {
385
+ const dir = recordPathOf(cwd, "");
386
+ const written = (r: SharedCheckoutRecord) => {
387
+ const file = recordFile(cwd, r.fid);
388
+ return file !== null && fs.existsSync(file) ? fs.statSync(file).mtimeMs : 0;
389
+ };
390
+ const ours = listRecords(cwd).filter((r) => r.branch === branch);
391
+ if (dir === null || ours.length === 0) return null;
392
+ return ours.reduce((a, b) => (written(b) > written(a) ? b : a));
393
+ }
394
+
395
+ /** Append a commit the run made; called only after the commit succeeded. */
396
+ export function appendRecordCommit(cwd: string, fid: string, sha: string): void {
397
+ const rec = readRecord(cwd, fid);
398
+ if (rec === null || rec.commits.includes(sha)) return;
399
+ writeRecord(cwd, { ...rec, commits: [...rec.commits, sha] });
400
+ }
401
+
402
+ /** Paths git reports as changed or untracked, relative to the top, one per file. */
403
+ function dirtyPaths(top: string): string[] {
404
+ const res = gitRaw(top, ["status", "--porcelain", "-z", "-uall", "--no-renames"]);
405
+ return nulList(res.stdout)
406
+ .filter((e) => e.length > 3 && !e.startsWith("!!"))
407
+ .map((e) => e.slice(3));
408
+ }
409
+
410
+ /** `git hash-object` of the working file; null when it is gone. */
411
+ function hashOf(top: string, rel: string): string | null {
412
+ const abs = path.join(top, rel);
413
+ if (!fs.existsSync(abs)) return null;
414
+ if (!fs.statSync(abs).isFile()) return "not-a-file";
415
+ const res = gitRaw(top, ["hash-object", "--", rel]);
416
+ return res.status === 0 ? res.stdout.trim() : "unhashable";
417
+ }
418
+
419
+ /** A text's non-blank lines. */
420
+ const rowsOf = (text: string) => text.split("\n").filter((l) => l.trim() !== "");
421
+
422
+ /** Lines of `file` in `cwd`'s working copy that its HEAD blob lacks (compared trimmed). */
423
+ export function rowsHeadLacks(cwd: string, file: string): string[] {
424
+ const head = new Set(rowsOf(gitRaw(cwd, ["show", `HEAD:${file}`]).stdout).map((l) => l.trim()));
425
+ return rowsOf(fs.readFileSync(path.join(cwd, file), "utf-8")).filter((l) => !head.has(l.trim()));
426
+ }
427
+
428
+ /**
429
+ * Rows of `file` the run appended: lines HEAD lacks, and past the recorded line
430
+ * count when the run's record holds the file (rows before it are someone else's).
431
+ */
432
+ export function runRows(cwd: string, file: string, rec: SharedCheckoutRecord | null): string[] {
433
+ const was = rec?.paths.find((p) => p.path === file);
434
+ if (was?.lines === undefined) return rowsHeadLacks(cwd, file);
435
+ const head = gitRaw(cwd, ["show", `HEAD:${file}`]);
436
+ const have = new Set(rowsOf(head.status === 0 ? head.stdout : "").map((l) => l.trim()));
437
+ const lines = fs.readFileSync(path.join(cwd, file), "utf-8").split("\n").slice(was.lines);
438
+ return rowsOf(lines.join("\n")).filter((l) => !have.has(l.trim()));
439
+ }
440
+
441
+ /** The record for a run starting now in `cwd` on `branch`. */
442
+ export function newRecord(cwd: string, fid: string, branch: string): SharedCheckoutRecord {
443
+ const top = topOf(cwd);
444
+ const startSha = gitRaw(top, ["rev-parse", "HEAD"]).stdout.trim();
445
+ const origin = gitRaw(top, ["rev-parse", "-q", "--verify", `refs/remotes/origin/${branch}`]);
446
+ const originSha = origin.status === 0 ? origin.stdout.trim() : null;
447
+ const ahead =
448
+ originSha === null
449
+ ? 0
450
+ : Number(gitRaw(top, ["rev-list", "--count", `${originSha}..HEAD`]).stdout);
451
+ const paths = dirtyPaths(top).map((rel): RecordedPath => {
452
+ const hash = hashOf(top, rel);
453
+ const abs = path.join(top, rel);
454
+ const text = hash !== null && rel.endsWith(".jsonl") ? fs.readFileSync(abs, "utf-8") : null;
455
+ return text !== null && (text === "" || text.endsWith("\n"))
456
+ ? { path: rel, hash, lines: fileLines(text).length }
457
+ : { path: rel, hash };
458
+ });
459
+ return { fid, branch, startSha, originSha, aheadAtStart: ahead, paths, commits: [] };
460
+ }
461
+
462
+ /** What a run may commit now: whole files, and recorded ledgers cut down to the run's rows. */
463
+ export interface OwnSet {
464
+ plain: string[];
465
+ ledgers: Array<{ path: string; text: string }>;
466
+ }
467
+
468
+ /**
469
+ * The paths that are the run's own: dirty now, minus every recorded path. A
470
+ * recorded append-only ledger contributes only the rows appended after the
471
+ * recorded line count that HEAD lacks. Any other recorded path whose content
472
+ * changed, or a ledger whose recorded lines changed, throws EXIT_FOREIGN_PATH.
473
+ * `among` limits which recorded paths count (a bookkeeping commit only commits
474
+ * its allow-list).
475
+ */
476
+ export function ownSet(cwd: string, rec: SharedCheckoutRecord, among?: string[]): OwnSet {
477
+ const top = topOf(cwd);
478
+ const recorded = new Map(rec.paths.map((p) => [p.path, p]));
479
+ const out: OwnSet = { plain: [], ledgers: [] };
480
+ const foreign: string[] = [];
481
+ for (const rel of dirtyPaths(top)) {
482
+ const was = recorded.get(rel);
483
+ if (was === undefined) {
484
+ out.plain.push(rel);
485
+ continue;
486
+ }
487
+ if (among !== undefined && !among.includes(rel)) continue;
488
+ if (hashOf(top, rel) === was.hash) continue;
489
+ if (was.lines === undefined) {
490
+ foreign.push(rel);
491
+ continue;
492
+ }
493
+ const text = fs.readFileSync(path.join(top, rel), "utf-8");
494
+ const lines = text.split("\n");
495
+ const prefix = `${lines.slice(0, was.lines).join("\n")}\n`;
496
+ // `--path` applies the same clean / eol filters `hashOf` hashed the file with.
497
+ const prefixHash = gitRaw(
498
+ top,
499
+ ["hash-object", `--path=${rel}`, "--stdin"],
500
+ {},
501
+ prefix,
502
+ ).stdout.trim();
503
+ if (was.lines > 0 && prefixHash !== was.hash) {
504
+ foreign.push(rel);
505
+ continue;
506
+ }
507
+ const own = runRows(top, rel, rec);
508
+ if (own.length === 0) continue;
509
+ const head = gitRaw(top, ["show", `HEAD:${rel}`]);
510
+ const base = head.status === 0 ? head.stdout : "";
511
+ const sep = base === "" || base.endsWith("\n") ? "" : "\n";
512
+ out.ledgers.push({ path: rel, text: `${base}${sep}${own.join("\n")}\n` });
513
+ }
514
+ if (foreign.length > 0) {
515
+ throw new CommandError(
516
+ EXIT_FOREIGN_PATH,
517
+ `refusing to commit: ${foreign.join(", ")} changed during the run but was already modified before it started — nothing committed; commit or revert ${foreign.length === 1 ? "it" : "them"} yourself, then re-run`,
518
+ );
519
+ }
520
+ return out;
521
+ }
522
+
523
+ export type OwnCommit = { ok: true; sha: string | null } | { ok: false; error: string };
524
+
525
+ /**
526
+ * Rebuild the real index entry of a ledger the user staged before the run: the
527
+ * new HEAD blob plus the staged rows HEAD lacks, so the user's next plain commit
528
+ * keeps the run's committed rows.
529
+ */
530
+ function restageLedger(top: string, rel: string): void {
531
+ const staged = gitRaw(top, ["show", `:${rel}`]);
532
+ const head = gitRaw(top, ["show", `HEAD:${rel}`]);
533
+ if (staged.status !== 0 || head.status !== 0) return;
534
+ const have = new Set(rowsOf(head.stdout).map((l) => l.trim()));
535
+ const theirs = rowsOf(staged.stdout).filter((l) => !have.has(l.trim()));
536
+ if (theirs.length === 0) {
537
+ gitRaw(top, ["reset", "-q", "--", rel]);
538
+ return;
539
+ }
540
+ const sep = head.stdout === "" || head.stdout.endsWith("\n") ? "" : "\n";
541
+ const blob = gitRaw(
542
+ top,
543
+ ["hash-object", "-w", "--stdin"],
544
+ {},
545
+ `${head.stdout}${sep}${theirs.join("\n")}\n`,
546
+ );
547
+ if (blob.status !== 0) return;
548
+ gitRaw(top, ["update-index", "--cacheinfo", `100644,${blob.stdout.trim()},${rel}`]);
549
+ }
550
+
551
+ /**
552
+ * Commit `set` and nothing else: foreign index entries stay staged and foreign
553
+ * files stay out. Plain files go through a pathspec commit; ledger rows, or an
554
+ * empty set, go through a temporary index read from HEAD. With `skipIfEmpty`, no
555
+ * change against HEAD makes no commit (`sha` null). The caller records the SHA.
556
+ */
557
+ export function commitOwnSet(
558
+ cwd: string,
559
+ set: OwnSet,
560
+ message: string,
561
+ o: { allowEmpty?: boolean; skipIfEmpty?: boolean } = {},
562
+ ): OwnCommit {
563
+ const top = topOf(cwd);
564
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "bkit-own-"));
565
+ try {
566
+ const list = path.join(tmp, "list");
567
+ const all = [...set.plain, ...set.ledgers.map((l) => l.path)];
568
+ // `dirtyPaths` drops ignored entries, so `all` never holds one today; name the
569
+ // failure if a future caller passes a gitignored path, rather than let git's
570
+ // ignored-paths guard surface as an opaque stage error.
571
+ const ignored = all.filter((p) => isIgnoredPath(top, p));
572
+ if (ignored.length > 0) {
573
+ return { ok: false, error: `refusing to stage gitignored path(s): ${ignored.join(", ")}` };
574
+ }
575
+ fs.writeFileSync(list, all.map((p) => `${p}\0`).join(""));
576
+ const stagedBefore = new Set(
577
+ nulList(gitRaw(top, ["diff", "--cached", "--name-only", "-z"]).stdout),
578
+ );
579
+ const tail = ["-m", message];
580
+ let made: GitResult;
581
+ if (set.ledgers.length === 0 && set.plain.length > 0) {
582
+ const add = gitRaw(top, ["add", `--pathspec-from-file=${list}`, "--pathspec-file-nul"]);
583
+ if (add.status !== 0) return { ok: false, error: `'git add' failed: ${add.stderr}` };
584
+ if (
585
+ o.skipIfEmpty === true &&
586
+ gitRaw(top, ["diff", "--cached", "--quiet", "--", ...set.plain]).status === 0
587
+ )
588
+ return { ok: true, sha: null };
589
+ made = gitRaw(top, [
590
+ "commit",
591
+ ...(o.allowEmpty === true ? ["--allow-empty"] : []),
592
+ `--pathspec-from-file=${list}`,
593
+ "--pathspec-file-nul",
594
+ ...tail,
595
+ ]);
596
+ } else {
597
+ const env = { GIT_INDEX_FILE: path.join(tmp, "index") };
598
+ if (gitRaw(top, ["rev-parse", "-q", "--verify", "HEAD"]).status === 0) {
599
+ const read = gitRaw(top, ["read-tree", "HEAD"], env);
600
+ if (read.status !== 0)
601
+ return { ok: false, error: `'git read-tree' failed: ${read.stderr}` };
602
+ }
603
+ if (set.plain.length > 0) {
604
+ const add = gitRaw(
605
+ top,
606
+ ["add", `--pathspec-from-file=${list}`, "--pathspec-file-nul"],
607
+ env,
608
+ );
609
+ if (add.status !== 0) return { ok: false, error: `'git add' failed: ${add.stderr}` };
610
+ }
611
+ for (const l of set.ledgers) {
612
+ const blob = gitRaw(top, ["hash-object", "-w", "--stdin"], env, l.text);
613
+ const upd = gitRaw(
614
+ top,
615
+ ["update-index", "--add", "--cacheinfo", `100644,${blob.stdout.trim()},${l.path}`],
616
+ env,
617
+ );
618
+ if (blob.status !== 0 || upd.status !== 0) {
619
+ return { ok: false, error: `'git update-index' failed: ${upd.stderr || blob.stderr}` };
620
+ }
621
+ }
622
+ if (o.skipIfEmpty === true && gitRaw(top, ["diff", "--cached", "--quiet"], env).status === 0)
623
+ return { ok: true, sha: null };
624
+ made = gitRaw(
625
+ top,
626
+ ["commit", ...(o.allowEmpty === true ? ["--allow-empty"] : []), ...tail],
627
+ env,
628
+ );
629
+ if (made.status === 0 && all.length > 0) {
630
+ // The real index still holds the pre-commit entries; bring the run's own
631
+ // (unstaged-by-anyone-else) paths level with the new HEAD.
632
+ const reset = all.filter((p) => !stagedBefore.has(p));
633
+ fs.writeFileSync(list, reset.map((p) => `${p}\0`).join(""));
634
+ if (reset.length > 0) {
635
+ gitRaw(top, ["reset", "-q", `--pathspec-from-file=${list}`, "--pathspec-file-nul"]);
636
+ }
637
+ // A ledger the user had staged keeps their rows in the index, on top of the new HEAD's.
638
+ for (const l of set.ledgers) if (stagedBefore.has(l.path)) restageLedger(top, l.path);
639
+ }
640
+ }
641
+ if (made.status !== 0) {
642
+ // Leave the index as it was: unstage what this attempt staged, never another's entry.
643
+ const unstage = all.filter((p) => !stagedBefore.has(p));
644
+ fs.writeFileSync(list, unstage.map((p) => `${p}\0`).join(""));
645
+ if (unstage.length > 0)
646
+ gitRaw(top, ["reset", "-q", `--pathspec-from-file=${list}`, "--pathspec-file-nul"]);
647
+ return { ok: false, error: made.stderr || made.stdout.trim() };
648
+ }
649
+ return { ok: true, sha: gitRaw(top, ["rev-parse", "HEAD"]).stdout.trim() };
650
+ } finally {
651
+ fs.rmSync(tmp, { recursive: true, force: true });
652
+ }
653
+ }
654
+
655
+ /**
656
+ * The run's own-path commit: compute the own set from the record, commit it,
657
+ * append the SHA to the record. Throws EXIT_FOREIGN_PATH before committing.
658
+ */
659
+ export function ownPathCommit(
660
+ cwd: string,
661
+ rec: SharedCheckoutRecord,
662
+ message: string,
663
+ o: { allowEmpty?: boolean } = {},
664
+ ): OwnCommit {
665
+ const made = commitOwnSet(cwd, ownSet(cwd, rec), message, o);
666
+ if (made.ok && made.sha !== null) appendRecordCommit(cwd, rec.fid, made.sha);
667
+ return made;
668
+ }
669
+
670
+ /**
671
+ * An empty commit of the run's own: nothing from the working tree or the real
672
+ * index goes in, so a path the user staged never lands in it. The SHA is
673
+ * appended to the record.
674
+ */
675
+ export function retriggerCommit(
676
+ cwd: string,
677
+ rec: SharedCheckoutRecord,
678
+ message: string,
679
+ ): OwnCommit {
680
+ const made = commitOwnSet(cwd, { plain: [], ledgers: [] }, message, { allowEmpty: true });
681
+ if (made.ok && made.sha !== null) appendRecordCommit(cwd, rec.fid, made.sha);
682
+ return made;
683
+ }
684
+
155
685
  // ---------------------------------------------------------------------------
156
686
  // Command
157
687
  // ---------------------------------------------------------------------------
@@ -159,10 +689,11 @@ function dirtyTracked(root: string): string[] {
159
689
  export const ledgersCommand: CommandSpec = {
160
690
  noun: "ledgers",
161
691
  summary:
162
- "Stage and commit bookkeeping by allow-list; union ledgers; check a range is bookkeeping only.",
692
+ "Stage and commit bookkeeping by allow-list; union ledgers; check a range is bookkeeping only; compact keyed ledgers.",
163
693
  verbs: {
164
694
  commit: {
165
695
  summary: "Stage (and commit) the bookkeeping allow-list for one feature.",
696
+ use: "workflow",
166
697
  flags: [
167
698
  ROOT_FLAG,
168
699
  MONTH_FLAG,
@@ -170,8 +701,7 @@ export const ledgersCommand: CommandSpec = {
170
701
  {
171
702
  name: "scope",
172
703
  type: "string",
173
- required: true,
174
- help: "core (logs + ledgers) | full (+ docs ledgers, skills) | pr (+ top-level docs/*.md)",
704
+ help: "core (logs + ledgers) | full (+ docs ledgers, skills) | pr (+ top-level docs/*.md); not with --path",
175
705
  },
176
706
  {
177
707
  name: "mode",
@@ -182,7 +712,12 @@ export const ledgersCommand: CommandSpec = {
182
712
  {
183
713
  name: "stage-tracked-updates",
184
714
  type: "boolean",
185
- help: "run `git add -u` first (stages every tracked change)",
715
+ help: "run `git add -u` first (stages every tracked change; commit modes commit them too)",
716
+ },
717
+ {
718
+ name: "path",
719
+ type: "string",
720
+ help: "commit this one path alone, relative to --root (commit modes only; no --scope)",
186
721
  },
187
722
  {
188
723
  name: "squash-of",
@@ -200,7 +735,8 @@ export const ledgersCommand: CommandSpec = {
200
735
  outcome:
201
736
  "committed | staged | nothing-to-commit | clean (no tracked changes, with --only-if-dirty-tracked)",
202
737
  commit: "the new commit's sha, or null",
203
- paths: "bookkeeping paths the allow-list matched",
738
+ paths: "bookkeeping paths the allow-list matched (the --path alone with --path)",
739
+ tracked: "tracked paths --stage-tracked-updates staged into the commit",
204
740
  squashPaths: "paths the --squash-of ref brought in",
205
741
  },
206
742
  exitCodes: {
@@ -208,13 +744,19 @@ export const ledgersCommand: CommandSpec = {
208
744
  "root not a directory or git repo, git < 2.25, or --squash-of does not resolve",
209
745
  [EXIT_STAGE]: "staging failed (git add / git add -u)",
210
746
  [EXIT_COMMIT]: "git commit failed",
211
- [EXIT_EMPTY]: "the allow-list matched nothing — refusing to commit the whole index",
747
+ [EXIT_EMPTY]:
748
+ "the allow-list matched nothing — refusing to commit the whole index; or --path is outside the checkout",
749
+ [EXIT_FOREIGN_PATH]:
750
+ "an in-place run's allow-listed path was already modified before the run and changed during it — nothing committed",
751
+ [EXIT_SHARED_BRANCH]:
752
+ "--scope=pr commit on dev, main or a detached HEAD — refused, nothing committed",
212
753
  },
213
754
  run: (ctx) => commit(ctx),
214
755
  },
215
756
  union: {
216
757
  summary:
217
758
  "Append a worktree's new ledger rows into another checkout (never .bkit/issues.jsonl).",
759
+ use: "workflow",
218
760
  flags: [
219
761
  { name: "src", type: "string", required: true, help: "worktree to read ledgers from" },
220
762
  { name: "dst", type: "string", required: true, help: "checkout to append them to" },
@@ -228,6 +770,7 @@ export const ledgersCommand: CommandSpec = {
228
770
  },
229
771
  "only-bookkeeping": {
230
772
  summary: "Exit 0 when every path changed in from..to is on the --scope=pr allow-list.",
773
+ use: "by-hand",
231
774
  flags: [
232
775
  ROOT_FLAG,
233
776
  MONTH_FLAG,
@@ -246,6 +789,105 @@ export const ledgersCommand: CommandSpec = {
246
789
  },
247
790
  run: (ctx) => onlyBookkeeping(ctx),
248
791
  },
792
+ append: {
793
+ summary: "Append validated rows to one ledger, minting each row's ts at append time.",
794
+ use: "by-hand",
795
+ flags: [
796
+ { name: "root", type: "string", help: "checkout whose ledger to append to (default: cwd)" },
797
+ {
798
+ name: "ledger",
799
+ type: "string",
800
+ required: true,
801
+ help: Object.keys(APPEND_LEDGERS).join(" | "),
802
+ },
803
+ {
804
+ name: "rows",
805
+ type: "string",
806
+ required: true,
807
+ help: "file holding a JSON array of rows without schema, ts or bkit, or - for stdin",
808
+ },
809
+ ],
810
+ output: {
811
+ ledger: "the ledger appended to",
812
+ file: "its path, relative to --root",
813
+ appended: "rows written",
814
+ keys: "each row's key, in order (null when a row has none)",
815
+ },
816
+ exitCodes: {
817
+ [EXIT_STAGE]: "mkdir or append failed",
818
+ [EXIT_ROW_REFUSED]:
819
+ "a row carries ts, has the wrong kind, fails validation, or names a writer not listed for its kind — nothing written",
820
+ },
821
+ run: (ctx) => append(ctx),
822
+ },
823
+ triage: {
824
+ summary:
825
+ "Bucket each deferral row the FID declared by the four Deferral Reason tests, and write the unjustified ones.",
826
+ use: "workflow",
827
+ flags: [
828
+ { name: "root", type: "string", help: "checkout whose deferrals to read (default: cwd)" },
829
+ FID_FLAG,
830
+ {
831
+ name: "plan",
832
+ type: "string",
833
+ required: true,
834
+ help: "plan file whose task surfaces and Out of Scope rows the four tests read",
835
+ },
836
+ ],
837
+ output: {
838
+ fid: "the feature id triaged",
839
+ plan: "the plan the tests were read from",
840
+ rows: "each matched deferral's key, bucket (Exempt | Lazy), test results (none for a settled row: closed, LOW, or already adjudicated) and whether a row was written",
841
+ total: "deferral rows the FID matched",
842
+ written: "unjustified rows appended",
843
+ },
844
+ exitCodes: {
845
+ [EXIT_ROW_REFUSED]:
846
+ "a computed unjustified row fails validation or its writer check — nothing written",
847
+ },
848
+ run: (ctx) => triage(ctx),
849
+ },
850
+ check: {
851
+ summary:
852
+ "Check that every decision / deferral key on a plan's `**Ledger rows:**` line is on disk.",
853
+ use: "by-hand",
854
+ flags: [
855
+ { name: "root", type: "string", help: "checkout whose ledgers to read (default: cwd)" },
856
+ { name: "plan", type: "string", required: true, help: "plan file, relative to --root" },
857
+ ],
858
+ output: {
859
+ plan: "the plan checked",
860
+ keys: "the keys its Ledger rows line names (empty for None)",
861
+ missing: "keys on neither docs/decisions.jsonl nor docs/deferrals.jsonl",
862
+ },
863
+ exitCodes: {
864
+ [EXIT_ROWS_MISSING]:
865
+ "no `**Ledger rows:**` line, the line is unfilled, or a key it names has no row",
866
+ },
867
+ run: (ctx) => check(ctx),
868
+ },
869
+ compact: {
870
+ summary:
871
+ "Rewrite keyed ledgers to their fold winners, stamping each winner's firstTs + updates.",
872
+ use: "by-hand",
873
+ flags: [
874
+ { name: "root", type: "string", help: "checkout whose ledgers to compact (default: cwd)" },
875
+ {
876
+ name: "ledger",
877
+ type: "string",
878
+ help: `${Object.keys(COMPACT_LEDGERS).join(" | ")} | all (default: all)`,
879
+ },
880
+ { name: "dry-run", type: "boolean", help: "count only; write nothing" },
881
+ ],
882
+ output: {
883
+ dryRun: "true when nothing was written by design",
884
+ ledgers:
885
+ "per ledger: ledger, file, rows (keyed rows folded), dropped (superseded rows removed), stamped (winners given firstTs / updates), written",
886
+ dropped: "superseded rows removed across all ledgers",
887
+ },
888
+ exitCodes: { [EXIT_STAGE]: "writing a compacted ledger failed" },
889
+ run: (ctx) => compact(ctx),
890
+ },
249
891
  },
250
892
  };
251
893
 
@@ -260,6 +902,8 @@ export interface BookkeepingCommit {
260
902
  stageTrackedUpdates?: boolean;
261
903
  squashOf?: string;
262
904
  onlyIfDirtyTracked?: boolean;
905
+ /** Commit this one path alone (commit modes only). */
906
+ path?: string;
263
907
  }
264
908
 
265
909
  export interface BookkeepingResult {
@@ -267,6 +911,54 @@ export interface BookkeepingResult {
267
911
  commit: string | null;
268
912
  paths: string[];
269
913
  squashPaths: string[];
914
+ tracked: string[];
915
+ }
916
+
917
+ /** Commit one named path alone: `git add` it, then `git commit -- <path>`. */
918
+ function commitOnePath(o: BookkeepingCommit, log: (m: string) => void): BookkeepingResult {
919
+ const { root, mode, message } = o;
920
+ const rel = o.path!;
921
+ const abs = path.resolve(root, rel);
922
+ const inside = path.relative(root, abs);
923
+ if (inside === "" || inside.startsWith("..") || path.isAbsolute(inside)) {
924
+ throw new CommandError(EXIT_EMPTY, `--path is outside the checkout: ${rel}`);
925
+ }
926
+ const done = (outcome: BookkeepingResult["outcome"], sha: string | null): BookkeepingResult => ({
927
+ outcome,
928
+ commit: sha,
929
+ paths: [inside],
930
+ squashPaths: [],
931
+ tracked: [],
932
+ });
933
+ if (isIgnoredPath(root, inside)) {
934
+ throw new CommandError(EXIT_STAGE, `--path is gitignored, refusing to stage it: ${inside}`);
935
+ }
936
+ const add = gitRaw(root, ["add", "--", inside]);
937
+ if (add.status !== 0) throw new CommandError(EXIT_STAGE, `'git add' failed: ${add.stderr}`);
938
+ if (
939
+ mode === "commit" &&
940
+ gitRaw(root, ["diff", "--cached", "--quiet", "--", inside]).status === 0
941
+ ) {
942
+ log(`nothing to commit at ${inside}`);
943
+ return done("nothing-to-commit", null);
944
+ }
945
+ const made = gitRaw(root, [
946
+ "commit",
947
+ ...(mode === "commit-allow-empty" ? ["--allow-empty"] : []),
948
+ "-m",
949
+ message!,
950
+ "--",
951
+ inside,
952
+ ]);
953
+ if (made.status !== 0) {
954
+ throw new CommandError(
955
+ EXIT_COMMIT,
956
+ `'git commit' failed: ${made.stderr || made.stdout.trim()}`,
957
+ );
958
+ }
959
+ const sha = gitRaw(root, ["rev-parse", "HEAD"]).stdout.trim();
960
+ if (activeRecord(root, o.fid) !== null) appendRecordCommit(root, o.fid, sha);
961
+ return done("committed", sha);
270
962
  }
271
963
 
272
964
  /**
@@ -278,6 +970,20 @@ export function commitBookkeeping(
278
970
  log: (m: string) => void,
279
971
  ): BookkeepingResult {
280
972
  const { root, month, fid, scope, mode, message, squashOf } = o;
973
+ if (o.path !== undefined) {
974
+ if (mode === "stage" || !MODES.includes(mode)) {
975
+ throw new CommandError(EXIT.USAGE, "--path needs --mode=commit or commit-allow-empty");
976
+ }
977
+ if (o.stageTrackedUpdates === true || squashOf !== undefined || o.onlyIfDirtyTracked === true) {
978
+ throw new CommandError(
979
+ EXIT.USAGE,
980
+ "--path commits one path alone; drop --stage-tracked-updates, --squash-of and --only-if-dirty-tracked",
981
+ );
982
+ }
983
+ if (!message) throw new CommandError(EXIT.USAGE, `--message is required for --mode=${mode}`);
984
+ requireRepo(root);
985
+ return commitOnePath(o, log);
986
+ }
281
987
  if (!SCOPES.includes(scope)) {
282
988
  throw new CommandError(EXIT.USAGE, `--scope must be core, full, or pr (got '${scope}')`);
283
989
  }
@@ -294,6 +1000,15 @@ export function commitBookkeeping(
294
1000
  }
295
1001
 
296
1002
  requireRepo(root);
1003
+ if (scope === "pr" && mode !== "stage") {
1004
+ const branch = gitRaw(root, ["branch", "--show-current"]).stdout.trim();
1005
+ if (branch === "" || isSharedBranch(branch)) {
1006
+ throw new CommandError(
1007
+ EXIT_SHARED_BRANCH,
1008
+ `--scope=pr commits a feature branch's bookkeeping: refusing to commit on '${branch || "detached HEAD"}'`,
1009
+ );
1010
+ }
1011
+ }
297
1012
  if (
298
1013
  squashOf !== undefined &&
299
1014
  gitRaw(root, ["rev-parse", "-q", "--verify", `${squashOf}^{commit}`]).status !== 0
@@ -306,17 +1021,37 @@ export function commitBookkeeping(
306
1021
  const dirty = dirtyTracked(root);
307
1022
  if (dirty.length === 0) {
308
1023
  log("no tracked file has uncommitted changes — nothing to commit");
309
- return { outcome: "clean", commit: null, paths: [], squashPaths: [] };
1024
+ return { outcome: "clean", commit: null, paths: [], squashPaths: [], tracked: [] };
310
1025
  }
311
1026
  for (const line of dirty) log(line);
312
1027
  }
313
1028
 
1029
+ // An in-place run on a shared branch: recorded paths are someone else's.
1030
+ const rec = squashOf === undefined ? activeRecord(root, fid) : null;
1031
+ let tracked: string[] = [];
314
1032
  if (o.stageTrackedUpdates === true) {
315
- const res = gitRaw(root, ["add", "-u"]);
1033
+ // Throws EXIT_FOREIGN_PATH when any recorded path changed, before anything is staged.
1034
+ if (rec !== null) ownSet(root, rec);
1035
+ const keepOut = (rec?.paths ?? []).map((p) => `:(exclude,literal)${p.path}`);
1036
+ const res = gitRaw(root, ["add", "-u", ...(keepOut.length > 0 ? ["--", ".", ...keepOut] : [])]);
316
1037
  if (res.status !== 0) throw new CommandError(EXIT_STAGE, `'git add -u' failed: ${res.stderr}`);
1038
+ if (mode !== "stage") {
1039
+ const cached = gitRaw(root, [
1040
+ "diff",
1041
+ "--cached",
1042
+ "--name-only",
1043
+ "-z",
1044
+ "--no-renames",
1045
+ ...(keepOut.length > 0 ? ["--", ".", ...keepOut] : []),
1046
+ ]);
1047
+ if (cached.status !== 0) {
1048
+ throw new CommandError(EXIT_STAGE, `'git diff --cached' failed: ${cached.stderr}`);
1049
+ }
1050
+ tracked = nulList(cached.stdout);
1051
+ }
317
1052
  }
318
1053
 
319
- const specs = bookPathspecs(month, fid, scope);
1054
+ const specs = bookPathspecs(month, fid, scope, readBkitConfig(root).ciSkipPaths);
320
1055
  const listed = gitRaw(root, [
321
1056
  "ls-files",
322
1057
  "-z",
@@ -332,7 +1067,14 @@ export function commitBookkeeping(
332
1067
  `'git ls-files' failed while building the pathspec: ${listed.stderr}`,
333
1068
  );
334
1069
  }
335
- const paths = nulList(listed.stdout);
1070
+ let paths = nulList(listed.stdout);
1071
+ let ledgerRows: OwnSet["ledgers"] = [];
1072
+ if (rec !== null) {
1073
+ // Throws EXIT_FOREIGN_PATH when a recorded path in the allow-list changed.
1074
+ ledgerRows = ownSet(root, rec, paths).ledgers;
1075
+ const recorded = new Set(rec.paths.map((p) => p.path));
1076
+ paths = paths.filter((p) => !recorded.has(p));
1077
+ }
336
1078
  let squashPaths: string[] = [];
337
1079
  if (squashOf !== undefined) {
338
1080
  const diff = gitRaw(root, ["diff", "--name-only", "-z", "--no-renames", `HEAD...${squashOf}`]);
@@ -345,13 +1087,16 @@ export function commitBookkeeping(
345
1087
  squashPaths = nulList(diff.stdout);
346
1088
  }
347
1089
 
348
- if (mode !== "stage" && paths.length + squashPaths.length === 0) {
1090
+ if (
1091
+ mode !== "stage" &&
1092
+ paths.length + squashPaths.length + ledgerRows.length + tracked.length === 0
1093
+ ) {
349
1094
  // The pre-worktree commit records only bookkeeping; a dirty tree with none
350
1095
  // of it (a fresh consumer repo) has nothing of ours to commit, and stopping
351
1096
  // here never reaches `git commit`.
352
1097
  if (o.onlyIfDirtyTracked === true) {
353
1098
  log(`no bookkeeping under scope=${scope} in ${root} — nothing to commit`);
354
- return { outcome: "nothing-to-commit", commit: null, paths, squashPaths };
1099
+ return { outcome: "nothing-to-commit", commit: null, paths, squashPaths, tracked };
355
1100
  }
356
1101
  throw new CommandError(
357
1102
  EXIT_EMPTY,
@@ -359,26 +1104,47 @@ export function commitBookkeeping(
359
1104
  );
360
1105
  }
361
1106
 
1107
+ if (rec !== null && mode !== "stage" && ledgerRows.length > 0) {
1108
+ const made = commitOwnSet(
1109
+ root,
1110
+ { plain: [...paths, ...tracked], ledgers: ledgerRows },
1111
+ message!,
1112
+ {
1113
+ allowEmpty: mode === "commit-allow-empty",
1114
+ skipIfEmpty: mode === "commit",
1115
+ },
1116
+ );
1117
+ if (!made.ok) throw new CommandError(EXIT_COMMIT, `'git commit' failed: ${made.error}`);
1118
+ if (made.sha === null) {
1119
+ log("nothing to commit");
1120
+ return { outcome: "nothing-to-commit", commit: null, paths, squashPaths, tracked };
1121
+ }
1122
+ appendRecordCommit(root, fid, made.sha);
1123
+ return { outcome: "committed", commit: made.sha, paths, squashPaths, tracked };
1124
+ }
1125
+
362
1126
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "bkit-ledgers-"));
363
1127
  try {
364
1128
  const bookList = path.join(tmp, "book");
365
1129
  const commitList = path.join(tmp, "commit");
366
1130
  fs.writeFileSync(bookList, paths.map((p) => `${p}\0`).join(""));
367
- fs.writeFileSync(commitList, [...paths, ...squashPaths].map((p) => `${p}\0`).join(""));
1131
+ const commitPaths = [...new Set([...paths, ...squashPaths, ...tracked])];
1132
+ fs.writeFileSync(commitList, commitPaths.map((p) => `${p}\0`).join(""));
368
1133
 
369
1134
  const add = gitRaw(root, ["add", `--pathspec-from-file=${bookList}`, "--pathspec-file-nul"]);
370
1135
  if (add.status !== 0) throw new CommandError(EXIT_STAGE, `'git add' failed: ${add.stderr}`);
371
1136
 
372
1137
  if (mode === "stage") {
373
1138
  log(`staged (scope=${scope})`);
374
- return { outcome: "staged", commit: null, paths, squashPaths };
1139
+ return { outcome: "staged", commit: null, paths, squashPaths, tracked };
375
1140
  }
376
1141
  if (
377
1142
  mode === "commit" &&
378
- gitRaw(root, ["diff", "--cached", "--quiet", "--", ...specs, ...squashPaths]).status === 0
1143
+ gitRaw(root, ["diff", "--cached", "--quiet", "--", ...specs, ...squashPaths, ...tracked])
1144
+ .status === 0
379
1145
  ) {
380
1146
  log("nothing to commit");
381
- return { outcome: "nothing-to-commit", commit: null, paths, squashPaths };
1147
+ return { outcome: "nothing-to-commit", commit: null, paths, squashPaths, tracked };
382
1148
  }
383
1149
  const made = gitRaw(root, [
384
1150
  "commit",
@@ -394,12 +1160,9 @@ export function commitBookkeeping(
394
1160
  `'git commit' failed: ${made.stderr || made.stdout.trim()}`,
395
1161
  );
396
1162
  }
397
- return {
398
- outcome: "committed",
399
- commit: gitRaw(root, ["rev-parse", "HEAD"]).stdout.trim(),
400
- paths,
401
- squashPaths,
402
- };
1163
+ const sha = gitRaw(root, ["rev-parse", "HEAD"]).stdout.trim();
1164
+ if (rec !== null) appendRecordCommit(root, fid, sha);
1165
+ return { outcome: "committed", commit: sha, paths, squashPaths, tracked };
403
1166
  } finally {
404
1167
  fs.rmSync(tmp, { recursive: true, force: true });
405
1168
  }
@@ -413,12 +1176,13 @@ function commit(ctx: RunContext): number {
413
1176
  root: rootOf(ctx),
414
1177
  month: required(ctx, "month"),
415
1178
  fid: required(ctx, "fid"),
416
- scope: String(f.scope) as Scope,
1179
+ scope: String(f.scope ?? "") as Scope,
417
1180
  mode: String(f.mode) as BookkeepingCommit["mode"],
418
1181
  message: str(f.message),
419
1182
  stageTrackedUpdates: f.stageTrackedUpdates === true,
420
1183
  squashOf: str(f.squashOf),
421
1184
  onlyIfDirtyTracked: f.onlyIfDirtyTracked === true,
1185
+ path: str(f.path),
422
1186
  },
423
1187
  ctx.log,
424
1188
  ),
@@ -483,6 +1247,207 @@ function union(ctx: RunContext): number {
483
1247
  return EXIT.OK;
484
1248
  }
485
1249
 
1250
+ export interface AppendResult {
1251
+ ledger: AppendLedger;
1252
+ file: string;
1253
+ appended: number;
1254
+ keys: Array<string | null>;
1255
+ }
1256
+
1257
+ /** The top section in its written order, then the row's own fields. */
1258
+ const TOP_ORDER = [
1259
+ "schema",
1260
+ "ts",
1261
+ "firstTs",
1262
+ "updates",
1263
+ "kind",
1264
+ "key",
1265
+ "repo",
1266
+ "bkit",
1267
+ "by",
1268
+ "references",
1269
+ ];
1270
+
1271
+ /**
1272
+ * Append `rows` to one ledger. Every row is checked before any is written, so a
1273
+ * refused row leaves the file byte-identical. Each row gets `schema` and a `ts`
1274
+ * minted now (never supplied), `repo` when it lacks one and `bkit.version` from
1275
+ * `.bkit/version`; an `AGED_KINDS` row also gets `firstTs` + `updates` carried
1276
+ * forward from its entry's rows already in the ledger (supplied values replaced).
1277
+ * Never rewrites existing rows. Throws a CommandError (USAGE / EXIT_ROW_REFUSED /
1278
+ * EXIT_STAGE).
1279
+ */
1280
+ export function appendLedgerRows(root: string, ledger: string, rows: unknown): AppendResult {
1281
+ if (!Object.hasOwn(APPEND_LEDGERS, ledger)) {
1282
+ throw new CommandError(
1283
+ EXIT.USAGE,
1284
+ `--ledger must be one of ${Object.keys(APPEND_LEDGERS).join(", ")} (got '${ledger}')`,
1285
+ );
1286
+ }
1287
+ const { file, kinds } = APPEND_LEDGERS[ledger as AppendLedger];
1288
+ const takes: readonly string[] = kinds;
1289
+ if (!Array.isArray(rows)) throw new CommandError(EXIT.USAGE, "--rows must hold a JSON array");
1290
+ if (rows.length === 0) throw new CommandError(EXIT.USAGE, "--rows holds no rows");
1291
+
1292
+ let repo: string | undefined;
1293
+ let version: string | undefined;
1294
+ let last: number | undefined;
1295
+ const abs = path.join(root, file);
1296
+ const prior: unknown[] = fs.existsSync(abs) ? parse(fs.readFileSync(abs, "utf-8")).events : [];
1297
+ const out: Array<Record<string, unknown>> = rows.map((raw, i) => {
1298
+ const refuse = (why: string) => new CommandError(EXIT_ROW_REFUSED, `row ${i + 1}: ${why}`);
1299
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
1300
+ throw refuse("not a JSON object");
1301
+ }
1302
+ const r = raw as Record<string, unknown>;
1303
+ if (Object.hasOwn(r, "ts")) throw refuse("carries ts; ts is minted at append time");
1304
+ if (Object.hasOwn(r, "schema")) throw refuse("carries schema; it is set at append time");
1305
+ if (!takes.includes(String(r["kind"]))) {
1306
+ throw refuse(
1307
+ `kind must be ${takes.join(" | ")} in --ledger=${ledger} (got ${String(r["kind"])})`,
1308
+ );
1309
+ }
1310
+ if (Object.hasOwn(r, "bkit")) throw refuse("carries bkit; bkit.version is set at append time");
1311
+ repo ??= resolveRepoSlug(root) || "unknown/repo";
1312
+ version ??= readBkitVersion(path.join(root, ".bkit", "version"))?.pinnedVersion || "unknown";
1313
+ last = mintTs(last);
1314
+ const filled = withLineage(prior, {
1315
+ repo,
1316
+ ...r,
1317
+ schema: SCHEMA,
1318
+ ts: last,
1319
+ bkit: { version },
1320
+ });
1321
+ const row: Record<string, unknown> = {};
1322
+ for (const k of TOP_ORDER) if (filled[k] !== undefined) row[k] = filled[k];
1323
+ for (const [k, v] of Object.entries(filled)) if (!(k in row)) row[k] = v;
1324
+ const v = validate(row);
1325
+ if (!v.ok) throw refuse(v.reason ?? "invalid");
1326
+ const who = writerProblem(row);
1327
+ if (who !== undefined) throw refuse(who);
1328
+ prior.push(row);
1329
+ return row;
1330
+ });
1331
+
1332
+ const made = mkdirp(path.dirname(abs));
1333
+ if (made) throw new CommandError(EXIT_STAGE, `mkdir failed for ${path.dirname(file)}: ${made}`);
1334
+ const block = out.map((r) => `${JSON.stringify(r)}\n`).join("");
1335
+ // A file missing its final newline would glue the first row onto its last one.
1336
+ const appendErr = appendText(abs, endsMidLine(abs) ? `\n${block}` : block);
1337
+ if (appendErr) throw new CommandError(EXIT_STAGE, `append failed: ${file} — ${appendErr}`);
1338
+ return {
1339
+ ledger: ledger as AppendLedger,
1340
+ file,
1341
+ appended: out.length,
1342
+ keys: out.map((r) => (typeof r["key"] === "string" ? r["key"] : null)),
1343
+ };
1344
+ }
1345
+
1346
+ /** True when `abs` exists, is non-empty and its last byte is not a newline. */
1347
+ function endsMidLine(abs: string): boolean {
1348
+ let fd: number | undefined;
1349
+ try {
1350
+ fd = fs.openSync(abs, "r");
1351
+ const size = fs.fstatSync(fd).size;
1352
+ if (size === 0) return false;
1353
+ const last = Buffer.alloc(1);
1354
+ fs.readSync(fd, last, 0, 1, size - 1);
1355
+ return last[0] !== 0x0a;
1356
+ } catch {
1357
+ // No file yet: the append creates it.
1358
+ return false;
1359
+ } finally {
1360
+ if (fd !== undefined) fs.closeSync(fd);
1361
+ }
1362
+ }
1363
+
1364
+ function append(ctx: RunContext): number {
1365
+ const root = path.resolve(ctx.cwd, str(ctx.flags.root) ?? ".");
1366
+ const src = String(ctx.flags.rows);
1367
+ const read = readText(src === "-" ? 0 : path.resolve(ctx.cwd, src));
1368
+ if (!read.ok) throw new CommandError(EXIT.USAGE, `--rows unreadable: ${read.error}`);
1369
+ const text = read.text;
1370
+ if (text.trim() === "") throw new CommandError(EXIT.USAGE, "--rows holds no rows");
1371
+ const parsed = parseJson(text);
1372
+ if (!parsed.ok) throw new CommandError(EXIT.USAGE, "--rows is not JSON");
1373
+ const r = appendLedgerRows(root, String(ctx.flags.ledger), parsed.value);
1374
+ ctx.log(`appended ${r.appended} row(s) to ${r.file}`);
1375
+ ctx.emit({ ...r });
1376
+ return EXIT.OK;
1377
+ }
1378
+
1379
+ const LEDGER_ROWS_LINE = /^\*\*Ledger rows:\*\*(.*)$/m;
1380
+ const CHECKED_LEDGERS = [APPEND_LEDGERS.decisions, APPEND_LEDGERS.deferrals];
1381
+
1382
+ export interface PlanRowsResult {
1383
+ keys: string[];
1384
+ missing: string[];
1385
+ }
1386
+
1387
+ /**
1388
+ * Read the plan's `**Ledger rows:**` line — backticked keys, or `None` — and
1389
+ * return the keys no `decision` / `deferral` row carries. Throws EXIT_ROWS_MISSING
1390
+ * when the line is absent or still a placeholder.
1391
+ */
1392
+ export function checkPlanRows(root: string, plan: string): PlanRowsResult {
1393
+ const abs = path.resolve(root, plan);
1394
+ if (!fs.existsSync(abs)) throw new CommandError(EXIT.USAGE, `--plan not found: ${plan}`);
1395
+ const text = fs.readFileSync(abs, "utf-8");
1396
+ const line = LEDGER_ROWS_LINE.exec(text)?.[1]?.trim();
1397
+ if (line === undefined) {
1398
+ throw new CommandError(EXIT_ROWS_MISSING, `${plan} has no **Ledger rows:** line`);
1399
+ }
1400
+ const keys = [...line.matchAll(/`([^`]+)`/g)].map((m) => m[1] ?? "");
1401
+ if (keys.length === 0) {
1402
+ if (line.replace(/[."\s]/g, "") === "None") return { keys: [], missing: [] };
1403
+ throw new CommandError(EXIT_ROWS_MISSING, `${plan}: **Ledger rows:** is unfilled (${line})`);
1404
+ }
1405
+ const onDisk = new Set<string>();
1406
+ for (const { file, kinds } of CHECKED_LEDGERS) {
1407
+ const abs = path.join(root, file);
1408
+ if (!fs.existsSync(abs)) continue;
1409
+ for (const e of parse(fs.readFileSync(abs, "utf-8")).events) {
1410
+ const key = (e as { key?: unknown }).key;
1411
+ if ((kinds as readonly string[]).includes(e.kind) && typeof key === "string") onDisk.add(key);
1412
+ }
1413
+ }
1414
+ return { keys, missing: keys.filter((k) => !onDisk.has(k)) };
1415
+ }
1416
+
1417
+ function check(ctx: RunContext): number {
1418
+ const root = rootOf(ctx);
1419
+ const plan = String(ctx.flags.plan);
1420
+ const r = checkPlanRows(root, plan);
1421
+ ctx.emit({ plan, ...r });
1422
+ if (r.missing.length > 0) {
1423
+ ctx.log(`${plan}: no ledger row for ${r.missing.join(", ")}`);
1424
+ return EXIT_ROWS_MISSING;
1425
+ }
1426
+ ctx.log(`${plan}: ${r.keys.length} ledger row(s) on disk`);
1427
+ return EXIT.OK;
1428
+ }
1429
+
1430
+ function compact(ctx: RunContext): number {
1431
+ const root = rootOf(ctx);
1432
+ const named = str(ctx.flags.ledger) ?? "all";
1433
+ if (named !== "all" && !Object.hasOwn(COMPACT_LEDGERS, named)) {
1434
+ throw new CommandError(
1435
+ EXIT.USAGE,
1436
+ `--ledger must be one of ${Object.keys(COMPACT_LEDGERS).join(", ")}, all (got '${named}')`,
1437
+ );
1438
+ }
1439
+ const ledgers = (named === "all" ? Object.keys(COMPACT_LEDGERS) : [named]) as CompactLedger[];
1440
+ const dryRun = ctx.flags.dryRun === true;
1441
+ const results = compactOrError(root, ledgers, dryRun);
1442
+ if (typeof results === "string") throw new CommandError(EXIT_STAGE, `compact failed: ${results}`);
1443
+ const dropped = results.reduce((n, r) => n + r.dropped, 0);
1444
+ for (const r of results) {
1445
+ ctx.log(`${r.file}: ${r.dropped} superseded row(s) dropped, ${r.stamped} winner(s) stamped`);
1446
+ }
1447
+ ctx.emit({ dryRun, ledgers: results, dropped });
1448
+ return EXIT.OK;
1449
+ }
1450
+
486
1451
  /** mkdir -p; the error text, or undefined on success. */
487
1452
  function mkdirp(dir: string): string | undefined {
488
1453
  try {
@@ -494,6 +1459,41 @@ function mkdirp(dir: string): string | undefined {
494
1459
  }
495
1460
  }
496
1461
 
1462
+ /** {@link compactLedgers}; its results, or the error text. A failed temp write or rename leaves the ledger untouched. */
1463
+ function compactOrError(
1464
+ root: string,
1465
+ ledgers: readonly CompactLedger[],
1466
+ dryRun: boolean,
1467
+ ): ReturnType<typeof compactLedgers> | string {
1468
+ try {
1469
+ return compactLedgers(root, ledgers, dryRun);
1470
+ } catch (err) {
1471
+ // Reported as the command's staging exit code, with the reason.
1472
+ return (err as Error).message;
1473
+ }
1474
+ }
1475
+
1476
+ /** Append `text` to `file`; the error text, or undefined on success. */
1477
+ function appendText(file: string, text: string): string | undefined {
1478
+ try {
1479
+ fs.appendFileSync(file, text);
1480
+ return undefined;
1481
+ } catch (err) {
1482
+ // Reported as the command's staging exit code, with the reason.
1483
+ return (err as Error).message;
1484
+ }
1485
+ }
1486
+
1487
+ /** Read `file` (0 = stdin) as UTF-8; the text, or the error text. */
1488
+ function readText(file: string | 0): { ok: true; text: string } | { ok: false; error: string } {
1489
+ try {
1490
+ return { ok: true, text: fs.readFileSync(file, "utf-8") };
1491
+ } catch (err) {
1492
+ // Reported as a usage error, with the reason.
1493
+ return { ok: false, error: (err as Error).message };
1494
+ }
1495
+ }
1496
+
497
1497
  function copy(from: string, to: string): string | undefined {
498
1498
  try {
499
1499
  fs.copyFileSync(from, to);
@@ -527,7 +1527,12 @@ export function checkOnlyBookkeeping(
527
1527
  if (gitRaw(root, ["merge-base", "--is-ancestor", o.from, o.to]).status !== 0) {
528
1528
  return { kind: "not-ancestor" };
529
1529
  }
530
- const diff = changedOutside(root, o.from, o.to, bookPathspecs(o.month, o.fid, "pr"));
1530
+ const diff = changedOutside(
1531
+ root,
1532
+ o.from,
1533
+ o.to,
1534
+ bookPathspecs(o.month, o.fid, "pr", readBkitConfig(root).ciSkipPaths),
1535
+ );
531
1536
  if (!diff.ok) return { kind: "diff-failed", stderr: diff.stderr };
532
1537
  return diff.outside.length ? { kind: "outside", outside: diff.outside } : { kind: "ok" };
533
1538
  }
@@ -592,3 +1597,295 @@ function onlyBookkeeping(ctx: RunContext): number {
592
1597
  return EXIT.OK;
593
1598
  }
594
1599
  }
1600
+
1601
+ // ---------------------------------------------------------------------------
1602
+ // triage — the sweep's deferral tests, computed
1603
+ // ---------------------------------------------------------------------------
1604
+ //
1605
+ // `.bkit/jsonl.md` § Deferral Reason states the four tests: each names a way a
1606
+ // deferral reads as in-scope work that should have been finished, and all four
1607
+ // holding marks the row `unjustified`. The engine decides them from the row, its
1608
+ // own `references`, the plan's task surfaces, its Reuse Inventory and its
1609
+ // Out of Scope table. The sweep keeps the judgement the four cannot reach.
1610
+
1611
+ /** The four tests, in `.bkit/jsonl.md` order; each holds when the row reads as in-scope work. */
1612
+ export const DEFERRAL_TESTS = [
1613
+ "bounded-remediation",
1614
+ "in-scope-surface",
1615
+ "no-external-blocker",
1616
+ "own-declaration",
1617
+ ] as const;
1618
+ export type DeferralTest = (typeof DEFERRAL_TESTS)[number];
1619
+
1620
+ /** One test's verdict on a row. */
1621
+ export interface DeferralTestResult {
1622
+ test: DeferralTest;
1623
+ held: boolean;
1624
+ }
1625
+
1626
+ /** One matched deferral row's bucket and the tests behind it. */
1627
+ export interface TriageRow {
1628
+ key: string | null;
1629
+ /**
1630
+ * `Lazy` when every test holds, and for a row already adjudicated `unjustified`:
1631
+ * in-scope work that should have been finished.
1632
+ */
1633
+ bucket: "Exempt" | "Lazy";
1634
+ /** Empty when the row is settled before the tests are applied. */
1635
+ tests: DeferralTestResult[];
1636
+ /** A same-`key` `unjustified` / `TRIAGED` row was appended for it. */
1637
+ written: boolean;
1638
+ }
1639
+
1640
+ export interface TriageResult {
1641
+ fid: string;
1642
+ plan: string;
1643
+ rows: TriageRow[];
1644
+ total: number;
1645
+ written: number;
1646
+ }
1647
+
1648
+ /** The issue number a FID leads with (`701-engine-work` → `701`), else "". */
1649
+ const fidIssue = (fid: string) => /^(\d+)(?=$|[-_])/.exec(fid)?.[1] ?? "";
1650
+
1651
+ /** A row's `references` entries, as written. */
1652
+ const rowRefs = (row: Record<string, unknown>): string[] =>
1653
+ Array.isArray(row["references"])
1654
+ ? row["references"].filter((x): x is string => typeof x === "string")
1655
+ : [];
1656
+
1657
+ /** True when `ref` names the feature: the FID, or its leading issue number as `N` / `#N`. */
1658
+ const namesFeature = (ref: string, fid: string, issue: string): boolean =>
1659
+ ref.includes(fid) || (issue !== "" && new RegExp(`^#?${issue}(?![0-9])`).test(ref));
1660
+
1661
+ /** Every well-formed row of a JSONL ledger, as written. */
1662
+ function readLedgerRows(file: string): Array<Record<string, unknown>> {
1663
+ if (!fs.existsSync(file)) return [];
1664
+ return fs
1665
+ .readFileSync(file, "utf-8")
1666
+ .split("\n")
1667
+ .flatMap((line): Array<Record<string, unknown>> => {
1668
+ if (line.trim() === "") return [];
1669
+ const parsed = parseJson(line);
1670
+ const v = parsed.ok ? parsed.value : null;
1671
+ return typeof v === "object" && v !== null && !Array.isArray(v)
1672
+ ? [v as Record<string, unknown>]
1673
+ : [];
1674
+ });
1675
+ }
1676
+
1677
+ /** The deferral rows `fid` declared, same-`key` folded last-wins, in first-seen order. */
1678
+ export function featureDeferrals(
1679
+ rows: Array<Record<string, unknown>>,
1680
+ fid: string,
1681
+ ): Array<Record<string, unknown>> {
1682
+ const issue = fidIssue(fid);
1683
+ const kept: Array<Record<string, unknown>> = [];
1684
+ const at = new Map<string, number>();
1685
+ for (const row of rows) {
1686
+ if (row["kind"] !== "deferral") continue;
1687
+ const key = typeof row["key"] === "string" ? row["key"] : "";
1688
+ const named = key !== "" && namesFeature(key, fid, issue);
1689
+ if (!named && !rowRefs(row).some((r) => namesFeature(r, fid, issue))) continue;
1690
+ const seen = key === "" ? undefined : at.get(key);
1691
+ if (seen !== undefined) {
1692
+ kept[seen] = row;
1693
+ continue;
1694
+ }
1695
+ if (key !== "") at.set(key, kept.length);
1696
+ kept.push(row);
1697
+ }
1698
+ return kept;
1699
+ }
1700
+
1701
+ /** A repo path a token names, with any `:line` suffix cut; null when the token is no path. */
1702
+ function pathToken(token: string): string | null {
1703
+ const t = token
1704
+ .trim()
1705
+ .replace(/:\d+(?:-\d+)?$/, "")
1706
+ .replace(/[.,;:]+$/, "")
1707
+ .replace(/^\.\//, "");
1708
+ if (t === "" || /\s/.test(t) || t.startsWith("#") || /^[a-z][a-z0-9+.-]*:\/\//i.test(t))
1709
+ return null;
1710
+ if (!t.includes("/") && !/\.[A-Za-z][A-Za-z0-9]{0,5}$/.test(t)) return null;
1711
+ return path.posix.normalize(t);
1712
+ }
1713
+
1714
+ /** The repo paths a row names: backticked spans and bare words of its `remediation`, plus its `references`. */
1715
+ function namedPaths(row: Record<string, unknown>): string[] {
1716
+ const texts = [
1717
+ ...(typeof row["remediation"] === "string" ? [row["remediation"]] : []),
1718
+ ...rowRefs(row),
1719
+ ];
1720
+ const tokens = texts.flatMap((t) => [
1721
+ ...[...t.matchAll(/`([^`]+)`/g)].map((m) => m[1]!),
1722
+ ...t.replace(/`[^`]*`/g, " ").split(/[\s,()[\]]+/),
1723
+ ]);
1724
+ return [
1725
+ ...new Set(
1726
+ tokens.map(pathToken).filter((p): p is string => p !== null && p !== "." && p !== ".."),
1727
+ ),
1728
+ ];
1729
+ }
1730
+
1731
+ /** True when one of `paths` is a file in `root`. */
1732
+ function existsIn(root: string, paths: string[]): boolean {
1733
+ return paths.some((p) => {
1734
+ const abs = path.resolve(root, p);
1735
+ const rel = path.relative(root, abs);
1736
+ return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel) && fs.existsSync(abs);
1737
+ });
1738
+ }
1739
+
1740
+ /** True when `a` and `b` name the same path, or one sits inside the other. */
1741
+ const within = (a: string, b: string) => a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
1742
+
1743
+ const NORMAL = (s: string) => s.toLowerCase().replace(/\s+/g, " ").trim();
1744
+
1745
+ /** The items the plan's `Out of Scope` rows declare: their excluded item and every backticked token. */
1746
+ function declaredItems(rows: OutOfScopeRow[] | null): Set<string> {
1747
+ const out = new Set<string>();
1748
+ for (const row of rows ?? []) {
1749
+ const item = row.cells[0] ?? "";
1750
+ if (item !== "") out.add(NORMAL(item));
1751
+ for (const cell of row.cells)
1752
+ for (const m of cell.matchAll(/`([^`]+)`/g)) if (m[1]!.trim() !== "") out.add(NORMAL(m[1]!));
1753
+ }
1754
+ return out;
1755
+ }
1756
+
1757
+ /**
1758
+ * True when a reference other than the row's own key or the bare FID names a
1759
+ * pre-existing declaration: a plan `Out of Scope` item, or a doc section declared
1760
+ * out of scope. A row that is its own only declaration names none.
1761
+ */
1762
+ function declares(
1763
+ row: Record<string, unknown>,
1764
+ fid: string,
1765
+ issue: string,
1766
+ declared: Set<string>,
1767
+ ): boolean {
1768
+ const own = typeof row["key"] === "string" ? NORMAL(row["key"]) : "";
1769
+ const self = NORMAL(fid);
1770
+ for (const ref of rowRefs(row)) {
1771
+ const t = ref.trim();
1772
+ if (t === "" || NORMAL(t) === own || NORMAL(t) === self || t === `#${issue}`) continue;
1773
+ if (t.includes("§") && /out[- ]of[- ]scope|non-?goals?/i.test(t)) return true;
1774
+ const n = NORMAL(t);
1775
+ if (declared.has(n)) return true;
1776
+ for (const d of declared) if (d.length >= 8 && n.includes(d)) return true;
1777
+ }
1778
+ return false;
1779
+ }
1780
+
1781
+ /** The same-`key` row triage appends: every prior field verbatim, the verdict fields replaced. */
1782
+ export function unjustifiedRow(
1783
+ row: Record<string, unknown>,
1784
+ fid: string,
1785
+ held: DeferralTest[],
1786
+ ): Record<string, unknown> {
1787
+ const out: Record<string, unknown> = {};
1788
+ for (const [k, v] of Object.entries(row)) {
1789
+ if (k === "schema" || k === "ts" || k === "bkit" || k === "by" || k === "description") continue;
1790
+ out[k] = v;
1791
+ }
1792
+ out["kind"] = "deferral";
1793
+ out["reason"] = UNJUSTIFIED_REASON;
1794
+ out["status"] = "TRIAGED";
1795
+ out["description"] =
1796
+ `Adjudicated unjustified by bkit ledgers triage for ${fid}: every deferral test holds (${held.join(", ")}).`;
1797
+ // The ship orchestrator's sweep step is the writer, so the row clears the kind's writer check.
1798
+ out["by"] = { workflow: "ship", step: "ship-deferred-sweep" };
1799
+ return out;
1800
+ }
1801
+
1802
+ /**
1803
+ * Bucket the FID's deferral rows by the four tests and append a same-`key`
1804
+ * `unjustified` / `TRIAGED` row for each that holds all four. Throws
1805
+ * CommandError(USAGE) on a missing `--plan` or a plan whose task blocks do not
1806
+ * parse, CommandError(NO) on a plan with no task blocks — nothing written either
1807
+ * way — and EXIT_ROW_REFUSED when a computed row fails validation.
1808
+ */
1809
+ export function triageDeferrals(root: string, fid: string, planPath: string): TriageResult {
1810
+ const abs = path.resolve(root, planPath);
1811
+ if (!fs.existsSync(abs)) throw new CommandError(EXIT.USAGE, `--plan not found: ${planPath}`);
1812
+ const text = fs.readFileSync(abs, "utf-8");
1813
+ const blocks = parsePlanBlocks(text);
1814
+ const error = blocks.errors[0];
1815
+ if (error !== undefined)
1816
+ throw new CommandError(
1817
+ EXIT.USAGE,
1818
+ `${planPath}:${error.line}: ${error.message} — run \`bkit tests plan-check\``,
1819
+ );
1820
+ // No task block means no task surface: every row would bucket `Exempt` unread.
1821
+ if (blocks.tasks.length === 0)
1822
+ throw new CommandError(EXIT.NO, `${planPath}: ${NO_MARKERS_REASON}`);
1823
+ const surfaces = new Set<string>();
1824
+ for (const task of blocks.tasks)
1825
+ for (const ref of [...task.create, ...task.read, ...task.update, ...task.delete])
1826
+ surfaces.add(path.posix.normalize(ref.file));
1827
+ for (const row of reuseInventory(text)?.rows ?? []) for (const f of row.files) surfaces.add(f);
1828
+ const scope = [...surfaces];
1829
+ const declared = declaredItems(outOfScope(text));
1830
+ const issue = fidIssue(fid);
1831
+ const rows = featureDeferrals(
1832
+ readLedgerRows(path.join(root, APPEND_LEDGERS.deferrals.file)),
1833
+ fid,
1834
+ );
1835
+ const out: TriageRow[] = [];
1836
+ const write: Array<Record<string, unknown>> = [];
1837
+ for (const row of rows) {
1838
+ const key = typeof row["key"] === "string" ? row["key"] : null;
1839
+ // Closed work is done: nothing to test, nothing to write.
1840
+ if (row["status"] === "CLOSED") {
1841
+ out.push({ key, bucket: "Exempt", tests: [], written: false });
1842
+ continue;
1843
+ }
1844
+ // A LOW challenge finding holds without the tests, and an adjudicated row is never
1845
+ // re-adjudicated: it keeps the `Lazy` bucket its adjudication earned, so an
1846
+ // outstanding unjustified deferral never reads as `Exempt Deferrals`.
1847
+ if (row["reason"] === UNJUSTIFIED_REASON) {
1848
+ out.push({ key, bucket: "Lazy", tests: [], written: false });
1849
+ continue;
1850
+ }
1851
+ if (row["reason"] === "low-severity" && row["severity"] === "LOW") {
1852
+ out.push({ key, bucket: "Exempt", tests: [], written: false });
1853
+ continue;
1854
+ }
1855
+ const paths = namedPaths(row);
1856
+ const verdicts: Record<DeferralTest, boolean> = {
1857
+ // Test 1 reads "not a new architecture": an `own-cycle` row declares itself plan-sized.
1858
+ "bounded-remediation": row["reason"] !== "own-cycle" && existsIn(root, paths),
1859
+ "in-scope-surface": paths.some((p) => scope.some((s) => within(p, s))),
1860
+ "no-external-blocker": row["reason"] !== "hard-blocked" && row["reason"] !== "needs-decision",
1861
+ "own-declaration": !declares(row, fid, issue, declared),
1862
+ };
1863
+ const tests = DEFERRAL_TESTS.map((test) => ({ test, held: verdicts[test] }));
1864
+ const lazy = tests.every((t) => t.held);
1865
+ if (lazy)
1866
+ write.push(
1867
+ unjustifiedRow(
1868
+ row,
1869
+ fid,
1870
+ tests.map((t) => t.test),
1871
+ ),
1872
+ );
1873
+ out.push({ key, bucket: lazy ? "Lazy" : "Exempt", tests, written: lazy });
1874
+ }
1875
+ if (write.length > 0) appendLedgerRows(root, "deferrals", write);
1876
+ return { fid, plan: planPath, rows: out, total: out.length, written: write.length };
1877
+ }
1878
+
1879
+ function triage(ctx: RunContext): number {
1880
+ const r = triageDeferrals(rootOf(ctx), required(ctx, "fid"), required(ctx, "plan"));
1881
+ for (const row of r.rows) {
1882
+ const verdict =
1883
+ row.tests.length === 0
1884
+ ? "not tested"
1885
+ : row.tests.map((t) => `${t.test} ${t.held ? "holds" : "fails"}`).join(", ");
1886
+ ctx.log(`${row.key ?? "(no key)"} — ${row.bucket}: ${verdict}`);
1887
+ }
1888
+ ctx.log(`${r.total} deferral row(s) for ${r.fid}, ${r.written} written unjustified`);
1889
+ ctx.emit({ ...r });
1890
+ return EXIT.OK;
1891
+ }