@cbartens/bkit 6.1.1 → 6.2.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 (313) hide show
  1. package/.bkit/README.md +14 -12
  2. package/.bkit/core/.agents/docs.md +1 -11
  3. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-gateguard.cjs +30 -9
  4. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-guardrails.cjs +25 -27
  5. package/.bkit/core/.agents/rules.md +22 -9
  6. package/.bkit/core/.bkit/README.md +13 -11
  7. package/.bkit/core/.bkit/authoring.md +58 -13
  8. package/.bkit/core/.bkit/cli.md +42 -32
  9. package/.bkit/core/.bkit/cloud.md +93 -30
  10. package/.bkit/core/.bkit/install.md +55 -16
  11. package/.bkit/core/.bkit/jsonl.md +24 -7
  12. package/.bkit/core/.bkit/pipeline.md +8 -8
  13. package/.bkit/core/.bkit/prompts.md +160 -43
  14. package/.bkit/core/.bkit/providers.md +97 -36
  15. package/.bkit/core/.bkit/templates.md +162 -34
  16. package/.bkit/core/.bkit/trackers.md +39 -6
  17. package/.bkit/core/.bkit/workflows.md +344 -136
  18. package/.bkit/core/.claude/hooks/bkit-guardrails.cjs +50 -27
  19. package/.bkit/core/.claude/hooks/bkit-preflight.sh +11 -11
  20. package/.bkit/core/.codex/hooks/bkit-gateguard.cjs +13 -8
  21. package/.bkit/core/.codex/hooks/bkit-guardrails.cjs +14 -25
  22. package/.bkit/core/.cursor/hooks/bkit-guardrails.cjs +20 -9
  23. package/.bkit/core/.cursor/hooks/bkit-preflight.sh +8 -8
  24. package/.bkit/core/.opencode/plugin/bkit-gateguard.js +14 -4
  25. package/.bkit/core/.opencode/plugin/bkit-guardrails.js +114 -0
  26. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +1 -1
  27. package/.bkit/core/docs/templates/bkit-audit-adoption.md +30 -6
  28. package/.bkit/core/docs/templates/bkit-audit-agents.md +1 -1
  29. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +1 -1
  30. package/.bkit/core/docs/templates/bkit-audit-analytics.md +1 -1
  31. package/.bkit/core/docs/templates/bkit-audit-annotations.md +1 -1
  32. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +1 -1
  33. package/.bkit/core/docs/templates/bkit-audit-app-store.md +1 -1
  34. package/.bkit/core/docs/templates/bkit-audit-architecture.md +1 -1
  35. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +2 -2
  36. package/.bkit/core/docs/templates/bkit-audit-config.md +3 -2
  37. package/.bkit/core/docs/templates/bkit-audit-cost.md +1 -1
  38. package/.bkit/core/docs/templates/bkit-audit-coverage.md +1 -1
  39. package/.bkit/core/docs/templates/bkit-audit-database.md +3 -3
  40. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +1 -1
  41. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +1 -1
  42. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +3 -3
  43. package/.bkit/core/docs/templates/bkit-audit-documentation.md +32 -2
  44. package/.bkit/core/docs/templates/bkit-audit-duplication.md +1 -1
  45. package/.bkit/core/docs/templates/bkit-audit-failures.md +1 -1
  46. package/.bkit/core/docs/templates/bkit-audit-flakes.md +2 -2
  47. package/.bkit/core/docs/templates/bkit-audit-gates.md +5 -3
  48. package/.bkit/core/docs/templates/bkit-audit-issues.md +1 -1
  49. package/.bkit/core/docs/templates/bkit-audit-llm.md +2 -2
  50. package/.bkit/core/docs/templates/bkit-audit-logs.md +1 -1
  51. package/.bkit/core/docs/templates/bkit-audit-models.md +2 -2
  52. package/.bkit/core/docs/templates/bkit-audit-privacy.md +1 -1
  53. package/.bkit/core/docs/templates/bkit-audit-prompts.md +1 -1
  54. package/.bkit/core/docs/templates/bkit-audit-red-team.md +2 -2
  55. package/.bkit/core/docs/templates/bkit-audit-reliability.md +3 -2
  56. package/.bkit/core/docs/templates/bkit-audit-repo.md +1 -1
  57. package/.bkit/core/docs/templates/bkit-audit-security.md +1 -1
  58. package/.bkit/core/docs/templates/bkit-audit-slop.md +1 -1
  59. package/.bkit/core/docs/templates/bkit-audit-testing.md +3 -2
  60. package/.bkit/core/docs/templates/bkit-audit-usability.md +1 -1
  61. package/.bkit/core/docs/templates/bkit-plan.md +38 -8
  62. package/.bkit/core/engine/checks/after/auth.ts +118 -47
  63. package/.bkit/core/engine/checks/after/github.ts +89 -37
  64. package/.bkit/core/engine/checks/after/index.ts +15 -3
  65. package/.bkit/core/engine/checks/after/tools.ts +245 -1
  66. package/.bkit/core/engine/checks/before/files.ts +59 -1
  67. package/.bkit/core/engine/checks/before/index.ts +8 -0
  68. package/.bkit/core/engine/checks/status-holes.ts +20 -26
  69. package/.bkit/core/engine/checks/tips/catalogue.ts +107 -10
  70. package/.bkit/core/engine/checks/tips/detect.ts +36 -3
  71. package/.bkit/core/engine/checks/tips/index.ts +1 -1
  72. package/.bkit/core/engine/cli.ts +13 -13
  73. package/.bkit/core/engine/commands/ci/ci.ts +64 -11
  74. package/.bkit/core/engine/commands/ci/push-gate.ts +101 -43
  75. package/.bkit/core/engine/commands/install/install.ts +28 -25
  76. package/.bkit/core/engine/commands/install/uninstall.ts +42 -30
  77. package/.bkit/core/engine/commands/install/upgrade.ts +14 -2
  78. package/.bkit/core/engine/commands/land.ts +2 -3
  79. package/.bkit/core/engine/commands/lib.ts +394 -39
  80. package/.bkit/core/engine/commands/registry.ts +1 -1
  81. package/.bkit/core/engine/commands/workflow/branches.ts +351 -78
  82. package/.bkit/core/engine/commands/workflow/challenge.ts +63 -14
  83. package/.bkit/core/engine/commands/workflow/context.ts +71 -10
  84. package/.bkit/core/engine/commands/workflow/counters.ts +298 -23
  85. package/.bkit/core/engine/commands/workflow/decisions.ts +260 -125
  86. package/.bkit/core/engine/commands/workflow/disk.ts +2 -1
  87. package/.bkit/core/engine/commands/workflow/feature-base.ts +66 -0
  88. package/.bkit/core/engine/commands/workflow/issues.ts +312 -17
  89. package/.bkit/core/engine/commands/workflow/junit.ts +204 -0
  90. package/.bkit/core/engine/commands/workflow/ledgers.ts +904 -99
  91. package/.bkit/core/engine/commands/workflow/locks.ts +186 -29
  92. package/.bkit/core/engine/commands/workflow/loops.ts +87 -0
  93. package/.bkit/core/engine/commands/workflow/open-decision.ts +251 -0
  94. package/.bkit/core/engine/commands/workflow/plan-blocks.ts +8 -0
  95. package/.bkit/core/engine/commands/workflow/plans.ts +1 -1
  96. package/.bkit/core/engine/commands/workflow/prs.ts +311 -16
  97. package/.bkit/core/engine/commands/workflow/repo.ts +1 -1
  98. package/.bkit/core/engine/commands/workflow/run-facts.ts +6 -0
  99. package/.bkit/core/engine/commands/workflow/runs.ts +877 -174
  100. package/.bkit/core/engine/commands/workflow/runtime.ts +12 -4
  101. package/.bkit/core/engine/commands/workflow/status.ts +324 -11
  102. package/.bkit/core/engine/commands/workflow/step-table.ts +41 -15
  103. package/.bkit/core/engine/commands/workflow/steps.ts +604 -29
  104. package/.bkit/core/engine/commands/workflow/summary-findings.ts +1 -1
  105. package/.bkit/core/engine/commands/workflow/summary.ts +314 -8
  106. package/.bkit/core/engine/commands/workflow/tasks.ts +400 -27
  107. package/.bkit/core/engine/commands/workflow/tests-base.ts +319 -0
  108. package/.bkit/core/engine/commands/workflow/tests-changed.ts +138 -74
  109. package/.bkit/core/engine/commands/workflow/tests-jump.ts +93 -0
  110. package/.bkit/core/engine/commands/workflow/tests.ts +815 -182
  111. package/.bkit/core/engine/commands/workflow/tracker.ts +1134 -137
  112. package/.bkit/core/engine/commands/workflow/workflows.ts +100 -72
  113. package/.bkit/core/engine/commands/workflow/worktrees.ts +421 -57
  114. package/.bkit/core/engine/install/cloud-env.ts +38 -10
  115. package/.bkit/core/engine/install/managed-block.ts +105 -0
  116. package/.bkit/core/engine/install/manifest.ts +7 -1
  117. package/.bkit/core/engine/install/modules/claude.ts +6 -2
  118. package/.bkit/core/engine/install/modules/cloud.ts +84 -95
  119. package/.bkit/core/engine/install/modules/codex.ts +10 -2
  120. package/.bkit/core/engine/install/modules/core.ts +148 -14
  121. package/.bkit/core/engine/install/modules/opencode.ts +18 -23
  122. package/.bkit/core/engine/install/network-allowlist.ts +8 -3
  123. package/.bkit/core/engine/install/project-docs.ts +650 -0
  124. package/.bkit/core/engine/install/template-copies.ts +58 -5
  125. package/.bkit/core/engine/install/write.ts +128 -7
  126. package/.bkit/core/engine/ledgers/journal.ts +18 -10
  127. package/.bkit/core/engine/ledgers/migrate.ts +20 -8
  128. package/.bkit/core/engine/ledgers/status.ts +604 -8
  129. package/.bkit/core/engine/ledgers/telemetry.ts +115 -13
  130. package/.bkit/core/engine/render/trackers.ts +3 -1
  131. package/.bkit/core/engine/shared/package-manager.ts +7 -3
  132. package/.bkit/core/engine/shared/settings.ts +12 -1
  133. package/.bkit/core/engine/shared/text.ts +14 -0
  134. package/.bkit/core/engine/tools/instructions-sources.ts +1 -0
  135. package/.bkit/core/engine/tools/instructions.ts +116 -20
  136. package/.bkit/core/hooks/antigravity-hook.js +20 -4
  137. package/.bkit/core/hooks/gateguard-edit-payload.js +8 -5
  138. package/.bkit/core/hooks/gateguard-engine.js +249 -23
  139. package/.bkit/core/hooks/guardrails-deny.js +167 -0
  140. package/.bkit/core/hooks/guardrails-read.js +3 -3
  141. package/.bkit/core/hooks/guardrails-shell.js +1122 -167
  142. package/.bkit/core/hooks/guardrails-tiers.js +247 -176
  143. package/.bkit/core/hooks/preflight-tracker.sh +219 -0
  144. package/.bkit/core/prompts/bkit-audit-generate.md +23 -6
  145. package/.bkit/core/prompts/bkit-build-challenge-1.md +5 -4
  146. package/.bkit/core/prompts/bkit-build-challenge-2.md +6 -5
  147. package/.bkit/core/prompts/bkit-build-install-skills.md +2 -2
  148. package/.bkit/core/prompts/bkit-build-plan-convert.md +21 -7
  149. package/.bkit/core/prompts/bkit-build-plan-current.md +5 -4
  150. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +22 -17
  151. package/.bkit/core/prompts/bkit-build-plan-tasks.md +16 -12
  152. package/.bkit/core/prompts/bkit-build-plan-tests.md +14 -10
  153. package/.bkit/core/prompts/bkit-build-plan-verify.md +21 -8
  154. package/.bkit/core/prompts/bkit-debug-abort-handover.md +10 -5
  155. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +22 -6
  156. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +19 -3
  157. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +22 -6
  158. package/.bkit/core/prompts/bkit-debug-failure-soak.md +10 -7
  159. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +3 -3
  160. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +4 -4
  161. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +3 -3
  162. package/.bkit/core/prompts/bkit-design-generate.md +6 -4
  163. package/.bkit/core/prompts/bkit-design-organise.md +4 -3
  164. package/.bkit/core/prompts/bkit-design-review-1.md +5 -4
  165. package/.bkit/core/prompts/bkit-design-review-2.md +6 -5
  166. package/.bkit/core/prompts/bkit-design-spike.md +4 -3
  167. package/.bkit/core/prompts/bkit-design-update.md +6 -4
  168. package/.bkit/core/prompts/bkit-plan-generate.md +35 -14
  169. package/.bkit/core/prompts/bkit-plan-review-1.md +9 -7
  170. package/.bkit/core/prompts/bkit-plan-review-2.md +9 -7
  171. package/.bkit/core/prompts/bkit-plan-scope-check.md +8 -6
  172. package/.bkit/core/prompts/bkit-plan-update.md +22 -8
  173. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +11 -8
  174. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +9 -5
  175. package/.bkit/core/prompts/bkit-ship-update-docs.md +26 -4
  176. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +3 -3
  177. package/.bkit/core/prompts/bkit-utility-update-decisions.md +10 -7
  178. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +8 -5
  179. package/.bkit/core/prompts/bkit-utility-update-documentation.md +31 -7
  180. package/.bkit/core/prompts/bkit-utility-update-failures.md +8 -5
  181. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +10 -7
  182. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +4 -4
  183. package/.bkit/core/prompts/bkit-utility-update-tracker.md +4 -4
  184. package/.bkit/core/workflows/bkit-auto.md +23 -11
  185. package/.bkit/core/workflows/bkit-build.md +331 -100
  186. package/.bkit/core/workflows/bkit-debug.md +135 -64
  187. package/.bkit/core/workflows/bkit-design.md +58 -32
  188. package/.bkit/core/workflows/bkit-plan.md +73 -45
  189. package/.bkit/core/workflows/bkit-ship.md +233 -167
  190. package/.bkit/shared/.agents/plugins/bkit/hooks.json +1 -1
  191. package/.bkit/shared/.bkit/.env.example +5 -0
  192. package/.bkit/shared/.claude/bkit-cloud.md +7 -7
  193. package/.bkit/shared/.claude/settings.json +5 -1
  194. package/.bkit/shared/.cursor/bkit-cloud.md +1 -1
  195. package/.bkit/shared/.cursor/hooks.json +1 -1
  196. package/.bkit/shared/.opencode/opencode.json +11 -2
  197. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +27 -0
  198. package/.bkit/templates/.cursor/Dockerfile +7 -7
  199. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-idea.yml +1 -1
  200. package/.bkit/templates/.github/dependabot.yml +5 -0
  201. package/.bkit/templates/.github/renovate.json5 +5 -3
  202. package/.bkit/templates/.github/workflows/bkit-ci.yml +11 -11
  203. package/.bkit/templates/.github/workflows/bkit-cloud.yml +525 -161
  204. package/.bkit/templates/.github/workflows/bkit-renovate.yml +2 -2
  205. package/.bkit/templates/.husky/pre-push +123 -6
  206. package/.bkit/templates/context/bkit-serena.md +1 -1
  207. package/.bkit/templates/docs/architecture.md +98 -0
  208. package/.bkit/templates/docs/capabilities.md +33 -37
  209. package/.bkit/templates/docs/components.md +142 -0
  210. package/.bkit/templates/docs/data-schema.md +87 -0
  211. package/.bkit/{shared → templates}/docs/deployments.md +128 -142
  212. package/.bkit/templates/docs/design.md +117 -0
  213. package/.bkit/templates/docs/noise.md +54 -0
  214. package/.bkit/templates/docs/observability.md +99 -0
  215. package/.bkit/templates/docs/security.md +137 -0
  216. package/.bkit/templates/docs/setup.md +93 -0
  217. package/.bkit/templates/docs/technology.md +70 -0
  218. package/.bkit/{shared → templates}/docs/testing.md +200 -87
  219. package/.bkit/templates/scripts/ci/bkit-machine-lock.sh +511 -103
  220. package/.bkit/templates/scripts/ci/bkit-test-awake.mjs +228 -35
  221. package/.bkit/templates/scripts/ci/bkit-test-awake.test.mjs +270 -2
  222. package/.bkit/templates/scripts/graphify/bkit-graphify-graphml.py +1 -1
  223. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +92 -63
  224. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +59 -11
  225. package/.bkit/templates/slop-scan.config.json +2 -0
  226. package/CHANGELOG.md +64 -0
  227. package/DETAILS.md +24 -19
  228. package/README.md +1 -1
  229. package/dist/checks/after/auth.js +114 -46
  230. package/dist/checks/after/github.js +77 -35
  231. package/dist/checks/after/index.js +12 -3
  232. package/dist/checks/after/tools.js +224 -1
  233. package/dist/checks/before/files.js +59 -1
  234. package/dist/checks/before/index.js +7 -1
  235. package/dist/checks/status-holes.js +20 -21
  236. package/dist/checks/tips/catalogue.js +99 -10
  237. package/dist/checks/tips/detect.js +35 -3
  238. package/dist/checks/tips/index.js +1 -1
  239. package/dist/cli.js +13 -13
  240. package/dist/commands/ci/ci.js +56 -12
  241. package/dist/commands/ci/push-gate.js +79 -44
  242. package/dist/commands/install/install.js +23 -22
  243. package/dist/commands/install/uninstall.js +36 -30
  244. package/dist/commands/install/upgrade.js +10 -2
  245. package/dist/commands/land.js +2 -3
  246. package/dist/commands/lib.js +323 -25
  247. package/dist/commands/workflow/branches.js +312 -72
  248. package/dist/commands/workflow/challenge.js +66 -13
  249. package/dist/commands/workflow/context.js +46 -10
  250. package/dist/commands/workflow/counters.js +231 -23
  251. package/dist/commands/workflow/decisions.js +221 -106
  252. package/dist/commands/workflow/disk.js +2 -1
  253. package/dist/commands/workflow/feature-base.js +60 -0
  254. package/dist/commands/workflow/issues.js +243 -15
  255. package/dist/commands/workflow/junit.js +137 -0
  256. package/dist/commands/workflow/ledgers.js +726 -112
  257. package/dist/commands/workflow/locks.js +150 -29
  258. package/dist/commands/workflow/loops.js +67 -0
  259. package/dist/commands/workflow/open-decision.js +199 -0
  260. package/dist/commands/workflow/plan-blocks.js +6 -0
  261. package/dist/commands/workflow/plans.js +1 -1
  262. package/dist/commands/workflow/prs.js +272 -16
  263. package/dist/commands/workflow/repo.js +1 -1
  264. package/dist/commands/workflow/run-facts.js +6 -0
  265. package/dist/commands/workflow/runs.js +747 -155
  266. package/dist/commands/workflow/runtime.js +8 -4
  267. package/dist/commands/workflow/status.js +259 -13
  268. package/dist/commands/workflow/step-table.js +41 -15
  269. package/dist/commands/workflow/steps.js +530 -26
  270. package/dist/commands/workflow/summary-findings.js +1 -1
  271. package/dist/commands/workflow/summary.js +289 -8
  272. package/dist/commands/workflow/tasks.js +294 -27
  273. package/dist/commands/workflow/tests-base.js +266 -0
  274. package/dist/commands/workflow/tests-changed.js +130 -56
  275. package/dist/commands/workflow/tests-jump.js +77 -0
  276. package/dist/commands/workflow/tests.js +608 -131
  277. package/dist/commands/workflow/tracker.js +920 -112
  278. package/dist/commands/workflow/workflows.js +80 -59
  279. package/dist/commands/workflow/worktrees.js +387 -58
  280. package/dist/install/cloud-env.js +32 -10
  281. package/dist/install/managed-block.js +101 -0
  282. package/dist/install/manifest.js +7 -1
  283. package/dist/install/modules/claude.js +6 -2
  284. package/dist/install/modules/cloud.js +73 -86
  285. package/dist/install/modules/codex.js +9 -2
  286. package/dist/install/modules/core.js +133 -14
  287. package/dist/install/modules/opencode.js +18 -23
  288. package/dist/install/network-allowlist.js +8 -3
  289. package/dist/install/project-docs.js +551 -0
  290. package/dist/install/template-copies.js +55 -5
  291. package/dist/install/write.js +117 -5
  292. package/dist/ledgers/journal.js +10 -8
  293. package/dist/ledgers/migrate.js +20 -9
  294. package/dist/ledgers/status.js +461 -8
  295. package/dist/ledgers/telemetry.js +71 -13
  296. package/dist/render/trackers.js +3 -1
  297. package/dist/shared/package-manager.js +7 -2
  298. package/dist/shared/settings.js +8 -0
  299. package/dist/shared/text.js +13 -0
  300. package/dist/tools/instructions-sources.js +1 -0
  301. package/dist/tools/instructions.js +97 -24
  302. package/package.json +22 -15
  303. package/.bkit/core/hooks/preflight-linear.sh +0 -73
  304. package/.bkit/shared/docs/architecture.md +0 -16
  305. package/.bkit/shared/docs/data-schema.md +0 -16
  306. package/.bkit/shared/docs/design.md +0 -38
  307. package/.bkit/shared/docs/noise.md +0 -20
  308. package/.bkit/shared/docs/observability.md +0 -22
  309. package/.bkit/shared/docs/security.md +0 -62
  310. package/.bkit/shared/docs/setup.md +0 -52
  311. package/.bkit/shared/docs/technology.md +0 -15
  312. /package/.bkit/templates/{.lintstagedrc.json → lintstagedrc.example.json} +0 -0
  313. /package/.bkit/templates/{.prettierignore → prettierignore.example} +0 -0
