@cbartens/bkit 5.5.1 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (425) hide show
  1. package/.bkit/README.md +167 -154
  2. package/.bkit/core/.agents/context.md +95 -29
  3. package/.bkit/core/.agents/docs.md +18 -15
  4. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-gateguard.cjs +1 -0
  5. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-guardrails.cjs +6 -5
  6. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-readguard.cjs +1 -0
  7. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-rules.cjs +65 -0
  8. package/.bkit/core/.agents/rules.md +112 -102
  9. package/.bkit/core/.agents/skills.md +63 -15
  10. package/.bkit/core/.bkit/README.md +167 -154
  11. package/.bkit/core/.bkit/authoring.md +747 -0
  12. package/.bkit/core/.bkit/cli.md +407 -0
  13. package/.bkit/core/.bkit/cloud.md +283 -195
  14. package/.bkit/core/.bkit/comparison.md +45 -43
  15. package/.bkit/core/.bkit/install.md +166 -95
  16. package/.bkit/core/.bkit/jsonl.md +339 -196
  17. package/.bkit/core/.bkit/pipeline.md +142 -145
  18. package/.bkit/core/.bkit/prompts.md +295 -264
  19. package/.bkit/core/.bkit/providers.md +460 -277
  20. package/.bkit/core/.bkit/router.md +69 -0
  21. package/.bkit/core/.bkit/templates.md +530 -256
  22. package/.bkit/core/.bkit/trackers.md +116 -65
  23. package/.bkit/core/.bkit/workflows.md +742 -618
  24. package/.bkit/core/.claude/hooks/bkit-gateguard.cjs +2 -2
  25. package/.bkit/core/.claude/hooks/bkit-guardrails.cjs +3 -3
  26. package/.bkit/core/.claude/hooks/bkit-preflight.sh +45 -14
  27. package/.bkit/core/.codex/hooks/bkit-guardrails.cjs +3 -3
  28. package/.bkit/core/.codex/hooks/bkit-rules.cjs +57 -0
  29. package/.bkit/core/.cursor/hooks/bkit-guardrails.cjs +7 -7
  30. package/.bkit/core/.cursor/hooks/bkit-preflight.sh +47 -12
  31. package/.bkit/core/.opencode/plugin/bkit-rules.js +89 -0
  32. package/.bkit/core/AGENTS.md +6 -80
  33. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +128 -130
  34. package/.bkit/core/docs/templates/bkit-audit-adoption.md +104 -94
  35. package/.bkit/core/docs/templates/bkit-audit-agents.md +96 -98
  36. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +100 -103
  37. package/.bkit/core/docs/templates/bkit-audit-analytics.md +141 -107
  38. package/.bkit/core/docs/templates/bkit-audit-annotations.md +99 -97
  39. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +122 -121
  40. package/.bkit/core/docs/templates/bkit-audit-app-store.md +158 -101
  41. package/.bkit/core/docs/templates/bkit-audit-architecture.md +114 -96
  42. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +76 -97
  43. package/.bkit/core/docs/templates/bkit-audit-config.md +123 -101
  44. package/.bkit/core/docs/templates/bkit-audit-cost.md +86 -99
  45. package/.bkit/core/docs/templates/bkit-audit-coverage.md +76 -93
  46. package/.bkit/core/docs/templates/bkit-audit-database.md +102 -95
  47. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +165 -108
  48. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +115 -109
  49. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +265 -113
  50. package/.bkit/core/docs/templates/bkit-audit-documentation.md +119 -118
  51. package/.bkit/core/docs/templates/bkit-audit-duplication.md +140 -111
  52. package/.bkit/core/docs/templates/bkit-audit-failures.md +111 -106
  53. package/.bkit/core/docs/templates/bkit-audit-flakes.md +100 -99
  54. package/.bkit/core/docs/templates/bkit-audit-gates.md +107 -103
  55. package/.bkit/core/docs/templates/bkit-audit-issues.md +105 -105
  56. package/.bkit/core/docs/templates/bkit-audit-llm.md +134 -85
  57. package/.bkit/core/docs/templates/bkit-audit-logs.md +124 -125
  58. package/.bkit/core/docs/templates/bkit-audit-models.md +99 -78
  59. package/.bkit/core/docs/templates/bkit-audit-privacy.md +56 -76
  60. package/.bkit/core/docs/templates/bkit-audit-prompts.md +63 -78
  61. package/.bkit/core/docs/templates/bkit-audit-red-team.md +125 -93
  62. package/.bkit/core/docs/templates/bkit-audit-reliability.md +97 -96
  63. package/.bkit/core/docs/templates/bkit-audit-repo.md +170 -98
  64. package/.bkit/core/docs/templates/bkit-audit-security.md +207 -121
  65. package/.bkit/core/docs/templates/bkit-audit-slop.md +78 -95
  66. package/.bkit/core/docs/templates/bkit-audit-testing.md +163 -139
  67. package/.bkit/core/docs/templates/bkit-audit-usability.md +114 -96
  68. package/.bkit/core/docs/templates/bkit-plan.md +158 -281
  69. package/.bkit/core/engine/checks/after/auth.ts +40 -37
  70. package/.bkit/core/engine/checks/after/ci-yml.ts +104 -31
  71. package/.bkit/core/engine/checks/after/github.ts +95 -17
  72. package/.bkit/core/engine/checks/after/index.ts +21 -8
  73. package/.bkit/core/engine/checks/after/suppression.ts +8 -5
  74. package/.bkit/core/engine/checks/after/tools.ts +125 -123
  75. package/.bkit/core/engine/checks/before/context-fetch.ts +227 -33
  76. package/.bkit/core/engine/checks/before/env.ts +3 -3
  77. package/.bkit/core/engine/checks/before/files.ts +5 -4
  78. package/.bkit/core/engine/checks/before/index.ts +25 -1
  79. package/.bkit/core/engine/checks/before/repo.ts +208 -2
  80. package/.bkit/core/engine/checks/status-holes.ts +916 -123
  81. package/.bkit/core/engine/checks/tips/catalogue.ts +82 -20
  82. package/.bkit/core/engine/checks/tips/detect.ts +66 -0
  83. package/.bkit/core/engine/checks/tips/index.ts +52 -11
  84. package/.bkit/core/engine/cli.ts +251 -130
  85. package/.bkit/core/engine/commands/analysis.ts +282 -199
  86. package/.bkit/core/engine/commands/ci/ci.ts +363 -29
  87. package/.bkit/core/engine/commands/ci/pins.ts +172 -0
  88. package/.bkit/core/engine/commands/ci/push-gate.ts +223 -0
  89. package/.bkit/core/engine/commands/comply.ts +77 -103
  90. package/.bkit/core/engine/commands/install/doctor.ts +2 -2
  91. package/.bkit/core/engine/commands/install/install.ts +57 -18
  92. package/.bkit/core/engine/commands/install/uninstall.ts +86 -55
  93. package/.bkit/core/engine/commands/install/upgrade.ts +32 -15
  94. package/.bkit/core/engine/commands/land.ts +139 -18
  95. package/.bkit/core/engine/commands/lib.ts +381 -22
  96. package/.bkit/core/engine/commands/registry.ts +10 -2
  97. package/.bkit/core/engine/commands/setup/setup.ts +8 -7
  98. package/.bkit/core/engine/commands/stats.ts +260 -0
  99. package/.bkit/core/engine/commands/tips.ts +10 -5
  100. package/.bkit/core/engine/commands/workflow/branches.ts +2215 -176
  101. package/.bkit/core/engine/commands/workflow/challenge.ts +748 -0
  102. package/.bkit/core/engine/commands/workflow/completeness.ts +109 -0
  103. package/.bkit/core/engine/commands/workflow/context.ts +1249 -47
  104. package/.bkit/core/engine/commands/workflow/counters.ts +483 -95
  105. package/.bkit/core/engine/commands/workflow/decisions.ts +585 -0
  106. package/.bkit/core/engine/commands/workflow/disk.ts +238 -56
  107. package/.bkit/core/engine/commands/workflow/fids.ts +811 -33
  108. package/.bkit/core/engine/commands/workflow/issues.ts +413 -64
  109. package/.bkit/core/engine/commands/workflow/ledgers.ts +1333 -36
  110. package/.bkit/core/engine/commands/workflow/locks.ts +28 -2
  111. package/.bkit/core/engine/commands/workflow/plan-blocks.ts +691 -0
  112. package/.bkit/core/engine/commands/workflow/plan-versions.ts +21 -0
  113. package/.bkit/core/engine/commands/workflow/plans.ts +257 -0
  114. package/.bkit/core/engine/commands/workflow/prs.ts +178 -33
  115. package/.bkit/core/engine/commands/workflow/repo.ts +66 -8
  116. package/.bkit/core/engine/commands/workflow/roadmap.ts +72 -22
  117. package/.bkit/core/engine/commands/workflow/run-facts.ts +492 -0
  118. package/.bkit/core/engine/commands/workflow/runs.ts +827 -79
  119. package/.bkit/core/engine/commands/workflow/runtime.ts +25 -1
  120. package/.bkit/core/engine/commands/workflow/skills.ts +1 -0
  121. package/.bkit/core/engine/commands/workflow/status.ts +329 -33
  122. package/.bkit/core/engine/commands/workflow/step-table.ts +381 -0
  123. package/.bkit/core/engine/commands/workflow/steps.ts +841 -105
  124. package/.bkit/core/engine/commands/workflow/summary-findings.ts +177 -0
  125. package/.bkit/core/engine/commands/workflow/summary.ts +544 -0
  126. package/.bkit/core/engine/commands/workflow/tasks.ts +409 -0
  127. package/.bkit/core/engine/commands/workflow/test-blocks.ts +254 -0
  128. package/.bkit/core/engine/commands/workflow/tests-changed.ts +201 -0
  129. package/.bkit/core/engine/commands/workflow/tests.ts +2124 -330
  130. package/.bkit/core/engine/commands/workflow/tracker.ts +1195 -0
  131. package/.bkit/core/engine/commands/workflow/workflows.ts +1197 -235
  132. package/.bkit/core/engine/commands/workflow/worktrees.ts +543 -24
  133. package/.bkit/core/engine/install/cloud-env.ts +251 -121
  134. package/.bkit/core/engine/install/context-ci-workflow.ts +102 -0
  135. package/.bkit/core/engine/install/manifest.ts +67 -17
  136. package/.bkit/core/engine/install/modules/antigravity.ts +3 -2
  137. package/.bkit/core/engine/install/modules/cloud.ts +24 -16
  138. package/.bkit/core/engine/install/modules/codex.ts +15 -2
  139. package/.bkit/core/engine/install/modules/core.ts +1196 -45
  140. package/.bkit/core/engine/install/modules/cursor.ts +6 -6
  141. package/.bkit/core/engine/install/modules/opencode.ts +18 -6
  142. package/.bkit/core/engine/install/template-notes.ts +130 -0
  143. package/.bkit/core/engine/install/version-file.ts +9 -4
  144. package/.bkit/core/engine/install/write.ts +5 -0
  145. package/.bkit/core/engine/ledgers/compact.ts +124 -0
  146. package/.bkit/core/engine/ledgers/journal.ts +291 -0
  147. package/.bkit/core/engine/ledgers/migrate.ts +92 -0
  148. package/.bkit/core/engine/ledgers/status.ts +249 -21
  149. package/.bkit/core/engine/ledgers/telemetry.ts +1397 -253
  150. package/.bkit/core/engine/render/hosts.ts +118 -14
  151. package/.bkit/core/engine/render/models.ts +12 -0
  152. package/.bkit/core/engine/shared/bkit-latest.ts +26 -4
  153. package/.bkit/core/engine/shared/branches.ts +4 -1
  154. package/.bkit/core/engine/shared/dep-updater.ts +60 -0
  155. package/.bkit/core/engine/shared/egress.ts +8 -1
  156. package/.bkit/core/engine/shared/json.ts +25 -7
  157. package/.bkit/core/engine/shared/package-manager.ts +9 -0
  158. package/.bkit/core/engine/shared/settings.ts +243 -31
  159. package/.bkit/core/engine/shared/text.ts +361 -0
  160. package/.bkit/core/engine/shared/timeouts.ts +2 -0
  161. package/.bkit/core/engine/tools/cli-doc.ts +111 -0
  162. package/.bkit/core/engine/tools/grammar-density.ts +215 -0
  163. package/.bkit/core/engine/tools/instructions-sources.ts +832 -0
  164. package/.bkit/core/engine/tools/instructions.ts +1802 -0
  165. package/.bkit/core/hooks/antigravity-hook.js +25 -10
  166. package/.bkit/core/hooks/gateguard-engine.js +54 -29
  167. package/.bkit/core/hooks/guardrails-shell.js +4 -5
  168. package/.bkit/core/hooks/guardrails-tiers.js +10 -4
  169. package/.bkit/core/hooks/preflight-linear.sh +9 -9
  170. package/.bkit/core/hooks/preflight-rules.sh +8 -0
  171. package/.bkit/core/hooks/readguard-engine.js +29 -10
  172. package/.bkit/core/hooks/session-rules-advisory.js +61 -0
  173. package/.bkit/core/prompts/bkit-audit-generate.md +202 -94
  174. package/.bkit/core/prompts/bkit-build-challenge-1.md +76 -34
  175. package/.bkit/core/prompts/bkit-build-challenge-2.md +85 -38
  176. package/.bkit/core/prompts/bkit-build-install-skills.md +50 -28
  177. package/.bkit/core/prompts/bkit-build-plan-convert.md +85 -0
  178. package/.bkit/core/prompts/bkit-build-plan-current.md +59 -36
  179. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +101 -36
  180. package/.bkit/core/prompts/bkit-build-plan-tasks.md +149 -0
  181. package/.bkit/core/prompts/bkit-build-plan-tests.md +120 -0
  182. package/.bkit/core/prompts/bkit-build-plan-verify.md +104 -43
  183. package/.bkit/core/prompts/bkit-debug-abort-handover.md +47 -32
  184. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +109 -57
  185. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +65 -39
  186. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +53 -31
  187. package/.bkit/core/prompts/bkit-debug-failure-soak.md +65 -34
  188. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +46 -31
  189. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +45 -31
  190. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +43 -30
  191. package/.bkit/core/prompts/bkit-design-generate.md +80 -46
  192. package/.bkit/core/prompts/bkit-design-organise.md +83 -32
  193. package/.bkit/core/prompts/bkit-design-review-1.md +70 -50
  194. package/.bkit/core/prompts/bkit-design-review-2.md +65 -46
  195. package/.bkit/core/prompts/bkit-design-spike.md +64 -40
  196. package/.bkit/core/prompts/bkit-design-update.md +53 -28
  197. package/.bkit/core/prompts/bkit-plan-generate.md +101 -29
  198. package/.bkit/core/prompts/bkit-plan-review-1.md +78 -41
  199. package/.bkit/core/prompts/bkit-plan-review-2.md +78 -35
  200. package/.bkit/core/prompts/bkit-plan-scope-check.md +116 -0
  201. package/.bkit/core/prompts/bkit-plan-update.md +86 -31
  202. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +94 -50
  203. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +91 -41
  204. package/.bkit/core/prompts/bkit-ship-update-docs.md +45 -24
  205. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +65 -49
  206. package/.bkit/core/prompts/bkit-utility-update-decisions.md +87 -42
  207. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +81 -37
  208. package/.bkit/core/prompts/bkit-utility-update-documentation.md +43 -25
  209. package/.bkit/core/prompts/bkit-utility-update-failures.md +84 -37
  210. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +88 -42
  211. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +92 -39
  212. package/.bkit/core/prompts/bkit-utility-update-tracker.md +159 -60
  213. package/.bkit/core/workflows/bkit-auto.md +89 -58
  214. package/.bkit/core/workflows/bkit-build.md +967 -517
  215. package/.bkit/core/workflows/bkit-debug.md +555 -387
  216. package/.bkit/core/workflows/bkit-design.md +319 -283
  217. package/.bkit/core/workflows/bkit-plan.md +319 -342
  218. package/.bkit/core/workflows/bkit-ship.md +525 -328
  219. package/.bkit/shared/.agents/plugins/bkit/hooks.json +10 -0
  220. package/.bkit/shared/.bkit/.env.example +2 -2
  221. package/.bkit/shared/.claude/bkit-cloud.md +12 -10
  222. package/.bkit/shared/.claude/settings.json +14 -0
  223. package/.bkit/shared/.codex/bkit-cloud.md +98 -0
  224. package/.bkit/shared/.codex/hooks.json +20 -0
  225. package/.bkit/shared/.cursor/bkit-cloud.md +3 -3
  226. package/.bkit/shared/.cursor/mcp.json +1 -1
  227. package/.bkit/shared/.cursor/rules/bkit-rules.mdc +1 -1
  228. package/.bkit/shared/.gitattributes +1 -1
  229. package/.bkit/shared/.mcp.json +1 -1
  230. package/.bkit/shared/.opencode/opencode.json +12 -1
  231. package/.bkit/shared/CLAUDE.md +6 -2
  232. package/.bkit/shared/GEMINI.md +5 -2
  233. package/.bkit/shared/docs/architecture.md +4 -7
  234. package/.bkit/shared/docs/data-schema.md +4 -7
  235. package/.bkit/shared/docs/deployments.md +241 -168
  236. package/.bkit/shared/docs/design.md +11 -12
  237. package/.bkit/shared/docs/noise.md +8 -7
  238. package/.bkit/shared/docs/observability.md +5 -8
  239. package/.bkit/shared/docs/security.md +35 -17
  240. package/.bkit/shared/docs/setup.md +29 -18
  241. package/.bkit/shared/docs/technology.md +3 -6
  242. package/.bkit/shared/docs/testing.md +289 -174
  243. package/.bkit/shared/gitignore +6 -2
  244. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +15 -16
  245. package/.bkit/templates/.cursor/Dockerfile +12 -8
  246. package/.bkit/templates/.cursor/environment.json +1 -1
  247. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-bug.yml +10 -8
  248. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-change.yml +45 -12
  249. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-idea.yml +3 -3
  250. package/.bkit/templates/.github/renovate.json5 +34 -6
  251. package/.bkit/templates/.github/workflows/bkit-ci.yml +54 -51
  252. package/.bkit/templates/.github/workflows/bkit-cloud.yml +34 -33
  253. package/.bkit/templates/.github/workflows/bkit-health.yml +97 -0
  254. package/.bkit/templates/.github/workflows/bkit-renovate.yml +5 -4
  255. package/.bkit/templates/.github/workflows/bkit-trivy.yml +5 -4
  256. package/.bkit/templates/.husky/pre-commit +2 -2
  257. package/.bkit/templates/.husky/pre-push +96 -36
  258. package/.bkit/templates/.prettierignore +6 -0
  259. package/.bkit/templates/.vale.ini +27 -27
  260. package/.bkit/templates/context/bkit-cloudrun.md +23 -15
  261. package/.bkit/templates/context/bkit-expo.md +70 -52
  262. package/.bkit/templates/context/bkit-github.md +93 -56
  263. package/.bkit/templates/context/bkit-inngest.md +21 -15
  264. package/.bkit/templates/context/bkit-maestro.md +22 -16
  265. package/.bkit/templates/context/bkit-playwright.md +23 -17
  266. package/.bkit/templates/context/bkit-resend.md +12 -10
  267. package/.bkit/templates/context/bkit-sentry.md +30 -20
  268. package/.bkit/templates/context/bkit-serena.md +8 -7
  269. package/.bkit/templates/context/bkit-stripe.md +14 -13
  270. package/.bkit/templates/context/bkit-supabase.md +16 -13
  271. package/.bkit/templates/context/bkit-tavily.md +14 -11
  272. package/.bkit/templates/context/bkit-vercel.md +27 -18
  273. package/.bkit/templates/docs/capabilities.md +15 -14
  274. package/.bkit/templates/scripts/ci/{check-accepted-divergences.mjs → bkit-check-accepted-divergences.mjs} +6 -3
  275. package/.bkit/templates/scripts/ci/{check-accepted-divergences.test.mjs → bkit-check-accepted-divergences.test.mjs} +3 -3
  276. package/.bkit/templates/scripts/ci/{check-capstone.mjs → bkit-check-capstone.mjs} +2 -2
  277. package/.bkit/templates/scripts/ci/{check-capstone.test.mjs → bkit-check-capstone.test.mjs} +4 -4
  278. package/.bkit/templates/scripts/ci/{check-dependency-audit.mjs → bkit-check-dependency-audit.mjs} +103 -18
  279. package/.bkit/templates/scripts/ci/{check-dependency-audit.test.mjs → bkit-check-dependency-audit.test.mjs} +31 -3
  280. package/.bkit/templates/scripts/ci/bkit-machine-lock.sh +387 -0
  281. package/.bkit/templates/scripts/ci/bkit-test-awake.mjs +75 -0
  282. package/.bkit/templates/scripts/ci/bkit-test-awake.test.mjs +160 -0
  283. package/.bkit/templates/scripts/ci/lanes/{resolve-push-base.mjs → bkit-resolve-push-base.mjs} +3 -3
  284. package/.bkit/templates/scripts/ci/lanes/{resolve-push-base.test.mjs → bkit-resolve-push-base.test.mjs} +4 -4
  285. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.mjs +10 -2
  286. package/.bkit/templates/scripts/graphify/bkit-graph-drift.py +1 -1
  287. package/.bkit/templates/scripts/graphify/bkit-graph-eager.py +3 -3
  288. package/.bkit/templates/scripts/graphify/bkit-graph-embed.py +63 -0
  289. package/.bkit/templates/scripts/graphify/bkit-graph-imports.py +2 -2
  290. package/.bkit/templates/scripts/graphify/bkit-graph-pre-push.sh +69 -18
  291. package/.bkit/templates/scripts/graphify/bkit-graph-repair.py +3 -3
  292. package/.bkit/templates/scripts/graphify/bkit-graph-surface.py +1 -1
  293. package/.bkit/templates/scripts/graphify/bkit-graphify-graphml.py +1 -1
  294. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +197 -126
  295. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +64 -41
  296. package/.bkit/templates/scripts/slop/bkit-slop-type-suppression.mjs +23 -7
  297. package/.bkit/templates/slop-scan.config.json +9 -2
  298. package/CHANGELOG.md +231 -0
  299. package/README.md +278 -89
  300. package/dist/checks/after/auth.js +36 -33
  301. package/dist/checks/after/ci-yml.js +91 -30
  302. package/dist/checks/after/github.js +91 -17
  303. package/dist/checks/after/index.js +22 -11
  304. package/dist/checks/after/suppression.js +8 -5
  305. package/dist/checks/after/tools.js +111 -114
  306. package/dist/checks/before/context-fetch.js +218 -33
  307. package/dist/checks/before/env.js +3 -3
  308. package/dist/checks/before/files.js +5 -3
  309. package/dist/checks/before/index.js +20 -3
  310. package/dist/checks/before/repo.js +197 -2
  311. package/dist/checks/status-holes.js +739 -114
  312. package/dist/checks/tips/catalogue.js +70 -19
  313. package/dist/checks/tips/detect.js +62 -0
  314. package/dist/checks/tips/index.js +51 -9
  315. package/dist/cli.js +234 -124
  316. package/dist/commands/analysis.js +174 -141
  317. package/dist/commands/ci/ci.js +302 -25
  318. package/dist/commands/ci/pins.js +142 -0
  319. package/dist/commands/ci/push-gate.js +194 -0
  320. package/dist/commands/comply.js +54 -91
  321. package/dist/commands/install/doctor.js +2 -2
  322. package/dist/commands/install/install.js +50 -19
  323. package/dist/commands/install/uninstall.js +82 -55
  324. package/dist/commands/install/upgrade.js +21 -11
  325. package/dist/commands/land.js +137 -17
  326. package/dist/commands/lib.js +295 -21
  327. package/dist/commands/registry.js +10 -2
  328. package/dist/commands/setup/setup.js +8 -7
  329. package/dist/commands/stats.js +175 -0
  330. package/dist/commands/tips.js +7 -3
  331. package/dist/commands/workflow/branches.js +1873 -152
  332. package/dist/commands/workflow/challenge.js +609 -0
  333. package/dist/commands/workflow/completeness.js +97 -0
  334. package/dist/commands/workflow/context.js +1045 -46
  335. package/dist/commands/workflow/counters.js +385 -86
  336. package/dist/commands/workflow/decisions.js +484 -0
  337. package/dist/commands/workflow/disk.js +214 -56
  338. package/dist/commands/workflow/fids.js +706 -33
  339. package/dist/commands/workflow/issues.js +349 -59
  340. package/dist/commands/workflow/ledgers.js +1123 -37
  341. package/dist/commands/workflow/locks.js +26 -2
  342. package/dist/commands/workflow/plan-blocks.js +501 -0
  343. package/dist/commands/workflow/plan-versions.js +22 -0
  344. package/dist/commands/workflow/plans.js +205 -0
  345. package/dist/commands/workflow/prs.js +154 -35
  346. package/dist/commands/workflow/repo.js +58 -8
  347. package/dist/commands/workflow/roadmap.js +58 -23
  348. package/dist/commands/workflow/run-facts.js +421 -0
  349. package/dist/commands/workflow/runs.js +670 -72
  350. package/dist/commands/workflow/runtime.js +15 -1
  351. package/dist/commands/workflow/skills.js +1 -0
  352. package/dist/commands/workflow/status.js +282 -34
  353. package/dist/commands/workflow/step-table.js +308 -0
  354. package/dist/commands/workflow/steps.js +703 -96
  355. package/dist/commands/workflow/summary-findings.js +117 -0
  356. package/dist/commands/workflow/summary.js +388 -0
  357. package/dist/commands/workflow/tasks.js +378 -0
  358. package/dist/commands/workflow/test-blocks.js +231 -0
  359. package/dist/commands/workflow/tests-changed.js +172 -0
  360. package/dist/commands/workflow/tests.js +1695 -305
  361. package/dist/commands/workflow/tracker.js +983 -0
  362. package/dist/commands/workflow/workflows.js +1014 -222
  363. package/dist/commands/workflow/worktrees.js +432 -26
  364. package/dist/install/cloud-env.js +233 -99
  365. package/dist/install/context-ci-workflow.js +85 -0
  366. package/dist/install/manifest.js +64 -17
  367. package/dist/install/modules/antigravity.js +3 -2
  368. package/dist/install/modules/cloud.js +25 -16
  369. package/dist/install/modules/codex.js +12 -2
  370. package/dist/install/modules/core.js +1090 -48
  371. package/dist/install/modules/cursor.js +6 -6
  372. package/dist/install/modules/opencode.js +13 -7
  373. package/dist/install/template-notes.js +116 -0
  374. package/dist/install/version-file.js +9 -4
  375. package/dist/ledgers/compact.js +87 -0
  376. package/dist/ledgers/journal.js +233 -0
  377. package/dist/ledgers/migrate.js +81 -0
  378. package/dist/ledgers/status.js +176 -13
  379. package/dist/ledgers/telemetry.js +1010 -125
  380. package/dist/render/hosts.js +104 -14
  381. package/dist/render/models.js +12 -0
  382. package/dist/shared/bkit-latest.js +26 -4
  383. package/dist/shared/branches.js +3 -1
  384. package/dist/shared/dep-updater.js +49 -0
  385. package/dist/shared/egress.js +8 -1
  386. package/dist/shared/json.js +20 -7
  387. package/dist/shared/package-manager.js +6 -0
  388. package/dist/shared/settings.js +181 -24
  389. package/dist/shared/text.js +333 -0
  390. package/dist/shared/timeouts.js +2 -0
  391. package/dist/tools/cli-doc.js +97 -0
  392. package/dist/tools/grammar-density.js +183 -0
  393. package/dist/tools/instructions-sources.js +720 -0
  394. package/dist/tools/instructions.js +1623 -0
  395. package/package.json +156 -51
  396. package/.bkit/core/.bkit/lite.md +0 -73
  397. package/.bkit/core/engine/commands/harvest.ts +0 -459
  398. package/.bkit/core/engine/commands/workflow/workstreams.ts +0 -166
  399. package/.bkit/core/engine/tools/wording.ts +0 -748
  400. package/.bkit/core/prompts/bkit-build-challenge-reconcile.md +0 -69
  401. package/.bkit/core/prompts/bkit-build-challenge-remediate.md +0 -71
  402. package/.bkit/core/prompts/bkit-build-challenge-tests.md +0 -74
  403. package/.bkit/core/prompts/bkit-build-plan-execute.md +0 -76
  404. package/.bkit/core/prompts/bkit-build-summary.md +0 -94
  405. package/.bkit/core/prompts/bkit-debug-summary.md +0 -96
  406. package/.bkit/core/prompts/bkit-design-summary.md +0 -107
  407. package/.bkit/core/prompts/bkit-plan-complexity-check.md +0 -67
  408. package/.bkit/core/prompts/bkit-plan-complexity-split.md +0 -88
  409. package/.bkit/core/prompts/bkit-plan-review-3.md +0 -93
  410. package/.bkit/core/prompts/bkit-plan-scope-check-1.md +0 -85
  411. package/.bkit/core/prompts/bkit-plan-scope-check-2.md +0 -85
  412. package/.bkit/core/prompts/bkit-plan-summary.md +0 -107
  413. package/.bkit/core/prompts/bkit-ship-summary.md +0 -78
  414. package/.bkit/templates/scripts/ci/bkit-local-stack-lock.sh +0 -194
  415. package/dist/commands/harvest.js +0 -353
  416. package/dist/commands/workflow/workstreams.js +0 -143
  417. package/dist/tools/wording.js +0 -680
  418. /package/.bkit/templates/.vale/styles/{House → Bkit}/Filler.yml +0 -0
  419. /package/.bkit/templates/.vale/styles/{House → Bkit}/Hedging.yml +0 -0
  420. /package/.bkit/templates/.vale/styles/{House → Bkit}/LLMSlop.yml +0 -0
  421. /package/.bkit/templates/.vale/styles/{House → Bkit}/Verbose.yml +0 -0
  422. /package/.bkit/templates/scripts/ci/{accepted-advisories.json → bkit-accepted-advisories.json} +0 -0
  423. /package/.bkit/templates/scripts/ci/{accepted-divergences.json → bkit-accepted-divergences.json} +0 -0
  424. /package/.bkit/templates/scripts/launchd/{launchd.env.example → bkit-launchd.env.example} +0 -0
  425. /package/.bkit/templates/scripts/launchd/{ai.bkit.launchd.plist → bkit-launchd.plist} +0 -0
