@cbartens/bkit 0.0.0-stage → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (373) hide show
  1. package/.bkit/README.md +421 -0
  2. package/.bkit/core/.agents/context.md +95 -0
  3. package/.bkit/core/.agents/docs.md +62 -0
  4. package/.bkit/core/.agents/rules.md +147 -0
  5. package/.bkit/core/.agents/skills.md +43 -0
  6. package/.bkit/core/.bkit/LICENSE.md +151 -0
  7. package/.bkit/core/.bkit/README.md +421 -0
  8. package/.bkit/core/.bkit/cloud.md +502 -0
  9. package/.bkit/core/.bkit/comparison.md +318 -0
  10. package/.bkit/core/.bkit/install.md +496 -0
  11. package/.bkit/core/.bkit/jsonl.md +497 -0
  12. package/.bkit/core/.bkit/prompts.md +474 -0
  13. package/.bkit/core/.bkit/providers.md +598 -0
  14. package/.bkit/core/.bkit/templates.md +471 -0
  15. package/.bkit/core/.bkit/trackers.md +95 -0
  16. package/.bkit/core/.bkit/workflows.md +1546 -0
  17. package/.bkit/core/.claude/hooks/bkit-gateguard.cjs +82 -0
  18. package/.bkit/core/.claude/hooks/bkit-guardrails.cjs +93 -0
  19. package/.bkit/core/.claude/hooks/bkit-preflight.sh +74 -0
  20. package/.bkit/core/.codex/hooks/bkit-gateguard.cjs +115 -0
  21. package/.bkit/core/.codex/hooks/bkit-guardrails.cjs +135 -0
  22. package/.bkit/core/.cursor/hooks/bkit-gateguard.cjs +111 -0
  23. package/.bkit/core/.cursor/hooks/bkit-guardrails.cjs +169 -0
  24. package/.bkit/core/.cursor/hooks/bkit-preflight.sh +63 -0
  25. package/.bkit/core/.opencode/plugin/bkit-gateguard.js +225 -0
  26. package/.bkit/core/AGENTS.md +77 -0
  27. package/.bkit/core/LICENSE.md +149 -0
  28. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +272 -0
  29. package/.bkit/core/docs/templates/bkit-audit-adoption.md +223 -0
  30. package/.bkit/core/docs/templates/bkit-audit-agents.md +230 -0
  31. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +227 -0
  32. package/.bkit/core/docs/templates/bkit-audit-analytics.md +266 -0
  33. package/.bkit/core/docs/templates/bkit-audit-annotations.md +230 -0
  34. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +270 -0
  35. package/.bkit/core/docs/templates/bkit-audit-app-store.md +254 -0
  36. package/.bkit/core/docs/templates/bkit-audit-architecture.md +221 -0
  37. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +241 -0
  38. package/.bkit/core/docs/templates/bkit-audit-config.md +230 -0
  39. package/.bkit/core/docs/templates/bkit-audit-cost.md +218 -0
  40. package/.bkit/core/docs/templates/bkit-audit-coverage.md +221 -0
  41. package/.bkit/core/docs/templates/bkit-audit-database.md +229 -0
  42. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +251 -0
  43. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +283 -0
  44. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +268 -0
  45. package/.bkit/core/docs/templates/bkit-audit-documentation.md +280 -0
  46. package/.bkit/core/docs/templates/bkit-audit-duplication.md +253 -0
  47. package/.bkit/core/docs/templates/bkit-audit-failures.md +259 -0
  48. package/.bkit/core/docs/templates/bkit-audit-flakes.md +237 -0
  49. package/.bkit/core/docs/templates/bkit-audit-gates.md +250 -0
  50. package/.bkit/core/docs/templates/bkit-audit-issues.md +273 -0
  51. package/.bkit/core/docs/templates/bkit-audit-llm.md +239 -0
  52. package/.bkit/core/docs/templates/bkit-audit-logs.md +266 -0
  53. package/.bkit/core/docs/templates/bkit-audit-models.md +210 -0
  54. package/.bkit/core/docs/templates/bkit-audit-privacy.md +211 -0
  55. package/.bkit/core/docs/templates/bkit-audit-prompts.md +216 -0
  56. package/.bkit/core/docs/templates/bkit-audit-red-team.md +220 -0
  57. package/.bkit/core/docs/templates/bkit-audit-reliability.md +222 -0
  58. package/.bkit/core/docs/templates/bkit-audit-repo.md +224 -0
  59. package/.bkit/core/docs/templates/bkit-audit-security.md +274 -0
  60. package/.bkit/core/docs/templates/bkit-audit-slop.md +200 -0
  61. package/.bkit/core/docs/templates/bkit-audit-testing.md +270 -0
  62. package/.bkit/core/docs/templates/bkit-audit-usability.md +237 -0
  63. package/.bkit/core/docs/templates/bkit-plan.md +476 -0
  64. package/.bkit/core/engine/checks/after/auth.ts +247 -0
  65. package/.bkit/core/engine/checks/after/ci-yml.ts +739 -0
  66. package/.bkit/core/engine/checks/after/github.ts +424 -0
  67. package/.bkit/core/engine/checks/after/index.ts +556 -0
  68. package/.bkit/core/engine/checks/after/managed.ts +217 -0
  69. package/.bkit/core/engine/checks/after/tools.ts +427 -0
  70. package/.bkit/core/engine/checks/after/vercel.ts +101 -0
  71. package/.bkit/core/engine/checks/before/context-fetch.ts +429 -0
  72. package/.bkit/core/engine/checks/before/env.ts +201 -0
  73. package/.bkit/core/engine/checks/before/files.ts +202 -0
  74. package/.bkit/core/engine/checks/before/index.ts +206 -0
  75. package/.bkit/core/engine/checks/before/mcp.ts +127 -0
  76. package/.bkit/core/engine/checks/before/repo.ts +77 -0
  77. package/.bkit/core/engine/checks/before/version.ts +67 -0
  78. package/.bkit/core/engine/checks/status-holes.ts +479 -0
  79. package/.bkit/core/engine/cli.ts +871 -0
  80. package/.bkit/core/engine/commands/analysis.ts +550 -0
  81. package/.bkit/core/engine/commands/ci/ci.ts +483 -0
  82. package/.bkit/core/engine/commands/comply.ts +415 -0
  83. package/.bkit/core/engine/commands/harvest.ts +459 -0
  84. package/.bkit/core/engine/commands/install/check.ts +70 -0
  85. package/.bkit/core/engine/commands/install/doctor.ts +247 -0
  86. package/.bkit/core/engine/commands/install/install.ts +528 -0
  87. package/.bkit/core/engine/commands/install/uninstall.ts +972 -0
  88. package/.bkit/core/engine/commands/install/upgrade.ts +1026 -0
  89. package/.bkit/core/engine/commands/launch.ts +139 -0
  90. package/.bkit/core/engine/commands/lib.ts +494 -0
  91. package/.bkit/core/engine/commands/registry.ts +53 -0
  92. package/.bkit/core/engine/commands/setup/setup.ts +184 -0
  93. package/.bkit/core/engine/commands/telemetry.ts +32 -0
  94. package/.bkit/core/engine/commands/workflow/branches.ts +1514 -0
  95. package/.bkit/core/engine/commands/workflow/context.ts +961 -0
  96. package/.bkit/core/engine/commands/workflow/counters.ts +268 -0
  97. package/.bkit/core/engine/commands/workflow/fids.ts +243 -0
  98. package/.bkit/core/engine/commands/workflow/issues.ts +675 -0
  99. package/.bkit/core/engine/commands/workflow/ledgers.ts +575 -0
  100. package/.bkit/core/engine/commands/workflow/locks.ts +478 -0
  101. package/.bkit/core/engine/commands/workflow/prs.ts +1087 -0
  102. package/.bkit/core/engine/commands/workflow/repo.ts +220 -0
  103. package/.bkit/core/engine/commands/workflow/roadmap.ts +576 -0
  104. package/.bkit/core/engine/commands/workflow/runs.ts +2140 -0
  105. package/.bkit/core/engine/commands/workflow/runtime.ts +300 -0
  106. package/.bkit/core/engine/commands/workflow/skills.ts +118 -0
  107. package/.bkit/core/engine/commands/workflow/status.ts +455 -0
  108. package/.bkit/core/engine/commands/workflow/steps.ts +1300 -0
  109. package/.bkit/core/engine/commands/workflow/tests.ts +161 -0
  110. package/.bkit/core/engine/commands/workflow/workflows.ts +1573 -0
  111. package/.bkit/core/engine/commands/workflow/workstreams.ts +164 -0
  112. package/.bkit/core/engine/commands/workflow/worktrees.ts +534 -0
  113. package/.bkit/core/engine/install/cloud-env.ts +925 -0
  114. package/.bkit/core/engine/install/managed-block.ts +212 -0
  115. package/.bkit/core/engine/install/manifest.ts +448 -0
  116. package/.bkit/core/engine/install/modules/claude.ts +362 -0
  117. package/.bkit/core/engine/install/modules/cloud.ts +174 -0
  118. package/.bkit/core/engine/install/modules/codex.ts +219 -0
  119. package/.bkit/core/engine/install/modules/core.ts +600 -0
  120. package/.bkit/core/engine/install/modules/cursor.ts +231 -0
  121. package/.bkit/core/engine/install/modules/index.ts +242 -0
  122. package/.bkit/core/engine/install/modules/opencode.ts +573 -0
  123. package/.bkit/core/engine/install/placeholders.ts +108 -0
  124. package/.bkit/core/engine/install/template-copies.ts +119 -0
  125. package/.bkit/core/engine/install/version-file.ts +284 -0
  126. package/.bkit/core/engine/install/write.ts +467 -0
  127. package/.bkit/core/engine/ledgers/clamp-log.ts +32 -0
  128. package/.bkit/core/engine/ledgers/status.ts +213 -0
  129. package/.bkit/core/engine/ledgers/telemetry.ts +1143 -0
  130. package/.bkit/core/engine/render/hosts.ts +372 -0
  131. package/.bkit/core/engine/render/models.ts +323 -0
  132. package/.bkit/core/engine/render/parts.ts +38 -0
  133. package/.bkit/core/engine/render/trackers.ts +170 -0
  134. package/.bkit/core/engine/shared/egress.ts +345 -0
  135. package/.bkit/core/engine/shared/json.ts +16 -0
  136. package/.bkit/core/engine/shared/log-prefix.ts +9 -0
  137. package/.bkit/core/engine/shared/package-json.ts +29 -0
  138. package/.bkit/core/engine/shared/package-manager.ts +38 -0
  139. package/.bkit/core/engine/shared/package-roots.ts +163 -0
  140. package/.bkit/core/engine/shared/protected-paths.ts +164 -0
  141. package/.bkit/core/engine/shared/settings.ts +72 -0
  142. package/.bkit/core/engine/shared/timeouts.ts +20 -0
  143. package/.bkit/core/engine/tools/wording.ts +748 -0
  144. package/.bkit/core/hooks/gateguard-edit-payload.js +18 -0
  145. package/.bkit/core/hooks/gateguard-engine.js +193 -0
  146. package/.bkit/core/hooks/guardrails-shell.js +154 -0
  147. package/.bkit/core/hooks/guardrails-tiers.js +68 -0
  148. package/.bkit/core/hooks/preflight-linear.sh +73 -0
  149. package/.bkit/core/prompts/bkit-audit-generate.md +66 -0
  150. package/.bkit/core/prompts/bkit-build-challenge-1.md +79 -0
  151. package/.bkit/core/prompts/bkit-build-challenge-2.md +81 -0
  152. package/.bkit/core/prompts/bkit-build-challenge-reconcile.md +68 -0
  153. package/.bkit/core/prompts/bkit-build-challenge-remediate.md +70 -0
  154. package/.bkit/core/prompts/bkit-build-challenge-tests.md +73 -0
  155. package/.bkit/core/prompts/bkit-build-install-skills.md +67 -0
  156. package/.bkit/core/prompts/bkit-build-plan-current.md +75 -0
  157. package/.bkit/core/prompts/bkit-build-plan-execute.md +72 -0
  158. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +73 -0
  159. package/.bkit/core/prompts/bkit-build-plan-verify.md +88 -0
  160. package/.bkit/core/prompts/bkit-build-summary.md +93 -0
  161. package/.bkit/core/prompts/bkit-debug-abort-handover.md +90 -0
  162. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +151 -0
  163. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +78 -0
  164. package/.bkit/core/prompts/bkit-debug-failure-soak.md +73 -0
  165. package/.bkit/core/prompts/bkit-debug-summary.md +95 -0
  166. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +72 -0
  167. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +72 -0
  168. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +75 -0
  169. package/.bkit/core/prompts/bkit-design-generate.md +110 -0
  170. package/.bkit/core/prompts/bkit-design-organise.md +85 -0
  171. package/.bkit/core/prompts/bkit-design-review-1.md +121 -0
  172. package/.bkit/core/prompts/bkit-design-review-2.md +111 -0
  173. package/.bkit/core/prompts/bkit-design-spike.md +97 -0
  174. package/.bkit/core/prompts/bkit-design-summary.md +106 -0
  175. package/.bkit/core/prompts/bkit-design-update.md +66 -0
  176. package/.bkit/core/prompts/bkit-plan-complexity-check.md +66 -0
  177. package/.bkit/core/prompts/bkit-plan-complexity-split.md +87 -0
  178. package/.bkit/core/prompts/bkit-plan-generate.md +74 -0
  179. package/.bkit/core/prompts/bkit-plan-review-1.md +90 -0
  180. package/.bkit/core/prompts/bkit-plan-review-2.md +80 -0
  181. package/.bkit/core/prompts/bkit-plan-review-3.md +92 -0
  182. package/.bkit/core/prompts/bkit-plan-scope-check-1.md +84 -0
  183. package/.bkit/core/prompts/bkit-plan-scope-check-2.md +84 -0
  184. package/.bkit/core/prompts/bkit-plan-summary.md +106 -0
  185. package/.bkit/core/prompts/bkit-plan-update.md +68 -0
  186. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +90 -0
  187. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +94 -0
  188. package/.bkit/core/prompts/bkit-ship-summary.md +77 -0
  189. package/.bkit/core/prompts/bkit-ship-update-docs.md +71 -0
  190. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +91 -0
  191. package/.bkit/core/prompts/bkit-utility-update-decisions.md +75 -0
  192. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +76 -0
  193. package/.bkit/core/prompts/bkit-utility-update-documentation.md +61 -0
  194. package/.bkit/core/prompts/bkit-utility-update-failures.md +76 -0
  195. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +75 -0
  196. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +82 -0
  197. package/.bkit/core/workflows/bkit-auto.md +121 -0
  198. package/.bkit/core/workflows/bkit-build.md +802 -0
  199. package/.bkit/core/workflows/bkit-debug.md +642 -0
  200. package/.bkit/core/workflows/bkit-design.md +495 -0
  201. package/.bkit/core/workflows/bkit-plan.md +510 -0
  202. package/.bkit/core/workflows/bkit-ship.md +650 -0
  203. package/.bkit/shared/.bkit/.env.example +108 -0
  204. package/.bkit/shared/.claude/bkit-cloud.md +117 -0
  205. package/.bkit/shared/.claude/settings.json +88 -0
  206. package/.bkit/shared/.codex/hooks.json +26 -0
  207. package/.bkit/shared/.cursor/bkit-cloud.md +84 -0
  208. package/.bkit/shared/.cursor/hooks.json +26 -0
  209. package/.bkit/shared/.cursor/mcp.json +15 -0
  210. package/.bkit/shared/.cursor/rules/bkit-rules.mdc +12 -0
  211. package/.bkit/shared/.gitattributes +37 -0
  212. package/.bkit/shared/.mcp.json +16 -0
  213. package/.bkit/shared/.opencode/opencode.json +62 -0
  214. package/.bkit/shared/CLAUDE.md +11 -0
  215. package/.bkit/shared/LICENSE.md +22 -0
  216. package/.bkit/shared/docs/architecture.md +19 -0
  217. package/.bkit/shared/docs/data-schema.md +19 -0
  218. package/.bkit/shared/docs/deployments.md +438 -0
  219. package/.bkit/shared/docs/design.md +39 -0
  220. package/.bkit/shared/docs/noise.md +19 -0
  221. package/.bkit/shared/docs/observability.md +25 -0
  222. package/.bkit/shared/docs/security.md +42 -0
  223. package/.bkit/shared/docs/setup.md +30 -0
  224. package/.bkit/shared/docs/technology.md +18 -0
  225. package/.bkit/shared/docs/testing.md +413 -0
  226. package/.bkit/shared/gitignore +92 -0
  227. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +192 -0
  228. package/.bkit/templates/.cursor/Dockerfile +68 -0
  229. package/.bkit/templates/.cursor/environment.json +6 -0
  230. package/.bkit/templates/.cursor/settings.json +11 -0
  231. package/.bkit/templates/.envrc +7 -0
  232. package/.bkit/templates/.github/dependabot.yml +52 -0
  233. package/.bkit/templates/.github/renovate.json5 +239 -0
  234. package/.bkit/templates/.github/workflows/bkit-ci.yml +1082 -0
  235. package/.bkit/templates/.github/workflows/bkit-cloud.yml +566 -0
  236. package/.bkit/templates/.github/workflows/bkit-renovate.yml +107 -0
  237. package/.bkit/templates/.graphifyignore +108 -0
  238. package/.bkit/templates/.husky/pre-commit +16 -0
  239. package/.bkit/templates/.husky/pre-push +91 -0
  240. package/.bkit/templates/.lintstagedrc.json +3 -0
  241. package/.bkit/templates/.prettierignore +41 -0
  242. package/.bkit/templates/.serena/project.yml +243 -0
  243. package/.bkit/templates/.vale/styles/House/Filler.yml +11 -0
  244. package/.bkit/templates/.vale/styles/House/Hedging.yml +12 -0
  245. package/.bkit/templates/.vale/styles/House/LLMSlop.yml +13 -0
  246. package/.bkit/templates/.vale/styles/House/Verbose.yml +12 -0
  247. package/.bkit/templates/.vale.ini +67 -0
  248. package/.bkit/templates/LICENSE.md +22 -0
  249. package/.bkit/templates/context/bkit-cloudrun.md +84 -0
  250. package/.bkit/templates/context/bkit-expo.md +186 -0
  251. package/.bkit/templates/context/bkit-github.md +79 -0
  252. package/.bkit/templates/context/bkit-inngest.md +45 -0
  253. package/.bkit/templates/context/bkit-maestro.md +76 -0
  254. package/.bkit/templates/context/bkit-playwright.md +62 -0
  255. package/.bkit/templates/context/bkit-resend.md +36 -0
  256. package/.bkit/templates/context/bkit-sentry.md +65 -0
  257. package/.bkit/templates/context/bkit-serena.md +33 -0
  258. package/.bkit/templates/context/bkit-stripe.md +36 -0
  259. package/.bkit/templates/context/bkit-supabase.md +59 -0
  260. package/.bkit/templates/context/bkit-tavily.md +49 -0
  261. package/.bkit/templates/context/bkit-vercel.md +64 -0
  262. package/.bkit/templates/docs/capabilities.md +72 -0
  263. package/.bkit/templates/scripts/ci/accepted-divergences.json +21 -0
  264. package/.bkit/templates/scripts/ci/check-accepted-divergences.mjs +152 -0
  265. package/.bkit/templates/scripts/ci/check-accepted-divergences.test.mjs +130 -0
  266. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.mjs +98 -0
  267. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.test.mjs +86 -0
  268. package/.bkit/templates/scripts/graphify/bkit-graph-drift-rules.json +23 -0
  269. package/.bkit/templates/scripts/graphify/bkit-graph-drift.py +208 -0
  270. package/.bkit/templates/scripts/graphify/bkit-graph-eager-rules.json +35 -0
  271. package/.bkit/templates/scripts/graphify/bkit-graph-eager.py +236 -0
  272. package/.bkit/templates/scripts/graphify/bkit-graph-external-rules.json +17 -0
  273. package/.bkit/templates/scripts/graphify/bkit-graph-imports.py +290 -0
  274. package/.bkit/templates/scripts/graphify/bkit-graph-pre-push.sh +19 -0
  275. package/.bkit/templates/scripts/graphify/bkit-graph-repair.py +120 -0
  276. package/.bkit/templates/scripts/graphify/bkit-graph-surface.py +232 -0
  277. package/.bkit/templates/scripts/graphify/bkit-graphify-graphml.py +36 -0
  278. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +927 -0
  279. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +351 -0
  280. package/.bkit/templates/scripts/launchd/ai.bkit.launchd.plist +26 -0
  281. package/.bkit/templates/scripts/launchd/bkit-launchd-env.sh +53 -0
  282. package/.bkit/templates/scripts/launchd/launchd.env.example +13 -0
  283. package/.bkit/templates/scripts/prettier/bkit-insert-ignore.mjs +275 -0
  284. package/.bkit/templates/scripts/secrets/bkit-secrets.config.mjs +66 -0
  285. package/.bkit/templates/scripts/secrets/bkit-secrets.mjs +785 -0
  286. package/.bkit/templates/scripts/serena/bkit-serena-mcp.sh +30 -0
  287. package/.bkit/templates/scripts/serena/bkit-serena.mcp.json +9 -0
  288. package/.bkit/templates/scripts/slop/bkit-slop-type-suppression.mjs +286 -0
  289. package/.bkit/templates/slop-scan.config.json +120 -0
  290. package/CHANGELOG.md +1486 -0
  291. package/LICENSE.md +161 -0
  292. package/README.md +185 -2
  293. package/dist/checks/after/auth.js +232 -0
  294. package/dist/checks/after/ci-yml.js +718 -0
  295. package/dist/checks/after/github.js +400 -0
  296. package/dist/checks/after/index.js +447 -0
  297. package/dist/checks/after/managed.js +187 -0
  298. package/dist/checks/after/tools.js +351 -0
  299. package/dist/checks/after/vercel.js +102 -0
  300. package/dist/checks/before/context-fetch.js +426 -0
  301. package/dist/checks/before/env.js +173 -0
  302. package/dist/checks/before/files.js +185 -0
  303. package/dist/checks/before/index.js +162 -0
  304. package/dist/checks/before/mcp.js +111 -0
  305. package/dist/checks/before/repo.js +71 -0
  306. package/dist/checks/before/version.js +60 -0
  307. package/dist/checks/status-holes.js +393 -0
  308. package/dist/cli.js +692 -0
  309. package/dist/commands/analysis.js +325 -0
  310. package/dist/commands/ci/ci.js +438 -0
  311. package/dist/commands/comply.js +310 -0
  312. package/dist/commands/harvest.js +354 -0
  313. package/dist/commands/install/check.js +61 -0
  314. package/dist/commands/install/doctor.js +207 -0
  315. package/dist/commands/install/install.js +461 -0
  316. package/dist/commands/install/uninstall.js +815 -0
  317. package/dist/commands/install/upgrade.js +771 -0
  318. package/dist/commands/launch.js +118 -0
  319. package/dist/commands/lib.js +362 -0
  320. package/dist/commands/registry.js +50 -0
  321. package/dist/commands/setup/setup.js +158 -0
  322. package/dist/commands/telemetry.js +29 -0
  323. package/dist/commands/workflow/branches.js +1265 -0
  324. package/dist/commands/workflow/context.js +846 -0
  325. package/dist/commands/workflow/counters.js +227 -0
  326. package/dist/commands/workflow/fids.js +224 -0
  327. package/dist/commands/workflow/issues.js +585 -0
  328. package/dist/commands/workflow/ledgers.js +472 -0
  329. package/dist/commands/workflow/locks.js +364 -0
  330. package/dist/commands/workflow/prs.js +904 -0
  331. package/dist/commands/workflow/repo.js +199 -0
  332. package/dist/commands/workflow/roadmap.js +495 -0
  333. package/dist/commands/workflow/runs.js +1717 -0
  334. package/dist/commands/workflow/runtime.js +257 -0
  335. package/dist/commands/workflow/skills.js +110 -0
  336. package/dist/commands/workflow/status.js +392 -0
  337. package/dist/commands/workflow/steps.js +1093 -0
  338. package/dist/commands/workflow/tests.js +144 -0
  339. package/dist/commands/workflow/workflows.js +1342 -0
  340. package/dist/commands/workflow/workstreams.js +141 -0
  341. package/dist/commands/workflow/worktrees.js +473 -0
  342. package/dist/install/cloud-env.js +819 -0
  343. package/dist/install/managed-block.js +182 -0
  344. package/dist/install/manifest.js +376 -0
  345. package/dist/install/modules/claude.js +288 -0
  346. package/dist/install/modules/cloud.js +152 -0
  347. package/dist/install/modules/codex.js +193 -0
  348. package/dist/install/modules/core.js +511 -0
  349. package/dist/install/modules/cursor.js +186 -0
  350. package/dist/install/modules/index.js +152 -0
  351. package/dist/install/modules/opencode.js +504 -0
  352. package/dist/install/placeholders.js +87 -0
  353. package/dist/install/template-copies.js +106 -0
  354. package/dist/install/version-file.js +204 -0
  355. package/dist/install/write.js +342 -0
  356. package/dist/ledgers/clamp-log.js +27 -0
  357. package/dist/ledgers/status.js +156 -0
  358. package/dist/ledgers/telemetry.js +637 -0
  359. package/dist/render/hosts.js +339 -0
  360. package/dist/render/models.js +288 -0
  361. package/dist/render/parts.js +33 -0
  362. package/dist/render/trackers.js +135 -0
  363. package/dist/shared/egress.js +299 -0
  364. package/dist/shared/json.js +16 -0
  365. package/dist/shared/log-prefix.js +7 -0
  366. package/dist/shared/package-json.js +22 -0
  367. package/dist/shared/package-manager.js +32 -0
  368. package/dist/shared/package-roots.js +145 -0
  369. package/dist/shared/protected-paths.js +153 -0
  370. package/dist/shared/settings.js +44 -0
  371. package/dist/shared/timeouts.js +19 -0
  372. package/dist/tools/wording.js +680 -0
  373. package/package.json +101 -4
