@cbartens/bkit 0.0.0-stage → 5.0.1

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 (375) hide show
  1. package/.bkit/README.md +417 -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 +417 -0
  8. package/.bkit/core/.bkit/cloud.md +493 -0
  9. package/.bkit/core/.bkit/comparison.md +321 -0
  10. package/.bkit/core/.bkit/install.md +401 -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 +470 -0
  15. package/.bkit/core/.bkit/trackers.md +95 -0
  16. package/.bkit/core/.bkit/workflows.md +1550 -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 +149 -0
  65. package/.bkit/core/engine/checks/after/ci-yml.ts +701 -0
  66. package/.bkit/core/engine/checks/after/github.ts +424 -0
  67. package/.bkit/core/engine/checks/after/index.ts +530 -0
  68. package/.bkit/core/engine/checks/after/managed.ts +217 -0
  69. package/.bkit/core/engine/checks/after/suppression.ts +53 -0
  70. package/.bkit/core/engine/checks/after/tools.ts +427 -0
  71. package/.bkit/core/engine/checks/before/context-fetch.ts +429 -0
  72. package/.bkit/core/engine/checks/before/env.ts +187 -0
  73. package/.bkit/core/engine/checks/before/files.ts +204 -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 +867 -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 +254 -0
  86. package/.bkit/core/engine/commands/install/install.ts +550 -0
  87. package/.bkit/core/engine/commands/install/uninstall.ts +995 -0
  88. package/.bkit/core/engine/commands/install/upgrade.ts +1037 -0
  89. package/.bkit/core/engine/commands/launch.ts +139 -0
  90. package/.bkit/core/engine/commands/lib.ts +495 -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 +924 -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 +173 -0
  118. package/.bkit/core/engine/install/modules/codex.ts +219 -0
  119. package/.bkit/core/engine/install/modules/core.ts +620 -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/payload-links.ts +150 -0
  124. package/.bkit/core/engine/install/placeholders.ts +108 -0
  125. package/.bkit/core/engine/install/template-copies.ts +119 -0
  126. package/.bkit/core/engine/install/version-file.ts +284 -0
  127. package/.bkit/core/engine/install/write.ts +467 -0
  128. package/.bkit/core/engine/ledgers/clamp-log.ts +32 -0
  129. package/.bkit/core/engine/ledgers/status.ts +213 -0
  130. package/.bkit/core/engine/ledgers/telemetry.ts +1143 -0
  131. package/.bkit/core/engine/render/hosts.ts +372 -0
  132. package/.bkit/core/engine/render/models.ts +323 -0
  133. package/.bkit/core/engine/render/parts.ts +38 -0
  134. package/.bkit/core/engine/render/trackers.ts +170 -0
  135. package/.bkit/core/engine/shared/egress.ts +345 -0
  136. package/.bkit/core/engine/shared/json.ts +16 -0
  137. package/.bkit/core/engine/shared/log-prefix.ts +9 -0
  138. package/.bkit/core/engine/shared/package-json.ts +29 -0
  139. package/.bkit/core/engine/shared/package-manager.ts +38 -0
  140. package/.bkit/core/engine/shared/package-roots.ts +163 -0
  141. package/.bkit/core/engine/shared/protected-paths.ts +164 -0
  142. package/.bkit/core/engine/shared/settings.ts +72 -0
  143. package/.bkit/core/engine/shared/timeouts.ts +20 -0
  144. package/.bkit/core/engine/tools/wording.ts +748 -0
  145. package/.bkit/core/hooks/gateguard-edit-payload.js +18 -0
  146. package/.bkit/core/hooks/gateguard-engine.js +193 -0
  147. package/.bkit/core/hooks/guardrails-shell.js +154 -0
  148. package/.bkit/core/hooks/guardrails-tiers.js +68 -0
  149. package/.bkit/core/hooks/preflight-linear.sh +73 -0
  150. package/.bkit/core/prompts/bkit-audit-generate.md +66 -0
  151. package/.bkit/core/prompts/bkit-build-challenge-1.md +79 -0
  152. package/.bkit/core/prompts/bkit-build-challenge-2.md +81 -0
  153. package/.bkit/core/prompts/bkit-build-challenge-reconcile.md +68 -0
  154. package/.bkit/core/prompts/bkit-build-challenge-remediate.md +70 -0
  155. package/.bkit/core/prompts/bkit-build-challenge-tests.md +73 -0
  156. package/.bkit/core/prompts/bkit-build-install-skills.md +67 -0
  157. package/.bkit/core/prompts/bkit-build-plan-current.md +75 -0
  158. package/.bkit/core/prompts/bkit-build-plan-execute.md +72 -0
  159. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +73 -0
  160. package/.bkit/core/prompts/bkit-build-plan-verify.md +88 -0
  161. package/.bkit/core/prompts/bkit-build-summary.md +93 -0
  162. package/.bkit/core/prompts/bkit-debug-abort-handover.md +90 -0
  163. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +151 -0
  164. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +78 -0
  165. package/.bkit/core/prompts/bkit-debug-failure-soak.md +73 -0
  166. package/.bkit/core/prompts/bkit-debug-summary.md +95 -0
  167. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +72 -0
  168. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +72 -0
  169. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +75 -0
  170. package/.bkit/core/prompts/bkit-design-generate.md +110 -0
  171. package/.bkit/core/prompts/bkit-design-organise.md +85 -0
  172. package/.bkit/core/prompts/bkit-design-review-1.md +121 -0
  173. package/.bkit/core/prompts/bkit-design-review-2.md +111 -0
  174. package/.bkit/core/prompts/bkit-design-spike.md +97 -0
  175. package/.bkit/core/prompts/bkit-design-summary.md +106 -0
  176. package/.bkit/core/prompts/bkit-design-update.md +66 -0
  177. package/.bkit/core/prompts/bkit-plan-complexity-check.md +66 -0
  178. package/.bkit/core/prompts/bkit-plan-complexity-split.md +87 -0
  179. package/.bkit/core/prompts/bkit-plan-generate.md +74 -0
  180. package/.bkit/core/prompts/bkit-plan-review-1.md +90 -0
  181. package/.bkit/core/prompts/bkit-plan-review-2.md +80 -0
  182. package/.bkit/core/prompts/bkit-plan-review-3.md +92 -0
  183. package/.bkit/core/prompts/bkit-plan-scope-check-1.md +84 -0
  184. package/.bkit/core/prompts/bkit-plan-scope-check-2.md +84 -0
  185. package/.bkit/core/prompts/bkit-plan-summary.md +106 -0
  186. package/.bkit/core/prompts/bkit-plan-update.md +68 -0
  187. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +90 -0
  188. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +94 -0
  189. package/.bkit/core/prompts/bkit-ship-summary.md +77 -0
  190. package/.bkit/core/prompts/bkit-ship-update-docs.md +71 -0
  191. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +91 -0
  192. package/.bkit/core/prompts/bkit-utility-update-decisions.md +75 -0
  193. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +76 -0
  194. package/.bkit/core/prompts/bkit-utility-update-documentation.md +61 -0
  195. package/.bkit/core/prompts/bkit-utility-update-failures.md +76 -0
  196. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +75 -0
  197. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +82 -0
  198. package/.bkit/core/workflows/bkit-auto.md +121 -0
  199. package/.bkit/core/workflows/bkit-build.md +802 -0
  200. package/.bkit/core/workflows/bkit-debug.md +649 -0
  201. package/.bkit/core/workflows/bkit-design.md +495 -0
  202. package/.bkit/core/workflows/bkit-plan.md +510 -0
  203. package/.bkit/core/workflows/bkit-ship.md +650 -0
  204. package/.bkit/shared/.bkit/.env.example +86 -0
  205. package/.bkit/shared/.claude/bkit-cloud.md +117 -0
  206. package/.bkit/shared/.claude/settings.json +88 -0
  207. package/.bkit/shared/.codex/hooks.json +26 -0
  208. package/.bkit/shared/.cursor/bkit-cloud.md +84 -0
  209. package/.bkit/shared/.cursor/hooks.json +26 -0
  210. package/.bkit/shared/.cursor/mcp.json +15 -0
  211. package/.bkit/shared/.cursor/rules/bkit-rules.mdc +12 -0
  212. package/.bkit/shared/.gitattributes +37 -0
  213. package/.bkit/shared/.mcp.json +16 -0
  214. package/.bkit/shared/.opencode/opencode.json +62 -0
  215. package/.bkit/shared/CLAUDE.md +11 -0
  216. package/.bkit/shared/LICENSE.md +22 -0
  217. package/.bkit/shared/docs/architecture.md +19 -0
  218. package/.bkit/shared/docs/data-schema.md +19 -0
  219. package/.bkit/shared/docs/deployments.md +433 -0
  220. package/.bkit/shared/docs/design.md +39 -0
  221. package/.bkit/shared/docs/noise.md +19 -0
  222. package/.bkit/shared/docs/observability.md +25 -0
  223. package/.bkit/shared/docs/security.md +42 -0
  224. package/.bkit/shared/docs/setup.md +30 -0
  225. package/.bkit/shared/docs/technology.md +18 -0
  226. package/.bkit/shared/docs/testing.md +413 -0
  227. package/.bkit/shared/gitignore +97 -0
  228. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +187 -0
  229. package/.bkit/templates/.cursor/Dockerfile +68 -0
  230. package/.bkit/templates/.cursor/environment.json +6 -0
  231. package/.bkit/templates/.cursor/settings.json +11 -0
  232. package/.bkit/templates/.envrc +7 -0
  233. package/.bkit/templates/.github/dependabot.yml +52 -0
  234. package/.bkit/templates/.github/renovate.json5 +224 -0
  235. package/.bkit/templates/.github/workflows/bkit-ci.yml +1062 -0
  236. package/.bkit/templates/.github/workflows/bkit-cloud.yml +564 -0
  237. package/.bkit/templates/.github/workflows/bkit-renovate.yml +102 -0
  238. package/.bkit/templates/.graphifyignore +108 -0
  239. package/.bkit/templates/.husky/pre-commit +16 -0
  240. package/.bkit/templates/.husky/pre-push +91 -0
  241. package/.bkit/templates/.lintstagedrc.json +3 -0
  242. package/.bkit/templates/.prettierignore +41 -0
  243. package/.bkit/templates/.serena/project.yml +243 -0
  244. package/.bkit/templates/.vale/styles/House/Filler.yml +11 -0
  245. package/.bkit/templates/.vale/styles/House/Hedging.yml +12 -0
  246. package/.bkit/templates/.vale/styles/House/LLMSlop.yml +13 -0
  247. package/.bkit/templates/.vale/styles/House/Verbose.yml +12 -0
  248. package/.bkit/templates/.vale.ini +67 -0
  249. package/.bkit/templates/LICENSE.md +22 -0
  250. package/.bkit/templates/context/bkit-cloudrun.md +84 -0
  251. package/.bkit/templates/context/bkit-expo.md +186 -0
  252. package/.bkit/templates/context/bkit-github.md +79 -0
  253. package/.bkit/templates/context/bkit-inngest.md +45 -0
  254. package/.bkit/templates/context/bkit-maestro.md +76 -0
  255. package/.bkit/templates/context/bkit-playwright.md +62 -0
  256. package/.bkit/templates/context/bkit-resend.md +36 -0
  257. package/.bkit/templates/context/bkit-sentry.md +65 -0
  258. package/.bkit/templates/context/bkit-serena.md +33 -0
  259. package/.bkit/templates/context/bkit-stripe.md +36 -0
  260. package/.bkit/templates/context/bkit-supabase.md +59 -0
  261. package/.bkit/templates/context/bkit-tavily.md +49 -0
  262. package/.bkit/templates/context/bkit-vercel.md +64 -0
  263. package/.bkit/templates/docs/capabilities.md +72 -0
  264. package/.bkit/templates/scripts/ci/accepted-divergences.json +21 -0
  265. package/.bkit/templates/scripts/ci/check-accepted-divergences.mjs +152 -0
  266. package/.bkit/templates/scripts/ci/check-accepted-divergences.test.mjs +130 -0
  267. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.mjs +98 -0
  268. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.test.mjs +86 -0
  269. package/.bkit/templates/scripts/graphify/bkit-graph-drift-rules.json +23 -0
  270. package/.bkit/templates/scripts/graphify/bkit-graph-drift.py +208 -0
  271. package/.bkit/templates/scripts/graphify/bkit-graph-eager-rules.json +35 -0
  272. package/.bkit/templates/scripts/graphify/bkit-graph-eager.py +236 -0
  273. package/.bkit/templates/scripts/graphify/bkit-graph-external-rules.json +17 -0
  274. package/.bkit/templates/scripts/graphify/bkit-graph-imports.py +290 -0
  275. package/.bkit/templates/scripts/graphify/bkit-graph-pre-push.sh +19 -0
  276. package/.bkit/templates/scripts/graphify/bkit-graph-repair.py +120 -0
  277. package/.bkit/templates/scripts/graphify/bkit-graph-surface.py +232 -0
  278. package/.bkit/templates/scripts/graphify/bkit-graphify-graphml.py +36 -0
  279. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +927 -0
  280. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +351 -0
  281. package/.bkit/templates/scripts/launchd/ai.bkit.launchd.plist +26 -0
  282. package/.bkit/templates/scripts/launchd/bkit-launchd-env.sh +53 -0
  283. package/.bkit/templates/scripts/launchd/launchd.env.example +13 -0
  284. package/.bkit/templates/scripts/prettier/bkit-insert-ignore.mjs +275 -0
  285. package/.bkit/templates/scripts/secrets/bkit-secrets.config.mjs +66 -0
  286. package/.bkit/templates/scripts/secrets/bkit-secrets.mjs +785 -0
  287. package/.bkit/templates/scripts/serena/bkit-serena-mcp.sh +30 -0
  288. package/.bkit/templates/scripts/serena/bkit-serena.mcp.json +9 -0
  289. package/.bkit/templates/scripts/slop/bkit-slop-type-suppression.mjs +286 -0
  290. package/.bkit/templates/slop-scan.config.json +120 -0
  291. package/CHANGELOG.md +1503 -0
  292. package/LICENSE.md +161 -0
  293. package/README.md +184 -2
  294. package/dist/checks/after/auth.js +140 -0
  295. package/dist/checks/after/ci-yml.js +681 -0
  296. package/dist/checks/after/github.js +400 -0
  297. package/dist/checks/after/index.js +431 -0
  298. package/dist/checks/after/managed.js +187 -0
  299. package/dist/checks/after/suppression.js +39 -0
  300. package/dist/checks/after/tools.js +351 -0
  301. package/dist/checks/before/context-fetch.js +426 -0
  302. package/dist/checks/before/env.js +163 -0
  303. package/dist/checks/before/files.js +187 -0
  304. package/dist/checks/before/index.js +162 -0
  305. package/dist/checks/before/mcp.js +111 -0
  306. package/dist/checks/before/repo.js +71 -0
  307. package/dist/checks/before/version.js +60 -0
  308. package/dist/checks/status-holes.js +393 -0
  309. package/dist/cli.js +688 -0
  310. package/dist/commands/analysis.js +325 -0
  311. package/dist/commands/ci/ci.js +438 -0
  312. package/dist/commands/comply.js +310 -0
  313. package/dist/commands/harvest.js +354 -0
  314. package/dist/commands/install/check.js +61 -0
  315. package/dist/commands/install/doctor.js +209 -0
  316. package/dist/commands/install/install.js +475 -0
  317. package/dist/commands/install/uninstall.js +839 -0
  318. package/dist/commands/install/upgrade.js +782 -0
  319. package/dist/commands/launch.js +118 -0
  320. package/dist/commands/lib.js +363 -0
  321. package/dist/commands/registry.js +50 -0
  322. package/dist/commands/setup/setup.js +158 -0
  323. package/dist/commands/telemetry.js +29 -0
  324. package/dist/commands/workflow/branches.js +1265 -0
  325. package/dist/commands/workflow/context.js +846 -0
  326. package/dist/commands/workflow/counters.js +227 -0
  327. package/dist/commands/workflow/fids.js +224 -0
  328. package/dist/commands/workflow/issues.js +585 -0
  329. package/dist/commands/workflow/ledgers.js +472 -0
  330. package/dist/commands/workflow/locks.js +364 -0
  331. package/dist/commands/workflow/prs.js +904 -0
  332. package/dist/commands/workflow/repo.js +199 -0
  333. package/dist/commands/workflow/roadmap.js +495 -0
  334. package/dist/commands/workflow/runs.js +1717 -0
  335. package/dist/commands/workflow/runtime.js +257 -0
  336. package/dist/commands/workflow/skills.js +110 -0
  337. package/dist/commands/workflow/status.js +392 -0
  338. package/dist/commands/workflow/steps.js +1093 -0
  339. package/dist/commands/workflow/tests.js +144 -0
  340. package/dist/commands/workflow/workflows.js +1342 -0
  341. package/dist/commands/workflow/workstreams.js +141 -0
  342. package/dist/commands/workflow/worktrees.js +473 -0
  343. package/dist/install/cloud-env.js +818 -0
  344. package/dist/install/managed-block.js +182 -0
  345. package/dist/install/manifest.js +376 -0
  346. package/dist/install/modules/claude.js +288 -0
  347. package/dist/install/modules/cloud.js +151 -0
  348. package/dist/install/modules/codex.js +193 -0
  349. package/dist/install/modules/core.js +531 -0
  350. package/dist/install/modules/cursor.js +186 -0
  351. package/dist/install/modules/index.js +152 -0
  352. package/dist/install/modules/opencode.js +504 -0
  353. package/dist/install/payload-links.js +119 -0
  354. package/dist/install/placeholders.js +87 -0
  355. package/dist/install/template-copies.js +106 -0
  356. package/dist/install/version-file.js +204 -0
  357. package/dist/install/write.js +342 -0
  358. package/dist/ledgers/clamp-log.js +27 -0
  359. package/dist/ledgers/status.js +156 -0
  360. package/dist/ledgers/telemetry.js +637 -0
  361. package/dist/render/hosts.js +339 -0
  362. package/dist/render/models.js +288 -0
  363. package/dist/render/parts.js +33 -0
  364. package/dist/render/trackers.js +135 -0
  365. package/dist/shared/egress.js +299 -0
  366. package/dist/shared/json.js +16 -0
  367. package/dist/shared/log-prefix.js +7 -0
  368. package/dist/shared/package-json.js +22 -0
  369. package/dist/shared/package-manager.js +32 -0
  370. package/dist/shared/package-roots.js +145 -0
  371. package/dist/shared/protected-paths.js +153 -0
  372. package/dist/shared/settings.js +44 -0
  373. package/dist/shared/timeouts.js +19 -0
  374. package/dist/tools/wording.js +680 -0
  375. package/package.json +101 -4
