@cbartens/bkit 6.1.0 → 6.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (317) hide show
  1. package/.bkit/README.md +14 -12
  2. package/.bkit/core/.agents/docs.md +1 -11
  3. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-gateguard.cjs +30 -9
  4. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-guardrails.cjs +25 -27
  5. package/.bkit/core/.agents/rules.md +22 -9
  6. package/.bkit/core/.bkit/README.md +13 -11
  7. package/.bkit/core/.bkit/authoring.md +58 -13
  8. package/.bkit/core/.bkit/cli.md +43 -33
  9. package/.bkit/core/.bkit/cloud.md +93 -30
  10. package/.bkit/core/.bkit/install.md +55 -16
  11. package/.bkit/core/.bkit/jsonl.md +24 -7
  12. package/.bkit/core/.bkit/pipeline.md +8 -8
  13. package/.bkit/core/.bkit/prompts.md +160 -43
  14. package/.bkit/core/.bkit/providers.md +99 -36
  15. package/.bkit/core/.bkit/templates.md +167 -37
  16. package/.bkit/core/.bkit/trackers.md +39 -6
  17. package/.bkit/core/.bkit/workflows.md +344 -136
  18. package/.bkit/core/.claude/hooks/bkit-guardrails.cjs +50 -27
  19. package/.bkit/core/.claude/hooks/bkit-preflight.sh +11 -11
  20. package/.bkit/core/.codex/hooks/bkit-gateguard.cjs +13 -8
  21. package/.bkit/core/.codex/hooks/bkit-guardrails.cjs +14 -25
  22. package/.bkit/core/.cursor/hooks/bkit-guardrails.cjs +20 -9
  23. package/.bkit/core/.cursor/hooks/bkit-preflight.sh +8 -8
  24. package/.bkit/core/.opencode/plugin/bkit-gateguard.js +14 -4
  25. package/.bkit/core/.opencode/plugin/bkit-guardrails.js +114 -0
  26. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +1 -1
  27. package/.bkit/core/docs/templates/bkit-audit-adoption.md +30 -6
  28. package/.bkit/core/docs/templates/bkit-audit-agents.md +1 -1
  29. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +1 -1
  30. package/.bkit/core/docs/templates/bkit-audit-analytics.md +1 -1
  31. package/.bkit/core/docs/templates/bkit-audit-annotations.md +1 -1
  32. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +1 -1
  33. package/.bkit/core/docs/templates/bkit-audit-app-store.md +1 -1
  34. package/.bkit/core/docs/templates/bkit-audit-architecture.md +1 -1
  35. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +2 -2
  36. package/.bkit/core/docs/templates/bkit-audit-config.md +3 -2
  37. package/.bkit/core/docs/templates/bkit-audit-cost.md +1 -1
  38. package/.bkit/core/docs/templates/bkit-audit-coverage.md +1 -1
  39. package/.bkit/core/docs/templates/bkit-audit-database.md +3 -3
  40. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +1 -1
  41. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +1 -1
  42. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +3 -3
  43. package/.bkit/core/docs/templates/bkit-audit-documentation.md +32 -2
  44. package/.bkit/core/docs/templates/bkit-audit-duplication.md +1 -1
  45. package/.bkit/core/docs/templates/bkit-audit-failures.md +1 -1
  46. package/.bkit/core/docs/templates/bkit-audit-flakes.md +2 -2
  47. package/.bkit/core/docs/templates/bkit-audit-gates.md +5 -3
  48. package/.bkit/core/docs/templates/bkit-audit-issues.md +1 -1
  49. package/.bkit/core/docs/templates/bkit-audit-llm.md +2 -2
  50. package/.bkit/core/docs/templates/bkit-audit-logs.md +1 -1
  51. package/.bkit/core/docs/templates/bkit-audit-models.md +2 -2
  52. package/.bkit/core/docs/templates/bkit-audit-privacy.md +1 -1
  53. package/.bkit/core/docs/templates/bkit-audit-prompts.md +1 -1
  54. package/.bkit/core/docs/templates/bkit-audit-red-team.md +2 -2
  55. package/.bkit/core/docs/templates/bkit-audit-reliability.md +3 -2
  56. package/.bkit/core/docs/templates/bkit-audit-repo.md +1 -1
  57. package/.bkit/core/docs/templates/bkit-audit-security.md +1 -1
  58. package/.bkit/core/docs/templates/bkit-audit-slop.md +1 -1
  59. package/.bkit/core/docs/templates/bkit-audit-testing.md +3 -2
  60. package/.bkit/core/docs/templates/bkit-audit-usability.md +1 -1
  61. package/.bkit/core/docs/templates/bkit-plan.md +38 -8
  62. package/.bkit/core/engine/checks/after/auth.ts +118 -47
  63. package/.bkit/core/engine/checks/after/github.ts +161 -37
  64. package/.bkit/core/engine/checks/after/index.ts +18 -3
  65. package/.bkit/core/engine/checks/after/tools.ts +245 -1
  66. package/.bkit/core/engine/checks/before/files.ts +59 -1
  67. package/.bkit/core/engine/checks/before/index.ts +8 -0
  68. package/.bkit/core/engine/checks/status-holes.ts +20 -26
  69. package/.bkit/core/engine/checks/tips/catalogue.ts +107 -10
  70. package/.bkit/core/engine/checks/tips/detect.ts +36 -3
  71. package/.bkit/core/engine/checks/tips/index.ts +1 -1
  72. package/.bkit/core/engine/cli.ts +13 -13
  73. package/.bkit/core/engine/commands/ci/ci.ts +124 -19
  74. package/.bkit/core/engine/commands/ci/push-gate.ts +101 -43
  75. package/.bkit/core/engine/commands/install/doctor.ts +5 -5
  76. package/.bkit/core/engine/commands/install/install.ts +28 -25
  77. package/.bkit/core/engine/commands/install/uninstall.ts +42 -30
  78. package/.bkit/core/engine/commands/install/upgrade.ts +14 -2
  79. package/.bkit/core/engine/commands/land.ts +2 -3
  80. package/.bkit/core/engine/commands/lib.ts +394 -39
  81. package/.bkit/core/engine/commands/registry.ts +1 -1
  82. package/.bkit/core/engine/commands/workflow/branches.ts +351 -78
  83. package/.bkit/core/engine/commands/workflow/challenge.ts +63 -14
  84. package/.bkit/core/engine/commands/workflow/context.ts +71 -10
  85. package/.bkit/core/engine/commands/workflow/counters.ts +298 -23
  86. package/.bkit/core/engine/commands/workflow/decisions.ts +260 -125
  87. package/.bkit/core/engine/commands/workflow/disk.ts +2 -1
  88. package/.bkit/core/engine/commands/workflow/feature-base.ts +66 -0
  89. package/.bkit/core/engine/commands/workflow/issues.ts +312 -17
  90. package/.bkit/core/engine/commands/workflow/junit.ts +204 -0
  91. package/.bkit/core/engine/commands/workflow/ledgers.ts +904 -99
  92. package/.bkit/core/engine/commands/workflow/locks.ts +186 -29
  93. package/.bkit/core/engine/commands/workflow/loops.ts +87 -0
  94. package/.bkit/core/engine/commands/workflow/open-decision.ts +251 -0
  95. package/.bkit/core/engine/commands/workflow/plan-blocks.ts +8 -0
  96. package/.bkit/core/engine/commands/workflow/plans.ts +1 -1
  97. package/.bkit/core/engine/commands/workflow/prs.ts +311 -16
  98. package/.bkit/core/engine/commands/workflow/repo.ts +1 -1
  99. package/.bkit/core/engine/commands/workflow/run-facts.ts +6 -0
  100. package/.bkit/core/engine/commands/workflow/runs.ts +877 -174
  101. package/.bkit/core/engine/commands/workflow/runtime.ts +12 -4
  102. package/.bkit/core/engine/commands/workflow/status.ts +324 -11
  103. package/.bkit/core/engine/commands/workflow/step-table.ts +41 -15
  104. package/.bkit/core/engine/commands/workflow/steps.ts +604 -29
  105. package/.bkit/core/engine/commands/workflow/summary-findings.ts +1 -1
  106. package/.bkit/core/engine/commands/workflow/summary.ts +314 -8
  107. package/.bkit/core/engine/commands/workflow/tasks.ts +400 -27
  108. package/.bkit/core/engine/commands/workflow/tests-base.ts +319 -0
  109. package/.bkit/core/engine/commands/workflow/tests-changed.ts +138 -74
  110. package/.bkit/core/engine/commands/workflow/tests-jump.ts +93 -0
  111. package/.bkit/core/engine/commands/workflow/tests.ts +815 -182
  112. package/.bkit/core/engine/commands/workflow/tracker.ts +1134 -137
  113. package/.bkit/core/engine/commands/workflow/workflows.ts +100 -72
  114. package/.bkit/core/engine/commands/workflow/worktrees.ts +421 -57
  115. package/.bkit/core/engine/install/cloud-env.ts +38 -10
  116. package/.bkit/core/engine/install/managed-block.ts +105 -0
  117. package/.bkit/core/engine/install/manifest.ts +7 -1
  118. package/.bkit/core/engine/install/modules/claude.ts +6 -2
  119. package/.bkit/core/engine/install/modules/cloud.ts +84 -95
  120. package/.bkit/core/engine/install/modules/codex.ts +10 -2
  121. package/.bkit/core/engine/install/modules/core.ts +202 -26
  122. package/.bkit/core/engine/install/modules/opencode.ts +18 -23
  123. package/.bkit/core/engine/install/network-allowlist.ts +8 -3
  124. package/.bkit/core/engine/install/project-docs.ts +650 -0
  125. package/.bkit/core/engine/install/template-copies.ts +58 -5
  126. package/.bkit/core/engine/install/write.ts +128 -7
  127. package/.bkit/core/engine/ledgers/journal.ts +18 -10
  128. package/.bkit/core/engine/ledgers/migrate.ts +20 -8
  129. package/.bkit/core/engine/ledgers/status.ts +604 -8
  130. package/.bkit/core/engine/ledgers/telemetry.ts +115 -13
  131. package/.bkit/core/engine/render/trackers.ts +46 -11
  132. package/.bkit/core/engine/shared/package-manager.ts +7 -3
  133. package/.bkit/core/engine/shared/settings.ts +12 -1
  134. package/.bkit/core/engine/shared/text.ts +14 -0
  135. package/.bkit/core/engine/tools/instructions-sources.ts +1 -0
  136. package/.bkit/core/engine/tools/instructions.ts +116 -20
  137. package/.bkit/core/hooks/antigravity-hook.js +20 -4
  138. package/.bkit/core/hooks/gateguard-edit-payload.js +8 -5
  139. package/.bkit/core/hooks/gateguard-engine.js +249 -23
  140. package/.bkit/core/hooks/guardrails-deny.js +167 -0
  141. package/.bkit/core/hooks/guardrails-read.js +3 -3
  142. package/.bkit/core/hooks/guardrails-shell.js +1122 -167
  143. package/.bkit/core/hooks/guardrails-tiers.js +247 -176
  144. package/.bkit/core/hooks/preflight-tracker.sh +219 -0
  145. package/.bkit/core/prompts/bkit-audit-generate.md +23 -6
  146. package/.bkit/core/prompts/bkit-build-challenge-1.md +5 -4
  147. package/.bkit/core/prompts/bkit-build-challenge-2.md +6 -5
  148. package/.bkit/core/prompts/bkit-build-install-skills.md +2 -2
  149. package/.bkit/core/prompts/bkit-build-plan-convert.md +21 -7
  150. package/.bkit/core/prompts/bkit-build-plan-current.md +5 -4
  151. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +22 -17
  152. package/.bkit/core/prompts/bkit-build-plan-tasks.md +16 -12
  153. package/.bkit/core/prompts/bkit-build-plan-tests.md +14 -10
  154. package/.bkit/core/prompts/bkit-build-plan-verify.md +21 -8
  155. package/.bkit/core/prompts/bkit-debug-abort-handover.md +10 -5
  156. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +22 -6
  157. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +19 -3
  158. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +22 -6
  159. package/.bkit/core/prompts/bkit-debug-failure-soak.md +10 -7
  160. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +3 -3
  161. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +4 -4
  162. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +3 -3
  163. package/.bkit/core/prompts/bkit-design-generate.md +6 -4
  164. package/.bkit/core/prompts/bkit-design-organise.md +4 -3
  165. package/.bkit/core/prompts/bkit-design-review-1.md +5 -4
  166. package/.bkit/core/prompts/bkit-design-review-2.md +6 -5
  167. package/.bkit/core/prompts/bkit-design-spike.md +4 -3
  168. package/.bkit/core/prompts/bkit-design-update.md +6 -4
  169. package/.bkit/core/prompts/bkit-plan-generate.md +35 -14
  170. package/.bkit/core/prompts/bkit-plan-review-1.md +9 -7
  171. package/.bkit/core/prompts/bkit-plan-review-2.md +9 -7
  172. package/.bkit/core/prompts/bkit-plan-scope-check.md +8 -6
  173. package/.bkit/core/prompts/bkit-plan-update.md +22 -8
  174. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +11 -8
  175. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +9 -5
  176. package/.bkit/core/prompts/bkit-ship-update-docs.md +26 -4
  177. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +3 -3
  178. package/.bkit/core/prompts/bkit-utility-update-decisions.md +10 -7
  179. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +8 -5
  180. package/.bkit/core/prompts/bkit-utility-update-documentation.md +31 -7
  181. package/.bkit/core/prompts/bkit-utility-update-failures.md +8 -5
  182. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +10 -7
  183. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +4 -4
  184. package/.bkit/core/prompts/bkit-utility-update-tracker.md +4 -4
  185. package/.bkit/core/workflows/bkit-auto.md +23 -11
  186. package/.bkit/core/workflows/bkit-build.md +331 -100
  187. package/.bkit/core/workflows/bkit-debug.md +135 -64
  188. package/.bkit/core/workflows/bkit-design.md +58 -32
  189. package/.bkit/core/workflows/bkit-plan.md +73 -45
  190. package/.bkit/core/workflows/bkit-ship.md +233 -167
  191. package/.bkit/shared/.agents/plugins/bkit/hooks.json +1 -1
  192. package/.bkit/shared/.bkit/.env.example +5 -0
  193. package/.bkit/shared/.claude/bkit-cloud.md +7 -7
  194. package/.bkit/shared/.claude/settings.json +5 -1
  195. package/.bkit/shared/.cursor/bkit-cloud.md +1 -1
  196. package/.bkit/shared/.cursor/hooks.json +1 -1
  197. package/.bkit/shared/.opencode/opencode.json +11 -2
  198. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +27 -0
  199. package/.bkit/templates/.cursor/Dockerfile +7 -7
  200. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-idea.yml +1 -1
  201. package/.bkit/templates/.github/dependabot.yml +5 -0
  202. package/.bkit/templates/.github/renovate.json5 +5 -3
  203. package/.bkit/templates/.github/workflows/bkit-ci.yml +11 -11
  204. package/.bkit/templates/.github/workflows/bkit-cloud.yml +525 -161
  205. package/.bkit/templates/.github/workflows/bkit-renovate.yml +2 -2
  206. package/.bkit/templates/.husky/pre-push +123 -6
  207. package/.bkit/templates/context/bkit-serena.md +1 -1
  208. package/.bkit/templates/context/bkit-vercel.md +103 -59
  209. package/.bkit/templates/docs/architecture.md +98 -0
  210. package/.bkit/templates/docs/capabilities.md +33 -37
  211. package/.bkit/templates/docs/components.md +142 -0
  212. package/.bkit/templates/docs/data-schema.md +87 -0
  213. package/.bkit/{shared → templates}/docs/deployments.md +128 -142
  214. package/.bkit/templates/docs/design.md +117 -0
  215. package/.bkit/templates/docs/noise.md +54 -0
  216. package/.bkit/templates/docs/observability.md +99 -0
  217. package/.bkit/templates/docs/security.md +137 -0
  218. package/.bkit/templates/docs/setup.md +93 -0
  219. package/.bkit/templates/docs/technology.md +70 -0
  220. package/.bkit/{shared → templates}/docs/testing.md +200 -87
  221. package/.bkit/templates/scripts/ci/bkit-check-accepted-divergences.mjs +1 -6
  222. package/.bkit/templates/scripts/ci/bkit-machine-lock.sh +511 -103
  223. package/.bkit/templates/scripts/ci/bkit-test-awake.mjs +314 -28
  224. package/.bkit/templates/scripts/ci/bkit-test-awake.test.mjs +500 -1
  225. package/.bkit/templates/scripts/graphify/bkit-graphify-graphml.py +1 -1
  226. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +91 -62
  227. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +59 -11
  228. package/.bkit/templates/slop-scan.config.json +2 -0
  229. package/CHANGELOG.md +79 -0
  230. package/DETAILS.md +661 -0
  231. package/README.md +73 -604
  232. package/dist/checks/after/auth.js +114 -46
  233. package/dist/checks/after/github.js +138 -35
  234. package/dist/checks/after/index.js +16 -4
  235. package/dist/checks/after/tools.js +224 -1
  236. package/dist/checks/before/files.js +59 -1
  237. package/dist/checks/before/index.js +7 -1
  238. package/dist/checks/status-holes.js +20 -21
  239. package/dist/checks/tips/catalogue.js +99 -10
  240. package/dist/checks/tips/detect.js +35 -3
  241. package/dist/checks/tips/index.js +1 -1
  242. package/dist/cli.js +13 -13
  243. package/dist/commands/ci/ci.js +113 -20
  244. package/dist/commands/ci/push-gate.js +79 -44
  245. package/dist/commands/install/doctor.js +5 -5
  246. package/dist/commands/install/install.js +23 -22
  247. package/dist/commands/install/uninstall.js +36 -30
  248. package/dist/commands/install/upgrade.js +10 -2
  249. package/dist/commands/land.js +2 -3
  250. package/dist/commands/lib.js +323 -25
  251. package/dist/commands/workflow/branches.js +312 -72
  252. package/dist/commands/workflow/challenge.js +66 -13
  253. package/dist/commands/workflow/context.js +46 -10
  254. package/dist/commands/workflow/counters.js +231 -23
  255. package/dist/commands/workflow/decisions.js +221 -106
  256. package/dist/commands/workflow/disk.js +2 -1
  257. package/dist/commands/workflow/feature-base.js +60 -0
  258. package/dist/commands/workflow/issues.js +243 -15
  259. package/dist/commands/workflow/junit.js +137 -0
  260. package/dist/commands/workflow/ledgers.js +726 -112
  261. package/dist/commands/workflow/locks.js +150 -29
  262. package/dist/commands/workflow/loops.js +67 -0
  263. package/dist/commands/workflow/open-decision.js +199 -0
  264. package/dist/commands/workflow/plan-blocks.js +6 -0
  265. package/dist/commands/workflow/plans.js +1 -1
  266. package/dist/commands/workflow/prs.js +272 -16
  267. package/dist/commands/workflow/repo.js +1 -1
  268. package/dist/commands/workflow/run-facts.js +6 -0
  269. package/dist/commands/workflow/runs.js +747 -155
  270. package/dist/commands/workflow/runtime.js +8 -4
  271. package/dist/commands/workflow/status.js +259 -13
  272. package/dist/commands/workflow/step-table.js +41 -15
  273. package/dist/commands/workflow/steps.js +530 -26
  274. package/dist/commands/workflow/summary-findings.js +1 -1
  275. package/dist/commands/workflow/summary.js +289 -8
  276. package/dist/commands/workflow/tasks.js +294 -27
  277. package/dist/commands/workflow/tests-base.js +266 -0
  278. package/dist/commands/workflow/tests-changed.js +130 -56
  279. package/dist/commands/workflow/tests-jump.js +77 -0
  280. package/dist/commands/workflow/tests.js +608 -131
  281. package/dist/commands/workflow/tracker.js +920 -112
  282. package/dist/commands/workflow/workflows.js +80 -59
  283. package/dist/commands/workflow/worktrees.js +387 -58
  284. package/dist/install/cloud-env.js +32 -10
  285. package/dist/install/managed-block.js +101 -0
  286. package/dist/install/manifest.js +7 -1
  287. package/dist/install/modules/claude.js +6 -2
  288. package/dist/install/modules/cloud.js +73 -86
  289. package/dist/install/modules/codex.js +9 -2
  290. package/dist/install/modules/core.js +190 -27
  291. package/dist/install/modules/opencode.js +18 -23
  292. package/dist/install/network-allowlist.js +8 -3
  293. package/dist/install/project-docs.js +551 -0
  294. package/dist/install/template-copies.js +55 -5
  295. package/dist/install/write.js +117 -5
  296. package/dist/ledgers/journal.js +10 -8
  297. package/dist/ledgers/migrate.js +20 -9
  298. package/dist/ledgers/status.js +461 -8
  299. package/dist/ledgers/telemetry.js +71 -13
  300. package/dist/render/trackers.js +21 -12
  301. package/dist/shared/package-manager.js +7 -2
  302. package/dist/shared/settings.js +8 -0
  303. package/dist/shared/text.js +13 -0
  304. package/dist/tools/instructions-sources.js +1 -0
  305. package/dist/tools/instructions.js +97 -24
  306. package/package.json +23 -15
  307. package/.bkit/core/hooks/preflight-linear.sh +0 -73
  308. package/.bkit/shared/docs/architecture.md +0 -16
  309. package/.bkit/shared/docs/data-schema.md +0 -16
  310. package/.bkit/shared/docs/design.md +0 -38
  311. package/.bkit/shared/docs/noise.md +0 -20
  312. package/.bkit/shared/docs/observability.md +0 -22
  313. package/.bkit/shared/docs/security.md +0 -62
  314. package/.bkit/shared/docs/setup.md +0 -52
  315. package/.bkit/shared/docs/technology.md +0 -15
  316. /package/.bkit/templates/{.lintstagedrc.json → lintstagedrc.example.json} +0 -0
  317. /package/.bkit/templates/{.prettierignore → prettierignore.example} +0 -0
