@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,1143 @@
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
+
20
+ import { spawnSync } from "node:child_process";
21
+ import * as fs from "node:fs";
22
+
23
+ // ---------------------------------------------------------------------------
24
+ // Constants
25
+ // ---------------------------------------------------------------------------
26
+
27
+ export const MAX_ROWS_BEFORE_ROLLUP = 5000;
28
+
29
+ // ---------------------------------------------------------------------------
30
+ // repo — the owner/repo slug, resolved ONE way
31
+ //
32
+ // `repo` is part of identity() for EVERY kind, so a respelled repo FORKS the
33
+ // entity — the same failure the spec warns about for `key`, except `repo` is not
34
+ // authored by anyone: it is derived. It therefore must be derived identically
35
+ // everywhere, from the only authoritative source: the git remote.
36
+ //
37
+ // NOT package.json `name` — that is an npm package name, not a slug
38
+ // (`@cbartens/bkit` vs `cbartens/bkit`). NOT the filesystem path — that makes the
39
+ // "owner" a folder on whoever's laptop ran the tool (`GitHub/my-app`, or
40
+ // `code/my-app` after they reorganise).
41
+ // ---------------------------------------------------------------------------
42
+
43
+ /**
44
+ * Parse `owner/repo` out of a git remote URL. Pure — the fiddly half, kept
45
+ * testable without a git repo.
46
+ *
47
+ * Handles HTTPS (`https://github.com/owner/repo.git`), SSH scp-form
48
+ * (`git@github.com:owner/repo.git`) and `ssh://` URLs. Returns "" when the URL
49
+ * yields no `owner/repo` pair rather than guessing.
50
+ */
51
+ export function parseRemoteUrlToSlug(url: string): string {
52
+ const m = url
53
+ .trim()
54
+ .replace(/\.git$/, "")
55
+ .match(/[/:]([^/:]+\/[^/:]+)$/);
56
+ return m?.[1] ?? "";
57
+ }
58
+
59
+ /** git env with hook vars scrubbed — see resolveRepoSlug. */
60
+ export function gitEnv(): NodeJS.ProcessEnv {
61
+ const env = { ...process.env };
62
+ delete env["GIT_DIR"];
63
+ delete env["GIT_WORK_TREE"];
64
+ delete env["GIT_INDEX_FILE"];
65
+ delete env["GIT_OBJECT_DIRECTORY"];
66
+ return env;
67
+ }
68
+
69
+ /**
70
+ * Resolve a rev (`HEAD~1`, a branch, a tag) to a full hex SHA. "" if it does not
71
+ * resolve — e.g. `HEAD~1` in a repo with one commit.
72
+ *
73
+ * `parentSha` MUST be resolved before it reaches a row: it is part of identity()
74
+ * for compliance and counter, and the grader's diff guard accepts only hex.
75
+ */
76
+ export function resolveGitSha(rev: string, cwd: string): string {
77
+ const res = spawnSync("git", ["rev-parse", "--verify", "--quiet", `${rev}^{commit}`], {
78
+ cwd,
79
+ encoding: "utf-8",
80
+ env: gitEnv(),
81
+ stdio: ["ignore", "pipe", "ignore"],
82
+ });
83
+ if (res.status !== 0 || typeof res.stdout !== "string") return "";
84
+ const sha = res.stdout.trim();
85
+ return /^[0-9a-f]{7,40}$/.test(sha) ? sha : "";
86
+ }
87
+
88
+ /**
89
+ * Resolve a repo's `owner/repo` slug from its git remote. "" when there is no
90
+ * remote or no git repo — callers decide the fallback, loudly.
91
+ *
92
+ * Scrubs GIT_DIR / GIT_WORK_TREE / GIT_INDEX_FILE (exported by git hooks) so
93
+ * `git -C <path>` answers for <path>, not the hook's repo.
94
+ *
95
+ * spawnSync: a non-zero exit ("no remote") is an expected answer, not an exception.
96
+ */
97
+ export function resolveRepoSlug(cwd: string): string {
98
+ const res = spawnSync("git", ["remote", "get-url", "origin"], {
99
+ cwd,
100
+ encoding: "utf-8",
101
+ env: gitEnv(),
102
+ stdio: ["ignore", "pipe", "ignore"],
103
+ });
104
+ if (res.status !== 0 || typeof res.stdout !== "string") return "";
105
+ return parseRemoteUrlToSlug(res.stdout);
106
+ }
107
+
108
+ // ---------------------------------------------------------------------------
109
+ // Shared envelope (A2-mandatory fields on EVERY row, every kind)
110
+ // ---------------------------------------------------------------------------
111
+
112
+ export interface TelemetryEnvelope {
113
+ /** Primary id = unix milliseconds (portable: jq `now*1000|floor`). */
114
+ ts: number;
115
+ /** Closed enum — validated on append; unknown kind rejected. */
116
+ kind: TelemetryKind;
117
+ /** Origin repo (slug, e.g. "cbartens/bkit"). */
118
+ repo: string;
119
+ /** bkit version stamped on every row for regression attribution. */
120
+ bkitVersion: string;
121
+ /** Emitting workflow: design | plan | build | debug | ship */
122
+ workflow: string;
123
+ /**
124
+ * The WORKFLOW STEP the row was emitted at, e.g. `build-close-workflow`,
125
+ * `ship-close-gate`. A step of the orchestrator, never an agent name — a
126
+ * subagent's identity goes in `subagent`, and its model in `model`.
127
+ */
128
+ step: string;
129
+ /**
130
+ * The SUBAGENT that wrote the row, e.g. `bkit-build-challenge-remediate`.
131
+ * Absent on orchestrator-written rows (the workflow itself wrote it).
132
+ *
133
+ * Distinct from `step`: `step` is WHERE in the workflow, `subagent` is WHO. One of
134
+ * the harvest's five slice dimensions (repo/workflow/step/subagent/severity).
135
+ */
136
+ subagent?: string;
137
+ /**
138
+ * The model that wrote the row, read from the writing subagent's OWN prompt
139
+ * frontmatter `model:` at call time — the deterministic source bkit already
140
+ * owns, and the only one that stays true when a prompt is re-pinned.
141
+ *
142
+ * Set ONLY on subagent-written rows, i.e. exactly when `subagent` is set. An
143
+ * orchestrator-written row has no `model`: the session model is the operator's
144
+ * runtime choice, not a property of the row, and self-reporting it invites the
145
+ * same nondeterminism the compliance grader exists to avoid.
146
+ */
147
+ model?: string;
148
+ /**
149
+ * Free-form related context: any pointer that helps a reader place this row —
150
+ * feature ids, tracker ids (`BAR-217`), PRs, commit SHAs, file paths, sibling
151
+ * `ts`, a ledger id (`KN-14`, `DE-7`). Every entry is a pointer,
152
+ * never an identity: `ts` (with `key` for instinct-loop kinds) identifies the row.
153
+ */
154
+ references?: string[];
155
+ /**
156
+ * Explicit written-once logical key for instinct-loop kinds
157
+ * (friction / deferral / failure / knowledge / decision).
158
+ * Author writes a stable slug ONCE; recurrence = same-key append.
159
+ * Absent on event kinds that key off composite tuples (compliance / counter / outcome).
160
+ */
161
+ key?: string;
162
+ }
163
+
164
+ // ---------------------------------------------------------------------------
165
+ // Per-kind discriminated-union payloads
166
+ // ---------------------------------------------------------------------------
167
+
168
+ export type TelemetryKind =
169
+ | "compliance"
170
+ | "outcome"
171
+ | "counter"
172
+ | "friction"
173
+ | "deferral"
174
+ | "failure"
175
+ | "knowledge"
176
+ | "decision"
177
+ | "feature";
178
+
179
+ export const VALID_KINDS: Set<string> = new Set([
180
+ "compliance",
181
+ "outcome",
182
+ "counter",
183
+ "friction",
184
+ "deferral",
185
+ "failure",
186
+ "knowledge",
187
+ "decision",
188
+ "feature",
189
+ ]);
190
+
191
+ /**
192
+ * Triage severity — carried by the three author-written kinds whose rows are
193
+ * triaged by a human or a later agent (friction / deferral / failure).
194
+ *
195
+ * The SAME vocabulary the challenge prompts assign to their findings;
196
+ * `@bkit-build-challenge-remediate` passes a blocked finding's severity straight
197
+ * through to its deferral row. NOT the preflight `blocker`/`advisory` scale (that
198
+ * gates `bkit install`).
199
+ *
200
+ * Absent on machine-generated kinds (compliance / outcome / counter) and on
201
+ * knowledge / decision, which have no triage severity.
202
+ */
203
+ type TelemetrySeverity = "CRITICAL" | "HIGH" | "MEDIUM" | "LOW";
204
+
205
+ export const VALID_SEVERITIES: Set<string> = new Set(["CRITICAL", "HIGH", "MEDIUM", "LOW"]);
206
+
207
+ /**
208
+ * Kinds that carry `severity` — and, identically, the kinds that carry the
209
+ * OPEN/TRIAGED/CLOSED ladder. Both express the same property: these three are
210
+ * the author-written kinds that describe OPEN WORK someone triages. Keep in
211
+ * sync with the payload interfaces below.
212
+ */
213
+ export const SEVERITY_KINDS: Set<string> = new Set(["friction", "deferral", "failure"]);
214
+
215
+ /**
216
+ * The triage ladder, shared by the SEVERITY_KINDS trio (friction/deferral/failure).
217
+ *
218
+ * `OPEN` raised, cause unknown -> `TRIAGED` analysed, disposition known, not yet
219
+ * fixed -> `CLOSED` dealt with (fixed, refuted, or established as not ours).
220
+ *
221
+ * `TRIAGED` IS STILL OPEN WORK. Readers counting open entries — a CI gate on open
222
+ * CRITICAL failures, an audit debt lens, an age report — MUST count it. Only
223
+ * `CLOSED` is done.
224
+ *
225
+ * NOT on knowledge or decision. Both use the `ACTIVE` / `SUPERSEDED`
226
+ * lifecycle, a different axis entirely. Absent `status` = `ACTIVE`.
227
+ */
228
+ export type TriageStatus = "OPEN" | "TRIAGED" | "CLOSED";
229
+
230
+ export const TRIAGE_STATUSES: Set<string> = new Set(["OPEN", "TRIAGED", "CLOSED"]);
231
+
232
+ /** The `ACTIVE` / `SUPERSEDED` lifecycle shared by `decision` and `knowledge`. */
233
+ export const DECISION_STATUSES: Set<string> = new Set(["ACTIVE", "SUPERSEDED"]);
234
+
235
+ /**
236
+ * The `feature` kind's six-state phase ladder — the canonical status for
237
+ * `.bkit/issues.jsonl`, appended once per phase close, same-`key`
238
+ * (the FID). `SHIPPED` projects into the roadmap's `## Shipped` section
239
+ * (last 10, ts desc); `ABANDONED` hides the FID from every section.
240
+ * `ABANDONED` is appended only by a human, or an agent on explicit human
241
+ * instruction — never inferred by a workflow.
242
+ *
243
+ * A separate axis from TRIAGE_STATUSES: `feature` carries no `severity`
244
+ * (`.bkit/jsonl.md` § Severity forbids it outside the friction/deferral/
245
+ * failure triage trio) — it tracks WHERE a feature is, not how badly
246
+ * something is broken.
247
+ */
248
+ export type FeatureStatus = "DESIGNED" | "PLANNED" | "BUILT" | "DEBUGGED" | "SHIPPED" | "ABANDONED";
249
+
250
+ export const FEATURE_STATUSES: Set<string> = new Set([
251
+ "DESIGNED",
252
+ "PLANNED",
253
+ "BUILT",
254
+ "DEBUGGED",
255
+ "SHIPPED",
256
+ "ABANDONED",
257
+ ]);
258
+
259
+ /**
260
+ * The justification for a `deferral`, on a different axis from `status` (how far
261
+ * the work has got) and `severity` (how much it matters). Closed enum:
262
+ *
263
+ * - `scope-declared` — a design or plan called this out of scope BEFORE the work
264
+ * started. MUST carry a `references` pointer to that section.
265
+ * - `hard-blocked` — an external blocker (missing credential, upstream fix,
266
+ * another feature) makes it impossible now. MUST name the blocker.
267
+ * - `needs-decision` — a human decision is missing, and guessing it is worse than
268
+ * waiting. Confirmation is unavailable inside `/bkit-*` workflows.
269
+ * - `own-cycle` — genuinely plan-sized: a new architecture, not a mechanical fix.
270
+ * - `unjustified` — ADJUDICATOR-ONLY (see UNJUSTIFIED_REASON).
271
+ *
272
+ * A writer who cannot pick one of the first four does not have a deferral; it has
273
+ * unfinished work (`.agents/rules.md` § Principles, "Finish over deferrals").
274
+ */
275
+ export type DeferralReason =
276
+ "scope-declared" | "hard-blocked" | "needs-decision" | "own-cycle" | "unjustified";
277
+
278
+ export const DEFERRAL_REASONS: Set<string> = new Set([
279
+ "scope-declared",
280
+ "hard-blocked",
281
+ "needs-decision",
282
+ "own-cycle",
283
+ "unjustified",
284
+ ]);
285
+
286
+ /**
287
+ * The adjudication verdict: this was in-scope work that should have been finished.
288
+ * Written ONLY by a reviewer judging someone else's deferral — never self-assigned
289
+ * at write time, where the four justifications are the whole legal vocabulary.
290
+ *
291
+ * Set via same-`key` append like any other update, and NEVER rewritten afterwards:
292
+ * a later row that closes the entry carries `unjustified` through verbatim. Feeds
293
+ * `computeDeferralDiscipline` in `commands/analysis.ts`.
294
+ */
295
+ export const UNJUSTIFIED_REASON = "unjustified";
296
+
297
+ /**
298
+ * The subagents sanctioned to write a `deferral` row (`.bkit/jsonl.md`
299
+ * § Ledgers & Writers). EXHAUSTIVE: a subagent absent from this set does not
300
+ * write the kind at all.
301
+ *
302
+ * `@bkit-build-plan-execute` and `@bkit-build-plan-gaps-remediate` are not in it: a
303
+ * blocked plan task's record is its `BLOCKED` log line, which the next verify pass reads.
304
+ *
305
+ * Orchestrator-written rows carry no `subagent` and are outside this check.
306
+ */
307
+ export const DEFERRAL_WRITERS: Set<string> = new Set([
308
+ "bkit-design-generate",
309
+ "bkit-plan-generate",
310
+ "bkit-plan-update",
311
+ "bkit-build-challenge-remediate",
312
+ "bkit-debug-abort-handover",
313
+ "bkit-ship-deferred-sweep",
314
+ "bkit-utility-update-deferrals",
315
+ ]);
316
+
317
+ // compliance — one row per run x rule (kind:"compliance")
318
+ export interface CompliancePayload {
319
+ rule: string;
320
+ result: "pass" | "fail" | "n/a";
321
+ evidence?: string;
322
+ phase: string;
323
+ parentSha: string;
324
+ }
325
+
326
+ /** Code-coverage percentages (0-100), from a coverage-summary.json `total`. */
327
+ export interface CoverageStats {
328
+ lines?: number;
329
+ branches?: number;
330
+ functions?: number;
331
+ statements?: number;
332
+ }
333
+
334
+ // outcome — one row per WORKFLOW RUN, keyed by (repo, workflow, parentSha).
335
+ // Every workflow writes one run row at its close, carrying just the fields that apply to it
336
+ // (absent fields are simply omitted — the summary shows a metric only when present).
337
+ // `prNumber` is ship-only; the per-run instinct-loop deltas (frictionAdded /
338
+ // deferralsAdded / failuresAdded) are what `workflowTelemetry` features.
339
+ export interface OutcomePayload {
340
+ /**
341
+ * Parent commit SHA of the run — the run's identity anchor (shared with the
342
+ * `compliance` / `counter` rows written in the same close). Optional: ship rows
343
+ * written without it are keyed by `prNumber`.
344
+ */
345
+ parentSha?: string;
346
+ /** Ship-only: the merged PR number. Absent on design/plan/build/debug runs. */
347
+ prNumber?: number;
348
+ /** Lines added (git diff --stat). */
349
+ linesAdded: number;
350
+ /** Lines deleted (git diff --stat). */
351
+ linesDeleted: number;
352
+ /** linesAdded + linesDeleted. */
353
+ linesChanged: number;
354
+ /** Files changed (git diff --stat). */
355
+ filesChanged: number;
356
+ /** Count of tasks in the sub-plan(s). */
357
+ taskCount: number;
358
+ /** Total workflow duration in seconds. */
359
+ durationSeconds: number;
360
+ /**
361
+ * Which CI attempt passed (e.g. 2 = failed once then passed on retry).
362
+ * undefined = not yet backfilled by P4 analysis.
363
+ */
364
+ ciTrySuccess?: number;
365
+ /** Number of corrective commits post-PR-open. */
366
+ correctiveCommits?: number;
367
+ /** Number of PR review iterations. */
368
+ reviewIterations?: number;
369
+ /**
370
+ * The repo's CUMULATIVE count of distinct deferrals at ship time — folded
371
+ * entities, not lines. Per-cycle is the DELTA against the previous outcome
372
+ * row (see newFailuresThisRun / isErrorRun in commands/analysis.ts).
373
+ */
374
+ deferrals: number;
375
+ /**
376
+ * The repo's CUMULATIVE count of distinct failures at ship time — folded
377
+ * entities, not lines. Per-cycle is the DELTA against the previous outcome row.
378
+ *
379
+ * A total, NOT this run's discoveries. Readers MUST diff consecutive rows rather
380
+ * than test this absolutely.
381
+ */
382
+ failures: number;
383
+ /**
384
+ * Per-run instinct-loop DELTAS — how many rows THIS run added to each ledger,
385
+ * counted at close from rows with `workflow == <this workflow>` and
386
+ * `ts >= workflow-started`. Distinct from the cumulative `deferrals`/`failures`
387
+ * above: those are repo totals, these are what this one run contributed.
388
+ * `frictionAdded` is the featured per-workflow signal (see `workflowTelemetry`);
389
+ * all three are optional so a workflow that cannot produce one simply omits it.
390
+ */
391
+ frictionAdded?: number;
392
+ deferralsAdded?: number;
393
+ failuresAdded?: number;
394
+ /** Sweep verdict from ship deferred-sweep step. */
395
+ sweepVerdict?: string;
396
+ /**
397
+ * `"brief"` = the run had no `{FID}-plan*.md` and worked from its input file
398
+ * (build / ship `workflow-meta` row). Absent = the run had a plan. Brief runs
399
+ * report `taskCount` 0 and are baselined only against other brief runs.
400
+ */
401
+ planSource?: "brief";
402
+ /**
403
+ * Per-tier code-coverage % — each tier's coverage-summary.json `total.*.pct`.
404
+ * Best-effort: a tier is absent when its coverage report is not produced
405
+ * (coverage is opt-in per tier). Additive-optional —
406
+ * no version bump; readers ingest rows with or without it.
407
+ */
408
+ coverage?: {
409
+ unit?: CoverageStats;
410
+ integration?: CoverageStats;
411
+ e2e?: CoverageStats;
412
+ };
413
+ }
414
+
415
+ // counter — attempt/failure counts, keyed by (repo, workflow, parentSha, counterName)
416
+ export interface CounterPayload {
417
+ counterName: string;
418
+ counterValue: number;
419
+ parentSha: string;
420
+ /**
421
+ * Trust-tier field: model-self-report (pre-P3) vs shell-bus (post-P3 deterministic).
422
+ */
423
+ counterSource: "model-self-report" | "shell-bus";
424
+ }
425
+
426
+ // friction — keyed by explicit `key` field
427
+ export interface FrictionPayload {
428
+ /**
429
+ * Free-form friction-type tag (see § Categories in .bkit/jsonl.md). Documented
430
+ * set: human-confirm, permission-prompt, agent-rework, manual-install,
431
+ * tool-failure, destructive-backout, other. NOT validated on write, like the
432
+ * deferral/failure domain vocabulary (the docs define the set).
433
+ */
434
+ category: string;
435
+ scope: "bkit-repo" | "consumer" | "universal";
436
+ /** How much this friction hurts — see TelemetrySeverity. */
437
+ severity: TelemetrySeverity;
438
+ /** Short title. `description` carries the prose; without this the title has nowhere to live. */
439
+ summary?: string;
440
+ description: string;
441
+ remediation?: string;
442
+ /** Who observed it: agent | human | phase | orchestrator. Mirrors DeferralPayload.source. */
443
+ source?: string;
444
+ /**
445
+ * `OPEN` raised, cause unknown -> `TRIAGED` analysed, disposition known, not yet
446
+ * fixed -> `CLOSED` dealt with (fixed, refuted, or not ours to fix).
447
+ *
448
+ * Each is its own same-`key` row (see § Updating a Row): the entry's `ts` is when it
449
+ * was raised, the TRIAGED row's `ts` when it was analysed, the CLOSED row's `ts` when it
450
+ * was fixed. Carry the disposition in `references` (the issue, the Fix N, or why it is
451
+ * not ours).
452
+ */
453
+ status?: TriageStatus | string;
454
+ confidence?: number;
455
+ lastConfirmed?: number;
456
+ recurrenceCount?: number;
457
+ }
458
+
459
+ // deferral — keyed by explicit `key` field
460
+ export interface DeferralPayload {
461
+ type: "issue" | "feature";
462
+ category: string;
463
+ /** Triage severity of the deferred work — see TelemetrySeverity. */
464
+ severity: TelemetrySeverity;
465
+ /** Short title. `description` carries the prose; without this the title has nowhere to live. */
466
+ summary?: string;
467
+ description: string;
468
+ remediation?: string;
469
+ source?: string;
470
+ /**
471
+ * The deferral's justification — see DeferralReason. Required on every new row;
472
+ * optional in the type: older rows in the append-only ledger lack it.
473
+ */
474
+ reason?: DeferralReason;
475
+ /** OPEN -> TRIAGED -> CLOSED. See TRIAGE_STATUSES; TRIAGED is still open work. */
476
+ status?: TriageStatus;
477
+ }
478
+
479
+ // failure — keyed by explicit `key` field
480
+ export interface FailurePayload {
481
+ /**
482
+ * Free-form domain tag (mirrors DeferralPayload.category; see § Categories in
483
+ * .bkit/jsonl.md). `"testing"` marks a flaky / intermittent test — recurrence
484
+ * via same-`key` append is the flake signal; no extra fields. See § Categories.
485
+ */
486
+ category?: string;
487
+ summary?: string;
488
+ /** Triage severity of the discovered bug — see TelemetrySeverity. */
489
+ severity: TelemetrySeverity;
490
+ description: string;
491
+ rootCause?: string;
492
+ remediation?: string;
493
+ /**
494
+ * OPEN -> TRIAGED -> CLOSED. See TRIAGE_STATUSES; TRIAGED is still open work
495
+ * — a diagnosed bug is not a fixed bug.
496
+ */
497
+ status?: TriageStatus | string;
498
+ }
499
+
500
+ // knowledge — keyed by explicit `key` field (P5)
501
+ export interface KnowledgePayload {
502
+ summary: string;
503
+ description?: string;
504
+ rootCause?: string;
505
+ remediation?: string;
506
+ /** Absent = `ACTIVE`. Same closed set as `DecisionPayload.status`. */
507
+ status?: "ACTIVE" | "SUPERSEDED";
508
+ }
509
+
510
+ // decision — keyed by explicit `key` field (P5)
511
+ interface DecisionPayload {
512
+ summary: string;
513
+ description?: string;
514
+ rationale?: string;
515
+ alternatives?: string;
516
+ status?: "ACTIVE" | "SUPERSEDED";
517
+ }
518
+
519
+ // feature — keyed by explicit `key` field (the FID). The canonical row for
520
+ // `.bkit/issues.jsonl`: a `deferral`/`failure` row MINUS `severity`,
521
+ // PLUS the six-state FeatureStatus ladder in place of TriageStatus. Appended
522
+ // at every one of the five phase closes (design/plan/build/debug/ship) —
523
+ // same-`key` append, last-write-wins fold gives the current phase.
524
+ export interface FeaturePayload {
525
+ /** DOMAIN category (shared vocabulary with deferral/failure). */
526
+ category: string;
527
+ /** Short title. `description` carries the prose. */
528
+ summary?: string;
529
+ description: string;
530
+ /** The phase ladder — REQUIRED, closed six-value enum. See FeatureStatus. */
531
+ status: FeatureStatus;
532
+ /**
533
+ * Unix ms the feature ACTUALLY shipped, when that differs from `ts`.
534
+ *
535
+ * `ts` is append time and MUST be minted at append (§ Write Idiom). `shippedAt` is
536
+ * not part of the row identity, so it MAY carry a historic literal: an issue's
537
+ * `closed_at`, or a merge-commit date. The board's
538
+ * Shipped section ranks on `shippedAt // ts`.
539
+ *
540
+ * Optional. A live phase close can omit it — there `ts` already IS the ship
541
+ * time. Only meaningful on `status: "SHIPPED"` rows.
542
+ */
543
+ shippedAt?: number;
544
+ }
545
+
546
+ // ---------------------------------------------------------------------------
547
+ // Discriminated union event type
548
+ // ---------------------------------------------------------------------------
549
+
550
+ export type TelemetryEvent = TelemetryEnvelope &
551
+ (
552
+ | ({ kind: "compliance" } & CompliancePayload)
553
+ | ({ kind: "outcome" } & OutcomePayload)
554
+ | ({ kind: "counter" } & CounterPayload)
555
+ | ({ kind: "friction" } & FrictionPayload)
556
+ | ({ kind: "deferral" } & DeferralPayload)
557
+ | ({ kind: "failure" } & FailurePayload)
558
+ | ({ kind: "knowledge" } & KnowledgePayload)
559
+ | ({ kind: "decision" } & DecisionPayload)
560
+ | ({ kind: "feature" } & FeaturePayload)
561
+ );
562
+
563
+ // ---------------------------------------------------------------------------
564
+ // Identity — per-kind composite tuple for dedup (NOT bare ts)
565
+ // Mirrors ledgers/status.ts's tuple dedupe approach.
566
+ // ---------------------------------------------------------------------------
567
+
568
+ export function identity(event: TelemetryEvent): string {
569
+ switch (event.kind) {
570
+ case "compliance":
571
+ return `compliance ${event.repo} ${event.workflow} ${event.parentSha} ${event.rule}`;
572
+ case "outcome": {
573
+ // One run row per workflow run: keyed by (repo, workflow, parentSha).
574
+ // A ship row with no parentSha falls back to prNumber (then ts), so it stays
575
+ // uniquely keyed per PR.
576
+ const anchor =
577
+ event.parentSha ?? (event.prNumber !== undefined ? `pr${event.prNumber}` : `ts${event.ts}`);
578
+ return `outcome ${event.repo} ${event.workflow} ${anchor}`;
579
+ }
580
+ case "counter":
581
+ return `counter ${event.repo} ${event.workflow} ${event.parentSha} ${event.counterName}`;
582
+ case "friction":
583
+ case "deferral":
584
+ case "failure":
585
+ case "knowledge":
586
+ case "decision":
587
+ case "feature":
588
+ // instinct-loop kinds (+ feature): identity = kind + key
589
+ return `${event.kind} ${event.repo} ${event.key ?? event.ts}`;
590
+ }
591
+ }
592
+
593
+ // ---------------------------------------------------------------------------
594
+ // Validation result
595
+ // ---------------------------------------------------------------------------
596
+
597
+ export interface ValidationResult {
598
+ ok: boolean;
599
+ reason?: string;
600
+ }
601
+
602
+ // ---------------------------------------------------------------------------
603
+ // Validate — reject malformed + unknown kind before write
604
+ // ---------------------------------------------------------------------------
605
+
606
+ export function validate(event: unknown): ValidationResult {
607
+ if (!event || typeof event !== "object") {
608
+ return { ok: false, reason: "event must be an object" };
609
+ }
610
+ const e = event as Record<string, unknown>;
611
+
612
+ // A2-mandatory envelope fields
613
+ const mandatory: string[] = ["ts", "kind", "repo", "bkitVersion", "step"];
614
+ for (const field of mandatory) {
615
+ if (e[field] === undefined || e[field] === null) {
616
+ return { ok: false, reason: `missing mandatory field: ${field}` };
617
+ }
618
+ }
619
+
620
+ if (typeof e["ts"] !== "number") {
621
+ return { ok: false, reason: "ts must be a number (ms unix)" };
622
+ }
623
+ if (typeof e["kind"] !== "string") {
624
+ return { ok: false, reason: "kind must be a string" };
625
+ }
626
+ if (!VALID_KINDS.has(e["kind"] as string)) {
627
+ return { ok: false, reason: `unknown kind: ${e["kind"]}` };
628
+ }
629
+ if (typeof e["repo"] !== "string" || e["repo"] === "") {
630
+ return { ok: false, reason: "repo must be a non-empty string" };
631
+ }
632
+ if (typeof e["bkitVersion"] !== "string" || e["bkitVersion"] === "") {
633
+ return { ok: false, reason: "bkitVersion must be a non-empty string" };
634
+ }
635
+ if (typeof e["step"] !== "string" || e["step"] === "") {
636
+ return { ok: false, reason: "step must be a non-empty string" };
637
+ }
638
+
639
+ // kind-specific payload validation (minimal — structural check)
640
+ const kind = e["kind"] as TelemetryKind;
641
+
642
+ // severity — required on the triaged author-written kinds, rejected elsewhere.
643
+ // Enforced on write only; `parse` stays tolerant so pre-severity rows still read.
644
+ if (SEVERITY_KINDS.has(kind)) {
645
+ if (e["severity"] === undefined || e["severity"] === null) {
646
+ return { ok: false, reason: `${kind} row missing required field: severity` };
647
+ }
648
+ if (!VALID_SEVERITIES.has(e["severity"] as string)) {
649
+ return {
650
+ ok: false,
651
+ reason: `${kind} severity must be one of CRITICAL|HIGH|MEDIUM|LOW (got: ${String(e["severity"])})`,
652
+ };
653
+ }
654
+ } else if (e["severity"] !== undefined) {
655
+ return { ok: false, reason: `${kind} rows do not carry severity` };
656
+ }
657
+
658
+ // status — triage ladder on the SEVERITY_KINDS trio, ACTIVE/SUPERSEDED lifecycle on
659
+ // decision and knowledge, absent elsewhere. Optional: absent = ACTIVE on that lifecycle.
660
+ // Enforced on write only; `parse` stays tolerant so a free-text status row still reads.
661
+ if (SEVERITY_KINDS.has(kind)) {
662
+ if (e["status"] !== undefined && !TRIAGE_STATUSES.has(e["status"] as string)) {
663
+ return {
664
+ ok: false,
665
+ reason: `${kind} status must be one of OPEN|TRIAGED|CLOSED (got: ${String(e["status"])})`,
666
+ };
667
+ }
668
+ } else if (kind === "decision" || kind === "knowledge") {
669
+ if (e["status"] !== undefined && !DECISION_STATUSES.has(e["status"] as string)) {
670
+ return {
671
+ ok: false,
672
+ reason: `${kind} status must be one of ACTIVE|SUPERSEDED (got: ${String(e["status"])})`,
673
+ };
674
+ }
675
+ } else if (kind === "feature") {
676
+ // status is REQUIRED on feature (unlike the optional triage ladder) — the
677
+ // roadmap projection has no phase to render without it.
678
+ if (e["status"] === undefined || !FEATURE_STATUSES.has(e["status"] as string)) {
679
+ return {
680
+ ok: false,
681
+ reason: `feature status must be one of DESIGNED|PLANNED|BUILT|DEBUGGED|SHIPPED|ABANDONED (got: ${String(e["status"])})`,
682
+ };
683
+ }
684
+ } else if (e["status"] !== undefined) {
685
+ return { ok: false, reason: `${kind} rows do not carry status` };
686
+ }
687
+
688
+ // reason — the deferral justification (see DeferralReason). Required on write:
689
+ // an unjustifiable deferral is unfinished work, and the whole point of the field
690
+ // is that it cannot be skipped. Enforced on write only; `parse` stays tolerant so
691
+ // rows appended before the field existed still read.
692
+ if (kind === "deferral") {
693
+ if (e["reason"] === undefined || e["reason"] === null) {
694
+ return { ok: false, reason: "deferral row missing required field: reason" };
695
+ }
696
+ if (!DEFERRAL_REASONS.has(e["reason"] as string)) {
697
+ return {
698
+ ok: false,
699
+ reason: `deferral reason must be one of ${[...DEFERRAL_REASONS].join("|")} (got: ${String(e["reason"])})`,
700
+ };
701
+ }
702
+ } else if (e["reason"] !== undefined) {
703
+ return { ok: false, reason: `${kind} rows do not carry reason` };
704
+ }
705
+
706
+ if (kind === "compliance") {
707
+ if (!e["rule"] || !e["result"] || !e["phase"] || !e["parentSha"]) {
708
+ return { ok: false, reason: "compliance row missing required payload fields" };
709
+ }
710
+ }
711
+ if (kind === "outcome") {
712
+ // Every workflow run carries these; `prNumber` is ship-only (see below).
713
+ const numFields = [
714
+ "linesAdded",
715
+ "linesDeleted",
716
+ "linesChanged",
717
+ "filesChanged",
718
+ "taskCount",
719
+ "durationSeconds",
720
+ "deferrals",
721
+ "failures",
722
+ ];
723
+ for (const f of numFields) {
724
+ if (typeof e[f] !== "number") {
725
+ return { ok: false, reason: `outcome missing or invalid numeric field: ${f}` };
726
+ }
727
+ }
728
+ // prNumber — ship-only, optional; validate only when present.
729
+ if (e["prNumber"] !== undefined && typeof e["prNumber"] !== "number") {
730
+ return { ok: false, reason: "outcome prNumber must be a number when present" };
731
+ }
732
+ // parentSha — the run's identity anchor; optional (absent on some ship rows).
733
+ if (e["parentSha"] !== undefined && typeof e["parentSha"] !== "string") {
734
+ return { ok: false, reason: "outcome parentSha must be a string when present" };
735
+ }
736
+ // Optional per-run numeric metrics: validate type only when present.
737
+ for (const f of [
738
+ "frictionAdded",
739
+ "deferralsAdded",
740
+ "failuresAdded",
741
+ "correctiveCommits",
742
+ "reviewIterations",
743
+ "ciTrySuccess",
744
+ ]) {
745
+ if (e[f] !== undefined && typeof e[f] !== "number") {
746
+ return { ok: false, reason: `outcome ${f} must be a number when present` };
747
+ }
748
+ }
749
+ if (e["planSource"] !== undefined && e["planSource"] !== "brief") {
750
+ return { ok: false, reason: 'outcome planSource must be "brief" when present' };
751
+ }
752
+ // coverage is optional + per-tier; validate structure only when present.
753
+ if (e["coverage"] !== undefined) {
754
+ const cov = e["coverage"];
755
+ if (typeof cov !== "object" || cov === null) {
756
+ return { ok: false, reason: "outcome coverage must be an object" };
757
+ }
758
+ for (const tier of ["unit", "integration", "e2e"]) {
759
+ const t = (cov as Record<string, unknown>)[tier];
760
+ if (t === undefined) continue;
761
+ if (typeof t !== "object" || t === null) {
762
+ return { ok: false, reason: `outcome coverage.${tier} must be an object` };
763
+ }
764
+ for (const m of ["lines", "branches", "functions", "statements"]) {
765
+ const v = (t as Record<string, unknown>)[m];
766
+ if (v !== undefined && typeof v !== "number") {
767
+ return { ok: false, reason: `outcome coverage.${tier}.${m} must be a number` };
768
+ }
769
+ }
770
+ }
771
+ }
772
+ }
773
+ if (kind === "counter") {
774
+ if (!e["counterName"] || typeof e["counterValue"] !== "number" || !e["parentSha"]) {
775
+ return { ok: false, reason: "counter row missing required payload fields" };
776
+ }
777
+ if (e["counterSource"] !== "model-self-report" && e["counterSource"] !== "shell-bus") {
778
+ return { ok: false, reason: "counter counterSource must be model-self-report or shell-bus" };
779
+ }
780
+ }
781
+ if (kind === "feature") {
782
+ if (!e["key"] || typeof e["key"] !== "string") {
783
+ return { ok: false, reason: "feature row missing required field: key (the FID)" };
784
+ }
785
+ if (!e["category"] || typeof e["category"] !== "string") {
786
+ return { ok: false, reason: "feature row missing required payload field: category" };
787
+ }
788
+ if (!e["description"] || typeof e["description"] !== "string") {
789
+ return { ok: false, reason: "feature row missing required payload field: description" };
790
+ }
791
+ }
792
+
793
+ return { ok: true };
794
+ }
795
+
796
+ // ---------------------------------------------------------------------------
797
+ // Parse result (tolerant — per-line try/catch, never throws)
798
+ // ---------------------------------------------------------------------------
799
+
800
+ export interface ParseResult {
801
+ events: TelemetryEvent[];
802
+ malformedLineCount: number;
803
+ }
804
+
805
+ /**
806
+ * Tolerant parse — per-line try/catch, skips + counts unparseable lines.
807
+ * NEVER throws.
808
+ *
809
+ * No version gating — ALL well-formed rows are kept regardless of `bkitVersion`.
810
+ */
811
+ export function parse(raw: string): ParseResult {
812
+ const result: ParseResult = {
813
+ events: [],
814
+ malformedLineCount: 0,
815
+ };
816
+ const lines = raw.split("\n");
817
+ for (const line of lines) {
818
+ const trimmed = line.trim();
819
+ if (trimmed === "") continue;
820
+ try {
821
+ const obj = JSON.parse(trimmed);
822
+ result.events.push(obj as TelemetryEvent);
823
+ } catch {
824
+ result.malformedLineCount++;
825
+ }
826
+ }
827
+ return result;
828
+ }
829
+
830
+ // ---------------------------------------------------------------------------
831
+ // Fold — reduce event log to current state map, deduping by composite identity
832
+ // ---------------------------------------------------------------------------
833
+
834
+ export type FoldedState = Map<string, TelemetryEvent>;
835
+
836
+ /**
837
+ * `ts` as a sortable number. A row may carry an ISO-string `ts` or none at all:
838
+ * ISO strings parse; anything else sorts oldest.
839
+ */
840
+ function tsOrder(ts: unknown): number {
841
+ if (typeof ts === "number" && Number.isFinite(ts)) return ts;
842
+ if (typeof ts === "string") {
843
+ const ms = Date.parse(ts);
844
+ if (Number.isFinite(ms)) return ms;
845
+ }
846
+ return Number.NEGATIVE_INFINITY;
847
+ }
848
+
849
+ /** Ascending `ts` comparator that stays consistent on string-`ts` and `ts`-less rows. Ties keep input order. */
850
+ export function compareTs(a: { ts: unknown }, b: { ts: unknown }): number {
851
+ const x = tsOrder(a.ts);
852
+ const y = tsOrder(b.ts);
853
+ return x < y ? -1 : x > y ? 1 : 0;
854
+ }
855
+
856
+ /**
857
+ * Fold events into a Map keyed by per-kind composite identity.
858
+ * Later rows (higher ts) win for the same key — last-write-wins fold.
859
+ * Mirrors ledgers/status.ts's dedupe approach but with per-kind composite tuples.
860
+ */
861
+ export function fold(events: TelemetryEvent[]): FoldedState {
862
+ // Sort by ts ascending so later rows overwrite earlier ones
863
+ const sorted = [...events].sort(compareTs);
864
+ const state: FoldedState = new Map();
865
+ for (const event of sorted) {
866
+ const key = identity(event);
867
+ state.set(key, event);
868
+ }
869
+ return state;
870
+ }
871
+
872
+ // ---------------------------------------------------------------------------
873
+ // FoldFrom — reads ledger files, returns combined fold
874
+ // ---------------------------------------------------------------------------
875
+
876
+ export interface FoldFromResult {
877
+ state: FoldedState;
878
+ rowCount: number;
879
+ malformedLineCount: number;
880
+ /** Row count per emitting `bkitVersion` — for triage of unexpected versions. */
881
+ versionCounts: Record<string, number>;
882
+ maxRowsWarning: boolean;
883
+ }
884
+
885
+ /** Reads every existing file in `paths` and folds all events together. */
886
+ export function foldFrom(paths: string[]): FoldFromResult {
887
+ let allEvents: TelemetryEvent[] = [];
888
+ let totalMalformed = 0;
889
+
890
+ for (const p of paths) {
891
+ if (!fs.existsSync(p)) continue;
892
+ const raw = fs.readFileSync(p, "utf-8");
893
+ const parsed = parse(raw);
894
+ allEvents = allEvents.concat(parsed.events);
895
+ totalMalformed += parsed.malformedLineCount;
896
+ }
897
+
898
+ const versionCounts: Record<string, number> = {};
899
+ for (const e of allEvents) {
900
+ const v = typeof e.bkitVersion === "string" && e.bkitVersion !== "" ? e.bkitVersion : "unknown";
901
+ versionCounts[v] = (versionCounts[v] ?? 0) + 1;
902
+ }
903
+
904
+ const rowCount = allEvents.length;
905
+ const maxRowsWarning = rowCount > MAX_ROWS_BEFORE_ROLLUP;
906
+ if (maxRowsWarning) {
907
+ console.warn(
908
+ `[bkit-telemetry] MAX_ROWS_BEFORE_ROLLUP exceeded: ${rowCount} rows > ${MAX_ROWS_BEFORE_ROLLUP}.`,
909
+ );
910
+ }
911
+
912
+ return {
913
+ state: fold(allEvents),
914
+ rowCount,
915
+ malformedLineCount: totalMalformed,
916
+ versionCounts,
917
+ maxRowsWarning,
918
+ };
919
+ }
920
+
921
+ // ---------------------------------------------------------------------------
922
+ // AppendLine — serialize one event to its NDJSON line
923
+ // ---------------------------------------------------------------------------
924
+
925
+ export function appendLine(event: TelemetryEvent): string {
926
+ const v = validate(event);
927
+ if (!v.ok) throw new Error(`[bkit-telemetry] appendLine: invalid event — ${v.reason}`);
928
+ return JSON.stringify(event);
929
+ }
930
+
931
+ // ---------------------------------------------------------------------------
932
+ // Summary report for per-workflow summary steps
933
+ // ---------------------------------------------------------------------------
934
+
935
+ export interface TelemetrySummary {
936
+ rowCount: number;
937
+ malformedLineCount: number;
938
+ versionCounts: Record<string, number>;
939
+ maxRowsWarning: boolean;
940
+ /** Folded ENTITY count per emitting workflow (an updated row folds to one). */
941
+ workflowCounts: Record<string, number>;
942
+ /** The workflow this report is scoped to, when given. */
943
+ workflow?: string;
944
+ /** Human-readable report lines — the block injected into the tracker close comment. */
945
+ lines: string[];
946
+ }
947
+
948
+ // Per-metric baseline: compare THIS run to the previous N runs of the SAME workflow.
949
+ /** Rolling-baseline window (median over the previous N same-workflow runs). */
950
+ export const RUN_BASELINE_WINDOW = 5;
951
+ /** Below this many prior runs the median is noise — show `n/a` instead. */
952
+ const RUN_BASELINE_MIN = 3;
953
+
954
+ // The three stats.jsonl member types, narrowed for the per-workflow report.
955
+ type OutcomeEvent = TelemetryEnvelope & { kind: "outcome" } & OutcomePayload;
956
+ type ComplianceEvent = TelemetryEnvelope & { kind: "compliance" } & CompliancePayload;
957
+ type CounterEvent = TelemetryEnvelope & { kind: "counter" } & CounterPayload;
958
+
959
+ /** Seconds → compact human duration: `45s` · `33m` · `2h11m`. */
960
+ export function humanizeDuration(sec: number): string {
961
+ if (!Number.isFinite(sec) || sec < 0) return `${sec}s`;
962
+ if (sec < 60) return `${Math.round(sec)}s`;
963
+ if (sec < 3600) return `${Math.round(sec / 60)}m`;
964
+ const h = Math.floor(sec / 3600);
965
+ const m = Math.round((sec % 3600) / 60);
966
+ return m > 0 ? `${h}h${m}m` : `${h}h`;
967
+ }
968
+
969
+ /** Median (lower-middle for even counts, matching computeElapsedStats). null if empty. */
970
+ function median(nums: number[]): number | null {
971
+ if (nums.length === 0) return null;
972
+ const s = [...nums].sort((a, b) => a - b);
973
+ return s[Math.floor(s.length / 2)] ?? null;
974
+ }
975
+
976
+ function versionSpread(versionCounts: Record<string, number>): string {
977
+ return (
978
+ Object.entries(versionCounts)
979
+ .map(([v, n]) => `${v}=${n}`)
980
+ .join(", ") || "none"
981
+ );
982
+ }
983
+
984
+ /**
985
+ * Ledger-health readout — the parse-integrity line kept as a footer, with the
986
+ * `rows` / `malformed:` / `versions:` tokens.
987
+ */
988
+ function ledgerLine(result: FoldFromResult): string {
989
+ return `[bkit-telemetry] ledger: ${result.rowCount} rows · malformed: ${result.malformedLineCount} · versions: ${versionSpread(result.versionCounts)}`;
990
+ }
991
+
992
+ /**
993
+ * THE per-workflow telemetry report, emitted at each workflow's close step and
994
+ * injected into the tracker close comment (`bkit telemetry summary --phase=<w>`).
995
+ *
996
+ * Scoped STRICTLY to the one workflow — never the design→…→ship chain. For the
997
+ * given workflow it shows THIS run's `outcome` (run) row against
998
+ * `med·N` = the median of that workflow's previous N runs (rolling), a secondary
999
+ * compliance line, and the ledger
1000
+ * footer. Fields absent on the run row are omitted — a metric shows only when the
1001
+ * workflow actually produced it.
1002
+ *
1003
+ * Without a workflow it degrades to the ledger-health line alone.
1004
+ */
1005
+ export function workflowTelemetry(result: FoldFromResult, workflow?: string): TelemetrySummary {
1006
+ const events = [...result.state.values()];
1007
+
1008
+ // Folded ENTITY count per workflow (not raw lines) — an updated row folds to one.
1009
+ const workflowCounts: Record<string, number> = {};
1010
+ for (const ev of events) {
1011
+ const w = ev.workflow || "unknown";
1012
+ workflowCounts[w] = (workflowCounts[w] ?? 0) + 1;
1013
+ }
1014
+
1015
+ const base = {
1016
+ rowCount: result.rowCount,
1017
+ malformedLineCount: result.malformedLineCount,
1018
+ versionCounts: result.versionCounts,
1019
+ maxRowsWarning: result.maxRowsWarning,
1020
+ workflowCounts,
1021
+ workflow,
1022
+ };
1023
+
1024
+ const maxRowsLines = result.maxRowsWarning
1025
+ ? [
1026
+ `[bkit-telemetry] WARNING: MAX_ROWS_BEFORE_ROLLUP (${MAX_ROWS_BEFORE_ROLLUP}) exceeded — ${result.rowCount} rows in stats.jsonl; consider archiving.`,
1027
+ ]
1028
+ : [];
1029
+
1030
+ // No workflow → ledger-health readout only.
1031
+ if (!workflow) {
1032
+ return { ...base, lines: [ledgerLine(result), ...maxRowsLines] };
1033
+ }
1034
+
1035
+ // This workflow's run rows (generalized outcome), oldest → newest.
1036
+ const runs = events
1037
+ .filter((e): e is OutcomeEvent => e.kind === "outcome" && e.workflow === workflow)
1038
+ .sort(compareTs);
1039
+ const cur = runs.at(-1);
1040
+ // Baseline only against runs of the same plan source — a brief run (no plan)
1041
+ // has no tasks and a different shape, so mixing them skews every median.
1042
+ const prev = runs
1043
+ .slice(0, -1)
1044
+ .filter((r) => r.planSource === cur?.planSource)
1045
+ .slice(-RUN_BASELINE_WINDOW);
1046
+
1047
+ const repo = cur?.repo ?? events[0]?.repo ?? "unknown/repo";
1048
+ // Rendered as a Markdown table so it drops straight into the tracker comment
1049
+ // (no code fence needed) — GitHub/Linear render it natively.
1050
+ const lines: string[] = [`**${workflow} close** · ${repo}`, ""];
1051
+
1052
+ const tableRows: string[] = [];
1053
+ const row = (label: string, self: string, med: string): void => {
1054
+ tableRows.push(`| ${label} | ${self} | ${med} |`);
1055
+ };
1056
+
1057
+ if (cur) {
1058
+ // med·N: median of the previous runs that carry the field, `—` until there are
1059
+ // at least RUN_BASELINE_MIN of them (1–2 samples is noise, not a baseline).
1060
+ const medCell = (key: keyof OutcomeEvent, fmt: (n: number) => string = String): string => {
1061
+ const vals = prev.map((r) => r[key]).filter((v): v is number => typeof v === "number");
1062
+ if (vals.length < RUN_BASELINE_MIN) return "—";
1063
+ const m = median(vals);
1064
+ return m === null ? "—" : fmt(m);
1065
+ };
1066
+
1067
+ // Core metrics — always shown.
1068
+ row(
1069
+ "durationSeconds",
1070
+ `${cur.durationSeconds} (${humanizeDuration(cur.durationSeconds)})`,
1071
+ medCell("durationSeconds", (n) => `${n} (${humanizeDuration(n)})`),
1072
+ );
1073
+ row(
1074
+ "linesChanged",
1075
+ `${cur.linesChanged} (+${cur.linesAdded}/-${cur.linesDeleted})`,
1076
+ medCell("linesChanged"),
1077
+ );
1078
+ row("filesChanged", `${cur.filesChanged}`, medCell("filesChanged"));
1079
+
1080
+ // Conditional metrics — shown only when this run carries them.
1081
+ if (cur.planSource) row("planSource", cur.planSource, "—");
1082
+ if (cur.taskCount > 0) row("taskCount", `${cur.taskCount}`, medCell("taskCount"));
1083
+ if (typeof cur.reviewIterations === "number")
1084
+ row("reviewIterations", `${cur.reviewIterations}`, medCell("reviewIterations"));
1085
+ if (typeof cur.correctiveCommits === "number")
1086
+ row("correctiveCommits", `${cur.correctiveCommits}`, medCell("correctiveCommits"));
1087
+ if (typeof cur.ciTrySuccess === "number")
1088
+ row(
1089
+ "ciTrySuccess",
1090
+ `${cur.ciTrySuccess}${cur.ciTrySuccess === 1 ? " (first-try)" : ""}`,
1091
+ medCell("ciTrySuccess"),
1092
+ );
1093
+ // Instinct-loop deltas — frictionAdded is the featured signal (shown even at 0).
1094
+ if (typeof cur.frictionAdded === "number")
1095
+ row("frictionAdded", `${cur.frictionAdded}`, medCell("frictionAdded"));
1096
+ if (typeof cur.deferralsAdded === "number")
1097
+ row("deferralsAdded", `${cur.deferralsAdded}`, medCell("deferralsAdded"));
1098
+ if (typeof cur.failuresAdded === "number")
1099
+ row("failuresAdded", `${cur.failuresAdded}`, medCell("failuresAdded"));
1100
+ }
1101
+
1102
+ // Compliance — this run's rows. The `outcome` and `compliance` rows are written
1103
+ // at different points in a close (different HEADs → different parentSha), so we
1104
+ // DON'T match on the run row's parentSha: we take the newest same-workflow
1105
+ // compliance group (its parentSha) as "this run".
1106
+ const complianceRows = events.filter(
1107
+ (e): e is ComplianceEvent => e.kind === "compliance" && e.workflow === workflow,
1108
+ );
1109
+ const compSha = complianceRows.slice().sort((a, b) => compareTs(b, a))[0]?.parentSha;
1110
+ if (compSha) {
1111
+ const comp = complianceRows.filter((c) => c.parentSha === compSha);
1112
+ const pass = comp.filter((c) => c.result === "pass").length;
1113
+ const fail = comp.filter((c) => c.result === "fail").length;
1114
+ const na = comp.filter((c) => c.result === "n/a").length;
1115
+ const denom = pass + fail + na;
1116
+ const rate = denom > 0 ? Math.round((pass / denom) * 100) : 0;
1117
+ row("compliance", `${pass} pass · ${fail} fail · ${na} n/a (${rate}%)`, "—");
1118
+ }
1119
+
1120
+ // Attempts — the newest same-workflow *_ATTEMPT counter (this run).
1121
+ const attempt = events
1122
+ .filter(
1123
+ (e): e is CounterEvent =>
1124
+ e.kind === "counter" && e.workflow === workflow && /_ATTEMPT$/.test(e.counterName),
1125
+ )
1126
+ .sort((a, b) => compareTs(b, a))[0];
1127
+ if (attempt) row("attempts", `${attempt.counterName} ${attempt.counterValue}`, "—");
1128
+
1129
+ if (tableRows.length > 0) {
1130
+ lines.push(
1131
+ `| metric | this run | med·${RUN_BASELINE_WINDOW} |`,
1132
+ "| --- | --- | --- |",
1133
+ ...tableRows,
1134
+ "",
1135
+ );
1136
+ }
1137
+ lines.push(
1138
+ `\`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`,
1139
+ );
1140
+ lines.push(...maxRowsLines);
1141
+
1142
+ return { ...base, lines };
1143
+ }