@cbartens/bkit 0.0.0-stage → 5.0.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 (373) hide show
  1. package/.bkit/README.md +421 -0
  2. package/.bkit/core/.agents/context.md +95 -0
  3. package/.bkit/core/.agents/docs.md +62 -0
  4. package/.bkit/core/.agents/rules.md +147 -0
  5. package/.bkit/core/.agents/skills.md +43 -0
  6. package/.bkit/core/.bkit/LICENSE.md +151 -0
  7. package/.bkit/core/.bkit/README.md +421 -0
  8. package/.bkit/core/.bkit/cloud.md +502 -0
  9. package/.bkit/core/.bkit/comparison.md +318 -0
  10. package/.bkit/core/.bkit/install.md +496 -0
  11. package/.bkit/core/.bkit/jsonl.md +497 -0
  12. package/.bkit/core/.bkit/prompts.md +474 -0
  13. package/.bkit/core/.bkit/providers.md +598 -0
  14. package/.bkit/core/.bkit/templates.md +471 -0
  15. package/.bkit/core/.bkit/trackers.md +95 -0
  16. package/.bkit/core/.bkit/workflows.md +1546 -0
  17. package/.bkit/core/.claude/hooks/bkit-gateguard.cjs +82 -0
  18. package/.bkit/core/.claude/hooks/bkit-guardrails.cjs +93 -0
  19. package/.bkit/core/.claude/hooks/bkit-preflight.sh +74 -0
  20. package/.bkit/core/.codex/hooks/bkit-gateguard.cjs +115 -0
  21. package/.bkit/core/.codex/hooks/bkit-guardrails.cjs +135 -0
  22. package/.bkit/core/.cursor/hooks/bkit-gateguard.cjs +111 -0
  23. package/.bkit/core/.cursor/hooks/bkit-guardrails.cjs +169 -0
  24. package/.bkit/core/.cursor/hooks/bkit-preflight.sh +63 -0
  25. package/.bkit/core/.opencode/plugin/bkit-gateguard.js +225 -0
  26. package/.bkit/core/AGENTS.md +77 -0
  27. package/.bkit/core/LICENSE.md +149 -0
  28. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +272 -0
  29. package/.bkit/core/docs/templates/bkit-audit-adoption.md +223 -0
  30. package/.bkit/core/docs/templates/bkit-audit-agents.md +230 -0
  31. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +227 -0
  32. package/.bkit/core/docs/templates/bkit-audit-analytics.md +266 -0
  33. package/.bkit/core/docs/templates/bkit-audit-annotations.md +230 -0
  34. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +270 -0
  35. package/.bkit/core/docs/templates/bkit-audit-app-store.md +254 -0
  36. package/.bkit/core/docs/templates/bkit-audit-architecture.md +221 -0
  37. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +241 -0
  38. package/.bkit/core/docs/templates/bkit-audit-config.md +230 -0
  39. package/.bkit/core/docs/templates/bkit-audit-cost.md +218 -0
  40. package/.bkit/core/docs/templates/bkit-audit-coverage.md +221 -0
  41. package/.bkit/core/docs/templates/bkit-audit-database.md +229 -0
  42. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +251 -0
  43. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +283 -0
  44. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +268 -0
  45. package/.bkit/core/docs/templates/bkit-audit-documentation.md +280 -0
  46. package/.bkit/core/docs/templates/bkit-audit-duplication.md +253 -0
  47. package/.bkit/core/docs/templates/bkit-audit-failures.md +259 -0
  48. package/.bkit/core/docs/templates/bkit-audit-flakes.md +237 -0
  49. package/.bkit/core/docs/templates/bkit-audit-gates.md +250 -0
  50. package/.bkit/core/docs/templates/bkit-audit-issues.md +273 -0
  51. package/.bkit/core/docs/templates/bkit-audit-llm.md +239 -0
  52. package/.bkit/core/docs/templates/bkit-audit-logs.md +266 -0
  53. package/.bkit/core/docs/templates/bkit-audit-models.md +210 -0
  54. package/.bkit/core/docs/templates/bkit-audit-privacy.md +211 -0
  55. package/.bkit/core/docs/templates/bkit-audit-prompts.md +216 -0
  56. package/.bkit/core/docs/templates/bkit-audit-red-team.md +220 -0
  57. package/.bkit/core/docs/templates/bkit-audit-reliability.md +222 -0
  58. package/.bkit/core/docs/templates/bkit-audit-repo.md +224 -0
  59. package/.bkit/core/docs/templates/bkit-audit-security.md +274 -0
  60. package/.bkit/core/docs/templates/bkit-audit-slop.md +200 -0
  61. package/.bkit/core/docs/templates/bkit-audit-testing.md +270 -0
  62. package/.bkit/core/docs/templates/bkit-audit-usability.md +237 -0
  63. package/.bkit/core/docs/templates/bkit-plan.md +476 -0
  64. package/.bkit/core/engine/checks/after/auth.ts +247 -0
  65. package/.bkit/core/engine/checks/after/ci-yml.ts +739 -0
  66. package/.bkit/core/engine/checks/after/github.ts +424 -0
  67. package/.bkit/core/engine/checks/after/index.ts +556 -0
  68. package/.bkit/core/engine/checks/after/managed.ts +217 -0
  69. package/.bkit/core/engine/checks/after/tools.ts +427 -0
  70. package/.bkit/core/engine/checks/after/vercel.ts +101 -0
  71. package/.bkit/core/engine/checks/before/context-fetch.ts +429 -0
  72. package/.bkit/core/engine/checks/before/env.ts +201 -0
  73. package/.bkit/core/engine/checks/before/files.ts +202 -0
  74. package/.bkit/core/engine/checks/before/index.ts +206 -0
  75. package/.bkit/core/engine/checks/before/mcp.ts +127 -0
  76. package/.bkit/core/engine/checks/before/repo.ts +77 -0
  77. package/.bkit/core/engine/checks/before/version.ts +67 -0
  78. package/.bkit/core/engine/checks/status-holes.ts +479 -0
  79. package/.bkit/core/engine/cli.ts +871 -0
  80. package/.bkit/core/engine/commands/analysis.ts +550 -0
  81. package/.bkit/core/engine/commands/ci/ci.ts +483 -0
  82. package/.bkit/core/engine/commands/comply.ts +415 -0
  83. package/.bkit/core/engine/commands/harvest.ts +459 -0
  84. package/.bkit/core/engine/commands/install/check.ts +70 -0
  85. package/.bkit/core/engine/commands/install/doctor.ts +247 -0
  86. package/.bkit/core/engine/commands/install/install.ts +528 -0
  87. package/.bkit/core/engine/commands/install/uninstall.ts +972 -0
  88. package/.bkit/core/engine/commands/install/upgrade.ts +1026 -0
  89. package/.bkit/core/engine/commands/launch.ts +139 -0
  90. package/.bkit/core/engine/commands/lib.ts +494 -0
  91. package/.bkit/core/engine/commands/registry.ts +53 -0
  92. package/.bkit/core/engine/commands/setup/setup.ts +184 -0
  93. package/.bkit/core/engine/commands/telemetry.ts +32 -0
  94. package/.bkit/core/engine/commands/workflow/branches.ts +1514 -0
  95. package/.bkit/core/engine/commands/workflow/context.ts +961 -0
  96. package/.bkit/core/engine/commands/workflow/counters.ts +268 -0
  97. package/.bkit/core/engine/commands/workflow/fids.ts +243 -0
  98. package/.bkit/core/engine/commands/workflow/issues.ts +675 -0
  99. package/.bkit/core/engine/commands/workflow/ledgers.ts +575 -0
  100. package/.bkit/core/engine/commands/workflow/locks.ts +478 -0
  101. package/.bkit/core/engine/commands/workflow/prs.ts +1087 -0
  102. package/.bkit/core/engine/commands/workflow/repo.ts +220 -0
  103. package/.bkit/core/engine/commands/workflow/roadmap.ts +576 -0
  104. package/.bkit/core/engine/commands/workflow/runs.ts +2140 -0
  105. package/.bkit/core/engine/commands/workflow/runtime.ts +300 -0
  106. package/.bkit/core/engine/commands/workflow/skills.ts +118 -0
  107. package/.bkit/core/engine/commands/workflow/status.ts +455 -0
  108. package/.bkit/core/engine/commands/workflow/steps.ts +1300 -0
  109. package/.bkit/core/engine/commands/workflow/tests.ts +161 -0
  110. package/.bkit/core/engine/commands/workflow/workflows.ts +1573 -0
  111. package/.bkit/core/engine/commands/workflow/workstreams.ts +164 -0
  112. package/.bkit/core/engine/commands/workflow/worktrees.ts +534 -0
  113. package/.bkit/core/engine/install/cloud-env.ts +925 -0
  114. package/.bkit/core/engine/install/managed-block.ts +212 -0
  115. package/.bkit/core/engine/install/manifest.ts +448 -0
  116. package/.bkit/core/engine/install/modules/claude.ts +362 -0
  117. package/.bkit/core/engine/install/modules/cloud.ts +174 -0
  118. package/.bkit/core/engine/install/modules/codex.ts +219 -0
  119. package/.bkit/core/engine/install/modules/core.ts +600 -0
  120. package/.bkit/core/engine/install/modules/cursor.ts +231 -0
  121. package/.bkit/core/engine/install/modules/index.ts +242 -0
  122. package/.bkit/core/engine/install/modules/opencode.ts +573 -0
  123. package/.bkit/core/engine/install/placeholders.ts +108 -0
  124. package/.bkit/core/engine/install/template-copies.ts +119 -0
  125. package/.bkit/core/engine/install/version-file.ts +284 -0
  126. package/.bkit/core/engine/install/write.ts +467 -0
  127. package/.bkit/core/engine/ledgers/clamp-log.ts +32 -0
  128. package/.bkit/core/engine/ledgers/status.ts +213 -0
  129. package/.bkit/core/engine/ledgers/telemetry.ts +1143 -0
  130. package/.bkit/core/engine/render/hosts.ts +372 -0
  131. package/.bkit/core/engine/render/models.ts +323 -0
  132. package/.bkit/core/engine/render/parts.ts +38 -0
  133. package/.bkit/core/engine/render/trackers.ts +170 -0
  134. package/.bkit/core/engine/shared/egress.ts +345 -0
  135. package/.bkit/core/engine/shared/json.ts +16 -0
  136. package/.bkit/core/engine/shared/log-prefix.ts +9 -0
  137. package/.bkit/core/engine/shared/package-json.ts +29 -0
  138. package/.bkit/core/engine/shared/package-manager.ts +38 -0
  139. package/.bkit/core/engine/shared/package-roots.ts +163 -0
  140. package/.bkit/core/engine/shared/protected-paths.ts +164 -0
  141. package/.bkit/core/engine/shared/settings.ts +72 -0
  142. package/.bkit/core/engine/shared/timeouts.ts +20 -0
  143. package/.bkit/core/engine/tools/wording.ts +748 -0
  144. package/.bkit/core/hooks/gateguard-edit-payload.js +18 -0
  145. package/.bkit/core/hooks/gateguard-engine.js +193 -0
  146. package/.bkit/core/hooks/guardrails-shell.js +154 -0
  147. package/.bkit/core/hooks/guardrails-tiers.js +68 -0
  148. package/.bkit/core/hooks/preflight-linear.sh +73 -0
  149. package/.bkit/core/prompts/bkit-audit-generate.md +66 -0
  150. package/.bkit/core/prompts/bkit-build-challenge-1.md +79 -0
  151. package/.bkit/core/prompts/bkit-build-challenge-2.md +81 -0
  152. package/.bkit/core/prompts/bkit-build-challenge-reconcile.md +68 -0
  153. package/.bkit/core/prompts/bkit-build-challenge-remediate.md +70 -0
  154. package/.bkit/core/prompts/bkit-build-challenge-tests.md +73 -0
  155. package/.bkit/core/prompts/bkit-build-install-skills.md +67 -0
  156. package/.bkit/core/prompts/bkit-build-plan-current.md +75 -0
  157. package/.bkit/core/prompts/bkit-build-plan-execute.md +72 -0
  158. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +73 -0
  159. package/.bkit/core/prompts/bkit-build-plan-verify.md +88 -0
  160. package/.bkit/core/prompts/bkit-build-summary.md +93 -0
  161. package/.bkit/core/prompts/bkit-debug-abort-handover.md +90 -0
  162. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +151 -0
  163. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +78 -0
  164. package/.bkit/core/prompts/bkit-debug-failure-soak.md +73 -0
  165. package/.bkit/core/prompts/bkit-debug-summary.md +95 -0
  166. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +72 -0
  167. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +72 -0
  168. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +75 -0
  169. package/.bkit/core/prompts/bkit-design-generate.md +110 -0
  170. package/.bkit/core/prompts/bkit-design-organise.md +85 -0
  171. package/.bkit/core/prompts/bkit-design-review-1.md +121 -0
  172. package/.bkit/core/prompts/bkit-design-review-2.md +111 -0
  173. package/.bkit/core/prompts/bkit-design-spike.md +97 -0
  174. package/.bkit/core/prompts/bkit-design-summary.md +106 -0
  175. package/.bkit/core/prompts/bkit-design-update.md +66 -0
  176. package/.bkit/core/prompts/bkit-plan-complexity-check.md +66 -0
  177. package/.bkit/core/prompts/bkit-plan-complexity-split.md +87 -0
  178. package/.bkit/core/prompts/bkit-plan-generate.md +74 -0
  179. package/.bkit/core/prompts/bkit-plan-review-1.md +90 -0
  180. package/.bkit/core/prompts/bkit-plan-review-2.md +80 -0
  181. package/.bkit/core/prompts/bkit-plan-review-3.md +92 -0
  182. package/.bkit/core/prompts/bkit-plan-scope-check-1.md +84 -0
  183. package/.bkit/core/prompts/bkit-plan-scope-check-2.md +84 -0
  184. package/.bkit/core/prompts/bkit-plan-summary.md +106 -0
  185. package/.bkit/core/prompts/bkit-plan-update.md +68 -0
  186. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +90 -0
  187. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +94 -0
  188. package/.bkit/core/prompts/bkit-ship-summary.md +77 -0
  189. package/.bkit/core/prompts/bkit-ship-update-docs.md +71 -0
  190. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +91 -0
  191. package/.bkit/core/prompts/bkit-utility-update-decisions.md +75 -0
  192. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +76 -0
  193. package/.bkit/core/prompts/bkit-utility-update-documentation.md +61 -0
  194. package/.bkit/core/prompts/bkit-utility-update-failures.md +76 -0
  195. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +75 -0
  196. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +82 -0
  197. package/.bkit/core/workflows/bkit-auto.md +121 -0
  198. package/.bkit/core/workflows/bkit-build.md +802 -0
  199. package/.bkit/core/workflows/bkit-debug.md +642 -0
  200. package/.bkit/core/workflows/bkit-design.md +495 -0
  201. package/.bkit/core/workflows/bkit-plan.md +510 -0
  202. package/.bkit/core/workflows/bkit-ship.md +650 -0
  203. package/.bkit/shared/.bkit/.env.example +108 -0
  204. package/.bkit/shared/.claude/bkit-cloud.md +117 -0
  205. package/.bkit/shared/.claude/settings.json +88 -0
  206. package/.bkit/shared/.codex/hooks.json +26 -0
  207. package/.bkit/shared/.cursor/bkit-cloud.md +84 -0
  208. package/.bkit/shared/.cursor/hooks.json +26 -0
  209. package/.bkit/shared/.cursor/mcp.json +15 -0
  210. package/.bkit/shared/.cursor/rules/bkit-rules.mdc +12 -0
  211. package/.bkit/shared/.gitattributes +37 -0
  212. package/.bkit/shared/.mcp.json +16 -0
  213. package/.bkit/shared/.opencode/opencode.json +62 -0
  214. package/.bkit/shared/CLAUDE.md +11 -0
  215. package/.bkit/shared/LICENSE.md +22 -0
  216. package/.bkit/shared/docs/architecture.md +19 -0
  217. package/.bkit/shared/docs/data-schema.md +19 -0
  218. package/.bkit/shared/docs/deployments.md +438 -0
  219. package/.bkit/shared/docs/design.md +39 -0
  220. package/.bkit/shared/docs/noise.md +19 -0
  221. package/.bkit/shared/docs/observability.md +25 -0
  222. package/.bkit/shared/docs/security.md +42 -0
  223. package/.bkit/shared/docs/setup.md +30 -0
  224. package/.bkit/shared/docs/technology.md +18 -0
  225. package/.bkit/shared/docs/testing.md +413 -0
  226. package/.bkit/shared/gitignore +92 -0
  227. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +192 -0
  228. package/.bkit/templates/.cursor/Dockerfile +68 -0
  229. package/.bkit/templates/.cursor/environment.json +6 -0
  230. package/.bkit/templates/.cursor/settings.json +11 -0
  231. package/.bkit/templates/.envrc +7 -0
  232. package/.bkit/templates/.github/dependabot.yml +52 -0
  233. package/.bkit/templates/.github/renovate.json5 +239 -0
  234. package/.bkit/templates/.github/workflows/bkit-ci.yml +1082 -0
  235. package/.bkit/templates/.github/workflows/bkit-cloud.yml +566 -0
  236. package/.bkit/templates/.github/workflows/bkit-renovate.yml +107 -0
  237. package/.bkit/templates/.graphifyignore +108 -0
  238. package/.bkit/templates/.husky/pre-commit +16 -0
  239. package/.bkit/templates/.husky/pre-push +91 -0
  240. package/.bkit/templates/.lintstagedrc.json +3 -0
  241. package/.bkit/templates/.prettierignore +41 -0
  242. package/.bkit/templates/.serena/project.yml +243 -0
  243. package/.bkit/templates/.vale/styles/House/Filler.yml +11 -0
  244. package/.bkit/templates/.vale/styles/House/Hedging.yml +12 -0
  245. package/.bkit/templates/.vale/styles/House/LLMSlop.yml +13 -0
  246. package/.bkit/templates/.vale/styles/House/Verbose.yml +12 -0
  247. package/.bkit/templates/.vale.ini +67 -0
  248. package/.bkit/templates/LICENSE.md +22 -0
  249. package/.bkit/templates/context/bkit-cloudrun.md +84 -0
  250. package/.bkit/templates/context/bkit-expo.md +186 -0
  251. package/.bkit/templates/context/bkit-github.md +79 -0
  252. package/.bkit/templates/context/bkit-inngest.md +45 -0
  253. package/.bkit/templates/context/bkit-maestro.md +76 -0
  254. package/.bkit/templates/context/bkit-playwright.md +62 -0
  255. package/.bkit/templates/context/bkit-resend.md +36 -0
  256. package/.bkit/templates/context/bkit-sentry.md +65 -0
  257. package/.bkit/templates/context/bkit-serena.md +33 -0
  258. package/.bkit/templates/context/bkit-stripe.md +36 -0
  259. package/.bkit/templates/context/bkit-supabase.md +59 -0
  260. package/.bkit/templates/context/bkit-tavily.md +49 -0
  261. package/.bkit/templates/context/bkit-vercel.md +64 -0
  262. package/.bkit/templates/docs/capabilities.md +72 -0
  263. package/.bkit/templates/scripts/ci/accepted-divergences.json +21 -0
  264. package/.bkit/templates/scripts/ci/check-accepted-divergences.mjs +152 -0
  265. package/.bkit/templates/scripts/ci/check-accepted-divergences.test.mjs +130 -0
  266. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.mjs +98 -0
  267. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.test.mjs +86 -0
  268. package/.bkit/templates/scripts/graphify/bkit-graph-drift-rules.json +23 -0
  269. package/.bkit/templates/scripts/graphify/bkit-graph-drift.py +208 -0
  270. package/.bkit/templates/scripts/graphify/bkit-graph-eager-rules.json +35 -0
  271. package/.bkit/templates/scripts/graphify/bkit-graph-eager.py +236 -0
  272. package/.bkit/templates/scripts/graphify/bkit-graph-external-rules.json +17 -0
  273. package/.bkit/templates/scripts/graphify/bkit-graph-imports.py +290 -0
  274. package/.bkit/templates/scripts/graphify/bkit-graph-pre-push.sh +19 -0
  275. package/.bkit/templates/scripts/graphify/bkit-graph-repair.py +120 -0
  276. package/.bkit/templates/scripts/graphify/bkit-graph-surface.py +232 -0
  277. package/.bkit/templates/scripts/graphify/bkit-graphify-graphml.py +36 -0
  278. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +927 -0
  279. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +351 -0
  280. package/.bkit/templates/scripts/launchd/ai.bkit.launchd.plist +26 -0
  281. package/.bkit/templates/scripts/launchd/bkit-launchd-env.sh +53 -0
  282. package/.bkit/templates/scripts/launchd/launchd.env.example +13 -0
  283. package/.bkit/templates/scripts/prettier/bkit-insert-ignore.mjs +275 -0
  284. package/.bkit/templates/scripts/secrets/bkit-secrets.config.mjs +66 -0
  285. package/.bkit/templates/scripts/secrets/bkit-secrets.mjs +785 -0
  286. package/.bkit/templates/scripts/serena/bkit-serena-mcp.sh +30 -0
  287. package/.bkit/templates/scripts/serena/bkit-serena.mcp.json +9 -0
  288. package/.bkit/templates/scripts/slop/bkit-slop-type-suppression.mjs +286 -0
  289. package/.bkit/templates/slop-scan.config.json +120 -0
  290. package/CHANGELOG.md +1486 -0
  291. package/LICENSE.md +161 -0
  292. package/README.md +185 -2
  293. package/dist/checks/after/auth.js +232 -0
  294. package/dist/checks/after/ci-yml.js +718 -0
  295. package/dist/checks/after/github.js +400 -0
  296. package/dist/checks/after/index.js +447 -0
  297. package/dist/checks/after/managed.js +187 -0
  298. package/dist/checks/after/tools.js +351 -0
  299. package/dist/checks/after/vercel.js +102 -0
  300. package/dist/checks/before/context-fetch.js +426 -0
  301. package/dist/checks/before/env.js +173 -0
  302. package/dist/checks/before/files.js +185 -0
  303. package/dist/checks/before/index.js +162 -0
  304. package/dist/checks/before/mcp.js +111 -0
  305. package/dist/checks/before/repo.js +71 -0
  306. package/dist/checks/before/version.js +60 -0
  307. package/dist/checks/status-holes.js +393 -0
  308. package/dist/cli.js +692 -0
  309. package/dist/commands/analysis.js +325 -0
  310. package/dist/commands/ci/ci.js +438 -0
  311. package/dist/commands/comply.js +310 -0
  312. package/dist/commands/harvest.js +354 -0
  313. package/dist/commands/install/check.js +61 -0
  314. package/dist/commands/install/doctor.js +207 -0
  315. package/dist/commands/install/install.js +461 -0
  316. package/dist/commands/install/uninstall.js +815 -0
  317. package/dist/commands/install/upgrade.js +771 -0
  318. package/dist/commands/launch.js +118 -0
  319. package/dist/commands/lib.js +362 -0
  320. package/dist/commands/registry.js +50 -0
  321. package/dist/commands/setup/setup.js +158 -0
  322. package/dist/commands/telemetry.js +29 -0
  323. package/dist/commands/workflow/branches.js +1265 -0
  324. package/dist/commands/workflow/context.js +846 -0
  325. package/dist/commands/workflow/counters.js +227 -0
  326. package/dist/commands/workflow/fids.js +224 -0
  327. package/dist/commands/workflow/issues.js +585 -0
  328. package/dist/commands/workflow/ledgers.js +472 -0
  329. package/dist/commands/workflow/locks.js +364 -0
  330. package/dist/commands/workflow/prs.js +904 -0
  331. package/dist/commands/workflow/repo.js +199 -0
  332. package/dist/commands/workflow/roadmap.js +495 -0
  333. package/dist/commands/workflow/runs.js +1717 -0
  334. package/dist/commands/workflow/runtime.js +257 -0
  335. package/dist/commands/workflow/skills.js +110 -0
  336. package/dist/commands/workflow/status.js +392 -0
  337. package/dist/commands/workflow/steps.js +1093 -0
  338. package/dist/commands/workflow/tests.js +144 -0
  339. package/dist/commands/workflow/workflows.js +1342 -0
  340. package/dist/commands/workflow/workstreams.js +141 -0
  341. package/dist/commands/workflow/worktrees.js +473 -0
  342. package/dist/install/cloud-env.js +819 -0
  343. package/dist/install/managed-block.js +182 -0
  344. package/dist/install/manifest.js +376 -0
  345. package/dist/install/modules/claude.js +288 -0
  346. package/dist/install/modules/cloud.js +152 -0
  347. package/dist/install/modules/codex.js +193 -0
  348. package/dist/install/modules/core.js +511 -0
  349. package/dist/install/modules/cursor.js +186 -0
  350. package/dist/install/modules/index.js +152 -0
  351. package/dist/install/modules/opencode.js +504 -0
  352. package/dist/install/placeholders.js +87 -0
  353. package/dist/install/template-copies.js +106 -0
  354. package/dist/install/version-file.js +204 -0
  355. package/dist/install/write.js +342 -0
  356. package/dist/ledgers/clamp-log.js +27 -0
  357. package/dist/ledgers/status.js +156 -0
  358. package/dist/ledgers/telemetry.js +637 -0
  359. package/dist/render/hosts.js +339 -0
  360. package/dist/render/models.js +288 -0
  361. package/dist/render/parts.js +33 -0
  362. package/dist/render/trackers.js +135 -0
  363. package/dist/shared/egress.js +299 -0
  364. package/dist/shared/json.js +16 -0
  365. package/dist/shared/log-prefix.js +7 -0
  366. package/dist/shared/package-json.js +22 -0
  367. package/dist/shared/package-manager.js +32 -0
  368. package/dist/shared/package-roots.js +145 -0
  369. package/dist/shared/protected-paths.js +153 -0
  370. package/dist/shared/settings.js +44 -0
  371. package/dist/shared/timeouts.js +19 -0
  372. package/dist/tools/wording.js +680 -0
  373. package/package.json +101 -4