@@ -0,0 +1,637 @@
1
+ // Contract + codec for the bkit unified JSONL telemetry ledgers.
2
+ //
3
+ // Generalises the per-FID `status.jsonl` machine into a family of append-only
4
+ // NDJSON ledgers governed by ONE canonical TypeScript reducer:
5
+ //
6
+ // .bkit/stats.jsonl — compliance, outcome, counter rows
7
+ // .bkit/friction.jsonl — friction entries
8
+ // docs/deferrals.jsonl — deferred work
9
+ // docs/failures.jsonl — discovered bugs
10
+ //
11
+ // LOAD-BEARING DIVERGENCES FROM ledgers/status.ts (NOT inherited — each pinned by test):
12
+ // (a) Tolerant `parse`: per-line try/catch + skip + malformedLineCount.
13
+ // (b) `validate` REJECTS unknown `kind` before write. No reject path in status.ts.
14
+ // (c) ms `ts` via now*1000|floor, NOT ISO `at`.
15
+ //
16
+ // Version provenance: every row records the emitting `bkitVersion`. Readers ingest
17
+ // ALL well-formed rows (no version gating) and report row counts per `bkitVersion`
18
+ // so an unexpected version surfaces for triage.
19
+ import { spawnSync } from "node:child_process";
20
+ import * as fs from "node:fs";
21
+ // ---------------------------------------------------------------------------
22
+ // Constants
23
+ // ---------------------------------------------------------------------------
24
+ export const MAX_ROWS_BEFORE_ROLLUP = 5000;
25
+ // ---------------------------------------------------------------------------
26
+ // repo — the owner/repo slug, resolved ONE way
27
+ //
28
+ // `repo` is part of identity() for EVERY kind, so a respelled repo FORKS the
29
+ // entity — the same failure the spec warns about for `key`, except `repo` is not
30
+ // authored by anyone: it is derived. It therefore must be derived identically
31
+ // everywhere, from the only authoritative source: the git remote.
32
+ //
33
+ // NOT package.json `name` — that is an npm package name, not a slug
34
+ // (`@cbartens/bkit` vs `cbartens/bkit`). NOT the filesystem path — that makes the
35
+ // "owner" a folder on whoever's laptop ran the tool (`GitHub/my-app`, or
36
+ // `code/my-app` after they reorganise).
37
+ // ---------------------------------------------------------------------------
38
+ /**
39
+ * Parse `owner/repo` out of a git remote URL. Pure — the fiddly half, kept
40
+ * testable without a git repo.
41
+ *
42
+ * Handles HTTPS (`https://github.com/owner/repo.git`), SSH scp-form
43
+ * (`git@github.com:owner/repo.git`) and `ssh://` URLs. Returns "" when the URL
44
+ * yields no `owner/repo` pair rather than guessing.
45
+ */
46
+ export function parseRemoteUrlToSlug(url) {
47
+ const m = url
48
+ .trim()
49
+ .replace(/\.git$/, "")
50
+ .match(/[/:]([^/:]+\/[^/:]+)$/);
51
+ return m?.[1] ?? "";
52
+ }
53
+ /** git env with hook vars scrubbed — see resolveRepoSlug. */
54
+ export function gitEnv() {
55
+ const env = { ...process.env };
56
+ delete env["GIT_DIR"];
57
+ delete env["GIT_WORK_TREE"];
58
+ delete env["GIT_INDEX_FILE"];
59
+ delete env["GIT_OBJECT_DIRECTORY"];
60
+ return env;
61
+ }
62
+ /**
63
+ * Resolve a rev (`HEAD~1`, a branch, a tag) to a full hex SHA. "" if it does not
64
+ * resolve — e.g. `HEAD~1` in a repo with one commit.
65
+ *
66
+ * `parentSha` MUST be resolved before it reaches a row: it is part of identity()
67
+ * for compliance and counter, and the grader's diff guard accepts only hex.
68
+ */
69
+ export function resolveGitSha(rev, cwd) {
70
+ const res = spawnSync("git", ["rev-parse", "--verify", "--quiet", `${rev}^{commit}`], {
71
+ cwd,
72
+ encoding: "utf-8",
73
+ env: gitEnv(),
74
+ stdio: ["ignore", "pipe", "ignore"],
75
+ });
76
+ if (res.status !== 0 || typeof res.stdout !== "string")
77
+ return "";
78
+ const sha = res.stdout.trim();
79
+ return /^[0-9a-f]{7,40}$/.test(sha) ? sha : "";
80
+ }
81
+ /**
82
+ * Resolve a repo's `owner/repo` slug from its git remote. "" when there is no
83
+ * remote or no git repo — callers decide the fallback, loudly.
84
+ *
85
+ * Scrubs GIT_DIR / GIT_WORK_TREE / GIT_INDEX_FILE (exported by git hooks) so
86
+ * `git -C <path>` answers for <path>, not the hook's repo.
87
+ *
88
+ * spawnSync: a non-zero exit ("no remote") is an expected answer, not an exception.
89
+ */
90
+ export function resolveRepoSlug(cwd) {
91
+ const res = spawnSync("git", ["remote", "get-url", "origin"], {
92
+ cwd,
93
+ encoding: "utf-8",
94
+ env: gitEnv(),
95
+ stdio: ["ignore", "pipe", "ignore"],
96
+ });
97
+ if (res.status !== 0 || typeof res.stdout !== "string")
98
+ return "";
99
+ return parseRemoteUrlToSlug(res.stdout);
100
+ }
101
+ export const VALID_KINDS = new Set([
102
+ "compliance",
103
+ "outcome",
104
+ "counter",
105
+ "friction",
106
+ "deferral",
107
+ "failure",
108
+ "knowledge",
109
+ "decision",
110
+ "feature",
111
+ ]);
112
+ export const VALID_SEVERITIES = new Set(["CRITICAL", "HIGH", "MEDIUM", "LOW"]);
113
+ /**
114
+ * Kinds that carry `severity` — and, identically, the kinds that carry the
115
+ * OPEN/TRIAGED/CLOSED ladder. Both express the same property: these three are
116
+ * the author-written kinds that describe OPEN WORK someone triages. Keep in
117
+ * sync with the payload interfaces below.
118
+ */
119
+ export const SEVERITY_KINDS = new Set(["friction", "deferral", "failure"]);
120
+ export const TRIAGE_STATUSES = new Set(["OPEN", "TRIAGED", "CLOSED"]);
121
+ /** The `ACTIVE` / `SUPERSEDED` lifecycle shared by `decision` and `knowledge`. */
122
+ export const DECISION_STATUSES = new Set(["ACTIVE", "SUPERSEDED"]);
123
+ export const FEATURE_STATUSES = new Set([
124
+ "DESIGNED",
125
+ "PLANNED",
126
+ "BUILT",
127
+ "DEBUGGED",
128
+ "SHIPPED",
129
+ "ABANDONED",
130
+ ]);
131
+ export const DEFERRAL_REASONS = new Set([
132
+ "scope-declared",
133
+ "hard-blocked",
134
+ "needs-decision",
135
+ "own-cycle",
136
+ "unjustified",
137
+ ]);
138
+ /**
139
+ * The adjudication verdict: this was in-scope work that should have been finished.
140
+ * Written ONLY by a reviewer judging someone else's deferral — never self-assigned
141
+ * at write time, where the four justifications are the whole legal vocabulary.
142
+ *
143
+ * Set via same-`key` append like any other update, and NEVER rewritten afterwards:
144
+ * a later row that closes the entry carries `unjustified` through verbatim. Feeds
145
+ * `computeDeferralDiscipline` in `commands/analysis.ts`.
146
+ */
147
+ export const UNJUSTIFIED_REASON = "unjustified";
148
+ /**
149
+ * The subagents sanctioned to write a `deferral` row (`.bkit/jsonl.md`
150
+ * § Ledgers & Writers). EXHAUSTIVE: a subagent absent from this set does not
151
+ * write the kind at all.
152
+ *
153
+ * `@bkit-build-plan-execute` and `@bkit-build-plan-gaps-remediate` are not in it: a
154
+ * blocked plan task's record is its `BLOCKED` log line, which the next verify pass reads.
155
+ *
156
+ * Orchestrator-written rows carry no `subagent` and are outside this check.
157
+ */
158
+ export const DEFERRAL_WRITERS = new Set([
159
+ "bkit-design-generate",
160
+ "bkit-plan-generate",
161
+ "bkit-plan-update",
162
+ "bkit-build-challenge-remediate",
163
+ "bkit-debug-abort-handover",
164
+ "bkit-ship-deferred-sweep",
165
+ "bkit-utility-update-deferrals",
166
+ ]);
167
+ // ---------------------------------------------------------------------------
168
+ // Identity — per-kind composite tuple for dedup (NOT bare ts)
169
+ // Mirrors ledgers/status.ts's tuple dedupe approach.
170
+ // ---------------------------------------------------------------------------
171
+ export function identity(event) {
172
+ switch (event.kind) {
173
+ case "compliance":
174
+ return `compliance ${event.repo} ${event.workflow} ${event.parentSha} ${event.rule}`;
175
+ case "outcome": {
176
+ // One run row per workflow run: keyed by (repo, workflow, parentSha).
177
+ // A ship row with no parentSha falls back to prNumber (then ts), so it stays
178
+ // uniquely keyed per PR.
179
+ const anchor = event.parentSha ?? (event.prNumber !== undefined ? `pr${event.prNumber}` : `ts${event.ts}`);
180
+ return `outcome ${event.repo} ${event.workflow} ${anchor}`;
181
+ }
182
+ case "counter":
183
+ return `counter ${event.repo} ${event.workflow} ${event.parentSha} ${event.counterName}`;
184
+ case "friction":
185
+ case "deferral":
186
+ case "failure":
187
+ case "knowledge":
188
+ case "decision":
189
+ case "feature":
190
+ // instinct-loop kinds (+ feature): identity = kind + key
191
+ return `${event.kind} ${event.repo} ${event.key ?? event.ts}`;
192
+ }
193
+ }
194
+ // ---------------------------------------------------------------------------
195
+ // Validate — reject malformed + unknown kind before write
196
+ // ---------------------------------------------------------------------------
197
+ export function validate(event) {
198
+ if (!event || typeof event !== "object") {
199
+ return { ok: false, reason: "event must be an object" };
200
+ }
201
+ const e = event;
202
+ // A2-mandatory envelope fields
203
+ const mandatory = ["ts", "kind", "repo", "bkitVersion", "step"];
204
+ for (const field of mandatory) {
205
+ if (e[field] === undefined || e[field] === null) {
206
+ return { ok: false, reason: `missing mandatory field: ${field}` };
207
+ }
208
+ }
209
+ if (typeof e["ts"] !== "number") {
210
+ return { ok: false, reason: "ts must be a number (ms unix)" };
211
+ }
212
+ if (typeof e["kind"] !== "string") {
213
+ return { ok: false, reason: "kind must be a string" };
214
+ }
215
+ if (!VALID_KINDS.has(e["kind"])) {
216
+ return { ok: false, reason: `unknown kind: ${e["kind"]}` };
217
+ }
218
+ if (typeof e["repo"] !== "string" || e["repo"] === "") {
219
+ return { ok: false, reason: "repo must be a non-empty string" };
220
+ }
221
+ if (typeof e["bkitVersion"] !== "string" || e["bkitVersion"] === "") {
222
+ return { ok: false, reason: "bkitVersion must be a non-empty string" };
223
+ }
224
+ if (typeof e["step"] !== "string" || e["step"] === "") {
225
+ return { ok: false, reason: "step must be a non-empty string" };
226
+ }
227
+ // kind-specific payload validation (minimal — structural check)
228
+ const kind = e["kind"];
229
+ // severity — required on the triaged author-written kinds, rejected elsewhere.
230
+ // Enforced on write only; `parse` stays tolerant so pre-severity rows still read.
231
+ if (SEVERITY_KINDS.has(kind)) {
232
+ if (e["severity"] === undefined || e["severity"] === null) {
233
+ return { ok: false, reason: `${kind} row missing required field: severity` };
234
+ }
235
+ if (!VALID_SEVERITIES.has(e["severity"])) {
236
+ return {
237
+ ok: false,
238
+ reason: `${kind} severity must be one of CRITICAL|HIGH|MEDIUM|LOW (got: ${String(e["severity"])})`,
239
+ };
240
+ }
241
+ }
242
+ else if (e["severity"] !== undefined) {
243
+ return { ok: false, reason: `${kind} rows do not carry severity` };
244
+ }
245
+ // status — triage ladder on the SEVERITY_KINDS trio, ACTIVE/SUPERSEDED lifecycle on
246
+ // decision and knowledge, absent elsewhere. Optional: absent = ACTIVE on that lifecycle.
247
+ // Enforced on write only; `parse` stays tolerant so a free-text status row still reads.
248
+ if (SEVERITY_KINDS.has(kind)) {
249
+ if (e["status"] !== undefined && !TRIAGE_STATUSES.has(e["status"])) {
250
+ return {
251
+ ok: false,
252
+ reason: `${kind} status must be one of OPEN|TRIAGED|CLOSED (got: ${String(e["status"])})`,
253
+ };
254
+ }
255
+ }
256
+ else if (kind === "decision" || kind === "knowledge") {
257
+ if (e["status"] !== undefined && !DECISION_STATUSES.has(e["status"])) {
258
+ return {
259
+ ok: false,
260
+ reason: `${kind} status must be one of ACTIVE|SUPERSEDED (got: ${String(e["status"])})`,
261
+ };
262
+ }
263
+ }
264
+ else if (kind === "feature") {
265
+ // status is REQUIRED on feature (unlike the optional triage ladder) — the
266
+ // roadmap projection has no phase to render without it.
267
+ if (e["status"] === undefined || !FEATURE_STATUSES.has(e["status"])) {
268
+ return {
269
+ ok: false,
270
+ reason: `feature status must be one of DESIGNED|PLANNED|BUILT|DEBUGGED|SHIPPED|ABANDONED (got: ${String(e["status"])})`,
271
+ };
272
+ }
273
+ }
274
+ else if (e["status"] !== undefined) {
275
+ return { ok: false, reason: `${kind} rows do not carry status` };
276
+ }
277
+ // reason — the deferral justification (see DeferralReason). Required on write:
278
+ // an unjustifiable deferral is unfinished work, and the whole point of the field
279
+ // is that it cannot be skipped. Enforced on write only; `parse` stays tolerant so
280
+ // rows appended before the field existed still read.
281
+ if (kind === "deferral") {
282
+ if (e["reason"] === undefined || e["reason"] === null) {
283
+ return { ok: false, reason: "deferral row missing required field: reason" };
284
+ }
285
+ if (!DEFERRAL_REASONS.has(e["reason"])) {
286
+ return {
287
+ ok: false,
288
+ reason: `deferral reason must be one of ${[...DEFERRAL_REASONS].join("|")} (got: ${String(e["reason"])})`,
289
+ };
290
+ }
291
+ }
292
+ else if (e["reason"] !== undefined) {
293
+ return { ok: false, reason: `${kind} rows do not carry reason` };
294
+ }
295
+ if (kind === "compliance") {
296
+ if (!e["rule"] || !e["result"] || !e["phase"] || !e["parentSha"]) {
297
+ return { ok: false, reason: "compliance row missing required payload fields" };
298
+ }
299
+ }
300
+ if (kind === "outcome") {
301
+ // Every workflow run carries these; `prNumber` is ship-only (see below).
302
+ const numFields = [
303
+ "linesAdded",
304
+ "linesDeleted",
305
+ "linesChanged",
306
+ "filesChanged",
307
+ "taskCount",
308
+ "durationSeconds",
309
+ "deferrals",
310
+ "failures",
311
+ ];
312
+ for (const f of numFields) {
313
+ if (typeof e[f] !== "number") {
314
+ return { ok: false, reason: `outcome missing or invalid numeric field: ${f}` };
315
+ }
316
+ }
317
+ // prNumber — ship-only, optional; validate only when present.
318
+ if (e["prNumber"] !== undefined && typeof e["prNumber"] !== "number") {
319
+ return { ok: false, reason: "outcome prNumber must be a number when present" };
320
+ }
321
+ // parentSha — the run's identity anchor; optional (absent on some ship rows).
322
+ if (e["parentSha"] !== undefined && typeof e["parentSha"] !== "string") {
323
+ return { ok: false, reason: "outcome parentSha must be a string when present" };
324
+ }
325
+ // Optional per-run numeric metrics: validate type only when present.
326
+ for (const f of [
327
+ "frictionAdded",
328
+ "deferralsAdded",
329
+ "failuresAdded",
330
+ "correctiveCommits",
331
+ "reviewIterations",
332
+ "ciTrySuccess",
333
+ ]) {
334
+ if (e[f] !== undefined && typeof e[f] !== "number") {
335
+ return { ok: false, reason: `outcome ${f} must be a number when present` };
336
+ }
337
+ }
338
+ if (e["planSource"] !== undefined && e["planSource"] !== "brief") {
339
+ return { ok: false, reason: 'outcome planSource must be "brief" when present' };
340
+ }
341
+ // coverage is optional + per-tier; validate structure only when present.
342
+ if (e["coverage"] !== undefined) {
343
+ const cov = e["coverage"];
344
+ if (typeof cov !== "object" || cov === null) {
345
+ return { ok: false, reason: "outcome coverage must be an object" };
346
+ }
347
+ for (const tier of ["unit", "integration", "e2e"]) {
348
+ const t = cov[tier];
349
+ if (t === undefined)
350
+ continue;
351
+ if (typeof t !== "object" || t === null) {
352
+ return { ok: false, reason: `outcome coverage.${tier} must be an object` };
353
+ }
354
+ for (const m of ["lines", "branches", "functions", "statements"]) {
355
+ const v = t[m];
356
+ if (v !== undefined && typeof v !== "number") {
357
+ return { ok: false, reason: `outcome coverage.${tier}.${m} must be a number` };
358
+ }
359
+ }
360
+ }
361
+ }
362
+ }
363
+ if (kind === "counter") {
364
+ if (!e["counterName"] || typeof e["counterValue"] !== "number" || !e["parentSha"]) {
365
+ return { ok: false, reason: "counter row missing required payload fields" };
366
+ }
367
+ if (e["counterSource"] !== "model-self-report" && e["counterSource"] !== "shell-bus") {
368
+ return { ok: false, reason: "counter counterSource must be model-self-report or shell-bus" };
369
+ }
370
+ }
371
+ if (kind === "feature") {
372
+ if (!e["key"] || typeof e["key"] !== "string") {
373
+ return { ok: false, reason: "feature row missing required field: key (the FID)" };
374
+ }
375
+ if (!e["category"] || typeof e["category"] !== "string") {
376
+ return { ok: false, reason: "feature row missing required payload field: category" };
377
+ }
378
+ if (!e["description"] || typeof e["description"] !== "string") {
379
+ return { ok: false, reason: "feature row missing required payload field: description" };
380
+ }
381
+ }
382
+ return { ok: true };
383
+ }
384
+ /**
385
+ * Tolerant parse — per-line try/catch, skips + counts unparseable lines.
386
+ * NEVER throws.
387
+ *
388
+ * No version gating — ALL well-formed rows are kept regardless of `bkitVersion`.
389
+ */
390
+ export function parse(raw) {
391
+ const result = {
392
+ events: [],
393
+ malformedLineCount: 0,
394
+ };
395
+ const lines = raw.split("\n");
396
+ for (const line of lines) {
397
+ const trimmed = line.trim();
398
+ if (trimmed === "")
399
+ continue;
400
+ try {
401
+ const obj = JSON.parse(trimmed);
402
+ result.events.push(obj);
403
+ }
404
+ catch {
405
+ result.malformedLineCount++;
406
+ }
407
+ }
408
+ return result;
409
+ }
410
+ /**
411
+ * `ts` as a sortable number. A row may carry an ISO-string `ts` or none at all:
412
+ * ISO strings parse; anything else sorts oldest.
413
+ */
414
+ function tsOrder(ts) {
415
+ if (typeof ts === "number" && Number.isFinite(ts))
416
+ return ts;
417
+ if (typeof ts === "string") {
418
+ const ms = Date.parse(ts);
419
+ if (Number.isFinite(ms))
420
+ return ms;
421
+ }
422
+ return Number.NEGATIVE_INFINITY;
423
+ }
424
+ /** Ascending `ts` comparator that stays consistent on string-`ts` and `ts`-less rows. Ties keep input order. */
425
+ export function compareTs(a, b) {
426
+ const x = tsOrder(a.ts);
427
+ const y = tsOrder(b.ts);
428
+ return x < y ? -1 : x > y ? 1 : 0;
429
+ }
430
+ /**
431
+ * Fold events into a Map keyed by per-kind composite identity.
432
+ * Later rows (higher ts) win for the same key — last-write-wins fold.
433
+ * Mirrors ledgers/status.ts's dedupe approach but with per-kind composite tuples.
434
+ */
435
+ export function fold(events) {
436
+ // Sort by ts ascending so later rows overwrite earlier ones
437
+ const sorted = [...events].sort(compareTs);
438
+ const state = new Map();
439
+ for (const event of sorted) {
440
+ const key = identity(event);
441
+ state.set(key, event);
442
+ }
443
+ return state;
444
+ }
445
+ /** Reads every existing file in `paths` and folds all events together. */
446
+ export function foldFrom(paths) {
447
+ let allEvents = [];
448
+ let totalMalformed = 0;
449
+ for (const p of paths) {
450
+ if (!fs.existsSync(p))
451
+ continue;
452
+ const raw = fs.readFileSync(p, "utf-8");
453
+ const parsed = parse(raw);
454
+ allEvents = allEvents.concat(parsed.events);
455
+ totalMalformed += parsed.malformedLineCount;
456
+ }
457
+ const versionCounts = {};
458
+ for (const e of allEvents) {
459
+ const v = typeof e.bkitVersion === "string" && e.bkitVersion !== "" ? e.bkitVersion : "unknown";
460
+ versionCounts[v] = (versionCounts[v] ?? 0) + 1;
461
+ }
462
+ const rowCount = allEvents.length;
463
+ const maxRowsWarning = rowCount > MAX_ROWS_BEFORE_ROLLUP;
464
+ if (maxRowsWarning) {
465
+ console.warn(`[bkit-telemetry] MAX_ROWS_BEFORE_ROLLUP exceeded: ${rowCount} rows > ${MAX_ROWS_BEFORE_ROLLUP}.`);
466
+ }
467
+ return {
468
+ state: fold(allEvents),
469
+ rowCount,
470
+ malformedLineCount: totalMalformed,
471
+ versionCounts,
472
+ maxRowsWarning,
473
+ };
474
+ }
475
+ // ---------------------------------------------------------------------------
476
+ // AppendLine — serialize one event to its NDJSON line
477
+ // ---------------------------------------------------------------------------
478
+ export function appendLine(event) {
479
+ const v = validate(event);
480
+ if (!v.ok)
481
+ throw new Error(`[bkit-telemetry] appendLine: invalid event — ${v.reason}`);
482
+ return JSON.stringify(event);
483
+ }
484
+ // Per-metric baseline: compare THIS run to the previous N runs of the SAME workflow.
485
+ /** Rolling-baseline window (median over the previous N same-workflow runs). */
486
+ export const RUN_BASELINE_WINDOW = 5;
487
+ /** Below this many prior runs the median is noise — show `n/a` instead. */
488
+ const RUN_BASELINE_MIN = 3;
489
+ /** Seconds → compact human duration: `45s` · `33m` · `2h11m`. */
490
+ export function humanizeDuration(sec) {
491
+ if (!Number.isFinite(sec) || sec < 0)
492
+ return `${sec}s`;
493
+ if (sec < 60)
494
+ return `${Math.round(sec)}s`;
495
+ if (sec < 3600)
496
+ return `${Math.round(sec / 60)}m`;
497
+ const h = Math.floor(sec / 3600);
498
+ const m = Math.round((sec % 3600) / 60);
499
+ return m > 0 ? `${h}h${m}m` : `${h}h`;
500
+ }
501
+ /** Median (lower-middle for even counts, matching computeElapsedStats). null if empty. */
502
+ function median(nums) {
503
+ if (nums.length === 0)
504
+ return null;
505
+ const s = [...nums].sort((a, b) => a - b);
506
+ return s[Math.floor(s.length / 2)] ?? null;
507
+ }
508
+ function versionSpread(versionCounts) {
509
+ return (Object.entries(versionCounts)
510
+ .map(([v, n]) => `${v}=${n}`)
511
+ .join(", ") || "none");
512
+ }
513
+ /**
514
+ * Ledger-health readout — the parse-integrity line kept as a footer, with the
515
+ * `rows` / `malformed:` / `versions:` tokens.
516
+ */
517
+ function ledgerLine(result) {
518
+ return `[bkit-telemetry] ledger: ${result.rowCount} rows · malformed: ${result.malformedLineCount} · versions: ${versionSpread(result.versionCounts)}`;
519
+ }
520
+ /**
521
+ * THE per-workflow telemetry report, emitted at each workflow's close step and
522
+ * injected into the tracker close comment (`bkit telemetry summary --phase=<w>`).
523
+ *
524
+ * Scoped STRICTLY to the one workflow — never the design→…→ship chain. For the
525
+ * given workflow it shows THIS run's `outcome` (run) row against
526
+ * `med·N` = the median of that workflow's previous N runs (rolling), a secondary
527
+ * compliance line, and the ledger
528
+ * footer. Fields absent on the run row are omitted — a metric shows only when the
529
+ * workflow actually produced it.
530
+ *
531
+ * Without a workflow it degrades to the ledger-health line alone.
532
+ */
533
+ export function workflowTelemetry(result, workflow) {
534
+ const events = [...result.state.values()];
535
+ // Folded ENTITY count per workflow (not raw lines) — an updated row folds to one.
536
+ const workflowCounts = {};
537
+ for (const ev of events) {
538
+ const w = ev.workflow || "unknown";
539
+ workflowCounts[w] = (workflowCounts[w] ?? 0) + 1;
540
+ }
541
+ const base = {
542
+ rowCount: result.rowCount,
543
+ malformedLineCount: result.malformedLineCount,
544
+ versionCounts: result.versionCounts,
545
+ maxRowsWarning: result.maxRowsWarning,
546
+ workflowCounts,
547
+ workflow,
548
+ };
549
+ const maxRowsLines = result.maxRowsWarning
550
+ ? [
551
+ `[bkit-telemetry] WARNING: MAX_ROWS_BEFORE_ROLLUP (${MAX_ROWS_BEFORE_ROLLUP}) exceeded — ${result.rowCount} rows in stats.jsonl; consider archiving.`,
552
+ ]
553
+ : [];
554
+ // No workflow → ledger-health readout only.
555
+ if (!workflow) {
556
+ return { ...base, lines: [ledgerLine(result), ...maxRowsLines] };
557
+ }
558
+ // This workflow's run rows (generalized outcome), oldest → newest.
559
+ const runs = events
560
+ .filter((e) => e.kind === "outcome" && e.workflow === workflow)
561
+ .sort(compareTs);
562
+ const cur = runs.at(-1);
563
+ // Baseline only against runs of the same plan source — a brief run (no plan)
564
+ // has no tasks and a different shape, so mixing them skews every median.
565
+ const prev = runs
566
+ .slice(0, -1)
567
+ .filter((r) => r.planSource === cur?.planSource)
568
+ .slice(-RUN_BASELINE_WINDOW);
569
+ const repo = cur?.repo ?? events[0]?.repo ?? "unknown/repo";
570
+ // Rendered as a Markdown table so it drops straight into the tracker comment
571
+ // (no code fence needed) — GitHub/Linear render it natively.
572
+ const lines = [`**${workflow} close** · ${repo}`, ""];
573
+ const tableRows = [];
574
+ const row = (label, self, med) => {
575
+ tableRows.push(`| ${label} | ${self} | ${med} |`);
576
+ };
577
+ if (cur) {
578
+ // med·N: median of the previous runs that carry the field, `—` until there are
579
+ // at least RUN_BASELINE_MIN of them (1–2 samples is noise, not a baseline).
580
+ const medCell = (key, fmt = String) => {
581
+ const vals = prev.map((r) => r[key]).filter((v) => typeof v === "number");
582
+ if (vals.length < RUN_BASELINE_MIN)
583
+ return "—";
584
+ const m = median(vals);
585
+ return m === null ? "—" : fmt(m);
586
+ };
587
+ // Core metrics — always shown.
588
+ row("durationSeconds", `${cur.durationSeconds} (${humanizeDuration(cur.durationSeconds)})`, medCell("durationSeconds", (n) => `${n} (${humanizeDuration(n)})`));
589
+ row("linesChanged", `${cur.linesChanged} (+${cur.linesAdded}/-${cur.linesDeleted})`, medCell("linesChanged"));
590
+ row("filesChanged", `${cur.filesChanged}`, medCell("filesChanged"));
591
+ // Conditional metrics — shown only when this run carries them.
592
+ if (cur.planSource)
593
+ row("planSource", cur.planSource, "—");
594
+ if (cur.taskCount > 0)
595
+ row("taskCount", `${cur.taskCount}`, medCell("taskCount"));
596
+ if (typeof cur.reviewIterations === "number")
597
+ row("reviewIterations", `${cur.reviewIterations}`, medCell("reviewIterations"));
598
+ if (typeof cur.correctiveCommits === "number")
599
+ row("correctiveCommits", `${cur.correctiveCommits}`, medCell("correctiveCommits"));
600
+ if (typeof cur.ciTrySuccess === "number")
601
+ row("ciTrySuccess", `${cur.ciTrySuccess}${cur.ciTrySuccess === 1 ? " (first-try)" : ""}`, medCell("ciTrySuccess"));
602
+ // Instinct-loop deltas — frictionAdded is the featured signal (shown even at 0).
603
+ if (typeof cur.frictionAdded === "number")
604
+ row("frictionAdded", `${cur.frictionAdded}`, medCell("frictionAdded"));
605
+ if (typeof cur.deferralsAdded === "number")
606
+ row("deferralsAdded", `${cur.deferralsAdded}`, medCell("deferralsAdded"));
607
+ if (typeof cur.failuresAdded === "number")
608
+ row("failuresAdded", `${cur.failuresAdded}`, medCell("failuresAdded"));
609
+ }
610
+ // Compliance — this run's rows. The `outcome` and `compliance` rows are written
611
+ // at different points in a close (different HEADs → different parentSha), so we
612
+ // DON'T match on the run row's parentSha: we take the newest same-workflow
613
+ // compliance group (its parentSha) as "this run".
614
+ const complianceRows = events.filter((e) => e.kind === "compliance" && e.workflow === workflow);
615
+ const compSha = complianceRows.slice().sort((a, b) => compareTs(b, a))[0]?.parentSha;
616
+ if (compSha) {
617
+ const comp = complianceRows.filter((c) => c.parentSha === compSha);
618
+ const pass = comp.filter((c) => c.result === "pass").length;
619
+ const fail = comp.filter((c) => c.result === "fail").length;
620
+ const na = comp.filter((c) => c.result === "n/a").length;
621
+ const denom = pass + fail + na;
622
+ const rate = denom > 0 ? Math.round((pass / denom) * 100) : 0;
623
+ row("compliance", `${pass} pass · ${fail} fail · ${na} n/a (${rate}%)`, "—");
624
+ }
625
+ // Attempts — the newest same-workflow *_ATTEMPT counter (this run).
626
+ const attempt = events
627
+ .filter((e) => e.kind === "counter" && e.workflow === workflow && /_ATTEMPT$/.test(e.counterName))
628
+ .sort((a, b) => compareTs(b, a))[0];
629
+ if (attempt)
630
+ row("attempts", `${attempt.counterName} ${attempt.counterValue}`, "—");
631
+ if (tableRows.length > 0) {
632
+ lines.push(`| metric | this run | med·${RUN_BASELINE_WINDOW} |`, "| --- | --- | --- |", ...tableRows, "");
633
+ }
634
+ lines.push(`\`med·${RUN_BASELINE_WINDOW}\` = median of the previous ${RUN_BASELINE_WINDOW} ${workflow}${cur?.planSource ? ` ${cur.planSource}` : ""} runs (— if < ${RUN_BASELINE_MIN}) · ledger ${result.rowCount} rows, ${result.malformedLineCount} malformed`);
635
+ lines.push(...maxRowsLines);
636
+ return { ...base, lines };
637
+ }