@@ -13,8 +13,8 @@
13
13
  // (b) `validate` REJECTS unknown `kind` before write. No reject path in status.ts.
14
14
  // (c) ms `ts` via now*1000|floor, NOT ISO `at`.
15
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`
16
+ // Version provenance: every row records the emitting `bkit.version`. Readers ingest
17
+ // ALL well-formed rows (no version gating) and report row counts per `bkit.version`
18
18
  // so an unexpected version surfaces for triage.
19
19
 
20
20
  import { spawnSync } from "node:child_process";
@@ -111,17 +111,19 @@ export function resolveRepoSlug(cwd: string): string {
111
111
  // Shared envelope (A2-mandatory fields on EVERY row, every kind)
112
112
  // ---------------------------------------------------------------------------
113
113
 
114
- export interface TelemetryEnvelope {
115
- /** Primary id = unix milliseconds (portable: jq `now*1000|floor`). */
116
- ts: number;
117
- /** Closed enum — validated on append; unknown kind rejected. */
118
- kind: TelemetryKind;
119
- /** Origin repo (slug, e.g. "cbartens/bkit"). */
120
- repo: string;
121
- /** bkit version stamped on every row for regression attribution. */
122
- bkitVersion: string;
123
- /** Emitting workflow: design | plan | build | debug | ship | audit */
124
- workflow: string;
114
+ /**
115
+ * Row format version. Rows written without `schema` are read through {@link normalize}.
116
+ * A schema-2 row differs only in its outcome `plan` block ({@link StoredPlanBlock}).
117
+ */
118
+ export const SCHEMA = 3;
119
+
120
+ /** The schema {@link normalize} stamps on a row written without one: the shape it builds. */
121
+ const NORMALIZED_SCHEMA = 2;
122
+
123
+ /** Who wrote a row: the workflow and step it was emitted at, and the subagent when one wrote it. */
124
+ export interface RowBy {
125
+ /** Emitting workflow: design | plan | build | debug | ship | auto | audit; `utility` for a direct chat outside any workflow; `chat-stats` on `chat` rows; the counted run's on `run` rows. */
126
+ workflow?: string;
125
127
  /**
126
128
  * The WORKFLOW STEP the row was emitted at, e.g. `build-close-workflow`,
127
129
  * `ship-close-gate`. A step of the orchestrator, never an agent name — a
@@ -129,38 +131,65 @@ export interface TelemetryEnvelope {
129
131
  */
130
132
  step: string;
131
133
  /**
132
- * The SUBAGENT that wrote the row, e.g. `bkit-build-challenge-remediate`.
134
+ * The SUBAGENT that wrote the row, e.g. `bkit-build-plan-gaps-remediate`.
133
135
  * Absent on orchestrator-written rows (the workflow itself wrote it).
134
- *
135
- * Distinct from `step`: `step` is WHERE in the workflow, `subagent` is WHO. One of
136
- * the harvest's five slice dimensions (repo/workflow/step/subagent/severity).
137
136
  */
138
137
  subagent?: string;
139
138
  /**
140
139
  * The model that wrote the row, read from the writing subagent's OWN prompt
141
- * frontmatter `model:` at call time — the deterministic source bkit already
142
- * owns, and the only one that stays true when a prompt is re-pinned.
143
- *
144
- * Set ONLY on subagent-written rows, i.e. exactly when `subagent` is set. An
145
- * orchestrator-written row has no `model`: the session model is the operator's
146
- * runtime choice, not a property of the row, and self-reporting it invites the
147
- * same nondeterminism the compliance grader exists to avoid.
140
+ * frontmatter `model:` at call time. Set ONLY on subagent-written rows, i.e.
141
+ * exactly when `subagent` is set.
148
142
  */
149
143
  model?: string;
144
+ }
145
+
146
+ /** The bkit that wrote a row; `chat` rows add what the chat did with bkit. */
147
+ export interface BkitBlock {
148
+ /** bkit version stamped on every row for regression attribution; null on a chat / run row when unknown. */
149
+ version: string | null;
150
+ [field: string]: unknown;
151
+ }
152
+
153
+ export interface TelemetryEnvelope {
154
+ /** {@link SCHEMA} on write; a stored row may carry `2` ({@link StoredPlanBlock}). */
155
+ schema: typeof SCHEMA | typeof NORMALIZED_SCHEMA;
156
+ /** Primary id = unix milliseconds (portable: jq `now*1000|floor`). */
157
+ ts: number;
150
158
  /**
151
- * Free-form related context: any pointer that helps a reader place this row —
152
- * feature ids, tracker ids (`BAR-217`), PRs, commit SHAs, file paths, sibling
153
- * `ts`, a ledger id (`KN-14`, `DE-7`). Every entry is a pointer,
154
- * never an identity: `ts` (with `key` for instinct-loop kinds) identifies the row.
159
+ * {@link AGED_KINDS} only: `ts` of the entry's first row, so `ts - firstTs` is its age
160
+ * after compaction drops the rows before it. Set by the writer ({@link withLineage}), never authored.
155
161
  */
156
- references?: string[];
162
+ firstTs?: number;
163
+ /** {@link AGED_KINDS} only: rows the entry has had, this one included — its recurrence count. Set like `firstTs`. */
164
+ updates?: number;
165
+ /** Closed enum — validated on append; unknown kind rejected. */
166
+ kind: TelemetryKind;
157
167
  /**
158
- * Explicit written-once logical key for instinct-loop kinds
159
- * (friction / deferral / failure / knowledge / decision).
168
+ * Explicit written-once logical key for the keyed kinds
169
+ * (friction / deferral / failure / knowledge / decision / feature / chat / run).
160
170
  * Author writes a stable slug ONCE; recurrence = same-key append.
161
171
  * Absent on event kinds that key off composite tuples (compliance / counter / outcome).
162
172
  */
163
173
  key?: string;
174
+ /** Origin repo (slug, e.g. "cbartens/bkit"). */
175
+ repo: string;
176
+ bkit: BkitBlock;
177
+ by: RowBy;
178
+ /**
179
+ * Free-form related context: any pointer that helps a reader place this row —
180
+ * feature ids, tracker ids (`BAR-217`), PRs, commit SHAs, file paths, sibling
181
+ * `ts`, a ledger id (`KN-14`, `DE-7`). Every entry is a pointer,
182
+ * never an identity: `ts` (with `key` for keyed kinds) identifies the row.
183
+ */
184
+ references?: string[];
185
+ }
186
+
187
+ /** The identity block of every row that belongs to one workflow run. */
188
+ export interface RunRef {
189
+ /** HEAD at the run's close — the join key shared by its compliance / counter / outcome rows. */
190
+ parentSha?: string;
191
+ /** Ship-only: the merged PR number. */
192
+ pr?: number;
164
193
  }
165
194
 
166
195
  // ---------------------------------------------------------------------------
@@ -176,7 +205,9 @@ export type TelemetryKind =
176
205
  | "failure"
177
206
  | "knowledge"
178
207
  | "decision"
179
- | "feature";
208
+ | "feature"
209
+ | "chat"
210
+ | "run";
180
211
 
181
212
  export const VALID_KINDS: Set<string> = new Set([
182
213
  "compliance",
@@ -188,6 +219,8 @@ export const VALID_KINDS: Set<string> = new Set([
188
219
  "knowledge",
189
220
  "decision",
190
221
  "feature",
222
+ "chat",
223
+ "run",
191
224
  ]);
192
225
 
193
226
  /**
@@ -195,8 +228,8 @@ export const VALID_KINDS: Set<string> = new Set([
195
228
  * triaged by a human or a later agent (friction / deferral / failure).
196
229
  *
197
230
  * The SAME vocabulary the challenge prompts assign to their findings;
198
- * `@bkit-build-challenge-remediate` passes a blocked finding's severity straight
199
- * through to its deferral row. NOT the preflight `blocker`/`advisory` scale (that
231
+ * `bkit challenge merge` passes a LOW finding's severity straight through to its
232
+ * deferral row. NOT the preflight `blocker`/`advisory` scale (that
200
233
  * gates `bkit install`).
201
234
  *
202
235
  * Absent on machine-generated kinds (compliance / outcome / counter) and on
@@ -233,6 +266,18 @@ export const TRIAGE_STATUSES: Set<string> = new Set(["OPEN", "TRIAGED", "CLOSED"
233
266
  /** The `ACTIVE` / `SUPERSEDED` lifecycle shared by `decision` and `knowledge`. */
234
267
  export const DECISION_STATUSES: Set<string> = new Set(["ACTIVE", "SUPERSEDED"]);
235
268
 
269
+ /**
270
+ * The kinds whose rows carry `firstTs` + `updates` (`.bkit/jsonl.md` § Compaction):
271
+ * the keyed kinds of the ledgers `bkit ledgers compact` rewrites to their fold winners.
272
+ */
273
+ export const AGED_KINDS: Set<string> = new Set([
274
+ "deferral",
275
+ "failure",
276
+ "knowledge",
277
+ "decision",
278
+ "feature",
279
+ ]);
280
+
236
281
  /**
237
282
  * The `feature` kind's six-state phase ladder — the canonical status for
238
283
  * `.bkit/issues.jsonl`, appended once per phase close, same-`key`
@@ -268,19 +313,28 @@ export const FEATURE_STATUSES: Set<string> = new Set([
268
313
  * - `needs-decision` — a human decision is missing, and guessing it is worse than
269
314
  * waiting. Confirmation is unavailable inside `/bkit-*` workflows.
270
315
  * - `own-cycle` — genuinely plan-sized: a new architecture, not a mechanical fix.
316
+ * - `low-severity` — a `LOW` challenge finding, written by `bkit challenge merge`;
317
+ * that writer and that severity only.
271
318
  * - `unjustified` — ADJUDICATOR-ONLY (see UNJUSTIFIED_REASON).
272
319
  *
273
- * A writer who cannot pick one of the first four does not have a deferral; it has
274
- * unfinished work (`.agents/rules.md` § Principles, "Finish over deferrals").
320
+ * A writer who cannot pick one of the first four, or `low-severity` where it
321
+ * applies, does not have a deferral; it has unfinished work (`.agents/rules.md`
322
+ * § Principles, "Finish over deferrals").
275
323
  */
276
324
  export type DeferralReason =
277
- "scope-declared" | "hard-blocked" | "needs-decision" | "own-cycle" | "unjustified";
325
+ | "scope-declared"
326
+ | "hard-blocked"
327
+ | "needs-decision"
328
+ | "own-cycle"
329
+ | "low-severity"
330
+ | "unjustified";
278
331
 
279
332
  export const DEFERRAL_REASONS: Set<string> = new Set([
280
333
  "scope-declared",
281
334
  "hard-blocked",
282
335
  "needs-decision",
283
336
  "own-cycle",
337
+ "low-severity",
284
338
  "unjustified",
285
339
  ]);
286
340
 
@@ -300,7 +354,7 @@ export const UNJUSTIFIED_REASON = "unjustified";
300
354
  * § Ledgers & Writers). EXHAUSTIVE: a subagent absent from this set does not
301
355
  * write the kind at all.
302
356
  *
303
- * `@bkit-build-plan-execute` and `@bkit-build-plan-gaps-remediate` are not in it: a
357
+ * `@bkit-build-plan-tasks` and `@bkit-build-plan-gaps-remediate` are not in it: a
304
358
  * blocked plan task's record is its `BLOCKED` log line, which the next verify pass reads.
305
359
  *
306
360
  * Orchestrator-written rows carry no `subagent` and are outside this check.
@@ -309,19 +363,144 @@ export const DEFERRAL_WRITERS: Set<string> = new Set([
309
363
  "bkit-design-generate",
310
364
  "bkit-plan-generate",
311
365
  "bkit-plan-update",
312
- "bkit-build-challenge-remediate",
313
366
  "bkit-debug-abort-handover",
314
367
  "bkit-ship-deferred-sweep",
315
368
  "bkit-utility-update-deferrals",
316
369
  ]);
317
370
 
371
+ /** A writer list that admits every name (`.bkit/jsonl.md` § Ledgers & Writers: "any agent"). */
372
+ export const ANY_WRITER = "any";
373
+
374
+ export interface KindWriters {
375
+ /** Who may write the kind as a subagent, matched against the row's `subagent`. */
376
+ subagents: ReadonlySet<string> | typeof ANY_WRITER;
377
+ /** Which orchestrators may write it, matched against the `workflow` of a row with no `subagent`. */
378
+ orchestrators: ReadonlySet<string> | typeof ANY_WRITER;
379
+ }
380
+
381
+ /**
382
+ * The ledgers `bkit ledgers append` lands rows in, and the kinds each takes.
383
+ * `feature` rows go through `bkit roadmap feature` (it re-renders the board);
384
+ * `chat` / `run` rows are written by bkit's harvest script, to `harvest/stats.jsonl`.
385
+ */
386
+ export const APPEND_LEDGERS = {
387
+ decisions: { file: "docs/decisions.jsonl", kinds: ["decision"] },
388
+ deferrals: { file: "docs/deferrals.jsonl", kinds: ["deferral"] },
389
+ failures: { file: "docs/failures.jsonl", kinds: ["failure"] },
390
+ knowledge: { file: "docs/knowledge.jsonl", kinds: ["knowledge"] },
391
+ friction: { file: ".bkit/friction.jsonl", kinds: ["friction"] },
392
+ stats: { file: ".bkit/stats.jsonl", kinds: ["compliance", "counter", "outcome"] },
393
+ } as const;
394
+
395
+ export type AppendLedger = keyof typeof APPEND_LEDGERS;
396
+ export type AppendKind = (typeof APPEND_LEDGERS)[AppendLedger]["kinds"][number];
397
+
398
+ /** The workflows whose close writes `.bkit/stats.jsonl` rows (`bkit workflows close`, `bkit comply`). */
399
+ const CLOSING_WORKFLOWS = new Set(["design", "plan", "build", "debug", "ship"]);
400
+
401
+ /**
402
+ * The stats writers: the closing workflows, plus `utility`, a direct chat outside any
403
+ * workflow (`by.step` `manual`), the owner deciding in it.
404
+ */
405
+ const STATS_WRITERS = new Set([...CLOSING_WORKFLOWS, "utility"]);
406
+
407
+ /**
408
+ * `.bkit/jsonl.md` § Ledgers & Writers as code, for the kinds in
409
+ * {@link APPEND_LEDGERS}. EXHAUSTIVE: a name absent from a set does not write the
410
+ * kind. `telemetry.test.ts` holds this to the doc table.
411
+ */
412
+ export const KIND_WRITERS: Record<AppendKind, KindWriters> = {
413
+ decision: {
414
+ subagents: new Set([
415
+ "bkit-debug-failure-remediate",
416
+ "bkit-plan-generate",
417
+ "bkit-plan-update",
418
+ "bkit-utility-update-decisions",
419
+ ]),
420
+ // Build: Decision Pause accept; plan: an open question answered after close; design: an
421
+ // open question answered by the owner at close (the human decides, the orchestrator
422
+ // records); ship: an assumed accept the owner confirms (`bkit decisions apply --by=owner`);
423
+ // utility: a direct chat outside any workflow (`by.step` `manual`), the owner deciding in it.
424
+ // All ONLY after explicit human approval.
425
+ orchestrators: new Set(["design", "build", "plan", "ship", "utility"]),
426
+ },
427
+ // Build: `bkit challenge merge` writes each LOW challenge finding (`low-severity`). Ship:
428
+ // `bkit decisions pending --defer` writes each assumed accept nobody confirmed (`needs-decision`).
429
+ // Utility: a direct chat outside any workflow (`by.step` `manual`), the owner deciding in it.
430
+ deferral: { subagents: DEFERRAL_WRITERS, orchestrators: new Set(["build", "ship", "utility"]) },
431
+ failure: { subagents: ANY_WRITER, orchestrators: ANY_WRITER },
432
+ knowledge: {
433
+ subagents: new Set([
434
+ "bkit-build-plan-tests",
435
+ "bkit-build-plan-tasks",
436
+ "bkit-build-plan-gaps-remediate",
437
+ "bkit-debug-failure-remediate",
438
+ "bkit-utility-update-knowledge",
439
+ ]),
440
+ // Utility: a direct chat outside any workflow (`by.step` `manual`), the owner deciding in it.
441
+ orchestrators: new Set(["utility"]),
442
+ },
443
+ friction: {
444
+ subagents: new Set(),
445
+ // Utility: a direct chat outside any workflow (`by.step` `manual`) that meets friction.
446
+ orchestrators: new Set(["design", "plan", "build", "debug", "ship", "auto", "utility"]),
447
+ },
448
+ compliance: { subagents: new Set(), orchestrators: STATS_WRITERS },
449
+ counter: { subagents: new Set(), orchestrators: STATS_WRITERS },
450
+ outcome: { subagents: new Set(), orchestrators: STATS_WRITERS },
451
+ };
452
+
453
+ const writerList = (w: KindWriters["subagents"]): string =>
454
+ w === ANY_WRITER ? "any" : w.size === 0 ? "none" : [...w].join(", ");
455
+
456
+ /** A row's `by` block, or an empty one when it has none. */
457
+ const byOf = (row: Record<string, unknown>): Record<string, unknown> =>
458
+ row["by"] !== null && typeof row["by"] === "object" ? (row["by"] as Record<string, unknown>) : {};
459
+
460
+ /**
461
+ * Why `row` may not be written by its author, or undefined when it may. The author
462
+ * is `by.subagent` when set (with its `by.model`), else the orchestrator in
463
+ * `by.workflow` (`.bkit/jsonl.md` § Who Wrote It).
464
+ */
465
+ export function writerProblem(row: Record<string, unknown>): string | undefined {
466
+ const kind = row["kind"] as AppendKind;
467
+ const writers = KIND_WRITERS[kind];
468
+ if (writers === undefined) return `${String(kind)} rows have no append writers`;
469
+ const by = byOf(row);
470
+ const subagent = by["subagent"];
471
+ if (subagent !== undefined) {
472
+ if (typeof subagent !== "string" || subagent === "") {
473
+ return "by.subagent must be a non-empty string";
474
+ }
475
+ if (typeof by["model"] !== "string" || by["model"] === "") {
476
+ return `subagent ${subagent} row missing by.model (its prompt's frontmatter model:)`;
477
+ }
478
+ if (writers.subagents === ANY_WRITER || writers.subagents.has(subagent)) return undefined;
479
+ return `subagent ${subagent} does not write ${kind} rows (subagents: ${writerList(writers.subagents)})`;
480
+ }
481
+ if (by["model"] !== undefined) return "by.model is set only on subagent rows";
482
+ if (writers.orchestrators === ANY_WRITER) return undefined;
483
+ const workflow = by["workflow"];
484
+ if (typeof workflow === "string" && writers.orchestrators.has(workflow)) return undefined;
485
+ return `the ${typeof workflow === "string" ? workflow : "(no workflow)"} orchestrator does not write ${kind} rows (orchestrators: ${writerList(writers.orchestrators)})`;
486
+ }
487
+
488
+ /**
489
+ * A `ts` minted now: `Date.now()`, or `after + 1` when the clock has not passed
490
+ * `after`, moved 1 ms off a whole second. The live-ledger gate fails whole-second
491
+ * values as hand-typed (`audits/repo/ledger-integrity.test.ts`), and a real mint
492
+ * must never trip it.
493
+ */
494
+ export function mintTs(after?: number): number {
495
+ let ts = Date.now();
496
+ if (after !== undefined && ts <= after) ts = after + 1;
497
+ return ts % 1000 === 0 ? ts + 1 : ts;
498
+ }
499
+
318
500
  // compliance — one row per run x rule (kind:"compliance")
