@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
@@ -22,18 +22,18 @@
22
22
  import * as fs from "node:fs";
23
23
  import * as path from "node:path";
24
24
  import { readJsonFile } from "../../shared/json.js";
25
- import { CI_TIERS, lastRun, statusTimestamp, validateCiSelection, } from "../../ledgers/status.js";
26
- import { bodySkipToken, commitMessage, CommandError, DEV, EXIT, git, isSharedBranch, parseJson, runGh, runGit, runTool, SKIP_CI_TOKEN, wholeNumber, } from "../lib.js";
25
+ import { appendLine, CI_HANDOFF_RESULTS, CI_TIERS, foldCiHandoff, lastRun, statusTimestamp, validateCiHandoffEvent, validateCiSelection, } from "../../ledgers/status.js";
26
+ import { bodySkipToken, commitMessage, CommandError, DEV, EXIT, git, INVOCATION_FLAG, isSharedBranch, parseJson, runGh, runGit, runTool, SKIP_CI_TOKEN, wholeNumber, } from "../lib.js";
27
27
  import { ciGeneratedSteps, readBkitConfig } from "../../shared/settings.js";
28
28
  import { TIMEOUTS } from "../../shared/timeouts.js";
29
29
  import { FID_PATTERNS, fromBranch, fromMarker, issueIdOf, readIssueTracker } from "./fids.js";
30
30
  import { AUTO_LABEL, AUTO_ROUTE_SUFFIX } from "./issues.js";
31
31
  import { fetchRemoteRef, pushBranch } from "./branches.js";
32
- import { activeRecord, checkOnlyBookkeeping, retriggerCommit } from "./ledgers.js";
33
- import { closeTransportRow, crossCheckFile, devRequiresChecks, prRepoSlug, probePr, } from "./prs.js";
34
- import { resolveOwnerRepo, splitSlug } from "./repo.js";
32
+ import { activeRecord, appendRecordCommit, checkOnlyBookkeeping, commitOwnSet, markRecordPushed, readRecord, retriggerCommit, } from "./ledgers.js";
33
+ import { closeTransportRow, crossCheckFile, devRequiresChecks, prRepoSlug, probePr, validPrFacts, } from "./prs.js";
34
+ import { originOwnerRepo, resolveOwnerRepo, splitSlug } from "./repo.js";
35
35
  import { restateOutcome } from "./run-facts.js";
36
- import { extraField, readRuns, str } from "./status.js";
36
+ import { extraField, readRuns, readStatusRows, str } from "./status.js";
37
37
  import { writeStepRow } from "./steps.js";
38
38
  import { attempt, issueRef, readLabels, trackerTarget } from "./tracker.js";
39
39
  const GH_MISSING = "gh is not on PATH — use the mapped GitHub MCP tool instead";
@@ -57,6 +57,8 @@ export function checkNamespace(capstoneJob) {
57
57
  const i = capstoneJob.lastIndexOf("-");
58
58
  return i > 0 ? capstoneJob.slice(0, i) : capstoneJob;
59
59
  }
60
+ /** The conclusions of a finished run or job that count as a failure. */
61
+ const FAILED_CONCLUSIONS = ["failure", "timed_out", "startup_failure"];
60
62
  /** Whether `.github/workflows/<bkit.testing.ciWorkflow>` exists — the only honest ground for a `no-ci` pass. */