@@ -14,6 +14,7 @@
14
14
  // `parentSha` is captured at step START via `git rev-parse HEAD`, BEFORE the
15
15
  // step's own commit (if any). Forensic only — points to the commit that preceded
16
16
  // this step's work, not the commit that resulted from it.
17
+ import { spawnSync } from "node:child_process";
17
18
  import { createHash } from "node:crypto";
18
19
  import * as fs from "node:fs";
19
20
  import * as path from "node:path";
@@ -55,6 +56,11 @@ export function validateCiSelection(value) {
55
56
  ["failure", "timed_out", "startup_failure"].includes(stringField("conclusion")) &&
56
57
  Array.isArray(v.redTiers) &&
57
58
  v.redTiers.every((tier) => CI_TIERS.some((known) => known === tier)) &&
59
+ (v.failedJobCount === undefined ||
60
+ (Number.isSafeInteger(v.failedJobCount) && Number(v.failedJobCount) > 0)) &&
61
+ (v.failedJobs === undefined ||
62
+ (Array.isArray(v.failedJobs) &&
63
+ v.failedJobs.every((name) => typeof name === "string" && name.length > 0))) &&
58
64
  typeof v.via === "string" &&
59
65
  v.via.trim().length > 0);
60
66
  }
@@ -72,18 +78,160 @@ export function ciSelectionIdentity(selection) {
72
78
  selection.headSha,
73
79
  ]);