319
501
  export interface CompliancePayload {
320
- rule: string;
321
- result: "pass" | "fail" | "n/a";
322
- evidence?: string;
323
- phase: string;
324
- parentSha: string;
502
+ run: { parentSha: string };
503
+ rule: { id: string; verdict: "pass" | "fail" | "n/a"; evidence?: string };
325
504
  }
326
505
 
327
506
  /** Code-coverage percentages (0-100), from a coverage-summary.json `total`. */
@@ -332,94 +511,154 @@ export interface CoverageStats {
332
511
  statements?: number;
333
512
  }
334
513
 
335
- // outcome — one row per WORKFLOW RUN, keyed by (repo, workflow, parentSha).
336
- // Every workflow writes one run row at its close, carrying just the fields that apply to it
337
- // (absent fields are simply omitted — the summary shows a metric only when present).
338
- // `prNumber` is ship-only; the per-run instinct-loop deltas (frictionAdded /
339
- // deferralsAdded / failuresAdded) are what `workflowTelemetry` features.
514
+ /** `start` / `end` unix ms; `totalMinutes` = end - start. `chat` and `run` rows add active time. */
515
+ export interface TimeBlock {
516
+ start: number;
517
+ end: number;
518
+ totalMinutes: number;
519
+ activeMinutes?: number | null;
520
+ lastActivity?: number;
521
+ [field: string]: unknown;
522
+ }
523
+
524
+ export interface LineCounts {
525
+ added: number;
526
+ deleted: number;
527
+ files: number;
528
+ }
529
+
530
+ /** Lines a run changed, split by what the file is; `total` = the sum of the three parts. */
531
+ export interface LinesBlock {
532
+ total: LineCounts & { changed: number };
533
+ code: LineCounts;
534
+ tests: LineCounts;
535
+ docs: LineCounts;
536
+ /** Merges (dev syncs) the count was cut at, so merged-in work is not counted. */
537
+ merges: number;
538
+ }
539
+
540
+ export interface StepTime {
541
+ n: number;
542
+ totalMinutes: number;
543
+ activeMinutes?: number | null;
544
+ }
545
+
546
+ /** Step-done rows per step; `total` = the sum of `byStep`. */
547
+ export interface StepsBlock {
548
+ total: StepTime;
549
+ byStep: Record<string, StepTime>;
550
+ }
551
+
552
+ /** One close-step CI dispatch. */
553
+ export interface CiDispatch {
554
+ status: string | null;
555
+ reason: string | null;
556
+ attempts: number | null;
557
+ }
558
+
559
+ /** One planned task: its `Test first` tests and distinct test files; `null` = the task has no `Test first` field. */
560
+ export interface PlanTask {
561
+ tests: number | null;
562
+ testFiles: number | null;
563
+ }
564
+
565
+ /** The plan a run worked from; `total.tasks` = the sum over `groups`. */
566
+ export interface PlanBlock {
567
+ /** `converted` = the build rewrote its input into the plan file. */
568
+ source: "file" | "converted";
569
+ total: { tasks: number; kb: number };
570
+ groups: Array<{ tasks: PlanTask[] }>;
571
+ }
572
+
573
+ /**
574
+ * A schema-1 or schema-2 row's plan block, read as stored: `brief` = no plan file
575
+ * (only this field); tasks per sub-plan; the complexity check's verdict.
576
+ */
577
+ export interface StoredPlanBlock {
578
+ source: "file" | "brief";
579
+ total?: { tasks: number; kb: number };
580
+ subPlans?: Array<{ kb: number; tasks: PlanTask[] }>;
581
+ complexity?: { verdict: string | null; tasksChecked: number | null; reasons: string[] };
582
+ }
583
+
584
+ export interface BuildBlock {
585
+ verify?: Array<Record<string, unknown>>;
586
+ gapsRemediate?: Array<Record<string, unknown>>;
587
+ holistic?: { verdict: string | null; failures: number | null } | null;
588
+ challenge?: {
589
+ verdict: string | null;
590
+ findings: { total: number; CRITICAL: number; HIGH: number; MEDIUM: number; LOW: number } | null;
591
+ /** The latest `bkit challenge gate` size: small skips challenge-1. Absent before the gate existed. */
592
+ gate?: {
593
+ size: string | null;
594
+ linesChanged: number | null;
595
+ filesChanged: number | null;
596
+ skipped: boolean;
597
+ };
598
+ } | null;
599
+ redTests?: number;
600
+ }
601
+
602
+ /**
603
+ * The context one subagent may fill before it hands over (the plan template's "about 160k
604
+ * tokens" per build group). Rows store peaks only; readers judge them against this.
605
+ */
606
+ export const AGENT_CONTEXT_CAP = 160_000;
607
+
608
+ /**
609
+ * The run's subagents, per agent type: `runs` = subagents of that type with a model call in
610
+ * the run, `peak` = the largest context (input + cache write + cache read tokens of one model
611
+ * call) any of them reached in it. `host` = where the counts came from.
612
+ */
613
+ export interface ContextBlock {
614
+ host: "claude-code";
615
+ byAgent: Record<string, { peak: number; runs: number }>;
616
+ }
617
+
618
+ export const OUTCOME_ENDINGS: Set<string> = new Set(["done", "close-failed", "held"]);
619
+
620
+ // outcome — one row per WORKFLOW RUN, keyed by (repo, by.workflow, run.parentSha), written
621
+ // by `bkit workflows close`. Blocks that do not apply to the workflow are absent.
340
622
  export interface OutcomePayload {
623
+ run: RunRef;
624
+ /** null when the run's start row is missing. */
625
+ time: TimeBlock | null;
341
626
  /**
342
- * Parent commit SHA of the run — the run's identity anchor (shared with the
343
- * `compliance` / `counter` rows written in the same close). Optional: ship rows
344
- * written without it are keyed by `prNumber`.
345
- */
346
- parentSha?: string;
347
- /** Ship-only: the merged PR number. Absent on design/plan/build/debug runs. */
348
- prNumber?: number;
349
- /** Lines added (git diff --stat). */
350
- linesAdded: number;
351
- /** Lines deleted (git diff --stat). */
352
- linesDeleted: number;
353
- /** linesAdded + linesDeleted. */
354
- linesChanged: number;
355
- /** Files changed (git diff --stat). */
356
- filesChanged: number;
357
- /** Count of tasks in the sub-plan(s). */
358
- taskCount: number;
359
- /** Total workflow duration in seconds. */
360
- durationSeconds: number;
361
- /**
362
- * Which CI attempt passed (e.g. 2 = failed once then passed on retry).
363
- * undefined = not yet backfilled by P4 analysis.
364
- */
365
- ciTrySuccess?: number;
366
- /** Number of corrective commits post-PR-open. */
367
- correctiveCommits?: number;
368
- /** Number of PR review iterations. */
369
- reviewIterations?: number;
370
- /**
371
- * The repo's CUMULATIVE count of distinct deferrals at ship time — folded
372
- * entities, not lines. Per-cycle is the DELTA against the previous outcome
373
- * row (see newFailuresThisRun / isErrorRun in commands/analysis.ts).
374
- */
375
- deferrals: number;
376
- /**
377
- * The repo's CUMULATIVE count of distinct failures at ship time — folded
378
- * entities, not lines. Per-cycle is the DELTA against the previous outcome row.
379
- *
380
- * A total, NOT this run's discoveries. Readers MUST diff consecutive rows rather
381
- * than test this absolutely.
382
- */
383
- failures: number;
384
- /**
385
- * Per-run instinct-loop DELTAS — how many rows THIS run added to each ledger,
386
- * counted at close from rows with `workflow == <this workflow>` and
387
- * `ts >= workflow-started`. Distinct from the cumulative `deferrals`/`failures`
388
- * above: those are repo totals, these are what this one run contributed.
389
- * `frictionAdded` is the featured per-workflow signal (see `workflowTelemetry`);
390
- * all three are optional so a workflow that cannot produce one simply omits it.
391
- */
392
- frictionAdded?: number;
393
- deferralsAdded?: number;
394
- failuresAdded?: number;
395
- /**
396
- * `"brief"` = the run had no `{FID}-plan*.md` and worked from its input file
397
- * (build / ship `workflow-meta` row). Absent = the run had a plan. Brief runs
398
- * report `taskCount` 0 and are baselined only against other brief runs.
627
+ * `close-failed` = the work finished and the close after it did not (its CI never started);
628
+ * `held` = a local build that published nothing.
399
629
  */
400
- planSource?: "brief";
630
+ ending: "done" | "close-failed" | "held";
631
+ /** A build's resolved publish value; `false` with `held`. */
632
+ publish?: boolean;
633
+ lines?: LinesBlock | null;
634
+ steps?: StepsBlock;
635
+ ci?: CiDispatch[];
401
636
  /**
402
- * Per-tier code-coverage % — each tier's coverage-summary.json `total.*.pct`.
403
- * Best-effort: a tier is absent when its coverage report is not produced
404
- * (coverage is opt-in per tier). Additive-optional —
405
- * no version bump; readers ingest rows with or without it.
637
+ * `repo` = the repo's count of distinct entries at close (folded entities, not lines);
638
+ * `added` = distinct keys THIS run added (rows of this workflow at or after its start),
639
+ * absent when the run's start is unknown.
406
640
  */
407
- coverage?: {
408
- unit?: CoverageStats;
409
- integration?: CoverageStats;
410
- e2e?: CoverageStats;
641
+ ledgers: {
642
+ deferrals: { repo: number; added?: number };
643
+ failures: { repo: number; added?: number };
644
+ friction: { added?: number };
411
645
  };
646
+ plan?: PlanBlock | StoredPlanBlock;
647
+ build?: BuildBlock;
648
+ /** Absent when the host keeps no transcript bkit can tie to the run. */
649
+ context?: ContextBlock;
650
+ ship?: { coverage?: { unit?: CoverageStats; integration?: CoverageStats; e2e?: CoverageStats } };
412
651
  }
413
652
 
414
- // counter — attempt/failure counts, keyed by (repo, workflow, parentSha, counterName)
653
+ // counter — attempt/failure counts, keyed by (repo, by.workflow, run.parentSha, counter.name)
415
654
  export interface CounterPayload {
416
- counterName: string;
417
- counterValue: number;
418
- parentSha: string;
419
- /**
420
- * Trust-tier field: model-self-report (pre-P3) vs shell-bus (post-P3 deterministic).
421
- */
422
- counterSource: "model-self-report" | "shell-bus";
655
+ run: { parentSha: string };
656
+ counter: {
657
+ name: string;
658
+ value: number;
659
+ /** Trust tier: model-self-report vs shell-bus (deterministic). */
660
+ source: "model-self-report" | "shell-bus";
661
+ };
423
662
  }
424
663
 
425
664
  // friction — keyed by explicit `key` field
@@ -480,7 +719,7 @@ export interface FailurePayload {
480
719
  /**
481
720
  * Free-form domain tag (mirrors DeferralPayload.category; see § Categories in
482
721
  * .bkit/jsonl.md). `"testing"` marks a flaky / intermittent test — recurrence
483
- * via same-`key` append is the flake signal; no extra fields. See § Categories.
722
+ * via same-`key` append is the flake signal, counted by `updates`. See § Categories.
484
723
  */
485
724
  category?: string;
486
725
  summary?: string;
@@ -542,6 +781,49 @@ export interface FeaturePayload {
542
781
  shippedAt?: number;
543
782
  }
544
783
 
784
+ // chat — one agent chat on any host (a session plus its subagents), written by
785
+ // `scripts/harvest/bkit-harvest.mjs`; keyed by explicit `key` (`<platform>:<sessionId>`).
786
+ // A resumed chat is a same-`key` append; last row wins. The script is the writer and the
787
+ // field reference (its header); the codec checks the join fields and every total.
788
+ export interface ChatPayload {
789
+ key: string;
790
+ session: { platform: string; id: string; [field: string]: unknown };
791
+ time: TimeBlock & { spans?: number[][] };
792
+ issue: { id: string | null; all: string[]; mentioned: string[]; source?: string | null };
793
+ /** `parentSha` values `bkit workflows close` printed in the chat — exact join to the run's rows. */
794
+ run: { parentShas: string[] };
795
+ scan: { files: number; bytes: number; settled: boolean; tokensRecorded?: boolean };
796
+ [field: string]: unknown;
797
+ }
798
+
799
+ // run — one workflow run, read from its run log (`docs/plans/<YYYYMM>/logs/<FID>/status.jsonl`)
800
+ // by `scripts/harvest/bkit-harvest.mjs`; keyed by explicit `key` (`<fid fp>:<workflow>:<start>`).
801
+ // A run whose log grew is a same-`key` append; last row wins.
802
+ export interface RunPayload {
803
+ key: string;
804
+ run: {
805
+ fid: string;
806
+ issue: string | null;
807
+ n: number;
808
+ /** The close step's `parentSha` — exact join to the run's outcome / counter / compliance rows. */
809
+ parentSha: string | null;
810
+ parentShas: string[];
811
+ };
812
+ time: TimeBlock;
813
+ ending: "done" | "close-failed" | "failed" | "decision-pause" | "stopped" | "held";
814
+ scan: { rows: number; afterEnd: number; settled: boolean };
815
+ [field: string]: unknown;
816
+ }
817
+
818
+ export const RUN_ENDINGS: Set<string> = new Set([
819
+ "done",
820
+ "close-failed",
821
+ "failed",
822
+ "decision-pause",
823
+ "stopped",
824
+ "held",
825
+ ]);
826
+
545
827
  // ---------------------------------------------------------------------------
546
828
  // Discriminated union event type
547
829
  // ---------------------------------------------------------------------------
@@ -557,6 +839,8 @@ export type TelemetryEvent = TelemetryEnvelope &
557
839
  | ({ kind: "knowledge" } & KnowledgePayload)
558
840
  | ({ kind: "decision" } & DecisionPayload)
559
841
  | ({ kind: "feature" } & FeaturePayload)
842
+ | ({ kind: "chat" } & ChatPayload)
843
+ | ({ kind: "run" } & RunPayload)
560
844
  );
561
845
 
562
846
  // ---------------------------------------------------------------------------
@@ -565,30 +849,662 @@ export type TelemetryEvent = TelemetryEnvelope &
565
849
  // ---------------------------------------------------------------------------
566
850
 
567
851
  export function identity(event: TelemetryEvent): string {
852
+ const workflow = event.by?.workflow;
568
853
  switch (event.kind) {
569
854
  case "compliance":
570
- return `compliance ${event.repo} ${event.workflow} ${event.parentSha} ${event.rule}`;
855
+ return `compliance ${event.repo} ${workflow} ${event.run?.parentSha} ${event.rule?.id}`;
571
856
  case "outcome": {
572
- // One run row per workflow run: keyed by (repo, workflow, parentSha).
573
- // A ship row with no parentSha falls back to prNumber (then ts), so it stays
857
+ // One run row per workflow run: keyed by (repo, workflow, run.parentSha).
858
+ // A ship row with no parentSha falls back to run.pr (then ts), so it stays
574
859
  // uniquely keyed per PR.
575
860
  const anchor =
576
- event.parentSha ?? (event.prNumber !== undefined ? `pr${event.prNumber}` : `ts${event.ts}`);
577
- return `outcome ${event.repo} ${event.workflow} ${anchor}`;
861
+ event.run?.parentSha ??
862
+ (event.run?.pr !== undefined ? `pr${event.run.pr}` : `ts${event.ts}`);
863
+ return `outcome ${event.repo} ${workflow} ${anchor}`;
578
864
  }
579
865
  case "counter":
580
- return `counter ${event.repo} ${event.workflow} ${event.parentSha} ${event.counterName}`;
866
+ return `counter ${event.repo} ${workflow} ${event.run?.parentSha} ${event.counter?.name}`;
581
867
  case "friction":
582
868
  case "deferral":
583
869
  case "failure":
584
870
  case "knowledge":
585
871
  case "decision":
586
872
  case "feature":
587
- // instinct-loop kinds (+ feature): identity = kind + key
873
+ case "chat":
874
+ case "run":
875
+ // keyed kinds: identity = kind + key
588
876
  return `${event.kind} ${event.repo} ${event.key ?? event.ts}`;
589
877
  }
590
878
  }
591
879
 
880
+ // ---------------------------------------------------------------------------
881
+ // Normalize — read a row written without `schema` in the schema-2 shape
882
+ // ---------------------------------------------------------------------------
883
+
884
+ type Obj = Record<string, unknown>;
885
+ const isObj = (v: unknown): v is Obj => v !== null && typeof v === "object" && !Array.isArray(v);
886
+ /** `o` without its undefined fields, so an absent value stays absent. */
887
+ const defined = (o: Obj): Obj =>
888
+ Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
889
+ const tenthOf = (n: number): number => Math.round(n * 10) / 10;
890
+
891
+ /** Fields of a row written without `schema` that the current shape moves or drops, per kind. */
892
+ const MOVED: Record<string, readonly string[]> = {
893
+ compliance: ["rule", "result", "evidence", "phase"],
894
+ counter: ["counterName", "counterValue", "counterSource", "phase"],
895
+ outcome: [
896
+ "phase",
897
+ "prNumber",
898
+ "linesAdded",
899
+ "linesDeleted",
900
+ "linesChanged",
901
+ "filesChanged",
902
+ "taskCount",
903
+ "durationSeconds",
904
+ "ciTrySuccess",
905
+ "correctiveCommits",
906
+ "reviewIterations",
907
+ "deferrals",
908
+ "failures",
909
+ "frictionAdded",
910
+ "deferralsAdded",
911
+ "failuresAdded",
912
+ "planSource",
913
+ "coverage",
914
+ "redTests",
915
+ ],
916
+ };
917
+ const TOP_MOVED = ["schema", "bkitVersion", "workflow", "step", "subagent", "model", "parentSha"];
918
+
919
+ /**
920
+ * A row in a `schema` shape. A row that carries `schema` is returned as it is; a
921
+ * row written without one is stamped `schema: 2` and has its top section (`bkitVersion` -> `bkit.version`,
922
+ * `workflow` / `step` / `subagent` / `model` -> `by.*`) and the stats kinds' run
923
+ * fields moved into their blocks as far as the row holds them. Fields with no
924
+ * place in the schema-2 shape are dropped, and any kind's `parentSha` moves to
925
+ * `run.parentSha`. `bkit install` / `bkit upgrade` rewrite old rows through it
926
+ * (`./migrate.ts`); readers still call it, as a union merge can bring an old line back.
927
+ */
928
+ export function normalize(raw: unknown): Obj {
929
+ if (!isObj(raw)) return {};
930
+ if (raw["schema"] !== undefined) return raw;
931
+ const kind = String(raw["kind"]);
932
+ const moved = new Set([...TOP_MOVED, ...(MOVED[kind] ?? [])]);
933
+ const rest = Object.fromEntries(Object.entries(raw).filter(([k]) => !moved.has(k)));
934
+ const { ts, kind: _kind, key, repo, references, ...payload } = rest;
935
+ const out: Obj = defined({
936
+ schema: NORMALIZED_SCHEMA,
937
+ ts,
938
+ kind: raw["kind"],
939
+ key,
940
+ repo,
941
+ // "none": the harvest script found no bkit version for the row.
942
+ bkit: {
943
+ version:
944
+ raw["bkitVersion"] === undefined || raw["bkitVersion"] === "none"
945
+ ? null
946
+ : raw["bkitVersion"],
947
+ },
948
+ // An old row's null or empty `workflow` / `subagent` / `model` meant "none": left out.
949
+ by: Object.fromEntries(
950
+ ["workflow", "step", "subagent", "model"]
951
+ .map((f) => [f, raw[f]] as const)
952
+ .filter(([, v]) => v !== undefined && v !== null && v !== ""),
953
+ ),
954
+ references,
955
+ });
956
+ const num = (f: string): number | undefined =>
957
+ typeof raw[f] === "number" ? (raw[f] as number) : undefined;
958
+ switch (kind) {
959
+ case "compliance":
960
+ out["run"] = { parentSha: raw["parentSha"] };
961
+ out["rule"] = defined({ id: raw["rule"], verdict: raw["result"], evidence: raw["evidence"] });
962
+ break;
963
+ case "counter":
964
+ out["run"] = { parentSha: raw["parentSha"] };
965
+ out["counter"] = {
966
+ name: raw["counterName"],
967
+ value: raw["counterValue"],
968
+ source: raw["counterSource"],
969
+ };
970
+ break;
971
+ case "outcome": {
972
+ out["run"] = defined({ parentSha: raw["parentSha"], pr: raw["prNumber"] });
973
+ const seconds = num("durationSeconds");
974
+ if (seconds !== undefined) out["time"] = { totalMinutes: tenthOf(seconds / 60) };
975
+ const added = num("linesAdded");
976
+ const deleted = num("linesDeleted");
977
+ if (added !== undefined && deleted !== undefined) {
978
+ out["lines"] = {
979
+ total: { added, deleted, changed: added + deleted, files: num("filesChanged") ?? 0 },
980
+ };
981
+ }
982
+ out["ledgers"] = {
983
+ deferrals: defined({ repo: num("deferrals"), added: num("deferralsAdded") }),
984
+ failures: defined({ repo: num("failures"), added: num("failuresAdded") }),
985
+ friction: defined({ added: num("frictionAdded") }),
986
+ };
987
+ if (raw["planSource"] === "brief") out["plan"] = { source: "brief" };
988
+ if (isObj(raw["coverage"])) out["ship"] = { coverage: raw["coverage"] };
989
+ if (num("redTests") !== undefined) out["build"] = { redTests: num("redTests") };
990
+ break;
991
+ }
992
+ case "chat":
993
+ return { ...out, ...oldChat(raw) };
994
+ case "run":
995
+ return {
996
+ ...out,
997
+ by: defined({ workflow: raw["workflow"], step: raw["step"] ?? "scan" }),
998
+ ...oldRun(raw),
999
+ };
1000
+ }
1001
+ const run =
1002
+ out["run"] ?? (raw["parentSha"] !== undefined ? { parentSha: raw["parentSha"] } : undefined);
1003
+ return { ...out, ...payload, ...defined({ run }) };
1004
+ }
1005
+
1006
+ // The harvest script's own kinds, mapped in full: every schema-1 field has a
1007
+ // place in the current shape or is dropped. `scripts/harvest/bkit-harvest.mjs`
1008
+ // `normalize` maps them the same way.
1009
+
1010
+ const objOf = (v: unknown): Obj => (isObj(v) ? v : {});
1011
+ const numOr = (v: unknown, or: number | null = 0): number | null =>
1012
+ typeof v === "number" ? v : or;
1013
+ const arrOf = (v: unknown): unknown[] => (Array.isArray(v) ? v : []);
1014
+ const TOKENS = ["input", "cacheWrite", "cacheRead", "output", "outputEst", "read"] as const;
1015
+ const oldTokens = (t: unknown) => Object.fromEntries(TOKENS.map((k) => [k, numOr(objOf(t)[k])]));
1016
+ const oldMix = (m: unknown): Obj | undefined => {
1017
+ if (!isObj(m)) return undefined;
1018
+ return {
1019
+ read: numOr(m["read"]),
1020
+ edit: numOr(m["edit"]),
1021
+ grep: numOr(m["grep"]),
1022
+ shellRead: numOr(m["sedCat"]),
1023
+ shellList: numOr(m["findLs"]),
1024
+ tests: numOr(m["tests"]),
1025
+ serena: numOr(m["serena"]),
1026
+ };
1027
+ };
1028
+ const sumNums = (xs: unknown[]) =>
1029
+ xs.reduce<number>((a, x) => a + (typeof x === "number" ? x : 0), 0);
1030
+ /** Shell tools by host: the tool a schema-1 chat row's per-chat shell categories move under. */
1031
+ const OLD_SHELL_TOOLS = [
1032
+ "Bash",
1033
+ "bash",
1034
+ "Shell",
1035
+ "shell",
1036
+ "shell_command",
1037
+ "local_shell",
1038
+ "exec_command",
1039
+ "run_command",
1040
+ "run_terminal_cmd",
1041
+ ];
1042
+
1043
+ function oldChat(r: Obj): Obj {
1044
+ const byAgent: Obj = {};
1045
+ for (const [type, av] of Object.entries(objOf(r["agents"]))) {
1046
+ const a = objOf(av);
1047
+ const peaks = arrOf(a["ctxPeaks"]).filter((p): p is number => typeof p === "number");
1048
+ const n = numOr(a["n"], peaks.length) as number;
1049
+ byAgent[type] = defined({
1050
+ n,
1051
+ errors: numOr(a["errors"]),
1052
+ // Per-instance turns were stored only as a sum: known when the type ran once.
1053
+ instances: peaks.map((p) => ({
1054
+ turns: n === 1 ? numOr(a["turns"], null) : null,
1055
+ contextPeak: p,
1056
+ })),
1057
+ usage: {
1058
+ turns: numOr(a["turns"]),
1059
+ tokens: oldTokens(a),
1060
+ context: { peak: numOr(a["ctxPeakMax"], Math.max(0, ...peaks)) },
1061
+ compactions: numOr(a["compactions"]),
1062
+ },
1063
+ mix: oldMix(a["mix"]),
1064
+ });
1065
+ }
1066
+ const byTool: Record<string, Obj> = {};
1067
+ for (const [k, tv] of Object.entries(objOf(r["tools"]))) {
1068
+ const t = objOf(tv);
1069
+ byTool[k] = { calls: numOr(t["calls"]), errors: numOr(t["errors"]) };
1070
+ }
1071
+ const shellTool = OLD_SHELL_TOOLS.find((k) => byTool[k] !== undefined);
1072
+ const bash = objOf(r["bash"]);
1073
+ if (shellTool !== undefined && Object.keys(bash).length > 0)
1074
+ byTool[shellTool]!["byCategory"] = { ...bash };
1075
+ const byModel = Object.fromEntries(
1076
+ Object.entries(objOf(r["models"])).map(([k, m]) => [
1077
+ k,
1078
+ { turns: numOr(objOf(m)["turns"]), tokens: oldTokens(m) },
1079
+ ]),
1080
+ );
1081
+ const m = objOf(r["main"]);
1082
+ const tokens = objOf(r["tokens"]);
1083
+ const byVerb = objOf(r["bkitCli"]);
1084
+ const agents = Object.values(byAgent).map(objOf);
1085
+ const tools = Object.values(byTool);
1086
+ const start = r["start"];
1087
+ const end = r["end"];
1088
+ return {
1089
+ by: defined({ workflow: r["workflow"] ?? "chat-stats", step: r["step"] ?? "scan" }),
1090
+ bkit: {
1091
+ version:
1092
+ r["bkitVersion"] === undefined || r["bkitVersion"] === "none" ? null : r["bkitVersion"],
1093
+ versionSource: r["bkitVersionSource"] ?? "none",
1094
+ via: arrOf(r["bkitVia"]),
1095
+ workflows: arrOf(r["bkitWorkflows"]),
1096
+ prompts: arrOf(r["bkitKinds"]),
1097
+ cli: { total: sumNums(Object.values(byVerb)), byVerb },
1098
+ },
1099
+ session: {
1100
+ platform: r["platform"] ?? "claude-code",
1101
+ id: r["sessionId"] ?? null,
1102
+ hostVersion: r["hostVersion"] ?? null,
1103
+ entrypoint: r["entrypoint"] ?? null,
1104
+ prompts: numOr(r["userPrompts"]),
1105
+ },
1106
+ time: defined({
1107
+ start: start ?? null,
1108
+ end: end ?? null,
1109
+ totalMinutes:
1110
+ typeof r["minutes"] === "number"
1111
+ ? r["minutes"]
1112
+ : typeof start === "number" && typeof end === "number"
1113
+ ? tenthOf((end - start) / 60000)
1114
+ : null,
1115
+ activeMinutes: numOr(r["activeMinutes"], null),
1116
+ spans: arrOf(r["active"]),
1117
+ lastActivity: r["lastActivityAt"],
1118
+ }),
1119
+ issue: {
1120
+ id: r["issue"] ?? null,
1121
+ all: arrOf(r["issues"]),
1122
+ mentioned: arrOf(r["mentioned"]),
1123
+ source: r["issueSource"] ?? "none",
1124
+ },
1125
+ run: { parentShas: arrOf(r["parentShas"]) },
1126
+ effort: objOf(r["effort"]),
1127
+ usage: {
1128
+ total: {
1129
+ turns: numOr(r["turns"]),
1130
+ // Summed from the models, as a fresh scan writes it: the old row's own total
1131
+ // estimated output once over the whole chat, so it can differ from its parts.
1132
+ tokens:
1133
+ Object.keys(byModel).length > 0
1134
+ ? Object.fromEntries(
1135
+ TOKENS.map((k) => [k, sumNums(Object.values(byModel).map((x) => x.tokens[k]))]),
1136
+ )
1137
+ : oldTokens(tokens),
1138
+ context: { start: numOr(tokens["ctxStart"]), peak: numOr(tokens["ctxPeak"]) },
1139
+ compactions: numOr(r["compactions"]),
1140
+ },
1141
+ main: defined({
1142
+ turns: numOr(m["turns"]),
1143
+ tokens: oldTokens(m),
1144
+ context: { peak: numOr(m["ctxPeak"]) },
1145
+ compactions: numOr(m["compactions"]),
1146
+ mix: oldMix(m["mix"]),
1147
+ }),
1148
+ byModel,
1149
+ },
1150
+ agents: {
1151
+ total: {
1152
+ n: numOr(r["subagents"], sumNums(agents.map((a) => a["n"]))),
1153
+ errors: sumNums(agents.map((a) => a["errors"])),
1154
+ },
1155
+ byAgent,
1156
+ },
1157
+ tools: {
1158
+ total: {
1159
+ calls: sumNums(tools.map((t) => t["calls"])),
1160
+ errors: sumNums(tools.map((t) => t["errors"])),
1161
+ },
1162
+ byTool,
1163
+ filesRead: numOr(r["filesRead"]),
1164
+ },
1165
+ scan: defined({
1166
+ files: r["sourceFiles"],
1167
+ bytes: r["sourceBytes"],
1168
+ settled: r["settled"],
1169
+ tokensRecorded: r["tokensRecorded"],
1170
+ }),
1171
+ };
1172
+ }
1173
+
1174
+ /** A schema-1 run row's plan: its per-task lists, grouped when unsplit. */
1175
+ function oldPlan(p: Obj): Obj {
1176
+ const n = numOr(p["subPlans"], 1) as number;
1177
+ const tests = arrOf(p["testsPerTask"]);
1178
+ const files = arrOf(p["testFilesPerTask"]);
1179
+ const tasks = numOr(p["tasks"], tests.length) as number;
1180
+ const kb = numOr(p["kb"]);
1181
+ const out: Obj = { source: "file", total: { tasks, kb } };
1182
+ out["subPlans"] =
1183
+ n === 1
1184
+ ? [
1185
+ {
1186
+ kb,
1187
+ tasks: Array.from({ length: tasks }, (_, i) => ({
1188
+ tests: numOr(tests[i], null),
1189
+ testFiles: numOr(files[i], null),
1190
+ })),
1191
+ },
1192
+ ]
1193
+ : // A split plan's per-task lists were stored flat: which sub-plan each task was in is not known.
1194
+ Array.from({ length: n }, () => ({ kb: null, tasks: null }));
1195
+ if (isObj(p["complexity"])) out["complexity"] = p["complexity"];
1196
+ return out;
1197
+ }
1198
+
1199
+ function oldRun(r: Obj): Obj {
1200
+ const steps = Object.entries(objOf(r["steps"])).map(([k, v]) => [k, objOf(v)] as const);
1201
+ const byStep = Object.fromEntries(
1202
+ steps.map(([k, st]) => [
1203
+ k,
1204
+ {
1205
+ n: numOr(st["n"]),
1206
+ totalMinutes: numOr(st["minutes"]),
1207
+ activeMinutes: numOr(st["active"], null),
1208
+ },
1209
+ ]),
1210
+ );
1211
+ const parts = steps.map(([, st]) => st);
1212
+ const isBuild =
1213
+ r["workflow"] === "build" ||
1214
+ ["verify", "gapsRemediate", "holistic", "challenge", "redTests"].some((k) => k in r);
1215
+ const ch = isObj(r["challenge"]) ? r["challenge"] : undefined;
1216
+ const f = isObj(ch?.["findings"]) ? (ch!["findings"] as Obj) : undefined;
1217
+ const lines = objOf(r["lines"]);
1218
+ const lineParts = ["code", "tests", "docs"].map((k) => objOf(lines[k]));
1219
+ const linesOut =
1220
+ isObj(r["lines"]) && isObj(lines["code"])
1221
+ ? (() => {
1222
+ const added = sumNums(lineParts.map((p) => p["added"]));
1223
+ const deleted = sumNums(lineParts.map((p) => p["deleted"]));
1224
+ return {
1225
+ total: {
1226
+ added,
1227
+ deleted,
1228
+ changed: added + deleted,
1229
+ files: sumNums(lineParts.map((p) => p["files"])),
1230
+ },
1231
+ code: lines["code"],
1232
+ tests: lines["tests"],
1233
+ docs: lines["docs"],
1234
+ merges: lines["merges"],
1235
+ };
1236
+ })()
1237
+ : r["lines"];
1238
+ return defined({
1239
+ run: {
1240
+ fid: r["fid"] ?? null,
1241
+ issue: r["issue"] ?? null,
1242
+ n: numOr(r["run"], null),
1243
+ parentSha: r["parentSha"] ?? null,
1244
+ parentShas: arrOf(r["parentShas"]),
1245
+ },
1246
+ time: defined({
1247
+ start: r["start"] ?? null,
1248
+ end: r["end"] ?? null,
1249
+ totalMinutes: numOr(r["minutes"], null),
1250
+ activeMinutes: numOr(r["activeMinutes"], null),
1251
+ activeFrom: r["activeFrom"] ?? null,
1252
+ lastActivity: r["lastActivityAt"],
1253
+ }),
1254
+ ending: r["ending"],
1255
+ ci: arrOf(r["closeCi"]).map((cv) => {
1256
+ const c = objOf(cv);
1257
+ return defined({
1258
+ status: c["outcome"] ?? null,
1259
+ reason: c["reason"] ?? undefined,
1260
+ attempts: numOr(c["attempts"], null),
1261
+ });
1262
+ }),
1263
+ steps: {
1264
+ total: {
1265
+ n: sumNums(parts.map((st) => st["n"])),
1266
+ totalMinutes: tenthOf(sumNums(parts.map((st) => st["minutes"]))),
1267
+ activeMinutes: parts.some((st) => typeof st["active"] !== "number")
1268
+ ? null
1269
+ : tenthOf(sumNums(parts.map((st) => st["active"]))),
1270
+ },
1271
+ byStep,
1272
+ },
1273
+ lines: linesOut,
1274
+ plan: isObj(r["plan"]) ? oldPlan(r["plan"]) : r["plan"],
1275
+ build: isBuild
1276
+ ? defined({
1277
+ verify: arrOf(r["verify"]),
1278
+ gapsRemediate: arrOf(r["gapsRemediate"]),
1279
+ holistic: r["holistic"] ?? undefined,
1280
+ challenge: ch
1281
+ ? {
1282
+ verdict: ch["verdict"] ?? null,
1283
+ findings: f ? { total: sumNums(Object.values(f)), ...f } : null,
1284
+ }
1285
+ : undefined,
1286
+ redTests: numOr(r["redTests"]),
1287
+ })
1288
+ : undefined,
1289
+ scan: defined({ rows: r["sourceRows"], afterEnd: r["afterEnd"], settled: r["settled"] }),
1290
+ });
1291
+ }
1292
+
1293
+ /** `normalize` typed for readers: every row a fold or report sees. */
1294
+ export const normalizeEvent = (raw: unknown): TelemetryEvent => normalize(raw) as TelemetryEvent;
1295
+
1296
+ // ---------------------------------------------------------------------------
1297
+ // Totals — every total beside its parts must equal them
1298
+ // ---------------------------------------------------------------------------
1299
+
1300
+ const sumOf = (xs: unknown[]): number =>
1301
+ xs.reduce<number>((a, x) => a + (typeof x === "number" ? x : 0), 0);
1302
+ const field = (o: unknown, ...pathTo: string[]): unknown =>
1303
+ pathTo.reduce<unknown>((v, k) => (isObj(v) ? v[k] : undefined), o);
1304
+ const TOKEN_FIELDS = ["input", "cacheWrite", "cacheRead", "output", "outputEst", "read"] as const;
1305
+
1306
+ /**
1307
+ * The first total on `row` that does not equal its parts, or undefined. Only blocks
1308
+ * the row carries are checked. Minute totals are summed from unrounded values, so
1309
+ * each part may be off by its rounding: +-0.1 per part.
1310
+ */
1311
+ export function totalsProblem(row: Obj): string | undefined {
1312
+ const eq = (what: string, total: unknown, parts: number, tol = 0): string | undefined =>
1313
+ typeof total === "number" && Math.abs(total - parts) <= tol + 1e-9
1314
+ ? undefined
1315
+ : `${what} is ${String(total)}, its parts sum to ${tenthOf(parts)}`;
1316
+ const checks: Array<() => string | undefined> = [];
1317
+
1318
+ const lines = row["lines"];
1319
+ if (isObj(lines) && isObj(lines["total"])) {
1320
+ const t = lines["total"];
1321
+ checks.push(() => eq("lines.total.changed", t["changed"], sumOf([t["added"], t["deleted"]])));
1322
+ if (["code", "tests", "docs"].some((p) => isObj(lines[p]))) {
1323
+ for (const f of ["added", "deleted", "files"]) {
1324
+ checks.push(() =>
1325
+ eq(
1326
+ `lines.total.${f}`,
1327
+ t[f],
1328
+ sumOf(["code", "tests", "docs"].map((p) => field(lines, p, f))),
1329
+ ),
1330
+ );
1331
+ }
1332
+ }
1333
+ }
1334
+
1335
+ const time = row["time"];
1336
+ if (isObj(time) && typeof time["start"] === "number" && typeof time["end"] === "number") {
1337
+ checks.push(() =>
1338
+ eq(
1339
+ "time.totalMinutes",
1340
+ time["totalMinutes"],
1341
+ ((time["end"] as number) - (time["start"] as number)) / 60000,
1342
+ 0.1,
1343
+ ),
1344
+ );
1345
+ const spans = time["spans"];
1346
+ if (
1347
+ row["kind"] === "chat" &&
1348
+ Array.isArray(spans) &&
1349
+ typeof time["activeMinutes"] === "number"
1350
+ ) {
1351
+ const ms = sumOf(spans.map((s) => (Array.isArray(s) ? Number(s[1]) - Number(s[0]) : 0)));
1352
+ checks.push(() => eq("time.activeMinutes", time["activeMinutes"], ms / 60000, 0.1));
1353
+ }
1354
+ }
1355
+
1356
+ const steps = row["steps"];
1357
+ if (isObj(steps) && isObj(steps["byStep"]) && isObj(steps["total"])) {
1358
+ const parts = Object.values(steps["byStep"]);
1359
+ for (const f of ["n", "totalMinutes", "activeMinutes"]) {
1360
+ const total = steps["total"][f];
1361
+ if (total === undefined || total === null) continue;
1362
+ const tol = f === "n" ? 0 : 0.1 * Math.max(1, parts.length);
1363
+ checks.push(() => eq(`steps.total.${f}`, total, sumOf(parts.map((p) => field(p, f))), tol));
1364
+ }
1365
+ }
1366
+
1367
+ const plan = row["plan"];
1368
+ if (isObj(plan) && isObj(plan["total"]) && Array.isArray(plan["groups"])) {
1369
+ const groups = plan["groups"];
1370
+ const total = plan["total"];
1371
+ checks.push(() =>
1372
+ eq(
1373
+ "plan.total.tasks",
1374
+ total["tasks"],
1375
+ sumOf(groups.map((g) => arrOf(field(g, "tasks")).length)),
1376
+ ),
1377
+ );
1378
+ }
1379
+
1380
+ const build = row["build"];
1381
+ if (isObj(build)) {
1382
+ const findings = field(build, "challenge", "findings");
1383
+ if (isObj(findings)) {
1384
+ checks.push(() =>
1385
+ eq(
1386
+ "build.challenge.findings.total",
1387
+ findings["total"],
1388
+ sumOf(["CRITICAL", "HIGH", "MEDIUM", "LOW"].map((s) => findings[s])),
1389
+ ),
1390
+ );
1391
+ }
1392
+ if (typeof build["redTests"] === "number" && isObj(field(steps, "byStep"))) {
1393
+ checks.push(() =>
1394
+ eq(
1395
+ "build.redTests",
1396
+ build["redTests"],
1397
+ Number(field(steps, "byStep", "build-tests-red", "n") ?? 0),
1398
+ ),
1399
+ );
1400
+ }
1401
+ }
1402
+
1403
+ const usage = row["usage"];
1404
+ const agents = row["agents"];
1405
+ const byAgent = isObj(agents) && isObj(agents["byAgent"]) ? Object.values(agents["byAgent"]) : [];
1406
+ if (isObj(usage)) {
1407
+ const blocks: Array<[string, unknown]> = [
1408
+ ["usage.total", usage["total"]],
1409
+ ["usage.main", usage["main"]],
1410
+ ...Object.entries(isObj(usage["byModel"]) ? usage["byModel"] : {}).map(
1411
+ ([m, u]): [string, unknown] => [`usage.byModel.${m}`, u],
1412
+ ),
1413
+ ...Object.entries(isObj(agents) && isObj(agents["byAgent"]) ? agents["byAgent"] : {}).map(
1414
+ ([a, v]): [string, unknown] => [`agents.byAgent.${a}.usage`, field(v, "usage")],
1415
+ ),
1416
+ ];
1417
+ for (const [name, u] of blocks) {
1418
+ const tokens = field(u, "tokens");
1419
+ if (!isObj(tokens) || tokens["read"] === undefined) continue;
1420
+ checks.push(() =>
1421
+ eq(
1422
+ `${name}.tokens.read`,
1423
+ tokens["read"],
1424
+ sumOf([tokens["input"], tokens["cacheWrite"], tokens["cacheRead"]]),
1425
+ ),
1426
+ );
1427
+ }
1428
+ const total = usage["total"];
1429
+ const models = isObj(usage["byModel"]) ? Object.values(usage["byModel"]) : [];
1430
+ if (isObj(total) && models.length > 0) {
1431
+ checks.push(() =>
1432
+ eq("usage.total.turns", total["turns"], sumOf(models.map((m) => field(m, "turns")))),
1433
+ );
1434
+ for (const f of TOKEN_FIELDS) {
1435
+ if (field(total, "tokens", f) === undefined) continue;
1436
+ checks.push(() =>
1437
+ eq(
1438
+ `usage.total.tokens.${f}`,
1439
+ field(total, "tokens", f),
1440
+ sumOf(models.map((m) => field(m, "tokens", f))),
1441
+ ),
1442
+ );
1443
+ }
1444
+ }
1445
+ if (isObj(total) && total["compactions"] !== undefined) {
1446
+ checks.push(() =>
1447
+ eq(
1448
+ "usage.total.compactions",
1449
+ total["compactions"],
1450
+ sumOf([
1451
+ field(usage, "main", "compactions"),
1452
+ ...byAgent.map((a) => field(a, "usage", "compactions")),
1453
+ ]),
1454
+ ),
1455
+ );
1456
+ }
1457
+ const peak = field(total, "context", "peak");
1458
+ if (typeof peak === "number") {
1459
+ const peaks = [
1460
+ field(usage, "main", "context", "peak"),
1461
+ ...byAgent.flatMap((a) =>
1462
+ Array.isArray(field(a, "instances"))
1463
+ ? (field(a, "instances") as unknown[]).map((i) => field(i, "contextPeak"))
1464
+ : [],
1465
+ ),
1466
+ ].filter((v): v is number => typeof v === "number");
1467
+ if (peaks.length > 0)
1468
+ checks.push(() => eq("usage.total.context.peak", peak, Math.max(...peaks)));
1469
+ }
1470
+ }
1471
+ if (isObj(agents) && isObj(agents["total"]) && isObj(agents["byAgent"])) {
1472
+ const total = agents["total"];
1473
+ for (const f of ["n", "errors"]) {
1474
+ checks.push(() => eq(`agents.total.${f}`, total[f], sumOf(byAgent.map((a) => field(a, f)))));
1475
+ }
1476
+ for (const [name, a] of Object.entries(agents["byAgent"])) {
1477
+ const instances = field(a, "instances");
1478
+ if (Array.isArray(instances)) {
1479
+ checks.push(() => eq(`agents.byAgent.${name}.n`, field(a, "n"), instances.length));
1480
+ }
1481
+ }
1482
+ }
1483
+
1484
+ const tools = row["tools"];
1485
+ if (isObj(tools) && isObj(tools["total"]) && isObj(tools["byTool"])) {
1486
+ const parts = Object.values(tools["byTool"]);
1487
+ for (const f of ["calls", "errors"]) {
1488
+ checks.push(() =>
1489
+ eq(`tools.total.${f}`, field(tools, "total", f), sumOf(parts.map((p) => field(p, f)))),
1490
+ );
1491
+ }
1492
+ }
1493
+
1494
+ const cli = field(row, "bkit", "cli");
1495
+ if (isObj(cli) && isObj(cli["byVerb"])) {
1496
+ checks.push(() =>
1497
+ eq("bkit.cli.total", cli["total"], sumOf(Object.values(cli["byVerb"] as Obj))),
1498
+ );
1499
+ }
1500
+
1501
+ for (const check of checks) {
1502
+ const problem = check();
1503
+ if (problem !== undefined) return problem;
1504
+ }
1505
+ return undefined;
1506
+ }
1507
+
592
1508
  // ---------------------------------------------------------------------------
593
1509
  // Validation result
594
1510
  // ---------------------------------------------------------------------------
@@ -608,13 +1524,19 @@ export function validate(event: unknown): ValidationResult {
608
1524
  }
609
1525
  const e = event as Record<string, unknown>;
610
1526
 
611
- // A2-mandatory envelope fields
612
- const mandatory: string[] = ["ts", "kind", "repo", "bkitVersion", "step"];
613
- for (const field of mandatory) {
1527
+ if (e["schema"] !== SCHEMA) {
1528
+ return { ok: false, reason: `schema must be ${SCHEMA} (got: ${String(e["schema"])})` };
1529
+ }
1530
+ for (const field of ["ts", "kind", "repo", "bkit", "by"]) {
614
1531
  if (e[field] === undefined || e[field] === null) {
615
1532
  return { ok: false, reason: `missing mandatory field: ${field}` };
616
1533
  }
617
1534
  }
1535
+ for (const flat of ["bkitVersion", "workflow", "step", "subagent", "model"]) {
1536
+ if (e[flat] !== undefined) {
1537
+ return { ok: false, reason: `${flat} is not a top-level field (bkit.version, by.*)` };
1538
+ }
1539
+ }
618
1540
 
619
1541
  if (typeof e["ts"] !== "number") {
620
1542
  return { ok: false, reason: "ts must be a number (ms unix)" };
@@ -628,11 +1550,37 @@ export function validate(event: unknown): ValidationResult {
628
1550
  if (typeof e["repo"] !== "string" || e["repo"] === "") {
629
1551
  return { ok: false, reason: "repo must be a non-empty string" };
630
1552
  }
631
- if (typeof e["bkitVersion"] !== "string" || e["bkitVersion"] === "") {
632
- return { ok: false, reason: "bkitVersion must be a non-empty string" };
1553
+ const bkit = e["bkit"];
1554
+ // null on chat / run rows: the script found no bkit version in the repo's history at that time.
1555
+ const unknownVersion =
1556
+ bkit !== undefined &&
1557
+ isObj(bkit) &&
1558
+ bkit["version"] === null &&
1559
+ (e["kind"] === "chat" || e["kind"] === "run");
1560
+ if (
1561
+ !isObj(bkit) ||
1562
+ ((typeof bkit["version"] !== "string" || bkit["version"] === "") && !unknownVersion)
1563
+ ) {
1564
+ return {
1565
+ ok: false,
1566
+ reason: "bkit.version must be a non-empty string (null on chat / run rows)",
1567
+ };
1568
+ }
1569
+ const by = e["by"];
1570
+ if (!isObj(by)) return { ok: false, reason: "by must be an object" };
1571
+ if (typeof by["step"] !== "string" || by["step"] === "") {
1572
+ return { ok: false, reason: "by.step must be a non-empty string" };
633
1573
  }
634
- if (typeof e["step"] !== "string" || e["step"] === "") {
635
- return { ok: false, reason: "step must be a non-empty string" };
1574
+ for (const f of ["workflow", "subagent", "model"]) {
1575
+ if (by[f] !== undefined && (typeof by[f] !== "string" || by[f] === "")) {
1576
+ return { ok: false, reason: `by.${f} must be a non-empty string when present` };
1577
+ }
1578
+ }
1579
+ if (by["model"] !== undefined && by["subagent"] === undefined) {
1580
+ return { ok: false, reason: "by.model is set only on subagent rows" };
1581
+ }
1582
+ if (e["references"] !== undefined && !Array.isArray(e["references"])) {
1583
+ return { ok: false, reason: "references must be an array when present" };
636
1584
  }
637
1585
 
638
1586
  // kind-specific payload validation (minimal — structural check)
@@ -702,79 +1650,189 @@ export function validate(event: unknown): ValidationResult {
702
1650
  return { ok: false, reason: `${kind} rows do not carry reason` };
703
1651
  }
704
1652
 
1653
+ // firstTs / updates — the entry's age and row count, set by the writer (withLineage).
1654
+ if (AGED_KINDS.has(kind)) {
1655
+ const first = e["firstTs"];
1656
+ if (first !== undefined && (typeof first !== "number" || !(first <= (e["ts"] as number)))) {
1657
+ return { ok: false, reason: "firstTs must be a number no later than ts" };
1658
+ }
1659
+ const updates = e["updates"];
1660
+ if (updates !== undefined && (!Number.isInteger(updates) || (updates as number) < 1)) {
1661
+ return { ok: false, reason: "updates must be a positive integer" };
1662
+ }
1663
+ } else {
1664
+ for (const f of ["firstTs", "updates"]) {
1665
+ if (e[f] !== undefined) return { ok: false, reason: `${kind} rows do not carry ${f}` };
1666
+ }
1667
+ }
1668
+
1669
+ const run = isObj(e["run"]) ? e["run"] : undefined;
1670
+ if (kind === "compliance" || kind === "counter") {
1671
+ if (typeof run?.["parentSha"] !== "string" || run["parentSha"] === "") {
1672
+ return { ok: false, reason: `${kind} row missing run.parentSha` };
1673
+ }
1674
+ }
705
1675
  if (kind === "compliance") {
706
- if (!e["rule"] || !e["result"] || !e["phase"] || !e["parentSha"]) {
707
- return { ok: false, reason: "compliance row missing required payload fields" };
1676
+ const rule = e["rule"];
1677
+ if (!isObj(rule) || typeof rule["id"] !== "string" || rule["id"] === "") {
1678
+ return { ok: false, reason: "compliance row missing rule.id" };
1679
+ }
1680
+ if (!["pass", "fail", "n/a"].includes(rule["verdict"] as string)) {
1681
+ return {
1682
+ ok: false,
1683
+ reason: `compliance rule.verdict must be pass|fail|n/a (got: ${String(rule["verdict"])})`,
1684
+ };
1685
+ }
1686
+ }
1687
+ if (kind === "counter") {
1688
+ const c = e["counter"];
1689
+ if (
1690
+ !isObj(c) ||
1691
+ typeof c["name"] !== "string" ||
1692
+ c["name"] === "" ||
1693
+ typeof c["value"] !== "number"
1694
+ ) {
1695
+ return { ok: false, reason: "counter row needs counter.name and a numeric counter.value" };
1696
+ }
1697
+ if (c["source"] !== "model-self-report" && c["source"] !== "shell-bus") {
1698
+ return { ok: false, reason: "counter.source must be model-self-report or shell-bus" };
708
1699
  }
709
1700
  }
710
1701
  if (kind === "outcome") {
711
- // Every workflow run carries these; `prNumber` is ship-only (see below).
712
- const numFields = [
713
- "linesAdded",
714
- "linesDeleted",
715
- "linesChanged",
716
- "filesChanged",
717
- "taskCount",
718
- "durationSeconds",
719
- "deferrals",
720
- "failures",
721
- ];
722
- for (const f of numFields) {
723
- if (typeof e[f] !== "number") {
724
- return { ok: false, reason: `outcome missing or invalid numeric field: ${f}` };
725
- }
1702
+ if (run === undefined) return { ok: false, reason: "outcome row missing run" };
1703
+ if (run["parentSha"] !== undefined && typeof run["parentSha"] !== "string") {
1704
+ return { ok: false, reason: "outcome run.parentSha must be a string when present" };
1705
+ }
1706
+ if (run["pr"] !== undefined && typeof run["pr"] !== "number") {
1707
+ return { ok: false, reason: "outcome run.pr must be a number when present" };
726
1708
  }
727
- // prNumber — ship-only, optional; validate only when present.
728
- if (e["prNumber"] !== undefined && typeof e["prNumber"] !== "number") {
729
- return { ok: false, reason: "outcome prNumber must be a number when present" };
1709
+ const time = e["time"];
1710
+ // null: the run's start row is missing, so its time could not be measured.
1711
+ if (
1712
+ time !== null &&
1713
+ (!isObj(time) || ["start", "end", "totalMinutes"].some((f) => typeof time[f] !== "number"))
1714
+ ) {
1715
+ return {
1716
+ ok: false,
1717
+ reason: "outcome row needs time.start, time.end and time.totalMinutes, or time: null",
1718
+ };
730
1719
  }
731
- // parentSha — the run's identity anchor; optional (absent on some ship rows).
732
- if (e["parentSha"] !== undefined && typeof e["parentSha"] !== "string") {
733
- return { ok: false, reason: "outcome parentSha must be a string when present" };
1720
+ if (!OUTCOME_ENDINGS.has(e["ending"] as string)) {
1721
+ return {
1722
+ ok: false,
1723
+ reason: `outcome ending must be ${[...OUTCOME_ENDINGS].join("|")} (got: ${String(e["ending"])})`,
1724
+ };
1725
+ }
1726
+ if (e["publish"] !== undefined && typeof e["publish"] !== "boolean") {
1727
+ return {
1728
+ ok: false,
1729
+ reason: `outcome publish must be a boolean (got: ${String(e["publish"])})`,
1730
+ };
1731
+ }
1732
+ const ledgers = e["ledgers"];
1733
+ if (
1734
+ typeof field(ledgers, "deferrals", "repo") !== "number" ||
1735
+ typeof field(ledgers, "failures", "repo") !== "number"
1736
+ ) {
1737
+ return {
1738
+ ok: false,
1739
+ reason: "outcome row needs ledgers.deferrals.repo and ledgers.failures.repo",
1740
+ };
734
1741
  }
735
- // Optional per-run numeric metrics: validate type only when present.
736
- for (const f of [
737
- "frictionAdded",
738
- "deferralsAdded",
739
- "failuresAdded",
740
- "correctiveCommits",
741
- "reviewIterations",
742
- "ciTrySuccess",
743
- ]) {
744
- if (e[f] !== undefined && typeof e[f] !== "number") {
745
- return { ok: false, reason: `outcome ${f} must be a number when present` };
1742
+ for (const l of ["deferrals", "failures", "friction"]) {
1743
+ const added = field(ledgers, l, "added");
1744
+ if (added !== undefined && typeof added !== "number") {
1745
+ return { ok: false, reason: `outcome ledgers.${l}.added must be a number when present` };
746
1746
  }
747
1747
  }
748
- if (e["planSource"] !== undefined && e["planSource"] !== "brief") {
749
- return { ok: false, reason: 'outcome planSource must be "brief" when present' };
1748
+ const source = field(e["plan"], "source");
1749
+ if (e["plan"] !== undefined && source !== "file" && source !== "converted") {
1750
+ return {
1751
+ ok: false,
1752
+ reason: `outcome plan.source must be file|converted (got: ${String(source)})`,
1753
+ };
750
1754
  }
751
- // coverage is optional + per-tier; validate structure only when present.
752
- if (e["coverage"] !== undefined) {
753
- const cov = e["coverage"];
754
- if (typeof cov !== "object" || cov === null) {
755
- return { ok: false, reason: "outcome coverage must be an object" };
1755
+ const context = e["context"];
1756
+ if (context !== undefined) {
1757
+ const byAgent = field(context, "byAgent");
1758
+ if (!isObj(context) || typeof context["host"] !== "string" || !isObj(byAgent)) {
1759
+ return { ok: false, reason: "outcome context needs host and a byAgent object" };
756
1760
  }
1761
+ for (const [agent, a] of Object.entries(byAgent)) {
1762
+ if (typeof field(a, "peak") !== "number" || typeof field(a, "runs") !== "number") {
1763
+ return {
1764
+ ok: false,
1765
+ reason: `outcome context.byAgent.${agent} needs numeric peak and runs`,
1766
+ };
1767
+ }
1768
+ }
1769
+ }
1770
+ const cov = field(e["ship"], "coverage");
1771
+ if (cov !== undefined) {
1772
+ if (!isObj(cov)) return { ok: false, reason: "outcome ship.coverage must be an object" };
757
1773
  for (const tier of ["unit", "integration", "e2e"]) {
758
- const t = (cov as Record<string, unknown>)[tier];
1774
+ const t = cov[tier];
759
1775
  if (t === undefined) continue;
760
- if (typeof t !== "object" || t === null) {
761
- return { ok: false, reason: `outcome coverage.${tier} must be an object` };
762
- }
1776
+ if (!isObj(t))
1777
+ return { ok: false, reason: `outcome ship.coverage.${tier} must be an object` };
763
1778
  for (const m of ["lines", "branches", "functions", "statements"]) {
764
- const v = (t as Record<string, unknown>)[m];
765
- if (v !== undefined && typeof v !== "number") {
766
- return { ok: false, reason: `outcome coverage.${tier}.${m} must be a number` };
1779
+ if (t[m] !== undefined && typeof t[m] !== "number") {
1780
+ return { ok: false, reason: `outcome ship.coverage.${tier}.${m} must be a number` };
767
1781
  }
768
1782
  }
769
1783
  }
770
1784
  }
771
1785
  }
772
- if (kind === "counter") {
773
- if (!e["counterName"] || typeof e["counterValue"] !== "number" || !e["parentSha"]) {
774
- return { ok: false, reason: "counter row missing required payload fields" };
1786
+ if (kind === "chat") {
1787
+ if (!e["key"] || typeof e["key"] !== "string") {
1788
+ return { ok: false, reason: "chat row missing required field: key (<platform>:<sessionId>)" };
1789
+ }
1790
+ if (
1791
+ typeof field(e, "time", "start") !== "number" ||
1792
+ typeof field(e, "time", "end") !== "number"
1793
+ ) {
1794
+ return { ok: false, reason: "chat row needs time.start and time.end" };
1795
+ }
1796
+ if (typeof field(e, "scan", "bytes") !== "number") {
1797
+ return { ok: false, reason: "chat row needs scan.bytes" };
1798
+ }
1799
+ if (!Array.isArray(field(e, "run", "parentShas")) || !Array.isArray(field(e, "issue", "all"))) {
1800
+ return {
1801
+ ok: false,
1802
+ reason: "chat row needs run.parentShas and issue.all arrays (the join keys)",
1803
+ };
1804
+ }
1805
+ }
1806
+ if (kind === "run") {
1807
+ if (!e["key"] || typeof e["key"] !== "string") {
1808
+ return {
1809
+ ok: false,
1810
+ reason: "run row missing required field: key (<fid fp>:<workflow>:<start>)",
1811
+ };
1812
+ }
1813
+ if (typeof run?.["fid"] !== "string" || run["fid"] === "") {
1814
+ return { ok: false, reason: "run row missing required field: run.fid" };
775
1815
  }
776
- if (e["counterSource"] !== "model-self-report" && e["counterSource"] !== "shell-bus") {
777
- return { ok: false, reason: "counter counterSource must be model-self-report or shell-bus" };
1816
+ if (
1817
+ typeof field(e, "time", "start") !== "number" ||
1818
+ typeof field(e, "time", "end") !== "number"
1819
+ ) {
1820
+ return { ok: false, reason: "run row needs time.start and time.end" };
1821
+ }
1822
+ if (typeof field(e, "scan", "rows") !== "number") {
1823
+ return { ok: false, reason: "run row needs scan.rows" };
1824
+ }
1825
+ if (!RUN_ENDINGS.has(e["ending"] as string)) {
1826
+ return {
1827
+ ok: false,
1828
+ reason: `run ending must be one of ${[...RUN_ENDINGS].join("|")} (got: ${String(e["ending"])})`,
1829
+ };
1830
+ }
1831
+ if (run["parentSha"] !== null && typeof run["parentSha"] !== "string") {
1832
+ return { ok: false, reason: "run run.parentSha must be a string or null" };
1833
+ }
1834
+ if (!Array.isArray(run["parentShas"])) {
1835
+ return { ok: false, reason: "run row needs a run.parentShas array (the join keys)" };
778
1836
  }
779
1837
  }
780
1838
  if (kind === "feature") {
@@ -789,6 +1847,9 @@ export function validate(event: unknown): ValidationResult {
789
1847
  }
790
1848
  }
791
1849
 
1850
+ const totals = totalsProblem(e);
1851
+ if (totals !== undefined) return { ok: false, reason: `totals: ${totals}` };
1852
+
792
1853
  return { ok: true };
793
1854
  }
794
1855
 
@@ -805,7 +1866,8 @@ export interface ParseResult {
805
1866
  * Tolerant parse — per-line try/catch, skips + counts unparseable lines.
806
1867
  * NEVER throws.
807
1868
  *
808
- * No version gating — ALL well-formed rows are kept regardless of `bkitVersion`.
1869
+ * No version gating — ALL well-formed rows are kept as written, `schema` or not;
1870
+ * {@link fold} reads each through {@link normalize}.
809
1871
  */
810
1872
  export function parse(raw: string): ParseResult {
811
1873
  const result: ParseResult = {
@@ -853,13 +1915,13 @@ export function compareTs(a: { ts: unknown }, b: { ts: unknown }): number {
853
1915
  }
854
1916
 
855
1917
  /**
856
- * Fold events into a Map keyed by per-kind composite identity.
857
- * Later rows (higher ts) win for the same key — last-write-wins fold.
858
- * Mirrors ledgers/status.ts's dedupe approach but with per-kind composite tuples.
1918
+ * Fold events into a Map keyed by per-kind composite identity, each row in the
1919
+ * current shape ({@link normalize}). Later rows (higher ts) win for the same key —
1920
+ * last-write-wins fold.
859
1921
  */
860
1922
  export function fold(events: TelemetryEvent[]): FoldedState {
861
1923
  // Sort by ts ascending so later rows overwrite earlier ones
862
- const sorted = [...events].sort(compareTs);
1924
+ const sorted = events.map(normalizeEvent).sort(compareTs);
863
1925
  const state: FoldedState = new Map();
864
1926
  for (const event of sorted) {
865
1927
  const key = identity(event);
@@ -868,6 +1930,84 @@ export function fold(events: TelemetryEvent[]): FoldedState {
868
1930
  return state;
869
1931
  }
870
1932
 
1933
+ // ---------------------------------------------------------------------------
1934
+ // Lineage — the entry age + row count a fold winner carries (AGED_KINDS)
1935
+ // ---------------------------------------------------------------------------
1936
+
1937
+ export interface Lineage {
1938
+ /** Earliest `ts` / `firstTs` among the entry's rows; absent when none is a number. */
1939
+ firstTs?: number;
1940
+ /** Rows the entry has had. */
1941
+ updates: number;
1942
+ }
1943
+
1944
+ const positiveInt = (v: unknown): number | undefined =>
1945
+ Number.isInteger(v) && (v as number) > 0 ? (v as number) : undefined;
1946
+
1947
+ /**
1948
+ * `firstTs` + `updates` of one entry from all of its rows, in any order. A row
1949
+ * carrying `updates` stands for that many rows, so the count survives compaction;
1950
+ * each later row adds one. Rows sharing a numeric `ts` are one write: a compacted
1951
+ * winner beside the pre-compaction copy a union merge brought back.
1952
+ */
1953
+ export function lineage(
1954
+ rows: ReadonlyArray<{ ts?: unknown; firstTs?: unknown; updates?: unknown }>,
1955
+ ): Lineage {
1956
+ let firstTs: number | undefined;
1957
+ let updates = 0;
1958
+ let prev: number | undefined;
1959
+ for (const r of [...rows].sort((a, b) => compareTs({ ts: a.ts }, { ts: b.ts }))) {
1960
+ for (const t of [r.firstTs, r.ts]) {
1961
+ if (typeof t === "number" && Number.isFinite(t) && (firstTs === undefined || t < firstTs)) {
1962
+ firstTs = t;
1963
+ }
1964
+ }
1965
+ const own = positiveInt(r.updates);
1966
+ const at = tsOrder(r.ts);
1967
+ updates =
1968
+ at === prev && Number.isFinite(at)
1969
+ ? Math.max(updates, own ?? updates)
1970
+ : Math.max(own ?? 0, updates + 1);
1971
+ prev = at;
1972
+ }
1973
+ return firstTs === undefined ? { updates } : { firstTs, updates };
1974
+ }
1975
+
1976
+ /** `row` with `firstTs` + `updates` set to `l`, placed right after `ts` (at the end when it has none). */
1977
+ export function placeLineage(row: Record<string, unknown>, l: Lineage): Record<string, unknown> {
1978
+ const fields: Record<string, unknown> = l.firstTs === undefined ? {} : { firstTs: l.firstTs };
1979
+ fields["updates"] = l.updates;
1980
+ const out: Record<string, unknown> = {};
1981
+ for (const [k, v] of Object.entries(row)) {
1982
+ if (k === "firstTs" || k === "updates") continue;
1983
+ out[k] = v;
1984
+ if (k === "ts") Object.assign(out, fields);
1985
+ }
1986
+ return "ts" in row ? out : { ...out, ...fields };
1987
+ }
1988
+
1989
+ /** True for a row `bkit ledgers compact` folds: an {@link AGED_KINDS} kind with a non-empty string `key`. */
1990
+ export const isAgedRow = (row: Record<string, unknown>): boolean =>
1991
+ AGED_KINDS.has(String(row["kind"])) && typeof row["key"] === "string" && row["key"] !== "";
1992
+
1993
+ /**
1994
+ * `row` about to be appended, with `firstTs` + `updates` carried forward from
1995
+ * `prior` (rows already in its ledger) and any supplied values replaced. A row
1996
+ * {@link isAgedRow} rejects is returned unchanged.
1997
+ */
1998
+ export function withLineage(
1999
+ prior: readonly unknown[],
2000
+ row: Record<string, unknown>,
2001
+ ): Record<string, unknown> {
2002
+ if (!isAgedRow(row)) return row;
2003
+ const id = identity(normalizeEvent(row));
2004
+ const same = prior
2005
+ .map(normalizeEvent)
2006
+ .filter((p) => isAgedRow(p as Record<string, unknown>) && identity(p) === id);
2007
+ const { firstTs: _first, updates: _updates, ...fresh } = row;
2008
+ return placeLineage(row, lineage([...same, fresh]));
2009
+ }
2010
+
871
2011
  // ---------------------------------------------------------------------------
872
2012
  // FoldFrom — reads ledger files, returns combined fold
873
2013
  // ---------------------------------------------------------------------------
@@ -876,7 +2016,7 @@ export interface FoldFromResult {
876
2016
  state: FoldedState;
877
2017
  rowCount: number;
878
2018
  malformedLineCount: number;
879
- /** Row count per emitting `bkitVersion` — for triage of unexpected versions. */
2019
+ /** Row count per emitting `bkit.version` — for triage of unexpected versions. */
880
2020
  versionCounts: Record<string, number>;
881
2021
  maxRowsWarning: boolean;
882
2022
  }
@@ -895,8 +2035,9 @@ export function foldFrom(paths: string[]): FoldFromResult {
895
2035
  }
896
2036
 
897
2037
  const versionCounts: Record<string, number> = {};
898
- for (const e of allEvents) {
899
- const v = typeof e.bkitVersion === "string" && e.bkitVersion !== "" ? e.bkitVersion : "unknown";
2038
+ for (const e of allEvents.map(normalizeEvent)) {
2039
+ const version = e.bkit?.version;
2040
+ const v = typeof version === "string" && version !== "" ? version : "unknown";
900
2041
  versionCounts[v] = (versionCounts[v] ?? 0) + 1;
901
2042
  }
902
2043
 
@@ -1007,7 +2148,7 @@ export function workflowTelemetry(result: FoldFromResult, workflow?: string): Te
1007
2148
  // Folded ENTITY count per workflow (not raw lines) — an updated row folds to one.
1008
2149
  const workflowCounts: Record<string, number> = {};
1009
2150
  for (const ev of events) {
1010
- const w = ev.workflow || "unknown";
2151
+ const w = ev.by?.workflow || "unknown";
1011
2152
  workflowCounts[w] = (workflowCounts[w] ?? 0) + 1;
1012
2153
  }
1013
2154
 
@@ -1033,14 +2174,17 @@ export function workflowTelemetry(result: FoldFromResult, workflow?: string): Te
1033
2174
 
1034
2175
  // This workflow's run rows (generalized outcome), oldest → newest.
1035
2176
  const runs = events
1036
- .filter((e): e is OutcomeEvent => e.kind === "outcome" && e.workflow === workflow)
2177
+ .filter((e): e is OutcomeEvent => e.kind === "outcome" && e.by?.workflow === workflow)
1037
2178
  .sort(compareTs);
1038
2179
  const cur = runs.at(-1);
1039
- // Baseline only against runs of the same plan source — a brief run (no plan)
1040
- // has no tasks and a different shape, so mixing them skews every median.
2180
+ // Baseline only against runs of the same plan source — a converted run's plan was
2181
+ // written by the build from its input, so mixing it with file runs skews every median.
2182
+ // An old `brief` row (no plan file) counts as converted.
2183
+ const oldBrief = (r: OutcomeEvent | undefined) => r?.plan?.source === "brief";
2184
+ const converted = (r: OutcomeEvent | undefined) => r?.plan?.source === "converted" || oldBrief(r);
1041
2185
  const prev = runs
1042
2186
  .slice(0, -1)
1043
- .filter((r) => r.planSource === cur?.planSource)
2187
+ .filter((r) => converted(r) === converted(cur))
1044
2188
  .slice(-RUN_BASELINE_WINDOW);
1045
2189
 
1046
2190
  const repo = cur?.repo ?? events[0]?.repo ?? "unknown/repo";
@@ -1056,74 +2200,72 @@ export function workflowTelemetry(result: FoldFromResult, workflow?: string): Te
1056
2200
  if (cur) {
1057
2201
  // med·N: median of the previous runs that carry the field, `—` until there are
1058
2202
  // at least RUN_BASELINE_MIN of them (1–2 samples is noise, not a baseline).
1059
- const medCell = (key: keyof OutcomeEvent, fmt: (n: number) => string = String): string => {
1060
- const vals = prev.map((r) => r[key]).filter((v): v is number => typeof v === "number");
2203
+ const medCell = (
2204
+ get: (r: OutcomeEvent) => unknown,
2205
+ fmt: (n: number) => string = String,
2206
+ ): string => {
2207
+ const vals = prev.map(get).filter((v): v is number => typeof v === "number");
1061
2208
  if (vals.length < RUN_BASELINE_MIN) return "—";
1062
2209
  const m = median(vals);
1063
2210
  return m === null ? "—" : fmt(m);
1064
2211
  };
2212
+ const mins = (n: number) => `${n} (${humanizeDuration(n * 60)})`;
2213
+ const show = (
2214
+ label: string,
2215
+ get: (r: OutcomeEvent) => unknown,
2216
+ fmt?: (n: number) => string,
2217
+ ) => {
2218
+ const v = get(cur);
2219
+ if (typeof v === "number") row(label, fmt ? fmt(v) : String(v), medCell(get, fmt));
2220
+ };
1065
2221
 
1066
- // Core metrics — always shown.
1067
- row(
1068
- "durationSeconds",
1069
- `${cur.durationSeconds} (${humanizeDuration(cur.durationSeconds)})`,
1070
- medCell("durationSeconds", (n) => `${n} (${humanizeDuration(n)})`),
1071
- );
1072
- row(
1073
- "linesChanged",
1074
- `${cur.linesChanged} (+${cur.linesAdded}/-${cur.linesDeleted})`,
1075
- medCell("linesChanged"),
1076
- );
1077
- row("filesChanged", `${cur.filesChanged}`, medCell("filesChanged"));
1078
-
1079
- // Conditional metrics — shown only when this run carries them.
1080
- if (cur.planSource) row("planSource", cur.planSource, "—");
1081
- if (cur.taskCount > 0) row("taskCount", `${cur.taskCount}`, medCell("taskCount"));
1082
- if (typeof cur.reviewIterations === "number")
1083
- row("reviewIterations", `${cur.reviewIterations}`, medCell("reviewIterations"));
1084
- if (typeof cur.correctiveCommits === "number")
1085
- row("correctiveCommits", `${cur.correctiveCommits}`, medCell("correctiveCommits"));
1086
- if (typeof cur.ciTrySuccess === "number")
2222
+ show("time.totalMinutes", (r) => r.time?.totalMinutes, mins);
2223
+ const total = cur.lines?.total;
2224
+ if (total) {
1087
2225
  row(
1088
- "ciTrySuccess",
1089
- `${cur.ciTrySuccess}${cur.ciTrySuccess === 1 ? " (first-try)" : ""}`,
1090
- medCell("ciTrySuccess"),
2226
+ "lines.total.changed",
2227
+ `${total.changed} (+${total.added}/-${total.deleted})`,
2228
+ medCell((r) => r.lines?.total?.changed),
1091
2229
  );
1092
- // Instinct-loop deltas — frictionAdded is the featured signal (shown even at 0).
1093
- if (typeof cur.frictionAdded === "number")
1094
- row("frictionAdded", `${cur.frictionAdded}`, medCell("frictionAdded"));
1095
- if (typeof cur.deferralsAdded === "number")
1096
- row("deferralsAdded", `${cur.deferralsAdded}`, medCell("deferralsAdded"));
1097
- if (typeof cur.failuresAdded === "number")
1098
- row("failuresAdded", `${cur.failuresAdded}`, medCell("failuresAdded"));
2230
+ show("lines.total.files", (r) => r.lines?.total?.files);
2231
+ }
2232
+ show("plan.total.tasks", (r) => r.plan?.total?.tasks);
2233
+ if (cur.ending === "close-failed" || cur.ending === "held") row("ending", cur.ending, "—");
2234
+ // Instinct-loop deltas — friction is the featured signal (shown even at 0).
2235
+ show("ledgers.friction.added", (r) => r.ledgers?.friction?.added);
2236
+ show("ledgers.deferrals.added", (r) => r.ledgers?.deferrals?.added);
2237
+ show("ledgers.failures.added", (r) => r.ledgers?.failures?.added);
1099
2238
  }
1100
2239
 
1101
- // Compliance — this run's rows. The `outcome` and `compliance` rows are written
1102
- // at different points in a close (different HEADs → different parentSha), so we
1103
- // DON'T match on the run row's parentSha: we take the newest same-workflow
1104
- // compliance group (its parentSha) as "this run".
2240
+ // Compliance — this run's rows: the run row's run.parentSha, else the newest
2241
+ // same-workflow compliance group.
1105
2242
  const complianceRows = events.filter(
1106
- (e): e is ComplianceEvent => e.kind === "compliance" && e.workflow === workflow,
2243
+ (e): e is ComplianceEvent => e.kind === "compliance" && e.by?.workflow === workflow,
1107
2244
  );
1108
- const compSha = complianceRows.slice().sort((a, b) => compareTs(b, a))[0]?.parentSha;
2245
+ const newestSha = complianceRows.slice().sort((a, b) => compareTs(b, a))[0]?.run?.parentSha;
2246
+ const curSha = cur?.run?.parentSha;
2247
+ const compSha = complianceRows.some((c) => c.run?.parentSha === curSha) ? curSha : newestSha;
1109
2248
  if (compSha) {
1110
- const comp = complianceRows.filter((c) => c.parentSha === compSha);
1111
- const pass = comp.filter((c) => c.result === "pass").length;
1112
- const fail = comp.filter((c) => c.result === "fail").length;
1113
- const na = comp.filter((c) => c.result === "n/a").length;
2249
+ const comp = complianceRows.filter((c) => c.run?.parentSha === compSha);
2250
+ const pass = comp.filter((c) => c.rule?.verdict === "pass").length;
2251
+ const fail = comp.filter((c) => c.rule?.verdict === "fail").length;
2252
+ const na = comp.filter((c) => c.rule?.verdict === "n/a").length;
1114
2253
  const denom = pass + fail + na;
1115
2254
  const rate = denom > 0 ? Math.round((pass / denom) * 100) : 0;
1116
2255
  row("compliance", `${pass} pass · ${fail} fail · ${na} n/a (${rate}%)`, "—");
1117
2256
  }
1118
2257
 
1119
- // Attempts — the newest same-workflow *_ATTEMPT counter (this run).
1120
- const attempt = events
2258
+ // Attempts — this run's *_ATTEMPT counter, else the newest same-workflow one.
2259
+ const attempts = events
1121
2260
  .filter(
1122
2261
  (e): e is CounterEvent =>
1123
- e.kind === "counter" && e.workflow === workflow && /_ATTEMPT$/.test(e.counterName),
2262
+ e.kind === "counter" &&
2263
+ e.by?.workflow === workflow &&
2264
+ /_ATTEMPT$/.test(e.counter?.name ?? ""),
1124
2265
  )
1125
- .sort((a, b) => compareTs(b, a))[0];
1126
- if (attempt) row("attempts", `${attempt.counterName} ${attempt.counterValue}`, "—");
2266
+ .sort((a, b) => compareTs(b, a));
2267
+ const attempt = attempts.find((c) => c.run?.parentSha === curSha) ?? attempts[0];
2268
+ if (attempt) row("attempts", `${attempt.counter.name} ${attempt.counter.value}`, "—");
1127
2269
 
1128
2270
  if (tableRows.length > 0) {
1129
2271
  lines.push(
@@ -1134,8 +2276,10 @@ export function workflowTelemetry(result: FoldFromResult, workflow?: string): Te
1134
2276
  );
1135
2277
  }
1136
2278
  lines.push(
1137
- `\`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`,
2279
+ `\`med·${RUN_BASELINE_WINDOW}\` = median of the previous ${RUN_BASELINE_WINDOW} ${workflow}${converted(cur) ? " converted" : ""} runs (— if < ${RUN_BASELINE_MIN}) · ledger ${result.rowCount} rows, ${result.malformedLineCount} malformed`,
1138
2280
  );
2281
+ if ([cur, ...prev].some(oldBrief))
2282
+ lines.push("Old `plan.source: brief` rows count as `converted`.");
1139
2283
  lines.push(...maxRowsLines);
1140
2284
 
1141
2285
  return { ...base, lines };