61
63
  export function ciDeclared(root) {
62
64
  const { ciWorkflow } = readBkitConfig(root);
@@ -66,7 +68,7 @@ export function ciDeclared(root) {
66
68
  /** Only the winning reference kind is actionable; a run takes precedence over a PR. */
67
69
  export function parseCiReference(input) {
68
70
  const references = [];
69
- const urls = [...input.matchAll(/https:\/\/github\.com\/[^\s<>"`]+/g)].map((match) => match[0].replace(/[),.;\]]+$/, ""));
71
+ const urls = [...input.matchAll(/https:\/\/github\.com\/[^\s<>"`\[\]()]+/g)].map((match) => match[0].replace(/[),.;\]]+$/, ""));
70
72
  const parsed = urls.flatMap((url) => {
71
73
  const ref = /^https:\/\/github\.com\/([^/]+\/[^/]+)\/(actions\/runs|pull)\/([^/?#]*)([^?#]*)/.exec(url);
72
74
  return ref ? [{ url, ref }] : [];
@@ -285,8 +287,7 @@ function locateCi(ctx) {
285
287
  throw new CommandError(82, "PR lookup returned a run from another head");
286
288
  }
287
289
  validateRun(run);
288
- if (run.status !== "completed" ||
289
- !["failure", "timed_out", "startup_failure"].includes(text(run.conclusion))) {
290
+ if (run.status !== "completed" || !FAILED_CONCLUSIONS.includes(text(run.conclusion))) {
290
291
  if (reference)
291
292
  throw new CommandError(82, `named evidence is ${text(run.status)}/${text(run.conclusion)}; choose [local] to discover locally`);
292
293
  if (run.status !== "completed" ||
@@ -328,10 +329,11 @@ function locateCi(ctx) {
328
329
  text(obj(run.repository).full_name).toLowerCase() !== repo.toLowerCase() ||
329
330
  text(obj(run.head_repository).full_name).toLowerCase() !== repo.toLowerCase())
330
331
  throw new CommandError(82, "run attempt, repository or fork identity does not match");
331
- const failedJobs = jobs.filter((job) => ["failure", "timed_out", "startup_failure"].includes(text(job.conclusion)));
332
- const mapped = failedJobs
333
- .filter((job) => job.name !== "bkit-tests-check")
334
- .map((job) => /^bkit-tests-(static|unit|integration|e2e|live|migration)$/.exec(text(job.name))?.[1]);
332
+ const failedJobs = jobs.filter((job) => FAILED_CONCLUSIONS.includes(text(job.conclusion)));
333
+ const failedNames = failedJobs
334
+ .map((job) => text(job.name))
335
+ .filter((name) => name !== "bkit-tests-check");
336
+ const mapped = failedNames.map((name) => /^bkit-tests-(static|unit|integration|e2e|live|migration)$/.exec(name)?.[1]);
335
337
  const tiers = mapped.some((tier) => tier === undefined)
336
338
  ? []
337
339
  : CI_TIERS.filter((tier) => mapped.includes(tier));
@@ -348,6 +350,12 @@ function locateCi(ctx) {
348
350
  headSha: text(run.head_sha),
349
351
  conclusion: text(run.conclusion),
350
352
  redTiers: tiers,
353
+ ...(failedJobs.length > 0
354
+ ? {
355
+ failedJobCount: Math.max(1, mapped.length),
356
+ failedJobs: [...new Set(failedNames)].sort(),
357
+ }
358
+ : {}),
351
359
  via,
352
360
  };
353
361
  if (saved?.mode === "ci" &&
@@ -475,6 +483,30 @@ function currentPr(cwd, gh) {
475
483
  const n = obj(arr(res.ok ? jsonOrUndefined(res.stdout) : undefined)[0]).number;
476
484
  return { pr: typeof n === "number" ? String(n) : null, missing: false };
477
485
  }
486
+ /**
487
+ * The one CI-Dispatch decision: the gate and `runs handoff` both call it, so a turn loop and an
488
+ * in-process poll reach the same verdict on the same evidence. Zero polls (no PR to read) count
489
+ * as every poll errored.
490
+ */
491
+ export function decideDispatch(f) {
492
+ const unresolved = (reason) => ({
493
+ next: "verdict",
494
+ outcome: "unresolved",
495
+ reason,
496
+ });
497
+ if (!f.found && f.attempts < f.budget)
498
+ return { next: "poll-again" };
499
+ // A run found on a suppressed re-trigger head cannot tell CI from suppression.
500
+ if (f.phase === "repoll" && f.headSuppressed)
501
+ return unresolved("retrigger-suppressed");
502
+ if (f.found)
503
+ return { next: "verdict", outcome: f.phase === "repoll" ? "self-healed" : "dispatched" };
504
+ if (f.errors === f.attempts)
505
+ return unresolved("gh-error");
506
+ if (f.phase === "poll")
507
+ return f.headSuppressed ? unresolved("timeout-dirty") : { next: "retrigger" };
508
+ return f.ciDeclared ? unresolved("ci-declared-no-run") : { next: "verdict", outcome: "no-ci" };
509
+ }
478
510
  /** Exit code: the re-trigger commit or its push failed. */
479
511
  export const EXIT_RETRIGGER_FAILED = 6;
480
512
  /** Push the current branch; the failure text is kept so the gate can name why. */
@@ -489,6 +521,92 @@ function pushCurrentBranch(cwd) {
489
521
  const res = runGit(cwd, args);
490
522
  return { ok: res.ok, error: res.ok ? "" : res.stderr || res.stdout };
491
523
  }
524
+ /**
525
+ * Land a shared-branch run's own commits when every one of them changes nothing (a re-trigger and
526
+ * an empty close): each is copied onto the remote tip with that tip's own tree and pushed as a
527
+ * fast-forward. The tree is one the remote already holds, so there is nothing for a landing gate
528
+ * to validate, and no foreign local commit rides along. `not-empty` hands the push to
529
+ * `pushBranch`, whose landing gate covers content.
530
+ */
531
+ function landEmptyOwnCommits(cwd, fid, branch, log,
532
+ /** Called with the copy's SHA before it is pushed, so a lost push response is recoverable. */
533
+ onCopy) {
534
+ const rec = readRecord(cwd, fid);
535
+ if (rec === null || !runGit(cwd, ["fetch", "origin", branch]).ok)
536
+ return { kind: "failed" };
537
+ const tip = git(cwd, ["rev-parse", "-q", "--verify", `origin/${branch}`]);
538
+ const tipTree = tip === null ? null : git(cwd, ["rev-parse", `${tip}^{tree}`]);
539
+ if (tip === null || tipTree === null)
540
+ return { kind: "failed" };
541
+ const landed = new Set(rec.pushed ?? []);
542
+ const pending = rec.commits.filter((c) => !landed.has(c) && !runGit(cwd, ["merge-base", "--is-ancestor", c, tip]).ok);
543
+ // Every run commit is already on the remote, or was pushed as a copy with a SHA of its own:
544
+ // the remote tip is what holds them, never a recorded local original.
545
+ if (pending.length === 0)
546
+ return { kind: "landed", sha: tip };
547
+ const empty = (c) => {
548
+ const tree = git(cwd, ["rev-parse", `${c}^{tree}`]);
549
+ return tree !== null && tree === git(cwd, ["rev-parse", `${c}^^{tree}`]);
550
+ };
551
+ if (!pending.every(empty))
552
+ return { kind: "not-empty" };
553
+ let parent = tip;
554
+ for (const c of pending) {
555
+ const made = runGit(cwd, [
556
+ "commit-tree",
557
+ tipTree,
558
+ "-p",
559
+ parent,
560
+ "-m",
561
+ git(cwd, ["log", "-1", "--format=%B", c]) ?? "",
562
+ ]);
563
+ if (!made.ok)
564
+ return { kind: "failed" };
565
+ parent = made.stdout;
566
+ }
567
+ onCopy?.(parent);
568
+ const pushed = runGit(cwd, ["push", "origin", `${parent}:refs/heads/${branch}`]);
569
+ if (!pushed.ok) {
570
+ log(`pushing the run's empty commits to ${branch} failed: ${pushed.stderr}`);
571
+ return { kind: "failed" };
572
+ }
573
+ markRecordPushed(cwd, fid, pending);
574
+ log(`landed ${pending.length} empty commit(s) of the run on ${branch} as copies (${parent.slice(0, 12)})`);
575
+ return { kind: "landed", sha: parent };
576
+ }
577
+ /** The persisted `ci-handoff` rows of a status file (none when the file does not exist yet). */
578
+ function handoffRowsOf(statusPath) {
579
+ return fs.existsSync(statusPath) ? readStatusRows(statusPath) : [];
580
+ }
581
+ /** The tip of `branch` on origin: its sha, "" when the branch is absent there, null when the lookup failed. */
582
+ function remoteTip(cwd, branch) {
583
+ const res = runGit(cwd, ["ls-remote", "origin", `refs/heads/${branch}`]);
584
+ if (!res.ok)
585
+ return null;
586
+ return res.stdout.split(/\s+/)[0] ?? "";
587
+ }
588
+ /**
589
+ * The head a target is persisted under. Rows written before a re-trigger carry the head the
590
+ * re-trigger started from, so a process that finds HEAD on the re-trigger commit resumes them.
591
+ */
592
+ function resolveHandoffHead(rows, identity, cwd, current) {
593
+ const mine = rows
594
+ .filter(validateCiHandoffEvent)
595
+ .filter((e) => e.target.repo.toLowerCase() === identity.repo.toLowerCase() &&
596
+ e.target.pr === identity.pr &&
597
+ e.target.branch === identity.branch);
598
+ const latest = mine.at(-1);
599
+ if (latest === undefined || latest.target.head === current)
600
+ return current;
601
+ const rt = latest.retrigger;
602
+ if (rt?.commit === current || rt?.remote === current)
603
+ return latest.target.head;
604
+ if (rt?.state === "intended" &&
605
+ git(cwd, ["rev-parse", "HEAD^"]) === rt.original &&
606
+ /re-trigger/.test(commitMessage(cwd, current) ?? ""))
607
+ return latest.target.head;
608
+ return current;
609
+ }
492
610
  /**
493
611
  * The CI-Dispatch Gate after build / debug's last push. Never pushes after the
494
612
  * verdict: a later commit would move the PR head away from the run it proved.
@@ -517,7 +635,7 @@ export async function ciDispatchGate(o, deps) {
517
635
  ciDispatch: null,
518
636
  head: head(),
519
637
  attempts: 0,
520
- retrigger: o.retriggered,
638
+ retrigger: false,
521
639
  ciWorkflow: declared.ciWorkflow,
522
640
  runBranch: byRun ? branch : null,
523
641
  };
@@ -535,28 +653,87 @@ export async function ciDispatchGate(o, deps) {
535
653
  ciWorkflow: declared.ciWorkflow,
536
654
  namespace: checkNamespace(capstoneJob),
537
655
  };
656
+ // Durable continuation: the persisted state of this target, and the totals kept in step with it.
657
+ const hand = o.handoff;
658
+ const rowsAtStart = handoffRowsOf(hand.statusPath);
659
+ const identity = {
660
+ provider: "github",
661
+ repo: originOwnerRepo(o.cwd) ?? "local/origin",
662
+ pr: o.pr,
663
+ branch: branch || "HEAD",
664
+ };
665
+ const ht = {
666
+ ...identity,
667
+ head: resolveHandoffHead(rowsAtStart, identity, o.cwd, res.head),
668
+ };
669
+ const hs = foldCiHandoff(rowsAtStart, ht);
670
+ let cumAttempts = hs.attempts;
671
+ let cumErrors = hs.errors;
672
+ let curRt = hs.retrigger;
673
+ const repollBase = hs.retriggerBase;
674
+ let lastResult = hs.last?.result ?? "none";
675
+ res.attempts = hs.attempts;
676
+ const persist = (phase, result) => {
677
+ lastResult = result;
678
+ fs.appendFileSync(hand.statusPath, appendLine({
679
+ type: "ci-handoff",
680
+ workflow: hand.workflow ?? "build",
681
+ at: statusTimestamp(),
682
+ phase,
683
+ target: ht,
684
+ observation: { result, attempts: cumAttempts, errors: cumErrors },
685
+ ...(curRt === null ? {} : { retrigger: curRt }),
686
+ }));
687
+ };
688
+ const pollBudget = Math.max(1, Math.ceil(o.budgetS / o.intervalS));
689
+ /** One phase's poll, resumed from the persisted rows: what it saw, in the phase's own counts. */
538
690
  const poll = async (phase) => {
539
- // A supplied result answers only the poll that was handed off; later polls run fresh.
540
- if (o.supplied && (phase === "repoll") === o.retriggered) {
541
- deps.log(`poll result supplied by the agent turn loop: ${o.supplied.pollResult} (attempts ${o.supplied.attempts})`);
542
- return o.supplied;
543
- }
544
- // No PR to read is the shell's empty-PR poll: zero attempts, all errored.
691
+ // No PR to read is the shell's empty-PR poll: zero attempts, all errored, nothing to spend.
545
692
  if (o.pr === null && !byRun)
546
- return { pollResult: "err", attempts: 0, allErrored: true };
693
+ return { found: false, attempts: 0, errors: 0, budget: 0 };
547
694
  if (byRun)
548
695
  target.head = head();
696
+ // The first phase ends where the re-trigger began; the re-poll counts from there.
697
+ const baseA = phase === "repoll" ? (repollBase?.attempts ?? cumAttempts) : 0;
698
+ const baseE = phase === "repoll" ? (repollBase?.errors ?? cumErrors) : 0;
699
+ const endA = phase === "poll" && repollBase ? repollBase.attempts : cumAttempts;
700
+ const endE = phase === "poll" && repollBase ? repollBase.errors : cumErrors;
701
+ const seen = (found, a, e) => ({
702
+ found,
703
+ attempts: a - baseA,
704
+ errors: e - baseE,
705
+ budget: pollBudget,
706
+ });
707
+ const foundBefore = hs.last !== null &&
708
+ ["pending", "success", "failure"].includes(hs.last.result) &&
709
+ hs.phase === phase;
710
+ if (foundBefore && endA === cumAttempts)
711
+ return seen(true, cumAttempts, cumErrors);
712
+ const remaining = pollBudget - (endA - baseA);
713
+ if (remaining <= 0)
714
+ return seen(false, endA, endE);
715
+ let errs = 0;
549
716
  deps.log(byRun
550
- ? `polling for a ${target.ciWorkflow} run on ${branch} at ${target.head} (budget ${o.budgetS}s, interval ${o.intervalS}s)`
551
- : `polling for a ${target.namespace} check on PR #${o.pr} (budget ${o.budgetS}s, interval ${o.intervalS}s)`);
552
- const w = await waitLoop({ budgetS: o.budgetS, intervalS: o.intervalS, once: false }, () => pollOnce(target, deps.gh), deps.sleep, deps.log);
717
+ ? `polling for a ${target.ciWorkflow} run on ${branch} at ${target.head} (${remaining} attempt(s) left, interval ${o.intervalS}s)`
718
+ : `polling for a ${target.namespace} check on PR #${o.pr} (${remaining} attempt(s) left, interval ${o.intervalS}s)`);
719
+ const w = await waitLoop({ budgetS: remaining * o.intervalS, intervalS: o.intervalS, once: false }, () => {
720
+ const p = pollOnce(target, deps.gh);
721
+ if (p.state === "err")
722
+ errs += 1;
723
+ return p;
724
+ }, deps.sleep, deps.log);
725
+ cumAttempts += w.attempts;
726
+ cumErrors += errs;
727
+ res.attempts = cumAttempts;
728
+ const phaseAttempts = cumAttempts - baseA;
729
+ const allErrored = phaseAttempts > 0 && cumErrors - baseE === phaseAttempts;
730
+ persist(phase, w.result === "found" ? "pending" : allErrored ? "provider-error" : "none");
553
731
  if (w.blocked || w.ghMissing) {
554
732
  res.phase = phase;
555
733
  res.handoff = w.ghMissing ? EXIT.USE_MCP : EXIT.AGENT_WAIT;
556
- res.attempts += w.attempts;
557
734
  return null;
558
735
  }
559
- return { pollResult: w.result, attempts: w.attempts, allErrored: w.allErrored };
736
+ return seen(w.result === "found", cumAttempts, cumErrors);
560
737
  };
561
738
  const verdict = (outcome, reason) => {
562
739
  res.ciDispatch = {
@@ -569,21 +746,150 @@ export async function ciDispatchGate(o, deps) {
569
746
  deps.log(`verdict: ${outcome}${reason ? `(${reason})` : ""} head=${res.head} attempts=${res.attempts} retrigger=${res.retrigger}`);
570
747
  return res;
571
748
  };
572
- if (!o.retriggered) {
749
+ /**
750
+ * The re-trigger as persisted checkpoints: intended -> commit-created -> push-completed ->
751
+ * receipt-completed. A fresh process continues from the last one; no effect repeats.
752
+ */
753
+ const handoffRetrigger = async (message, rec) => {
754
+ const refName = `refs/heads/${branch}`;
755
+ let cur = curRt ?? { state: "intended", original: head() };
756
+ if (curRt === null) {
757
+ curRt = cur;
758
+ persist("poll", lastResult);
759
+ }
760
+ if (cur.state === "intended") {
761
+ const parent = git(o.cwd, ["rev-parse", "HEAD^"]);
762
+ const adopted = git(o.cwd, ["rev-parse", "HEAD"]) !== cur.original &&
763
+ parent === cur.original &&
764
+ /re-trigger/.test(commitMessage(o.cwd, "HEAD") ?? "");
765
+ let sha;
766
+ if (adopted) {
767
+ sha = git(o.cwd, ["rev-parse", "HEAD"]);
768
+ if (rec !== null && sha !== null && !readRecord(o.cwd, o.fid)?.commits.includes(sha))
769
+ appendRecordCommit(o.cwd, o.fid, sha);
770
+ }
771
+ else {
772
+ const made = rec === null
773
+ ? commitOwnSet(o.cwd, { plain: [], ledgers: [] }, message, { allowEmpty: true })
774
+ : retriggerCommit(o.cwd, rec, message);
775
+ if (!made.ok)
776
+ deps.log(`re-trigger commit failed: ${made.error}`);
777
+ sha = made.ok ? made.sha : null;
778
+ }
779
+ if (sha === null)
780
+ return false;
781
+ cur = { state: "commit-created", original: cur.original, commit: sha };
782
+ curRt = cur;
783
+ persist("poll", lastResult);
784
+ hand.checkpoint?.("commit-created");
785
+ }
786
+ if (cur.state === "commit-created" && cur.commit !== undefined) {
787
+ let remoteSha;
788
+ if (rec === null) {
789
+ const tip = remoteTip(o.cwd, branch);
790
+ if (tip === null) {
791
+ deps.log("re-trigger push blocked: the remote branch could not be read");
792
+ return false;
793
+ }
794
+ if (tip !== cur.commit) {
795
+ // Whatever `origin/<branch>` holds, a tip that is not behind the re-trigger commit is
796
+ // someone else's work: a lease taken against an up-to-date tracking ref would overwrite it.
797
+ const fastForward = tip === "" || runGit(o.cwd, ["merge-base", "--is-ancestor", tip, cur.commit]).ok;
798
+ if (!fastForward) {
799
+ deps.log(`re-trigger push blocked: ${branch} moved on the remote to ${tip.slice(0, 12)} after the re-trigger commit was made`);
800
+ return false;
801
+ }
802
+ const push = pushCurrentBranch(o.cwd);
803
+ if (!push.ok) {
804
+ deps.log(`re-trigger push failed: ${push.error}`);
805
+ return false;
806
+ }
807
+ }
808
+ remoteSha = remoteTip(o.cwd, branch) === cur.commit ? cur.commit : null;
809
+ }
810
+ else {
811
+ // A copy persisted by an earlier attempt may already be on the remote: the push
812
+ // response can be lost, so check before copying again.
813
+ const earlier = cur.copy;
814
+ const held = earlier !== undefined &&
815
+ runGit(o.cwd, ["fetch", "origin", branch]).ok &&
816
+ runGit(o.cwd, ["merge-base", "--is-ancestor", earlier, `origin/${branch}`]).ok;
817
+ if (held) {
818
+ markRecordPushed(o.cwd, o.fid, [cur.commit]);
819
+ remoteSha = earlier;
820
+ }
821
+ const empties = held
822
+ ? { kind: "landed", sha: earlier }
823
+ : landEmptyOwnCommits(o.cwd, o.fid, branch, deps.log, (copy) => {
824
+ cur = { ...cur, copy };
825
+ curRt = cur;
826
+ persist("poll", lastResult);
827
+ });
828
+ if (empties.kind === "landed")
829
+ remoteSha = empties.sha;
830
+ else if (empties.kind === "failed")
831
+ remoteSha = null;
832
+ else {
833
+ const out = await pushBranch(o.cwd, { mode: "feature", fid: o.fid }, deps.log);
834
+ remoteSha = out.out.pushed
835
+ ? out.out.sha
836
+ : out.out.skipped === "no-run-commits"
837
+ ? (readRecord(o.cwd, o.fid)?.pushed?.at(-1) ?? null)
838
+ : null;
839
+ }
840
+ }
841
+ if (remoteSha === null) {
842
+ deps.log("re-trigger push did not land the re-trigger commit on the remote");
843
+ return false;
844
+ }
845
+ cur = { ...cur, state: "push-completed", ref: refName, remote: remoteSha };
846
+ curRt = cur;
847
+ persist("poll", lastResult);
848
+ hand.checkpoint?.("push-completed");
849
+ }
850
+ if (cur.state === "push-completed" && cur.remote !== undefined) {
851
+ if (rec === null && remoteTip(o.cwd, branch) !== cur.remote) {
852
+ deps.log("re-trigger receipt blocked: the remote branch no longer holds the pushed commit");
853
+ return false;
854
+ }
855
+ cur = { ...cur, state: "receipt-completed", receipt: hand.operation };
856
+ curRt = cur;
857
+ persist("repoll", lastResult);
858
+ hand.checkpoint?.("receipt-completed");
859
+ }
860
+ return curRt.state === "receipt-completed";
861
+ };
862
+ /** Why each verdict was reached, for the log. */
863
+ const why = {
864
+ "gh-error": "every poll of the phase errored — gh unavailable or unauthenticated; silence proves nothing",
865
+ "timeout-dirty": "no run and the pushed head carries a CI suppressor — not re-triggering a dirty head",
866
+ "retrigger-suppressed": "the re-trigger head carries a suppressor — cannot tell no-ci from suppression",
867
+ "ci-declared-no-run": `${declared.path} exists but a clean re-trigger dispatched no check — look for a startup failure`,
868
+ "no-ci": `a clean re-trigger dispatched nothing and ${declared.path} is absent — the repo has no CI workflow (logged pass)`,
869
+ };
870
+ /** The shared decision on what a phase saw; null when the phase must re-trigger. */
871
+ const decide = (phase, seen, headSuppressed) => {
872
+ const d = decideDispatch({ phase, ...seen, headSuppressed, ciDeclared: declared.declared });
873
+ if (d.next === "retrigger")
874
+ return null;
875
+ if (d.next === "poll-again") {
876
+ throw new Error(`CI-Dispatch ${phase} ended with polls left in its budget`);
877
+ }
878
+ const note = why[d.reason ?? d.outcome];
879
+ if (note !== undefined)
880
+ deps.log(`${d.reason === undefined ? d.outcome : `unresolved(${d.reason})`}: ${note}`);
881
+ return verdict(d.outcome, d.reason);
882
+ };
883
+ const suppressed = (sha) => SKIP_CI_TOKEN.test(commitMessage(o.cwd, sha) ?? "");
884
+ if (curRt?.state !== "receipt-completed") {
573
885
  const first = await poll("poll");
574
886
  if (first === null)
575
887
  return res;
576
- res.attempts = first.attempts;
577
- if (first.pollResult === "found")
578
- return verdict("dispatched");
579
- if (first.allErrored) {
580
- deps.log("unresolved(gh-error): every poll errored — gh unavailable or unauthenticated");
581
- return verdict("unresolved", "gh-error");
582
- }
583
- if (SKIP_CI_TOKEN.test(commitMessage(o.cwd, res.head) ?? "")) {
584
- deps.log("unresolved(timeout-dirty): no run and the pushed head carries a CI suppressor — not re-triggering a dirty head");
585
- return verdict("unresolved", "timeout-dirty");
586
- }
888
+ res.attempts = cumAttempts;
889
+ // A re-trigger already under way is resumed, never refused for the head it started from.
890
+ const done = decide("poll", first, curRt === null && suppressed(res.head));
891
+ if (done !== null)
892
+ return done;
587
893
  const message = `chore(${o.fid}): re-trigger${o.autoRouteSuffix}`;
588
894
  // A run in place on a shared branch commits and pushes only its own work; with
589
895
  // no record of the run there, nothing is committed or pushed.
@@ -594,73 +900,27 @@ export async function ciDispatchGate(o, deps) {
594
900
  res.handoff = EXIT_RETRIGGER_FAILED;
595
901
  return res;
596
902
  }
597
- let pushed;
598
- let failure = "";
599
- if (rec === null) {
600
- landed = null;
601
- const before = git(o.cwd, ["rev-parse", "HEAD"]);
602
- const made = runGit(o.cwd, ["commit", "--allow-empty", "-m", message]);
603
- if (!made.ok) {
604
- pushed = false;
605
- failure = made.stderr || made.stdout;
606
- }
607
- else {
608
- const push = pushCurrentBranch(o.cwd);
609
- pushed = push.ok;
610
- if (!push.ok) {
611
- failure = push.error;
612
- // The commit never reached the remote: drop it so a re-run does not pile
613
- // up orphan re-triggers. --soft restores the index exactly as the commit left it.
614
- if (before !== null)
615
- runGit(o.cwd, ["reset", "--soft", before]);
616
- }
617
- }
618
- }
619
- else {
620
- const made = retriggerCommit(o.cwd, rec, message);
621
- if (!made.ok)
622
- deps.log(`re-trigger commit failed: ${made.error}`);
623
- const out = made.ok
624
- ? await pushBranch(o.cwd, { mode: "feature", fid: o.fid }, deps.log)
625
- : null;
626
- landed = out?.out.pushed === true ? out.out.sha : landed;
627
- pushed = out?.out.pushed === true && out.out.sha !== null;
628
- if (pushed)
629
- fetchLanded();
630
- }
631
- if (!pushed) {
632
- deps.log(`re-trigger commit or push failed${failure ? `: ${failure}` : ""} — no verdict; route to the Failure Path`);
903
+ if (!(await handoffRetrigger(message, rec))) {
904
+ deps.log("re-trigger commit or push failed — no verdict; route to the Failure Path");
633
905
  res.phase = "repoll";
634
906
  res.handoff = EXIT_RETRIGGER_FAILED;
635
907
  return res;
636
908
  }
637
- res.retrigger = true;
638
- res.head = head();
639
909
  deps.log("re-trigger pushed; re-polling");
640
910
  }
641
- const prior = res.attempts;
911
+ res.retrigger = true;
912
+ if (shared && curRt?.remote !== undefined)
913
+ landed = curRt.remote;
914
+ res.head = head();
642
915
  const second = await poll("repoll");
643
916
  if (second === null)
644
917
  return res;
645
- // A supplied re-poll carries the running total; a fresh one adds to the first poll.
646
- res.attempts = o.retriggered && o.supplied ? second.attempts : prior + second.attempts;
918
+ res.attempts = cumAttempts;
647
919
  res.head = head();
648
- if (SKIP_CI_TOKEN.test(commitMessage(o.cwd, res.head) ?? "")) {
649
- deps.log("unresolved(retrigger-suppressed): the re-trigger head carries a suppressor — cannot tell no-ci from suppression");
650
- return verdict("unresolved", "retrigger-suppressed");
651
- }
652
- if (second.pollResult === "found")
653
- return verdict("self-healed");
654
- if (second.allErrored) {
655
- deps.log("unresolved(gh-error): every re-poll errored — silence after the re-trigger proves nothing");
656
- return verdict("unresolved", "gh-error");
657
- }
658
- if (declared.declared) {
659
- deps.log(`unresolved(ci-declared-no-run): ${declared.path} exists but a clean re-trigger dispatched no check — look for a startup failure: gh run list --commit ${res.head}`);
660
- return verdict("unresolved", "ci-declared-no-run");
661
- }
662
- deps.log(`no-ci: a clean re-trigger dispatched nothing and ${declared.path} is absent — the repo has no CI workflow (logged pass)`);
663
- return verdict("no-ci");
920
+ const done = decide("repoll", second, suppressed(res.head));
921
+ if (done === null)
922
+ throw new Error("CI-Dispatch re-poll cannot re-trigger a second time");
923
+ return done;
664
924
  }
665
925
  // ---------------------------------------------------------------------------
666
926
  // Ship merge gate
@@ -685,6 +945,8 @@ export const GATE = {
685
945
  NOT_BOOKKEEPING: 17,
686
946
  /** --pr: the PR title carries a CI-suppressing token (its squash would skip CI on dev). */
687
947
  TITLE_SKIP: 18,
948
+ /** The current dev is absent from the validated code head. */
949
+ STALE_BASE: 19,
688
950
  /** API error, rate limit, or auth — distinct from "no run". */
689
951
  API_ERROR: 20,
690
952
  };
@@ -1243,6 +1505,95 @@ async function waitFor(cwd, i, d) {
1243
1505
  return { code: EXIT.AGENT_WAIT, out };
1244
1506
  return { code: EXIT.NO, out };
1245
1507
  }
1508
+ /**
1509
+ * `runs handoff`: record one batch of CI poll observations in the invocation's run and derive the
1510
+ * phase, the cumulative totals and the next action from the persisted rows. The caller supplies
1511
+ * what it saw (`--result`, `--polls`), never a count, a phase or a verdict.
1512
+ */
1513
+ function runHandoff(ctx) {
1514
+ const f = ctx.flags;
1515
+ const inv = ctx.invocation;
1516
+ if (inv === undefined ||
1517
+ inv.scope !== "run" ||
1518
+ inv.statusPath === null ||
1519
+ inv.workflow === null) {
1520
+ throw new CommandError(EXIT.USAGE, "--invocation is required: an invocation issued by `bkit status invocation` for a workflow run");
1521
+ }
1522
+ const text = (v) => (typeof v === "string" ? v : "");
1523
+ const repo = text(f.repo);
1524
+ // A run in place on a shared branch has no PR: an empty --pr names that target.
1525
+ const pr = text(f.pr) === "" ? null : text(f.pr);
1526
+ const suppliedHead = text(f.head);
1527
+ const branch = text(f.branch);
1528
+ const result = CI_HANDOFF_RESULTS.find((r) => r === text(f.result));
1529
+ if (result === undefined) {
1530
+ throw new CommandError(EXIT.USAGE, `--result must be one of ${CI_HANDOFF_RESULTS.join(" | ")}`);
1531
+ }
1532
+ const polls = wholeNumber(f.polls, "polls", 0, 1);
1533
+ const budgetS = wholeNumber(f.budgetS, "budget-s", 60);
1534
+ const intervalS = wholeNumber(f.intervalS, "interval-s", 10, 1);
1535
+ // After a re-trigger the printed head is the re-trigger commit; its rows live under the original head.
1536
+ const head = resolveHandoffHead(handoffRowsOf(inv.statusPath), { provider: "github", repo, pr, branch }, ctx.cwd, suppliedHead);
1537
+ const target = { provider: "github", repo, pr, head, branch };
1538
+ const probe = {
1539
+ type: "ci-handoff",
1540
+ workflow: inv.workflow,
1541
+ at: statusTimestamp(),
1542
+ phase: "poll",
1543
+ target,
1544
+ observation: { result: "none", attempts: 0, errors: 0 },
1545
+ };
1546
+ if (!validateCiHandoffEvent(probe)) {
1547
+ throw new CommandError(EXIT.USAGE, "--repo, --pr, --head and --branch must name the owner/repo, PR number, full commit sha and branch");
1548
+ }
1549
+ const state = foldCiHandoff(readStatusRows(inv.statusPath), target);
1550
+ const attempts = state.attempts + polls;
1551
+ const errors = state.errors + (result === "provider-error" ? polls : 0);
1552
+ const retrigger = state.retrigger;
1553
+ const phase = retrigger?.state === "receipt-completed" ? "repoll" : "poll";
1554
+ fs.appendFileSync(inv.statusPath, appendLine({
1555
+ ...probe,
1556
+ phase,
1557
+ observation: { result, attempts, errors },
1558
+ ...(retrigger === null ? {} : { retrigger }),
1559
+ }));
1560
+ const max = Math.max(1, Math.ceil(budgetS / intervalS));
1561
+ const base = phase === "repoll" ? (state.retriggerBase ?? { attempts: 0, errors: 0 }) : null;
1562
+ const phaseAttempts = attempts - (base?.attempts ?? 0);
1563
+ const phaseErrors = errors - (base?.errors ?? 0);
1564
+ const found = result === "pending" || result === "success" || result === "failure";
1565
+ const out = {
1566
+ phase,
1567
+ attempts,
1568
+ errors,
1569
+ ciResult: result,
1570
+ stale: state.stale,
1571
+ };
1572
+ if (retrigger !== null && retrigger.state !== "receipt-completed") {
1573
+ ctx.emit({ ...out, nextAction: "reconcile-retrigger", retrigger });
1574
+ return EXIT.OK;
1575
+ }
1576
+ // The head the phase polled: the pushed head before the re-trigger, the re-trigger commit after it.
1577
+ const polled = phase === "repoll" ? (retrigger?.commit ?? head) : head;
1578
+ const d = decideDispatch({
1579
+ phase,
1580
+ found,
1581
+ attempts: phaseAttempts,
1582
+ errors: phaseErrors,
1583
+ budget: max,
1584
+ headSuppressed: SKIP_CI_TOKEN.test(commitMessage(ctx.cwd, polled) ?? ""),
1585
+ ciDeclared: ciDeclared(checkoutRoot(ctx.cwd)).declared,
1586
+ });
1587
+ ctx.emit(d.next === "verdict"
1588
+ ? {
1589
+ ...out,
1590
+ nextAction: "verdict",
1591
+ outcome: d.outcome,
1592
+ ...(d.reason === undefined ? {} : { reason: d.reason }),
1593
+ }
1594
+ : { ...out, nextAction: d.next });
1595
+ return EXIT.OK;
1596
+ }
1246
1597
  async function runWait(ctx) {
1247
1598
  const f = ctx.flags;
1248
1599
  const r = await waitFor(ctx.cwd, {
@@ -1271,6 +1622,12 @@ const waitOutput = (w, kind) => ({
1271
1622
  async function runDispatch(ctx) {
1272
1623
  const f = ctx.flags;
1273
1624
  const d = deps(ctx);
1625
+ const inv = ctx.invocation;
1626
+ // Every poll and re-trigger checkpoint is saved in the run's status log, so a re-entry resumes
1627
+ // from what was persisted: without a run's invocation there is nowhere to save it.
1628
+ if (inv === undefined || inv.scope !== "run" || inv.statusPath === null) {
1629
+ throw new CommandError(EXIT.USAGE, "--invocation is required: an invocation issued by `bkit status invocation` for a workflow run");
1630
+ }
1274
1631
  // An empty --pr is the workflow's unresolved PR_NUMBER: derive it, as if omitted.
1275
1632
  let pr = str(f.pr) || null;
1276
1633
  if (pr === null) {
@@ -1289,13 +1646,6 @@ async function runDispatch(ctx) {
1289
1646
  if (sha !== undefined && (pr !== null || !onShared)) {
1290
1647
  throw new CommandError(EXIT.USAGE, "--sha goes with a run in place on a shared branch that has no PR");
1291
1648
  }
1292
- const pollResult = str(f.pollResult);
1293
- if (pollResult !== undefined && !["found", "none", "err"].includes(pollResult)) {
1294
- throw new CommandError(EXIT.USAGE, "--poll-result must be found, none, or err");
1295
- }
1296
- if (pollResult === undefined && (f.attempts !== undefined || f.allErrored === true)) {
1297
- throw new CommandError(EXIT.USAGE, "--attempts / --all-errored go with --poll-result");
1298
- }
1299
1649
  const r = await ciDispatchGate({
1300
1650
  cwd: ctx.cwd,
1301
1651
  pr,
@@ -1305,15 +1655,12 @@ async function runDispatch(ctx) {
1305
1655
  : "",
1306
1656
  budgetS: wholeNumber(f.budgetS, "budget-s", 60),
1307
1657
  intervalS: wholeNumber(f.intervalS, "interval-s", 10, 1),
1308
- supplied: pollResult === undefined
1309
- ? undefined
1310
- : {
1311
- pollResult: pollResult,
1312
- attempts: wholeNumber(f.attempts, "attempts", 0),
1313
- allErrored: f.allErrored === true,
1314
- },
1315
- retriggered: f.retriggered === true,
1316
1658
  sha,
1659
+ handoff: {
1660
+ statusPath: inv.statusPath,
1661
+ operation: `ci-retrigger:${inv.id}`,
1662
+ ...(inv.workflow === null ? {} : { workflow: inv.workflow }),
1663
+ },
1317
1664
  }, d);
1318
1665
  const scanResult = r.ciDispatch && r.ciDispatch.outcome !== "unresolved" ? scanBody(ctx.cwd, r.head) : null;
1319
1666
  // With --file / --step: the verdict lands on the step's row, and a passed one is
@@ -1325,7 +1672,7 @@ async function runDispatch(ctx) {
1325
1672
  let row = null;
1326
1673
  let progressLine;
1327
1674
  let transport = null;
1328
- const code = dispatchCode(r, pr, scanResult, ctx.log);
1675
+ const code = dispatchCode(r, pr, scanResult, ctx.log, inv.id);
1329
1676
  if (file !== undefined && r.ciDispatch !== null) {
1330
1677
  const status = path.resolve(ctx.cwd, file);
1331
1678
  const written = writeStepRow(ctx.cwd, {
@@ -1387,13 +1734,13 @@ async function runDispatch(ctx) {
1387
1734
  return code;
1388
1735
  }
1389
1736
  /** The dispatch verdict as an exit code, with its log line. */
1390
- function dispatchCode(r, pr, scanResult, log) {
1737
+ function dispatchCode(r, pr, scanResult, log, invocation) {
1391
1738
  if (r.handoff === EXIT.AGENT_WAIT || r.handoff === EXIT.USE_MCP) {
1392
- const again = r.phase === "repoll" ? " --retriggered" : "";
1393
1739
  const [wait, keep] = r.runBranch === null
1394
1740
  ? [`--pr=${pr ?? "<n>"}`, ""]
1395
1741
  : [`--head=${r.head} --branch=${r.runBranch} --until=present`, ` --sha=${r.head}`];
1396
- log(`${r.handoff === EXIT.USE_MCP ? GH_MISSING : "this runtime cannot wait"}: resolve the ${r.phase} each turn with \`bkit runs wait ${wait} --once\`, then re-run with --poll-result=<found|none|err> --attempts=<total>${again}${keep}`);
1742
+ const lead = `${r.handoff === EXIT.USE_MCP ? GH_MISSING : "this runtime cannot wait"}: resolve the ${r.phase} each turn with \`bkit runs wait ${wait} --once\``;
1743
+ log(`${lead}, record what it saw with \`bkit runs handoff --invocation=${invocation} --head=${r.head} --result=<none|pending|success|failure|provider-error> --polls=1\`, follow its nextAction, then re-run this command with the same --invocation${keep}`);
1397
1744
  return r.handoff;
1398
1745
  }
1399
1746
  if (r.handoff !== 0)
@@ -1436,8 +1783,35 @@ function logResolvedPrRepo(repoFlag, prNumber, pr, log) {
1436
1783
  log(`PR ${prNumber} resolved in ${repoFlag}`);
1437
1784
  }
1438
1785
  }
1439
- function runGate(ctx) {
1786
+ async function runGate(ctx) {
1440
1787
  const f = ctx.flags;
1788
+ if (f.wait === true && f.squashOf === undefined)
1789
+ throw new CommandError(EXIT.USAGE, "--wait needs --squash-of");
1790
+ const freshBase = f.freshBase === true;
1791
+ if (freshBase && (f.pr === undefined || f.capstoneOnly === true))
1792
+ throw new CommandError(EXIT.USAGE, "--fresh-base requires --pr without --capstone-only");
1793
+ const factsPath = str(f.factsFile);
1794
+ let facts;
1795
+ if (factsPath !== undefined) {
1796
+ if (!freshBase)
1797
+ throw new CommandError(EXIT.USAGE, "--facts-file requires --fresh-base");
1798
+ const parsed = readJsonFile(path.resolve(ctx.cwd, factsPath));
1799
+ if (!parsed.ok)
1800
+ throw new CommandError(EXIT.USAGE, "cannot read scoped gate facts");
1801
+ facts = obj(parsed.value);
1802
+ const info = facts.pr;
1803
+ if (!validPrFacts(info) ||
1804
+ facts.ownerRepo !== prRepoSlug(info.url) ||
1805
+ (str(f.repo) !== undefined && facts.ownerRepo !== str(f.repo)) ||
1806
+ facts.prNumber !== Number(f.pr) ||
1807
+ info.number !== Number(f.pr) ||
1808
+ facts.headRefName !== info.headRefName ||
1809
+ (str(f.branch) !== undefined && facts.headRefName !== str(f.branch)) ||
1810
+ facts.baseRefName !== DEV ||
1811
+ info.baseRefName !== DEV ||
1812
+ info.state !== "OPEN")
1813
+ throw new CommandError(EXIT.USAGE, "gate facts repository, PR, head or base scope mismatch");
1814
+ }
1441
1815
  let selection;
1442
1816
  const selectionFile = str(f.ciSelectionFile);
1443
1817
  if (selectionFile !== undefined) {
@@ -1459,7 +1833,71 @@ function runGate(ctx) {
1459
1833
  ctx.log(`fetch of origin/${branch} failed: ${fetched.stderr.trim()}`);
1460
1834
  }
1461
1835
  const root = checkoutRoot(ctx.cwd);
1462
- const gh = (args) => runGh(ctx.cwd, args);
1836
+ const gh = facts === undefined
1837
+ ? (args) => runGh(ctx.cwd, args)
1838
+ : (args) => {
1839
+ const reply = (value) => ({
1840
+ ok: true,
1841
+ stdout: JSON.stringify(value),
1842
+ stderr: "",
1843
+ missing: false,
1844
+ });
1845
+ const ci = obj(facts.ci);
1846
+ const repo = text(facts.ownerRepo);
1847
+ const endpoint = args[1]?.replace(/^\//, "") ?? "";
1848
+ if (args[0] === "repo" && args[1] === "view")
1849
+ return { ok: true, stdout: repo, stderr: "", missing: false };
1850
+ const workflow = readBkitConfig(checkoutRoot(ctx.cwd)).ciWorkflow;
1851
+ const scopedRuns = arr(obj(ci.workflowRuns).workflow_runs).map(obj);
1852
+ const workflowPath = workflow.startsWith(".github/workflows/")
1853
+ ? workflow
1854
+ : `.github/workflows/${workflow}`;
1855
+ const validRun = (run) => Number.isSafeInteger(run.id) &&
1856
+ Number(run.id) > 0 &&
1857
+ text(obj(run.repository).full_name).toLowerCase() === repo.toLowerCase() &&
1858
+ text(obj(run.head_repository).full_name).toLowerCase() === repo.toLowerCase() &&
1859
+ (text(run.path) === workflowPath ||
1860
+ (/^[1-9][0-9]*$/.test(workflow) && String(run.workflow_id) === workflow)) &&
1861
+ run.head_sha === (str(f.validated) ?? obj(facts.pr).headRefOid) &&
1862
+ run.head_branch === facts.headRefName &&
1863
+ run.html_url === `https://github.com/${repo}/actions/runs/${run.id}`;
1864
+ const invalidEvidence = () => ({
1865
+ ok: false,
1866
+ stdout: "",
1867
+ stderr: "scoped gate CI provenance is missing or mismatched",
1868
+ missing: false,
1869
+ });
1870
+ if (args[0] === "api" &&
1871
+ endpoint.startsWith(`repos/${repo}/actions/workflows/${workflow}/runs?`)) {
1872
+ if (!Array.isArray(obj(ci.workflowRuns).workflow_runs) ||
1873
+ scopedRuns.some((run) => !validRun(run)))
1874
+ return invalidEvidence();
1875
+ return reply(ci.workflowRuns);
1876
+ }
1877
+ const jobMatch = new RegExp(`^repos/${repo}/actions/runs/([0-9]+)/jobs$`).exec(endpoint);
1878
+ if (args[0] === "api" && jobMatch) {
1879
+ const run = scopedRuns.find((candidate) => String(candidate.id) === jobMatch[1]);
1880
+ const pages = Array.isArray(ci.jobs) ? ci.jobs : [ci.jobs];
1881
+ if (!run ||
1882
+ !validRun(run) ||
1883
+ pages.length === 0 ||
1884
+ pages.some((page) => !Array.isArray(obj(page).jobs) ||
1885
+ arr(obj(page).jobs).some((value) => {
1886
+ const job = obj(value);
1887
+ return (job.run_id !== run.id ||
1888
+ job.head_sha !== run.head_sha ||
1889
+ job.run_url !== `https://api.github.com/repos/${repo}/actions/runs/${run.id}`);
1890
+ })))
1891
+ return invalidEvidence();
1892
+ return reply(ci.jobs);
1893
+ }
1894
+ return {
1895
+ ok: false,
1896
+ stdout: "",
1897
+ stderr: "scoped gate facts do not contain this API evidence",
1898
+ missing: false,
1899
+ };
1900
+ };
1463
1901
  const record = str(f.record);
1464
1902
  const recordFile = record === undefined ? undefined : path.resolve(ctx.cwd, record);
1465
1903
  const prNumber = str(f.pr) ?? str(f.squashOf);
@@ -1469,7 +1907,10 @@ function runGate(ctx) {
1469
1907
  if (prNumber !== undefined) {
1470
1908
  if (!/^[1-9][0-9]*$/.test(prNumber))
1471
1909
  throw new CommandError(EXIT.USAGE, "--pr / --squash-of take a PR number");
1472
- pr = probePr(ctx.cwd, { number: prNumber, state: "open", repo: str(f.repo) });
1910
+ pr =
1911
+ facts !== undefined && validPrFacts(facts.pr)
1912
+ ? { kind: "ok", pr: facts.pr }
1913
+ : probePr(ctx.cwd, { number: prNumber, state: "open", repo: str(f.repo) });
1473
1914
  if (pr.kind === "unavailable") {
1474
1915
  ctx.log(pr.message);
1475
1916
  return EXIT.USE_MCP;
@@ -1491,6 +1932,62 @@ function runGate(ctx) {
1491
1932
  }
1492
1933
  if (head === "")
1493
1934
  throw new CommandError(EXIT.USAGE, "--head needs a non-empty value");
1935
+ const info = pr?.kind === "ok" ? pr.pr : undefined;
1936
+ const repo = str(f.repo) ?? prRepoSlug(info?.url);
1937
+ if (f.wait === true) {
1938
+ // The squash commit's CI runs on the PR's base branch. A wait that runs out is not a verdict:
1939
+ // the gate below still judges what it finds (a run still going is 11, with no row).
1940
+ const waited = await waitFor(ctx.cwd, {
1941
+ head,
1942
+ branch: info?.baseRefName ?? DEV,
1943
+ until: "completed",
1944
+ budgetS: f.budgetS,
1945
+ intervalS: f.intervalS,
1946
+ }, deps(ctx, str(f.repo)));
1947
+ if (waited.code === EXIT.AGENT_WAIT)
1948
+ return EXIT.AGENT_WAIT;
1949
+ if (waited.code === EXIT.NO)
1950
+ ctx.log(`the CI run at ${head} did not finish within the wait`);
1951
+ }
1952
+ const codeHead = str(f.validated) ?? head;
1953
+ let baseEvidence;
1954
+ if (freshBase) {
1955
+ baseEvidence = { devSha: "", comparedHead: codeHead, ancestor: null };
1956
+ if (facts !== undefined) {
1957
+ const base = obj(facts.base);
1958
+ if (base.ref === DEV &&
1959
+ /^[0-9a-f]{40,64}$/i.test(text(base.sha)) &&
1960
+ base.comparedHead === codeHead &&
1961
+ ["ahead", "identical", "behind", "diverged"].includes(text(base.status))) {
1962
+ baseEvidence.devSha = text(base.sha);
1963
+ baseEvidence.ancestor = ["ahead", "identical"].includes(text(base.status));
1964
+ }
1965
+ }
1966
+ else if (repo !== undefined && isForeignRepo(ctx.cwd, repo)) {
1967
+ const dev = gh(["api", `repos/${repo}/commits/dev`, "--jq", ".sha"]);
1968
+ if (dev.ok && /^[0-9a-f]{40,64}$/i.test(dev.stdout.trim())) {
1969
+ baseEvidence.devSha = dev.stdout.trim();
1970
+ const compare = gh([
1971
+ "api",
1972
+ `repos/${repo}/compare/${baseEvidence.devSha}...${codeHead}`,
1973
+ "--jq",
1974
+ ".status",
1975
+ ]);
1976
+ if (compare.ok &&
1977
+ ["ahead", "identical", "behind", "diverged"].includes(compare.stdout.trim()))
1978
+ baseEvidence.ancestor = ["ahead", "identical"].includes(compare.stdout.trim());
1979
+ }
1980
+ }
1981
+ else {
1982
+ const fetched = fetchRemoteRef(ctx.cwd, "origin/dev");
1983
+ if (fetched?.ok) {
1984
+ baseEvidence.devSha = git(ctx.cwd, ["rev-parse", "--verify", "origin/dev^{commit}"]) ?? "";
1985
+ const compared = runTool("git", ["merge-base", "--is-ancestor", baseEvidence.devSha, codeHead], ctx.cwd);
1986
+ if (compared.status === 0 || compared.status === 1)
1987
+ baseEvidence.ancestor = compared.status === 0;
1988
+ }
1989
+ }
1990
+ }
1494
1991
  // The pre-merge snapshot, written BEFORE the gate decides.
1495
1992
  const snapshot = str(f.snapshot);
1496
1993
  if (snapshot !== undefined) {
@@ -1500,7 +1997,11 @@ function runGate(ctx) {
1500
1997
  // A foreign repo's dev and ancestry come from the API: the checkout's origin/dev is another repo's.
1501
1998
  let dev;
1502
1999
  let ancestor;
1503
- if (foreign && repoFlag !== undefined) {
2000
+ if (baseEvidence !== undefined) {
2001
+ dev = baseEvidence.devSha;
2002
+ ancestor = baseEvidence.ancestor === true;
2003
+ }
2004
+ else if (foreign && repoFlag !== undefined) {
1504
2005
  const devRes = gh(["api", `repos/${repoFlag}/commits/dev`, "--jq", ".sha"]);
1505
2006
  dev = devRes.ok ? devRes.stdout.trim() : "";
1506
2007
  const cmp = gh(["api", `repos/${repoFlag}/compare/dev...${head}`, "--jq", ".status"]);
@@ -1533,6 +2034,12 @@ function runGate(ctx) {
1533
2034
  validatedHead: str(f.validated) ?? "",
1534
2035
  devSha: dev,
1535
2036
  ancestor: String(ancestor),
2037
+ ...(baseEvidence === undefined
2038
+ ? {}
2039
+ : {
2040
+ comparedHead: baseEvidence.comparedHead,
2041
+ baseEvidenceAvailable: baseEvidence.ancestor !== null,
2042
+ }),
1536
2043
  capstone,
1537
2044
  mergeable: info?.mergeable ?? "",
1538
2045
  })}\n`);
@@ -1540,9 +2047,20 @@ function runGate(ctx) {
1540
2047
  // A title carrying a skip token would squash into a dev commit CI never runs on.
1541
2048
  const title = pr?.kind === "ok" ? (pr.pr?.title ?? "") : "";
1542
2049
  const titleToken = f.pr !== undefined ? SKIP_CI_TOKEN.exec(title)?.[0] : undefined;
1543
- let r = titleToken !== undefined
2050
+ const baseUnavailable = baseEvidence?.ancestor === null || (freshBase && info?.baseRefName !== DEV);
2051
+ const baseRefused = freshBase && (baseEvidence?.ancestor !== true || baseUnavailable);
2052
+ const safetyReason = baseRefused
2053
+ ? baseUnavailable
2054
+ ? "fresh dev base evidence is unavailable or the PR base is not dev"
2055
+ : `dev base ${baseEvidence?.devSha ?? ""} is absent from validated code head ${codeHead}; integrate dev and revalidate`
2056
+ : `PR title '${title}' contains the CI-suppressing token ${titleToken ?? ""}`;
2057
+ let r = baseRefused || titleToken !== undefined
1544
2058
  ? {
1545
- code: GATE.TITLE_SKIP,
2059
+ code: baseRefused
2060
+ ? baseUnavailable
2061
+ ? GATE.API_ERROR
2062
+ : GATE.STALE_BASE
2063
+ : GATE.TITLE_SKIP,
1546
2064
  passed: false,
1547
2065
  overridden: false,
1548
2066
  head,
@@ -1553,12 +2071,12 @@ function runGate(ctx) {
1553
2071
  conclusion: null,
1554
2072
  capstone: "",
1555
2073
  ciWorkflow: "",
1556
- repo: str(f.repo) ?? null,
2074
+ repo: repo ?? null,
1557
2075
  skippedLanes: [],
1558
2076
  nonBookkeepingPaths: [],
1559
2077
  failedSteps: [],
1560
2078
  regenerable: false,
1561
- reason: `PR title '${title}' contains the CI-suppressing token ${titleToken}`,
2079
+ reason: safetyReason,
1562
2080
  }
1563
2081
  : shipGate({
1564
2082
  root,
@@ -1573,7 +2091,7 @@ function runGate(ctx) {
1573
2091
  override: process.env.BKIT_SHIP_GATE_OVERRIDE || undefined,
1574
2092
  statusFile: f.file === undefined ? undefined : path.resolve(ctx.cwd, String(f.file)),
1575
2093
  }, gh, ctx.log);
1576
- if (titleToken !== undefined)
2094
+ if (baseRefused || titleToken !== undefined)
1577
2095
  ctx.log(r.reason);
1578
2096
  // Debug retains the configured gate above and also proves the original
1579
2097
  // selected workflow at the pushed head. A different workflow need not contain
@@ -1624,13 +2142,16 @@ function runGate(ctx) {
1624
2142
  }
1625
2143
  if (recordFile !== undefined && r.code !== EXIT.USE_MCP) {
1626
2144
  if (f.capstoneOnly === true) {
1627
- const verdict = r.code === EXIT.OK ? "PASS" : "FAIL";
1628
- auditRow(recordFile, "ship-merge-ci", {
1629
- sha: head,
1630
- run: String(r.runId ?? ""),
1631
- verdict,
1632
- reason: verdict === "PASS" ? "" : r.reason,
1633
- });
2145
+ // No run yet (10) and a run still in progress (11) are not verdicts: the row waits for one.
2146
+ if (r.code !== GATE.NO_RUN && r.code !== GATE.IN_PROGRESS) {
2147
+ const verdict = r.code === EXIT.OK ? "PASS" : "FAIL";
2148
+ auditRow(recordFile, "ship-merge-ci", {
2149
+ sha: head,
2150
+ run: String(r.runId ?? ""),
2151
+ verdict,
2152
+ reason: verdict === "PASS" ? "" : r.reason,
2153
+ });
2154
+ }
1634
2155
  }
1635
2156
  else if (r.code !== EXIT.OK) {
1636
2157
  auditRow(recordFile, "ship-gate-refusal", { exitCode: r.code, head: r.mergeHead });
@@ -1680,6 +2201,7 @@ async function runRevalidate(ctx) {
1680
2201
  // CI must pass at the code head while the PR head adds bookkeeping only and dev
1681
2202
  // demands no status checks; otherwise at the PR head.
1682
2203
  let validated = codeHead;
2204
+ let reconcileRequired = current !== codeHead;
1683
2205
  if (foreign) {
1684
2206
  // The bookkeeping diff reads the checkout's git, which is not the named repo's history.
1685
2207
  ctx.log(`--repo ${repoFlag} is not this checkout's repo — bookkeeping diff skipped, validating at the PR head ${current}`);
@@ -1692,15 +2214,31 @@ async function runRevalidate(ctx) {
1692
2214
  from: codeHead,
1693
2215
  to: current,
1694
2216
  });
2217
+ reconcileRequired = !book.ok;
1695
2218
  if (!book.ok)
1696
2219
  validated = current;
1697
2220
  }
2221
+ if (f.requireReconciled === true && reconcileRequired) {
2222
+ auditRow(status, "ship-gate-refusal", { exitCode: 21, head: current });
2223
+ ctx.log(`feature code changed at ${current} — reconcile before CI validation`);
2224
+ ctx.emit({
2225
+ reconcileRequired: true,
2226
+ validatedHead: null,
2227
+ currentHead: current,
2228
+ revalidated: false,
2229
+ probe: null,
2230
+ dispatched: false,
2231
+ wait: null,
2232
+ });
2233
+ return 21;
2234
+ }
1698
2235
  const repo = repoFlag ?? resolveOwnerRepo(ctx.cwd)?.ownerRepo;
1699
2236
  if (repo !== undefined && devRequiresChecks(d.gh, repo)) {
1700
2237
  ctx.log(`dev requires status checks — validating at the PR head ${current}`);
1701
2238
  validated = current;
1702
2239
  }
1703
2240
  const out = {
2241
+ ...(f.requireReconciled === true ? { reconcileRequired: false } : {}),
1704
2242
  validatedHead: validated,
1705
2243
  currentHead: current,
1706
2244
  revalidated: false,
@@ -1771,7 +2309,7 @@ const PHASES = {
1771
2309
  export const EXIT_UNKNOWN_PHASE = 3;
1772
2310
  /** Exit code (context): the CI PR is not OPEN. */
1773
2311
  export const EXIT_PR_NOT_OPEN = 7;
1774
- /** Exit code (context): no CI run at the PR head. */
2312
+ /** Exit code (context): no matching CI run at the PR head (the test workflow's newest run, or its newest failed run for debug). */
1775
2313
  export const EXIT_NO_RUN_ID = 8;
1776
2314
  /** Exit code (context): no FID from the marker, the branch, or the slug. */
1777
2315
  export const EXIT_NO_FID = 9;
@@ -1856,22 +2394,29 @@ async function runContext(ctx) {
1856
2394
  ctx.emit(out);
1857
2395
  return EXIT_PR_NOT_OPEN;
1858
2396
  }
2397
+ const testWorkflow = ciDeclared(checkoutRoot(ctx.cwd));
2398
+ const wantsFailed = chosen.phase === "debug";
1859
2399
  const runs = runGh(ctx.cwd, [
1860
2400
  "run",
1861
2401
  "list",
1862
2402
  "--branch",
1863
2403
  branch,
2404
+ ...(testWorkflow.declared ? ["--workflow", testWorkflow.ciWorkflow] : []),
2405
+ "--commit",
2406
+ headSha,
1864
2407
  "--limit",
1865
2408
  "5",
1866
2409
  "--json",
1867
- "databaseId,headSha",
2410
+ "databaseId,headSha,status,conclusion",
1868
2411
  ]);
1869
2412
  const run = arr(runs.ok ? jsonOrUndefined(runs.stdout) : undefined)
1870
2413
  .map(obj)
1871
- .find((r) => r.headSha === headSha);
2414
+ .find((r) => r.headSha === headSha &&
2415
+ (!wantsFailed ||
2416
+ (r.status === "completed" && FAILED_CONCLUSIONS.includes(text(r.conclusion)))));
1872
2417
  out.runId = run?.databaseId === undefined ? null : String(run.databaseId);
1873
2418
  if (out.runId === null) {
1874
- ctx.log(`no CI run at ${headSha} on ${branch}`);
2419
+ ctx.log(`no ${wantsFailed ? "failed " : ""}CI run of ${testWorkflow.declared ? testWorkflow.ciWorkflow : "any workflow"} at ${headSha} on ${branch}`);
1875
2420
  ctx.emit(out);
1876
2421
  return EXIT_NO_RUN_ID;
1877
2422
  }
@@ -2038,10 +2583,46 @@ export const runsCommand = {
2038
2583
  exitCodes: { [EXIT_TRIGGER_FAILED]: "--dispatch-if-absent: gh workflow run failed" },
2039
2584
  run: runWait,
2040
2585
  },
2586
+ handoff: {
2587
+ summary: "Persist one batch of CI poll observations into the invocation's run and derive the phase, cumulative attempts and errors, next action and verdict from the persisted rows (poll-again | retrigger | reconcile-retrigger | verdict). Rows for another repo, PR or head never count.",
2588
+ use: "workflow",
2589
+ flags: [
2590
+ INVOCATION_FLAG,
2591
+ { name: "repo", type: "string", required: true, help: "owner/repo of the PR" },
2592
+ {
2593
+ name: "pr",
2594
+ type: "string",
2595
+ help: "PR number; empty for a run in place on a shared branch (no PR)",
2596
+ },
2597
+ { name: "head", type: "string", required: true, help: "full commit sha the polls ran at" },
2598
+ { name: "branch", type: "string", required: true, help: "branch the PR is on" },
2599
+ BUDGET_FLAG,
2600
+ INTERVAL_FLAG,
2601
+ {
2602
+ name: "result",
2603
+ type: "string",
2604
+ required: true,
2605
+ help: "what the polls saw: none | pending | success | failure | provider-error",
2606
+ },
2607
+ { name: "polls", type: "string", required: true, help: "polls this batch ran (>= 1)" },
2608
+ ],
2609
+ output: {
2610
+ phase: "poll | repoll (repoll once the re-trigger is receipt-completed)",
2611
+ attempts: "cumulative polls for this target",
2612
+ errors: "cumulative provider-error polls for this target",
2613
+ nextAction: "poll-again | retrigger | reconcile-retrigger | verdict",
2614
+ outcome: "dispatched | self-healed | no-ci | unresolved (nextAction verdict only)",
2615
+ reason: "unresolved reason: gh-error | timeout-dirty | retrigger-suppressed | ci-declared-no-run (the same decision `runs dispatch` makes)",
2616
+ ciResult: "the result this batch recorded",
2617
+ stale: "persisted rows for another repo, PR, head or branch, not counted",
2618
+ },
2619
+ run: runHandoff,
2620
+ },
2041
2621
  dispatch: {
2042
- summary: "CI-Dispatch Gate after the last push: poll, one clean re-trigger, the ciDispatch verdict, and the body scan. A run in place on dev has no PR: it polls the push-event run at the pushed sha, and its re-trigger commits and pushes only the run's own work.",
2622
+ summary: "CI-Dispatch Gate after the last push: poll, one clean re-trigger, the ciDispatch verdict, and the body scan. A run in place on dev has no PR: it polls the push-event run at the pushed sha, and its re-trigger commits and pushes only the run's own work. It needs a workflow run's --invocation and resumes from the rows that run persisted (its own polls and `runs handoff` turns): attempts, errors and the re-trigger checkpoint are never supplied.",
2043
2623
  use: "workflow",
2044
2624
  flags: [
2625
+ INVOCATION_FLAG,
2045
2626
  {
2046
2627
  name: "pr",
2047
2628
  type: "string",
@@ -2085,22 +2666,6 @@ export const runsCommand = {
2085
2666
  },
2086
2667
  { ...BUDGET_FLAG, help: "poll budget in seconds (default 60)" },
2087
2668
  { ...INTERVAL_FLAG, help: "seconds between polls (default 10)" },
2088
- {
2089
- name: "poll-result",
2090
- type: "string",
2091
- help: "re-entry after a hand-off: found | none | err, as the agent turn loop resolved it",
2092
- },
2093
- {
2094
- name: "attempts",
2095
- type: "string",
2096
- help: "re-entry: total poll attempts so far (hand-off attempts + turns)",
2097
- },
2098
- { name: "all-errored", type: "boolean", help: "re-entry: every turn-loop poll errored" },
2099
- {
2100
- name: "retriggered",
2101
- type: "boolean",
2102
- help: "re-entry: the hand-off was in the re-poll (re-trigger already pushed)",
2103
- },
2104
2669
  ],
2105
2670
  output: {
2106
2671
  ciDispatch: "{outcome, head, attempts, retrigger, reason?} — record with `bkit steps done --field ciDispatch=…` (local only, never pushed); null on a hand-off",
@@ -2131,6 +2696,16 @@ export const runsCommand = {
2131
2696
  type: "string",
2132
2697
  help: "validated original debug selection: additionally require its workflow to succeed at the exact pushed head",
2133
2698
  },
2699
+ {
2700
+ name: "fresh-base",
2701
+ type: "boolean",
2702
+ help: "ship pre-merge: require fresh dev ancestry in the validated code head; CI overrides cannot waive it",
2703
+ },
2704
+ {
2705
+ name: "facts-file",
2706
+ type: "string",
2707
+ help: "with --fresh-base: scoped independently read PR, CI and dev comparison facts, without gh calls",
2708
+ },
2134
2709
  { ...HEAD_FLAG, help: "the PR head to merge (or --pr / --squash-of)" },
2135
2710
  {
2136
2711
  name: "pr",
@@ -2150,7 +2725,7 @@ export const runsCommand = {
2150
2725
  {
2151
2726
  name: "record",
2152
2727
  type: "string",
2153
- help: "status.jsonl: append ship-gate-refusal on a refusal, or ship-merge-ci with --capstone-only",
2728
+ help: "status.jsonl: append ship-gate-refusal on a refusal, or ship-merge-ci with --capstone-only once CI has a verdict (no row on exit 10 or 11)",
2154
2729
  },
2155
2730
  {
2156
2731
  name: "validated",
@@ -2185,6 +2760,13 @@ export const runsCommand = {
2185
2760
  type: "boolean",
2186
2761
  help: "pass or fail on the capstone job's result alone; the run's conclusion, other jobs and required lanes do not count (ship post-merge)",
2187
2762
  },
2763
+ {
2764
+ name: "wait",
2765
+ type: "boolean",
2766
+ help: "with --squash-of: first wait until the CI run at the squash commit on the PR's base branch has finished, then gate it (a run still going when the wait runs out is exit 11)",
2767
+ },
2768
+ { ...BUDGET_FLAG, help: "with --wait: the wait budget in seconds" },
2769
+ { ...INTERVAL_FLAG, help: "with --wait: seconds between polls (>= 1)" },
2188
2770
  ],
2189
2771
  output: {
2190
2772
  code: "the exit code",
@@ -2217,6 +2799,7 @@ export const runsCommand = {
2217
2799
  [GATE.LANE_SKIPPED]: "a required lane concluded skipped",
2218
2800
  [GATE.NOT_BOOKKEEPING]: "non-bookkeeping change past --validated, or not its descendant",
2219
2801
  [GATE.TITLE_SKIP]: "--pr: the PR title carries a CI-suppressing token",
2802
+ [GATE.STALE_BASE]: "fresh dev is absent from the validated code head; integrate and revalidate",
2220
2803
  [GATE.API_ERROR]: "API error / rate limit / auth, or the PR head / squash commit unreadable",
2221
2804
  },
2222
2805
  run: runGate,
@@ -2225,6 +2808,11 @@ export const runsCommand = {
2225
2808
  summary: "Ship: pick the head CI must pass at, probe for a run there, dispatch only when none, wait for it to complete.",
2226
2809
  use: "workflow",
2227
2810
  flags: [
2811
+ {
2812
+ name: "require-reconciled",
2813
+ type: "boolean",
2814
+ help: "refuse newly observed feature code before CI validation",
2815
+ },
2228
2816
  { name: "pr", type: "string", required: true, help: "the PR number" },
2229
2817
  { name: "entry-head", type: "string", required: true, help: "the PR head read at Step 2" },
2230
2818
  {
@@ -2261,13 +2849,17 @@ export const runsCommand = {
2261
2849
  ],
2262
2850
  output: {
2263
2851
  validatedHead: "the head CI was (or must be) checked at",
2852
+ reconcileRequired: "with --require-reconciled, whether new feature code needs reconciliation",
2264
2853
  currentHead: "the PR head now",
2265
2854
  revalidated: "a probe / wait ran (the head moved, or a gate refusal re-entered)",
2266
2855
  probe: "the presence probe's wait result, or null",
2267
2856
  dispatched: "the probe found no run and dispatched one",
2268
2857
  wait: "the completion wait's result, or null",
2269
2858
  },
2270
- exitCodes: { [EXIT_TRIGGER_FAILED]: "no run and gh workflow run failed" },
2859
+ exitCodes: {
2860
+ [EXIT_TRIGGER_FAILED]: "no run and gh workflow run failed",
2861
+ 21: "--require-reconciled: new feature code needs reconciliation",
2862
+ },
2271
2863
  run: runRevalidate,
2272
2864
  },
2273
2865
  mirror: {
@@ -2342,12 +2934,12 @@ export const runsCommand = {
2342
2934
  headSha: "the PR head (CI) or origin/dev (CI_DEV), else null",
2343
2935
  prUrl: "the PR URL (CI), else null",
2344
2936
  prState: "the PR state (CI), else null",
2345
- runId: "the CI run at the PR head (CI), else null",
2937
+ runId: "the CI run at the PR head (CI), else null: the newest run of the test workflow for ship, the newest failed run of it for debug",
2346
2938
  },
2347
2939
  exitCodes: {
2348
2940
  [EXIT_UNKNOWN_PHASE]: "the phase word is not one bkit dispatches",
2349
2941
  [EXIT_PR_NOT_OPEN]: "the PR is not OPEN",
2350
- [EXIT_NO_RUN_ID]: "no CI run at the PR head",
2942
+ [EXIT_NO_RUN_ID]: "no CI run at the PR head: no run of the test workflow (any workflow when none is declared), and for debug no failed one (failure, timed_out or startup_failure)",
2351
2943
  [EXIT_NO_FID]: "no valid FID or no issue (CI_DEV slug off the allowlist, no marker / feat/{FID} branch, or an issue-less FID: /bkit-auto runs issue-only)",
2352
2944
  },
2353
2945
  run: runContext,