74
80
  }
81
+ export const CI_HANDOFF_RESULTS = [
82
+ "none",
83
+ "pending",
84
+ "success",
85
+ "failure",
86
+ "provider-error",
87
+ ];
88
+ export const CI_RETRIGGER_STATES = [
89
+ "intended",
90
+ "commit-created",
91
+ "push-completed",
92
+ "receipt-completed",
93
+ ];
94
+ const SHA_RE = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
95
+ const REPO_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9][A-Za-z0-9_.-]*$/;
96
+ const isRecord = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
97
+ const isCount = (v) => Number.isSafeInteger(v) && Number(v) >= 0;
98
+ const nonEmpty = (v) => typeof v === "string" && v.trim().length > 0;
99
+ function validHandoffTarget(value) {
100
+ if (!isRecord(value))
101
+ return false;
102
+ return (value.provider === "github" &&
103
+ typeof value.repo === "string" &&
104
+ REPO_RE.test(value.repo) &&
105
+ (value.pr === null || (typeof value.pr === "string" && /^[1-9][0-9]*$/.test(value.pr))) &&
106
+ typeof value.head === "string" &&
107
+ SHA_RE.test(value.head) &&
108
+ nonEmpty(value.branch));
109
+ }
110
+ function validRetrigger(value) {
111
+ if (!isRecord(value))
112
+ return false;
113
+ const state = CI_RETRIGGER_STATES.find((s) => s === value.state);
114
+ if (state === undefined)
115
+ return false;
116
+ if (typeof value.original !== "string" || !SHA_RE.test(value.original))
117
+ return false;
118
+ const sha = (k) => typeof value[k] === "string" && SHA_RE.test(value[k]);
119
+ if (value.copy !== undefined && !sha("copy"))
120
+ return false;
121
+ if (state === "intended")
122
+ return true;
123
+ if (!sha("commit"))
124
+ return false;
125
+ if (state === "commit-created")
126
+ return true;
127
+ if (!nonEmpty(value.ref) || !sha("remote"))
128
+ return false;
129
+ if (state === "push-completed")
130
+ return true;
131
+ return nonEmpty(value.receipt);
132
+ }
133
+ /** Validate one `ci-handoff` row before any reader treats it as evidence. */
134
+ export function validateCiHandoffEvent(value) {
135
+ if (!isRecord(value) || value.type !== "ci-handoff")
136
+ return false;
137
+ if (!nonEmpty(value.workflow) || !nonEmpty(value.at))
138
+ return false;
139
+ if (value.phase !== "poll" && value.phase !== "repoll")
140
+ return false;
141
+ if (!validHandoffTarget(value.target))
142
+ return false;
143
+ const o = value.observation;
144
+ if (!isRecord(o))
145
+ return false;
146
+ if (!CI_HANDOFF_RESULTS.some((r) => r === o.result))
147
+ return false;
148
+ if (!isCount(o.attempts) || !isCount(o.errors) || o.errors > o.attempts)
149
+ return false;
150
+ if (value.retrigger !== undefined && !validRetrigger(value.retrigger))
151
+ return false;
152
+ return value.phase !== "repoll" || value.retrigger !== undefined;
153
+ }
154
+ /** Wording and transport do not change which target a handoff row is about. */
155
+ export function ciHandoffIdentity(target) {
156
+ return JSON.stringify([
157
+ target.provider,
158
+ target.repo.toLowerCase(),
159
+ target.pr,
160
+ target.head,
161
+ target.branch,
162
+ ]);
163
+ }
164
+ /**
165
+ * The cumulative handoff state of one target: de-dupes, orders by `at`, counts rows for other
166
+ * targets as `stale` and rows whose cumulative counts go backwards as `invalid`.
167
+ */
168
+ export function foldCiHandoff(rows, target) {
169
+ const seen = new Set();
170
+ const events = [];
171
+ for (const row of rows) {
172
+ if (!validateCiHandoffEvent(row))
173
+ continue;
174
+ const key = JSON.stringify(row);
175
+ if (seen.has(key))
176
+ continue;
177
+ seen.add(key);
178
+ events.push(row);
179
+ }
180
+ const ordered = events
181
+ .map((e, i) => ({ e, i }))
182
+ .sort((a, b) => (a.e.at < b.e.at ? -1 : a.e.at > b.e.at ? 1 : a.i - b.i))
183
+ .map((x) => x.e);
184
+ const want = ciHandoffIdentity(target);
185
+ const state = {
186
+ phase: "poll",
187
+ attempts: 0,
188
+ errors: 0,
189
+ last: null,
190
+ retrigger: null,
191
+ retriggerBase: null,
192
+ stale: 0,
193
+ invalid: 0,
194
+ };
195
+ for (const e of ordered) {
196
+ if (ciHandoffIdentity(e.target) !== want) {
197
+ state.stale += 1;
198
+ continue;
199
+ }
200
+ if (e.observation.attempts < state.attempts || e.observation.errors < state.errors) {
201
+ state.invalid += 1;
202
+ continue;
203
+ }
204
+ state.attempts = e.observation.attempts;
205
+ state.errors = e.observation.errors;
206
+ state.phase = e.phase;
207
+ state.last = { result: e.observation.result, at: e.at };
208
+ if (e.retrigger !== undefined) {
209
+ state.retriggerBase ??= { attempts: e.observation.attempts, errors: e.observation.errors };
210
+ state.retrigger = e.retrigger;
211
+ }
212
+ }
213
+ return state;
214
+ }
75
215
  /** Validate the bounded CI evidence variant without relaxing local exit codes. */