@@ -0,0 +1,748 @@
1
+ // tools/wording.ts — check and sync the shared sentences in `.bkit/wording.md`.
2
+ //
3
+ // Check mode runs in the test suite (`tools/wording.test.ts`); write mode is
4
+ // `pnpm wording:sync`. Same model as prettier: CI checks, the author writes.
5
+ //
6
+ // The unit is the sentence. A clause is matched as a substring of a line, so a
7
+ // list marker, step number, or trailing local text around it never matters.
8
+ // Clause instances carry no markers in the prompts: sync finds them by
9
+ // near-copy similarity and by the clause's `retired` wordings, which is how a
10
+ // wording change reaches every file — edit the clause, move the old text to
11
+ // `retired`, run the sync.
12
+
13
+ import * as fs from "node:fs";
14
+ import * as path from "node:path";
15
+ import { fileURLToPath } from "node:url";
16
+
17
+ import { findLineAnchoredMarkers, selectMarkers } from "../install/managed-block.js";
18
+
19
+ export type Surface = "prompt" | "workflow" | "rules" | "audit";
20
+ export type Mode =
21
+ "required" | "where-used" | "repeatable" | "forbidden" | "if-verdict" | "if-bash";
22
+ export type Position = "first" | "header" | "last";
23
+
24
+ export interface Clause {
25
+ name: string;
26
+ /** Canonical wordings; more than one = exactly one of them is used. */
27
+ texts: string[];
28
+ /** Earlier wordings: never valid, and sync rewrites them to `texts[0]`. */
29
+ retired: string[];
30
+ modes: Partial<Record<Surface, Mode>>;
31
+ /** File basenames (no `.md`) that word this clause differently. */
32
+ except: Set<string>;
33
+ /** Header line for prompts and workflows, in wording-file order among positioned clauses; first / last also open / close the labelled lines. */
34
+ position?: Position;
35
+ /** Slotted clause only: a line holding the fixed text before the first slot must match one of the templates. */
36
+ anchored: boolean;
37
+ }
38
+
39
+ export interface WordingFile {
40
+ surface: Surface;
41
+ /** Repo-relative path. */
42
+ id: string;
43
+ /** Basename without `.md`, matched against `except`. */
44
+ name: string;
45
+ content: string;
46
+ }
47
+
48
+ export interface Finding {
49
+ file: string;
50
+ line?: number;
51
+ clause: string;
52
+ problem: string;
53
+ }
54
+
55
+ /** Near-copy threshold: a sentence this similar to a clause but not equal to it is drift. */
56
+ export const NEAR_COPY = 0.8;
57
+ /** Cut-off per surface: a sentence shared by this many files of one surface belongs in the wording file. */
58
+ export const SHARED_MIN: Partial<Record<Surface, number>> = { prompt: 5, workflow: 3, audit: 5 };
59
+
60
+ const SURFACES: readonly Surface[] = ["prompt", "workflow", "rules", "audit"];
61
+ /** Surfaces whose files open with the CAUTION header that positioned clauses order. */
62
+ const HEADED: readonly Surface[] = ["prompt", "workflow"];
63
+ /** Surfaces checked inside the `bkit:start` / `bkit:end` block only. */
64
+ const MANAGED: readonly Surface[] = ["rules", "audit"];
65
+ const NOUN: Partial<Record<Surface, string>> = {
66
+ prompt: "prompts",
67
+ workflow: "workflows",
68
+ audit: "audit templates",
69
+ };
70
+ const MODES: readonly Mode[] = [
71
+ "required",
72
+ "where-used",
73
+ "repeatable",
74
+ "forbidden",
75
+ "if-verdict",
76
+ "if-bash",
77
+ ];
78
+ const POSITIONS: readonly Position[] = ["first", "header", "last"];
79
+ const VERDICT_END = "<!-- verdict:end -->";
80
+ const SLOT = /\{\{([A-Za-z][\w-]*)(\?)?\}\}/g;
81
+ const LABEL = /^\*\*[^*]+:\*\* /;
82
+ /** Structure, not sentences: headings, HTML comments, table rows. Never counted toward the cut-off. */
83
+ const STRUCTURE = /^(?:#{1,6} |<!--|\|)/;
84
+
85
+ // ---------------------------------------------------------------------------
86
+ // Wording file
87
+ // ---------------------------------------------------------------------------
88
+
89
+ /** Parse `.bkit/wording.md`: one `### name` section per clause under `## Clauses`. */
90
+ export function parseWording(md: string): Clause[] {
91
+ const start = md.indexOf("\n## Clauses\n");
92
+ if (start === -1) throw new Error("[bkit-wording] wording file has no `## Clauses` section");
93
+ const clauses: Clause[] = [];
94
+ for (const section of md.slice(start).split(/^### /m).slice(1)) {
95
+ const name = section.slice(0, section.indexOf("\n")).trim();
96
+ const clause: Clause = {
97
+ name,
98
+ texts: [],
99
+ retired: [],
100
+ modes: {},
101
+ except: new Set(),
102
+ anchored: false,
103
+ };
104
+ for (const m of section.matchAll(/^- ([a-z]+): (.+)$/gm)) {
105
+ const [key, value] = [m[1]!, m[2]!.trim()];
106
+ if ((SURFACES as readonly string[]).includes(key)) {
107
+ if (!(MODES as readonly string[]).includes(value)) {
108
+ throw new Error(`[bkit-wording] ${name}: unknown mode "${value}" for ${key}`);
109
+ }
110
+ clause.modes[key as Surface] = value as Mode;
111
+ } else if (key === "except") {
112
+ for (const f of value.split(",")) clause.except.add(f.trim());
113
+ } else if (key === "position") {
114
+ if (!(POSITIONS as readonly string[]).includes(value)) {
115
+ throw new Error(`[bkit-wording] ${name}: position must be first, header, or last`);
116
+ }
117
+ clause.position = value as Position;
118
+ } else if (key === "anchored") {
119
+ clause.anchored = value === "yes";
120
+ } else {
121
+ throw new Error(`[bkit-wording] ${name}: unknown key "${key}"`);
122
+ }
123
+ }
124
+ for (const m of section.matchAll(/^```(text|retired)\n([\s\S]*?)^```$/gm)) {
125
+ const lines = m[2]!.split("\n").filter((l) => l.trim() !== "");
126
+ if (m[1] === "text") clause.texts.push(...lines);
127
+ else clause.retired.push(...lines);
128
+ }
129
+ if (clause.texts.length === 0) throw new Error(`[bkit-wording] ${name}: no text block`);
130
+ if (Object.keys(clause.modes).length === 0) {
131
+ throw new Error(`[bkit-wording] ${name}: applies to no surface`);
132
+ }
133
+ clauses.push(clause);
134
+ }
135
+ return clauses;
136
+ }
137
+
138
+ // ---------------------------------------------------------------------------
139
+ // Corpus
140
+ // ---------------------------------------------------------------------------
141
+
142
+ const RULES_FILES = [".bkit/core/.agents/rules.md", ".agents/rules.md"];
143
+ /** Audit templates, then the repo's adopted copies (same basenames, same managed block). */
144
+ const AUDIT_DIRS = [".bkit/core/docs/templates", "docs/templates"];
145
+ const AUDIT_FILE = /^bkit-audit-.+\.md$/;
146
+
147
+ /** Every file the wording file governs, read from `root`. */
148
+ export function loadCorpus(root: string): WordingFile[] {
149
+ const files: WordingFile[] = [];
150
+ for (const [surface, dir] of [
151
+ ["prompt", path.join(".bkit", "core", "prompts")],
152
+ ["workflow", path.join(".bkit", "core", "workflows")],
153
+ ] as const) {
154
+ for (const f of fs
155
+ .readdirSync(path.join(root, dir))
156
+ .filter((n) => n.endsWith(".md"))
157
+ .sort()) {
158
+ const id = path.join(dir, f);
159
+ files.push({
160
+ surface,
161
+ id,
162
+ name: f.slice(0, -3),
163
+ content: fs.readFileSync(path.join(root, id), "utf-8"),
164
+ });
165
+ }
166
+ }
167
+ for (const dir of AUDIT_DIRS) {
168
+ if (!fs.existsSync(path.join(root, dir))) continue;
169
+ for (const f of fs
170
+ .readdirSync(path.join(root, dir))
171
+ .filter((n) => AUDIT_FILE.test(n))
172
+ .sort()) {
173
+ const id = path.join(dir, f);
174
+ files.push({
175
+ surface: "audit",
176
+ id,
177
+ name: f.slice(0, -3),
178
+ content: fs.readFileSync(path.join(root, id), "utf-8"),
179
+ });
180
+ }
181
+ }
182
+ for (const id of RULES_FILES) {
183
+ if (!fs.existsSync(path.join(root, id))) continue;
184
+ files.push({
185
+ surface: "rules",
186
+ id,
187
+ name: "rules",
188
+ content: fs.readFileSync(path.join(root, id), "utf-8"),
189
+ });
190
+ }
191
+ return files;
192
+ }
193
+
194
+ /**
195
+ * Indexes of the lines that are prose the clauses govern. Prompts and workflows:
196
+ * everything but front matter and fenced blocks (a fenced example is
197
+ * documentation, not instruction). Rules and audit templates: only the
198
+ * bkit-managed block — the consumer-owned part below `bkit:end` is never bkit's
199
+ * to check or rewrite.
200
+ */
201
+ export function proseLineIndexes(file: WordingFile): number[] {
202
+ const lines = file.content.split("\n");
203
+ let from = 0;
204
+ let to = lines.length;
205
+ if (MANAGED.includes(file.surface)) {
206
+ const [startMarker, endMarker] = selectMarkers("html-comment");
207
+ const starts = findLineAnchoredMarkers(file.content, startMarker);
208
+ const ends = findLineAnchoredMarkers(file.content, endMarker);
209
+ if (starts.length !== 1 || ends.length !== 1) return [];
210
+ from = file.content.slice(0, starts[0]).split("\n").length;
211
+ to = file.content.slice(0, ends[0]).split("\n").length - 1;
212
+ } else if (lines[0] === "---") {
213
+ const close = lines.indexOf("---", 1);
214
+ if (close !== -1) from = close + 1;
215
+ }
216
+ const out: number[] = [];
217
+ let fence: string | null = null;
218
+ for (let i = from; i < to; i++) {
219
+ const line = lines[i]!;
220
+ if (fence !== null) {
221
+ if (new RegExp(`^[ \\t]*${fence}[ \\t]*$`).test(line)) fence = null;
222
+ continue;
223
+ }
224
+ const open = /^[ \t]*(`{3,})[\w-]*[ \t]*$/.exec(line);
225
+ if (open) {
226
+ fence = open[1]!;
227
+ continue;
228
+ }
229
+ out.push(i);
230
+ }
231
+ return out;
232
+ }
233
+
234
+ /** Tool names in the front matter `tools:` list, inline (`[a, b]`) or block (`- a`) form. */
235
+ export function toolsOf(content: string): string[] {
236
+ const lines = content.split("\n");
237
+ if (lines[0] !== "---") return [];
238
+ const close = lines.indexOf("---", 1);
239
+ const front = lines.slice(1, close === -1 ? 1 : close);
240
+ const at = front.findIndex((l) => /^tools:/.test(l));
241
+ if (at === -1) return [];
242
+ const inline = /^tools:[ \t]*\[(.*)\][ \t]*$/.exec(front[at]!);
243
+ if (inline) {
244
+ return inline[1]!
245
+ .split(",")
246
+ .map((t) => t.trim())
247
+ .filter(Boolean);
248
+ }
249
+ const tools: string[] = [];
250
+ for (const line of front.slice(at + 1)) {
251
+ if (/^\S/.test(line)) break;
252
+ const item = /^[ \t]+-[ \t]+(\S+)/.exec(line);
253
+ if (item) tools.push(item[1]!);
254
+ }
255
+ return tools;
256
+ }
257
+
258
+ // ---------------------------------------------------------------------------
259
+ // Matching
260
+ // ---------------------------------------------------------------------------
261
+
262
+ const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
263
+
264
+ interface Compiled {
265
+ re: RegExp;
266
+ slots: string[];
267
+ /** Fixed text before the first slot; the whole text when unslotted. */
268
+ prefix: string;
269
+ slotted: boolean;
270
+ }
271
+
272
+ const compiledCache = new Map<string, Compiled>();
273
+
274
+ export function compileText(text: string): Compiled {
275
+ const hit = compiledCache.get(text);
276
+ if (hit) return hit;
277
+ const slots: string[] = [];
278
+ let source = "";
279
+ let last = 0;
280
+ for (const m of text.matchAll(SLOT)) {
281
+ source += escapeRe(text.slice(last, m.index));
282
+ source += m[2] ? "(.*?)" : "(.+?)";
283
+ slots.push(m[1]!);
284
+ last = m.index! + m[0].length;
285
+ }
286
+ const tail = text.slice(last);
287
+ // A closing `.` also matches `;`: the line continues the sentence with local text.
288
+ source += tail.endsWith(".") ? `${escapeRe(tail.slice(0, -1))}[.;]` : escapeRe(tail);
289
+ const first = text.search(SLOT);
290
+ const compiled = {
291
+ re: new RegExp(source, "g"),
292
+ slots,
293
+ prefix: first === -1 ? text : text.slice(0, first),
294
+ slotted: slots.length > 0,
295
+ };
296
+ compiledCache.set(text, compiled);
297
+ return compiled;
298
+ }
299
+
300
+ const countIn = (line: string, c: Compiled) => [...line.matchAll(c.re)].length;
301
+
302
+ /** Drop the blockquote, list marker, step number, or checkbox in front of a line's text. */
303
+ export const stripLinePrefix = (line: string) =>
304
+ line.replace(/^[ \t]*(?:>[ \t]?)?(?:[ \t]*(?:[-*]|\d+\.)[ \t]+)?(?:\[[ xX]\][ \t]+)?/, "");
305
+
306
+ /** Split after `.` or `;` (bold close allowed between), never after `e.g.`; the punctuation stays on the sentence. */
307
+ export const splitSentences = (s: string) =>
308
+ s
309
+ .split(/(?<!\be\.g\.)(?<=[.;]\**)\s+(?=\S)/)
310
+ .map((x) => x.trim())
311
+ .filter(Boolean);
312
+
313
+ /** Word-level Levenshtein similarity in [0, 1]. */
314
+ export function similarity(a: string, b: string): number {
315
+ const x = a.split(/\s+/);
316
+ const y = b.split(/\s+/);
317
+ let prev = Array.from({ length: y.length + 1 }, (_, j) => j);
318
+ for (let i = 1; i <= x.length; i++) {
319
+ const cur = [i];
320
+ for (let j = 1; j <= y.length; j++) {
321
+ cur[j] = Math.min(
322
+ prev[j]! + 1,
323
+ cur[j - 1]! + 1,
324
+ prev[j - 1]! + (x[i - 1] === y[j - 1] ? 0 : 1),
325
+ );
326
+ }
327
+ prev = cur;
328
+ }
329
+ return 1 - prev[y.length]! / Math.max(x.length, y.length);
330
+ }
331
+
332
+ function modeFor(clause: Clause, file: WordingFile): Mode | undefined {
333
+ if (clause.except.has(file.name)) return undefined;
334
+ const mode = clause.modes[file.surface];
335
+ if (mode === "if-verdict") return file.content.includes(VERDICT_END) ? "required" : "forbidden";
336
+ if (mode === "if-bash") return toolsOf(file.content).includes("Bash") ? "required" : "forbidden";
337
+ return mode;
338
+ }
339
+
340
+ interface NearCopy {
341
+ line: number;
342
+ found: string;
343
+ canonical: string;
344
+ }
345
+
346
+ const siblingCache = new WeakMap<Set<string>, Map<string, string[]>>();
347
+ const lineCache = new Map<string, { sentences: string[]; words: Map<string, number> }>();
348
+
349
+ const wordCounts = (words: string[]) => {
350
+ const counts = new Map<string, number>();
351
+ for (const w of words) counts.set(w, (counts.get(w) ?? 0) + 1);
352
+ return counts;
353
+ };
354
+
355
+ const canonicalCache = new Map<
356
+ string,
357
+ { sentences: number; words: string[]; counts: Map<string, number> }
358
+ >();
359
+
360
+ /** A clause wording's sentence count, words, and word counts; memoised like `lineParts`. */
361
+ function canonicalParts(canonical: string) {
362
+ let hit = canonicalCache.get(canonical);
363
+ if (!hit) {
364
+ const words = canonical.split(/\s+/);
365
+ hit = { sentences: splitSentences(canonical).length, words, counts: wordCounts(words) };
366
+ canonicalCache.set(canonical, hit);
367
+ }
368
+ return hit;
369
+ }
370
+
371
+ /** A line's sentences and word counts, prefix dropped; memoised, since every clause scans every line. */
372
+ function lineParts(line: string) {
373
+ let hit = lineCache.get(line);
374
+ if (!hit) {
375
+ if (lineCache.size > 50_000) lineCache.clear();
376
+ const rest = stripLinePrefix(line);
377
+ hit = { sentences: splitSentences(rest), words: wordCounts(rest.split(/\s+/)) };
378
+ lineCache.set(line, hit);
379
+ }
380
+ return hit;
381
+ }
382
+
383
+ /** Other unslotted clause wordings near enough to `canonical` to read as its near-copy. */
384
+ function siblingsOf(canonical: string, allTexts: Set<string>): string[] {
385
+ let byText = siblingCache.get(allTexts);
386
+ if (!byText) {
387
+ byText = new Map();
388
+ siblingCache.set(allTexts, byText);
389
+ }
390
+ let hit = byText.get(canonical);
391
+ if (!hit) {
392
+ hit = [...allTexts].filter(
393
+ (t) => t !== canonical && !compileText(t).slotted && similarity(t, canonical) >= NEAR_COPY,
394
+ );
395
+ byText.set(canonical, hit);
396
+ }
397
+ return hit;
398
+ }
399
+
400
+ /** Sentence windows in a line that are near, but not equal to, an unslotted clause wording. */
401
+ function nearCopies(
402
+ clause: Clause,
403
+ lineIdx: number,
404
+ line: string,
405
+ allTexts: Set<string>,
406
+ ): NearCopy[] {
407
+ if (clause.texts.some((t) => countIn(line, compileText(t)) > 0)) return [];
408
+ const { sentences, words: lineWords } = lineParts(line);
409
+ const out: NearCopy[] = [];
410
+ for (const canonical of clause.texts) {
411
+ if (compileText(canonical).slotted) continue;
412
+ // A line carrying a sibling clause verbatim (`Gate 2` beside `Gate 3`) is that clause, not drift of this one.
413
+ if (siblingsOf(canonical, allTexts).some((t) => countIn(line, compileText(t)) > 0)) continue;
414
+ const { sentences: k, words: canonicalWords, counts } = canonicalParts(canonical);
415
+ const cw = canonicalWords.length;
416
+ // Every window is drawn from the line's words: too few of the clause's words anywhere → no near-copy.
417
+ let shared = 0;
418
+ for (const [w, n] of counts) shared += Math.min(n, lineWords.get(w) ?? 0);
419
+ if (shared < Math.ceil(NEAR_COPY * cw)) continue;
420
+ // A drift can add or drop a sentence break (`;` turned into `,`): try one sentence fewer and more.
421
+ for (let i = 0; i < sentences.length;) {
422
+ let best: { found: string; size: number; score: number } | undefined;
423
+ for (let size = Math.max(1, k - 1); size <= k + 1 && i + size <= sentences.length; size++) {
424
+ let window = sentences.slice(i, i + size).join(" ");
425
+ // An unlabelled clause can sit behind any surface's own label
426
+ // (`**Tools:**` in a prompt, `**Verify tools:**` in rules): compare the text only.
427
+ if (!canonical.startsWith("**")) window = window.replace(LABEL, "");
428
+ // A clause can close a sentence that opens with local text (`**If** {cond} → {clause}`): also compare the tail.
429
+ const words = window.split(/\s+/);
430
+ const candidates = [window];
431
+ for (const n of [cw - 1, cw, cw + 1]) {
432
+ if (n > 0 && n < words.length) candidates.push(words.slice(-n).join(" "));
433
+ }
434
+ for (const found of candidates) {
435
+ if (allTexts.has(found) || !nearCandidate(found.split(/\s+/), canonicalWords)) continue;
436
+ const score = similarity(found, canonical);
437
+ if (score >= NEAR_COPY && (!best || score > best.score)) best = { found, size, score };
438
+ }
439
+ }
440
+ if (!best) {
441
+ i++;
442
+ continue;
443
+ }
444
+ out.push({ line: lineIdx, found: best.found, canonical });
445
+ i += best.size;
446
+ }
447
+ }
448
+ return out;
449
+ }
450
+
451
+ /** Header line indexes in file order: the CAUTION block through to the body. */
452
+ export function headerLines(content: string): number[] {
453
+ const lines = content.split("\n");
454
+ const start = lines.findIndex((l) => l.startsWith("> [!CAUTION]"));
455
+ if (start === -1) return [];
456
+ const out: number[] = [];
457
+ for (let i = start; i < lines.length; i++) {
458
+ const line = lines[i]!;
459
+ if (line === "---" || /^\*\*/.test(line)) break;
460
+ out.push(i);
461
+ }
462
+ return out;
463
+ }
464
+
465
+ /** Labelled header lines in file order, EXECUTION PROTOCOL excluded. */
466
+ export function headerLabels(content: string): string[] {
467
+ const lines = content.split("\n");
468
+ return headerLines(content)
469
+ .map((i) => lines[i]!.match(/^> (?:- )?\*\*([^*]+):\*\*/)?.[1])
470
+ .filter((l): l is string => l !== undefined && l !== "EXECUTION PROTOCOL");
471
+ }
472
+
473
+ // ---------------------------------------------------------------------------
474
+ // Check
475
+ // ---------------------------------------------------------------------------
476
+
477
+ export function checkWording(clauses: Clause[], files: WordingFile[]): Finding[] {
478
+ const findings: Finding[] = [];
479
+ const allTexts = new Set(clauses.flatMap((c) => c.texts));
480
+ const compiled = new Map(clauses.map((c) => [c, c.texts.map(compileText)]));
481
+
482
+ for (const file of files) {
483
+ const lines = file.content.split("\n");
484
+ const prose = proseLineIndexes(file);
485
+ const headed = HEADED.includes(file.surface);
486
+ const labels = headed ? headerLabels(file.content) : [];
487
+ const header = new Set(headed ? headerLines(file.content) : []);
488
+ const positioned: { clause: Clause; line: number }[] = [];
489
+ const at = (i: number | undefined) => (i === undefined ? undefined : i + 1);
490
+ for (const clause of clauses) {
491
+ const mode = modeFor(clause, file);
492
+ if (mode === undefined) continue;
493
+ const forms = compiled.get(clause)!;
494
+ // Forms can overlap (a slotted form may also fit another's line): a line counts once per instance.
495
+ const perLine = (i: number) => Math.max(...forms.map((c) => countIn(lines[i]!, c)));
496
+ const hits = prose.filter((i) => perLine(i) > 0);
497
+ const count = hits.reduce((n, i) => n + perLine(i), 0);
498
+ if (mode === "forbidden" && count > 0) {
499
+ findings.push({
500
+ file: file.id,
501
+ line: at(hits[0]),
502
+ clause: clause.name,
503
+ problem: "present where it must not be",
504
+ });
505
+ }
506
+ if (mode === "required" && count === 0) {
507
+ findings.push({
508
+ file: file.id,
509
+ clause: clause.name,
510
+ problem: `missing; add: ${clause.texts[0]}`,
511
+ });
512
+ }
513
+ if ((mode === "required" || mode === "where-used") && count > 1) {
514
+ findings.push({
515
+ file: file.id,
516
+ line: at(hits[1]),
517
+ clause: clause.name,
518
+ problem: `appears ${count} times; expected once`,
519
+ });
520
+ }
521
+ if (mode === "forbidden") continue;
522
+
523
+ for (const i of prose) {
524
+ const line = lines[i]!;
525
+ for (const near of nearCopies(clause, i, line, allTexts)) {
526
+ findings.push({
527
+ file: file.id,
528
+ line: near.line + 1,
529
+ clause: clause.name,
530
+ problem: `near-copy (run pnpm wording:sync): "${near.found}"`,
531
+ });
532
+ }
533
+ for (const old of clause.retired) {
534
+ if (countIn(line, compileText(old)) > 0) {
535
+ findings.push({
536
+ file: file.id,
537
+ line: i + 1,
538
+ clause: clause.name,
539
+ problem: "retired wording (run pnpm wording:sync)",
540
+ });
541
+ }
542
+ }
543
+ if (
544
+ clause.anchored &&
545
+ forms.some((c) => c.slotted && line.includes(c.prefix)) &&
546
+ perLine(i) === 0
547
+ ) {
548
+ const templates = clause.texts.filter((t) => compileText(t).slotted);
549
+ findings.push({
550
+ file: file.id,
551
+ line: i + 1,
552
+ clause: clause.name,
553
+ problem: `does not match the template${templates.length > 1 ? "s" : ""}: ${templates.join(" | ")}`,
554
+ });
555
+ }
556
+ }
557
+
558
+ if (clause.position && count > 0 && headed) {
559
+ positioned.push({ clause, line: hits[0]! });
560
+ const label = clause.texts[0]!.match(/^\*\*([^*]+):\*\*/)?.[1];
561
+ const edge = clause.position === "first" ? labels[0] : labels[labels.length - 1];
562
+ if (clause.position !== "header" && label && edge !== label) {
563
+ findings.push({
564
+ file: file.id,
565
+ clause: clause.name,
566
+ problem: `must be the ${clause.position} labelled header line; found "${edge ?? "none"}"`,
567
+ });
568
+ }
569
+ }
570
+ }
571
+
572
+ // Positioned clauses keep wording-file order inside the header.
573
+ let prev: { clause: Clause; line: number } | undefined;
574
+ for (const p of positioned) {
575
+ if (!header.has(p.line)) {
576
+ findings.push({
577
+ file: file.id,
578
+ line: at(p.line),
579
+ clause: p.clause.name,
580
+ problem: "must be a header line",
581
+ });
582
+ continue;
583
+ }
584
+ if (prev && p.line < prev.line) {
585
+ findings.push({
586
+ file: file.id,
587
+ line: at(p.line),
588
+ clause: p.clause.name,
589
+ problem: `header order: must come after ${prev.clause.name}`,
590
+ });
591
+ }
592
+ prev = p;
593
+ }
594
+ }
595
+ return findings.concat(unlistedShared(clauses, files));
596
+ }
597
+
598
+ /** Could two sentences be NEAR_COPY-similar? Cheap word-count and shared-word bounds before `similarity`. */
599
+ function nearCandidate(a: string[], b: string[]): boolean {
600
+ const longer = Math.max(a.length, b.length);
601
+ const need = Math.ceil(NEAR_COPY * longer);
602
+ if (Math.min(a.length, b.length) < need) return false;
603
+ const pool = new Map<string, number>();
604
+ for (const w of b) pool.set(w, (pool.get(w) ?? 0) + 1);
605
+ let shared = 0;
606
+ for (const w of a) {
607
+ const n = pool.get(w) ?? 0;
608
+ if (n > 0) {
609
+ shared++;
610
+ pool.set(w, n - 1);
611
+ }
612
+ }
613
+ return shared >= need;
614
+ }
615
+
616
+ /**
617
+ * Sentences shared by a surface's SHARED_MIN or more files that no clause covers.
618
+ * The cut-off is the rule for what belongs in the wording file. Files count by
619
+ * basename, so an adopted copy never counts twice. Headings, HTML comments, and
620
+ * table rows are structure and never count. A sentence ending its line and
621
+ * the same sentence continued with `;` count as one. Near-copies count toward the
622
+ * cut-off, so one drifted copy cannot hide a sentence the other files share.
623
+ */
624
+ export function unlistedShared(clauses: Clause[], files: WordingFile[]): Finding[] {
625
+ const forms = clauses.flatMap((c) => c.texts.map(compileText));
626
+ const findings: Finding[] = [];
627
+ for (const surface of SURFACES) {
628
+ const min = SHARED_MIN[surface];
629
+ if (min === undefined) continue;
630
+ const seen = new Map<string, Map<string, string>>();
631
+ for (const file of files.filter((f) => f.surface === surface)) {
632
+ const lines = file.content.split("\n");
633
+ for (const i of proseLineIndexes(file)) {
634
+ let rest = stripLinePrefix(lines[i]!);
635
+ if (STRUCTURE.test(rest)) continue;
636
+ for (const c of forms) rest = rest.replace(c.re, "\u0000");
637
+ for (const sentence of splitSentences(rest)) {
638
+ const s = sentence.replace(/[.;]$/, "");
639
+ if (s.includes("\u0000") || s.split(/\s+/).length < 3) continue;
640
+ if (!seen.has(s)) seen.set(s, new Map());
641
+ if (!seen.get(s)!.has(file.name)) seen.get(s)!.set(file.name, file.id);
642
+ }
643
+ }
644
+ }
645
+ findings.push(...sharedGroups(seen, min, NOUN[surface]!));
646
+ }
647
+ return findings;
648
+ }
649
+
650
+ /** Group each sentence with its near-copies; report every group reaching `min` files. */
651
+ function sharedGroups(
652
+ seen: Map<string, Map<string, string>>,
653
+ min: number,
654
+ noun: string,
655
+ ): Finding[] {
656
+ const words = new Map([...seen.keys()].map((s) => [s, s.split(/\s+/)]));
657
+ const reported = new Set<string>();
658
+ const findings: Finding[] = [];
659
+ // Seeds: sentences in 2+ files, widest first, so a group is reported once under its most-copied wording.
660
+ const seeds = [...seen].filter(([, ids]) => ids.size >= 2).sort((a, b) => b[1].size - a[1].size);
661
+ for (const [seed, ids] of seeds) {
662
+ if (reported.has(seed)) continue;
663
+ const near = [...seen.keys()].filter(
664
+ (s) =>
665
+ s !== seed &&
666
+ !reported.has(s) &&
667
+ nearCandidate(words.get(seed)!, words.get(s)!) &&
668
+ similarity(seed, s) >= NEAR_COPY,
669
+ );
670
+ const group = new Set([...ids.keys(), ...near.flatMap((s) => [...seen.get(s)!.keys()])]);
671
+ if (group.size < min) continue;
672
+ for (const s of [seed, ...near]) reported.add(s);
673
+ const drifted = near.length > 0 ? `, ${group.size - ids.size} as near-copies` : "";
674
+ findings.push({
675
+ file: [...ids.values()][0]!,
676
+ clause: "(none)",
677
+ problem: `shared by ${group.size} ${noun}${drifted} but not in .bkit/wording.md: "${seed}"`,
678
+ });
679
+ }
680
+ return findings;
681
+ }
682
+
683
+ // ---------------------------------------------------------------------------
684
+ // Sync
685
+ // ---------------------------------------------------------------------------
686
+
687
+ /** Rewrite near-copies and retired wordings in place. Returns only the files that changed. */
688
+ export function syncWording(clauses: Clause[], files: WordingFile[]): Map<string, string> {
689
+ const changed = new Map<string, string>();
690
+ const allTexts = new Set(clauses.flatMap((c) => c.texts));
691
+ for (const file of files) {
692
+ const lines = file.content.split("\n");
693
+ for (const i of proseLineIndexes(file)) {
694
+ for (const clause of clauses) {
695
+ if (modeFor(clause, file) === undefined || modeFor(clause, file) === "forbidden") continue;
696
+ const target = compileText(clause.texts[0]!);
697
+ for (const old of clause.retired) {
698
+ const from = compileText(old);
699
+ lines[i] = lines[i]!.replace(from.re, (...groups) => {
700
+ const bySlot = new Map(from.slots.map((s, n) => [s, String(groups[n + 1])]));
701
+ const out = clause.texts[0]!.replace(SLOT, (_, slot: string) => bySlot.get(slot) ?? "");
702
+ return String(groups[0]).endsWith(";") && out.endsWith(".")
703
+ ? `${out.slice(0, -1)};`
704
+ : out;
705
+ });
706
+ }
707
+ if (target.slotted) continue;
708
+ for (const near of nearCopies(clause, i, lines[i]!, allTexts)) {
709
+ lines[i] = lines[i]!.replace(near.found, near.canonical);
710
+ }
711
+ }
712
+ }
713
+ const content = lines.join("\n");
714
+ if (content !== file.content) changed.set(file.id, content);
715
+ }
716
+ return changed;
717
+ }
718
+
719
+ // ---------------------------------------------------------------------------
720
+ // CLI: `pnpm wording:sync` (write) / `tsx .bkit/core/engine/tools/wording.ts` (check)
721
+ // ---------------------------------------------------------------------------
722
+
723
+ function main(argv: string[]): number {
724
+ const root = process.cwd();
725
+ const clauses = parseWording(fs.readFileSync(path.join(root, ".bkit/wording.md"), "utf-8"));
726
+ let files = loadCorpus(root);
727
+ if (argv.includes("--write")) {
728
+ const changed = syncWording(clauses, files);
729
+ for (const [id, content] of changed) {
730
+ fs.writeFileSync(path.join(root, id), content, "utf-8");
731
+ console.error(`[bkit-wording] rewrote ${id}`);
732
+ }
733
+ files = loadCorpus(root);
734
+ }
735
+ const findings = checkWording(clauses, files);
736
+ for (const f of findings) {
737
+ console.error(
738
+ `[bkit-wording] ${f.file}${f.line ? `:${f.line}` : ""} ${f.clause}: ${f.problem}`,
739
+ );
740
+ }
741
+ return findings.length === 0 ? 0 : 1;
742
+ }
743
+
744
+ if (process.argv[1] && fs.existsSync(process.argv[1])) {
745
+ if (fs.realpathSync(fileURLToPath(import.meta.url)) === fs.realpathSync(process.argv[1])) {
746
+ process.exitCode = main(process.argv.slice(2));
747
+ }
748
+ }