@@ -9,11 +9,13 @@
9
9
  // lock this caller owns (same token, else same workflow and feature), so a Failure
10
10
  // Path that never got the lock cannot delete the holder's.
11
11
 
12
- import { randomBytes } from "node:crypto";
12
+ import { createHash, randomBytes } from "node:crypto";
13
13
  import * as fs from "node:fs";
14
+ import * as os from "node:os";
14
15
  import * as path from "node:path";
15
16
 
16
17
  import {
18
+ createExclusive,
17
19
  fold,
18
20
  lastRun,
19
21
  statusTimestamp,
@@ -23,8 +25,10 @@ import {
23
25
  import {
24
26
  CommandError,
25
27
  EXIT,
28
+ git,
26
29
  parseJson,
27
30
  repoRoot,
31
+ runTool,
28
32
  statusRelPath,
29
33
  utcMonth,
30
34
  type CommandSpec,
@@ -43,6 +47,8 @@ export const EXIT_SPLIT_BUCKET = 7;
43
47
  export const EXIT_NOT_OWNER = 4;
44
48
  /** Exit code: the lock file is still there after removing it. */
45
49
  export const EXIT_REMOVE_FAILED = 5;
50
+ /** Exit code: another run of the feature holds the lock and is still stepping. */
51
+ export const EXIT_LOCK_BUSY = 8;
46
52
 
47
53
  const KINDS = ["workflow"] as const;
48
54
  type Kind = (typeof KINDS)[number];
@@ -112,24 +118,102 @@ export function readHolder(file: string): Holder | undefined {
112
118
  /** Create `file` only if absent (`set -C`); false when someone else holds it. */
113
119
  export function tryCreate(file: string, line: string): boolean {
114
120
  fs.mkdirSync(path.dirname(file), { recursive: true });
115
- const fd = openExclusive(file);
116
- if (fd === undefined) return false;
117
- fs.writeSync(fd, `${line}\n`);
118
- fs.closeSync(fd);
119
- return true;
121
+ return createExclusive(file, `${line}\n`);
120
122
  }
121
123
 
122
- function openExclusive(file: string): number | undefined {
124
+ const newToken = () => randomBytes(4).toString("hex");
125
+
126
+ export interface PublicationLock {
127
+ path: string;
128
+ token: string;
129
+ owner: { host: string; pid: number; startTime: string };
130
+ }
131
+
132
+ /** The OS start identity distinguishes a live reused PID from a recorded owner. */
133
+ function processStart(pid: number, timeoutMs = 1000): string | null {
134
+ const result = runTool("ps", ["-p", String(pid), "-o", "lstart="], process.cwd(), {
135
+ timeoutMs: Math.max(50, Math.min(1000, timeoutMs)),
136
+ });
137
+ return result.found && result.status === 0 && result.stdout.trim() !== ""
138
+ ? result.stdout.trim()
139
+ : null;
140
+ }
141
+
142
+ function publicationHolder(file: string): PublicationLock | null {
143
+ const parsed = parseJson(fs.readFileSync(file, "utf8"));
144
+ if (!parsed.ok || typeof parsed.value !== "object" || parsed.value === null) return null;
145
+ const raw = parsed.value as Partial<PublicationLock>;
146
+ return typeof raw.token === "string" &&
147
+ /^[a-f0-9]{32}$/.test(raw.token) &&
148
+ typeof raw.path === "string" &&
149
+ typeof raw.owner?.host === "string" &&
150
+ Number.isInteger(raw.owner.pid) &&
151
+ raw.owner.pid > 0 &&
152
+ typeof raw.owner.startTime === "string" &&
153
+ Number.isFinite(Date.parse(raw.owner.startTime))
154
+ ? { path: file, token: raw.token, owner: raw.owner }
155
+ : null;
156
+ }
157
+
158
+ /** A separate best-effort lock for one issue and invocation; age never establishes death. */
159
+ export async function acquirePublicationLock(
160
+ cwd: string,
161
+ options: { target: string; invocation: string; timeoutMs?: number },
162
+ ): Promise<PublicationLock | null> {
123
163
  try {
124
- return fs.openSync(file, "wx");
125
- } catch (err) {
126
- // EEXIST is the expected "someone holds it" answer; anything else is a real error.
127
- if ((err as NodeJS.ErrnoException).code === "EEXIST") return undefined;
128
- throw err;
164
+ const end = performance.now() + Math.min(30_000, Math.max(0, options.timeoutMs ?? 30_000));
165
+ const common = git(cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
166
+ const startTime = processStart(process.pid, end - performance.now());
167
+ if (!common || !startTime || !options.target || !options.invocation) return null;
168
+ const digest = createHash("sha256")
169
+ .update(`${options.target}\0${options.invocation}`)
170
+ .digest("hex");
171
+ const file = path.join(common, "bkit-outbox", "publication-locks", `${digest}.lock`);
172
+ const lock: PublicationLock = {
173
+ path: file,
174
+ token: randomBytes(16).toString("hex"),
175
+ owner: { host: os.hostname(), pid: process.pid, startTime },
176
+ };
177
+ fs.mkdirSync(path.dirname(file), { recursive: true });
178
+ do {
179
+ if (tryCreate(file, JSON.stringify(lock))) return lock;
180
+ const holder = publicationHolder(file);
181
+ if (!holder || holder.owner.host !== lock.owner.host) return null;
182
+ let dead = false;
183
+ try {
184
+ process.kill(holder.owner.pid, 0);
185
+ } catch (error) {
186
+ dead = (error as NodeJS.ErrnoException).code === "ESRCH";
187
+ }
188
+ if (dead) {
189
+ if (publicationHolder(file)?.token !== holder.token) return null;
190
+ fs.unlinkSync(file);
191
+ if (tryCreate(file, JSON.stringify(lock))) return lock;
192
+ continue;
193
+ }
194
+ if (processStart(holder.owner.pid, end - performance.now()) !== holder.owner.startTime)
195
+ return null;
196
+ const remaining = end - performance.now();
197
+ if (remaining <= 0) return null;
198
+ await new Promise((resolve) => setTimeout(resolve, Math.min(20, remaining)));
199
+ } while (performance.now() <= end);
200
+ return null;
201
+ } catch {
202
+ // Lock failures select standalone publication rather than fail substantive work.
203
+ return null;
129
204
  }
130
205
  }
131
206
 
132
- const newToken = () => randomBytes(4).toString("hex");
207
+ /** Remove only this publication token; filesystem errors leave append unavailable. */
208
+ export async function releasePublicationLock(lock: PublicationLock): Promise<boolean> {
209
+ try {
210
+ if (publicationHolder(lock.path)?.token !== lock.token) return false;
211
+ fs.unlinkSync(lock.path);
212
+ return true;
213
+ } catch {
214
+ return false;
215
+ }
216
+ }
133
217
 
134
218
  const lockLine = (workflow: string, fid: string, token: string) =>
135
219
  `${statusTimestamp()} ${workflow} ${fid} ${token}`;
@@ -152,6 +236,17 @@ export interface WorkflowLockResult {
152
236
  reclaimed: { holder: string; reason: "finished" | "stale" | "orphaned" } | null;
153
237
  }
154
238
 
239
+ /** The run holding a live workflow lock: who, since when, and when it last stepped. */
240
+ export interface LockHeldBy {
241
+ workflow: string | null;
242
+ /** When the holder took the lock (its lock line's timestamp). */
243
+ since: string | null;
244
+ /** The holder's last status step; null when it took the lock this instant and has none yet. */
245
+ lastStepAt: string | null;
246
+ idleSeconds: number | null;
247
+ line: string;
248
+ }
249
+
155
250
  /** Why a held workflow lock is still live, or why it may be reclaimed. */
156
251
  function liveReason(
157
252
  root: string,
@@ -159,7 +254,7 @@ function liveReason(
159
254
  fid: string,
160
255
  holder: Holder,
161
256
  now: number,
162
- ): { live: string } | { reason: "finished" | "stale" | "orphaned" } {
257
+ ): { live: LockHeldBy } | { reason: "finished" | "stale" | "orphaned" } {
163
258
  const rel = statusRelPath(month, fid);
164
259
  const worktreeCopy = path.join(root, ".worktrees", fid, rel);
165
260
  const own = fs.existsSync(worktreeCopy) ? worktreeCopy : path.join(root, rel);
@@ -168,7 +263,16 @@ function liveReason(
168
263
  const lastAt = run?.steps.at(-1)?.at;
169
264
  if (run?.status === "IN_PROGRESS" && lastAt) {
170
265
  const idle = Math.floor((now - Date.parse(lastAt)) / 1000);
171
- if (idle < WORKFLOW_LOCK_IDLE_S) return { live: `idle ${idle}s` };
266
+ if (idle < WORKFLOW_LOCK_IDLE_S)
267
+ return {
268
+ live: {
269
+ workflow: holder.workflow ?? null,
270
+ since: holder.at ?? null,
271
+ lastStepAt: lastAt,
272
+ idleSeconds: idle,
273
+ line: holder.line,
274
+ },
275
+ };
172
276
  }
173
277
  if (run === undefined) return { reason: "orphaned" };
174
278
  return { reason: run.status === "IN_PROGRESS" ? "stale" : "finished" };
@@ -211,13 +315,27 @@ export function workflowLockFresh(root: string, fid: string): boolean {
211
315
  });
212
316
  }
213
317
 
214
- export function acquireWorkflowLock(opts: {
318
+ /** A lock another live run holds: nothing was taken or removed. */
319
+ export interface WorkflowLockBusy {
320
+ path: string;
321
+ month: string;
322
+ heldBy: LockHeldBy;
323
+ }
324
+
325
+ const busyMessage = (fid: string, by: LockHeldBy) =>
326
+ `workflow already running for ${fid} (workflow=${by.workflow ?? "?"}, ${by.idleSeconds === null ? "just started" : `idle ${by.idleSeconds}s`})`;
327
+
328
+ /**
329
+ * Take the feature's workflow lock, reclaiming an idle holder's. A holder still
330
+ * stepping keeps its lock, and the result names it in `heldBy`.
331
+ */
332
+ export function tryAcquireWorkflowLock(opts: {
215
333
  cwd: string;
216
334
  workflow: string;
217
335
  fid: string;
218
336
  month?: string;
219
337
  log: (m: string) => void;
220
- }): WorkflowLockResult {
338
+ }): WorkflowLockResult | WorkflowLockBusy {
221
339
  const root = repoRoot(opts.cwd);
222
340
  const month = resolveMonth(root, opts.fid, opts.month);
223
341
  const file = workflowLockPath(root, month, opts.fid);
@@ -227,18 +345,40 @@ export function acquireWorkflowLock(opts: {
227
345
 
228
346
  const holder = readHolder(file) ?? { line: "" };
229
347
  const verdict = liveReason(root, month, opts.fid, holder, Date.now());
230
- if ("live" in verdict) {
231
- throw new CommandError(
232
- EXIT.NO,
233
- `workflow already running for ${opts.fid} (workflow=${holder.workflow ?? "?"}, ${verdict.live})`,
234
- );
235
- }
348
+ if ("live" in verdict) return { path: file, month, heldBy: verdict.live };
236
349
  opts.log(`reclaiming ${verdict.reason} lock for ${opts.fid}: ${holder.line}`);
237
350
  fs.rmSync(file, { force: true });
238
- if (!tryCreate(file, line)) throw new CommandError(EXIT.NO, `lock contended for ${opts.fid}`);
351
+ if (!tryCreate(file, line)) {
352
+ // Another acquirer took the lock between the removal and this create.
353
+ const winner = readHolder(file) ?? { line: "" };
354
+ return {
355
+ path: file,
356
+ month,
357
+ heldBy: {
358
+ workflow: winner.workflow ?? null,
359
+ since: winner.at ?? null,
360
+ lastStepAt: null,
361
+ idleSeconds: null,
362
+ line: winner.line,
363
+ },
364
+ };
365
+ }
239
366
  return { path: file, month, token, reclaimed: { holder: holder.line, reason: verdict.reason } };
240
367
  }
241
368
 
369
+ /** {@link tryAcquireWorkflowLock}, refusing with {@link EXIT_LOCK_BUSY} when a live run holds the lock. */
370
+ export function acquireWorkflowLock(opts: {
371
+ cwd: string;
372
+ workflow: string;
373
+ fid: string;
374
+ month?: string;
375
+ log: (m: string) => void;
376
+ }): WorkflowLockResult {
377
+ const lock = tryAcquireWorkflowLock(opts);
378
+ if ("heldBy" in lock) throw new CommandError(EXIT_LOCK_BUSY, busyMessage(opts.fid, lock.heldBy));
379
+ return lock;
380
+ }
381
+
242
382
  // ---------------------------------------------------------------------------
243
383
  // Release
244
384
  // ---------------------------------------------------------------------------
@@ -305,29 +445,46 @@ export const locksCommand: CommandSpec = {
305
445
  summary: "Acquire and release the per-feature workflow lock.",
306
446
  verbs: {
307
447
  acquire: {
308
- summary: "Take the workflow lock, reclaiming a dead holder's.",
448
+ summary:
449
+ "Take the workflow lock, reclaiming a dead holder's; a live holder exits 8 and prints heldBy.",
309
450
  use: "workflow",
310
451
  flags: [KIND_FLAG, LOCK_WORKFLOW_FLAG, FID_FLAG, MONTH_FLAG],
311
452
  output: {
312
453
  kind: "workflow",
313
454
  path: "absolute path of the lock file",
314
- token: "this holder's token; pass it to release",
455
+ token: "this holder's token; pass it to release (null when busy)",
315
456
  month: "the month bucket",
316
457
  reclaimed: "{holder, reason: finished|stale|orphaned}; null when none",
458
+ heldBy:
459
+ "{workflow, since, lastStepAt, idleSeconds, line} of the live run that keeps the lock; null when this call took it",
460
+ route:
461
+ "go when this call took the lock; stop when a live run keeps it (exit 8). An error exit prints no route",
462
+ message:
463
+ "for stop: the line for the owner naming the holder, when it took the lock and last stepped, and when this run can start again; empty for go",
317
464
  },
318
465
  exitCodes: {
319
466
  [EXIT_SPLIT_BUCKET]: "the feature has logs in more than one month bucket",
467
+ [EXIT_LOCK_BUSY]:
468
+ "another run of the feature holds the lock and stepped in the last 30 minutes; nothing was taken or changed",
320
469
  },
321
470
  run: (ctx) => {
322
471
  const kind = kindOf(ctx);
323
- const lock = acquireWorkflowLock({
472
+ const fid = String(ctx.flags.fid);
473
+ const lock = tryAcquireWorkflowLock({
324
474
  cwd: ctx.cwd,
325
475
  workflow: String(ctx.flags.workflow),
326
- fid: String(ctx.flags.fid),
476
+ fid,
327
477
  month: str(ctx.flags.month),
328
478
  log: ctx.log,
329
479
  });
330
- ctx.emit({ kind, ...lock });
480
+ if ("heldBy" in lock) {
481
+ const by = lock.heldBy;
482
+ const message = `${by.workflow ?? "another run"} has held ${fid} since ${by.since ?? "an unknown time"} and last stepped at ${by.lastStepAt ?? "no step yet"}. Nothing changed; this run can start again once that run ends or has been idle ${WORKFLOW_LOCK_IDLE_S / 60} minutes.`;
483
+ ctx.emit({ kind, ...lock, token: null, reclaimed: null, route: "stop", message });
484
+ ctx.log(busyMessage(fid, lock.heldBy));
485
+ return EXIT_LOCK_BUSY;
486
+ }
487
+ ctx.emit({ kind, ...lock, heldBy: null, route: "go", message: "" });
331
488
  return EXIT.OK;
332
489
  },
333
490
  },
@@ -0,0 +1,87 @@
1
+ // The build fix loops, and the step whose test-run rows judge each fix round.
2
+ // Kept apart from decisions.ts and status.ts so both can import it without an import cycle.
3
+
4
+ export interface FixLoop {
5
+ /** The loop question's title in a decision file. */
6
+ title: string;
7
+ /** The step that counts the loop's problems. */
8
+ check: string;
9
+ /** The step that fixes them. */
10
+ fix: string;
11
+ /** The `build {point}: attempt` line's name. */
12
+ point: string;
13
+ /** Only the rounds after the check's last clean round count: the loop reopens. */
14
+ sinceClean?: true;
15
+ /** The gate's test-run step (prefix for a grouped loop): its failing tests join each round's count. */
16
+ gate?: string;
17
+ /** The gate's name in the decision file's progress lines. */
18
+ gateTitle?: string;
19
+ /** The gate runs per task group: its test-run step is `{gate}-{group}`. */
20
+ grouped?: true;
21
+ }
22
+
23
+ export const LOOPS: Readonly<Record<string, FixLoop>> = {
24
+ verify: {
25
+ title: "Verify",
26
+ check: "build-plan-verify",
27
+ fix: "build-plan-gaps-remediate",
28
+ point: "verify",
29
+ gate: "build-group-gate",
30
+ gateTitle: "Group gate",
31
+ grouped: true,
32
+ },
33
+ // The whole-feature check reopens after each clean round, so its loop starts there. Its allowance is `build.holistic`.
34
+ holistic: {
35
+ title: "Holistic verify",
36
+ check: "build-plan-verify-holistic",
37
+ fix: "build-plan-gaps-remediate-holistic",
38
+ point: "holistic",
39
+ sinceClean: true,
40
+ gate: "build-holistic-gate",
41
+ gateTitle: "Holistic gate",
42
+ },
43
+ tests: {
44
+ title: "Tests",
45
+ check: "build-run-tests",
46
+ fix: "build-failure-diagnose",
47
+ point: "tests",
48
+ },
49
+ };
50
+
51
+ /** Fix steps outside the build loops, and the test step each one's rounds are judged by. */
52
+ const OTHER_FIX_TESTS: Readonly<Record<string, string>> = {
53
+ "debug-failure-diagnose": "debug-run-tests",
54
+ };
55
+
56
+ /**
57
+ * The test-run step a loop's gate writes: the gate, with `-{group}` appended for a grouped
58
+ * loop. Undefined for a loop with no gate, or a grouped loop given no group.
59
+ */
60
+ export function loopGateStep(loop: FixLoop, group?: number): string | undefined {
61
+ if (loop.gate === undefined) return undefined;
62
+ if (loop.grouped !== true) return loop.gate;
63
+ return group === undefined ? undefined : `${loop.gate}-${group}`;
64
+ }
65
+
66
+ /**
67
+ * The step whose test-run rows show what a fix step's rounds left failing: the loop's gate
68
+ * (with the group for a grouped loop), else its check; `debug-failure-diagnose` gives
69
+ * `debug-run-tests`. Undefined for any other step, or a grouped loop given no group.
70
+ */
71
+ export function fixTestStep(fix: string, group?: number): string | undefined {
72
+ const other = OTHER_FIX_TESTS[fix];
73
+ if (other !== undefined) return other;
74
+ const loop = Object.values(LOOPS).find((l) => l.fix === fix);
75
+ if (loop === undefined) return undefined;
76
+ return loop.gate === undefined ? loop.check : loopGateStep(loop, group);
77
+ }
78
+
79
+ /**
80
+ * The check step whose current attempt a fix step's round follows, for a loop whose gate
81
+ * does not run on every round: the gate's newest row can belong to an older attempt.
82
+ * Undefined for a loop with no gate, whose test step is the check itself.
83
+ */
84
+ export function gatedCheckStep(fix: string): string | undefined {
85
+ const loop = Object.values(LOOPS).find((l) => l.fix === fix);
86
+ return loop?.gate === undefined ? undefined : loop.check;
87
+ }
@@ -0,0 +1,251 @@
1
+ // Read a build Decision Pause file: its header, its items, the run's open pause, and the two
2
+ // rules read from them — whether a resume re-runs a red gate (`gateRerun`) and whether a
3
+ // pause may route `continue` (`skipProblem`). `decisions.ts` writes these files; this module
4
+ // only reads them and imports nothing from the command modules, so `status.ts`, `steps.ts`
5
+ // and `workflows.ts` read it without an import cycle.
6
+
7
+ import * as fs from "node:fs";
8
+ import * as path from "node:path";
9
+
10
+ /** One question of a decision file. */
11
+ export interface DecisionItem {
12
+ n: number;
13
+ title: string;
14
+ /** The item's whole text, from its `**Q{n}` line to the next item. */
15
+ text: string;
16
+ options: string[];
17
+ /** The recommended option; null for a hard blocker. */
18
+ recommended: string | null;
19
+ reason: string;
20
+ /** The `Decision:` line's text, a lettered answer read as its option (`optionAnswer`). */
21
+ decision: string | null;
22
+ /** The plan task on the `Fix task:` line, else null. */
23
+ fixTask: number | null;
24
+ assumed: boolean;
25
+ rejected: boolean;
26
+ deferred: boolean;
27
+ }
28
+
29
+ /** Splits a decision file before each `**Q{n} — ` item line. */
30
+ export const ITEM_SPLIT = /^(?=\*\*Q\d+ — )/m;
31
+ const lineOf = (text: string, key: string): string | null =>
32
+ new RegExp(`^${key}:[ \\t]*(.+?)[ \\t]*$`, "m").exec(text)?.[1] ?? null;
33
+
34
+ /** `A`, `B`, … for option index `i`. */
35
+ export const letterAt = (i: number): string => String.fromCharCode(65 + i);
36
+ /** An option entry's leading letter (`A) `) dropped, so a parsed name stays bare. */
37
+ const bareName = (s: string): string => s.replace(/^[A-Z]\)[ \t]*/, "");
38
+ /** A reply opening on an option letter: `B`, `B)`, `B — …`, `B) {option} …`, `B {option} …`. */
39
+ const LETTER_REPLY = /^([A-Za-z])(?:\)|(?=[ \t—:,.-]|$))[ \t]*(?:[—:,.-][ \t]*)?/;
40
+
41
+ /**
42
+ * An answer read as the option it names. A leading letter of `options` (either case, with or
43
+ * without `)`) becomes the option it labels: `B`, `B) Reject` and `B — too risky` read as
44
+ * `Reject`, `Reject` and `Reject — too risky`. Any other answer is returned unchanged; with
45
+ * no options known, only a leading `A) ` is dropped.
46
+ */
47
+ export function optionAnswer(answer: string, options: string[]): string {
48
+ if (options.length === 0) return bareName(answer);
49
+ const m = LETTER_REPLY.exec(answer);
50
+ const name = m === null ? undefined : options[m[1]!.toUpperCase().charCodeAt(0) - 65];
51
+ if (m === null || name === undefined) return answer;
52
+ const rest = answer.slice(m[0].length);
53
+ if (rest.toLowerCase().startsWith(name.toLowerCase())) return name + rest.slice(name.length);
54
+ if (rest === "") return name;
55
+ return /[)—:,.-]/.test(m[0]) ? `${name} — ${rest}` : answer;
56
+ }
57
+
58
+ /** A `Fix task:` value as a positive integer, else null. */
59
+ const fixTaskOf = (v: string | null): number | null =>
60
+ v !== null && /^[1-9][0-9]*$/.test(v) ? Number(v) : null;
61
+
62
+ /** The `Key: value` lines before the file's first blank line. */
63
+ export function decisionHeader(text: string): Record<string, string> {
64
+ const out: Record<string, string> = {};
65
+ for (const line of text.split("\n")) {
66
+ if (line.trim() === "" || line.startsWith("**Q")) break;
67
+ const m = /^([A-Za-z][\w ]*):[ \t]*(.*?)[ \t]*$/.exec(line);
68
+ if (m !== null && !(m[1]! in out)) out[m[1]!] = m[2]!;
69
+ }
70
+ return out;
71
+ }
72
+
73
+ /** The items of a decision file's text, in file order. */
74
+ export function parseDecisionItems(text: string): DecisionItem[] {
75
+ return text
76
+ .split(ITEM_SPLIT)
77
+ .slice(1)
78
+ .map((part) => {
79
+ const head = /^\*\*Q(\d+) — (.+?):\*\*/.exec(part);
80
+ const rec = lineOf(part, "Recommended");
81
+ const [option, ...why] = (rec ?? "").split(" — ");
82
+ const none = /^No recommendation\b/m.test(part) || /^none$/i.test((option ?? "").trim());
83
+ const perLine = [...part.matchAll(/^[A-Z]\)[ \t]+(.+?)[ \t]*$/gm)].map((m) =>
84
+ (m[1] ?? "").split(" — ")[0]!.trim(),
85
+ );
86
+ const options =
87
+ perLine.length > 0
88
+ ? perLine.filter(Boolean)
89
+ : (lineOf(part, "Options") ?? "")
90
+ .split(" / ")
91
+ .map((o) => bareName(o.trim()))
92
+ .filter(Boolean);
93
+ const answer = lineOf(part, "Decision");
94
+ const decision = answer === null ? null : optionAnswer(answer, options);
95
+ return {
96
+ n: Number(head?.[1] ?? 0),
97
+ title: head?.[2] ?? "",
98
+ text: part.trimEnd(),
99
+ options,
100
+ recommended: none || rec === null ? null : bareName((option ?? "").trim()),
101
+ reason: why.join(" — ").trim(),
102
+ decision,
103
+ fixTask: fixTaskOf(lineOf(part, "Fix task")),
104
+ assumed: decision !== null && /^Accept \(assumed\)/.test(decision),
105
+ rejected: lineOf(part, "Rejected") !== null,
106
+ deferred: lineOf(part, "Deferred") !== null,
107
+ };
108
+ });
109
+ }
110
+
111
+ /**
112
+ * Whether Q1 is the loop question (the text before the first item holds a `## Progress`
113
+ * block), and the questions besides it that nobody answered, rejected or deferred.
114
+ */
115
+ export function undecidedBesidesLoop(text: string): { hasLoop: boolean; undecided: string[] } {
116
+ const hasLoop = /^## Progress$/m.test(text.split(ITEM_SPLIT, 1)[0] ?? "");
117
+ const undecided = parseDecisionItems(text)
118
+ .filter(
119
+ (i) => (hasLoop ? i.n !== 1 : true) && i.decision === null && !i.rejected && !i.deferred,
120
+ )
121
+ .map((i) => `Q${i.n}`);
122
+ return { hasLoop, undecided };
123
+ }
124
+
125
+ /** The checks a red-gate pause re-runs, by the decision file's `From` header. */
126
+ export const RERUN_FROM = ["verify", "holistic", "tests"] as const;
127
+ export type RerunFrom = (typeof RERUN_FROM)[number];
128
+
129
+ /**
130
+ * Whether a resume re-runs the pause's gate instead of asking it again: its `Gate` header is
131
+ * `FAIL`, its `Status` is `OPEN`, the loop question is its only undecided question, and its
132
+ * `From` names a check that re-runs. `rerunFrom` is that check, null when `gateRerun` is false.
133
+ */
134
+ export function gateRerun(
135
+ open: Pick<OpenDecision, "gate" | "status" | "from"> | null,
136
+ text: string,
137
+ ): { gateRerun: boolean; rerunFrom: RerunFrom | null } {
138
+ const from = RERUN_FROM.find((f) => f === open?.from);
139
+ const { hasLoop, undecided } = undecidedBesidesLoop(text);
140
+ const rerun =
141
+ open?.gate === "FAIL" &&
142
+ open.status === "OPEN" &&
143
+ from !== undefined &&
144
+ hasLoop &&
145
+ undecided.length === 0;
146
+ return { gateRerun: rerun, rerunFrom: rerun ? from! : null };
147
+ }
148
+
149
+ /** An item answer that accepts the item: `Accept` or `Accept (assumed)`, with or without words. */
150
+ const ACCEPTED = /^Accept(?: \(assumed\))?(?:$|[ \t]+—)/;
151
+
152
+ /**
153
+ * The first fact that stops a settled pause from routing `continue`, or null when all five
154
+ * hold: `From` is `verify` or `holistic`; every item is `Accept` or `Accept (assumed)`; the
155
+ * loop question, when asked, is `Decide`; no `Gate: FAIL` header; and a `Source changed`
156
+ * header that reads `false`. Headers count only in the header block, so a line inside an item
157
+ * never stands in for one. A missing fact refuses; it is never guessed.
158
+ */
159
+ export function skipProblem(text: string): string | null {
160
+ const header = decisionHeader(text);
161
+ const from = header.From;
162
+ if (from === undefined) return "no From header";
163
+ if (from !== "verify" && from !== "holistic") return `From is "${from}", not verify or holistic`;
164
+ const { hasLoop } = undecidedBesidesLoop(text);
165
+ const items = parseDecisionItems(text);
166
+ for (const it of items) {
167
+ if (hasLoop && it.n === 1) continue;
168
+ if (it.rejected) return `Q${it.n} is rejected, not Accept`;
169
+ if (it.decision === null || !ACCEPTED.test(it.decision))
170
+ return `Q${it.n} is ${it.decision === null ? "undecided" : `"${it.decision}"`}, not Accept`;
171
+ }
172
+ const loop = hasLoop ? items.find((i) => i.n === 1) : undefined;
173
+ if (loop !== undefined && !/^Decide\b/.test(loop.decision ?? ""))
174
+ return `the loop question Q1 is ${loop.decision === null ? "undecided" : `"${loop.decision}"`}, not Decide`;
175
+ if (/^FAIL\b/.test(header.Gate ?? "")) return "Gate: FAIL header: the gate is red";
176
+ const changed = header["Source changed"];
177
+ if (changed === undefined) return "no Source changed header";
178
+ if (changed !== "false") return `Source changed is "${changed}", not false`;
179
+ return null;
180
+ }
181
+
182
+ /** An OPEN Decision Pause file of the current run, as `workflows start` prints it. */
183
+ export interface OpenDecision {
184
+ file: string;
185
+ decision: number;
186
+ question: string | null;
187
+ from: string | null;
188
+ pauseStep: number | null;
189
+ group: number | null;
190
+ verifyAttempt: number | null;
191
+ testAttempt: number | null;
192
+ plan: string | null;
193
+ gate: string | null;
194
+ sourceChanged: string | null;
195
+ status: string;
196
+ }
197
+
198
+ /**
199
+ * The highest-numbered `{workflow}-decision-{run}-{N}.md` in `logDir` whose header holds
200
+ * `Status: OPEN`, or a `DECIDED` / `ASSUMED` file that none of the run's `{workflow}-decision`
201
+ * rows names (a pause stopped after its answers were written, before the step finished), or
202
+ * null. Only the given run's files count, so an earlier run's pause never resurfaces.
203
+ * `file` is relative to `tree`; `finished` lists the paths the run's decision rows name.
204
+ */
205
+ export function openDecision(
206
+ logDir: string,
207
+ tree: string,
208
+ workflow: string,
209
+ run: number,
210
+ finished: readonly string[] = [],
211
+ ): OpenDecision | null {
212
+ if (!fs.existsSync(logDir)) return null;
213
+ const name = new RegExp(`^${workflow}-decision-${run}-([0-9]+)\\.md$`);
214
+ const found = fs
215
+ .readdirSync(logDir)
216
+ .map((f) => ({ f, m: name.exec(f) }))
217
+ .filter((x): x is { f: string; m: RegExpExecArray } => x.m !== null)
218
+ .map(({ f, m }) => ({ f, n: Number(m[1]) }))
219
+ .sort((a, b) => b.n - a.n);
220
+ for (const { f, n } of found) {
221
+ const text = fs.readFileSync(path.join(logDir, f), "utf-8");
222
+ const field = (key: string) =>
223
+ new RegExp(`^${key}:[ \\t]*(.+?)[ \\t]*$`, "m").exec(text)?.[1] ?? null;
224
+ const status = field("Status");
225
+ const rel = path.relative(tree, path.join(logDir, f));
226
+ const unfinished = (status === "DECIDED" || status === "ASSUMED") && !finished.includes(rel);
227
+ if (status !== "OPEN" && !unfinished) continue;
228
+ // `Gate:` counts only in the header block (the lines before the first blank line).
229
+ const header = text.split(/\r?\n[ \t]*\r?\n/, 1)[0] ?? "";
230
+ const gate = /^Gate:[ \t]*(.+?)[ \t]*$/m.exec(header)?.[1] ?? null;
231
+ const num = (key: string) => {
232
+ const v = field(key);
233
+ return v !== null && /^[0-9]+$/.test(v) ? Number(v) : null;
234
+ };
235
+ return {
236
+ file: rel,
237
+ decision: n,
238
+ question: field("Question"),
239
+ from: field("From"),
240
+ pauseStep: num("Pause step"),
241
+ group: num("Group"),
242
+ verifyAttempt: num("Verify attempt"),
243
+ testAttempt: num("Test attempt"),
244
+ plan: field("Plan"),
245
+ gate,
246
+ sourceChanged: field("Source changed"),
247
+ status: status ?? "OPEN",
248
+ };
249
+ }
250
+ return null;
251
+ }
@@ -150,6 +150,14 @@ function firstTable(lines: string[], heading: RegExp): { head: number; cols: str
150
150
  return { head, cols: tableCells(lines[head]!) };
151
151
  }
152
152
 
153
+ /** The test tier `docs/testing.md` records for a test file's name. */
154
+ export const testTier = (file: string) =>
155
+ /\.integration\.test\./.test(file)
156
+ ? "Integration"
157
+ : /\.live\.test\./.test(file)
158
+ ? "@live (golden)"
159
+ : "Unit";
160
+
153
161
  /**
154
162
  * The plan's Reuse Inventory: the first table under the first heading naming Reuse
155
163
  * Inventory, before the next heading of the same or a higher level. Each row's `File`
@@ -249,7 +249,7 @@ export const plansCommand: CommandSpec = {
249
249
  month: String(ctx.flags.month),
250
250
  fid: String(ctx.flags.fid),
251
251
  });
252
- ctx.emit({ comment: body, commentFile: commentFileOf(ctx.cwd, body), plans });
252
+ ctx.emit({ comment: body, commentFile: commentFileOf(ctx.cwd, body, ctx), plans });
253
253
  return EXIT.OK;
254
254
  },
255
255
  },