76
216
  export function testRunProblem(value) {
77
217
  if (!value || typeof value !== "object")
78
218
  return "test-run must be an object";
79
219
  const r = value;
80
220
  const positive = (v) => Number.isSafeInteger(v) && Number(v) > 0;
221
+ if (r.failedTests !== undefined &&
222
+ (!Array.isArray(r.failedTests) ||
223
+ !r.failedTests.every((name) => typeof name === "string" && name !== "")))
224
+ return "failedTests must be an array of non-empty strings";
225
+ if (r.failedTestsTruncated !== undefined && typeof r.failedTestsTruncated !== "boolean")
226
+ return "failedTestsTruncated must be a boolean";
81
227
  if (r.source === "ci") {
228
+ if (r.tested !== undefined)
229
+ return "a CI evidence round records no tested snapshot";
82
230
  if (r.workflow !== "debug" ||
83
231
  r.step !== "debug-run-tests" ||
84
232
  r.verdict !== "FAIL" ||
85
233
  r.exitCode !== null ||
86
- r.failures !== null ||
234
+ (r.failures !== null && !positive(r.failures)) ||
87
235
  r.gate !== null ||
88
236
  !positive(r.ciGeneration) ||
89
237
  !positive(r.runAttempt) ||
@@ -110,6 +258,8 @@ export function testRunProblem(value) {
110
258
  return "local exitCode must be a non-negative integer";
111
259
  if (r.failures !== null && (!Number.isSafeInteger(r.failures) || Number(r.failures) < 0))
112
260
  return "invalid failure count";
261
+ if (r.tested !== undefined && !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(String(r.tested)))
262
+ return "tested must be a full commit sha";
113
263
  return null;
114
264
  }
115
265
  /** A round belongs to exactly one saved evidence generation. */
@@ -198,6 +348,22 @@ export function fold(events) {
198
348
  }
199
349
  return runs;
200
350
  }
351
+ /** True for a parsed `status.jsonl` row that is a complete `invocation` event. */
352
+ export function isInvocationEvent(value) {
353
+ if (value === null || typeof value !== "object")
354
+ return false;
355
+ const v = value;
356
+ return (v["type"] === "invocation" &&
357
+ typeof v["id"] === "string" &&
358
+ typeof v["workflow"] === "string" &&
359
+ typeof v["step"] === "string" &&
360
+ typeof v["number"] === "number" &&
361
+ typeof v["title"] === "string" &&
362
+ typeof v["run"] === "number" &&
363
+ typeof v["statusPath"] === "string" &&
364
+ typeof v["bookRoot"] === "string" &&
365
+ typeof v["worktree"] === "string");
366
+ }
201
367
  // Serialize one event to the NDJSON line appended to `status.jsonl`, newline included.
202
368
  export function appendLine(event) {
203
369
  return `${JSON.stringify(event)}\n`;
@@ -206,8 +372,8 @@ export function appendLine(event) {
206
372
  // Queries — the reads routing and counters make. Two opposite scopings: attempt
207
373
  // counts and verdict/failures/mode reads look at the ACTIVE
208
374
  // run only, so a resumed run never inherits a finished run's spent budget;
209
- // strategy reads ALL runs, so a resumed run keeps its place on the
210
- // STANDARD -> PIVOT -> FINAL ladder instead of restarting it.
375
+ // strategy reads ALL runs, so a test that also failed in an earlier run's
376
+ // attempt still counts toward the fix round's STANDARD / PIVOT / FINAL label.
211
377
  // ---------------------------------------------------------------------------
212
378
  /** `status.jsonl` timestamp: UTC, whole seconds (`date -u +%FT%TZ`). */
213
379
  export const statusTimestamp = (now = new Date()) => now.toISOString().replace(/\.\d{3}Z$/, "Z");
@@ -226,6 +392,24 @@ export function activeDoneSteps(runs, workflow, f) {
226
392
  return [];
227
393
  return run.steps.filter((s) => matches(s, f));
228
394
  }
395
+ /** A check round that found no problems: verdict PASS, or CONCERNS with 0 failures. */
396
+ export const cleanRound = (s) => s.status === "DONE" && (s.verdict === "PASS" || (s.verdict === "CONCERNS" && s.failures === 0));
397
+ /** The active run's last clean round of `step` (`isClean`, by default `cleanRound`); undefined when none ran. */
398
+ export function lastCleanRound(runs, workflow, step, isClean = cleanRound) {
399
+ return lastRun(runs, workflow)
400
+ ?.steps.filter((s) => s.step === step && isClean(s))
401
+ .at(-1);
402
+ }
403
+ /** `activeDoneSteps` after `clean`'s last clean round (`isClean`): the rounds of the loop still open. */
404
+ export function activeDoneStepsSinceClean(runs, workflow, f, clean, isClean = cleanRound) {
405
+ const run = lastRun(runs, workflow);
406
+ if (!run)
407
+ return [];
408
+ const last = lastCleanRound(runs, workflow, clean, isClean);
409
+ return run.steps
410
+ .slice(last === undefined ? 0 : run.steps.indexOf(last) + 1)
411
+ .filter((s) => matches(s, f));
412
+ }
229
413
  /** DONE rows for the step across ALL runs of `workflow`: debug's limits span every run. */
230
414
  export function allRunsDoneSteps(runs, workflow, f) {
231
415
  return runs
@@ -311,9 +495,278 @@ export function recordAction(file, a) {
311
495
  fs.appendFileSync(file, appendLine(row));
312
496
  return row;
313
497
  }
314
- /** Next rung: none -> STANDARD -> PIVOT -> FINAL, and FINAL stays FINAL. */
315
- export function nextStrategy(prior) {
316
- if (prior === undefined)
317
- return "STANDARD";
318
- return prior === "STANDARD" ? "PIVOT" : "FINAL";
498
+ // ---------------------------------------------------------------------------
499
+ // Ledger operations — a bookkeeping write that must survive a lost response. One
500
+ // operation id names one request (its hash): the same id and hash replays the
501
+ // original receipt, the same id with another hash is refused, and a new id on the
502
+ // same ledger key is a deliberate later update. This is stricter than the generic
503
+ // action policy above, where the same key with a changed hash acts again.
504
+ // ---------------------------------------------------------------------------
505
+ /**
506
+ * The operations store of one book root: `<git common dir>/bkit-outbox/ledger-operations/<root hash>.jsonl`.
507
+ * It holds prepared row bytes, so it stays private (0700 dirs, 0600 file) and outside every committed
508
+ * or unioned path. One file per book root keeps a linked worktree's offsets apart from the main
509
+ * checkout's. Null outside a git repository.
510
+ */
511
+ export function ledgerOperationsFile(root, prepare = false) {
512
+ // Not `commands/lib.ts`: that module imports this one.
513
+ const res = spawnSync("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], {
514
+ cwd: root,
515
+ encoding: "utf-8",
516
+ });
517
+ const common = res.status === 0 ? res.stdout.trim() : "";
518
+ if (common === "")
519
+ return null;
520
+ const outbox = path.join(common, "bkit-outbox");
521
+ const id = createHash("sha256").update(fs.realpathSync(root)).digest("hex").slice(0, 16);
522
+ const file = path.join(outbox, "ledger-operations", `${id}.jsonl`);
523
+ if (prepare)
524
+ privateDir(file);
525
+ return file;
526
+ }
527
+ /** Create the private directory chain of `file`'s parent (0700). */
528
+ function privateDir(file) {
529
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
530
+ }
531
+ /** Intents on `target` of this root with no receipt; none when there is no store. */
532
+ export function pendingLedgerIntentsFor(root, target) {
533
+ const ops = ledgerOperationsFile(root);
534
+ return ops === null ? [] : pendingLedgerIntents(ops, target);
535
+ }
536
+ const ledgerOpKey = (operation) => actionKey("ledger-op", operation);
537
+ /** The status rows of one bounded correction: a guaranteed no-write rejection, a corrected retry, its success. */
538
+ export const CORRECTION_REJECTED_ROW = "correction-rejected";
539
+ export const CORRECTION_CANDIDATE_ROW = "correction-candidate";
540
+ export const CORRECTION_SUCCEEDED_ROW = "correction-succeeded";
541
+ /**
542
+ * The stable scope one rejected sub-step's corrected retries share: derived from the run, step,
543
+ * task group and attempt, the ledger and the sub-step, never from an invocation or operation id,
544
+ * so a new tool call, helper or resume spends from the same budget.
545
+ */
546
+ export function correctionScope(o) {
547
+ return [
548
+ "ledgers-append",
549
+ o.ledger,
550
+ o.substep,
551
+ o.workflow,
552
+ `run${o.run ?? 0}`,
553
+ o.step,
554
+ ...(o.group === null ? [] : [`group${o.group}`]),
555
+ ...(o.attempt === null ? [] : [`attempt${o.attempt}`]),
556
+ ].join(":");
557
+ }
558
+ /** Where `operation` stands in `file`: unseen, done with this request, or used for another. */
559
+ export function ledgerOperation(file, operation, hash) {
560
+ const known = engineActions(file)
561
+ .filter((r) => r.key === ledgerOpKey(operation))
562
+ .at(0);
563
+ if (known === undefined)
564
+ return { state: "new" };
565
+ return { state: known.hash === hash ? "replay" : "conflict", row: known };
566
+ }
567
+ /**
568
+ * Record the receipt of a finished ledger operation. A known operation with the same
569
+ * hash returns its original row unchanged; one with another hash throws and writes nothing.
570
+ * `detail` rides on the row so a replay can return the original effect.
571
+ */
572
+ export function recordLedgerOperation(file, a) {
573
+ const known = ledgerOperation(file, a.operation, a.hash);
574
+ if (known.state === "conflict")
575
+ throw new Error(`ledger operation ${a.operation} was already used for a different request`);
576
+ if (known.state === "replay")
577
+ return known.row;
578
+ const row = {
579
+ ...recordRow({
580
+ action: "ledger-append",
581
+ key: ledgerOpKey(a.operation),
582
+ hash: a.hash,
583
+ ref: a.ref,
584
+ }),
585
+ ...(a.detail === undefined ? {} : { detail: a.detail }),
586
+ };
587
+ privateDir(file);
588
+ fs.appendFileSync(file, appendLine(row), { mode: 0o600 });
589
+ return row;
590
+ }
591
+ const recordRow = (a) => ({ type: ENGINE_ACTION, ...a, at: statusTimestamp() });
592
+ function intentRows(file) {
593
+ if (!fs.existsSync(file))
594
+ return [];
595
+ const out = [];
596
+ for (const line of fs.readFileSync(file, "utf-8").split("\n")) {
597
+ if (line.trim() === "")
598
+ continue;
599
+ const parsed = parseJson(line);
600
+ if (!parsed.ok)
601
+ continue;
602
+ const r = parsed.value;
603
+ if (r?.type === "ledger-intent" && typeof r.operation === "string")
604
+ out.push(r);
605
+ }
606
+ return out;
607
+ }
608
+ /** Record the prepared bytes of an operation before writing them. */
609
+ export function recordLedgerIntent(file, intent) {
610
+ privateDir(file);
611
+ const row = { type: "ledger-intent", ...intent, at: statusTimestamp() };
612
+ fs.appendFileSync(file, `${JSON.stringify(row)}\n`, { mode: 0o600 });
613
+ }
614
+ /** The latest prepared intent of `operation`, or undefined. */
615
+ export function ledgerIntent(file, operation) {
616
+ return intentRows(file)
617
+ .filter((i) => i.operation === operation)
618
+ .at(-1);
619
+ }
620
+ /** Intents on `target` (relative path) whose operation has no receipt: effects not yet confirmed. */
621
+ export function pendingLedgerIntents(file, target) {
622
+ const receipted = new Set(engineActions(file).map((r) => r.key));
623
+ const latest = new Map();
624
+ for (const i of intentRows(file))
625
+ latest.set(i.operation, i);
626
+ return [...latest.values()].filter((i) => i.file === target && !receipted.has(ledgerOpKey(i.operation)));
627
+ }
628
+ /** Create `file` holding `content` only if absent; false when it exists. Other errors throw. */
629
+ export function createExclusive(file, content) {
630
+ let fd;
631
+ try {
632
+ fd = fs.openSync(file, "wx");
633
+ }
634
+ catch (err) {
635
+ // EEXIST is the expected "someone holds it" answer; anything else is a real error.
636
+ if (err.code === "EEXIST")
637
+ return false;
638
+ throw err;
639
+ }
640
+ try {
641
+ fs.writeSync(fd, content);
642
+ }
643
+ finally {
644
+ fs.closeSync(fd);
645
+ }
646
+ return true;
647
+ }
648
+ const sleepSync = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
649
+ /** How long a writer waits for another writer's lock on a ledger before refusing. */
650
+ export const TARGET_LOCK_WAIT_MS = 10_000;
651
+ /**
652
+ * Run `fn` holding the exclusive lock on `target` (`<target>.bkit-lock`). A holder that
653
+ * does not release in time is never reclaimed: the call throws, naming the lock file.
654
+ */
655
+ export function withTargetLock(target, fn, waitMs = TARGET_LOCK_WAIT_MS) {
656
+ const lock = `${target}.bkit-lock`;
657
+ const token = `${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
658
+ fs.mkdirSync(path.dirname(lock), { recursive: true });
659
+ const body = JSON.stringify({ pid: process.pid, at: statusTimestamp(), token });
660
+ const deadline = Date.now() + waitMs;
661
+ while (!createExclusive(lock, body)) {
662
+ if (Date.now() >= deadline) {
663
+ const holder = fs.existsSync(lock) ? fs.readFileSync(lock, "utf-8").trim() : "unknown";
664
+ throw new Error(`ledger target ${target} is locked by another writer (${holder}); if that process is gone, remove ${lock}`);
665
+ }
666
+ sleepSync(20);
667
+ }
668
+ try {
669
+ return fn();
670
+ }
671
+ finally {
672
+ const held = fs.existsSync(lock) ? fs.readFileSync(lock, "utf-8") : "";
673
+ if (held === body)
674
+ fs.rmSync(lock, { force: true });
675
+ }
676
+ }
677
+ /** Append `block` to `target` at exactly `offset`, flush it and read it back; throws on any mismatch. */
678
+ export function writePrepared(target, block, offset) {
679
+ const size = fs.existsSync(target) ? fs.statSync(target).size : 0;
680
+ if (size !== offset)
681
+ throw new Error(`ledger ${target} changed since the append was prepared (${size} != ${offset})`);
682
+ fs.mkdirSync(path.dirname(target), { recursive: true });
683
+ const fd = fs.openSync(target, "a");
684
+ try {
685
+ fs.writeSync(fd, block);
686
+ fs.fsyncSync(fd);
687
+ }
688
+ finally {
689
+ fs.closeSync(fd);
690
+ }
691
+ const bytes = Buffer.byteLength(block);
692
+ const back = Buffer.alloc(bytes);
693
+ const rd = fs.openSync(target, "r");
694
+ try {
695
+ fs.readSync(rd, back, 0, bytes, offset);
696
+ }
697
+ finally {
698
+ fs.closeSync(rd);
699
+ }
700
+ if (back.toString("utf-8") !== block)
701
+ throw new Error(`ledger ${target} read-back disagrees with the bytes just written`);
702
+ }
703
+ /**
704
+ * The one lock-and-confirm append: under the target lock, read the current text, let
705
+ * `prepare` build the rows to add, write them (a missing final newline is closed first)
706
+ * and flush and read them back. Returns where the bytes landed.
707
+ */
708
+ export function appendLocked(target, prepare, hooks = {}) {
709
+ return withTargetLock(target, () => appendHeld(target, prepare, hooks));
710
+ }
711
+ /** {@link appendLocked} for a caller that already holds the target lock. */
712
+ export function appendHeld(target, prepare, hooks = {}) {
713
+ {
714
+ const current = fs.existsSync(target) ? fs.readFileSync(target, "utf-8") : "";
715
+ const body = prepare(current);
716
+ const block = `${current !== "" && !current.endsWith("\n") ? "\n" : ""}${body}`;
717
+ const offset = Buffer.byteLength(current);
718
+ hooks.prepared?.({ offset, block });
719
+ hooks.checkpoint?.("prepared");
720
+ writePrepared(target, block, offset);
721
+ const bytes = Buffer.byteLength(block);
722
+ hooks.checkpoint?.("written");
723
+ hooks.written?.({ offset, bytes, block });
724
+ hooks.checkpoint?.("receipted");
725
+ return { offset, bytes, block };
726
+ }
727
+ }
728
+ /**
729
+ * The next fix round's label, from the tests failing now. Reads the `test-run` rows of one
730
+ * test step across every run of the workflow; the latest row's `failedTests` are the tests
731
+ * failing now. For each, it counts the distinct earlier attempts (run and attempt) whose rows
732
+ * list it; re-runs under one attempt count once, and a row without `failedTests` lists none.
733
+ * Rows with no `attempt` share one key per run, so they count as one attempt.
734
+ * The highest count gives the label: 0 `STANDARD`, 1 `PIVOT`, 2 or more `FINAL`.
735
+ * `repeatTests` holds the tests with a count of 1 or more, in the latest row's order.
736
+ *
737
+ * `current` is the attempt the fix round follows, for a test step that does not run on every
738
+ * round (a group gate runs only after a passing verify). A latest row from an older run or
739
+ * another attempt says nothing about the tests failing now: `STANDARD`, no `repeatTests`.
740
+ */
741
+ export function repeatStrategy(rows, workflow, step, current) {
742
+ let run = 0;
743
+ const attempts = [];
744
+ for (const r of rows) {
745
+ if (r.type === "workflow-started" && r.workflow === workflow)
746
+ run += 1;
747
+ if (r.type !== "test-run" || r.step !== step)
748
+ continue;
749
+ if (r.workflow !== undefined && r.workflow !== workflow)
750
+ continue;
751
+ const tests = Array.isArray(r.failedTests)
752
+ ? r.failedTests.filter((t) => typeof t === "string")
753
+ : [];
754
+ attempts.push({ key: `${run}:${String(r.attempt)}`, run, attempt: r.attempt, tests });
755
+ }
756
+ const latest = attempts.at(-1);
757
+ if (latest === undefined)
758
+ return { strategy: "STANDARD", repeatTests: [] };
759
+ if (current !== undefined && (latest.run !== run || Number(latest.attempt) !== current))
760
+ return { strategy: "STANDARD", repeatTests: [] };
761
+ const earlier = attempts.filter((a) => a.key !== latest.key);
762
+ let highest = 0;
763
+ const repeatTests = [];
764
+ for (const name of new Set(latest.tests)) {
765
+ const count = new Set(earlier.filter((a) => a.tests.includes(name)).map((a) => a.key)).size;
766
+ if (count > 0)
767
+ repeatTests.push(name);
768
+ highest = Math.max(highest, count);
769
+ }
770
+ const strategy = highest === 0 ? "STANDARD" : highest === 1 ? "PIVOT" : "FINAL";
771
+ return { strategy, repeatTests };
319
772
  }
@@ -109,6 +109,7 @@ export function resolveRepoSlug(cwd) {
109
109
  export const SCHEMA = 3;
110
110
  /** The schema {@link normalize} stamps on a row written without one: the shape it builds. */
111
111
  const NORMALIZED_SCHEMA = 2;
112
+ export const MODEL_SOURCES = new Set(["observed", "unavailable"]);
112
113
  export const VALID_KINDS = new Set([
113
114
  "compliance",
114
115
  "outcome",
@@ -235,17 +236,8 @@ export const KIND_WRITERS = {
235
236
  // Utility: a direct chat outside any workflow (`by.step` `manual`), the owner deciding in it.
236
237
  deferral: { subagents: DEFERRAL_WRITERS, orchestrators: new Set(["build", "ship", "utility"]) },
237
238
  failure: { subagents: ANY_WRITER, orchestrators: ANY_WRITER },
238
- knowledge: {
239
- subagents: new Set([
240
- "bkit-build-plan-tests",
241
- "bkit-build-plan-tasks",
242
- "bkit-build-plan-gaps-remediate",
243
- "bkit-debug-failure-remediate",
244
- "bkit-utility-update-knowledge",
245
- ]),
246
- // Utility: a direct chat outside any workflow (`by.step` `manual`), the owner deciding in it.
247
- orchestrators: new Set(["utility"]),
248
- },
239
+ // Any agent on a discovered gotcha (`.agents/rules.md` Discovered gotchas).
240
+ knowledge: { subagents: ANY_WRITER, orchestrators: ANY_WRITER },
249
241
  friction: {
250
242
  subagents: new Set(),
251
243
  // Utility: a direct chat outside any workflow (`by.step` `manual`) that meets friction.
@@ -274,7 +266,8 @@ export function writerProblem(row) {
274
266
  if (typeof subagent !== "string" || subagent === "") {
275
267
  return "by.subagent must be a non-empty string";
276
268
  }
277
- if (typeof by["model"] !== "string" || by["model"] === "") {
269
+ const unavailable = by["modelSource"] === "unavailable" && by["model"] === undefined;
270
+ if (!unavailable && (typeof by["model"] !== "string" || by["model"] === "")) {
278
271
  return `subagent ${subagent} row missing by.model (its prompt's frontmatter model:)`;
279
272
  }
280
273
  if (writers.subagents === ANY_WRITER || writers.subagents.has(subagent))
@@ -928,7 +921,7 @@ export function validate(event) {
928
921
  if (typeof by["step"] !== "string" || by["step"] === "") {
929
922
  return { ok: false, reason: "by.step must be a non-empty string" };
930
923
  }
931
- for (const f of ["workflow", "subagent", "model"]) {
924
+ for (const f of ["workflow", "subagent", "model", "configuredModel", "host"]) {
932
925
  if (by[f] !== undefined && (typeof by[f] !== "string" || by[f] === "")) {
933
926
  return { ok: false, reason: `by.${f} must be a non-empty string when present` };
934
927
  }
@@ -936,6 +929,26 @@ export function validate(event) {
936
929
  if (by["model"] !== undefined && by["subagent"] === undefined) {
937
930
  return { ok: false, reason: "by.model is set only on subagent rows" };
938
931
  }
932
+ if (by["modelSource"] !== undefined) {
933
+ if (typeof by["modelSource"] !== "string" || !MODEL_SOURCES.has(by["modelSource"])) {
934
+ return { ok: false, reason: "by.modelSource must be observed|unavailable when present" };
935
+ }
936
+ if (by["subagent"] === undefined) {
937
+ return { ok: false, reason: "by.modelSource is set only on subagent rows" };
938
+ }
939
+ if (by["modelSource"] === "unavailable" && by["model"] !== undefined) {
940
+ return {
941
+ ok: false,
942
+ reason: "by.model must be absent when by.modelSource is unavailable",
943
+ };
944
+ }
945
+ if (by["modelSource"] === "observed" && by["model"] === undefined) {
946
+ return { ok: false, reason: "by.modelSource observed needs by.model" };
947
+ }
948
+ }
949
+ if (by["configuredModel"] !== undefined && by["subagent"] === undefined) {
950
+ return { ok: false, reason: "by.configuredModel is set only on subagent rows" };
951
+ }
939
952
  if (e["references"] !== undefined && !Array.isArray(e["references"])) {
940
953
  return { ok: false, reason: "references must be an array when present" };
941
954
  }
@@ -1264,6 +1277,51 @@ export function fold(events) {
1264
1277
  }
1265
1278
  return state;
1266
1279
  }
1280
+ /** Statuses of the keyed lifecycle kinds: a row with no `status` is ACTIVE. */
1281
+ const DEFAULT_ACTIVE_KINDS = new Set(["decision", "knowledge"]);
1282
+ /**
1283
+ * The canonical ledger read: parse every line (reporting each unreadable one with its line
1284
+ * number), fold with {@link fold}, and only then apply `filter` to the winners, so an older
1285
+ * row a newer winner superseded is never resurrected. Pure and read-only.
1286
+ */
1287
+ export function queryLedger(raw, filter = {}) {
1288
+ const diagnostics = [];
1289
+ const events = [];
1290
+ let lines = 0;
1291
+ raw.split("\n").forEach((text, i) => {
1292
+ const trimmed = text.trim();
1293
+ if (trimmed === "")
1294
+ return;
1295
+ lines++;
1296
+ const obj = parseJson(trimmed);
1297
+ if (!obj.ok)
1298
+ diagnostics.push({ line: i + 1, reason: "malformed-json" });
1299
+ else if (obj.value === null || typeof obj.value !== "object" || Array.isArray(obj.value))
1300
+ diagnostics.push({ line: i + 1, reason: "not-an-object" });
1301
+ else {
1302
+ const row = obj.value;
1303
+ const ts = row["ts"];
1304
+ if (typeof ts !== "number" || !Number.isFinite(ts))
1305
+ diagnostics.push({ line: i + 1, reason: "invalid-timestamp" });
1306
+ else if (typeof row["kind"] !== "string" ||
1307
+ (AGED_KINDS.has(row["kind"]) && (typeof row["key"] !== "string" || row["key"] === "")))
1308
+ diagnostics.push({ line: i + 1, reason: "invalid-identity" });
1309
+ events.push(obj.value);
1310
+ }
1311
+ });
1312
+ const winners = [...fold(events).entries()].sort(([ia, a], [ib, b]) => compareTs(a, b) || (ia < ib ? -1 : ia > ib ? 1 : 0));
1313
+ const rows = winners
1314
+ .map(([, e]) => e)
1315
+ .filter((e) => {
1316
+ if (filter.key !== undefined && e.key !== filter.key)
1317
+ return false;
1318
+ if (filter.status === undefined)
1319
+ return true;
1320
+ const status = e.status ?? (DEFAULT_ACTIVE_KINDS.has(String(e.kind)) ? "ACTIVE" : undefined);
1321
+ return status === filter.status;
1322
+ });
1323
+ return { rows, diagnostics, lines, readRows: events.length };
1324
+ }
1267
1325
  const positiveInt = (v) => Number.isInteger(v) && v > 0 ? v : undefined;
1268
1326
  /**
1269
1327
  * `firstTs` + `updates` of one entry from all of its rows, in any order. A row
@@ -85,7 +85,9 @@ function trimKeptContent(s) {
85
85
  }
86
86
  /** Retain indentation only when the replacement leaves content on its line. */
87
87
  function attachPrefix(prefix, body, head, tail) {
88
- const hardBreak = / {2,}$/.test(prefix) && /\S[^\r\n]*$/.test(head);
88
+ // Only the current line of `head` matters; scanning the whole document prefix is quadratic.
89
+ const lastLine = head.slice(Math.max(head.lastIndexOf("\n"), head.lastIndexOf("\r")) + 1);
90
+ const hardBreak = / {2,}$/.test(prefix) && /\S/.test(lastLine);
89
91
  return !hardBreak && /^[ \t]*(?:\r?\n|$)/.test(body + tail) ? body : prefix + body;
90
92
  }
91
93
  // ---------------------------------------------------------------------------