@@ -0,0 +1,1717 @@
1
+ // bkit runs wait|dispatch|revalidate|gate|mirror|declared|context — CI runs on
2
+ // GitHub Actions, and the context an auto-routed run starts from.
3
+ //
4
+ // Three questions, answered against `gh`, never against prose:
5
+ // wait has a CI run appeared (or finished) yet? Bounded poll; a runtime
6
+ // that cannot wait hands the poll back to the agent's turn loop.
7
+ // dispatch after build / debug's last push, did CI start on the pushed head?
8
+ // The CI-Dispatch Gate: poll, one clean re-trigger, a named verdict.
9
+ // gate may ship merge? The capstone job must be present and green at the
10
+ // head — one exit code per refusal reason, never collapsed. Ship's
11
+ // post-merge check (`--capstone-only`) reads the capstone job alone.
12
+ // `revalidate` is ship's re-validation before the merge gate: pick the head CI must
13
+ // pass at, probe for a run there, dispatch only when none, wait for it. `mirror` is
14
+ // `gate` in a loop, for a release PR that copies the dev push run's verdict;
15
+ // `declared` says whether the repo has a CI workflow file at all; `context` is
16
+ // `/bkit-auto` Step 1.
17
+ //
18
+ // The CI workflow file and the capstone job come from `package.json` `bkit`
19
+ // (`shared/settings.ts`). The "did CI dispatch" probe matches the capstone's lane
20
+ // namespace (`bkit-tests-check` -> any check containing `bkit-tests`), not one lane
21
+ // name and not "any check".
22
+ import * as fs from "node:fs";
23
+ import * as path from "node:path";
24
+ import { statusTimestamp } from "../../ledgers/status.js";
25
+ import { bodySkipToken, commitMessage, CommandError, EXIT, git, parseJson, runGh, runGit, SKIP_CI_TOKEN, } from "../lib.js";
26
+ import { readBkitConfig } from "../../shared/settings.js";
27
+ import { TIMEOUTS } from "../../shared/timeouts.js";
28
+ import { FID_PATTERNS, fromBranch, fromMarker, issueIdOf, readIssueTracker } from "./fids.js";
29
+ import { AUTO_LABEL, AUTO_ROUTE_SUFFIX } from "./issues.js";
30
+ import { checkOnlyBookkeeping } from "./ledgers.js";
31
+ import { closeTransportRow, crossCheckFile, probePr } from "./prs.js";
32
+ import { resolveOwnerRepo, splitSlug } from "./repo.js";
33
+ import { extraField, str } from "./status.js";
34
+ import { writeStepRow } from "./steps.js";
35
+ const GH_MISSING = "gh is not on PATH — use the mapped GitHub MCP tool instead";
36
+ /** Not JSON reads as undefined: every caller treats that as an API error, distinct from an empty answer. */
37
+ function jsonOrUndefined(raw) {
38
+ const parsed = parseJson(raw);
39
+ return parsed.ok ? parsed.value : undefined;
40
+ }
41
+ const obj = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : {};
42
+ const arr = (v) => (Array.isArray(v) ? v : []);
43
+ const text = (v) => (typeof v === "string" ? v : "");
44
+ /** Keeps `/` readable (GitHub accepts it raw in a query value) and escapes the rest. */
45
+ const queryValue = (v) => encodeURIComponent(v).replace(/%2F/gi, "/");
46
+ // ---------------------------------------------------------------------------
47
+ // Config and repo facts
48
+ // ---------------------------------------------------------------------------
49
+ /** The checkout to read `package.json` and `.github/workflows/` from: the worktree top, or cwd outside git. */
50
+ const checkoutRoot = (cwd) => git(cwd, ["rev-parse", "--show-toplevel"]) ?? cwd;
51
+ /** The lane namespace the dispatch probe matches: the capstone minus its last `-segment`. */
52
+ export function checkNamespace(capstoneJob) {
53
+ const i = capstoneJob.lastIndexOf("-");
54
+ return i > 0 ? capstoneJob.slice(0, i) : capstoneJob;
55
+ }
56
+ /** Whether `.github/workflows/<bkit.ciWorkflow>` exists — the only honest ground for a `no-ci` pass. */
57
+ export function ciDeclared(root) {
58
+ const { ciWorkflow } = readBkitConfig(root);
59
+ const rel = path.join(".github", "workflows", ciWorkflow);
60
+ return { declared: fs.existsSync(path.join(root, rel)), ciWorkflow, path: rel };
61
+ }
62
+ /** Skip-token scan of a landed commit's body (see `bodySkipToken`). */
63
+ export function scanBody(cwd, sha) {
64
+ const token = bodySkipToken(cwd, sha);
65
+ return token === undefined ? "error" : token ? "skip-token-found" : "clean";
66
+ }
67
+ /** One poll of `target`. PR targets read the PR's check rollup; run targets read the CI workflow's runs at a head. */
68
+ export function pollOnce(target, gh) {
69
+ if (target.kind === "pr-present" || target.kind === "pr-completed") {
70
+ const res = gh(["pr", "view", String(target.pr), "--json", "statusCheckRollup"]);
71
+ if (res.missing)
72
+ return { state: "missing" };
73
+ const data = res.ok ? jsonOrUndefined(res.stdout) : undefined;
74
+ if (data === undefined)
75
+ return { state: "err" };
76
+ const checks = arr(obj(data).statusCheckRollup).map(obj);
77
+ if (target.kind === "pr-present") {
78
+ const ns = target.namespace.toLowerCase();
79
+ const hits = checks.filter((c) => text(c.name || c.context)
80
+ .toLowerCase()
81
+ .includes(ns));
82
+ return { state: hits.length > 0 ? "found" : "none", checks: checks.length };
83
+ }
84
+ // A check is open while its run has not completed, or its commit status is pending.
85
+ const open = checks.filter((c) => (text(c.status) || "COMPLETED") !== "COMPLETED" || text(c.state) === "PENDING");
86
+ return { state: open.length === 0 ? "found" : "none", checks: checks.length };
87
+ }
88
+ const res = gh([
89
+ "run",
90
+ "list",
91
+ "--branch",
92
+ String(target.branch),
93
+ "--workflow",
94
+ target.ciWorkflow,
95
+ "--limit",
96
+ "20",
97
+ "--json",
98
+ "status,conclusion,headSha",
99
+ ]);
100
+ if (res.missing)
101
+ return { state: "missing" };
102
+ const data = res.ok ? jsonOrUndefined(res.stdout) : undefined;
103
+ if (!Array.isArray(data))
104
+ return { state: "err" };
105
+ // Head-anchored: without it a completed run from a superseded head would pass.
106
+ const atHead = data.map(obj).filter((r) => r.headSha === target.head);
107
+ if (target.kind === "run-present")
108
+ return { state: atHead.length > 0 ? "found" : "none" };
109
+ const latest = atHead[0];
110
+ return latest && latest.status === "completed"
111
+ ? { state: "found", conclusion: text(latest.conclusion) || null }
112
+ : { state: "none" };
113
+ }
114
+ /** Sleeps `ms` and returns how long it really took. */
115
+ export const realSleep = (ms) => new Promise((resolve) => {
116
+ const t0 = Date.now();
117
+ setTimeout(() => resolve(Date.now() - t0), ms);
118
+ });
119
+ /** Slack before a sleep counts as blocked (the shell wrapped each sleep in `timeout interval+5`). */
120
+ const SLEEP_SLACK_MS = 5000;
121
+ /**
122
+ * Poll until found or the budget is spent: `ceil(budget / interval)` attempts,
123
+ * no sleep after the last one. `once` polls a single time, for an agent turn loop.
124
+ */
125
+ export async function waitLoop(opts, poll, sleep, log) {
126
+ const out = {
127
+ result: "none",
128
+ attempts: 0,
129
+ elapsedS: 0,
130
+ allErrored: true,
131
+ blocked: false,
132
+ ghMissing: false,
133
+ conclusion: null,
134
+ checks: null,
135
+ };
136
+ const max = opts.once ? 1 : Math.max(1, Math.ceil(opts.budgetS / opts.intervalS));
137
+ while (out.attempts < max) {
138
+ out.attempts++;
139
+ const p = poll();
140
+ if (p.state === "missing") {
141
+ out.ghMissing = true;
142
+ out.result = "err";
143
+ return out;
144
+ }
145
+ if (p.state !== "err")
146
+ out.allErrored = false;
147
+ if (p.checks !== undefined)
148
+ out.checks = p.checks;
149
+ log(`attempt ${out.attempts}: ${p.state} (elapsed ${out.elapsedS}s)`);
150
+ if (p.state === "found") {
151
+ out.result = "found";
152
+ out.conclusion = p.conclusion ?? null;
153
+ return out;
154
+ }
155
+ if (out.attempts >= max)
156
+ break;
157
+ const slept = await sleep(opts.intervalS * 1000);
158
+ if (slept > opts.intervalS * 1000 + SLEEP_SLACK_MS) {
159
+ log(`sleep did not return within ${opts.intervalS + 5}s — this runtime cannot wait here; resolve the poll in the agent turn loop`);
160
+ out.blocked = true;
161
+ out.result = "err";
162
+ return out;
163
+ }
164
+ out.elapsedS += opts.intervalS;
165
+ }
166
+ out.result = out.allErrored ? "err" : "none";
167
+ return out;
168
+ }
169
+ /** The open PR from the current branch into dev, or null. */
170
+ function currentPr(cwd, gh) {
171
+ const branch = git(cwd, ["branch", "--show-current"]);
172
+ if (!branch)
173
+ return { pr: null, missing: false };
174
+ const res = gh(["pr", "list", "--head", branch, "--base", "dev", "--json", "number"]);
175
+ if (res.missing)
176
+ return { pr: null, missing: true };
177
+ const n = obj(arr(res.ok ? jsonOrUndefined(res.stdout) : undefined)[0]).number;
178
+ return { pr: typeof n === "number" ? String(n) : null, missing: false };
179
+ }
180
+ /** Exit code: the re-trigger commit or its push failed. */
181
+ export const EXIT_RETRIGGER_FAILED = 6;
182
+ function pushCurrentBranch(cwd) {
183
+ const branch = git(cwd, ["branch", "--show-current"]);
184
+ if (!branch)
185
+ return false;
186
+ // Shared branches never force; a feature branch is rewritten only by this run.
187
+ const args = branch === "dev" || branch === "main"
188
+ ? ["push", "origin", branch]
189
+ : ["push", "--force-with-lease", "origin", branch];
190
+ return runGit(cwd, args).ok;
191
+ }
192
+ /**
193
+ * The CI-Dispatch Gate after build / debug's last push. Never pushes after the
194
+ * verdict: a later commit would move the PR head away from the run it proved.
195
+ */
196
+ export async function ciDispatchGate(o, deps) {
197
+ const root = checkoutRoot(o.cwd);
198
+ const { capstoneJob } = readBkitConfig(root);
199
+ const declared = ciDeclared(root);
200
+ const head = () => git(o.cwd, ["rev-parse", "HEAD"]) ?? "";
201
+ const res = {
202
+ phase: "done",
203
+ handoff: 0,
204
+ ciDispatch: null,
205
+ head: head(),
206
+ attempts: 0,
207
+ retrigger: o.retriggered,
208
+ ciWorkflow: declared.ciWorkflow,
209
+ };
210
+ const target = {
211
+ kind: "pr-present",
212
+ pr: o.pr ?? undefined,
213
+ ciWorkflow: declared.ciWorkflow,
214
+ namespace: checkNamespace(capstoneJob),
215
+ };
216
+ const poll = async (phase) => {
217
+ // A supplied result answers only the poll that was handed off; later polls run fresh.
218
+ if (o.supplied && (phase === "repoll") === o.retriggered) {
219
+ deps.log(`poll result supplied by the agent turn loop: ${o.supplied.pollResult} (attempts ${o.supplied.attempts})`);
220
+ return o.supplied;
221
+ }
222
+ // No PR to read is the shell's empty-PR poll: zero attempts, all errored.
223
+ if (o.pr === null)
224
+ return { pollResult: "err", attempts: 0, allErrored: true };
225
+ deps.log(`polling for a ${target.namespace} check on PR #${o.pr} (budget ${o.budgetS}s, interval ${o.intervalS}s)`);
226
+ const w = await waitLoop({ budgetS: o.budgetS, intervalS: o.intervalS, once: false }, () => pollOnce(target, deps.gh), deps.sleep, deps.log);
227
+ if (w.blocked || w.ghMissing) {
228
+ res.phase = phase;
229
+ res.handoff = w.ghMissing ? EXIT.USE_MCP : EXIT.AGENT_WAIT;
230
+ res.attempts += w.attempts;
231
+ return null;
232
+ }
233
+ return { pollResult: w.result, attempts: w.attempts, allErrored: w.allErrored };
234
+ };
235
+ const verdict = (outcome, reason) => {
236
+ res.ciDispatch = {
237
+ outcome,
238
+ head: res.head,
239
+ attempts: res.attempts,
240
+ retrigger: res.retrigger,
241
+ ...(reason ? { reason } : {}),
242
+ };
243
+ deps.log(`verdict: ${outcome}${reason ? `(${reason})` : ""} head=${res.head} attempts=${res.attempts} retrigger=${res.retrigger}`);
244
+ return res;
245
+ };
246
+ if (!o.retriggered) {
247
+ const first = await poll("poll");
248
+ if (first === null)
249
+ return res;
250
+ res.attempts = first.attempts;
251
+ if (first.pollResult === "found")
252
+ return verdict("dispatched");
253
+ if (first.allErrored) {
254
+ deps.log("unresolved(gh-error): every poll errored — gh unavailable or unauthenticated");
255
+ return verdict("unresolved", "gh-error");
256
+ }
257
+ if (SKIP_CI_TOKEN.test(commitMessage(o.cwd, res.head) ?? "")) {
258
+ deps.log("unresolved(timeout-dirty): no run and the pushed head carries a CI suppressor — not re-triggering a dirty head");
259
+ return verdict("unresolved", "timeout-dirty");
260
+ }
261
+ const committed = runGit(o.cwd, [
262
+ "commit",
263
+ "--allow-empty",
264
+ "-m",
265
+ `chore(${o.fid}): re-trigger${o.autoRouteSuffix}`,
266
+ ]).ok;
267
+ if (!committed || !pushCurrentBranch(o.cwd)) {
268
+ deps.log("re-trigger commit or push failed — no verdict; route to the Failure Path");
269
+ res.phase = "repoll";
270
+ res.handoff = EXIT_RETRIGGER_FAILED;
271
+ return res;
272
+ }
273
+ res.retrigger = true;
274
+ res.head = head();
275
+ deps.log("re-trigger pushed; re-polling");
276
+ }
277
+ const prior = res.attempts;
278
+ const second = await poll("repoll");
279
+ if (second === null)
280
+ return res;
281
+ // A supplied re-poll carries the running total; a fresh one adds to the first poll.
282
+ res.attempts = o.retriggered && o.supplied ? second.attempts : prior + second.attempts;
283
+ res.head = head();
284
+ if (SKIP_CI_TOKEN.test(commitMessage(o.cwd, res.head) ?? "")) {
285
+ deps.log("unresolved(retrigger-suppressed): the re-trigger head carries a suppressor — cannot tell no-ci from suppression");
286
+ return verdict("unresolved", "retrigger-suppressed");
287
+ }
288
+ if (second.pollResult === "found")
289
+ return verdict("self-healed");
290
+ if (second.allErrored) {
291
+ deps.log("unresolved(gh-error): every re-poll errored — silence after the re-trigger proves nothing");
292
+ return verdict("unresolved", "gh-error");
293
+ }
294
+ if (declared.declared) {
295
+ 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}`);
296
+ return verdict("unresolved", "ci-declared-no-run");
297
+ }
298
+ deps.log(`no-ci: a clean re-trigger dispatched nothing and ${declared.path} is absent — the repo has no CI workflow (logged pass)`);
299
+ return verdict("no-ci");
300
+ }
301
+ // ---------------------------------------------------------------------------
302
+ // Ship merge gate
303
+ // ---------------------------------------------------------------------------
304
+ /** One exit code per refusal reason — callers route on them, so they never collapse. */
305
+ export const GATE = {
306
+ /** No run of the CI workflow at the head. */
307
+ NO_RUN: 10,
308
+ /** Runs at the head, none completed — poll. */
309
+ IN_PROGRESS: 11,
310
+ /** The selected run, or its capstone, did not conclude success. */
311
+ FAILED: 12,
312
+ /** The selected run has no capstone job — never a vacuous pass. */
313
+ NO_CAPSTONE: 13,
314
+ /** No run at the head, but the branch's latest green is at a superseded head (needs --branch). */
315
+ SUPERSEDED: 14,
316
+ /** The selected run was cancelled. */
317
+ CANCELLED: 15,
318
+ /** A lane named in bkit.shipGateRequiredLanes concluded skipped. */
319
+ LANE_SKIPPED: 16,
320
+ /** --validated is not an ancestor of the head plus bookkeeping-only commits. */
321
+ NOT_BOOKKEEPING: 17,
322
+ /** --pr: the PR title carries a CI-suppressing token (its squash would skip CI on dev). */
323
+ TITLE_SKIP: 18,
324
+ /** API error, rate limit, or auth — distinct from "no run". */
325
+ API_ERROR: 20,
326
+ };
327
+ /** Whether `to` is `from` plus bookkeeping-only commits. `outside` lists the other changed paths. */
328
+ export function onlyBookkeeping(root, o) {
329
+ const check = checkOnlyBookkeeping(root, o);
330
+ switch (check.kind) {
331
+ case "ok":
332
+ return { ok: true, outside: [], reason: "" };
333
+ case "unknown-commit":
334
+ return { ok: false, outside: [], reason: `unknown commit: ${check.ref}` };
335
+ case "not-ancestor":
336
+ return { ok: false, outside: [], reason: `${o.from} is not an ancestor of ${o.to}` };
337
+ case "diff-failed":
338
+ return { ok: false, outside: [], reason: `git diff failed for ${o.from}..${o.to}` };
339
+ case "outside":
340
+ return {
341
+ ok: false,
342
+ outside: check.outside,
343
+ reason: `non-bookkeeping paths changed in ${o.from}..${o.to}`,
344
+ };
345
+ }
346
+ }
347
+ const toRun = (v) => {
348
+ const r = obj(v);
349
+ return {
350
+ id: typeof r.id === "number" ? r.id : null,
351
+ head_sha: text(r.head_sha),
352
+ status: text(r.status),
353
+ conclusion: text(r.conclusion),
354
+ event: text(r.event),
355
+ html_url: text(r.html_url),
356
+ updated_at: text(r.updated_at),
357
+ };
358
+ };
359
+ /** Latest by `updated_at`; ties keep list order, as jq's stable `sort_by | last` does. */
360
+ const latest = (runs) => runs.reduce((best, r) => (!best || r.updated_at >= best.updated_at ? r : best), undefined);
361
+ /**
362
+ * Assert the capstone is present and green at the head. Returns the code; the
363
+ * caller exits with it. Diagnostics go through `log`.
364
+ */
365
+ export function shipGate(o, gh, log) {
366
+ const cfg = readBkitConfig(o.root);
367
+ const r = {
368
+ code: 0,
369
+ passed: false,
370
+ overridden: false,
371
+ head: o.head,
372
+ mergeHead: o.head,
373
+ testedHead: null,
374
+ runId: null,
375
+ runUrl: null,
376
+ conclusion: null,
377
+ capstone: o.capstone || cfg.capstoneJob,
378
+ ciWorkflow: o.ciWorkflow || cfg.ciWorkflow,
379
+ repo: o.repo || null,
380
+ skippedLanes: [],
381
+ nonBookkeepingPaths: [],
382
+ reason: "",
383
+ };
384
+ const requiredLanes = cfg.shipGateRequiredLanes;
385
+ const refuse = (code, reason, runUrl) => {
386
+ log(reason);
387
+ log(`required head: ${r.head}`);
388
+ if (r.mergeHead !== r.head) {
389
+ log(`merge head: ${r.mergeHead} (bookkeeping-only commits on top of the required head)`);
390
+ }
391
+ if (r.testedHead && r.testedHead !== r.head)
392
+ log(`head tested: ${r.testedHead} (SUPERSEDED)`);
393
+ if (runUrl)
394
+ log(`run: ${runUrl}`);
395
+ r.code = code;
396
+ r.reason = reason;
397
+ if (o.override && o.override === r.head)
398
+ return overrideRefusal();
399
+ return r;
400
+ };
401
+ const overrideRefusal = () => {
402
+ const row = JSON.stringify({
403
+ type: "ship-gate-override",
404
+ at: statusTimestamp(),
405
+ head: r.head,
406
+ assertedBy: "bkit runs gate",
407
+ });
408
+ let landed = false;
409
+ if (o.statusFile) {
410
+ try {
411
+ fs.appendFileSync(o.statusFile, `${row}\n`);
412
+ landed = true;
413
+ }
414
+ catch {
415
+ // Unwritable status file: the row goes to stderr below, so the override is never invisible.
416
+ landed = false;
417
+ }
418
+ }
419
+ if (!landed) {
420
+ log(`override audit row (status file unset/unwritable: '${o.statusFile ?? "<unset>"}'), emitting to stderr:`);
421
+ log(row);
422
+ }
423
+ log(`override honoured for head ${r.head} (BKIT_SHIP_GATE_OVERRIDE matches refused head)`);
424
+ r.overridden = true;
425
+ r.passed = true;
426
+ r.code = EXIT.OK;
427
+ return r;
428
+ };
429
+ const apiError = (what, runUrl) => {
430
+ const rate = gh(["api", "rate_limit"]);
431
+ const rl = rate.ok ? obj(obj(jsonOrUndefined(rate.stdout)).rate) : undefined;
432
+ let detail;
433
+ if (!rl) {
434
+ detail =
435
+ "API error — rate_limit query also failed; auth / network / unknown API blip (distinct from 'no run')";
436
+ }
437
+ else if (rl.remaining === 0) {
438
+ detail = `rate limit exhausted (remaining=0, reset at ${String(rl.reset ?? "")}) — dispatch, do not push`;
439
+ }
440
+ else {
441
+ detail = `API error (rate remaining=${String(rl.remaining ?? "")}) — auth / network / unknown; distinct from 'no run'`;
442
+ }
443
+ log(what);
444
+ return refuse(GATE.API_ERROR, detail, runUrl);
445
+ };
446
+ const ghMissing = () => {
447
+ r.code = EXIT.USE_MCP;
448
+ r.reason = GH_MISSING;
449
+ log(GH_MISSING);
450
+ return r;
451
+ };
452
+ /** The run's jobs, or the refusal. `--slurp` turns --paginate's one-document-per-page
453
+ * stream into one array; without it a run with more than 100 jobs hides every page but the first. */
454
+ const readJobs = (run) => {
455
+ const jobsRes = gh([
456
+ "api",
457
+ `/repos/${r.repo}/actions/runs/${run.id}/jobs`,
458
+ "--paginate",
459
+ "--slurp",
460
+ ]);
461
+ if (jobsRes.missing)
462
+ return ghMissing();
463
+ if (!jobsRes.ok) {
464
+ return apiError(`jobs query failed for run ${run.id} — API error (distinct from 'no capstone')`, run.html_url);
465
+ }
466
+ const jobsJson = jsonOrUndefined(jobsRes.stdout);
467
+ if (jobsJson === undefined) {
468
+ return refuse(GATE.API_ERROR, `jobs response for run ${run.id} is not valid JSON`, run.html_url);
469
+ }
470
+ const pages = Array.isArray(jobsJson) ? jobsJson : [jobsJson];
471
+ return pages.flatMap((p) => arr(obj(p).jobs).map(obj));
472
+ };
473
+ /** Capstone-only verdict: the capstone job's own result, whatever the run and its other jobs did. */
474
+ const capstoneVerdict = (run) => {
475
+ const url = run.html_url;
476
+ const jobs = readJobs(run);
477
+ if (!Array.isArray(jobs))
478
+ return jobs;
479
+ const capstone = jobs.find((j) => j.name === r.capstone);
480
+ if (!capstone && run.status !== "completed") {
481
+ return refuse(GATE.IN_PROGRESS, `run ${run.id} at head ${r.head} is ${run.status || "unknown"} and has no capstone job yet — caller may poll`, url);
482
+ }
483
+ if (!capstone) {
484
+ return refuse(GATE.NO_CAPSTONE, `capstone job '${r.capstone}' ABSENT from run ${run.id} at head ${r.head} — never vacuous pass`, url);
485
+ }
486
+ if (text(capstone.status) !== "completed") {
487
+ return refuse(GATE.IN_PROGRESS, `capstone '${r.capstone}' is ${text(capstone.status) || "unknown"} at head ${r.head} — caller may poll`, url);
488
+ }
489
+ if (capstone.conclusion === "cancelled") {
490
+ return refuse(GATE.CANCELLED, `capstone '${r.capstone}' was CANCELLED at head ${r.head}`, url);
491
+ }
492
+ if (capstone.conclusion !== "success") {
493
+ return refuse(GATE.FAILED, `capstone '${r.capstone}' concluded '${text(capstone.conclusion)}' (not success) at head ${r.head}`, url);
494
+ }
495
+ r.passed = true;
496
+ r.reason = `capstone ${r.capstone}=success at head ${r.head} (run ${run.id}, ${url}); other jobs not checked`;
497
+ log(r.reason);
498
+ return r;
499
+ };
500
+ if (!r.repo) {
501
+ const view = gh(["repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner"]);
502
+ if (view.missing)
503
+ return ghMissing();
504
+ r.repo = view.ok ? view.stdout.trim() || null : null;
505
+ if (!r.repo) {
506
+ return refuse(GATE.API_ERROR, "could not resolve repo (pass --repo <o/r> or run inside a gh-authenticated checkout)");
507
+ }
508
+ }
509
+ // 0. Validated-head carry-forward: ship's own [skip ci] bookkeeping commits ride
510
+ // on a head CI already passed, so CI is checked at the validated sha instead.
511
+ if (o.validated && o.validated !== o.head) {
512
+ if (!o.month || !o.fid) {
513
+ throw new CommandError(EXIT.USAGE, "--validated needs --month and --fid (the bookkeeping allow-list is FID-scoped)");
514
+ }
515
+ const book = onlyBookkeeping(o.root, {
516
+ month: o.month,
517
+ fid: o.fid,
518
+ from: o.validated,
519
+ to: o.head,
520
+ });
521
+ if (!book.ok) {
522
+ r.nonBookkeepingPaths = book.outside;
523
+ for (const p of book.outside)
524
+ log(` ${p}`);
525
+ return refuse(GATE.NOT_BOOKKEEPING, `head ${o.head} is not ${o.validated} plus bookkeeping only (${book.reason}) — re-validate at head`);
526
+ }
527
+ log(`head ${o.head} = validated ${o.validated} + bookkeeping only — checking CI at the validated sha`);
528
+ r.head = o.validated;
529
+ }
530
+ // 1. Workflow-scoped, head-keyed run list. --event narrows it in the query AND
531
+ // here, so an API that ignores the parameter still cannot hand back another event's run.
532
+ const base = `/repos/${r.repo}/actions/workflows/${r.ciWorkflow}/runs`;
533
+ const eventQuery = o.event ? `&event=${queryValue(o.event)}` : "";
534
+ const eventLabel = o.event ? ` (event=${o.event})` : "";
535
+ const keepEvent = (runs) => (o.event ? runs.filter((x) => x.event === o.event) : runs);
536
+ const listed = gh(["api", `${base}?head_sha=${queryValue(r.head)}${eventQuery}`]);
537
+ if (listed.missing)
538
+ return ghMissing();
539
+ if (!listed.ok) {
540
+ return apiError(`workflow runs query failed for ${r.repo}/${r.ciWorkflow} at head ${r.head}`);
541
+ }
542
+ const listedJson = jsonOrUndefined(listed.stdout);
543
+ if (listedJson === undefined) {
544
+ log(`workflow runs response for ${r.repo}/${r.ciWorkflow} at head ${r.head} is not valid JSON`);
545
+ return refuse(GATE.API_ERROR, "workflow runs response is not valid JSON");
546
+ }
547
+ const runs = keepEvent(arr(obj(listedJson).workflow_runs).map(toRun));
548
+ const total = o.event ? runs.length : Number(obj(listedJson).total_count ?? 0) || 0;
549
+ if (total === 0) {
550
+ // The head query is filtered server-side, so a superseded head looks exactly
551
+ // like one never validated; only a branch-scoped query tells them apart.
552
+ if (o.branch) {
553
+ const recent = gh([
554
+ "api",
555
+ `${base}?branch=${queryValue(o.branch)}&status=success&per_page=1${eventQuery}`,
556
+ ]);
557
+ const stale = recent.ok
558
+ ? latest(keepEvent(arr(obj(jsonOrUndefined(recent.stdout)).workflow_runs).map(toRun)))
559
+ : undefined;
560
+ if (stale) {
561
+ r.testedHead = stale.head_sha || null;
562
+ return refuse(GATE.SUPERSEDED, `no run at head ${r.head}; latest green on ${o.branch} is at a SUPERSEDED head (${stale.head_sha}) — re-validate`, stale.html_url);
563
+ }
564
+ }
565
+ return refuse(GATE.NO_RUN, `no run of ${r.ciWorkflow}${eventLabel} exists at head ${r.head} (total_count=0)`);
566
+ }
567
+ // 2. The most recent COMPLETED run at the head: a re-dispatch still in flight
568
+ // is newer, and must not mask a run that has in fact completed here. Capstone-only
569
+ // falls back to the run in flight, whose capstone may already have concluded.
570
+ const atHead = runs.filter((x) => x.head_sha === r.head);
571
+ const completed = latest(atHead.filter((x) => x.status === "completed"));
572
+ const selected = completed ?? (o.capstoneOnly ? latest(atHead) : undefined);
573
+ if (!selected) {
574
+ const inFlight = latest(runs);
575
+ return refuse(GATE.IN_PROGRESS, `runs exist at head ${r.head} but none completed (status=${inFlight?.status || "unknown"}) — caller may poll`, inFlight?.html_url);
576
+ }
577
+ r.runId = selected.id;
578
+ r.runUrl = selected.html_url || null;
579
+ r.conclusion = selected.conclusion || null;
580
+ r.testedHead = selected.head_sha || null;
581
+ const url = selected.html_url;
582
+ if (o.capstoneOnly)
583
+ return capstoneVerdict(selected);
584
+ if (selected.conclusion === "failure") {
585
+ return refuse(GATE.FAILED, `selected run concluded FAILURE at head ${r.head}`, url);
586
+ }
587
+ if (selected.conclusion === "cancelled") {
588
+ return refuse(GATE.CANCELLED, `selected run was CANCELLED at head ${r.head} — dispatch, do not push`, url);
589
+ }
590
+ if (selected.conclusion !== "success") {
591
+ return refuse(GATE.FAILED, `selected run concluded '${selected.conclusion}' at head ${r.head} — not validated`, url);
592
+ }
593
+ // 3. Capstone.
594
+ const listedJobs = readJobs(selected);
595
+ if (!Array.isArray(listedJobs))
596
+ return listedJobs;
597
+ const jobs = listedJobs;
598
+ const capstone = jobs.find((j) => j.name === r.capstone);
599
+ if (!capstone) {
600
+ return refuse(GATE.NO_CAPSTONE, `capstone job '${r.capstone}' ABSENT from run ${selected.id} at head ${r.head} — never vacuous pass`, url);
601
+ }
602
+ if (capstone.conclusion !== "success") {
603
+ return refuse(GATE.FAILED, `capstone '${r.capstone}' concluded '${text(capstone.conclusion)}' (not success) at head ${r.head}`, url);
604
+ }
605
+ // 4. Skipped lanes. The jobs API gives no reason for a skip; the capstone takes
606
+ // every lane result as input and owns planned-vs-vacuous, so a skip is reported,
607
+ // and refuses only for a lane the consumer declared required.
608
+ r.skippedLanes = jobs
609
+ .filter((j) => j.name !== r.capstone && j.conclusion === "skipped")
610
+ .map((j) => text(j.name) || "<unnamed>");
611
+ if (r.skippedLanes.length) {
612
+ log(`note: ${r.skippedLanes.length} lane(s) concluded 'skipped' at head ${r.head}: ${r.skippedLanes.join(", ")}`);
613
+ log(`note: capstone '${r.capstone}' is green and owns the planned-vs-vacuous judgement for those lanes`);
614
+ const required = r.skippedLanes.filter((l) => requiredLanes.includes(l));
615
+ if (required.length) {
616
+ log(`declared in bkit.shipGateRequiredLanes: ${requiredLanes.join(",")}`);
617
+ return refuse(GATE.LANE_SKIPPED, `required lane(s) concluded 'skipped' at head ${r.head} — vacuous green: ${required.join(", ")}`, url);
618
+ }
619
+ }
620
+ r.passed = true;
621
+ r.reason = `capstone ${r.capstone}=success at head ${r.head} (run ${selected.id}, ${url})`;
622
+ log(r.reason);
623
+ return r;
624
+ }
625
+ // ---------------------------------------------------------------------------
626
+ // Release-PR mirror
627
+ // ---------------------------------------------------------------------------
628
+ /** Exit codes of `mirror`. */
629
+ export const MIRROR = {
630
+ /** No push run at the head after --absent-minutes. */
631
+ ABSENT: 3,
632
+ /** Still in progress at --max-minutes. */
633
+ TIMED_OUT: 4,
634
+ /** Three API errors in a row. */
635
+ API_ERRORS: 20,
636
+ };
637
+ /**
638
+ * Wait for the branch's push run at the head and copy its capstone verdict. The
639
+ * gate owns run selection and its codes; this owns waiting. The override never
640
+ * reaches the gate: it is a per-head escape for ship, never a way to green a required check.
641
+ */
642
+ export async function mirrorPushRun(o, deps) {
643
+ const start = deps.now();
644
+ const out = {
645
+ code: EXIT.NO,
646
+ passed: false,
647
+ gateCode: -1,
648
+ polls: 0,
649
+ elapsedMinutes: 0,
650
+ };
651
+ let apiErrors = 0;
652
+ let lastState = "";
653
+ for (;;) {
654
+ const g = deps.gate();
655
+ out.polls++;
656
+ out.gateCode = g.code;
657
+ out.elapsedMinutes = Math.floor((deps.now() - start) / 60000);
658
+ const elapsed = out.elapsedMinutes;
659
+ if (g.code === EXIT.OK) {
660
+ deps.log(`${o.branch} push run at ${o.head} passed its capstone — release PR mirrors green.`);
661
+ out.code = EXIT.OK;
662
+ out.passed = true;
663
+ return out;
664
+ }
665
+ if (g.code === GATE.IN_PROGRESS) {
666
+ apiErrors = 0;
667
+ if (lastState !== "running") {
668
+ deps.log(`${o.branch} push run at ${o.head} is in progress — waiting (up to ${o.maxMinutes}m).`);
669
+ }
670
+ lastState = "running";
671
+ }
672
+ else if (g.code === GATE.NO_RUN || g.code === GATE.SUPERSEDED) {
673
+ apiErrors = 0;
674
+ if (elapsed >= o.absentMinutes) {
675
+ deps.log(g.reason);
676
+ deps.log(`no ${o.branch} push run exists at ${o.head} after ${elapsed}m. A [skip ci] commit at the ${o.branch} tip dispatches none: push a commit without it to ${o.branch}, then re-run this check.`);
677
+ out.code = MIRROR.ABSENT;
678
+ return out;
679
+ }
680
+ if (lastState !== "absent") {
681
+ deps.log(`no ${o.branch} push run at ${o.head} yet — waiting up to ${o.absentMinutes}m for one to appear.`);
682
+ }
683
+ lastState = "absent";
684
+ }
685
+ else if (g.code === GATE.API_ERROR) {
686
+ apiErrors++;
687
+ if (apiErrors >= 3) {
688
+ deps.log(g.reason);
689
+ deps.log(`GitHub API failed ${apiErrors} times in a row — cannot read the ${o.branch} push run.`);
690
+ out.code = MIRROR.API_ERRORS;
691
+ return out;
692
+ }
693
+ deps.log(`GitHub API error (${apiErrors}/3) — retrying.`);
694
+ }
695
+ else {
696
+ deps.log(g.reason);
697
+ deps.log(`${o.branch} push run at ${o.head} is not green (gate exit ${g.code}) — fix ${o.branch}, or re-run the failed push run, then re-run this check.`);
698
+ out.code = EXIT.NO;
699
+ return out;
700
+ }
701
+ if (elapsed >= o.maxMinutes) {
702
+ deps.log(`${o.branch} push run at ${o.head} still not finished after ${elapsed}m (limit ${o.maxMinutes}m).`);
703
+ out.code = MIRROR.TIMED_OUT;
704
+ return out;
705
+ }
706
+ await deps.sleep(o.intervalS * 1000);
707
+ }
708
+ }
709
+ // ---------------------------------------------------------------------------
710
+ // Command
711
+ // ---------------------------------------------------------------------------
712
+ /** Exit code: `wait --dispatch-if-absent` found no run and `gh workflow run` failed. */
713
+ export const EXIT_TRIGGER_FAILED = 5;
714
+ /** Exit code: the dispatch verdict passed, but the pushed head's body carries a skip token. */
715
+ export const EXIT_SKIP_TOKEN = 4;
716
+ /** Exit code: the pushed head's commit message could not be read for the body scan. */
717
+ export const EXIT_SCAN_ERROR = 5;
718
+ const wholeNumber = (v, flag, fallback, min = 0) => {
719
+ if (v === undefined)
720
+ return fallback;
721
+ const s = String(v);
722
+ if (!/^[0-9]+$/.test(s) || Number(s) < min) {
723
+ throw new CommandError(EXIT.USAGE, `--${flag} takes a whole number >= ${min} (got "${s}")`);
724
+ }
725
+ return Number(s);
726
+ };
727
+ const HEAD_FLAG = { name: "head", type: "string", help: "commit SHA" };
728
+ const REPO_FLAG = {
729
+ name: "repo",
730
+ type: "string",
731
+ help: "owner/repo (default: gh repo view)",
732
+ };
733
+ const CI_WORKFLOW_FLAG = {
734
+ name: "ci-workflow",
735
+ type: "string",
736
+ help: "CI workflow file (default: package.json bkit.ciWorkflow)",
737
+ };
738
+ const CAPSTONE_FLAG = {
739
+ name: "capstone",
740
+ type: "string",
741
+ help: "capstone job name (default: package.json bkit.capstoneJob)",
742
+ };
743
+ const BUDGET_FLAG = { name: "budget-s", type: "string", help: "poll budget in seconds" };
744
+ const INTERVAL_FLAG = {
745
+ name: "interval-s",
746
+ type: "string",
747
+ help: "seconds between polls (>= 1)",
748
+ };
749
+ const deps = (ctx) => ({
750
+ gh: (args) => runGh(ctx.cwd, args),
751
+ sleep: realSleep,
752
+ log: ctx.log,
753
+ });
754
+ /** Defaults per wait target: the dispatch probe's 60/10, ship's probe and CI-completion budgets. */
755
+ const WAIT_DEFAULTS = {
756
+ "pr-present": { budgetS: 60, intervalS: 10 },
757
+ "pr-completed": {
758
+ budgetS: TIMEOUTS.SHIP_CI_WAIT_TIMEOUT_S,
759
+ intervalS: TIMEOUTS.SHIP_POLL_INTERVAL_S,
760
+ },
761
+ "run-present": {
762
+ budgetS: TIMEOUTS.SHIP_PROBE_ATTEMPTS * TIMEOUTS.SHIP_PROBE_INTERVAL_S,
763
+ intervalS: TIMEOUTS.SHIP_PROBE_INTERVAL_S,
764
+ },
765
+ "run-completed": {
766
+ budgetS: TIMEOUTS.SHIP_CI_WAIT_TIMEOUT_S,
767
+ intervalS: TIMEOUTS.SHIP_POLL_INTERVAL_S,
768
+ },
769
+ };
770
+ /** One bounded wait (`runs wait`), its exit code and printed object. */
771
+ async function waitFor(cwd, i, d) {
772
+ const { pr, head, branch } = i;
773
+ if (pr === "" || head === "")
774
+ throw new CommandError(EXIT.USAGE, "--pr / --head must not be empty");
775
+ if ((pr === undefined) === (head === undefined)) {
776
+ throw new CommandError(EXIT.USAGE, "give exactly one of --pr or --head");
777
+ }
778
+ if (head !== undefined && !branch)
779
+ throw new CommandError(EXIT.USAGE, "--head needs --branch");
780
+ const until = i.until ?? "present";
781
+ if (until !== "present" && until !== "completed") {
782
+ throw new CommandError(EXIT.USAGE, "--until must be present or completed");
783
+ }
784
+ const kind = `${pr !== undefined ? "pr" : "run"}-${until}`;
785
+ if (i.dispatchIfAbsent && (kind !== "run-present" || i.once === true)) {
786
+ // One turn-loop poll is not a probe: dispatching on it would duplicate a run still registering.
787
+ throw new CommandError(EXIT.USAGE, "--dispatch-if-absent needs --head --branch --until=present, without --once");
788
+ }
789
+ const cfg = readBkitConfig(checkoutRoot(cwd));
790
+ const ciWorkflow = cfg.ciWorkflow;
791
+ const target = {
792
+ kind,
793
+ pr,
794
+ head,
795
+ branch,
796
+ ciWorkflow,
797
+ namespace: checkNamespace(cfg.capstoneJob),
798
+ };
799
+ const budgetS = wholeNumber(i.budgetS, "budget-s", WAIT_DEFAULTS[kind].budgetS);
800
+ const intervalS = wholeNumber(i.intervalS, "interval-s", WAIT_DEFAULTS[kind].intervalS, 1);
801
+ const w = await waitLoop({ budgetS, intervalS, once: i.once === true }, () => pollOnce(target, d.gh), d.sleep, d.log);
802
+ let dispatched = false;
803
+ if (i.dispatchIfAbsent && w.result !== "found" && !w.blocked && !w.ghMissing) {
804
+ d.log(`no run at ${head} after ${w.attempts} probes (probe=${w.result}) — dispatching ${ciWorkflow} on ${branch}`);
805
+ const run = d.gh(["workflow", "run", ciWorkflow, "--ref", String(branch)]);
806
+ if (run.missing)
807
+ w.ghMissing = true;
808
+ else if (!run.ok) {
809
+ d.log(`gh workflow run failed (403 = actions:write scope): ${run.stderr.trim()}`);
810
+ return { code: EXIT_TRIGGER_FAILED, out: { ...waitOutput(w, kind), dispatched } };
811
+ }
812
+ else
813
+ dispatched = true;
814
+ }
815
+ const out = { ...waitOutput(w, kind), dispatched };
816
+ if (w.ghMissing) {
817
+ d.log(GH_MISSING);
818
+ return { code: EXIT.USE_MCP, out };
819
+ }
820
+ if (w.result === "found" || dispatched)
821
+ return { code: EXIT.OK, out };
822
+ if (w.blocked || i.once === true)
823
+ return { code: EXIT.AGENT_WAIT, out };
824
+ return { code: EXIT.NO, out };
825
+ }
826
+ async function runWait(ctx) {
827
+ const f = ctx.flags;
828
+ const r = await waitFor(ctx.cwd, {
829
+ pr: str(f.pr),
830
+ head: str(f.head),
831
+ branch: str(f.branch),
832
+ until: str(f.until),
833
+ budgetS: f.budgetS,
834
+ intervalS: f.intervalS,
835
+ once: f.once === true,
836
+ dispatchIfAbsent: f.dispatchIfAbsent === true,
837
+ }, deps(ctx));
838
+ ctx.emit(r.out);
839
+ return r.code;
840
+ }
841
+ const waitOutput = (w, kind) => ({
842
+ result: w.result,
843
+ target: kind,
844
+ attempts: w.attempts,
845
+ elapsedS: w.elapsedS,
846
+ allErrored: w.allErrored,
847
+ blocked: w.blocked,
848
+ conclusion: w.conclusion,
849
+ checks: w.checks,
850
+ });
851
+ async function runDispatch(ctx) {
852
+ const f = ctx.flags;
853
+ const d = deps(ctx);
854
+ // An empty --pr is the workflow's unresolved PR_NUMBER: derive it, as if omitted.
855
+ let pr = str(f.pr) || null;
856
+ if (pr === null) {
857
+ const found = currentPr(ctx.cwd, d.gh);
858
+ if (found.missing) {
859
+ ctx.log(GH_MISSING);
860
+ return EXIT.USE_MCP;
861
+ }
862
+ pr = found.pr;
863
+ }
864
+ const pollResult = str(f.pollResult);
865
+ if (pollResult !== undefined && !["found", "none", "err"].includes(pollResult)) {
866
+ throw new CommandError(EXIT.USAGE, "--poll-result must be found, none, or err");
867
+ }
868
+ if (pollResult === undefined && (f.attempts !== undefined || f.allErrored === true)) {
869
+ throw new CommandError(EXIT.USAGE, "--attempts / --all-errored go with --poll-result");
870
+ }
871
+ const r = await ciDispatchGate({
872
+ cwd: ctx.cwd,
873
+ pr,
874
+ fid: String(f.fid),
875
+ autoRouteSuffix: (f.label ?? []).includes(AUTO_LABEL)
876
+ ? AUTO_ROUTE_SUFFIX
877
+ : "",
878
+ budgetS: wholeNumber(f.budgetS, "budget-s", 60),
879
+ intervalS: wholeNumber(f.intervalS, "interval-s", 10, 1),
880
+ supplied: pollResult === undefined
881
+ ? undefined
882
+ : {
883
+ pollResult: pollResult,
884
+ attempts: wholeNumber(f.attempts, "attempts", 0),
885
+ allErrored: f.allErrored === true,
886
+ },
887
+ retriggered: f.retriggered === true,
888
+ }, d);
889
+ const scanResult = r.ciDispatch && r.ciDispatch.outcome !== "unresolved" ? scanBody(ctx.cwd, r.head) : null;
890
+ // With --file / --step: the verdict lands on the step's row, and a passed one is
891
+ // cross-checked and recorded as the close transport.
892
+ const file = str(f.file);
893
+ const step = str(f.step);
894
+ if ((file === undefined) !== (step === undefined))
895
+ throw new CommandError(EXIT.USAGE, "--file and --step go together");
896
+ let row = null;
897
+ let transport = null;
898
+ const code = dispatchCode(r, pr, scanResult, ctx.log);
899
+ if (file !== undefined && r.ciDispatch !== null) {
900
+ const status = path.resolve(ctx.cwd, file);
901
+ row = writeStepRow(ctx.cwd, {
902
+ file: status,
903
+ workflow: String(f.workflow ?? "build"),
904
+ step: step,
905
+ artifacts: f.artifact ?? [],
906
+ extras: {
907
+ ...Object.fromEntries((f.field ?? []).map(extraField)),
908
+ ciDispatch: r.ciDispatch,
909
+ },
910
+ commit: "none",
911
+ }, ctx.log).row;
912
+ if (code === EXIT.OK || code === EXIT_SKIP_TOKEN) {
913
+ const check = crossCheckFile(status, "gh", ctx.log);
914
+ if (!check.ok) {
915
+ ctx.log("close transport cross-check failed");
916
+ ctx.emit({
917
+ ciDispatch: r.ciDispatch,
918
+ phase: r.phase,
919
+ pr,
920
+ head: r.head,
921
+ attempts: r.attempts,
922
+ retrigger: r.retrigger,
923
+ scanResult,
924
+ ciWorkflow: r.ciWorkflow,
925
+ row,
926
+ transport,
927
+ });
928
+ return EXIT.NO;
929
+ }
930
+ transport = closeTransportRow(status, {
931
+ shape: "push",
932
+ sha: r.head,
933
+ scanResult: scanResult ?? "clean",
934
+ });
935
+ }
936
+ }
937
+ ctx.emit({
938
+ ciDispatch: r.ciDispatch,
939
+ phase: r.phase,
940
+ pr,
941
+ head: r.head,
942
+ attempts: r.attempts,
943
+ retrigger: r.retrigger,
944
+ scanResult,
945
+ ciWorkflow: r.ciWorkflow,
946
+ row,
947
+ transport,
948
+ });
949
+ return code;
950
+ }
951
+ /** The dispatch verdict as an exit code, with its log line. */
952
+ function dispatchCode(r, pr, scanResult, log) {
953
+ if (r.handoff === EXIT.AGENT_WAIT || r.handoff === EXIT.USE_MCP) {
954
+ const again = r.phase === "repoll" ? " --retriggered" : "";
955
+ log(`${r.handoff === EXIT.USE_MCP ? GH_MISSING : "this runtime cannot wait"}: resolve the ${r.phase} each turn with \`bkit runs wait --pr=${pr ?? "<n>"} --once\`, then re-run with --poll-result=<found|none|err> --attempts=<total>${again}`);
956
+ return r.handoff;
957
+ }
958
+ if (r.handoff !== 0)
959
+ return r.handoff;
960
+ if (r.ciDispatch?.outcome === "unresolved") {
961
+ log("unresolved verdict — recorded; route to the Failure Path");
962
+ return EXIT.NO;
963
+ }
964
+ if (scanResult === "error") {
965
+ log(`post-close body scan could not read ${r.head}`);
966
+ return EXIT_SCAN_ERROR;
967
+ }
968
+ if (scanResult === "skip-token-found") {
969
+ log(`landed commit ${r.head} inherited a CI-suppression token in its body`);
970
+ return EXIT_SKIP_TOKEN;
971
+ }
972
+ return EXIT.OK;
973
+ }
974
+ /** Append one typed audit row (ship's gate refusal / merge CI / re-validate rows). */
975
+ function auditRow(file, type, fields) {
976
+ if (!fs.existsSync(file))
977
+ throw new CommandError(EXIT.USAGE, `${file} does not exist`);
978
+ fs.appendFileSync(file, `${JSON.stringify({ type, workflow: "ship", at: statusTimestamp(), ...fields })}\n`);
979
+ }
980
+ function runGate(ctx) {
981
+ const f = ctx.flags;
982
+ const given = [f.head, f.pr, f.squashOf].filter((v) => v !== undefined).length;
983
+ if (given !== 1)
984
+ throw new CommandError(EXIT.USAGE, "give exactly one of --head, --pr, --squash-of");
985
+ const root = checkoutRoot(ctx.cwd);
986
+ const gh = (args) => runGh(ctx.cwd, args);
987
+ const record = str(f.record);
988
+ const recordFile = record === undefined ? undefined : path.resolve(ctx.cwd, record);
989
+ const prNumber = str(f.pr) ?? str(f.squashOf);
990
+ // The head: given, the PR's current head, or the PR's squash commit.
991
+ let head = str(f.head) ?? "";
992
+ let pr;
993
+ if (prNumber !== undefined) {
994
+ if (!/^[1-9][0-9]*$/.test(prNumber))
995
+ throw new CommandError(EXIT.USAGE, "--pr / --squash-of take a PR number");
996
+ pr = probePr(ctx.cwd, { number: prNumber, state: "open" });
997
+ if (pr.kind === "unavailable") {
998
+ ctx.log(pr.message);
999
+ return EXIT.USE_MCP;
1000
+ }
1001
+ const info = pr.kind === "ok" ? pr.pr : undefined;
1002
+ head = (f.squashOf !== undefined ? info?.mergeCommit?.oid : info?.headRefOid) ?? "";
1003
+ if (head === "") {
1004
+ ctx.log(`cannot read the ${f.squashOf !== undefined ? "squash commit" : "head"} of PR ${prNumber}`);
1005
+ ctx.emit({
1006
+ code: GATE.API_ERROR,
1007
+ passed: false,
1008
+ head: null,
1009
+ mergeHead: null,
1010
+ reason: "PR unreadable",
1011
+ });
1012
+ return GATE.API_ERROR;
1013
+ }
1014
+ }
1015
+ if (head === "")
1016
+ throw new CommandError(EXIT.USAGE, "--head needs a non-empty value");
1017
+ // The pre-merge snapshot, written BEFORE the gate decides.
1018
+ const snapshot = str(f.snapshot);
1019
+ if (snapshot !== undefined) {
1020
+ const info = pr?.kind === "ok" ? pr.pr : undefined;
1021
+ const dev = git(ctx.cwd, ["rev-parse", "origin/dev"]) ?? "";
1022
+ const ancestor = runGit(ctx.cwd, ["merge-base", "--is-ancestor", "origin/dev", head]).ok;
1023
+ const ciWorkflow = readBkitConfig(root).ciWorkflow;
1024
+ const runs = gh([
1025
+ "run",
1026
+ "list",
1027
+ "--branch",
1028
+ String(f.branch ?? info?.headRefName ?? ""),
1029
+ "--workflow",
1030
+ ciWorkflow,
1031
+ "--limit",
1032
+ "1",
1033
+ "--json",
1034
+ "databaseId,url",
1035
+ ]);
1036
+ const capstone = obj(arr(runs.ok ? jsonOrUndefined(runs.stdout) : undefined)[0]);
1037
+ const file = path.resolve(ctx.cwd, snapshot);
1038
+ fs.mkdirSync(path.dirname(file), { recursive: true });
1039
+ fs.appendFileSync(file, `${JSON.stringify({
1040
+ type: "ship-pre-merge-snapshot",
1041
+ workflow: "ship",
1042
+ gateHead: head,
1043
+ validatedHead: str(f.validated) ?? "",
1044
+ devSha: dev,
1045
+ ancestor: String(ancestor),
1046
+ capstone,
1047
+ mergeable: info?.mergeable ?? "",
1048
+ })}\n`);
1049
+ }
1050
+ // A title carrying a skip token would squash into a dev commit CI never runs on.
1051
+ const title = pr?.kind === "ok" ? (pr.pr?.title ?? "") : "";
1052
+ const titleToken = f.pr !== undefined ? SKIP_CI_TOKEN.exec(title)?.[0] : undefined;
1053
+ const r = titleToken !== undefined
1054
+ ? {
1055
+ code: GATE.TITLE_SKIP,
1056
+ passed: false,
1057
+ overridden: false,
1058
+ head,
1059
+ mergeHead: head,
1060
+ testedHead: null,
1061
+ runId: null,
1062
+ runUrl: null,
1063
+ conclusion: null,
1064
+ capstone: "",
1065
+ ciWorkflow: "",
1066
+ repo: str(f.repo) ?? null,
1067
+ skippedLanes: [],
1068
+ nonBookkeepingPaths: [],
1069
+ reason: `PR title '${title}' contains the CI-suppressing token ${titleToken}`,
1070
+ }
1071
+ : shipGate({
1072
+ root,
1073
+ head,
1074
+ validated: str(f.validated),
1075
+ month: str(f.month),
1076
+ fid: str(f.fid),
1077
+ repo: str(f.repo),
1078
+ branch: str(f.branch),
1079
+ event: str(f.event),
1080
+ capstoneOnly: f.capstoneOnly === true,
1081
+ override: process.env.BKIT_SHIP_GATE_OVERRIDE || undefined,
1082
+ statusFile: f.file === undefined ? undefined : path.resolve(ctx.cwd, String(f.file)),
1083
+ }, gh, ctx.log);
1084
+ if (titleToken !== undefined)
1085
+ ctx.log(r.reason);
1086
+ if (recordFile !== undefined && r.code !== EXIT.USE_MCP) {
1087
+ if (f.capstoneOnly === true) {
1088
+ const verdict = r.code === EXIT.OK ? "PASS" : "FAIL";
1089
+ auditRow(recordFile, "ship-merge-ci", {
1090
+ sha: head,
1091
+ run: String(r.runId ?? ""),
1092
+ verdict,
1093
+ reason: verdict === "PASS" ? "" : r.reason,
1094
+ });
1095
+ }
1096
+ else if (r.code !== EXIT.OK) {
1097
+ auditRow(recordFile, "ship-gate-refusal", { exitCode: r.code, head: r.mergeHead });
1098
+ }
1099
+ }
1100
+ ctx.emit({ ...r });
1101
+ return r.code;
1102
+ }
1103
+ // ---------------------------------------------------------------------------
1104
+ // revalidate
1105
+ // ---------------------------------------------------------------------------
1106
+ /** Whether dev demands status checks (ruleset or branch protection): CI must then pass at the PR head. */
1107
+ function devRequiresChecks(gh, repo) {
1108
+ const rules = gh(["api", `repos/${repo}/rules/branches/dev`]);
1109
+ const list = rules.ok ? arr(jsonOrUndefined(rules.stdout)) : [];
1110
+ if (list.some((r) => obj(r).type === "required_status_checks"))
1111
+ return true;
1112
+ return gh(["api", `repos/${repo}/branches/dev/protection/required_status_checks`]).ok;
1113
+ }
1114
+ async function runRevalidate(ctx) {
1115
+ const f = ctx.flags;
1116
+ const d = deps(ctx);
1117
+ const branch = String(f.branch);
1118
+ const entry = String(f.entryHead);
1119
+ const codeHead = String(f.codeHead);
1120
+ const reason = str(f.reason) || "head-move";
1121
+ if (!["head-move", "gate-refusal"].includes(reason))
1122
+ throw new CommandError(EXIT.USAGE, "--reason must be head-move or gate-refusal");
1123
+ const status = path.resolve(ctx.cwd, String(f.file));
1124
+ runGit(ctx.cwd, ["fetch", "origin", branch]);
1125
+ const pr = probePr(ctx.cwd, { number: String(f.pr), state: "open" });
1126
+ if (pr.kind === "unavailable") {
1127
+ ctx.log(pr.message);
1128
+ return EXIT.USE_MCP;
1129
+ }
1130
+ const current = pr.kind === "ok" ? (pr.pr?.headRefOid ?? "") : "";
1131
+ if (current === "") {
1132
+ ctx.log("cannot read the PR head — query failed (403 = PAT scope)");
1133
+ return EXIT.NO;
1134
+ }
1135
+ // CI must pass at the code head while the PR head adds bookkeeping only and dev
1136
+ // demands no status checks; otherwise at the PR head.
1137
+ let validated = codeHead;
1138
+ const book = onlyBookkeeping(checkoutRoot(ctx.cwd), {
1139
+ month: String(f.month),
1140
+ fid: String(f.fid),
1141
+ from: codeHead,
1142
+ to: current,
1143
+ });
1144
+ if (!book.ok)
1145
+ validated = current;
1146
+ const repo = str(f.repo) ?? resolveOwnerRepo(ctx.cwd)?.ownerRepo;
1147
+ if (repo !== undefined && devRequiresChecks(d.gh, repo)) {
1148
+ ctx.log(`dev requires status checks — validating at the PR head ${current}`);
1149
+ validated = current;
1150
+ }
1151
+ const out = {
1152
+ validatedHead: validated,
1153
+ currentHead: current,
1154
+ revalidated: false,
1155
+ probe: null,
1156
+ dispatched: false,
1157
+ wait: null,
1158
+ };
1159
+ if (validated !== entry || reason === "gate-refusal") {
1160
+ out.revalidated = true;
1161
+ // Probe first: a run may already exist at this head; dispatch only on none.
1162
+ const probe = await waitFor(ctx.cwd, { head: validated, branch, until: "present", dispatchIfAbsent: true }, d);
1163
+ if (probe.code !== EXIT.OK) {
1164
+ ctx.emit({ ...out, probe: probe.out });
1165
+ return probe.code;
1166
+ }
1167
+ if (probe.out.dispatched === true) {
1168
+ validated = current;
1169
+ ctx.log(`no run at the validated head — dispatched at ${current}`);
1170
+ }
1171
+ else {
1172
+ ctx.log(`run already present at ${validated} — not dispatching a duplicate`);
1173
+ }
1174
+ auditRow(status, "ship-revalidate-dispatch", {
1175
+ head: validated,
1176
+ probe: probe.out.result,
1177
+ reason,
1178
+ dispatched: probe.out.dispatched,
1179
+ attempts: probe.out.attempts,
1180
+ });
1181
+ const wait = await waitFor(ctx.cwd, { head: validated, branch, until: "completed" }, d);
1182
+ if (wait.code === EXIT.NO) {
1183
+ auditRow(status, "ship-revalidate-timeout", {
1184
+ attempt: wait.out.attempts,
1185
+ timeout_s: wait.out.elapsedS,
1186
+ });
1187
+ ctx.log(`CI did not complete at ${validated}`);
1188
+ }
1189
+ Object.assign(out, {
1190
+ validatedHead: validated,
1191
+ probe: probe.out,
1192
+ dispatched: probe.out.dispatched,
1193
+ wait: wait.out,
1194
+ });
1195
+ if (wait.code !== EXIT.OK) {
1196
+ ctx.emit(out);
1197
+ return wait.code;
1198
+ }
1199
+ }
1200
+ ctx.emit(out);
1201
+ return EXIT.OK;
1202
+ }
1203
+ // ---------------------------------------------------------------------------
1204
+ // context (/bkit-auto Step 1)
1205
+ // ---------------------------------------------------------------------------
1206
+ /** `{PHASE}` as dispatched: CI verdict words map onto ship / debug. */
1207
+ const PHASES = {
1208
+ ship: { phase: "ship", mode: "CI" },
1209
+ success: { phase: "ship", mode: "CI" },
1210
+ pass: { phase: "ship", mode: "CI" },
1211
+ debug: { phase: "debug", mode: "CI" },
1212
+ failure: { phase: "debug", mode: "CI" },
1213
+ fail: { phase: "debug", mode: "CI" },
1214
+ design: { phase: "design", mode: "BRIEF" },
1215
+ plan: { phase: "plan", mode: "BRIEF" },
1216
+ build: { phase: "build", mode: "BRIEF" },
1217
+ };
1218
+ /** Exit code (context): the phase word is not one bkit dispatches. */
1219
+ export const EXIT_UNKNOWN_PHASE = 3;
1220
+ /** Exit code (context): the CI PR is not OPEN. */
1221
+ export const EXIT_PR_NOT_OPEN = 7;
1222
+ /** Exit code (context): no CI run at the PR head. */
1223
+ export const EXIT_NO_RUN_ID = 8;
1224
+ /** Exit code (context): no FID from the marker, the branch, or the slug. */
1225
+ export const EXIT_NO_FID = 9;
1226
+ async function runContext(ctx) {
1227
+ const phaseArg = String(ctx.flags.phase);
1228
+ const arg = String(ctx.flags.arg);
1229
+ const chosen = PHASES[phaseArg.toLowerCase()];
1230
+ if (!chosen) {
1231
+ ctx.log(`Unrecognised PHASE: ${phaseArg}`);
1232
+ return EXIT_UNKNOWN_PHASE;
1233
+ }
1234
+ const resolved = resolveOwnerRepo(ctx.cwd);
1235
+ const slug = resolved ? splitSlug(resolved.ownerRepo) : null;
1236
+ if (!resolved || !slug) {
1237
+ ctx.log("could not resolve owner/repo from gh or the origin remote");
1238
+ return EXIT.USAGE;
1239
+ }
1240
+ const out = {
1241
+ phase: chosen.phase,
1242
+ mode: chosen.mode,
1243
+ ownerRepo: resolved.ownerRepo,
1244
+ owner: slug.owner,
1245
+ repo: slug.repo,
1246
+ issueId: null,
1247
+ fid: null,
1248
+ prNumber: null,
1249
+ branch: null,
1250
+ headSha: null,
1251
+ prUrl: null,
1252
+ prState: null,
1253
+ runId: null,
1254
+ };
1255
+ if (chosen.mode === "BRIEF") {
1256
+ ctx.emit({ ...out, issueId: arg });
1257
+ return EXIT.OK;
1258
+ }
1259
+ const tracker = readIssueTracker(ctx.cwd);
1260
+ if (!/^[0-9]+$/.test(arg)) {
1261
+ // CI_DEV: a post-merge dev failure names the FID slug; checked before any path sees it.
1262
+ if (!FID_PATTERNS.any.test(arg)) {
1263
+ ctx.log(`Invalid CI_DEV FID: ${arg}`);
1264
+ return EXIT_NO_FID;
1265
+ }
1266
+ ctx.emit({
1267
+ ...out,
1268
+ mode: "CI_DEV",
1269
+ fid: arg,
1270
+ issueId: tracker === "none" ? null : issueIdOf(arg, "any"),
1271
+ branch: "dev",
1272
+ headSha: git(ctx.cwd, ["rev-parse", "origin/dev"]) ?? "",
1273
+ });
1274
+ return EXIT.OK;
1275
+ }
1276
+ const view = runGh(ctx.cwd, [
1277
+ "pr",
1278
+ "view",
1279
+ arg,
1280
+ "--json",
1281
+ "headRefName,headRefOid,state,url,body",
1282
+ ]);
1283
+ if (view.missing || view.status === 4) {
1284
+ ctx.log(GH_MISSING);
1285
+ return EXIT.USE_MCP;
1286
+ }
1287
+ const pr = obj(view.ok ? jsonOrUndefined(view.stdout) : undefined);
1288
+ const branch = text(pr.headRefName);
1289
+ const headSha = text(pr.headRefOid);
1290
+ Object.assign(out, {
1291
+ prNumber: arg,
1292
+ branch,
1293
+ headSha,
1294
+ prUrl: text(pr.url),
1295
+ prState: text(pr.state).toUpperCase(),
1296
+ });
1297
+ if (!branch || !headSha || !text(pr.url)) {
1298
+ ctx.log(`could not read PR ${arg}`);
1299
+ ctx.emit(out);
1300
+ return EXIT.NO;
1301
+ }
1302
+ if (out.prState !== "OPEN") {
1303
+ ctx.log(`PR ${arg} is ${String(out.prState)}, not OPEN`);
1304
+ ctx.emit(out);
1305
+ return EXIT_PR_NOT_OPEN;
1306
+ }
1307
+ const runs = runGh(ctx.cwd, [
1308
+ "run",
1309
+ "list",
1310
+ "--branch",
1311
+ branch,
1312
+ "--limit",
1313
+ "5",
1314
+ "--json",
1315
+ "databaseId,headSha",
1316
+ ]);
1317
+ const run = arr(runs.ok ? jsonOrUndefined(runs.stdout) : undefined)
1318
+ .map(obj)
1319
+ .find((r) => r.headSha === headSha);
1320
+ out.runId = run?.databaseId === undefined ? null : String(run.databaseId);
1321
+ if (out.runId === null) {
1322
+ ctx.log(`no CI run at ${headSha} on ${branch}`);
1323
+ ctx.emit(out);
1324
+ return EXIT_NO_RUN_ID;
1325
+ }
1326
+ // The PR-body marker first, the feat/{FID} branch as the fallback.
1327
+ const markerTracker = tracker;
1328
+ const viaMarker = fromMarker(str(ctx.flags.marker) ?? text(pr.body), markerTracker);
1329
+ const viaBranch = viaMarker ? null : fromBranch(branch, markerTracker);
1330
+ const parsed = viaMarker ?? (viaBranch?.ok ? viaBranch.parsed : null);
1331
+ if (!parsed) {
1332
+ ctx.log(viaBranch && !viaBranch.ok ? viaBranch.why : "no FID in the PR-body marker or the branch");
1333
+ ctx.emit(out);
1334
+ return EXIT_NO_FID;
1335
+ }
1336
+ ctx.emit({ ...out, fid: parsed.fid, issueId: parsed.issueId });
1337
+ return EXIT.OK;
1338
+ }
1339
+ async function runMirror(ctx) {
1340
+ const f = ctx.flags;
1341
+ const head = String(f.head);
1342
+ const branch = str(f.branch) ?? "dev";
1343
+ if (!branch)
1344
+ throw new CommandError(EXIT.USAGE, "--branch must not be empty");
1345
+ const o = {
1346
+ head,
1347
+ branch,
1348
+ absentMinutes: wholeNumber(f.absentMinutes, "absent-minutes", 10),
1349
+ maxMinutes: wholeNumber(f.maxMinutes, "max-minutes", 170),
1350
+ intervalS: wholeNumber(f.intervalS, "interval-s", 30),
1351
+ };
1352
+ const root = checkoutRoot(ctx.cwd);
1353
+ const repo = str(f.repo) ?? (process.env.GITHUB_REPOSITORY || undefined);
1354
+ const gh = (args) => runGh(ctx.cwd, args);
1355
+ const r = await mirrorPushRun(o, {
1356
+ // Each poll's diagnostics are dropped; the mirror logs the gate's reason when it stops on it.
1357
+ gate: () => shipGate({
1358
+ root,
1359
+ head,
1360
+ branch,
1361
+ event: "push",
1362
+ repo,
1363
+ ciWorkflow: str(f.ciWorkflow),
1364
+ capstone: str(f.capstone),
1365
+ }, gh, () => undefined),
1366
+ sleep: realSleep,
1367
+ now: Date.now,
1368
+ log: ctx.log,
1369
+ });
1370
+ ctx.emit({ ...r });
1371
+ return r.code;
1372
+ }
1373
+ export const runsCommand = {
1374
+ noun: "runs",
1375
+ summary: "CI runs: wait for one, prove one was dispatched, re-validate and gate a merge on one; auto's start context.",
1376
+ verbs: {
1377
+ wait: {
1378
+ summary: "Bounded poll for a CI check on a PR (--pr) or a CI run at a head (--head --branch), present or completed.",
1379
+ flags: [
1380
+ { name: "pr", type: "string", help: "PR number: read its check rollup" },
1381
+ { ...HEAD_FLAG, help: "commit SHA: read the CI workflow's runs at it (with --branch)" },
1382
+ { name: "branch", type: "string", help: "branch the runs are on (with --head)" },
1383
+ {
1384
+ name: "until",
1385
+ type: "string",
1386
+ help: "present (a check / run exists, default) | completed (PR: no open checks; run: completed)",
1387
+ },
1388
+ BUDGET_FLAG,
1389
+ INTERVAL_FLAG,
1390
+ {
1391
+ name: "once",
1392
+ type: "boolean",
1393
+ help: "poll once, for an agent turn loop; not found exits 81 (end the turn, call again)",
1394
+ },
1395
+ {
1396
+ name: "dispatch-if-absent",
1397
+ type: "boolean",
1398
+ help: "with --head --until=present: no run after the budget -> gh workflow run <ciWorkflow> --ref <branch>",
1399
+ },
1400
+ ],
1401
+ output: {
1402
+ result: "found | none | err (err: every poll errored, gh absent, or the sleep was blocked)",
1403
+ target: "pr-present | pr-completed | run-present | run-completed",
1404
+ attempts: "polls run",
1405
+ elapsedS: "seconds slept",
1406
+ allErrored: "every poll errored",
1407
+ blocked: "a sleep overran its window: resolve the poll in the agent turn loop",
1408
+ conclusion: "the run's conclusion (run-completed when found), else null",
1409
+ checks: "checks in the PR rollup (PR targets), else null",
1410
+ dispatched: "--dispatch-if-absent ran gh workflow run",
1411
+ },
1412
+ exitCodes: { [EXIT_TRIGGER_FAILED]: "--dispatch-if-absent: gh workflow run failed" },
1413
+ run: runWait,
1414
+ },
1415
+ dispatch: {
1416
+ summary: "CI-Dispatch Gate after the last push: poll, one clean re-trigger, the ciDispatch verdict, and the body scan.",
1417
+ flags: [
1418
+ {
1419
+ name: "pr",
1420
+ type: "string",
1421
+ help: "PR number (default: the open PR from this branch into dev)",
1422
+ },
1423
+ {
1424
+ name: "fid",
1425
+ type: "string",
1426
+ required: true,
1427
+ help: "feature id, for the re-trigger commit subject",
1428
+ },
1429
+ {
1430
+ name: "label",
1431
+ type: "string",
1432
+ repeatable: true,
1433
+ help: "a label the issue carries now (as the tracker MCP read returned it): bkit:auto adds ` bkit [auto route]` to the re-trigger subject",
1434
+ },
1435
+ {
1436
+ name: "file",
1437
+ type: "string",
1438
+ help: "status.jsonl: write the --step row carrying ciDispatch once a verdict exists; a passed verdict is cross-checked and recorded as the close transport",
1439
+ },
1440
+ { name: "workflow", type: "string", help: "with --file: build | debug (default build)" },
1441
+ { name: "step", type: "string", help: "with --file: the step the row records" },
1442
+ {
1443
+ name: "artifact",
1444
+ type: "string",
1445
+ repeatable: true,
1446
+ help: "with --file: an artifact on the row (the created PR's URL)",
1447
+ },
1448
+ {
1449
+ name: "field",
1450
+ type: "string",
1451
+ repeatable: true,
1452
+ help: "with --file: an extra row field key=value",
1453
+ },
1454
+ { ...BUDGET_FLAG, help: "poll budget in seconds (default 60)" },
1455
+ { ...INTERVAL_FLAG, help: "seconds between polls (default 10)" },
1456
+ {
1457
+ name: "poll-result",
1458
+ type: "string",
1459
+ help: "re-entry after a hand-off: found | none | err, as the agent turn loop resolved it",
1460
+ },
1461
+ {
1462
+ name: "attempts",
1463
+ type: "string",
1464
+ help: "re-entry: total poll attempts so far (hand-off attempts + turns)",
1465
+ },
1466
+ { name: "all-errored", type: "boolean", help: "re-entry: every turn-loop poll errored" },
1467
+ {
1468
+ name: "retriggered",
1469
+ type: "boolean",
1470
+ help: "re-entry: the hand-off was in the re-poll (re-trigger already pushed)",
1471
+ },
1472
+ ],
1473
+ output: {
1474
+ ciDispatch: "{outcome, head, attempts, retrigger, reason?} — record with `bkit steps done --field ciDispatch=…` (local only, never pushed); null on a hand-off",
1475
+ phase: "done | poll | repoll (which poll was handed to the agent)",
1476
+ pr: "PR number polled (null when none was found)",
1477
+ head: "the pushed head (the re-trigger commit after a re-trigger)",
1478
+ attempts: "poll attempts so far",
1479
+ retrigger: "a re-trigger commit was pushed",
1480
+ scanResult: "clean | skip-token-found | error — the pushed head's BODY scan; null when unresolved",
1481
+ ciWorkflow: "the CI workflow file the no-ci check looked for",
1482
+ row: "--file: the step-done row written (null on a hand-off)",
1483
+ transport: "--file: the close-transport row written for a passed verdict, else null",
1484
+ },
1485
+ exitCodes: {
1486
+ [EXIT_SKIP_TOKEN]: "the pushed head's body carries a CI-suppression token",
1487
+ [EXIT_SCAN_ERROR]: "the pushed head's commit message could not be read",
1488
+ [EXIT_RETRIGGER_FAILED]: "the re-trigger commit or push failed (no verdict)",
1489
+ },
1490
+ run: runDispatch,
1491
+ },
1492
+ gate: {
1493
+ summary: "Ship merge gate: the capstone job present and green at the head (exit 0), or why not.",
1494
+ flags: [
1495
+ { ...HEAD_FLAG, help: "the PR head to merge (or --pr / --squash-of)" },
1496
+ {
1497
+ name: "pr",
1498
+ type: "string",
1499
+ help: "the PR number: gate its current head, refusing a title that carries a skip token (18)",
1500
+ },
1501
+ {
1502
+ name: "squash-of",
1503
+ type: "string",
1504
+ help: "the merged PR number: gate its squash commit (ship's post-merge check, with --capstone-only)",
1505
+ },
1506
+ {
1507
+ name: "snapshot",
1508
+ type: "string",
1509
+ help: "with --pr: append the pre-merge snapshot row to this file before gating",
1510
+ },
1511
+ {
1512
+ name: "record",
1513
+ type: "string",
1514
+ help: "status.jsonl: append ship-gate-refusal on a refusal, or ship-merge-ci with --capstone-only",
1515
+ },
1516
+ {
1517
+ name: "validated",
1518
+ type: "string",
1519
+ help: "an ancestor CI passed at; checked instead when only bookkeeping changed since (needs --month --fid)",
1520
+ },
1521
+ { name: "month", type: "string", help: "YYYYMM, for the bookkeeping allow-list" },
1522
+ { name: "fid", type: "string", help: "feature id, for the bookkeeping allow-list" },
1523
+ REPO_FLAG,
1524
+ {
1525
+ name: "branch",
1526
+ type: "string",
1527
+ help: "PR branch: tells a superseded head (14) from no run (10)",
1528
+ },
1529
+ {
1530
+ name: "event",
1531
+ type: "string",
1532
+ help: "count only runs fired by this event (push, pull_request)",
1533
+ },
1534
+ {
1535
+ name: "file",
1536
+ type: "string",
1537
+ help: "status.jsonl for the BKIT_SHIP_GATE_OVERRIDE audit row (stderr when absent or unwritable)",
1538
+ },
1539
+ {
1540
+ name: "capstone-only",
1541
+ type: "boolean",
1542
+ 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)",
1543
+ },
1544
+ ],
1545
+ output: {
1546
+ code: "the exit code",
1547
+ passed: "merge may proceed (green, or override honoured)",
1548
+ overridden: "BKIT_SHIP_GATE_OVERRIDE equalled the refused head",
1549
+ head: "head CI was checked at (--validated when the carry-forward applied)",
1550
+ mergeHead: "--head",
1551
+ testedHead: "head the selected (or superseded) run tested",
1552
+ runId: "selected run id",
1553
+ runUrl: "selected run URL",
1554
+ conclusion: "selected run conclusion",
1555
+ capstone: "capstone job name",
1556
+ ciWorkflow: "CI workflow file",
1557
+ repo: "owner/repo",
1558
+ skippedLanes: "lanes that concluded skipped (reported, refuse only when required)",
1559
+ nonBookkeepingPaths: "paths past --validated outside the allow-list (code 17)",
1560
+ reason: "why — the refusal or pass line",
1561
+ },
1562
+ exitCodes: {
1563
+ [GATE.NO_RUN]: "no run of the CI workflow at the head",
1564
+ [GATE.IN_PROGRESS]: "runs at the head, none completed; --capstone-only: capstone not completed (poll)",
1565
+ [GATE.FAILED]: "selected run or its capstone did not conclude success (--capstone-only: the capstone)",
1566
+ [GATE.NO_CAPSTONE]: "selected run has no capstone job",
1567
+ [GATE.SUPERSEDED]: "green run only at a superseded head (needs --branch)",
1568
+ [GATE.CANCELLED]: "selected run was cancelled",
1569
+ [GATE.LANE_SKIPPED]: "a required lane concluded skipped",
1570
+ [GATE.NOT_BOOKKEEPING]: "non-bookkeeping change past --validated, or not its descendant",
1571
+ [GATE.TITLE_SKIP]: "--pr: the PR title carries a CI-suppressing token",
1572
+ [GATE.API_ERROR]: "API error / rate limit / auth, or the PR head / squash commit unreadable",
1573
+ },
1574
+ run: runGate,
1575
+ },
1576
+ revalidate: {
1577
+ summary: "Ship: pick the head CI must pass at, probe for a run there, dispatch only when none, wait for it to complete.",
1578
+ flags: [
1579
+ { name: "pr", type: "string", required: true, help: "the PR number" },
1580
+ { name: "entry-head", type: "string", required: true, help: "the PR head read at Step 2" },
1581
+ {
1582
+ name: "code-head",
1583
+ type: "string",
1584
+ required: true,
1585
+ help: "the head before ship's bookkeeping commit (Step 8)",
1586
+ },
1587
+ { name: "branch", type: "string", required: true, help: "the PR branch" },
1588
+ {
1589
+ name: "month",
1590
+ type: "string",
1591
+ required: true,
1592
+ help: "YYYYMM, for the bookkeeping allow-list",
1593
+ },
1594
+ {
1595
+ name: "fid",
1596
+ type: "string",
1597
+ required: true,
1598
+ help: "feature id, for the bookkeeping allow-list",
1599
+ },
1600
+ {
1601
+ name: "file",
1602
+ type: "string",
1603
+ required: true,
1604
+ help: "status.jsonl for the ship-revalidate-dispatch / -timeout rows",
1605
+ },
1606
+ {
1607
+ name: "reason",
1608
+ type: "string",
1609
+ help: "head-move (default) | gate-refusal (re-validate even when the head did not move)",
1610
+ },
1611
+ REPO_FLAG,
1612
+ ],
1613
+ output: {
1614
+ validatedHead: "the head CI was (or must be) checked at",
1615
+ currentHead: "the PR head now",
1616
+ revalidated: "a probe / wait ran (the head moved, or a gate refusal re-entered)",
1617
+ probe: "the presence probe's wait result, or null",
1618
+ dispatched: "the probe found no run and dispatched one",
1619
+ wait: "the completion wait's result, or null",
1620
+ },
1621
+ exitCodes: { [EXIT_TRIGGER_FAILED]: "no run and gh workflow run failed" },
1622
+ run: runRevalidate,
1623
+ },
1624
+ mirror: {
1625
+ summary: "Release PR: wait for the branch's push run at the head and copy its capstone verdict.",
1626
+ flags: [
1627
+ { ...HEAD_FLAG, required: true, help: "the PR head (same SHA the push run tests)" },
1628
+ { name: "branch", type: "string", help: "branch whose push run to mirror (default dev)" },
1629
+ { ...REPO_FLAG, help: "owner/repo (default: $GITHUB_REPOSITORY, then gh repo view)" },
1630
+ CI_WORKFLOW_FLAG,
1631
+ CAPSTONE_FLAG,
1632
+ {
1633
+ name: "absent-minutes",
1634
+ type: "string",
1635
+ help: "how long no push run may exist (default 10)",
1636
+ },
1637
+ {
1638
+ name: "max-minutes",
1639
+ type: "string",
1640
+ help: "how long to wait in total (default 170; keep below the job's timeout-minutes)",
1641
+ },
1642
+ { name: "interval-s", type: "string", help: "seconds between polls (default 30)" },
1643
+ ],
1644
+ output: {
1645
+ code: "the exit code",
1646
+ passed: "the push run's capstone passed",
1647
+ gateCode: "the last gate code",
1648
+ polls: "gate calls made",
1649
+ elapsedMinutes: "minutes waited",
1650
+ },
1651
+ exitCodes: {
1652
+ [MIRROR.ABSENT]: "no push run at the head after --absent-minutes ([skip ci] at the tip?)",
1653
+ [MIRROR.TIMED_OUT]: "push run still in progress at --max-minutes",
1654
+ [MIRROR.API_ERRORS]: "three GitHub API errors in a row",
1655
+ },
1656
+ run: runMirror,
1657
+ },
1658
+ context: {
1659
+ summary: "/bkit-auto Step 1: the phase and mode, the repo, and the issue / FID / PR / run the dispatch carries.",
1660
+ flags: [
1661
+ {
1662
+ name: "phase",
1663
+ type: "string",
1664
+ required: true,
1665
+ help: "ship | success | pass | debug | failure | fail | design | plan | build",
1666
+ },
1667
+ {
1668
+ name: "arg",
1669
+ type: "string",
1670
+ required: true,
1671
+ help: "CI: the PR number, or (CI_DEV) the FID slug; BRIEF: the issue",
1672
+ },
1673
+ {
1674
+ name: "marker",
1675
+ type: "string",
1676
+ help: "the PR body (default: read with gh) — its bkit:fid marker names the FID",
1677
+ },
1678
+ ],
1679
+ output: {
1680
+ phase: "ship | debug | design | plan | build",
1681
+ mode: "CI | CI_DEV | BRIEF",
1682
+ ownerRepo: "owner/repo",
1683
+ owner: "owner half",
1684
+ repo: "repo half",
1685
+ issueId: "the issue (BRIEF: the arg; CI: from the marker or branch; null under no tracker)",
1686
+ fid: "the FID (CI / CI_DEV), else null",
1687
+ prNumber: "the PR (CI), else null",
1688
+ branch: "the PR head branch (CI), dev (CI_DEV), else null",
1689
+ headSha: "the PR head (CI) or origin/dev (CI_DEV), else null",
1690
+ prUrl: "the PR URL (CI), else null",
1691
+ prState: "the PR state (CI), else null",
1692
+ runId: "the CI run at the PR head (CI), else null",
1693
+ },
1694
+ exitCodes: {
1695
+ [EXIT_UNKNOWN_PHASE]: "the phase word is not one bkit dispatches",
1696
+ [EXIT_PR_NOT_OPEN]: "the PR is not OPEN",
1697
+ [EXIT_NO_RUN_ID]: "no CI run at the PR head",
1698
+ [EXIT_NO_FID]: "no valid FID (CI_DEV slug off the allowlist, or no marker / feat/{FID} branch)",
1699
+ },
1700
+ run: runContext,
1701
+ },
1702
+ declared: {
1703
+ summary: "Whether the repo declares a CI workflow: .github/workflows/<bkit.ciWorkflow> exists (exit 0) or not (exit 1).",
1704
+ flags: [],
1705
+ output: {
1706
+ declared: "the workflow file exists",
1707
+ ciWorkflow: "the workflow file name checked",
1708
+ path: "its path relative to the checkout",
1709
+ },
1710
+ run: (ctx) => {
1711
+ const d = ciDeclared(checkoutRoot(ctx.cwd));
1712
+ ctx.emit({ ...d });
1713
+ return d.declared ? EXIT.OK : EXIT.NO;
1714
+ },
1715
+ },
1716
+ },
1717
+ };