@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
@@ -25,10 +25,18 @@ import * as path from "node:path";
25
25
  import { readJsonFile } from "../../shared/json.js";
26
26
 
27
27
  import {
28
+ appendLine,
29
+ CI_HANDOFF_RESULTS,
28
30
  CI_TIERS,
31
+ foldCiHandoff,
29
32
  lastRun,
30
33
  statusTimestamp,
34
+ validateCiHandoffEvent,
31
35
  validateCiSelection,
36
+ type CiHandoffResult,
37
+ type CiHandoffRetrigger,
38
+ type CiHandoffState,
39
+ type CiHandoffTarget,
32
40
  type CiSelection,
33
41
  type CiTier,
34
42
  } from "../../ledgers/status.js";
@@ -39,6 +47,7 @@ import {
39
47
  DEV,
40
48
  EXIT,
41
49
  git,
50
+ INVOCATION_FLAG,
42
51
  isSharedBranch,
43
52
  parseJson,
44
53
  runGh,
@@ -58,18 +67,27 @@ import { FID_PATTERNS, fromBranch, fromMarker, issueIdOf, readIssueTracker } fro
58
67
  import type { IssueTracker } from "../../install/manifest.js";
59
68
  import { AUTO_LABEL, AUTO_ROUTE_SUFFIX } from "./issues.js";
60
69
  import { fetchRemoteRef, pushBranch } from "./branches.js";
61
- import { activeRecord, checkOnlyBookkeeping, retriggerCommit } from "./ledgers.js";
70
+ import {
71
+ activeRecord,
72
+ appendRecordCommit,
73
+ checkOnlyBookkeeping,
74
+ commitOwnSet,
75
+ markRecordPushed,
76
+ readRecord,
77
+ retriggerCommit,
78
+ } from "./ledgers.js";
62
79
  import {
63
80
  closeTransportRow,
64
81
  crossCheckFile,
65
82
  devRequiresChecks,
66
83
  prRepoSlug,
67
84
  probePr,
85
+ validPrFacts,
68
86
  type PrInfo,
69
87
  } from "./prs.js";
70
- import { resolveOwnerRepo, splitSlug } from "./repo.js";
88
+ import { originOwnerRepo, resolveOwnerRepo, splitSlug } from "./repo.js";
71
89
  import { restateOutcome } from "./run-facts.js";
72
- import { extraField, readRuns, str } from "./status.js";
90
+ import { extraField, readRuns, readStatusRows, str } from "./status.js";
73
91
  import { writeStepRow } from "./steps.js";
74
92
  import { attempt, issueRef, readLabels, trackerTarget } from "./tracker.js";
75
93
 
@@ -108,6 +126,9 @@ export function checkNamespace(capstoneJob: string): string {
108
126
  return i > 0 ? capstoneJob.slice(0, i) : capstoneJob;
109
127
  }
110
128
 
129
+ /** The conclusions of a finished run or job that count as a failure. */
130
+ const FAILED_CONCLUSIONS = ["failure", "timed_out", "startup_failure"];
131
+
111
132
  /** Whether `.github/workflows/<bkit.testing.ciWorkflow>` exists — the only honest ground for a `no-ci` pass. */
112
133
  export function ciDeclared(root: string): { declared: boolean; ciWorkflow: string; path: string } {
113
134
  const { ciWorkflow } = readBkitConfig(root);
@@ -120,7 +141,7 @@ type CiReference = { kind: "run" | "pr"; repo: string; id: string; attempt?: num
120
141
  /** Only the winning reference kind is actionable; a run takes precedence over a PR. */
121
142
  export function parseCiReference(input: string): CiReference | undefined {
122
143
  const references: CiReference[] = [];
123
- const urls = [...input.matchAll(/https:\/\/github\.com\/[^\s<>"`]+/g)].map((match) =>
144
+ const urls = [...input.matchAll(/https:\/\/github\.com\/[^\s<>"`\[\]()]+/g)].map((match) =>
124
145
  match[0].replace(/[),.;\]]+$/, ""),
125
146
  );
126
147
  const parsed = urls.flatMap((url) => {
@@ -399,10 +420,7 @@ function locateCi(ctx: RunContext): number {
399
420
  throw new CommandError(82, "PR lookup returned a run from another head");
400
421
  }
401
422
  validateRun(run);
402
- if (
403
- run.status !== "completed" ||
404
- !["failure", "timed_out", "startup_failure"].includes(text(run.conclusion))
405
- ) {
423
+ if (run.status !== "completed" || !FAILED_CONCLUSIONS.includes(text(run.conclusion))) {
406
424
  if (reference)
407
425
  throw new CommandError(
408
426
  82,
@@ -468,15 +486,13 @@ function locateCi(ctx: RunContext): number {
468
486
  text(obj(run.head_repository).full_name).toLowerCase() !== repo.toLowerCase()
469
487
  )
470
488
  throw new CommandError(82, "run attempt, repository or fork identity does not match");
471
- const failedJobs = jobs.filter((job) =>
472
- ["failure", "timed_out", "startup_failure"].includes(text(job.conclusion)),
489
+ const failedJobs = jobs.filter((job) => FAILED_CONCLUSIONS.includes(text(job.conclusion)));
490
+ const failedNames = failedJobs
491
+ .map((job) => text(job.name))
492
+ .filter((name) => name !== "bkit-tests-check");
493
+ const mapped = failedNames.map(
494
+ (name) => /^bkit-tests-(static|unit|integration|e2e|live|migration)$/.exec(name)?.[1],
473
495
  );
474
- const mapped = failedJobs
475
- .filter((job) => job.name !== "bkit-tests-check")
476
- .map(
477
- (job) =>
478
- /^bkit-tests-(static|unit|integration|e2e|live|migration)$/.exec(text(job.name))?.[1],
479
- );
480
496
  const tiers: CiTier[] = mapped.some((tier) => tier === undefined)
481
497
  ? []
482
498
  : CI_TIERS.filter((tier) => mapped.includes(tier));
@@ -493,6 +509,12 @@ function locateCi(ctx: RunContext): number {
493
509
  headSha: text(run.head_sha),
494
510
  conclusion: text(run.conclusion) as Extract<CiSelection, { mode: "ci" }>["conclusion"],
495
511
  redTiers: tiers,
512
+ ...(failedJobs.length > 0
513
+ ? {
514
+ failedJobCount: Math.max(1, mapped.length),
515
+ failedJobs: [...new Set(failedNames)].sort(),
516
+ }
517
+ : {}),
496
518
  via,
497
519
  };
498
520
  if (
@@ -683,10 +705,47 @@ export interface CiDispatch {
683
705
  reason?: DispatchReason;
684
706
  }
685
707
 
686
- export interface SuppliedPoll {
687
- pollResult: "found" | "none" | "err";
708
+ /** What one poll phase saw, in that phase's own counts. */
709
+ export interface DispatchFacts {
710
+ /** `poll` before the re-trigger, `repoll` after its receipt. */
711
+ phase: "poll" | "repoll";
712
+ /** A check or run exists at the head. */
713
+ found: boolean;
688
714
  attempts: number;
689
- allErrored: boolean;
715
+ errors: number;
716
+ /** How many polls the phase may spend before it decides on silence. */
717
+ budget: number;
718
+ /** The head that was polled carries a CI suppressor (`poll`: the pushed head; `repoll`: the re-trigger commit). */
719
+ headSuppressed: boolean;
720
+ /** The repo declares a CI workflow file. */
721
+ ciDeclared: boolean;
722
+ }
723
+
724
+ export type DispatchDecision =
725
+ | { next: "verdict"; outcome: DispatchOutcome; reason?: DispatchReason }
726
+ | { next: "poll-again" }
727
+ | { next: "retrigger" };
728
+
729
+ /**
730
+ * The one CI-Dispatch decision: the gate and `runs handoff` both call it, so a turn loop and an
731
+ * in-process poll reach the same verdict on the same evidence. Zero polls (no PR to read) count
732
+ * as every poll errored.
733
+ */
734
+ export function decideDispatch(f: DispatchFacts): DispatchDecision {
735
+ const unresolved = (reason: DispatchReason): DispatchDecision => ({
736
+ next: "verdict",
737
+ outcome: "unresolved",
738
+ reason,
739
+ });
740
+ if (!f.found && f.attempts < f.budget) return { next: "poll-again" };
741
+ // A run found on a suppressed re-trigger head cannot tell CI from suppression.
742
+ if (f.phase === "repoll" && f.headSuppressed) return unresolved("retrigger-suppressed");
743
+ if (f.found)
744
+ return { next: "verdict", outcome: f.phase === "repoll" ? "self-healed" : "dispatched" };
745
+ if (f.errors === f.attempts) return unresolved("gh-error");
746
+ if (f.phase === "poll")
747
+ return f.headSuppressed ? unresolved("timeout-dirty") : { next: "retrigger" };
748
+ return f.ciDeclared ? unresolved("ci-declared-no-run") : { next: "verdict", outcome: "no-ci" };
690
749
  }
691
750
 
692
751
  export interface DispatchOptions {
@@ -696,15 +755,25 @@ export interface DispatchOptions {
696
755
  autoRouteSuffix: string;
697
756
  budgetS: number;
698
757
  intervalS: number;
699
- /** The poll result an agent turn loop resolved after a hand-off. */
700
- supplied?: SuppliedPoll;
701
- /** The re-trigger commit is already pushed (re-entry after a hand-off in the re-poll). */
702
- retriggered: boolean;
703
758
  /**
704
759
  * The sha the run's last push landed on a shared branch, for a run with no PR.
705
760
  * An own-commit push lands copies, so it is not necessarily local HEAD.
706
761
  */
707
762
  sha?: string;
763
+ /**
764
+ * Durable continuation: every poll observation and re-trigger checkpoint is appended to
765
+ * `statusPath` as a `ci-handoff` row, and a fresh call with the same path resumes from them.
766
+ */
767
+ handoff: HandoffOptions;
768
+ }
769
+
770
+ export interface HandoffOptions {
771
+ statusPath: string;
772
+ /** The receipt written once the re-trigger is complete. */
773
+ operation: string;
774
+ workflow?: string;
775
+ /** Called after each re-trigger checkpoint is durable. */
776
+ checkpoint?: (name: "commit-created" | "push-completed" | "receipt-completed") => void;
708
777
  }
709
778
 
710
779
  export interface DispatchResult {
@@ -736,6 +805,107 @@ function pushCurrentBranch(cwd: string): { ok: boolean; error: string } {
736
805
  return { ok: res.ok, error: res.ok ? "" : res.stderr || res.stdout };
737
806
  }
738
807
 
808
+ /**
809
+ * Land a shared-branch run's own commits when every one of them changes nothing (a re-trigger and
810
+ * an empty close): each is copied onto the remote tip with that tip's own tree and pushed as a
811
+ * fast-forward. The tree is one the remote already holds, so there is nothing for a landing gate
812
+ * to validate, and no foreign local commit rides along. `not-empty` hands the push to
813
+ * `pushBranch`, whose landing gate covers content.
814
+ */
815
+ function landEmptyOwnCommits(
816
+ cwd: string,
817
+ fid: string,
818
+ branch: string,
819
+ log: (m: string) => void,
820
+ /** Called with the copy's SHA before it is pushed, so a lost push response is recoverable. */
821
+ onCopy?: (sha: string) => void,
822
+ ): { kind: "landed"; sha: string } | { kind: "not-empty" } | { kind: "failed" } {
823
+ const rec = readRecord(cwd, fid);
824
+ if (rec === null || !runGit(cwd, ["fetch", "origin", branch]).ok) return { kind: "failed" };
825
+ const tip = git(cwd, ["rev-parse", "-q", "--verify", `origin/${branch}`]);
826
+ const tipTree = tip === null ? null : git(cwd, ["rev-parse", `${tip}^{tree}`]);
827
+ if (tip === null || tipTree === null) return { kind: "failed" };
828
+ const landed = new Set(rec.pushed ?? []);
829
+ const pending = rec.commits.filter(
830
+ (c) => !landed.has(c) && !runGit(cwd, ["merge-base", "--is-ancestor", c, tip]).ok,
831
+ );
832
+ // Every run commit is already on the remote, or was pushed as a copy with a SHA of its own:
833
+ // the remote tip is what holds them, never a recorded local original.
834
+ if (pending.length === 0) return { kind: "landed", sha: tip };
835
+ const empty = (c: string) => {
836
+ const tree = git(cwd, ["rev-parse", `${c}^{tree}`]);
837
+ return tree !== null && tree === git(cwd, ["rev-parse", `${c}^^{tree}`]);
838
+ };
839
+ if (!pending.every(empty)) return { kind: "not-empty" };
840
+ let parent = tip;
841
+ for (const c of pending) {
842
+ const made = runGit(cwd, [
843
+ "commit-tree",
844
+ tipTree,
845
+ "-p",
846
+ parent,
847
+ "-m",
848
+ git(cwd, ["log", "-1", "--format=%B", c]) ?? "",
849
+ ]);
850
+ if (!made.ok) return { kind: "failed" };
851
+ parent = made.stdout;
852
+ }
853
+ onCopy?.(parent);
854
+ const pushed = runGit(cwd, ["push", "origin", `${parent}:refs/heads/${branch}`]);
855
+ if (!pushed.ok) {
856
+ log(`pushing the run's empty commits to ${branch} failed: ${pushed.stderr}`);
857
+ return { kind: "failed" };
858
+ }
859
+ markRecordPushed(cwd, fid, pending);
860
+ log(
861
+ `landed ${pending.length} empty commit(s) of the run on ${branch} as copies (${parent.slice(0, 12)})`,
862
+ );
863
+ return { kind: "landed", sha: parent };
864
+ }
865
+
866
+ /** The persisted `ci-handoff` rows of a status file (none when the file does not exist yet). */
867
+ function handoffRowsOf(statusPath: string): object[] {
868
+ return fs.existsSync(statusPath) ? readStatusRows(statusPath) : [];
869
+ }
870
+
871
+ /** The tip of `branch` on origin: its sha, "" when the branch is absent there, null when the lookup failed. */
872
+ function remoteTip(cwd: string, branch: string): string | null {
873
+ const res = runGit(cwd, ["ls-remote", "origin", `refs/heads/${branch}`]);
874
+ if (!res.ok) return null;
875
+ return res.stdout.split(/\s+/)[0] ?? "";
876
+ }
877
+
878
+ /**
879
+ * The head a target is persisted under. Rows written before a re-trigger carry the head the
880
+ * re-trigger started from, so a process that finds HEAD on the re-trigger commit resumes them.
881
+ */
882
+ function resolveHandoffHead(
883
+ rows: object[],
884
+ identity: Omit<CiHandoffTarget, "head">,
885
+ cwd: string,
886
+ current: string,
887
+ ): string {
888
+ const mine = rows
889
+ .filter(validateCiHandoffEvent)
890
+ .filter(
891
+ (e) =>
892
+ e.target.repo.toLowerCase() === identity.repo.toLowerCase() &&
893
+ e.target.pr === identity.pr &&
894
+ e.target.branch === identity.branch,
895
+ );
896
+ const latest = mine.at(-1);
897
+ if (latest === undefined || latest.target.head === current) return current;
898
+ const rt = latest.retrigger;
899
+ if (rt?.commit === current || rt?.remote === current) return latest.target.head;
900
+ if (
901
+ rt?.state === "intended" &&
902
+ git(cwd, ["rev-parse", "HEAD^"]) === rt.original &&
903
+ /re-trigger/.test(commitMessage(cwd, current) ?? "")
904
+ )
905
+ return latest.target.head;
906
+ return current;
907
+ }
908
+
739
909
  /**
740
910
  * The CI-Dispatch Gate after build / debug's last push. Never pushes after the
741
911
  * verdict: a later commit would move the PR head away from the run it proved.
@@ -766,7 +936,7 @@ export async function ciDispatchGate(
766
936
  ciDispatch: null,
767
937
  head: head(),
768
938
  attempts: 0,
769
- retrigger: o.retriggered,
939
+ retrigger: false,
770
940
  ciWorkflow: declared.ciWorkflow,
771
941
  runBranch: byRun ? branch : null,
772
942
  };
@@ -784,35 +954,95 @@ export async function ciDispatchGate(
784
954
  ciWorkflow: declared.ciWorkflow,
785
955
  namespace: checkNamespace(capstoneJob),
786
956
  };
787
- const poll = async (phase: "poll" | "repoll"): Promise<SuppliedPoll | null> => {
788
- // A supplied result answers only the poll that was handed off; later polls run fresh.
789
- if (o.supplied && (phase === "repoll") === o.retriggered) {
790
- deps.log(
791
- `poll result supplied by the agent turn loop: ${o.supplied.pollResult} (attempts ${o.supplied.attempts})`,
792
- );
793
- return o.supplied;
794
- }
795
- // No PR to read is the shell's empty-PR poll: zero attempts, all errored.
796
- if (o.pr === null && !byRun) return { pollResult: "err", attempts: 0, allErrored: true };
957
+ // Durable continuation: the persisted state of this target, and the totals kept in step with it.
958
+ const hand = o.handoff;
959
+ const rowsAtStart = handoffRowsOf(hand.statusPath);
960
+ const identity = {
961
+ provider: "github" as const,
962
+ repo: originOwnerRepo(o.cwd) ?? "local/origin",
963
+ pr: o.pr,
964
+ branch: branch || "HEAD",
965
+ };
966
+ const ht: CiHandoffTarget = {
967
+ ...identity,
968
+ head: resolveHandoffHead(rowsAtStart, identity, o.cwd, res.head),
969
+ };
970
+ const hs: CiHandoffState = foldCiHandoff(rowsAtStart, ht);
971
+ let cumAttempts = hs.attempts;
972
+ let cumErrors = hs.errors;
973
+ let curRt: CiHandoffRetrigger | null = hs.retrigger;
974
+ const repollBase = hs.retriggerBase;
975
+ let lastResult: CiHandoffResult = hs.last?.result ?? "none";
976
+ res.attempts = hs.attempts;
977
+ const persist = (phase: "poll" | "repoll", result: CiHandoffResult) => {
978
+ lastResult = result;
979
+ fs.appendFileSync(
980
+ hand.statusPath,
981
+ appendLine({
982
+ type: "ci-handoff",
983
+ workflow: hand.workflow ?? "build",
984
+ at: statusTimestamp(),
985
+ phase,
986
+ target: ht,
987
+ observation: { result, attempts: cumAttempts, errors: cumErrors },
988
+ ...(curRt === null ? {} : { retrigger: curRt }),
989
+ }),
990
+ );
991
+ };
992
+ const pollBudget = Math.max(1, Math.ceil(o.budgetS / o.intervalS));
993
+ /** One phase's poll, resumed from the persisted rows: what it saw, in the phase's own counts. */
994
+ const poll = async (
995
+ phase: "poll" | "repoll",
996
+ ): Promise<{ found: boolean; attempts: number; errors: number; budget: number } | null> => {
997
+ // No PR to read is the shell's empty-PR poll: zero attempts, all errored, nothing to spend.
998
+ if (o.pr === null && !byRun) return { found: false, attempts: 0, errors: 0, budget: 0 };
797
999
  if (byRun) target.head = head();
1000
+ // The first phase ends where the re-trigger began; the re-poll counts from there.
1001
+ const baseA = phase === "repoll" ? (repollBase?.attempts ?? cumAttempts) : 0;
1002
+ const baseE = phase === "repoll" ? (repollBase?.errors ?? cumErrors) : 0;
1003
+ const endA = phase === "poll" && repollBase ? repollBase.attempts : cumAttempts;
1004
+ const endE = phase === "poll" && repollBase ? repollBase.errors : cumErrors;
1005
+ const seen = (found: boolean, a: number, e: number) => ({
1006
+ found,
1007
+ attempts: a - baseA,
1008
+ errors: e - baseE,
1009
+ budget: pollBudget,
1010
+ });
1011
+ const foundBefore =
1012
+ hs.last !== null &&
1013
+ ["pending", "success", "failure"].includes(hs.last.result) &&
1014
+ hs.phase === phase;
1015
+ if (foundBefore && endA === cumAttempts) return seen(true, cumAttempts, cumErrors);
1016
+ const remaining = pollBudget - (endA - baseA);
1017
+ if (remaining <= 0) return seen(false, endA, endE);
1018
+ let errs = 0;
798
1019
  deps.log(
799
1020
  byRun
800
- ? `polling for a ${target.ciWorkflow} run on ${branch} at ${target.head} (budget ${o.budgetS}s, interval ${o.intervalS}s)`
801
- : `polling for a ${target.namespace} check on PR #${o.pr} (budget ${o.budgetS}s, interval ${o.intervalS}s)`,
1021
+ ? `polling for a ${target.ciWorkflow} run on ${branch} at ${target.head} (${remaining} attempt(s) left, interval ${o.intervalS}s)`
1022
+ : `polling for a ${target.namespace} check on PR #${o.pr} (${remaining} attempt(s) left, interval ${o.intervalS}s)`,
802
1023
  );
803
1024
  const w = await waitLoop(
804
- { budgetS: o.budgetS, intervalS: o.intervalS, once: false },
805
- () => pollOnce(target, deps.gh),
1025
+ { budgetS: remaining * o.intervalS, intervalS: o.intervalS, once: false },
1026
+ () => {
1027
+ const p = pollOnce(target, deps.gh);
1028
+ if (p.state === "err") errs += 1;
1029
+ return p;
1030
+ },
806
1031
  deps.sleep,
807
1032
  deps.log,
808
1033
  );
1034
+ cumAttempts += w.attempts;
1035
+ cumErrors += errs;
1036
+ res.attempts = cumAttempts;
1037
+ const phaseAttempts = cumAttempts - baseA;
1038
+ const allErrored = phaseAttempts > 0 && cumErrors - baseE === phaseAttempts;
1039
+ persist(phase, w.result === "found" ? "pending" : allErrored ? "provider-error" : "none");
809
1040
  if (w.blocked || w.ghMissing) {
810
1041
  res.phase = phase;
811
1042
  res.handoff = w.ghMissing ? EXIT.USE_MCP : EXIT.AGENT_WAIT;
812
- res.attempts += w.attempts;
813
1043
  return null;
814
1044
  }
815
- return { pollResult: w.result, attempts: w.attempts, allErrored: w.allErrored };
1045
+ return seen(w.result === "found", cumAttempts, cumErrors);
816
1046
  };
817
1047
  const verdict = (outcome: DispatchOutcome, reason?: DispatchReason): DispatchResult => {
818
1048
  res.ciDispatch = {
@@ -828,21 +1058,159 @@ export async function ciDispatchGate(
828
1058
  return res;
829
1059
  };
830
1060
 
831
- if (!o.retriggered) {
832
- const first = await poll("poll");
833
- if (first === null) return res;
834
- res.attempts = first.attempts;
835
- if (first.pollResult === "found") return verdict("dispatched");
836
- if (first.allErrored) {
837
- deps.log("unresolved(gh-error): every poll errored — gh unavailable or unauthenticated");
838
- return verdict("unresolved", "gh-error");
1061
+ /**
1062
+ * The re-trigger as persisted checkpoints: intended -> commit-created -> push-completed ->
1063
+ * receipt-completed. A fresh process continues from the last one; no effect repeats.
1064
+ */
1065
+ const handoffRetrigger = async (
1066
+ message: string,
1067
+ rec: ReturnType<typeof activeRecord>,
1068
+ ): Promise<boolean> => {
1069
+ const refName = `refs/heads/${branch}`;
1070
+ let cur: CiHandoffRetrigger = curRt ?? { state: "intended", original: head() };
1071
+ if (curRt === null) {
1072
+ curRt = cur;
1073
+ persist("poll", lastResult);
839
1074
  }
840
- if (SKIP_CI_TOKEN.test(commitMessage(o.cwd, res.head) ?? "")) {
841
- deps.log(
842
- "unresolved(timeout-dirty): no run and the pushed head carries a CI suppressor — not re-triggering a dirty head",
843
- );
844
- return verdict("unresolved", "timeout-dirty");
1075
+ if (cur.state === "intended") {
1076
+ const parent = git(o.cwd, ["rev-parse", "HEAD^"]);
1077
+ const adopted =
1078
+ git(o.cwd, ["rev-parse", "HEAD"]) !== cur.original &&
1079
+ parent === cur.original &&
1080
+ /re-trigger/.test(commitMessage(o.cwd, "HEAD") ?? "");
1081
+ let sha: string | null;
1082
+ if (adopted) {
1083
+ sha = git(o.cwd, ["rev-parse", "HEAD"]);
1084
+ if (rec !== null && sha !== null && !readRecord(o.cwd, o.fid)?.commits.includes(sha))
1085
+ appendRecordCommit(o.cwd, o.fid, sha);
1086
+ } else {
1087
+ const made =
1088
+ rec === null
1089
+ ? commitOwnSet(o.cwd, { plain: [], ledgers: [] }, message, { allowEmpty: true })
1090
+ : retriggerCommit(o.cwd, rec, message);
1091
+ if (!made.ok) deps.log(`re-trigger commit failed: ${made.error}`);
1092
+ sha = made.ok ? made.sha : null;
1093
+ }
1094
+ if (sha === null) return false;
1095
+ cur = { state: "commit-created", original: cur.original, commit: sha };
1096
+ curRt = cur;
1097
+ persist("poll", lastResult);
1098
+ hand.checkpoint?.("commit-created");
1099
+ }
1100
+ if (cur.state === "commit-created" && cur.commit !== undefined) {
1101
+ let remoteSha: string | null;
1102
+ if (rec === null) {
1103
+ const tip = remoteTip(o.cwd, branch);
1104
+ if (tip === null) {
1105
+ deps.log("re-trigger push blocked: the remote branch could not be read");
1106
+ return false;
1107
+ }
1108
+ if (tip !== cur.commit) {
1109
+ // Whatever `origin/<branch>` holds, a tip that is not behind the re-trigger commit is
1110
+ // someone else's work: a lease taken against an up-to-date tracking ref would overwrite it.
1111
+ const fastForward =
1112
+ tip === "" || runGit(o.cwd, ["merge-base", "--is-ancestor", tip, cur.commit]).ok;
1113
+ if (!fastForward) {
1114
+ deps.log(
1115
+ `re-trigger push blocked: ${branch} moved on the remote to ${tip.slice(0, 12)} after the re-trigger commit was made`,
1116
+ );
1117
+ return false;
1118
+ }
1119
+ const push = pushCurrentBranch(o.cwd);
1120
+ if (!push.ok) {
1121
+ deps.log(`re-trigger push failed: ${push.error}`);
1122
+ return false;
1123
+ }
1124
+ }
1125
+ remoteSha = remoteTip(o.cwd, branch) === cur.commit ? cur.commit : null;
1126
+ } else {
1127
+ // A copy persisted by an earlier attempt may already be on the remote: the push
1128
+ // response can be lost, so check before copying again.
1129
+ const earlier = cur.copy;
1130
+ const held =
1131
+ earlier !== undefined &&
1132
+ runGit(o.cwd, ["fetch", "origin", branch]).ok &&
1133
+ runGit(o.cwd, ["merge-base", "--is-ancestor", earlier, `origin/${branch}`]).ok;
1134
+ if (held) {
1135
+ markRecordPushed(o.cwd, o.fid, [cur.commit]);
1136
+ remoteSha = earlier;
1137
+ }
1138
+ const empties = held
1139
+ ? ({ kind: "landed", sha: earlier } as const)
1140
+ : landEmptyOwnCommits(o.cwd, o.fid, branch, deps.log, (copy) => {
1141
+ cur = { ...cur, copy };
1142
+ curRt = cur;
1143
+ persist("poll", lastResult);
1144
+ });
1145
+ if (empties.kind === "landed") remoteSha = empties.sha;
1146
+ else if (empties.kind === "failed") remoteSha = null;
1147
+ else {
1148
+ const out = await pushBranch(o.cwd, { mode: "feature", fid: o.fid }, deps.log);
1149
+ remoteSha = out.out.pushed
1150
+ ? out.out.sha
1151
+ : out.out.skipped === "no-run-commits"
1152
+ ? (readRecord(o.cwd, o.fid)?.pushed?.at(-1) ?? null)
1153
+ : null;
1154
+ }
1155
+ }
1156
+ if (remoteSha === null) {
1157
+ deps.log("re-trigger push did not land the re-trigger commit on the remote");
1158
+ return false;
1159
+ }
1160
+ cur = { ...cur, state: "push-completed", ref: refName, remote: remoteSha };
1161
+ curRt = cur;
1162
+ persist("poll", lastResult);
1163
+ hand.checkpoint?.("push-completed");
845
1164
  }
1165
+ if (cur.state === "push-completed" && cur.remote !== undefined) {
1166
+ if (rec === null && remoteTip(o.cwd, branch) !== cur.remote) {
1167
+ deps.log("re-trigger receipt blocked: the remote branch no longer holds the pushed commit");
1168
+ return false;
1169
+ }
1170
+ cur = { ...cur, state: "receipt-completed", receipt: hand.operation };
1171
+ curRt = cur;
1172
+ persist("repoll", lastResult);
1173
+ hand.checkpoint?.("receipt-completed");
1174
+ }
1175
+ return curRt.state === "receipt-completed";
1176
+ };
1177
+
1178
+ /** Why each verdict was reached, for the log. */
1179
+ const why: Record<string, string> = {
1180
+ "gh-error":
1181
+ "every poll of the phase errored — gh unavailable or unauthenticated; silence proves nothing",
1182
+ "timeout-dirty":
1183
+ "no run and the pushed head carries a CI suppressor — not re-triggering a dirty head",
1184
+ "retrigger-suppressed":
1185
+ "the re-trigger head carries a suppressor — cannot tell no-ci from suppression",
1186
+ "ci-declared-no-run": `${declared.path} exists but a clean re-trigger dispatched no check — look for a startup failure`,
1187
+ "no-ci": `a clean re-trigger dispatched nothing and ${declared.path} is absent — the repo has no CI workflow (logged pass)`,
1188
+ };
1189
+ /** The shared decision on what a phase saw; null when the phase must re-trigger. */
1190
+ const decide = (
1191
+ phase: "poll" | "repoll",
1192
+ seen: { found: boolean; attempts: number; errors: number; budget: number },
1193
+ headSuppressed: boolean,
1194
+ ): DispatchResult | null => {
1195
+ const d = decideDispatch({ phase, ...seen, headSuppressed, ciDeclared: declared.declared });
1196
+ if (d.next === "retrigger") return null;
1197
+ if (d.next === "poll-again") {
1198
+ throw new Error(`CI-Dispatch ${phase} ended with polls left in its budget`);
1199
+ }
1200
+ const note = why[d.reason ?? d.outcome];
1201
+ if (note !== undefined)
1202
+ deps.log(`${d.reason === undefined ? d.outcome : `unresolved(${d.reason})`}: ${note}`);
1203
+ return verdict(d.outcome, d.reason);
1204
+ };
1205
+ const suppressed = (sha: string) => SKIP_CI_TOKEN.test(commitMessage(o.cwd, sha) ?? "");
1206
+
1207
+ if (curRt?.state !== "receipt-completed") {
1208
+ const first = await poll("poll");
1209
+ if (first === null) return res;
1210
+ res.attempts = cumAttempts;
1211
+ // A re-trigger already under way is resumed, never refused for the head it started from.
1212
+ const done = decide("poll", first, curRt === null && suppressed(res.head));
1213
+ if (done !== null) return done;
846
1214
  const message = `chore(${o.fid}): re-trigger${o.autoRouteSuffix}`;
847
1215
  // A run in place on a shared branch commits and pushes only its own work; with
848
1216
  // no record of the run there, nothing is committed or pushed.
@@ -855,77 +1223,25 @@ export async function ciDispatchGate(
855
1223
  res.handoff = EXIT_RETRIGGER_FAILED;
856
1224
  return res;
857
1225
  }
858
- let pushed: boolean;
859
- let failure = "";
860
- if (rec === null) {
861
- landed = null;
862
- const before = git(o.cwd, ["rev-parse", "HEAD"]);
863
- const made = runGit(o.cwd, ["commit", "--allow-empty", "-m", message]);
864
- if (!made.ok) {
865
- pushed = false;
866
- failure = made.stderr || made.stdout;
867
- } else {
868
- const push = pushCurrentBranch(o.cwd);
869
- pushed = push.ok;
870
- if (!push.ok) {
871
- failure = push.error;
872
- // The commit never reached the remote: drop it so a re-run does not pile
873
- // up orphan re-triggers. --soft restores the index exactly as the commit left it.
874
- if (before !== null) runGit(o.cwd, ["reset", "--soft", before]);
875
- }
876
- }
877
- } else {
878
- const made = retriggerCommit(o.cwd, rec, message);
879
- if (!made.ok) deps.log(`re-trigger commit failed: ${made.error}`);
880
- const out = made.ok
881
- ? await pushBranch(o.cwd, { mode: "feature", fid: o.fid }, deps.log)
882
- : null;
883
- landed = out?.out.pushed === true ? out.out.sha : landed;
884
- pushed = out?.out.pushed === true && out.out.sha !== null;
885
- if (pushed) fetchLanded();
886
- }
887
- if (!pushed) {
888
- deps.log(
889
- `re-trigger commit or push failed${failure ? `: ${failure}` : ""} — no verdict; route to the Failure Path`,
890
- );
1226
+ if (!(await handoffRetrigger(message, rec))) {
1227
+ deps.log("re-trigger commit or push failed — no verdict; route to the Failure Path");
891
1228
  res.phase = "repoll";
892
1229
  res.handoff = EXIT_RETRIGGER_FAILED;
893
1230
  return res;
894
1231
  }
895
- res.retrigger = true;
896
- res.head = head();
897
1232
  deps.log("re-trigger pushed; re-polling");
898
1233
  }
1234
+ res.retrigger = true;
1235
+ if (shared && curRt?.remote !== undefined) landed = curRt.remote;
1236
+ res.head = head();
899
1237
 
900
- const prior = res.attempts;
901
1238
  const second = await poll("repoll");
902
1239
  if (second === null) return res;
903
- // A supplied re-poll carries the running total; a fresh one adds to the first poll.
904
- res.attempts = o.retriggered && o.supplied ? second.attempts : prior + second.attempts;
1240
+ res.attempts = cumAttempts;
905
1241
  res.head = head();
906
- if (SKIP_CI_TOKEN.test(commitMessage(o.cwd, res.head) ?? "")) {
907
- deps.log(
908
- "unresolved(retrigger-suppressed): the re-trigger head carries a suppressor — cannot tell no-ci from suppression",
909
- );
910
- return verdict("unresolved", "retrigger-suppressed");
911
- }
912
- if (second.pollResult === "found") return verdict("self-healed");
913
- if (second.allErrored) {
914
- deps.log(
915
- "unresolved(gh-error): every re-poll errored — silence after the re-trigger proves nothing",
916
- );
917
- return verdict("unresolved", "gh-error");
918
- }
919
- if (declared.declared) {
920
- deps.log(
921
- `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}`,
922
- );
923
- return verdict("unresolved", "ci-declared-no-run");
924
- }
925
- deps.log(
926
- `no-ci: a clean re-trigger dispatched nothing and ${declared.path} is absent — the repo has no CI workflow (logged pass)`,
927
- );
928
- return verdict("no-ci");
1242
+ const done = decide("repoll", second, suppressed(res.head));
1243
+ if (done === null) throw new Error("CI-Dispatch re-poll cannot re-trigger a second time");
1244
+ return done;
929
1245
  }
930
1246
 
931
1247
  // ---------------------------------------------------------------------------
@@ -952,6 +1268,8 @@ export const GATE = {
952
1268
  NOT_BOOKKEEPING: 17,
953
1269
  /** --pr: the PR title carries a CI-suppressing token (its squash would skip CI on dev). */
954
1270
  TITLE_SKIP: 18,
1271
+ /** The current dev is absent from the validated code head. */
1272
+ STALE_BASE: 19,
955
1273
  /** API error, rate limit, or auth — distinct from "no run". */
956
1274
  API_ERROR: 20,
957
1275
  } as const;
@@ -1725,6 +2043,114 @@ async function waitFor(
1725
2043
  return { code: EXIT.NO, out };
1726
2044
  }
1727
2045
 
2046
+ /**
2047
+ * `runs handoff`: record one batch of CI poll observations in the invocation's run and derive the
2048
+ * phase, the cumulative totals and the next action from the persisted rows. The caller supplies
2049
+ * what it saw (`--result`, `--polls`), never a count, a phase or a verdict.
2050
+ */
2051
+ function runHandoff(ctx: RunContext): number {
2052
+ const f = ctx.flags;
2053
+ const inv = ctx.invocation;
2054
+ if (
2055
+ inv === undefined ||
2056
+ inv.scope !== "run" ||
2057
+ inv.statusPath === null ||
2058
+ inv.workflow === null
2059
+ ) {
2060
+ throw new CommandError(
2061
+ EXIT.USAGE,
2062
+ "--invocation is required: an invocation issued by `bkit status invocation` for a workflow run",
2063
+ );
2064
+ }
2065
+ const text = (v: FlagValue) => (typeof v === "string" ? v : "");
2066
+ const repo = text(f.repo);
2067
+ // A run in place on a shared branch has no PR: an empty --pr names that target.
2068
+ const pr = text(f.pr) === "" ? null : text(f.pr);
2069
+ const suppliedHead = text(f.head);
2070
+ const branch = text(f.branch);
2071
+ const result = CI_HANDOFF_RESULTS.find((r) => r === text(f.result));
2072
+ if (result === undefined) {
2073
+ throw new CommandError(EXIT.USAGE, `--result must be one of ${CI_HANDOFF_RESULTS.join(" | ")}`);
2074
+ }
2075
+ const polls = wholeNumber(f.polls, "polls", 0, 1);
2076
+ const budgetS = wholeNumber(f.budgetS, "budget-s", 60);
2077
+ const intervalS = wholeNumber(f.intervalS, "interval-s", 10, 1);
2078
+ // After a re-trigger the printed head is the re-trigger commit; its rows live under the original head.
2079
+ const head = resolveHandoffHead(
2080
+ handoffRowsOf(inv.statusPath),
2081
+ { provider: "github", repo, pr, branch },
2082
+ ctx.cwd,
2083
+ suppliedHead,
2084
+ );
2085
+ const target: CiHandoffTarget = { provider: "github", repo, pr, head, branch };
2086
+ const probe = {
2087
+ type: "ci-handoff",
2088
+ workflow: inv.workflow,
2089
+ at: statusTimestamp(),
2090
+ phase: "poll",
2091
+ target,
2092
+ observation: { result: "none", attempts: 0, errors: 0 },
2093
+ };
2094
+ if (!validateCiHandoffEvent(probe)) {
2095
+ throw new CommandError(
2096
+ EXIT.USAGE,
2097
+ "--repo, --pr, --head and --branch must name the owner/repo, PR number, full commit sha and branch",
2098
+ );
2099
+ }
2100
+ const state = foldCiHandoff(readStatusRows(inv.statusPath), target);
2101
+ const attempts = state.attempts + polls;
2102
+ const errors = state.errors + (result === "provider-error" ? polls : 0);
2103
+ const retrigger = state.retrigger;
2104
+ const phase = retrigger?.state === "receipt-completed" ? "repoll" : "poll";
2105
+ fs.appendFileSync(
2106
+ inv.statusPath,
2107
+ appendLine({
2108
+ ...probe,
2109
+ phase,
2110
+ observation: { result, attempts, errors },
2111
+ ...(retrigger === null ? {} : { retrigger }),
2112
+ }),
2113
+ );
2114
+ const max = Math.max(1, Math.ceil(budgetS / intervalS));
2115
+ const base = phase === "repoll" ? (state.retriggerBase ?? { attempts: 0, errors: 0 }) : null;
2116
+ const phaseAttempts = attempts - (base?.attempts ?? 0);
2117
+ const phaseErrors = errors - (base?.errors ?? 0);
2118
+ const found = result === "pending" || result === "success" || result === "failure";
2119
+ const out: Record<string, unknown> = {
2120
+ phase,
2121
+ attempts,
2122
+ errors,
2123
+ ciResult: result,
2124
+ stale: state.stale,
2125
+ };
2126
+ if (retrigger !== null && retrigger.state !== "receipt-completed") {
2127
+ ctx.emit({ ...out, nextAction: "reconcile-retrigger", retrigger });
2128
+ return EXIT.OK;
2129
+ }
2130
+ // The head the phase polled: the pushed head before the re-trigger, the re-trigger commit after it.
2131
+ const polled = phase === "repoll" ? (retrigger?.commit ?? head) : head;
2132
+ const d = decideDispatch({
2133
+ phase,
2134
+ found,
2135
+ attempts: phaseAttempts,
2136
+ errors: phaseErrors,
2137
+ budget: max,
2138
+ headSuppressed: SKIP_CI_TOKEN.test(commitMessage(ctx.cwd, polled) ?? ""),
2139
+ ciDeclared: ciDeclared(checkoutRoot(ctx.cwd)).declared,
2140
+ });
2141
+ ctx.emit(
2142
+ d.next === "verdict"
2143
+ ? {
2144
+ ...out,
2145
+ nextAction: "verdict",
2146
+ outcome: d.outcome,
2147
+ ...(d.reason === undefined ? {} : { reason: d.reason }),
2148
+ }
2149
+ : { ...out, nextAction: d.next },
2150
+ );
2151
+ return EXIT.OK;
2152
+ }
2153
+
1728
2154
  async function runWait(ctx: RunContext): Promise<number> {
1729
2155
  const f = ctx.flags;
1730
2156
  const r = await waitFor(
@@ -1759,6 +2185,15 @@ const waitOutput = (w: WaitResult, kind: WaitKind) => ({
1759
2185
  async function runDispatch(ctx: RunContext): Promise<number> {
1760
2186
  const f = ctx.flags;
1761
2187
  const d = deps(ctx);
2188
+ const inv = ctx.invocation;
2189
+ // Every poll and re-trigger checkpoint is saved in the run's status log, so a re-entry resumes
2190
+ // from what was persisted: without a run's invocation there is nowhere to save it.
2191
+ if (inv === undefined || inv.scope !== "run" || inv.statusPath === null) {
2192
+ throw new CommandError(
2193
+ EXIT.USAGE,
2194
+ "--invocation is required: an invocation issued by `bkit status invocation` for a workflow run",
2195
+ );
2196
+ }
1762
2197
  // An empty --pr is the workflow's unresolved PR_NUMBER: derive it, as if omitted.
1763
2198
  let pr = str(f.pr) || null;
1764
2199
  if (pr === null) {
@@ -1783,13 +2218,6 @@ async function runDispatch(ctx: RunContext): Promise<number> {
1783
2218
  "--sha goes with a run in place on a shared branch that has no PR",
1784
2219
  );
1785
2220
  }
1786
- const pollResult = str(f.pollResult);
1787
- if (pollResult !== undefined && !["found", "none", "err"].includes(pollResult)) {
1788
- throw new CommandError(EXIT.USAGE, "--poll-result must be found, none, or err");
1789
- }
1790
- if (pollResult === undefined && (f.attempts !== undefined || f.allErrored === true)) {
1791
- throw new CommandError(EXIT.USAGE, "--attempts / --all-errored go with --poll-result");
1792
- }
1793
2221
  const r = await ciDispatchGate(
1794
2222
  {
1795
2223
  cwd: ctx.cwd,
@@ -1800,16 +2228,12 @@ async function runDispatch(ctx: RunContext): Promise<number> {
1800
2228
  : "",
1801
2229
  budgetS: wholeNumber(f.budgetS, "budget-s", 60),
1802
2230
  intervalS: wholeNumber(f.intervalS, "interval-s", 10, 1),
1803
- supplied:
1804
- pollResult === undefined
1805
- ? undefined
1806
- : {
1807
- pollResult: pollResult as SuppliedPoll["pollResult"],
1808
- attempts: wholeNumber(f.attempts, "attempts", 0),
1809
- allErrored: f.allErrored === true,
1810
- },
1811
- retriggered: f.retriggered === true,
1812
2231
  sha,
2232
+ handoff: {
2233
+ statusPath: inv.statusPath,
2234
+ operation: `ci-retrigger:${inv.id}`,
2235
+ ...(inv.workflow === null ? {} : { workflow: inv.workflow }),
2236
+ },
1813
2237
  },
1814
2238
  d,
1815
2239
  );
@@ -1825,7 +2249,7 @@ async function runDispatch(ctx: RunContext): Promise<number> {
1825
2249
  let row: Record<string, unknown> | null = null;
1826
2250
  let progressLine: string | undefined;
1827
2251
  let transport: Record<string, unknown> | null = null;
1828
- const code = dispatchCode(r, pr, scanResult, ctx.log);
2252
+ const code = dispatchCode(r, pr, scanResult, ctx.log, inv.id);
1829
2253
  if (file !== undefined && r.ciDispatch !== null) {
1830
2254
  const status = path.resolve(ctx.cwd, file);
1831
2255
  const written = writeStepRow(
@@ -1897,15 +2321,16 @@ function dispatchCode(
1897
2321
  pr: string | null,
1898
2322
  scanResult: ReturnType<typeof scanBody> | null,
1899
2323
  log: (m: string) => void,
2324
+ invocation: string,
1900
2325
  ): number {
1901
2326
  if (r.handoff === EXIT.AGENT_WAIT || r.handoff === EXIT.USE_MCP) {
1902
- const again = r.phase === "repoll" ? " --retriggered" : "";
1903
2327
  const [wait, keep] =
1904
2328
  r.runBranch === null
1905
2329
  ? [`--pr=${pr ?? "<n>"}`, ""]
1906
2330
  : [`--head=${r.head} --branch=${r.runBranch} --until=present`, ` --sha=${r.head}`];
2331
+ 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\``;
1907
2332
  log(
1908
- `${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}`,
2333
+ `${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}`,
1909
2334
  );
1910
2335
  return r.handoff;
1911
2336
  }
@@ -1955,8 +2380,35 @@ function logResolvedPrRepo(
1955
2380
  }
1956
2381
  }
1957
2382
 
1958
- function runGate(ctx: RunContext): number {
2383
+ async function runGate(ctx: RunContext): Promise<number> {
1959
2384
  const f = ctx.flags;
2385
+ if (f.wait === true && f.squashOf === undefined)
2386
+ throw new CommandError(EXIT.USAGE, "--wait needs --squash-of");
2387
+ const freshBase = f.freshBase === true;
2388
+ if (freshBase && (f.pr === undefined || f.capstoneOnly === true))
2389
+ throw new CommandError(EXIT.USAGE, "--fresh-base requires --pr without --capstone-only");
2390
+ const factsPath = str(f.factsFile);
2391
+ let facts: Record<string, unknown> | undefined;
2392
+ if (factsPath !== undefined) {
2393
+ if (!freshBase) throw new CommandError(EXIT.USAGE, "--facts-file requires --fresh-base");
2394
+ const parsed = readJsonFile(path.resolve(ctx.cwd, factsPath));
2395
+ if (!parsed.ok) throw new CommandError(EXIT.USAGE, "cannot read scoped gate facts");
2396
+ facts = obj(parsed.value);
2397
+ const info = facts.pr;
2398
+ if (
2399
+ !validPrFacts(info) ||
2400
+ facts.ownerRepo !== prRepoSlug(info.url) ||
2401
+ (str(f.repo) !== undefined && facts.ownerRepo !== str(f.repo)) ||
2402
+ facts.prNumber !== Number(f.pr) ||
2403
+ info.number !== Number(f.pr) ||
2404
+ facts.headRefName !== info.headRefName ||
2405
+ (str(f.branch) !== undefined && facts.headRefName !== str(f.branch)) ||
2406
+ facts.baseRefName !== DEV ||
2407
+ info.baseRefName !== DEV ||
2408
+ info.state !== "OPEN"
2409
+ )
2410
+ throw new CommandError(EXIT.USAGE, "gate facts repository, PR, head or base scope mismatch");
2411
+ }
1960
2412
  let selection: CiSelection | undefined;
1961
2413
  const selectionFile = str(f.ciSelectionFile);
1962
2414
  if (selectionFile !== undefined) {
@@ -1980,7 +2432,84 @@ function runGate(ctx: RunContext): number {
1980
2432
  ctx.log(`fetch of origin/${branch} failed: ${fetched.stderr.trim()}`);
1981
2433
  }
1982
2434
  const root = checkoutRoot(ctx.cwd);
1983
- const gh: Gh = (args) => runGh(ctx.cwd, args);
2435
+ const gh: Gh =
2436
+ facts === undefined
2437
+ ? (args) => runGh(ctx.cwd, args)
2438
+ : (args) => {
2439
+ const reply = (value: unknown): GhResult => ({
2440
+ ok: true,
2441
+ stdout: JSON.stringify(value),
2442
+ stderr: "",
2443
+ missing: false,
2444
+ });
2445
+ const ci = obj(facts.ci);
2446
+ const repo = text(facts.ownerRepo);
2447
+ const endpoint = args[1]?.replace(/^\//, "") ?? "";
2448
+ if (args[0] === "repo" && args[1] === "view")
2449
+ return { ok: true, stdout: repo, stderr: "", missing: false };
2450
+ const workflow = readBkitConfig(checkoutRoot(ctx.cwd)).ciWorkflow;
2451
+ const scopedRuns = arr(obj(ci.workflowRuns).workflow_runs).map(obj);
2452
+ const workflowPath = workflow.startsWith(".github/workflows/")
2453
+ ? workflow
2454
+ : `.github/workflows/${workflow}`;
2455
+ const validRun = (run: Record<string, unknown>) =>
2456
+ Number.isSafeInteger(run.id) &&
2457
+ Number(run.id) > 0 &&
2458
+ text(obj(run.repository).full_name).toLowerCase() === repo.toLowerCase() &&
2459
+ text(obj(run.head_repository).full_name).toLowerCase() === repo.toLowerCase() &&
2460
+ (text(run.path) === workflowPath ||
2461
+ (/^[1-9][0-9]*$/.test(workflow) && String(run.workflow_id) === workflow)) &&
2462
+ run.head_sha === (str(f.validated) ?? obj(facts.pr).headRefOid) &&
2463
+ run.head_branch === facts.headRefName &&
2464
+ run.html_url === `https://github.com/${repo}/actions/runs/${run.id}`;
2465
+ const invalidEvidence = (): GhResult => ({
2466
+ ok: false,
2467
+ stdout: "",
2468
+ stderr: "scoped gate CI provenance is missing or mismatched",
2469
+ missing: false,
2470
+ });
2471
+ if (
2472
+ args[0] === "api" &&
2473
+ endpoint.startsWith(`repos/${repo}/actions/workflows/${workflow}/runs?`)
2474
+ ) {
2475
+ if (
2476
+ !Array.isArray(obj(ci.workflowRuns).workflow_runs) ||
2477
+ scopedRuns.some((run) => !validRun(run))
2478
+ )
2479
+ return invalidEvidence();
2480
+ return reply(ci.workflowRuns);
2481
+ }
2482
+ const jobMatch = new RegExp(`^repos/${repo}/actions/runs/([0-9]+)/jobs$`).exec(endpoint);
2483
+ if (args[0] === "api" && jobMatch) {
2484
+ const run = scopedRuns.find((candidate) => String(candidate.id) === jobMatch[1]);
2485
+ const pages = Array.isArray(ci.jobs) ? ci.jobs : [ci.jobs];
2486
+ if (
2487
+ !run ||
2488
+ !validRun(run) ||
2489
+ pages.length === 0 ||
2490
+ pages.some(
2491
+ (page) =>
2492
+ !Array.isArray(obj(page).jobs) ||
2493
+ arr(obj(page).jobs).some((value) => {
2494
+ const job = obj(value);
2495
+ return (
2496
+ job.run_id !== run.id ||
2497
+ job.head_sha !== run.head_sha ||
2498
+ job.run_url !== `https://api.github.com/repos/${repo}/actions/runs/${run.id}`
2499
+ );
2500
+ }),
2501
+ )
2502
+ )
2503
+ return invalidEvidence();
2504
+ return reply(ci.jobs);
2505
+ }
2506
+ return {
2507
+ ok: false,
2508
+ stdout: "",
2509
+ stderr: "scoped gate facts do not contain this API evidence",
2510
+ missing: false,
2511
+ };
2512
+ };
1984
2513
  const record = str(f.record);
1985
2514
  const recordFile = record === undefined ? undefined : path.resolve(ctx.cwd, record);
1986
2515
  const prNumber = str(f.pr) ?? str(f.squashOf);
@@ -1991,7 +2520,10 @@ function runGate(ctx: RunContext): number {
1991
2520
  if (prNumber !== undefined) {
1992
2521
  if (!/^[1-9][0-9]*$/.test(prNumber))
1993
2522
  throw new CommandError(EXIT.USAGE, "--pr / --squash-of take a PR number");
1994
- pr = probePr(ctx.cwd, { number: prNumber, state: "open", repo: str(f.repo) });
2523
+ pr =
2524
+ facts !== undefined && validPrFacts(facts.pr)
2525
+ ? { kind: "ok", pr: facts.pr }
2526
+ : probePr(ctx.cwd, { number: prNumber, state: "open", repo: str(f.repo) });
1995
2527
  if (pr.kind === "unavailable") {
1996
2528
  ctx.log(pr.message);
1997
2529
  return EXIT.USE_MCP;
@@ -2015,6 +2547,71 @@ function runGate(ctx: RunContext): number {
2015
2547
  }
2016
2548
  if (head === "") throw new CommandError(EXIT.USAGE, "--head needs a non-empty value");
2017
2549
 
2550
+ const info = pr?.kind === "ok" ? pr.pr : undefined;
2551
+ const repo = str(f.repo) ?? prRepoSlug(info?.url);
2552
+ if (f.wait === true) {
2553
+ // The squash commit's CI runs on the PR's base branch. A wait that runs out is not a verdict:
2554
+ // the gate below still judges what it finds (a run still going is 11, with no row).
2555
+ const waited = await waitFor(
2556
+ ctx.cwd,
2557
+ {
2558
+ head,
2559
+ branch: info?.baseRefName ?? DEV,
2560
+ until: "completed",
2561
+ budgetS: f.budgetS,
2562
+ intervalS: f.intervalS,
2563
+ },
2564
+ deps(ctx, str(f.repo)),
2565
+ );
2566
+ if (waited.code === EXIT.AGENT_WAIT) return EXIT.AGENT_WAIT;
2567
+ if (waited.code === EXIT.NO) ctx.log(`the CI run at ${head} did not finish within the wait`);
2568
+ }
2569
+ const codeHead = str(f.validated) ?? head;
2570
+ let baseEvidence: { devSha: string; comparedHead: string; ancestor: boolean | null } | undefined;
2571
+ if (freshBase) {
2572
+ baseEvidence = { devSha: "", comparedHead: codeHead, ancestor: null };
2573
+ if (facts !== undefined) {
2574
+ const base = obj(facts.base);
2575
+ if (
2576
+ base.ref === DEV &&
2577
+ /^[0-9a-f]{40,64}$/i.test(text(base.sha)) &&
2578
+ base.comparedHead === codeHead &&
2579
+ ["ahead", "identical", "behind", "diverged"].includes(text(base.status))
2580
+ ) {
2581
+ baseEvidence.devSha = text(base.sha);
2582
+ baseEvidence.ancestor = ["ahead", "identical"].includes(text(base.status));
2583
+ }
2584
+ } else if (repo !== undefined && isForeignRepo(ctx.cwd, repo)) {
2585
+ const dev = gh(["api", `repos/${repo}/commits/dev`, "--jq", ".sha"]);
2586
+ if (dev.ok && /^[0-9a-f]{40,64}$/i.test(dev.stdout.trim())) {
2587
+ baseEvidence.devSha = dev.stdout.trim();
2588
+ const compare = gh([
2589
+ "api",
2590
+ `repos/${repo}/compare/${baseEvidence.devSha}...${codeHead}`,
2591
+ "--jq",
2592
+ ".status",
2593
+ ]);
2594
+ if (
2595
+ compare.ok &&
2596
+ ["ahead", "identical", "behind", "diverged"].includes(compare.stdout.trim())
2597
+ )
2598
+ baseEvidence.ancestor = ["ahead", "identical"].includes(compare.stdout.trim());
2599
+ }
2600
+ } else {
2601
+ const fetched = fetchRemoteRef(ctx.cwd, "origin/dev");
2602
+ if (fetched?.ok) {
2603
+ baseEvidence.devSha = git(ctx.cwd, ["rev-parse", "--verify", "origin/dev^{commit}"]) ?? "";
2604
+ const compared = runTool(
2605
+ "git",
2606
+ ["merge-base", "--is-ancestor", baseEvidence.devSha, codeHead],
2607
+ ctx.cwd,
2608
+ );
2609
+ if (compared.status === 0 || compared.status === 1)
2610
+ baseEvidence.ancestor = compared.status === 0;
2611
+ }
2612
+ }
2613
+ }
2614
+
2018
2615
  // The pre-merge snapshot, written BEFORE the gate decides.
2019
2616
  const snapshot = str(f.snapshot);
2020
2617
  if (snapshot !== undefined) {
@@ -2024,7 +2621,10 @@ function runGate(ctx: RunContext): number {
2024
2621
  // A foreign repo's dev and ancestry come from the API: the checkout's origin/dev is another repo's.
2025
2622
  let dev: string;
2026
2623
  let ancestor: boolean;
2027
- if (foreign && repoFlag !== undefined) {
2624
+ if (baseEvidence !== undefined) {
2625
+ dev = baseEvidence.devSha;
2626
+ ancestor = baseEvidence.ancestor === true;
2627
+ } else if (foreign && repoFlag !== undefined) {
2028
2628
  const devRes = gh(["api", `repos/${repoFlag}/commits/dev`, "--jq", ".sha"]);
2029
2629
  dev = devRes.ok ? devRes.stdout.trim() : "";
2030
2630
  const cmp = gh(["api", `repos/${repoFlag}/compare/dev...${head}`, "--jq", ".status"]);
@@ -2061,6 +2661,12 @@ function runGate(ctx: RunContext): number {
2061
2661
  validatedHead: str(f.validated) ?? "",
2062
2662
  devSha: dev,
2063
2663
  ancestor: String(ancestor),
2664
+ ...(baseEvidence === undefined
2665
+ ? {}
2666
+ : {
2667
+ comparedHead: baseEvidence.comparedHead,
2668
+ baseEvidenceAvailable: baseEvidence.ancestor !== null,
2669
+ }),
2064
2670
  capstone,
2065
2671
  mergeable: info?.mergeable ?? "",
2066
2672
  })}\n`,
@@ -2070,10 +2676,22 @@ function runGate(ctx: RunContext): number {
2070
2676
  // A title carrying a skip token would squash into a dev commit CI never runs on.
2071
2677
  const title = pr?.kind === "ok" ? (pr.pr?.title ?? "") : "";
2072
2678
  const titleToken = f.pr !== undefined ? SKIP_CI_TOKEN.exec(title)?.[0] : undefined;
2679
+ const baseUnavailable =
2680
+ baseEvidence?.ancestor === null || (freshBase && info?.baseRefName !== DEV);
2681
+ const baseRefused = freshBase && (baseEvidence?.ancestor !== true || baseUnavailable);
2682
+ const safetyReason = baseRefused
2683
+ ? baseUnavailable
2684
+ ? "fresh dev base evidence is unavailable or the PR base is not dev"
2685
+ : `dev base ${baseEvidence?.devSha ?? ""} is absent from validated code head ${codeHead}; integrate dev and revalidate`
2686
+ : `PR title '${title}' contains the CI-suppressing token ${titleToken ?? ""}`;
2073
2687
  let r: GateResult =
2074
- titleToken !== undefined
2688
+ baseRefused || titleToken !== undefined
2075
2689
  ? {
2076
- code: GATE.TITLE_SKIP,
2690
+ code: baseRefused
2691
+ ? baseUnavailable
2692
+ ? GATE.API_ERROR
2693
+ : GATE.STALE_BASE
2694
+ : GATE.TITLE_SKIP,
2077
2695
  passed: false,
2078
2696
  overridden: false,
2079
2697
  head,
@@ -2084,12 +2702,12 @@ function runGate(ctx: RunContext): number {
2084
2702
  conclusion: null,
2085
2703
  capstone: "",
2086
2704
  ciWorkflow: "",
2087
- repo: str(f.repo) ?? null,
2705
+ repo: repo ?? null,
2088
2706
  skippedLanes: [],
2089
2707
  nonBookkeepingPaths: [],
2090
2708
  failedSteps: [],
2091
2709
  regenerable: false,
2092
- reason: `PR title '${title}' contains the CI-suppressing token ${titleToken}`,
2710
+ reason: safetyReason,
2093
2711
  }
2094
2712
  : shipGate(
2095
2713
  {
@@ -2108,7 +2726,7 @@ function runGate(ctx: RunContext): number {
2108
2726
  gh,
2109
2727
  ctx.log,
2110
2728
  );
2111
- if (titleToken !== undefined) ctx.log(r.reason);
2729
+ if (baseRefused || titleToken !== undefined) ctx.log(r.reason);
2112
2730
 
2113
2731
  // Debug retains the configured gate above and also proves the original
2114
2732
  // selected workflow at the pushed head. A different workflow need not contain
@@ -2160,13 +2778,16 @@ function runGate(ctx: RunContext): number {
2160
2778
 
2161
2779
  if (recordFile !== undefined && r.code !== EXIT.USE_MCP) {
2162
2780
  if (f.capstoneOnly === true) {
2163
- const verdict = r.code === EXIT.OK ? "PASS" : "FAIL";
2164
- auditRow(recordFile, "ship-merge-ci", {
2165
- sha: head,
2166
- run: String(r.runId ?? ""),
2167
- verdict,
2168
- reason: verdict === "PASS" ? "" : r.reason,
2169
- });
2781
+ // No run yet (10) and a run still in progress (11) are not verdicts: the row waits for one.
2782
+ if (r.code !== GATE.NO_RUN && r.code !== GATE.IN_PROGRESS) {
2783
+ const verdict = r.code === EXIT.OK ? "PASS" : "FAIL";
2784
+ auditRow(recordFile, "ship-merge-ci", {
2785
+ sha: head,
2786
+ run: String(r.runId ?? ""),
2787
+ verdict,
2788
+ reason: verdict === "PASS" ? "" : r.reason,
2789
+ });
2790
+ }
2170
2791
  } else if (r.code !== EXIT.OK) {
2171
2792
  auditRow(recordFile, "ship-gate-refusal", { exitCode: r.code, head: r.mergeHead });
2172
2793
  }
@@ -2217,6 +2838,7 @@ async function runRevalidate(ctx: RunContext): Promise<number> {
2217
2838
  // CI must pass at the code head while the PR head adds bookkeeping only and dev
2218
2839
  // demands no status checks; otherwise at the PR head.
2219
2840
  let validated = codeHead;
2841
+ let reconcileRequired = current !== codeHead;
2220
2842
  if (foreign) {
2221
2843
  // The bookkeeping diff reads the checkout's git, which is not the named repo's history.
2222
2844
  ctx.log(
@@ -2230,8 +2852,23 @@ async function runRevalidate(ctx: RunContext): Promise<number> {
2230
2852
  from: codeHead,
2231
2853
  to: current,
2232
2854
  });
2855
+ reconcileRequired = !book.ok;
2233
2856
  if (!book.ok) validated = current;
2234
2857
  }
2858
+ if (f.requireReconciled === true && reconcileRequired) {
2859
+ auditRow(status, "ship-gate-refusal", { exitCode: 21, head: current });
2860
+ ctx.log(`feature code changed at ${current} — reconcile before CI validation`);
2861
+ ctx.emit({
2862
+ reconcileRequired: true,
2863
+ validatedHead: null,
2864
+ currentHead: current,
2865
+ revalidated: false,
2866
+ probe: null,
2867
+ dispatched: false,
2868
+ wait: null,
2869
+ });
2870
+ return 21;
2871
+ }
2235
2872
  const repo = repoFlag ?? resolveOwnerRepo(ctx.cwd)?.ownerRepo;
2236
2873
  if (repo !== undefined && devRequiresChecks(d.gh, repo)) {
2237
2874
  ctx.log(`dev requires status checks — validating at the PR head ${current}`);
@@ -2239,6 +2876,7 @@ async function runRevalidate(ctx: RunContext): Promise<number> {
2239
2876
  }
2240
2877
 
2241
2878
  const out: Record<string, unknown> = {
2879
+ ...(f.requireReconciled === true ? { reconcileRequired: false } : {}),
2242
2880
  validatedHead: validated,
2243
2881
  currentHead: current,
2244
2882
  revalidated: false,
@@ -2315,7 +2953,7 @@ const PHASES: Record<string, { phase: string; mode: "CI" | "BRIEF" }> = {
2315
2953
  export const EXIT_UNKNOWN_PHASE = 3;
2316
2954
  /** Exit code (context): the CI PR is not OPEN. */
2317
2955
  export const EXIT_PR_NOT_OPEN = 7;
2318
- /** Exit code (context): no CI run at the PR head. */
2956
+ /** Exit code (context): no matching CI run at the PR head (the test workflow's newest run, or its newest failed run for debug). */
2319
2957
  export const EXIT_NO_RUN_ID = 8;
2320
2958
  /** Exit code (context): no FID from the marker, the branch, or the slug. */
2321
2959
  export const EXIT_NO_FID = 9;
@@ -2407,22 +3045,34 @@ async function runContext(ctx: RunContext): Promise<number> {
2407
3045
  ctx.emit(out);
2408
3046
  return EXIT_PR_NOT_OPEN;
2409
3047
  }
3048
+ const testWorkflow = ciDeclared(checkoutRoot(ctx.cwd));
3049
+ const wantsFailed = chosen.phase === "debug";
2410
3050
  const runs = runGh(ctx.cwd, [
2411
3051
  "run",
2412
3052
  "list",
2413
3053
  "--branch",
2414
3054
  branch,
3055
+ ...(testWorkflow.declared ? ["--workflow", testWorkflow.ciWorkflow] : []),
3056
+ "--commit",
3057
+ headSha,
2415
3058
  "--limit",
2416
3059
  "5",
2417
3060
  "--json",
2418
- "databaseId,headSha",
3061
+ "databaseId,headSha,status,conclusion",
2419
3062
  ]);
2420
3063
  const run = arr(runs.ok ? jsonOrUndefined(runs.stdout) : undefined)
2421
3064
  .map(obj)
2422
- .find((r) => r.headSha === headSha);
3065
+ .find(
3066
+ (r) =>
3067
+ r.headSha === headSha &&
3068
+ (!wantsFailed ||
3069
+ (r.status === "completed" && FAILED_CONCLUSIONS.includes(text(r.conclusion)))),
3070
+ );
2423
3071
  out.runId = run?.databaseId === undefined ? null : String(run.databaseId);
2424
3072
  if (out.runId === null) {
2425
- ctx.log(`no CI run at ${headSha} on ${branch}`);
3073
+ ctx.log(
3074
+ `no ${wantsFailed ? "failed " : ""}CI run of ${testWorkflow.declared ? testWorkflow.ciWorkflow : "any workflow"} at ${headSha} on ${branch}`,
3075
+ );
2426
3076
  ctx.emit(out);
2427
3077
  return EXIT_NO_RUN_ID;
2428
3078
  }
@@ -2604,11 +3254,49 @@ export const runsCommand: CommandSpec = {
2604
3254
  exitCodes: { [EXIT_TRIGGER_FAILED]: "--dispatch-if-absent: gh workflow run failed" },
2605
3255
  run: runWait,
2606
3256
  },
3257
+ handoff: {
3258
+ summary:
3259
+ "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.",
3260
+ use: "workflow",
3261
+ flags: [
3262
+ INVOCATION_FLAG,
3263
+ { name: "repo", type: "string", required: true, help: "owner/repo of the PR" },
3264
+ {
3265
+ name: "pr",
3266
+ type: "string",
3267
+ help: "PR number; empty for a run in place on a shared branch (no PR)",
3268
+ },
3269
+ { name: "head", type: "string", required: true, help: "full commit sha the polls ran at" },
3270
+ { name: "branch", type: "string", required: true, help: "branch the PR is on" },
3271
+ BUDGET_FLAG,
3272
+ INTERVAL_FLAG,
3273
+ {
3274
+ name: "result",
3275
+ type: "string",
3276
+ required: true,
3277
+ help: "what the polls saw: none | pending | success | failure | provider-error",
3278
+ },
3279
+ { name: "polls", type: "string", required: true, help: "polls this batch ran (>= 1)" },
3280
+ ],
3281
+ output: {
3282
+ phase: "poll | repoll (repoll once the re-trigger is receipt-completed)",
3283
+ attempts: "cumulative polls for this target",
3284
+ errors: "cumulative provider-error polls for this target",
3285
+ nextAction: "poll-again | retrigger | reconcile-retrigger | verdict",
3286
+ outcome: "dispatched | self-healed | no-ci | unresolved (nextAction verdict only)",
3287
+ reason:
3288
+ "unresolved reason: gh-error | timeout-dirty | retrigger-suppressed | ci-declared-no-run (the same decision `runs dispatch` makes)",
3289
+ ciResult: "the result this batch recorded",
3290
+ stale: "persisted rows for another repo, PR, head or branch, not counted",
3291
+ },
3292
+ run: runHandoff,
3293
+ },
2607
3294
  dispatch: {
2608
3295
  summary:
2609
- "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.",
3296
+ "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.",
2610
3297
  use: "workflow",
2611
3298
  flags: [
3299
+ INVOCATION_FLAG,
2612
3300
  {
2613
3301
  name: "pr",
2614
3302
  type: "string",
@@ -2652,22 +3340,6 @@ export const runsCommand: CommandSpec = {
2652
3340
  },
2653
3341
  { ...BUDGET_FLAG, help: "poll budget in seconds (default 60)" },
2654
3342
  { ...INTERVAL_FLAG, help: "seconds between polls (default 10)" },
2655
- {
2656
- name: "poll-result",
2657
- type: "string",
2658
- help: "re-entry after a hand-off: found | none | err, as the agent turn loop resolved it",
2659
- },
2660
- {
2661
- name: "attempts",
2662
- type: "string",
2663
- help: "re-entry: total poll attempts so far (hand-off attempts + turns)",
2664
- },
2665
- { name: "all-errored", type: "boolean", help: "re-entry: every turn-loop poll errored" },
2666
- {
2667
- name: "retriggered",
2668
- type: "boolean",
2669
- help: "re-entry: the hand-off was in the re-poll (re-trigger already pushed)",
2670
- },
2671
3343
  ],
2672
3344
  output: {
2673
3345
  ciDispatch:
@@ -2702,6 +3374,16 @@ export const runsCommand: CommandSpec = {
2702
3374
  type: "string",
2703
3375
  help: "validated original debug selection: additionally require its workflow to succeed at the exact pushed head",
2704
3376
  },
3377
+ {
3378
+ name: "fresh-base",
3379
+ type: "boolean",
3380
+ help: "ship pre-merge: require fresh dev ancestry in the validated code head; CI overrides cannot waive it",
3381
+ },
3382
+ {
3383
+ name: "facts-file",
3384
+ type: "string",
3385
+ help: "with --fresh-base: scoped independently read PR, CI and dev comparison facts, without gh calls",
3386
+ },
2705
3387
  { ...HEAD_FLAG, help: "the PR head to merge (or --pr / --squash-of)" },
2706
3388
  {
2707
3389
  name: "pr",
@@ -2721,7 +3403,7 @@ export const runsCommand: CommandSpec = {
2721
3403
  {
2722
3404
  name: "record",
2723
3405
  type: "string",
2724
- help: "status.jsonl: append ship-gate-refusal on a refusal, or ship-merge-ci with --capstone-only",
3406
+ 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)",
2725
3407
  },
2726
3408
  {
2727
3409
  name: "validated",
@@ -2756,6 +3438,13 @@ export const runsCommand: CommandSpec = {
2756
3438
  type: "boolean",
2757
3439
  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)",
2758
3440
  },
3441
+ {
3442
+ name: "wait",
3443
+ type: "boolean",
3444
+ 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)",
3445
+ },
3446
+ { ...BUDGET_FLAG, help: "with --wait: the wait budget in seconds" },
3447
+ { ...INTERVAL_FLAG, help: "with --wait: seconds between polls (>= 1)" },
2759
3448
  ],
2760
3449
  output: {
2761
3450
  code: "the exit code",
@@ -2792,6 +3481,8 @@ export const runsCommand: CommandSpec = {
2792
3481
  [GATE.LANE_SKIPPED]: "a required lane concluded skipped",
2793
3482
  [GATE.NOT_BOOKKEEPING]: "non-bookkeeping change past --validated, or not its descendant",
2794
3483
  [GATE.TITLE_SKIP]: "--pr: the PR title carries a CI-suppressing token",
3484
+ [GATE.STALE_BASE]:
3485
+ "fresh dev is absent from the validated code head; integrate and revalidate",
2795
3486
  [GATE.API_ERROR]:
2796
3487
  "API error / rate limit / auth, or the PR head / squash commit unreadable",
2797
3488
  },
@@ -2802,6 +3493,11 @@ export const runsCommand: CommandSpec = {
2802
3493
  "Ship: pick the head CI must pass at, probe for a run there, dispatch only when none, wait for it to complete.",
2803
3494
  use: "workflow",
2804
3495
  flags: [
3496
+ {
3497
+ name: "require-reconciled",
3498
+ type: "boolean",
3499
+ help: "refuse newly observed feature code before CI validation",
3500
+ },
2805
3501
  { name: "pr", type: "string", required: true, help: "the PR number" },
2806
3502
  { name: "entry-head", type: "string", required: true, help: "the PR head read at Step 2" },
2807
3503
  {
@@ -2838,13 +3534,18 @@ export const runsCommand: CommandSpec = {
2838
3534
  ],
2839
3535
  output: {
2840
3536
  validatedHead: "the head CI was (or must be) checked at",
3537
+ reconcileRequired:
3538
+ "with --require-reconciled, whether new feature code needs reconciliation",
2841
3539
  currentHead: "the PR head now",
2842
3540
  revalidated: "a probe / wait ran (the head moved, or a gate refusal re-entered)",
2843
3541
  probe: "the presence probe's wait result, or null",
2844
3542
  dispatched: "the probe found no run and dispatched one",
2845
3543
  wait: "the completion wait's result, or null",
2846
3544
  },
2847
- exitCodes: { [EXIT_TRIGGER_FAILED]: "no run and gh workflow run failed" },
3545
+ exitCodes: {
3546
+ [EXIT_TRIGGER_FAILED]: "no run and gh workflow run failed",
3547
+ 21: "--require-reconciled: new feature code needs reconciliation",
3548
+ },
2848
3549
  run: runRevalidate,
2849
3550
  },
2850
3551
  mirror: {
@@ -2922,12 +3623,14 @@ export const runsCommand: CommandSpec = {
2922
3623
  headSha: "the PR head (CI) or origin/dev (CI_DEV), else null",
2923
3624
  prUrl: "the PR URL (CI), else null",
2924
3625
  prState: "the PR state (CI), else null",
2925
- runId: "the CI run at the PR head (CI), else null",
3626
+ runId:
3627
+ "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",
2926
3628
  },
2927
3629
  exitCodes: {
2928
3630
  [EXIT_UNKNOWN_PHASE]: "the phase word is not one bkit dispatches",
2929
3631
  [EXIT_PR_NOT_OPEN]: "the PR is not OPEN",
2930
- [EXIT_NO_RUN_ID]: "no CI run at the PR head",
3632
+ [EXIT_NO_RUN_ID]:
3633
+ "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)",
2931
3634
  [EXIT_NO_FID]:
2932
3635
  "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)",
2933
3636
  },