@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,1093 @@
1
+ // bkit steps done|finish|verdict|gate|stub — write a step's status row, read a
2
+ // subagent's verdict header, check the step left everything the gate requires,
3
+ // and seed a versioned artifact's header.
4
+ //
5
+ // `done` captures `parentSha` before committing, writes the row, then commits,
6
+ // in that fixed order: the fold's de-dup key includes `parentSha`, so attempt
7
+ // counts stay right only if it moves forward after every step. The gate checks
8
+ // what `done` wrote, so a step cannot hand-type its own row and then tick a box
9
+ // saying it did. `finish` is the whole step ending in one call: read the verdict
10
+ // headers, derive the attempt, check what the gate checks, write the row, commit,
11
+ // and print the step's tracker comment.
12
+ import * as fs from "node:fs";
13
+ import * as path from "node:path";
14
+ import { activeDoneSteps, appendLine, runOrStepField, statusTimestamp, } from "../../ledgers/status.js";
15
+ import { clampLogPath, readRecords } from "../../ledgers/clamp-log.js";
16
+ import { resolveRepoSlug } from "../../ledgers/telemetry.js";
17
+ import { getPromptsRoot } from "../../shared/package-roots.js";
18
+ import { CommandError, EXIT, repoRoot, runGit, } from "../lib.js";
19
+ import { FID_PATTERNS, readIssueTracker } from "./fids.js";
20
+ import { buildComment } from "./issues.js";
21
+ import { lockRoot, readHolder, resolveMonth, workflowLockPath } from "./locks.js";
22
+ import { EXIT_NO_STATUS, FILE_FLAG, STEP_FLAG, SUB_PLAN_FLAG, WORKFLOW_FLAG, extraField, nonNegativeInt, positiveInt, readRuns, statusFile, str, } from "./status.js";
23
+ const VERDICT_END = "<!-- verdict:end -->";
24
+ const DEFAULT_VERDICTS = ["PASS", "CONCERNS", "FAIL"];
25
+ const STRATEGIES = ["STANDARD", "PIVOT", "FINAL"];
26
+ /** Exit codes shared by verdict, done and finish. */
27
+ export const EXIT_EMPTY = 4;
28
+ export const EXIT_PENDING = 5;
29
+ export const EXIT_INVALID = 6;
30
+ export const EXIT_ARTIFACT = 7;
31
+ export const EXIT_COMMIT = 8;
32
+ /** finish --docs-only: the step staged a file outside the artifact tree. */
33
+ export const EXIT_OUTSIDE_DOCS = 9;
34
+ /** Where `finish` puts the derived attempt in `--artifact` / `--message` / `--clamp-log`. */
35
+ export const ATTEMPT_TOKEN = "<attempt>";
36
+ /** Where `finish` puts the first `DONE` line's description in `--message`. */
37
+ export const DONE_TOKEN = "<done>";
38
+ /**
39
+ * The header a prompt's output template declares: its `Verdict: A | B | C` line
40
+ * and every `Key: …` line under it down to `<!-- verdict:end -->`.
41
+ */
42
+ export function promptHeader(agent) {
43
+ const file = path.join(getPromptsRoot(), `${agent}.md`);
44
+ if (!fs.existsSync(file))
45
+ throw new CommandError(EXIT.USAGE, `no prompt ${agent} at ${file}`);
46
+ const lines = fs.readFileSync(file, "utf-8").split("\n");
47
+ const start = lines.findIndex((l) => l.startsWith("Verdict: "));
48
+ if (start === -1)
49
+ throw new CommandError(EXIT.USAGE, `${agent} declares no Verdict: line`);
50
+ const values = (raw) => raw
51
+ .replace(/\[.*\]/, "")
52
+ .split("|")
53
+ .map((v) => v.trim())
54
+ .filter(Boolean);
55
+ const verdicts = values(lines[start].slice("Verdict: ".length));
56
+ const fields = [];
57
+ for (const line of lines.slice(start + 1)) {
58
+ if (line.trim() === VERDICT_END || line.startsWith("```"))
59
+ break;
60
+ const m = /^([A-Z][A-Za-z ]*):\s*(.*)$/.exec(line);
61
+ if (!m)
62
+ continue;
63
+ const raw = m[2].replace(/\[.*\]/, "").trim();
64
+ if (/^<integer/.test(raw))
65
+ fields.push({ name: m[1], integer: true });
66
+ else if (raw.includes("|"))
67
+ fields.push({ name: m[1], values: values(raw) });
68
+ else
69
+ fields.push({ name: m[1] });
70
+ }
71
+ return { verdicts, fields };
72
+ }
73
+ /** Allowed verdicts from a prompt's own `Verdict: A | B | C [note]` output line. */
74
+ export const promptVerdicts = (agent) => promptHeader(agent).verdicts;
75
+ const PLACEHOLDER = /^(?:\[?PENDING\]?|.*:\s*\[?PENDING\]?\.?)$/;
76
+ /**
77
+ * Read an artifact's header — every line above `<!-- verdict:end -->` — as
78
+ * `Key: value` fields. `require` names fields that must be present; `declared`
79
+ * fields must be present and hold one of their allowed values.
80
+ */
81
+ export function readHeader(file, allowed, require = [], declared = []) {
82
+ if (!fs.existsSync(file) || fs.statSync(file).size === 0) {
83
+ return { ok: false, code: EXIT_EMPTY, problem: `${file} is missing or empty` };
84
+ }
85
+ const lines = fs.readFileSync(file, "utf-8").split("\n");
86
+ const end = lines.indexOf(VERDICT_END);
87
+ if (end === -1)
88
+ return { ok: false, code: EXIT_INVALID, problem: `${file} has no ${VERDICT_END} line` };
89
+ const fields = {};
90
+ for (const line of lines.slice(0, end)) {
91
+ const m = /^([A-Z][A-Za-z ]*):\s*(.*)$/.exec(line.trim());
92
+ if (m && !(m[1] in fields))
93
+ fields[m[1]] = m[2].trim();
94
+ }
95
+ const pending = Object.entries(fields).filter(([, v]) => /\bPENDING\b/.test(v));
96
+ if (pending.length > 0) {
97
+ return {
98
+ ok: false,
99
+ code: EXIT_PENDING,
100
+ problem: `${file}: ${pending.map(([k]) => k).join(", ")} still PENDING`,
101
+ };
102
+ }
103
+ const verdict = fields.Verdict;
104
+ if (verdict === undefined || !allowed.includes(verdict)) {
105
+ return {
106
+ ok: false,
107
+ code: EXIT_INVALID,
108
+ problem: `${file}: Verdict "${verdict ?? ""}" is not ${allowed.join("|")}`,
109
+ };
110
+ }
111
+ const missing = [...require, ...declared.map((d) => d.name)].filter((f) => fields[f] === undefined || fields[f] === "");
112
+ if (missing.length > 0)
113
+ return { ok: false, code: EXIT_INVALID, problem: `${file}: missing ${missing.join(", ")}` };
114
+ if (fields.Failures !== undefined && !/^[0-9]+$/.test(fields.Failures)) {
115
+ return {
116
+ ok: false,
117
+ code: EXIT_INVALID,
118
+ problem: `${file}: Failures "${fields.Failures}" is not a non-negative integer`,
119
+ };
120
+ }
121
+ for (const d of declared) {
122
+ const v = fields[d.name];
123
+ if (d.values && !d.values.includes(v)) {
124
+ return {
125
+ ok: false,
126
+ code: EXIT_INVALID,
127
+ problem: `${file}: ${d.name} "${v}" is not ${d.values.join("|")}`,
128
+ };
129
+ }
130
+ if (d.integer && !/^[0-9]+$/.test(v)) {
131
+ return {
132
+ ok: false,
133
+ code: EXIT_INVALID,
134
+ problem: `${file}: ${d.name} "${v}" is not a non-negative integer`,
135
+ };
136
+ }
137
+ }
138
+ return { ok: true, verdict, fields };
139
+ }
140
+ /** Lines left as a stub placeholder: a bare `PENDING`, or a field whose whole value is `PENDING`. */
141
+ export function placeholderLines(file) {
142
+ return fs
143
+ .readFileSync(file, "utf-8")
144
+ .split("\n")
145
+ .flatMap((l, i) => (PLACEHOLDER.test(l.trim()) ? [i + 1] : []));
146
+ }
147
+ const ALLOWED_FLAGS = [
148
+ {
149
+ name: "agent",
150
+ type: "string",
151
+ help: "subagent name; its prompt's Verdict: line gives the allowed values",
152
+ },
153
+ {
154
+ name: "allowed",
155
+ type: "string",
156
+ help: "allowed verdicts, comma-separated (default PASS,CONCERNS,FAIL)",
157
+ },
158
+ ];
159
+ function allowedVerdicts(flags) {
160
+ if (flags.agent !== undefined && flags.allowed !== undefined) {
161
+ throw new CommandError(EXIT.USAGE, "give --agent or --allowed, not both");
162
+ }
163
+ if (flags.agent !== undefined)
164
+ return promptVerdicts(String(flags.agent));
165
+ if (flags.allowed !== undefined)
166
+ return String(flags.allowed)
167
+ .split(",")
168
+ .map((v) => v.trim());
169
+ return DEFAULT_VERDICTS;
170
+ }
171
+ /** The worst verdict, by position in the allowed list (later = worse: PASS < CONCERNS < FAIL). */
172
+ export function worstVerdict(verdicts, allowed) {
173
+ return verdicts.reduce((worst, v) => (allowed.indexOf(v) > allowed.indexOf(worst) ? v : worst));
174
+ }
175
+ // ---------------------------------------------------------------------------
176
+ // Artifacts and row rules
177
+ // ---------------------------------------------------------------------------
178
+ /** An `https://` artifact (a PR URL) is recorded as given; it is not a file. */
179
+ const isUrl = (artifact) => /^https:\/\//.test(artifact);
180
+ /** Problems with an artifact path: missing, empty, or outside the working directory. */
181
+ function artifactProblem(cwd, rel) {
182
+ if (isUrl(rel))
183
+ return undefined;
184
+ const abs = path.resolve(cwd, rel);
185
+ const inside = path.relative(cwd, abs);
186
+ if (inside.startsWith("..") || path.isAbsolute(inside))
187
+ return `${rel} is outside ${cwd}`;
188
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isFile())
189
+ return `${rel} does not exist`;
190
+ if (fs.statSync(abs).size === 0)
191
+ return `${rel} is empty`;
192
+ return undefined;
193
+ }
194
+ /** `failures` agrees with `verdict`: PASS => 0, FAIL => > 0, CONCERNS => >= 0. */
195
+ export function failuresProblem(verdict, failures) {
196
+ if (failures === undefined || verdict === undefined)
197
+ return undefined;
198
+ if (verdict === "PASS" && failures !== 0)
199
+ return `PASS needs failures=0, got ${failures}`;
200
+ if (verdict === "FAIL" && failures <= 0)
201
+ return `FAIL needs failures>0, got ${failures}`;
202
+ return undefined;
203
+ }
204
+ /**
205
+ * The steps whose row carries `attempt`, `strategy` or `scope`, keyed
206
+ * `workflow/step`. `steps gate` and `steps finish` fail a row missing one;
207
+ * `steps.test.ts` holds this table to the workflows' `steps done` / `steps finish`
208
+ * calls (a finish call's `--agent` writes `strategy` when its prompt declares one).
209
+ */
210
+ export const ROW_FIELDS = {
211
+ "design/design-brainstorm-ideate": ["attempt"],
212
+ "design/design-generate": ["attempt"],
213
+ "design/design-review": ["attempt"],
214
+ "design/design-spike": ["attempt"],
215
+ "design/design-apply-review": ["attempt"],
216
+ "design/design-organise": ["attempt"],
217
+ "design/design-summary": ["attempt"],
218
+ "plan/plan-generate": ["attempt"],
219
+ "plan/plan-fetch-context": ["attempt"],
220
+ "plan/plan-review": ["attempt"],
221
+ "plan/plan-apply-review": ["attempt"],
222
+ "plan/plan-scope-check": ["attempt"],
223
+ "plan/plan-apply-scope": ["attempt"],
224
+ "plan/plan-complexity-check": ["attempt"],
225
+ "plan/plan-complexity-split": ["attempt"],
226
+ "plan/plan-summary": ["attempt"],
227
+ "build/build-plan-current": ["attempt"],
228
+ "build/build-install-skills": ["attempt"],
229
+ "build/build-plan-execute": ["attempt"],
230
+ "build/build-plan-verify": ["attempt"],
231
+ "build/build-subplan-gate": ["attempt", "scope"],
232
+ "build/build-plan-gaps-remediate": ["attempt", "strategy"],
233
+ "build/build-plan-verify-holistic": ["attempt"],
234
+ "build/build-challenge": ["attempt"],
235
+ "build/build-challenge-reconcile": ["attempt"],
236
+ "build/build-challenge-remediate": ["attempt"],
237
+ "build/build-challenge-tests": ["attempt"],
238
+ "build/build-run-tests": ["attempt", "scope"],
239
+ "build/build-failure-diagnose": ["attempt", "strategy"],
240
+ "build/build-failure-remediate": ["attempt", "strategy"],
241
+ "build/build-summary": ["attempt"],
242
+ "debug/debug-run-tests": ["attempt", "scope"],
243
+ "debug/context-fetch": ["attempt"],
244
+ "debug/debug-failure-diagnose": ["attempt", "strategy"],
245
+ "debug/debug-failure-remediate": ["attempt", "strategy"],
246
+ "debug/debug-failure-soak": ["attempt"],
247
+ "debug/debug-push-remediation": ["attempt"],
248
+ "debug/debug-summary": ["attempt"],
249
+ "ship/ship-summary": ["attempt"],
250
+ "ship/ship-merge-pr": ["attempt"],
251
+ "ship/ship-failure-diagnose": ["attempt"],
252
+ "ship/ship-failure-remediate": ["attempt", "strategy"],
253
+ };
254
+ /** The required fields missing (absent or empty) from a row. */
255
+ export function missingRowFields(workflow, step, row) {
256
+ return (ROW_FIELDS[`${workflow}/${step}`] ?? []).filter((k) => row[k] === undefined || row[k] === null || row[k] === "");
257
+ }
258
+ const CORE_ROW_KEYS = new Set([
259
+ "type",
260
+ "workflow",
261
+ "step",
262
+ "status",
263
+ "at",
264
+ "parentSha",
265
+ "artifacts",
266
+ "verdict",
267
+ "attempt",
268
+ "subPlan",
269
+ "failures",
270
+ "strategy",
271
+ ]);
272
+ /**
273
+ * Append one `step-done` row, then commit (parentSha first, the row, then the
274
+ * commit — the order the fold's de-dup relies on). Returns the row and the new
275
+ * commit; `code` is EXIT_COMMIT when the row landed but the commit failed.
276
+ */
277
+ export function writeStepRow(cwd, r, log) {
278
+ const clash = Object.keys(r.extras ?? {}).filter((k) => CORE_ROW_KEYS.has(k));
279
+ if (clash.length > 0)
280
+ throw new CommandError(EXIT.USAGE, `--field cannot set ${clash.join(", ")}; use its own flag`);
281
+ const parentSha = r.parentSha ?? runGit(cwd, ["rev-parse", "HEAD"]).stdout;
282
+ if (!/^[0-9a-f]{40}$/.test(parentSha))
283
+ throw new CommandError(EXIT.USAGE, `parentSha "${parentSha}" is not a commit sha`);
284
+ if (r.commit === "auto" && !r.message)
285
+ throw new CommandError(EXIT.USAGE, "--message is required unless --commit=none");
286
+ const row = {
287
+ type: "step-done",
288
+ workflow: r.workflow,
289
+ step: r.step,
290
+ status: (r.status ?? "DONE"),
291
+ at: statusTimestamp(),
292
+ parentSha,
293
+ artifacts: r.artifacts,
294
+ ...(r.verdict === undefined ? {} : { verdict: r.verdict }),
295
+ ...(r.attempt === undefined ? {} : { attempt: r.attempt }),
296
+ ...(r.subPlan === undefined ? {} : { subPlan: r.subPlan }),
297
+ ...(r.failures === undefined ? {} : { failures: r.failures }),
298
+ ...(r.strategy === undefined ? {} : { strategy: r.strategy }),
299
+ ...(r.extras ?? {}),
300
+ };
301
+ fs.mkdirSync(path.dirname(r.file), { recursive: true });
302
+ fs.appendFileSync(r.file, appendLine(row));
303
+ if (r.commit === "none")
304
+ return { row, commit: null, code: EXIT.OK };
305
+ const add = runGit(cwd, ["add", "-A"]);
306
+ const made = add.ok ? runGit(cwd, ["commit", "--allow-empty", "-m", r.message]) : add;
307
+ if (!made.ok) {
308
+ log(`row written to ${r.file} but the commit failed: ${made.stderr || made.stdout}`);
309
+ return { row, commit: null, code: EXIT_COMMIT };
310
+ }
311
+ return { row, commit: runGit(cwd, ["rev-parse", "HEAD"]).stdout, code: EXIT.OK };
312
+ }
313
+ /** Every mechanical gate check for one step; `ok` false names the first problem per check. */
314
+ function gateChecks(cwd, o) {
315
+ const checks = [];
316
+ const add = (check, problem, okDetail) => checks.push({ check, ok: problem === undefined, detail: problem ?? okDetail });
317
+ for (const p of o.placeholders) {
318
+ const eq = p.indexOf("=");
319
+ if (eq <= 0)
320
+ throw new CommandError(EXIT.USAGE, `--placeholder "${p}" must be NAME=value`);
321
+ add(`placeholder ${p.slice(0, eq)}`, p.slice(eq + 1).trim() === "" ? "empty" : undefined, "non-empty");
322
+ }
323
+ if (o.fid !== undefined) {
324
+ const tracker = readIssueTracker(cwd);
325
+ const fid = tracker === "linear" ? o.fid.toLowerCase() : o.fid;
326
+ add(`fid ${fid}`, FID_PATTERNS[tracker].test(fid)
327
+ ? undefined
328
+ : `does not match the ${tracker} shape ${FID_PATTERNS[tracker].source}`, `${tracker} shape`);
329
+ if (o.token !== undefined) {
330
+ const lock = workflowLockPath(lockRoot(cwd, o.workflow, o.devPushes === true), resolveMonth(repoRoot(cwd), o.fid, o.month), o.fid);
331
+ const holder = readHolder(lock);
332
+ add("workflow lock", holder === undefined
333
+ ? `no lock at ${lock}`
334
+ : holder.token === o.token
335
+ ? undefined
336
+ : `${lock} is held by another owner: ${holder.line}`, `held at ${lock}`);
337
+ }
338
+ }
339
+ else if (o.token !== undefined) {
340
+ throw new CommandError(EXIT.USAGE, "--token needs --fid");
341
+ }
342
+ for (const a of o.artifacts) {
343
+ if (isUrl(a))
344
+ continue;
345
+ const problem = artifactProblem(cwd, a);
346
+ add(`artifact ${a}`, problem, "present and non-empty");
347
+ if (problem)
348
+ continue;
349
+ const left = placeholderLines(path.resolve(cwd, a));
350
+ add(`placeholders ${a}`, left.length ? `PENDING left on line(s) ${left.join(", ")}` : undefined, "none left");
351
+ }
352
+ let headerVerdict;
353
+ if (o.verdictRequired) {
354
+ const verdictFile = o.artifacts[0];
355
+ if (verdictFile === undefined) {
356
+ add("verdict", "--verdict-required needs an --artifact to read it from", "");
357
+ }
358
+ else {
359
+ const header = readHeader(path.resolve(cwd, verdictFile), o.allowed);
360
+ headerVerdict = header.ok ? header.verdict : undefined;
361
+ add(`verdict ${verdictFile}`, header.ok ? undefined : header.problem, `Verdict: ${header.ok ? header.verdict : ""}`);
362
+ }
363
+ }
364
+ if (o.file === undefined)
365
+ return checks;
366
+ const rows = activeDoneSteps(readRuns(o.file), o.workflow, { step: o.step, subPlan: o.subPlan });
367
+ const row = rows.filter((r) => o.attempt === undefined || r.attempt === o.attempt).at(-1);
368
+ const rowProblems = [];
369
+ if (!row) {
370
+ rowProblems.push(`no DONE ${o.step} row in the active run${o.attempt === undefined ? "" : ` with attempt ${o.attempt}`}`);
371
+ }
372
+ else {
373
+ if (!/^[0-9a-f]{40}$/.test(row.parentSha ?? ""))
374
+ rowProblems.push(`parentSha "${row.parentSha ?? ""}" is not a sha`);
375
+ const recorded = new Set((row.artifacts ?? []).map((a) => path.normalize(a)));
376
+ for (const a of o.artifacts)
377
+ if (!recorded.has(path.normalize(a)))
378
+ rowProblems.push(`row does not list ${a}`);
379
+ const mismatch = failuresProblem(row.verdict, row.failures);
380
+ if (mismatch)
381
+ rowProblems.push(mismatch);
382
+ const missing = missingRowFields(o.workflow, o.step, row);
383
+ if (missing.length)
384
+ rowProblems.push(`row is missing ${missing.join(", ")}`);
385
+ if (o.verdictRequired && !o.allowed.includes(String(row.verdict))) {
386
+ rowProblems.push(`row verdict "${String(row.verdict ?? "")}" is not ${o.allowed.join("|")}`);
387
+ }
388
+ if (o.verdictRequired && headerVerdict !== undefined && row.verdict !== headerVerdict) {
389
+ rowProblems.push(`row verdict ${String(row.verdict)} differs from the artifact's ${headerVerdict}`);
390
+ }
391
+ }
392
+ add("status row", rowProblems.length ? rowProblems.join("; ") : undefined, `at ${row?.at ?? ""}`);
393
+ return checks;
394
+ }
395
+ // ---------------------------------------------------------------------------
396
+ // finish
397
+ // ---------------------------------------------------------------------------
398
+ const POSITIONS = ["next", "current", "count"];
399
+ /** `<step>:<next|current|count>[:<since>]` → the counter it names, from the active run. */
400
+ function derivedCounter(file, workflow, spec, subPlan, since) {
401
+ const [step, position, specSince] = spec.split(":");
402
+ if (!step || !POSITIONS.includes(position ?? "")) {
403
+ throw new CommandError(EXIT.USAGE, `"${spec}" must be <step>:<next|current|count>[:<since>]`);
404
+ }
405
+ const count = fs.existsSync(file)
406
+ ? activeDoneSteps(readRuns(file), workflow, { step, subPlan }, specSince ?? since).length
407
+ : 0;
408
+ if (position === "current" && count === 0) {
409
+ throw new CommandError(EXIT.NO, `${step}: no DONE row in the active run — the step's own row is missing`);
410
+ }
411
+ return position === "next" ? count + 1 : count;
412
+ }
413
+ /** The first `DONE …: description — …` line of a log, as a commit-subject fragment. */
414
+ export function doneDescription(file) {
415
+ if (!fs.existsSync(file))
416
+ return "";
417
+ const line = fs
418
+ .readFileSync(file, "utf-8")
419
+ .split("\n")
420
+ .find((l) => l.startsWith("DONE"));
421
+ if (line === undefined)
422
+ return "";
423
+ return line
424
+ .replace(/^DONE[^:]*: /, "")
425
+ .replace(/ — .*$/, "")
426
+ .replace(/[\r\n`"\\]/g, "")
427
+ .replace(/\s+$/, "")
428
+ .slice(0, 72);
429
+ }
430
+ /** Staged paths a docs-only step may not touch: anything outside the artifact tree and its ledgers. */
431
+ const DOCS_ONLY = /^docs\/plans\/|^docs\/(deferrals|decisions|failures)\.jsonl$|^\.bkit\/(friction|stats)\.jsonl$/;
432
+ /** `soakAttempt` → `Soak Attempt`, for a comment header. */
433
+ const titleCase = (key) => key.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase());
434
+ /** `<attempt>` filled in, once the attempt is known. */
435
+ const fill = (s, attempt) => attempt === undefined ? s : s.split(ATTEMPT_TOKEN).join(String(attempt));
436
+ const list = (v) => v ?? [];
437
+ function finish(ctx) {
438
+ const f = ctx.flags;
439
+ const file = statusFile(ctx);
440
+ const workflow = String(f.workflow);
441
+ const step = String(f.step);
442
+ const subPlan = positiveInt(f.subPlan, "sub-plan");
443
+ const since = str(f.since);
444
+ const agents = list(f.agent);
445
+ // Attempt: given, next from the log, or another step's counter.
446
+ if ([f.attempt, f.attemptOf].filter((v) => v !== undefined).length > 1)
447
+ throw new CommandError(EXIT.USAGE, "give --attempt or --attempt-of, not both");
448
+ let attempt;
449
+ let derived = false;
450
+ if (f.attemptOf !== undefined) {
451
+ attempt = derivedCounter(file, workflow, String(f.attemptOf), subPlan, since);
452
+ derived = true;
453
+ }
454
+ else if (f.attempt === "next") {
455
+ attempt = derivedCounter(file, workflow, `${step}:next`, subPlan, since);
456
+ derived = true;
457
+ }
458
+ else {
459
+ attempt = nonNegativeInt(f.attempt, "attempt");
460
+ }
461
+ const extras = Object.fromEntries(list(f.field).map(extraField));
462
+ for (const spec of list(f.countField)) {
463
+ const eq = spec.indexOf("=");
464
+ if (eq <= 0)
465
+ throw new CommandError(EXIT.USAGE, `--count-field "${spec}" must be key=<counter>`);
466
+ extras[spec.slice(0, eq)] = derivedCounter(file, workflow, spec.slice(eq + 1), subPlan, since);
467
+ }
468
+ const scope = str(f.scope);
469
+ if (scope !== undefined)
470
+ extras.scope = scope;
471
+ const artifacts = [
472
+ ...list(f.artifact).map((a) => fill(a, attempt)),
473
+ ...list(f.optionalArtifact)
474
+ .map((a) => fill(a, attempt))
475
+ .filter((a) => fs.existsSync(path.resolve(ctx.cwd, a))),
476
+ ];
477
+ // Artifacts first: every one present, non-empty, inside the working directory.
478
+ const bad = artifacts.map((a) => artifactProblem(ctx.cwd, a)).filter(Boolean);
479
+ if (bad.length > 0) {
480
+ ctx.log(bad.join("; "));
481
+ return EXIT_ARTIFACT;
482
+ }
483
+ // Verdict: the agents' headers (worst wins, Failures summed), or given.
484
+ if (agents.length > 0 && (f.verdict !== undefined || f.failures !== undefined))
485
+ throw new CommandError(EXIT.USAGE, "--agent reads the verdict; drop --verdict / --failures");
486
+ if (agents.length > artifacts.filter((a) => !isUrl(a)).length)
487
+ throw new CommandError(EXIT.USAGE, "each --agent reads the --artifact in the same position");
488
+ let verdict = str(f.verdict);
489
+ let failures = f.failures === undefined ? undefined : nonNegativeInt(f.failures, "failures");
490
+ let allowed = f.allowed === undefined ? DEFAULT_VERDICTS : allowedVerdicts({ allowed: f.allowed });
491
+ const fields = {};
492
+ if (agents.length > 0) {
493
+ const verdicts = [];
494
+ for (const [i, agent] of agents.entries()) {
495
+ const header = promptHeader(agent);
496
+ if (i === 0)
497
+ allowed = header.verdicts;
498
+ const read = readHeader(path.resolve(ctx.cwd, artifacts[i]), header.verdicts, [], header.fields);
499
+ if (!read.ok) {
500
+ ctx.log(read.problem);
501
+ ctx.emit({ reask: { agent, artifact: artifacts[i] }, problem: read.problem });
502
+ return read.code;
503
+ }
504
+ verdicts.push(read.verdict);
505
+ for (const [k, v] of Object.entries(read.fields)) {
506
+ if (k === "Verdict")
507
+ continue;
508
+ if (k === "Failures")
509
+ failures = (failures ?? 0) + Number(v);
510
+ else if (!(k in fields))
511
+ fields[k] = v;
512
+ }
513
+ }
514
+ verdict = worstVerdict(verdicts, allowed);
515
+ }
516
+ else if (verdict !== undefined && !allowed.includes(verdict)) {
517
+ throw new CommandError(EXIT.USAGE, `--verdict must be ${allowed.join("|")}`);
518
+ }
519
+ const mismatch = failuresProblem(verdict, failures);
520
+ if (mismatch) {
521
+ ctx.log(mismatch);
522
+ ctx.emit({
523
+ reask: agents.length ? { agent: agents[0], artifact: artifacts[0] } : null,
524
+ problem: mismatch,
525
+ });
526
+ return agents.length ? EXIT_INVALID : EXIT.USAGE;
527
+ }
528
+ const strategy = str(f.strategy) ?? fields.Strategy;
529
+ if (strategy !== undefined && !STRATEGIES.includes(strategy))
530
+ throw new CommandError(EXIT.USAGE, "--strategy must be STANDARD|PIVOT|FINAL");
531
+ delete fields.Strategy;
532
+ const clampLog = str(f.clampLog);
533
+ if (clampLog !== undefined) {
534
+ const [clampStep, clampAttempt] = fill(clampLog, attempt).split(":");
535
+ const fid = path.basename(path.dirname(file));
536
+ extras.clamped = readRecords(clampLogPath(ctx.cwd, fid, clampStep, positiveInt(clampAttempt, "clamp-log attempt")), (l) => ctx.log(`skipping a malformed clamp record: ${l}`));
537
+ }
538
+ // What the gate would refuse, refused before anything is written.
539
+ const pre = gateChecks(ctx.cwd, {
540
+ workflow,
541
+ step,
542
+ artifacts,
543
+ verdictRequired: false,
544
+ allowed,
545
+ placeholders: [],
546
+ });
547
+ const missing = missingRowFields(workflow, step, {
548
+ attempt,
549
+ strategy,
550
+ ...extras,
551
+ });
552
+ if (missing.length)
553
+ pre.push({ check: "status row", ok: false, detail: `row would miss ${missing.join(", ")}` });
554
+ if (pre.some((c) => !c.ok)) {
555
+ for (const c of pre.filter((x) => !x.ok))
556
+ ctx.log(`${c.check}: ${c.detail}`);
557
+ ctx.emit({ pass: false, checks: pre });
558
+ return EXIT.NO;
559
+ }
560
+ const commit = str(f.commit) ?? "auto";
561
+ if (!["auto", "none"].includes(commit))
562
+ throw new CommandError(EXIT.USAGE, "--commit must be auto or none");
563
+ if (f.docsOnly === true && commit === "auto") {
564
+ runGit(ctx.cwd, ["add", "-A"]);
565
+ const outside = runGit(ctx.cwd, ["diff", "--cached", "--name-only"])
566
+ .stdout.split("\n")
567
+ .filter((p) => p !== "" && !DOCS_ONLY.test(p));
568
+ if (outside.length) {
569
+ ctx.log(`the step wrote outside docs/plans/: ${outside.join(", ")}`);
570
+ ctx.emit({ pass: false, outside });
571
+ return EXIT_OUTSIDE_DOCS;
572
+ }
573
+ }
574
+ let message = str(f.message);
575
+ if (message !== undefined) {
576
+ message = fill(message, attempt);
577
+ if (message.includes(DONE_TOKEN)) {
578
+ const done = doneDescription(path.resolve(ctx.cwd, artifacts[0] ?? ""));
579
+ message = message.split(DONE_TOKEN).join(done || fill(str(f.doneFallback) ?? "", attempt));
580
+ }
581
+ if (f.verboseCiLocal === true &&
582
+ runOrStepField(readRuns(file), workflow, "pushMode") === "LOCAL")
583
+ message += " bkit [verbose ci]";
584
+ }
585
+ const written = writeStepRow(ctx.cwd, {
586
+ file,
587
+ workflow,
588
+ step,
589
+ verdict,
590
+ failures,
591
+ attempt,
592
+ subPlan,
593
+ strategy,
594
+ artifacts,
595
+ extras,
596
+ parentSha: str(f.parentSha),
597
+ commit: commit,
598
+ message,
599
+ }, ctx.log);
600
+ const checks = gateChecks(ctx.cwd, {
601
+ file,
602
+ workflow,
603
+ step,
604
+ subPlan,
605
+ attempt,
606
+ artifacts,
607
+ verdictRequired: false,
608
+ allowed,
609
+ placeholders: [],
610
+ });
611
+ // The step's tracker comment: header fields in one fixed order.
612
+ let comment = null;
613
+ const number = str(f.number);
614
+ if (number !== undefined) {
615
+ const title = str(f.title);
616
+ if (title === undefined)
617
+ throw new CommandError(EXIT.USAGE, "--number needs --title");
618
+ const count = str(f.subPlanCount);
619
+ const header = [
620
+ ...(verdict === undefined ? [] : [["Verdict", verdict]]),
621
+ ...(failures === undefined ? [] : [["Failures", String(failures)]]),
622
+ ...(scope === undefined ? [] : [["Scope", scope]]),
623
+ ...(subPlan === undefined
624
+ ? []
625
+ : [
626
+ ["Sub-plan", `${subPlan}${count === undefined ? "" : `/${count}`}`],
627
+ ]),
628
+ ...(derived && attempt !== undefined
629
+ ? [["Attempt", String(attempt)]]
630
+ : []),
631
+ ...(strategy === undefined ? [] : [["Strategy", strategy]]),
632
+ ...list(f.countField).map((c) => {
633
+ const key = c.slice(0, c.indexOf("="));
634
+ return [titleCase(key), String(extras[key])];
635
+ }),
636
+ ...Object.entries(fields),
637
+ ...list(f.commentField).map((c) => {
638
+ const eq = c.indexOf("=");
639
+ if (eq <= 0)
640
+ throw new CommandError(EXIT.USAGE, `--comment-field "${c}" must be Name=value`);
641
+ return [c.slice(0, eq), fill(c.slice(eq + 1), attempt)];
642
+ }),
643
+ ];
644
+ const linkRef = str(f.linkRef);
645
+ const tree = str(f.tree);
646
+ const fileArtifacts = artifacts.filter((a) => !isUrl(a));
647
+ comment = buildComment(ctx.cwd, {
648
+ stepNumber: number,
649
+ stepTitle: title,
650
+ fields: header,
651
+ ownerRepo: linkRef === undefined && tree === undefined
652
+ ? undefined
653
+ : (str(f.ownerRepo) ?? resolveRepoSlug(ctx.cwd)),
654
+ tree,
655
+ artifacts: linkRef === undefined ? [] : fileArtifacts,
656
+ ref: linkRef,
657
+ bodyFile: f.commentBody === true ? fileArtifacts[0] : undefined,
658
+ });
659
+ }
660
+ const pass = checks.every((c) => c.ok);
661
+ for (const c of checks.filter((x) => !x.ok))
662
+ ctx.log(`${c.check}: ${c.detail}`);
663
+ ctx.emit({
664
+ verdict: verdict ?? null,
665
+ failures: failures ?? null,
666
+ attempt: attempt ?? null,
667
+ fields,
668
+ row: written.row,
669
+ commit: written.commit,
670
+ pass,
671
+ checks,
672
+ comment,
673
+ });
674
+ if (written.code !== EXIT.OK)
675
+ return written.code;
676
+ return pass ? EXIT.OK : EXIT.NO;
677
+ }
678
+ // ---------------------------------------------------------------------------
679
+ // stub
680
+ // ---------------------------------------------------------------------------
681
+ /** The header a fresh versioned artifact starts with; the subagent fills it in last. */
682
+ export const STUB_HEADER = `Verdict: PENDING\n${VERDICT_END}\n\n`;
683
+ /** `text` without everything up to and including its first `<!-- verdict:end -->` line. */
684
+ export function stripHeader(text) {
685
+ const lines = text.split("\n");
686
+ const end = lines.indexOf(VERDICT_END);
687
+ return end === -1 ? text : lines.slice(end + 1).join("\n");
688
+ }
689
+ // ---------------------------------------------------------------------------
690
+ // Command
691
+ // ---------------------------------------------------------------------------
692
+ const COMMIT_FLAGS = [
693
+ {
694
+ name: "parent-sha",
695
+ type: "string",
696
+ help: "commit the step started from (default: HEAD now, before this commit)",
697
+ },
698
+ { name: "commit", type: "string", help: "auto (default: git add -A + commit) or none" },
699
+ { name: "message", type: "string", help: "commit message (required unless --commit=none)" },
700
+ ];
701
+ export const stepsCommand = {
702
+ noun: "steps",
703
+ summary: "Write a step's status row, finish a step in one call, read a verdict header, check a gate, seed an artifact header.",
704
+ verbs: {
705
+ done: {
706
+ summary: "Append a step-done row and commit it (parentSha captured first).",
707
+ flags: [
708
+ { ...FILE_FLAG, help: "path to status.jsonl (created if absent)" },
709
+ WORKFLOW_FLAG,
710
+ STEP_FLAG,
711
+ { name: "status", type: "string", help: "DONE (default) or FAILED" },
712
+ {
713
+ name: "verdict",
714
+ type: "string",
715
+ help: "PASS|CONCERNS|FAIL, or the set --agent / --allowed gives",
716
+ },
717
+ ...ALLOWED_FLAGS,
718
+ {
719
+ name: "failures",
720
+ type: "string",
721
+ help: "non-negative integer; must agree with --verdict",
722
+ },
723
+ {
724
+ name: "attempt",
725
+ type: "string",
726
+ help: "non-negative integer (0 included), or `next` to derive it from the log",
727
+ },
728
+ SUB_PLAN_FLAG,
729
+ { name: "strategy", type: "string", help: "STANDARD|PIVOT|FINAL" },
730
+ {
731
+ name: "artifact",
732
+ type: "string",
733
+ repeatable: true,
734
+ help: "file the step produced, relative to the working directory, or an https:// URL (a PR)",
735
+ },
736
+ {
737
+ name: "field",
738
+ type: "string",
739
+ repeatable: true,
740
+ help: "extra row field key=value (value parsed as JSON when it is JSON)",
741
+ },
742
+ ...COMMIT_FLAGS,
743
+ ],
744
+ output: {
745
+ row: "the appended step-done row",
746
+ commit: "the new commit's sha, or null with --commit=none",
747
+ },
748
+ exitCodes: {
749
+ [EXIT_NO_STATUS]: "--attempt=next could not read status.jsonl",
750
+ [EXIT_ARTIFACT]: "an --artifact is missing, empty, or outside the working directory",
751
+ [EXIT_COMMIT]: "the row was written but the commit failed",
752
+ },
753
+ run: (ctx) => {
754
+ const f = ctx.flags;
755
+ const file = statusFile(ctx);
756
+ const workflow = String(f.workflow);
757
+ const step = String(f.step);
758
+ const status = str(f.status) ?? "DONE";
759
+ if (!["DONE", "FAILED"].includes(status))
760
+ throw new CommandError(EXIT.USAGE, "--status must be DONE or FAILED");
761
+ const verdict = str(f.verdict);
762
+ const allowed = allowedVerdicts(f);
763
+ if (verdict !== undefined && !allowed.includes(verdict)) {
764
+ throw new CommandError(EXIT.USAGE, `--verdict must be ${allowed.join("|")}`);
765
+ }
766
+ const failures = nonNegativeInt(f.failures, "failures");
767
+ const mismatch = failuresProblem(verdict, failures);
768
+ if (mismatch)
769
+ throw new CommandError(EXIT.USAGE, mismatch);
770
+ const strategy = str(f.strategy);
771
+ if (strategy !== undefined && !STRATEGIES.includes(strategy)) {
772
+ throw new CommandError(EXIT.USAGE, "--strategy must be STANDARD|PIVOT|FINAL");
773
+ }
774
+ const subPlan = positiveInt(f.subPlan, "sub-plan");
775
+ const commit = str(f.commit) ?? "auto";
776
+ if (!["auto", "none"].includes(commit))
777
+ throw new CommandError(EXIT.USAGE, "--commit must be auto or none");
778
+ const artifacts = list(f.artifact);
779
+ const bad = artifacts.map((a) => artifactProblem(ctx.cwd, a)).filter(Boolean);
780
+ if (bad.length > 0)
781
+ throw new CommandError(EXIT_ARTIFACT, bad.join("; "));
782
+ const attempt = f.attempt === "next"
783
+ ? derivedCounter(file, workflow, `${step}:next`, subPlan, undefined)
784
+ : nonNegativeInt(f.attempt, "attempt");
785
+ const written = writeStepRow(ctx.cwd, {
786
+ file,
787
+ workflow,
788
+ step,
789
+ status: status,
790
+ verdict,
791
+ failures,
792
+ attempt,
793
+ subPlan,
794
+ strategy,
795
+ artifacts,
796
+ extras: Object.fromEntries(list(f.field).map(extraField)),
797
+ parentSha: str(f.parentSha),
798
+ commit: commit,
799
+ message: str(f.message),
800
+ }, ctx.log);
801
+ ctx.emit({ row: written.row, commit: written.commit });
802
+ return written.code;
803
+ },
804
+ },
805
+ finish: {
806
+ summary: "End a step: read the verdict header(s), derive the attempt, check the gate, write the row, commit, print the tracker comment.",
807
+ flags: [
808
+ { ...FILE_FLAG, help: "path to status.jsonl (created if absent)" },
809
+ WORKFLOW_FLAG,
810
+ STEP_FLAG,
811
+ {
812
+ name: "artifact",
813
+ type: "string",
814
+ repeatable: true,
815
+ help: `file the step produced (or an https:// URL); ${ATTEMPT_TOKEN} becomes the attempt`,
816
+ },
817
+ {
818
+ name: "optional-artifact",
819
+ type: "string",
820
+ repeatable: true,
821
+ help: "an artifact recorded (and checked) only when the file exists",
822
+ },
823
+ {
824
+ name: "agent",
825
+ type: "string",
826
+ repeatable: true,
827
+ help: "subagent whose prompt declares the header of the --artifact in the same position; verdicts worst-of, Failures summed",
828
+ },
829
+ {
830
+ name: "verdict",
831
+ type: "string",
832
+ help: "the verdict, when no --agent reads it (checked against --allowed)",
833
+ },
834
+ { name: "allowed", type: "string", help: "allowed --verdict values, comma-separated" },
835
+ { name: "failures", type: "string", help: "failure count, when no --agent reads it" },
836
+ {
837
+ name: "attempt",
838
+ type: "string",
839
+ help: "non-negative integer, or `next` (this step's count + 1)",
840
+ },
841
+ {
842
+ name: "attempt-of",
843
+ type: "string",
844
+ help: "<step>:<next|current|count> — the attempt is that step's counter in the active run",
845
+ },
846
+ {
847
+ name: "since",
848
+ type: "string",
849
+ help: "run field holding a timestamp (soakEntryAt); only rows after it count",
850
+ },
851
+ {
852
+ name: "count-field",
853
+ type: "string",
854
+ repeatable: true,
855
+ help: "key=<step>:<next|current|count>[:<since>] — a row field holding another counter",
856
+ },
857
+ SUB_PLAN_FLAG,
858
+ {
859
+ name: "strategy",
860
+ type: "string",
861
+ help: "STANDARD|PIVOT|FINAL (default: the agent header's Strategy)",
862
+ },
863
+ { name: "scope", type: "string", help: "test scope: row field scope, comment Scope" },
864
+ {
865
+ name: "field",
866
+ type: "string",
867
+ repeatable: true,
868
+ help: "extra row field key=value (value parsed as JSON when it is JSON)",
869
+ },
870
+ {
871
+ name: "clamp-log",
872
+ type: "string",
873
+ help: `<step>[:<attempt>] — read that clamp log into the row's clamped (${ATTEMPT_TOKEN} allowed)`,
874
+ },
875
+ {
876
+ name: "docs-only",
877
+ type: "boolean",
878
+ help: "refuse (exit 9) when the step staged anything outside docs/plans/ and the docs ledgers",
879
+ },
880
+ ...COMMIT_FLAGS.map((c) => c.name === "message"
881
+ ? {
882
+ ...c,
883
+ help: `commit message; ${ATTEMPT_TOKEN} becomes the attempt, ${DONE_TOKEN} the first artifact's first DONE line`,
884
+ }
885
+ : c),
886
+ {
887
+ name: "done-fallback",
888
+ type: "string",
889
+ help: `${DONE_TOKEN} when the artifact has no DONE line`,
890
+ },
891
+ {
892
+ name: "verbose-ci-local",
893
+ type: "boolean",
894
+ help: "append ` bkit [verbose ci]` to the message when the run's pushMode is LOCAL",
895
+ },
896
+ { name: "number", type: "string", help: "step number: print the step's tracker comment" },
897
+ { name: "title", type: "string", help: "step title for the comment heading" },
898
+ { name: "sub-plan-count", type: "string", help: "y of the comment's Sub-plan x/y" },
899
+ {
900
+ name: "link-ref",
901
+ type: "string",
902
+ help: "link the file artifacts at this ref in the comment",
903
+ },
904
+ { name: "tree", type: "string", help: "link the tree of this ref in the comment" },
905
+ {
906
+ name: "owner-repo",
907
+ type: "string",
908
+ help: "owner/repo for the links (default: the origin remote)",
909
+ },
910
+ {
911
+ name: "comment-body",
912
+ type: "boolean",
913
+ help: "append the first artifact verbatim to the comment (summaries)",
914
+ },
915
+ {
916
+ name: "comment-field",
917
+ type: "string",
918
+ repeatable: true,
919
+ help: "extra comment header field Name=value",
920
+ },
921
+ ],
922
+ output: {
923
+ verdict: "the verdict recorded (worst of the agents' headers), or null",
924
+ failures: "failures recorded (summed over the agents' headers), or null",
925
+ attempt: "the attempt recorded, or null",
926
+ fields: "the other header fields the agents' prompts declare (Spike, Mode, Affected)",
927
+ row: "the appended step-done row",
928
+ commit: "the new commit's sha, or null with --commit=none",
929
+ pass: "every gate check passed",
930
+ checks: "[{check, ok, detail}] per gate check",
931
+ comment: "the step's tracker comment body (with --number), else null",
932
+ reask: "verdict read failed: {agent, artifact} to re-ask (exit 4 / 5 / 6 only)",
933
+ problem: "why the verdict read failed (exit 4 / 5 / 6 only)",
934
+ },
935
+ exitCodes: {
936
+ [EXIT_NO_STATUS]: "status.jsonl is not valid NDJSON",
937
+ [EXIT_EMPTY]: "an --agent's artifact is missing or empty (nothing written)",
938
+ [EXIT_PENDING]: "an --agent's header still has a PENDING field — re-ask it (nothing written)",
939
+ [EXIT_INVALID]: "an --agent's header is invalid (no verdict:end, a value outside its set, Failures disagreeing with Verdict) — re-ask it (nothing written)",
940
+ [EXIT_ARTIFACT]: "an --artifact is missing, empty, or outside the working directory (nothing written)",
941
+ [EXIT_COMMIT]: "the row was written but the commit failed",
942
+ [EXIT_OUTSIDE_DOCS]: "--docs-only and the step staged a file outside the artifact tree (nothing written)",
943
+ },
944
+ run: finish,
945
+ },
946
+ verdict: {
947
+ summary: "Read an artifact's header down to <!-- verdict:end -->.",
948
+ flags: [
949
+ { name: "file", type: "string", required: true, help: "the subagent's artifact" },
950
+ ...ALLOWED_FLAGS,
951
+ {
952
+ name: "field",
953
+ type: "string",
954
+ repeatable: true,
955
+ help: "header field that must be present, e.g. Failures",
956
+ },
957
+ ],
958
+ output: { verdict: "the Verdict value", fields: "every Key: value header field" },
959
+ exitCodes: {
960
+ [EXIT_EMPTY]: "artifact missing or empty",
961
+ [EXIT_PENDING]: "a header field is still PENDING",
962
+ [EXIT_INVALID]: "no verdict:end line, Verdict outside the allowed set, or a required field missing — re-prompt the subagent",
963
+ },
964
+ run: (ctx) => {
965
+ const header = readHeader(path.resolve(ctx.cwd, String(ctx.flags.file)), allowedVerdicts(ctx.flags), list(ctx.flags.field));
966
+ if (!header.ok) {
967
+ ctx.log(header.problem);
968
+ return header.code;
969
+ }
970
+ ctx.emit({ verdict: header.verdict, fields: header.fields });
971
+ return EXIT.OK;
972
+ },
973
+ },
974
+ gate: {
975
+ summary: "Mechanical gate checks for one step: placeholders, FID, lock, artifacts, verdict, status row (with its attempt / strategy / scope where the step writes them).",
976
+ flags: [
977
+ {
978
+ ...FILE_FLAG,
979
+ required: false,
980
+ help: "path to status.jsonl; without it the status row is not checked (Step 1)",
981
+ },
982
+ WORKFLOW_FLAG,
983
+ STEP_FLAG,
984
+ SUB_PLAN_FLAG,
985
+ {
986
+ name: "attempt",
987
+ type: "string",
988
+ help: "the row must carry this attempt (non-negative integer)",
989
+ },
990
+ {
991
+ name: "attempt-of",
992
+ type: "string",
993
+ help: "<step>:<next|current|count> — the row must carry that counter as its attempt",
994
+ },
995
+ {
996
+ name: "artifact",
997
+ type: "string",
998
+ repeatable: true,
999
+ help: `artifact the step must have produced (${ATTEMPT_TOKEN} becomes the attempt)`,
1000
+ },
1001
+ {
1002
+ name: "verdict-required",
1003
+ type: "boolean",
1004
+ help: "the artifact header and the row must carry a valid verdict",
1005
+ },
1006
+ ...ALLOWED_FLAGS,
1007
+ {
1008
+ name: "placeholder",
1009
+ type: "string",
1010
+ repeatable: true,
1011
+ help: "NAME=value — the held placeholder must be non-empty",
1012
+ },
1013
+ { name: "fid", type: "string", help: "the FID must match the wired tracker's shape" },
1014
+ { name: "month", type: "string", help: "month bucket of the lock (with --token)" },
1015
+ {
1016
+ name: "token",
1017
+ type: "string",
1018
+ help: "the workflow lock must be held with this token (needs --fid)",
1019
+ },
1020
+ {
1021
+ name: "dev-pushes",
1022
+ type: "boolean",
1023
+ help: "ship only: the lock lives in the main checkout",
1024
+ },
1025
+ ],
1026
+ output: { pass: "true when every check passed", checks: "[{check, ok, detail}] per check" },
1027
+ exitCodes: {
1028
+ [EXIT_NO_STATUS]: "status.jsonl missing, unreadable, or not valid NDJSON",
1029
+ },
1030
+ run: (ctx) => {
1031
+ const f = ctx.flags;
1032
+ const file = str(f.file) === undefined ? undefined : statusFile(ctx);
1033
+ const workflow = String(f.workflow);
1034
+ const subPlan = positiveInt(f.subPlan, "sub-plan");
1035
+ if (f.attempt !== undefined && f.attemptOf !== undefined)
1036
+ throw new CommandError(EXIT.USAGE, "give --attempt or --attempt-of, not both");
1037
+ if (f.attemptOf !== undefined && file === undefined)
1038
+ throw new CommandError(EXIT.USAGE, "--attempt-of needs --file");
1039
+ const attempt = f.attemptOf !== undefined
1040
+ ? derivedCounter(file, workflow, String(f.attemptOf), subPlan, undefined)
1041
+ : nonNegativeInt(f.attempt, "attempt");
1042
+ const checks = gateChecks(ctx.cwd, {
1043
+ file,
1044
+ workflow,
1045
+ step: String(f.step),
1046
+ subPlan,
1047
+ attempt,
1048
+ artifacts: list(f.artifact).map((a) => fill(a, attempt)),
1049
+ verdictRequired: f.verdictRequired === true,
1050
+ allowed: allowedVerdicts(f),
1051
+ fid: str(f.fid),
1052
+ month: str(f.month),
1053
+ token: str(f.token),
1054
+ devPushes: f.devPushes === true,
1055
+ placeholders: list(f.placeholder),
1056
+ });
1057
+ const pass = checks.every((c) => c.ok);
1058
+ for (const c of checks.filter((x) => !x.ok))
1059
+ ctx.log(`${c.check}: ${c.detail}`);
1060
+ ctx.emit({ pass, checks });
1061
+ return pass ? EXIT.OK : EXIT.NO;
1062
+ },
1063
+ },
1064
+ stub: {
1065
+ summary: "Seed a versioned artifact: copy the prior version, then put a PENDING verdict header on top.",
1066
+ flags: [
1067
+ { name: "from", type: "string", required: true, help: "the prior versioned artifact" },
1068
+ { name: "to", type: "string", required: true, help: "the artifact to create" },
1069
+ {
1070
+ name: "strip-header",
1071
+ type: "boolean",
1072
+ help: "drop the prior version's own header (everything down to its <!-- verdict:end -->)",
1073
+ },
1074
+ ],
1075
+ output: { file: "the artifact written", stripped: "the prior header was dropped" },
1076
+ exitCodes: { [EXIT_EMPTY]: "--from is missing or empty" },
1077
+ run: (ctx) => {
1078
+ const from = path.resolve(ctx.cwd, String(ctx.flags.from));
1079
+ if (!fs.existsSync(from) || fs.statSync(from).size === 0) {
1080
+ ctx.log(`${String(ctx.flags.from)} is missing or empty`);
1081
+ return EXIT_EMPTY;
1082
+ }
1083
+ const body = fs.readFileSync(from, "utf-8");
1084
+ const stripped = ctx.flags.stripHeader === true;
1085
+ const to = path.resolve(ctx.cwd, String(ctx.flags.to));
1086
+ fs.mkdirSync(path.dirname(to), { recursive: true });
1087
+ fs.writeFileSync(to, STUB_HEADER + (stripped ? stripHeader(body) : body));
1088
+ ctx.emit({ file: String(ctx.flags.to), stripped });
1089
+ return EXIT.OK;
1090
+ },
1091
+ },
1092
+ },
1093
+ };