@cbartens/bkit 5.5.0 → 6.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 (297) hide show
  1. package/.bkit/README.md +30 -20
  2. package/.bkit/core/.agents/docs.md +1 -0
  3. package/.bkit/core/.agents/rules.md +51 -26
  4. package/.bkit/core/.bkit/README.md +29 -19
  5. package/.bkit/core/.bkit/authoring.md +117 -0
  6. package/.bkit/core/.bkit/cloud.md +11 -11
  7. package/.bkit/core/.bkit/comparison.md +5 -5
  8. package/.bkit/core/.bkit/install.md +20 -20
  9. package/.bkit/core/.bkit/jsonl.md +202 -122
  10. package/.bkit/core/.bkit/lite.md +1 -1
  11. package/.bkit/core/.bkit/pipeline.md +49 -52
  12. package/.bkit/core/.bkit/prompts.md +106 -167
  13. package/.bkit/core/.bkit/providers.md +29 -32
  14. package/.bkit/core/.bkit/templates.md +44 -18
  15. package/.bkit/core/.bkit/trackers.md +60 -28
  16. package/.bkit/core/.bkit/workflows.md +399 -359
  17. package/.bkit/core/AGENTS.md +16 -22
  18. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +14 -38
  19. package/.bkit/core/docs/templates/bkit-audit-adoption.md +16 -40
  20. package/.bkit/core/docs/templates/bkit-audit-agents.md +19 -43
  21. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +16 -40
  22. package/.bkit/core/docs/templates/bkit-audit-analytics.md +14 -38
  23. package/.bkit/core/docs/templates/bkit-audit-annotations.md +11 -35
  24. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +15 -39
  25. package/.bkit/core/docs/templates/bkit-audit-app-store.md +12 -36
  26. package/.bkit/core/docs/templates/bkit-audit-architecture.md +16 -40
  27. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +16 -40
  28. package/.bkit/core/docs/templates/bkit-audit-config.md +18 -42
  29. package/.bkit/core/docs/templates/bkit-audit-cost.md +16 -40
  30. package/.bkit/core/docs/templates/bkit-audit-coverage.md +15 -39
  31. package/.bkit/core/docs/templates/bkit-audit-database.md +16 -40
  32. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +15 -39
  33. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +15 -38
  34. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +16 -40
  35. package/.bkit/core/docs/templates/bkit-audit-documentation.md +11 -35
  36. package/.bkit/core/docs/templates/bkit-audit-duplication.md +18 -42
  37. package/.bkit/core/docs/templates/bkit-audit-failures.md +13 -37
  38. package/.bkit/core/docs/templates/bkit-audit-flakes.md +12 -36
  39. package/.bkit/core/docs/templates/bkit-audit-gates.md +14 -38
  40. package/.bkit/core/docs/templates/bkit-audit-issues.md +15 -39
  41. package/.bkit/core/docs/templates/bkit-audit-llm.md +16 -40
  42. package/.bkit/core/docs/templates/bkit-audit-logs.md +14 -38
  43. package/.bkit/core/docs/templates/bkit-audit-models.md +12 -36
  44. package/.bkit/core/docs/templates/bkit-audit-privacy.md +12 -36
  45. package/.bkit/core/docs/templates/bkit-audit-prompts.md +15 -39
  46. package/.bkit/core/docs/templates/bkit-audit-red-team.md +15 -39
  47. package/.bkit/core/docs/templates/bkit-audit-reliability.md +15 -39
  48. package/.bkit/core/docs/templates/bkit-audit-repo.md +12 -36
  49. package/.bkit/core/docs/templates/bkit-audit-security.md +13 -37
  50. package/.bkit/core/docs/templates/bkit-audit-slop.md +14 -38
  51. package/.bkit/core/docs/templates/bkit-audit-testing.md +12 -36
  52. package/.bkit/core/docs/templates/bkit-audit-usability.md +16 -40
  53. package/.bkit/core/docs/templates/bkit-plan.md +97 -226
  54. package/.bkit/core/engine/checks/after/ci-yml.ts +39 -30
  55. package/.bkit/core/engine/checks/after/github.ts +101 -72
  56. package/.bkit/core/engine/checks/after/index.ts +10 -12
  57. package/.bkit/core/engine/checks/after/suppression.ts +8 -5
  58. package/.bkit/core/engine/checks/after/tools.ts +47 -92
  59. package/.bkit/core/engine/checks/before/env.ts +2 -2
  60. package/.bkit/core/engine/checks/before/files.ts +5 -4
  61. package/.bkit/core/engine/checks/before/index.ts +18 -1
  62. package/.bkit/core/engine/checks/before/repo.ts +168 -2
  63. package/.bkit/core/engine/checks/tips/catalogue.ts +16 -5
  64. package/.bkit/core/engine/checks/tips/detect.ts +34 -0
  65. package/.bkit/core/engine/checks/tips/index.ts +10 -7
  66. package/.bkit/core/engine/cli.ts +20 -53
  67. package/.bkit/core/engine/commands/analysis.ts +171 -140
  68. package/.bkit/core/engine/commands/ci/ci.ts +6 -6
  69. package/.bkit/core/engine/commands/comply.ts +77 -103
  70. package/.bkit/core/engine/commands/install/doctor.ts +2 -2
  71. package/.bkit/core/engine/commands/install/install.ts +57 -18
  72. package/.bkit/core/engine/commands/install/uninstall.ts +65 -28
  73. package/.bkit/core/engine/commands/land.ts +18 -12
  74. package/.bkit/core/engine/commands/lib.ts +79 -17
  75. package/.bkit/core/engine/commands/registry.ts +4 -0
  76. package/.bkit/core/engine/commands/setup/setup.ts +7 -7
  77. package/.bkit/core/engine/commands/stats.ts +204 -0
  78. package/.bkit/core/engine/commands/tips.ts +10 -5
  79. package/.bkit/core/engine/commands/workflow/branches.ts +741 -62
  80. package/.bkit/core/engine/commands/workflow/challenge.ts +673 -0
  81. package/.bkit/core/engine/commands/workflow/context.ts +853 -29
  82. package/.bkit/core/engine/commands/workflow/counters.ts +267 -84
  83. package/.bkit/core/engine/commands/workflow/decisions.ts +541 -0
  84. package/.bkit/core/engine/commands/workflow/disk.ts +2 -2
  85. package/.bkit/core/engine/commands/workflow/fids.ts +793 -33
  86. package/.bkit/core/engine/commands/workflow/issues.ts +427 -105
  87. package/.bkit/core/engine/commands/workflow/ledgers.ts +884 -27
  88. package/.bkit/core/engine/commands/workflow/locks.ts +26 -2
  89. package/.bkit/core/engine/commands/workflow/plan-blocks.ts +582 -0
  90. package/.bkit/core/engine/commands/workflow/plan-versions.ts +21 -0
  91. package/.bkit/core/engine/commands/workflow/prs.ts +166 -30
  92. package/.bkit/core/engine/commands/workflow/repo.ts +59 -7
  93. package/.bkit/core/engine/commands/workflow/roadmap.ts +16 -7
  94. package/.bkit/core/engine/commands/workflow/run-facts.ts +501 -0
  95. package/.bkit/core/engine/commands/workflow/runs.ts +179 -49
  96. package/.bkit/core/engine/commands/workflow/runtime.ts +22 -1
  97. package/.bkit/core/engine/commands/workflow/status.ts +142 -29
  98. package/.bkit/core/engine/commands/workflow/step-table.ts +339 -0
  99. package/.bkit/core/engine/commands/workflow/steps.ts +213 -88
  100. package/.bkit/core/engine/commands/workflow/summary.ts +398 -0
  101. package/.bkit/core/engine/commands/workflow/tests.ts +1013 -148
  102. package/.bkit/core/engine/commands/workflow/tracker.ts +1195 -0
  103. package/.bkit/core/engine/commands/workflow/workflows.ts +984 -207
  104. package/.bkit/core/engine/commands/workflow/workstreams.ts +11 -5
  105. package/.bkit/core/engine/commands/workflow/worktrees.ts +276 -22
  106. package/.bkit/core/engine/install/manifest.ts +11 -9
  107. package/.bkit/core/engine/install/modules/cloud.ts +21 -13
  108. package/.bkit/core/engine/install/modules/core.ts +325 -7
  109. package/.bkit/core/engine/install/modules/opencode.ts +2 -2
  110. package/.bkit/core/engine/install/version-file.ts +6 -2
  111. package/.bkit/core/engine/ledgers/migrate.ts +92 -0
  112. package/.bkit/core/engine/ledgers/status.ts +92 -15
  113. package/.bkit/core/engine/ledgers/telemetry.ts +1261 -254
  114. package/.bkit/core/engine/render/hosts.ts +4 -0
  115. package/.bkit/core/engine/render/models.ts +12 -0
  116. package/.bkit/core/engine/shared/branches.ts +4 -1
  117. package/.bkit/core/engine/shared/egress.ts +7 -0
  118. package/.bkit/core/engine/shared/json.ts +25 -7
  119. package/.bkit/core/engine/shared/settings.ts +202 -33
  120. package/.bkit/core/engine/shared/text.ts +361 -0
  121. package/.bkit/core/engine/tools/grammar-density.ts +215 -0
  122. package/.bkit/core/engine/tools/instructions-sources.ts +834 -0
  123. package/.bkit/core/engine/tools/instructions.ts +1751 -0
  124. package/.bkit/core/hooks/gateguard-engine.js +24 -23
  125. package/.bkit/core/hooks/guardrails-shell.js +2 -3
  126. package/.bkit/core/hooks/guardrails-tiers.js +7 -1
  127. package/.bkit/core/hooks/readguard-engine.js +2 -2
  128. package/.bkit/core/prompts/bkit-audit-generate.md +62 -25
  129. package/.bkit/core/prompts/bkit-build-challenge-1.md +40 -17
  130. package/.bkit/core/prompts/bkit-build-challenge-2.md +44 -17
  131. package/.bkit/core/prompts/bkit-build-install-skills.md +26 -13
  132. package/.bkit/core/prompts/bkit-build-plan-convert.md +74 -0
  133. package/.bkit/core/prompts/bkit-build-plan-current.md +26 -13
  134. package/.bkit/core/prompts/bkit-build-plan-execute.md +74 -26
  135. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +64 -23
  136. package/.bkit/core/prompts/bkit-build-plan-verify.md +57 -33
  137. package/.bkit/core/prompts/bkit-debug-abort-handover.md +30 -14
  138. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +34 -14
  139. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +34 -17
  140. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +26 -13
  141. package/.bkit/core/prompts/bkit-debug-failure-soak.md +31 -16
  142. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +21 -11
  143. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +20 -11
  144. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +20 -11
  145. package/.bkit/core/prompts/bkit-design-generate.md +33 -13
  146. package/.bkit/core/prompts/bkit-design-organise.md +25 -12
  147. package/.bkit/core/prompts/bkit-design-review-1.md +31 -15
  148. package/.bkit/core/prompts/bkit-design-review-2.md +28 -13
  149. package/.bkit/core/prompts/bkit-design-spike.md +30 -13
  150. package/.bkit/core/prompts/bkit-design-update.md +33 -19
  151. package/.bkit/core/prompts/bkit-plan-generate.md +75 -19
  152. package/.bkit/core/prompts/bkit-plan-review-1.md +50 -27
  153. package/.bkit/core/prompts/bkit-plan-review-2.md +59 -28
  154. package/.bkit/core/prompts/bkit-plan-scope-check.md +109 -0
  155. package/.bkit/core/prompts/bkit-plan-update.md +61 -24
  156. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +27 -15
  157. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +31 -16
  158. package/.bkit/core/prompts/bkit-ship-update-docs.md +30 -15
  159. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +24 -14
  160. package/.bkit/core/prompts/bkit-utility-update-decisions.md +32 -14
  161. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +29 -14
  162. package/.bkit/core/prompts/bkit-utility-update-documentation.md +28 -13
  163. package/.bkit/core/prompts/bkit-utility-update-failures.md +31 -14
  164. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +33 -14
  165. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +38 -17
  166. package/.bkit/core/prompts/bkit-utility-update-tracker.md +43 -20
  167. package/.bkit/core/workflows/bkit-auto.md +54 -46
  168. package/.bkit/core/workflows/bkit-build.md +577 -458
  169. package/.bkit/core/workflows/bkit-debug.md +348 -333
  170. package/.bkit/core/workflows/bkit-design.md +201 -237
  171. package/.bkit/core/workflows/bkit-plan.md +210 -321
  172. package/.bkit/core/workflows/bkit-ship.md +328 -278
  173. package/.bkit/shared/.bkit/.env.example +2 -2
  174. package/.bkit/shared/.claude/settings.json +11 -0
  175. package/.bkit/shared/.cursor/mcp.json +1 -1
  176. package/.bkit/shared/.cursor/rules/bkit-rules.mdc +1 -1
  177. package/.bkit/shared/.gitattributes +1 -1
  178. package/.bkit/shared/.mcp.json +1 -1
  179. package/.bkit/shared/.opencode/opencode.json +11 -0
  180. package/.bkit/shared/CLAUDE.md +2 -2
  181. package/.bkit/shared/GEMINI.md +2 -2
  182. package/.bkit/shared/docs/architecture.md +1 -1
  183. package/.bkit/shared/docs/data-schema.md +1 -1
  184. package/.bkit/shared/docs/deployments.md +16 -28
  185. package/.bkit/shared/docs/design.md +1 -1
  186. package/.bkit/shared/docs/noise.md +1 -1
  187. package/.bkit/shared/docs/observability.md +2 -2
  188. package/.bkit/shared/docs/security.md +1 -1
  189. package/.bkit/shared/docs/setup.md +1 -1
  190. package/.bkit/shared/docs/technology.md +1 -1
  191. package/.bkit/shared/docs/testing.md +27 -10
  192. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +1 -1
  193. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-change.yml +26 -5
  194. package/.bkit/templates/.github/workflows/bkit-ci.yml +22 -84
  195. package/.bkit/templates/.github/workflows/bkit-cloud.yml +21 -19
  196. package/.bkit/templates/.husky/pre-push +52 -13
  197. package/.bkit/templates/.prettierignore +7 -0
  198. package/.bkit/templates/scripts/ci/bkit-local-stack-lock.sh +194 -0
  199. package/.bkit/templates/scripts/ci/check-capstone.mjs +2 -4
  200. package/.bkit/templates/scripts/ci/check-capstone.test.mjs +4 -23
  201. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.mjs +104 -23
  202. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.test.mjs +103 -6
  203. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.mjs +1 -1
  204. package/.bkit/templates/scripts/graphify/bkit-graph-pre-push.sh +3 -1
  205. package/.bkit/templates/scripts/prettier/bkit-insert-ignore.mjs +49 -29
  206. package/CHANGELOG.md +142 -0
  207. package/README.md +58 -34
  208. package/dist/checks/after/ci-yml.js +39 -29
  209. package/dist/checks/after/github.js +99 -72
  210. package/dist/checks/after/index.js +11 -13
  211. package/dist/checks/after/suppression.js +8 -5
  212. package/dist/checks/after/tools.js +40 -83
  213. package/dist/checks/before/env.js +2 -2
  214. package/dist/checks/before/files.js +5 -3
  215. package/dist/checks/before/index.js +15 -2
  216. package/dist/checks/before/repo.js +163 -2
  217. package/dist/checks/tips/catalogue.js +14 -5
  218. package/dist/checks/tips/detect.js +32 -0
  219. package/dist/checks/tips/index.js +7 -5
  220. package/dist/cli.js +19 -47
  221. package/dist/commands/analysis.js +109 -100
  222. package/dist/commands/ci/ci.js +6 -6
  223. package/dist/commands/comply.js +54 -91
  224. package/dist/commands/install/doctor.js +2 -2
  225. package/dist/commands/install/install.js +50 -19
  226. package/dist/commands/install/uninstall.js +59 -28
  227. package/dist/commands/land.js +16 -12
  228. package/dist/commands/lib.js +51 -16
  229. package/dist/commands/registry.js +4 -0
  230. package/dist/commands/setup/setup.js +7 -7
  231. package/dist/commands/stats.js +136 -0
  232. package/dist/commands/tips.js +7 -3
  233. package/dist/commands/workflow/branches.js +656 -56
  234. package/dist/commands/workflow/challenge.js +556 -0
  235. package/dist/commands/workflow/context.js +709 -30
  236. package/dist/commands/workflow/counters.js +208 -75
  237. package/dist/commands/workflow/decisions.js +441 -0
  238. package/dist/commands/workflow/disk.js +2 -2
  239. package/dist/commands/workflow/fids.js +689 -33
  240. package/dist/commands/workflow/issues.js +362 -99
  241. package/dist/commands/workflow/ledgers.js +762 -27
  242. package/dist/commands/workflow/locks.js +24 -2
  243. package/dist/commands/workflow/plan-blocks.js +437 -0
  244. package/dist/commands/workflow/plan-versions.js +22 -0
  245. package/dist/commands/workflow/prs.js +142 -32
  246. package/dist/commands/workflow/repo.js +52 -7
  247. package/dist/commands/workflow/roadmap.js +9 -7
  248. package/dist/commands/workflow/run-facts.js +426 -0
  249. package/dist/commands/workflow/runs.js +144 -43
  250. package/dist/commands/workflow/runtime.js +12 -1
  251. package/dist/commands/workflow/status.js +130 -29
  252. package/dist/commands/workflow/step-table.js +276 -0
  253. package/dist/commands/workflow/steps.js +171 -80
  254. package/dist/commands/workflow/summary.js +275 -0
  255. package/dist/commands/workflow/tests.js +834 -136
  256. package/dist/commands/workflow/tracker.js +983 -0
  257. package/dist/commands/workflow/workflows.js +834 -195
  258. package/dist/commands/workflow/workstreams.js +11 -5
  259. package/dist/commands/workflow/worktrees.js +221 -22
  260. package/dist/install/manifest.js +11 -9
  261. package/dist/install/modules/cloud.js +22 -13
  262. package/dist/install/modules/core.js +326 -7
  263. package/dist/install/modules/opencode.js +2 -2
  264. package/dist/install/version-file.js +6 -2
  265. package/dist/ledgers/migrate.js +81 -0
  266. package/dist/ledgers/status.js +61 -8
  267. package/dist/ledgers/telemetry.js +905 -124
  268. package/dist/render/hosts.js +4 -0
  269. package/dist/render/models.js +12 -0
  270. package/dist/shared/branches.js +3 -1
  271. package/dist/shared/egress.js +7 -0
  272. package/dist/shared/json.js +20 -7
  273. package/dist/shared/settings.js +147 -26
  274. package/dist/shared/text.js +333 -0
  275. package/dist/tools/grammar-density.js +183 -0
  276. package/dist/tools/instructions-sources.js +721 -0
  277. package/dist/tools/instructions.js +1579 -0
  278. package/package.json +114 -23
  279. package/.bkit/core/engine/commands/harvest.ts +0 -459
  280. package/.bkit/core/engine/tools/wording.ts +0 -748
  281. package/.bkit/core/prompts/bkit-build-challenge-reconcile.md +0 -69
  282. package/.bkit/core/prompts/bkit-build-challenge-remediate.md +0 -71
  283. package/.bkit/core/prompts/bkit-build-challenge-tests.md +0 -74
  284. package/.bkit/core/prompts/bkit-build-summary.md +0 -94
  285. package/.bkit/core/prompts/bkit-debug-summary.md +0 -96
  286. package/.bkit/core/prompts/bkit-design-summary.md +0 -107
  287. package/.bkit/core/prompts/bkit-plan-complexity-check.md +0 -67
  288. package/.bkit/core/prompts/bkit-plan-complexity-split.md +0 -88
  289. package/.bkit/core/prompts/bkit-plan-review-3.md +0 -93
  290. package/.bkit/core/prompts/bkit-plan-scope-check-1.md +0 -85
  291. package/.bkit/core/prompts/bkit-plan-scope-check-2.md +0 -85
  292. package/.bkit/core/prompts/bkit-plan-summary.md +0 -107
  293. package/.bkit/core/prompts/bkit-ship-summary.md +0 -78
  294. package/.bkit/templates/scripts/ci/lanes/check-tree-cache.mjs +0 -138
  295. package/.bkit/templates/scripts/ci/lanes/check-tree-cache.test.mjs +0 -181
  296. package/dist/commands/harvest.js +0 -353
  297. package/dist/tools/wording.js +0 -680
@@ -1,6 +1,7 @@
1
- // bkit fids check|parse|find — feature-id format per tracker, recovering a FID
2
- // from a branch name or a PR-body marker, and finding the feature already logged
3
- // for an issue.
1
+ // bkit fids check|parse|resolve|plans|design|find — feature-id format per tracker,
2
+ // the issue and FID a session prompt names, recovering a FID from a branch name or a
3
+ // PR-body marker, the one FID chain Step 1 resolves, a feature's plan files and its
4
+ // plan inputs, and finding the feature already logged for an issue.
4
5
  //
5
6
  // A FID names the branch (`feat/{FID}`), the log folder and every artifact, so
6
7
  // it is checked before first use. Its shape follows the tracker that minted it:
@@ -9,12 +10,26 @@
9
10
  // jira {project}-{N}-{slug} ^[a-z][a-z0-9]+-[0-9]+-[a-z0-9-]+$ (issue key lowercased first)
10
11
  // none any slug ^[a-z0-9][a-z0-9-]*$ (no tracker shape; still path-safe)
11
12
  // any any tracker's shape ^([0-9]+|[a-z][a-z0-9]*-[0-9]+)-[a-z0-9-]+$ (auto's CI_DEV allowlist)
13
+ // A run with no issue carries an issue-less FID under every tracker. One minted from a
14
+ // prompt is a slug with no all-digit word (`dev-ci-failures`), so it can never parse as an
15
+ // issue id; one taken verbatim from the branch (`feat/upgrade-react-19`) or the prompt is
16
+ // any slug.
17
+ //
18
+ // Minting (`fids resolve`): `{issue}-{slug}` with an issue (Linear / Jira key lowercased),
19
+ // `{branch-suffix}-{slug}` without one. The slug is the first three words of the issue
20
+ // title (the prompt when the title has none, the workflow name when neither has any),
21
+ // ASCII-folded and lowercased, with `STOPWORDS` and all-digit words dropped. The branch
22
+ // suffix is the last `/` segment of the current branch, all-digit words dropped; it does
23
+ // not count toward the three words.
12
24
  import * as fs from "node:fs";
13
25
  import * as path from "node:path";
14
26
  import { parseIssueTracker } from "../../install/manifest.js";
15
- import { CommandError, EXIT, git, repoRoot } from "../lib.js";
27
+ import { CommandError, EXIT, git, parseJson, repoRoot, statusRelPath, } from "../lib.js";
16
28
  import { readBkitConfig } from "../../shared/settings.js";
17
- import { str } from "./status.js";
29
+ import { originOwnerRepo } from "./repo.js";
30
+ import { lastRun } from "../../ledgers/status.js";
31
+ import { monthBuckets, readRunsLenient } from "./locks.js";
32
+ import { WORKFLOW_FLAG, str } from "./status.js";
18
33
  export const FID_PATTERNS = {
19
34
  github: /^[0-9]+-[a-z0-9-]+$/,
20
35
  linear: /^[a-z]+-[0-9]+-[a-z0-9-]+$/,
@@ -28,10 +43,59 @@ const KEYED = new Set(["linear", "jira"]);
28
43
  const ISSUE_KEY = { linear: /^[A-Z]+-[0-9]+$/, jira: /^[A-Z][A-Z0-9]+-[0-9]+$/ };
29
44
  /** The slug every recovered FID must pass before it touches a path (auto's branch fallback). */
30
45
  const SLUG = FID_PATTERNS.none;
46
+ /** An issue-less FID: a slug with no all-digit `-`-separated word, so it never parses as an issue id. */
47
+ export const ISSUE_LESS_FID = /^(?!.*(?:^|-)[0-9]+(?:-|$))[a-z0-9][a-z0-9-]*$/;
48
+ /** The issue id each wired tracker mints (`#` stripped; linear and jira keys are uppercase). */
49
+ export const ISSUE_ID_PATTERNS = {
50
+ github: /^[0-9]+$/,
51
+ linear: /^[A-Z]+-[0-9]+$/,
52
+ jira: /^[A-Z][A-Z0-9]+-[0-9]+$/,
53
+ };
54
+ /**
55
+ * The problem with a FID for the tracker and the run's issue, or undefined when it is valid.
56
+ * `issue` absent: the tracker's FID shape alone. A non-empty `issue`: the issue id and the
57
+ * FID both match the tracker, and the issue id the FID embeds is that issue. An empty
58
+ * `issue` (a run with no issue): the FID is any slug (a minted one is held to
59
+ * `ISSUE_LESS_FID` by `fids resolve`). The `none` tracker has no issue-id shape, so `issue`
60
+ * is ignored.
61
+ */
62
+ export function fidProblem(fid, tracker, issue) {
63
+ const shape = FID_PATTERNS[tracker];
64
+ const shapeProblem = shape.test(fid)
65
+ ? undefined
66
+ : `FID "${fid}" does not match the ${tracker} shape ${shape.source}`;
67
+ if (issue === undefined || tracker === "none")
68
+ return shapeProblem;
69
+ if (issue === "") {
70
+ return SLUG.test(fid)
71
+ ? undefined
72
+ : `FID "${fid}" is not a slug (${SLUG.source}): a run with no issue needs a lowercase slug`;
73
+ }
74
+ const idShapes = tracker === "any" ? Object.values(ISSUE_ID_PATTERNS) : [ISSUE_ID_PATTERNS[tracker]];
75
+ if (!idShapes.some((re) => re.test(issue))) {
76
+ return `issue "${issue}" is not a ${tracker} issue id`;
77
+ }
78
+ if (shapeProblem !== undefined)
79
+ return shapeProblem;
80
+ const embedded = issueIdOf(fid, tracker);
81
+ return embedded === issue
82
+ ? undefined
83
+ : `FID "${fid}" embeds issue ${embedded ?? "none"}, not the run's issue ${issue}`;
84
+ }
31
85
  /** Exit code: no FID could be recovered from the marker or the branch. */
32
86
  export const EXIT_NO_FID = 3;
33
87
  /** Exit code (find): more than one feature is logged for the issue. */
34
88
  export const EXIT_SEVERAL = 4;
89
+ /** Exit code (resolve): the minted name and every suffix of it are used. */
90
+ export const EXIT_NO_FREE = 5;
91
+ /** Exit code: a file a flag names is missing. */
92
+ export const EXIT_NO_FILE = 7;
93
+ /** Exit code (parse --prompt-file): the prompt names more than one issue. */
94
+ export const EXIT_AMBIGUOUS = 8;
95
+ /** Exit code (resolve): the prompt holds only a bare number, so the FID would mint from the workflow name. */
96
+ export const EXIT_BARE_NUMBER = 9;
97
+ /** The stop message for a prompt that does not say which issue it means. */
98
+ const NAME_THE_ISSUE = "name the issue as #N, its key or its URL";
35
99
  /**
36
100
  * Features already logged for an issue: every `docs/plans/{YYYYMM}/logs/{issue}-*`
37
101
  * folder, the issue id lowercased (a Linear or Jira FID carries it lowercased). Sorted, unique.
@@ -53,6 +117,291 @@ export function logged(root, issue) {
53
117
  }
54
118
  return [...found].sort();
55
119
  }
120
+ /** Suffixes tried after a minted name that an earlier run used: `-b` … `-z`. */
121
+ const MINT_SUFFIXES = [..."bcdefghijklmnopqrstuvwxyz"];
122
+ /**
123
+ * The FID a minted issue-less run takes: `fid` itself, or the first of `fid-b`, `fid-c`, ...
124
+ * that no earlier run used. A name is used when it has a log folder (any month bucket) in
125
+ * one of `roots` whose last `workflow` run is not IN_PROGRESS; an in-progress one is
126
+ * continued. null when every name is used.
127
+ */
128
+ export function freeFid(roots, fid, workflow) {
129
+ for (const name of [fid, ...MINT_SUFFIXES.map((x) => `${fid}-${x}`)]) {
130
+ let used = false;
131
+ for (const root of roots) {
132
+ for (const month of monthBuckets(root, name)) {
133
+ const run = lastRun(readRunsLenient(path.join(root, statusRelPath(month, name))), workflow);
134
+ if (run?.status === "IN_PROGRESS")
135
+ return name;
136
+ used = true;
137
+ }
138
+ }
139
+ if (!used)
140
+ return name;
141
+ }
142
+ return null;
143
+ }
144
+ /** A file a flag names, or exit 7 when it is missing. */
145
+ function readNamed(file, flag) {
146
+ if (!fs.existsSync(file) || !fs.statSync(file).isFile())
147
+ throw new CommandError(EXIT_NO_FILE, `--${flag}: no file at ${file}`);
148
+ return fs.readFileSync(file, "utf-8");
149
+ }
150
+ /** The issue title a `--title-file` holds: a JSON object's `title`, else the text itself. */
151
+ export function titleOf(text) {
152
+ const parsed = parseJson(text);
153
+ if (parsed.ok && typeof parsed.value === "object" && parsed.value !== null) {
154
+ const title = parsed.value.title;
155
+ if (typeof title === "string")
156
+ return title;
157
+ }
158
+ return text.trim();
159
+ }
160
+ /** English words a minted slug drops. */
161
+ export const STOPWORDS = new Set(("a about after all also an and any are as at be been before being but by can could " +
162
+ "did do does doing for from had has have he her his how i if in into is it its just " +
163
+ "let me more most my no nor not now of off on once only or other our out over per " +
164
+ "please same she should so some such than that the their them then there these they " +
165
+ "this those through to too under until up us very via was we were what when where " +
166
+ "which while who why will with would you your").split(" "));
167
+ /**
168
+ * The slug words of free text in order: URLs, `<tags>` and `/commands` removed, letters
169
+ * folded to ASCII, lowercased, split on anything else; stopwords and all-digit words dropped.
170
+ */
171
+ export function slugWords(text) {
172
+ return text
173
+ .replace(/\S+:\/\/\S+/g, " ")
174
+ .replace(/<[^>]*>/g, " ")
175
+ .replace(/(^|\s)\/\S+/g, " ")
176
+ .normalize("NFKD")
177
+ .replace(/[\u0300-\u036f]/g, "")
178
+ .toLowerCase()
179
+ .split(/[^a-z0-9]+/)
180
+ .filter((w) => w !== "" && !STOPWORDS.has(w) && !/^[0-9]+$/.test(w));
181
+ }
182
+ /** The FID a run mints; see the header comment for the rules. */
183
+ export function mintFid(o) {
184
+ const fromTitle = slugWords(o.title ?? "");
185
+ const words = (fromTitle.length > 0 ? fromTitle : slugWords(o.prompt)).slice(0, 3);
186
+ const slug = (words.length > 0 ? words : [o.workflow ?? "feature"]).join("-");
187
+ if (o.issue !== "")
188
+ return `${o.issue.replace(/^#/, "").toLowerCase()}-${slug}`;
189
+ const suffix = (o.branch ?? "")
190
+ .split("/")
191
+ .at(-1)
192
+ .toLowerCase()
193
+ .split(/[^a-z0-9]+/)
194
+ .filter((w) => w !== "" && !/^[0-9]+$/.test(w));
195
+ return [...suffix, slug].join("-");
196
+ }
197
+ const MONTH = /^[0-9]{6}$/;
198
+ /** Every `docs/plans/{YYYYMM}/logs/{name}` folder name under the roots. */
199
+ function loggedNames(roots) {
200
+ const names = new Set();
201
+ for (const root of roots) {
202
+ const plans = path.join(root, "docs", "plans");
203
+ if (!fs.existsSync(plans))
204
+ continue;
205
+ for (const month of fs.readdirSync(plans).filter((m) => MONTH.test(m))) {
206
+ const logs = path.join(plans, month, "logs");
207
+ if (!fs.existsSync(logs))
208
+ continue;
209
+ for (const name of fs.readdirSync(logs)) {
210
+ if (fs.statSync(path.join(logs, name)).isDirectory())
211
+ names.add(name);
212
+ }
213
+ }
214
+ }
215
+ return names;
216
+ }
217
+ /** Features logged for an issue on `origin/dev` (else local `dev`), read from git, not the working tree. */
218
+ export function loggedOnDev(cwd, issue) {
219
+ const ref = git(cwd, ["rev-parse", "--verify", "-q", "origin/dev"]) ? "origin/dev" : "dev";
220
+ const out = git(cwd, ["ls-tree", "-r", "-d", "--name-only", ref, "--", "docs/plans"]);
221
+ if (!out)
222
+ return [];
223
+ const key = `${issue.replace(/^#/, "").toLowerCase()}-`;
224
+ const found = new Set();
225
+ for (const line of out.split("\n")) {
226
+ const m = /^docs\/plans\/[0-9]{6}\/logs\/([^/]+)$/.exec(line.trim());
227
+ if (m && m[1].startsWith(key))
228
+ found.add(m[1]);
229
+ }
230
+ return [...found].sort();
231
+ }
232
+ function hits(text, re, map) {
233
+ const out = [];
234
+ for (const m of text.matchAll(re)) {
235
+ const value = map(m);
236
+ if (value !== null)
237
+ out.push({ value, at: m.index });
238
+ }
239
+ return out;
240
+ }
241
+ /** The line text before a `#N` ends in a CSS colour property (`color: `, `background-color: `). */
242
+ const CSS_COLOUR_LEAD = /(?:colou?r|background|border|fill|stroke|outline|shadow)[\w-]*\s*:\s*$/i;
243
+ /** A `#N` hit that is a 3- or 6-digit CSS colour (`color: #123456`), not an issue. */
244
+ function cssColour(text, h) {
245
+ if (h.value.length !== 3 && h.value.length !== 6)
246
+ return false;
247
+ return CSS_COLOUR_LEAD.test(text.slice(text.lastIndexOf("\n", h.at) + 1, h.at));
248
+ }
249
+ const byPosition = (a, b) => a.at - b.at;
250
+ /** Start and end of every match of `re` in `text`. */
251
+ const spans = (text, re) => [...text.matchAll(re)].map((m) => [m.index, m.index + m[0].length]);
252
+ /** The host of a URL or bare host, lowercased: `https://Acme.atlassian.net/` -> `acme.atlassian.net`. */
253
+ const hostOf = (site) => site
254
+ .replace(/^[a-z][a-z0-9+.-]*:\/\//i, "")
255
+ .split("/")[0]
256
+ .toLowerCase();
257
+ /** A URL in prose: a bare key or `#N` inside one is part of the URL, not a mention. */
258
+ const ANY_URL = /\b[a-z][a-z0-9+.-]*:\/\/\S+/gi;
259
+ /**
260
+ * Every issue reference the prompt makes for the tracker, in text order (ids may repeat),
261
+ * split by form. `explicit`: an `<id>` / `<{tracker}_issue>` tag, a labelled form
262
+ * (`GitHub issue: #N`, `issue #N`, `issue ABC-12`, `ISSUE-N`), or a tracker issue URL /
263
+ * `owner/repo#N` pointing at this repo / team / site (`scope`). `bare`: a `#N` (a CSS
264
+ * colour after `color:` and the like dropped), `owner/repo#N` with no origin to compare,
265
+ * or a bare Linear / Jira key carrying the `scope.key` prefix; with no prefix configured a
266
+ * bare key never counts and lands in `skipped` instead. A tracker URL or `owner/repo#N`
267
+ * pointing elsewhere counts as neither, and a key or `#N` inside any URL is never bare.
268
+ */
269
+ export function issueRefs(text, tracker, scope = {}) {
270
+ const id = (m) => m[1];
271
+ const upper = (m) => {
272
+ const k = m[1].toUpperCase();
273
+ return k.startsWith("ISSUE-") && !/^ISSUE-[0-9]+$/.test(k) ? null : k;
274
+ };
275
+ const prefix = scope.key ? `${scope.key.toUpperCase()}-` : null;
276
+ let explicit;
277
+ let bare;
278
+ let skipped = [];
279
+ let urlForm;
280
+ if (tracker === "github") {
281
+ // With no origin to compare against, a URL to any repo counts and `owner/repo#N` stays bare.
282
+ const ours = scope.ownerRepo?.toLowerCase() ?? null;
283
+ const isOurs = (m) => m[1].toLowerCase() === ours;
284
+ urlForm = /https?:\/\/[^\s/]+\/([^\s/]+\/[^\s/]+)\/issues\/([0-9]+)(?![\w])/g;
285
+ const shortRef = /(?<![\w&#/])([\w.-]+\/[\w.-]+)#([0-9]+)(?![\w-])/g;
286
+ const inShortRef = spans(text, shortRef);
287
+ explicit = [
288
+ ...hits(text, /<id>\s*#?([0-9]+)\s*<\/id>/gi, id),
289
+ ...hits(text, /<github_issue>\s*#?([0-9]+)\s*<\/github_issue>/gi, id),
290
+ ...hits(text, /GitHub issue:\s*#?([0-9]+)\b/gi, id),
291
+ ...hits(text, /\bissue:?\s*#([0-9]+)\b/gi, id),
292
+ ...hits(text, /\bISSUE-([0-9]+)\b/g, id),
293
+ ...hits(text, urlForm, (m) => (ours === null || isOurs(m) ? m[2] : null)),
294
+ ...hits(text, shortRef, (m) => (ours !== null && isOurs(m) ? m[2] : null)),
295
+ ];
296
+ bare = [
297
+ ...hits(text, /(?<![\w&#/])#([0-9]+)(?![\w-])/g, id).filter((h) => !cssColour(text, h) && !inShortRef.some(([from, to]) => h.at >= from && h.at < to)),
298
+ ...hits(text, shortRef, (m) => (ours === null ? m[2] : null)),
299
+ ];
300
+ }
301
+ else if (tracker === "linear" || tracker === "jira") {
302
+ const k = tracker === "linear" ? "[A-Za-z]+-[0-9]+" : "[A-Za-z][A-Za-z0-9]+-[0-9]+";
303
+ const plain = tracker === "linear" ? "[A-Z]+-[0-9]+" : "[A-Z][A-Z0-9]+-[0-9]+";
304
+ // bkit has no Linear workspace setting, so a Linear URL is matched on the team key alone.
305
+ // With no team / project / site configured, that part of the URL is not compared.
306
+ const site = tracker === "jira" && scope.site ? hostOf(scope.site) : null;
307
+ urlForm =
308
+ tracker === "linear"
309
+ ? new RegExp(`()linear\\.app\\/[^\\s/]+\\/issue\\/(${k})`, "gi")
310
+ : new RegExp(`(?:[a-z][a-z0-9+.-]*:\\/\\/)?([^\\s/]+)(?:\\/\\S*?)?\\/browse\\/(${k})`, "gi");
311
+ const ourUrl = (m) => {
312
+ const key = m[2].toUpperCase();
313
+ if (prefix !== null && !key.startsWith(prefix))
314
+ return null;
315
+ if (site !== null && m[1].toLowerCase() !== site)
316
+ return null;
317
+ return key;
318
+ };
319
+ explicit = [
320
+ ...hits(text, new RegExp(`<id>\\s*(${k})\\s*<\\/id>`, "gi"), upper),
321
+ ...hits(text, new RegExp(`<${tracker}_issue>\\s*(${k})\\s*<\\/${tracker}_issue>`, "gi"), upper),
322
+ ...hits(text, new RegExp(`${tracker} issue:\\s*(${k})\\b`, "gi"), upper),
323
+ ...hits(text, new RegExp(`\\b[Ii]ssue:?\\s+(${plain})\\b`, "g"), upper),
324
+ ...hits(text, new RegExp(`\\bISSUE-(${plain})\\b`, "g"), upper),
325
+ ...hits(text, urlForm, ourUrl),
326
+ ];
327
+ bare = hits(text, new RegExp(`(?<![\\w-])(${plain})(?![\\w-])`, "g"), upper);
328
+ if (prefix === null) {
329
+ skipped = bare;
330
+ bare = [];
331
+ }
332
+ else {
333
+ bare = bare.filter((h) => h.value.startsWith(prefix));
334
+ }
335
+ }
336
+ else {
337
+ return { explicit: [], bare: [], skipped: [] };
338
+ }
339
+ const urls = [...spans(text, ANY_URL), ...spans(text, urlForm)];
340
+ const outsideUrls = (h) => !urls.some(([from, to]) => h.at >= from && h.at < to);
341
+ const shape = ISSUE_ID_PATTERNS[tracker];
342
+ const keep = (list) => list.filter((h) => shape.test(h.value)).sort(byPosition);
343
+ return {
344
+ explicit: keep(explicit),
345
+ bare: keep(bare.filter(outsideUrls)),
346
+ skipped: keep(skipped.filter(outsideUrls)),
347
+ };
348
+ }
349
+ /** The issues a prompt names: the distinct explicit ids, else the distinct bare ones, in text order. */
350
+ export function issueCandidates(refs) {
351
+ const pool = refs.explicit.length > 0 ? refs.explicit : refs.bare;
352
+ return [...new Set(pool.map((h) => h.value))];
353
+ }
354
+ /** All-digit words a prompt holds outside URLs, tags, `/commands` and `#N`: an issue typed without its `#`. */
355
+ export function bareNumbers(text) {
356
+ const plain = text
357
+ .replace(/\S+:\/\/\S+/g, " ")
358
+ .replace(/<[^>]*>/g, " ")
359
+ .replace(/(^|\s)\/\S+/g, " ");
360
+ return [...plain.matchAll(/(?<![\w#/.-])([0-9]+)(?![\w/.-])/g)].map((m) => m[1]);
361
+ }
362
+ /** The stderr hint for a bare number: how to write it so it names the issue. */
363
+ function bareNumberHint(n, tracker, key) {
364
+ const write = tracker === "github" ? `#${n}` : `its issue key (${key ?? "KEY"}-${n})`;
365
+ return `${n} reads as a bare number; write ${write}`;
366
+ }
367
+ /** The FID a prompt names explicitly: `feat/` and `docs/plans/` paths always, a bare word only when `logs/{word}/` exists. */
368
+ export function namedFid(text, roots) {
369
+ const fid = (m) => {
370
+ const f = m[1].replace(/-+$/, "");
371
+ return SLUG.test(f) ? f : null;
372
+ };
373
+ const logged = loggedNames(roots);
374
+ const found = [
375
+ ...hits(text, /\bfeat\/([a-z0-9][a-z0-9-]*)/g, fid),
376
+ ...hits(text, /docs\/plans\/[0-9]{6}\/logs\/([a-z0-9][a-z0-9-]*)/g, fid),
377
+ ...hits(text, /docs\/plans\/[0-9]{6}\/([a-z0-9][a-z0-9-]*?)-(?:design|plan)(?:-[0-9]+)?\.md/g, fid),
378
+ ...hits(text, /(?<![\w/-])([a-z0-9][a-z0-9-]*[a-z0-9])(?![\w/-])/g, (m) => logged.has(m[1]) ? m[1] : null),
379
+ ].sort((a, b) => a.at - b.at);
380
+ return found[0]?.value ?? null;
381
+ }
382
+ /** `#N` for GitHub, the key itself for Linear and Jira, "" with no issue. */
383
+ export const issueRef = (issue, tracker) => issue === "" ? "" : tracker === "github" ? `#${issue}` : issue;
384
+ /** A feature's plan in a month bucket, as ship reads it: `{FID}-plan.md`, or none. */
385
+ export function planFiles(root, fid, month) {
386
+ const name = `${fid}-plan.md`;
387
+ return fs.existsSync(path.join(root, "docs", "plans", month, name))
388
+ ? { source: "single", plan: `docs/plans/${month}/${name}` }
389
+ : { source: "none", plan: null };
390
+ }
391
+ /** The `**Parent design:**` link target's FID and month in the text, or null. */
392
+ export function parentDesignLink(text) {
393
+ const m = /\*\*Parent design:\*\*[^\n]*?docs\/plans\/([0-9]{6})\/([a-z0-9][a-z0-9-]*)-design\.md/.exec(text);
394
+ return m ? { month: m[1], fid: m[2] } : null;
395
+ }
396
+ /** Every `docs/audits/{YYYYMM}/*.md` path in the texts, first mention order, unique. */
397
+ export function auditPaths(...texts) {
398
+ const seen = new Set();
399
+ for (const text of texts) {
400
+ for (const m of text.matchAll(/docs\/audits\/[0-9]{6}\/[A-Za-z0-9._-]+\.md/g))
401
+ seen.add(m[0]);
402
+ }
403
+ return [...seen];
404
+ }
56
405
  /**
57
406
  * The canonical design doc for a feature, `docs/plans/{YYYYMM}/{fid}-design.md`: the
58
407
  * `month` bucket first, else the newest bucket holding one. null when none exists.
@@ -70,10 +419,43 @@ export function designDoc(root, fid, month) {
70
419
  const hit = month !== undefined && months.includes(month) && at(month) ? month : months.find(at);
71
420
  return hit === undefined ? null : { month: hit, path: `docs/plans/${hit}/${fid}-design.md` };
72
421
  }
73
- /** `package.json` `bkit.issueTracker` at the main checkout (cwd outside git); default `none`. */
74
- export function readIssueTracker(cwd) {
422
+ /** `package.json` `bkit` config at the main checkout (cwd outside git). */
423
+ function mainConfig(cwd) {
75
424
  const common = git(cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
76
- return readBkitConfig(common ? path.dirname(common) : cwd).issueTracker;
425
+ return readBkitConfig(common ? path.dirname(common) : cwd);
426
+ }
427
+ /** `package.json` `bkit.tracker.default` at the main checkout (cwd outside git); default `none`. */
428
+ export function readIssueTracker(cwd) {
429
+ return mainConfig(cwd).issueTracker;
430
+ }
431
+ /**
432
+ * Where this repo's issues live, per tracker: github the `origin` owner/repo (read from the
433
+ * remote, not gh, so a prompt parse makes no network call); linear `bkit.tracker.linear.team`; jira
434
+ * `bkit.tracker.jira.project` and `bkit.tracker.jira.site`. Each is null when unset.
435
+ */
436
+ function issueScope(cwd, tracker) {
437
+ if (tracker === "github")
438
+ return { key: null, ownerRepo: originOwnerRepo(cwd), site: null };
439
+ if (tracker !== "linear" && tracker !== "jira")
440
+ return { key: null };
441
+ const cfg = mainConfig(cwd);
442
+ return tracker === "linear"
443
+ ? { key: cfg.linear.team }
444
+ : { key: cfg.jira.project, site: cfg.jira.site };
445
+ }
446
+ /** The setting that names the issue-key prefix of a keyed tracker. */
447
+ const KEY_SETTING = {
448
+ linear: "bkit.tracker.linear.team",
449
+ jira: "bkit.tracker.jira.project",
450
+ };
451
+ /** The stderr hint for bare keys skipped because no key prefix is configured. */
452
+ function skippedKeyHint(skipped, tracker) {
453
+ return `${skipped.join(", ")} not read as an issue: bare keys count only once ${KEY_SETTING[tracker]} is set in package.json; or name the issue as "issue KEY-N"`;
454
+ }
455
+ /** The current tree and the main checkout: where log folders are looked for. */
456
+ function fidRoots(cwd) {
457
+ const top = git(cwd, ["rev-parse", "--show-toplevel"]) ?? cwd;
458
+ return [...new Set([top, repoRoot(cwd)])];
77
459
  }
78
460
  function trackerFlag(value, cwd, allowAny) {
79
461
  if (value === undefined)
@@ -113,26 +495,71 @@ const MARKERS = {
113
495
  jira: /<!-- bkit:issue=([A-Za-z][A-Za-z0-9]+-[0-9]+) bkit:fid=(\S+) -->/,
114
496
  none: /<!-- bkit:fid=(\S+) -->/,
115
497
  };
116
- /** FID from the marker, when present and well-formed for the tracker. */
498
+ /**
499
+ * FID from the marker, when present and well-formed for the tracker. A wired tracker also
500
+ * accepts the FID-only marker of an issue-less run: its FID must be issue-less, and it
501
+ * resolves to `issueId: null`.
502
+ */
117
503
  export function fromMarker(text, tracker) {
118
504
  const m = MARKERS[tracker].exec(text);
119
- if (!m)
120
- return null;
505
+ if (!m) {
506
+ if (tracker === "none")
507
+ return null;
508
+ const bare = MARKERS.none.exec(text);
509
+ const fid = bare?.[1];
510
+ return fid !== undefined && ISSUE_LESS_FID.test(fid)
511
+ ? { fid, issueId: null, source: "marker" }
512
+ : null;
513
+ }
121
514
  const fid = normaliseFid(m[m.length - 1], tracker);
122
515
  if (!FID_PATTERNS[tracker].test(fid))
123
516
  return null;
124
517
  const issueId = tracker === "none" ? null : KEYED.has(tracker) ? m[1].toUpperCase() : m[1];
125
518
  return { fid, issueId, source: "marker" };
126
519
  }
127
- /** FID from `feat/{FID}`; the slug check, then the issue id the tracker needs. */
128
- export function fromBranch(branch, tracker) {
520
+ /**
521
+ * The issue ids a repo's feature rows in `.bkit/issues.jsonl` carry in their FID keys,
522
+ * per the tracker's FID shape (`650-x` -> `650`; linear and jira keys uppercased).
523
+ */
524
+ export function featureIssueIds(root, tracker) {
525
+ const file = path.join(root, ".bkit", "issues.jsonl");
526
+ const ids = new Set();
527
+ if (tracker === "none" || !fs.existsSync(file) || !fs.statSync(file).isFile())
528
+ return ids;
529
+ for (const line of fs.readFileSync(file, "utf-8").split("\n")) {
530
+ if (line.trim() === "")
531
+ continue;
532
+ const row = parseJson(line);
533
+ if (!row.ok || typeof row.value !== "object" || row.value === null)
534
+ continue;
535
+ const { kind, key } = row.value;
536
+ if (kind !== "feature" || typeof key !== "string")
537
+ continue;
538
+ const id = issueIdOf(key, tracker);
539
+ if (id !== null)
540
+ ids.add(id);
541
+ }
542
+ return ids;
543
+ }
544
+ /**
545
+ * FID from `feat/{FID}`; the slug check, then the issue id the tracker needs. A wired
546
+ * tracker also accepts an issue-less FID (no issue id embedded, no all-digit word) as `issueId: null`.
547
+ * With `known` (the issue ids the repo's feature rows carry), the FID is the suffix verbatim
548
+ * for any slug: the issue id its shape embeds counts only when `known` holds it, else the
549
+ * run is issue-less (`issueId: null`).
550
+ */
551
+ export function fromBranch(branch, tracker, known) {
129
552
  if (!branch.startsWith("feat/"))
130
553
  return { ok: false, why: `branch "${branch}" is not feat/{FID}` };
131
554
  const fid = branch.slice("feat/".length);
132
555
  if (!SLUG.test(fid))
133
556
  return { ok: false, why: `"${fid}" is not a slug (${SLUG.source})` };
134
557
  const issueId = issueIdOf(fid, tracker);
135
- if (tracker !== "none" && issueId === null) {
558
+ if (known !== undefined) {
559
+ const linked = issueId !== null && known.has(issueId) ? issueId : null;
560
+ return { ok: true, parsed: { fid, issueId: linked, source: "branch" } };
561
+ }
562
+ if (tracker !== "none" && issueId === null && !ISSUE_LESS_FID.test(fid)) {
136
563
  return { ok: false, why: `"${fid}" embeds no ${tracker} issue id` };
137
564
  }
138
565
  return { ok: true, parsed: { fid, issueId, source: "branch" } };
@@ -140,32 +567,39 @@ export function fromBranch(branch, tracker) {
140
567
  const TRACKER_FLAG = {
141
568
  name: "tracker",
142
569
  type: "string",
143
- help: "github | linear | jira | none (default: package.json bkit.issueTracker, else none)",
570
+ help: "github | linear | jira | none (default: package.json bkit.tracker.default, else none)",
144
571
  };
145
572
  export const fidsCommand = {
146
573
  noun: "fids",
147
- summary: "Feature-id format per tracker, and FID recovery from a branch or PR-body marker.",
574
+ summary: "Feature-id format per tracker; the issue, FID, plan files and plan inputs Step 1 resolves; FID recovery from a branch or PR-body marker.",
148
575
  verbs: {
149
576
  check: {
150
577
  summary: "Validate a FID for the tracker: exit 0 valid, exit 1 not.",
151
578
  flags: [
152
579
  { name: "fid", type: "string", required: true, help: "feature id to check" },
153
580
  { ...TRACKER_FLAG, help: `${TRACKER_FLAG.help}; any = any tracker's shape (CI_DEV)` },
581
+ {
582
+ name: "issue",
583
+ type: "string",
584
+ help: 'the run\'s issue id (the FID must embed it), or "" for a run with no issue (then the FID must be a slug); absent = the tracker shape alone',
585
+ },
154
586
  ],
155
587
  output: {
156
588
  fid: "the FID as checked (linear, jira: lowercased)",
157
589
  tracker: "tracker the shape came from",
158
590
  valid: "true when the FID matches",
159
- pattern: "the regex checked",
591
+ pattern: "the regex checked (the slug rule when --issue is empty)",
160
592
  issueId: "issue id the FID embeds (null under none, or when invalid)",
161
593
  },
162
594
  run: (ctx) => {
163
595
  const tracker = trackerFlag(str(ctx.flags.tracker), ctx.cwd, true);
164
596
  const fid = normaliseFid(String(ctx.flags.fid), tracker);
165
- const pattern = FID_PATTERNS[tracker];
166
- const valid = pattern.test(fid);
597
+ const issue = str(ctx.flags.issue)?.replace(/^#/, "");
598
+ const pattern = issue === "" && tracker !== "none" ? SLUG : FID_PATTERNS[tracker];
599
+ const problem = fidProblem(fid, tracker, issue);
600
+ const valid = problem === undefined;
167
601
  if (!valid)
168
- ctx.log(`FID "${fid}" does not match the ${tracker} shape ${pattern.source}`);
602
+ ctx.log(problem);
169
603
  ctx.emit({
170
604
  fid,
171
605
  tracker,
@@ -177,8 +611,13 @@ export const fidsCommand = {
177
611
  },
178
612
  },
179
613
  parse: {
180
- summary: "Recover FID and issue id: the PR-body marker first, then a feat/{FID} branch.",
614
+ summary: "--prompt-file: the issue and the FID a session prompt names. --marker / --branch: recover FID and issue id, the PR-body marker first, then a feat/{FID} branch (any slug; its issue id counts only when .bkit/issues.jsonl has a feature row for it, else the run is issue-less).",
181
615
  flags: [
616
+ {
617
+ name: "prompt-file",
618
+ type: "string",
619
+ help: "the session prompt, written verbatim (Step 1: {SESSION_DIR}/prompt.md); not with --marker / --branch",
620
+ },
182
621
  {
183
622
  name: "marker",
184
623
  type: "string",
@@ -188,17 +627,60 @@ export const fidsCommand = {
188
627
  TRACKER_FLAG,
189
628
  ],
190
629
  output: {
191
- fid: "the recovered FID",
192
- issueId: "tracker issue id (null under none)",
193
- source: "marker | branch",
194
- tracker: "tracker the shapes came from",
630
+ source: "--prompt-file: github | linear | jira — the wired tracker, when the prompt names one of its issues; none otherwise (a bare number, another tracker's form, tracker none). --marker / --branch: marker | branch",
631
+ issue: '--prompt-file: the issue named (github: the number, linear / jira: the key): an explicit form (<id> tag, "GitHub issue: #N", "issue #N" / "issue KEY", owner/repo#N or a tracker URL into the origin repo / bkit.tracker.linear.team / bkit.tracker.jira.site + bkit.tracker.jira.project; a URL elsewhere is ignored) over a bare #N / key; a bare Linear / Jira key only with the bkit.tracker.linear.team / bkit.tracker.jira.project prefix set; else ""',
632
+ ambiguous: "--prompt-file, exit 8 only: the issues named, as a person types them (then no other key prints)",
633
+ ref: '--prompt-file: the issue as a person types it (github: #N, linear / jira: the key), else ""',
634
+ fidNamed: "--prompt-file: the first FID the prompt names (feat/{FID}, a docs/plans/{YYYYMM}/ path, or a bare word with a logs/{word}/ folder), else null",
635
+ fid: "--marker / --branch: the recovered FID",
636
+ issueId: "--marker / --branch: tracker issue id; null under none, for a marker with none, and for a branch whose embedded issue id has no feature row (an issue-less run)",
637
+ tracker: "--marker / --branch: tracker the shapes came from",
638
+ },
639
+ exitCodes: {
640
+ [EXIT_NO_FID]: "neither the marker nor the branch yielded a FID (a branch that is not feat/ or whose suffix is not a slug)",
641
+ [EXIT_NO_FILE]: "the --prompt-file is missing",
642
+ [EXIT_AMBIGUOUS]: `--prompt-file names more than one issue (explicit forms first) — ${NAME_THE_ISSUE}`,
195
643
  },
196
- exitCodes: { [EXIT_NO_FID]: "neither the marker nor the branch yielded a valid FID" },
197
644
  run: (ctx) => {
198
645
  const marker = str(ctx.flags.marker);
199
646
  const branch = str(ctx.flags.branch);
647
+ const promptFile = str(ctx.flags.promptFile);
648
+ if (promptFile !== undefined) {
649
+ if (marker !== undefined || branch !== undefined)
650
+ throw new CommandError(EXIT.USAGE, "--prompt-file goes alone, without --marker / --branch");
651
+ const text = readNamed(path.resolve(ctx.cwd, promptFile), "prompt-file");
652
+ const tracker = trackerFlag(str(ctx.flags.tracker), ctx.cwd, false);
653
+ const scope = issueScope(ctx.cwd, tracker);
654
+ const key = scope.key ?? null;
655
+ const refs = issueRefs(text, tracker, scope);
656
+ const candidates = issueCandidates(refs);
657
+ if (candidates.length > 1) {
658
+ const named = candidates.map((c) => issueRef(c, tracker));
659
+ ctx.log(`the prompt names more than one issue (${named.join(", ")}); ${NAME_THE_ISSUE}`);
660
+ ctx.emit({ ambiguous: named });
661
+ return EXIT_AMBIGUOUS;
662
+ }
663
+ const issue = candidates[0] ?? "";
664
+ const others = [...new Set([...refs.explicit, ...refs.bare].map((r) => r.value))].filter((v) => v !== issue);
665
+ if (others.length > 0)
666
+ ctx.log(`taking ${issueRef(issue, tracker)}, named explicitly; not the bare mention ${others.map((o) => issueRef(o, tracker)).join(", ")}`);
667
+ const bareNumber = bareNumbers(text)[0];
668
+ if (issue === "" && tracker !== "none" && bareNumber !== undefined)
669
+ ctx.log(bareNumberHint(bareNumber, tracker, key));
670
+ if (issue === "" &&
671
+ refs.skipped.length > 0 &&
672
+ (tracker === "linear" || tracker === "jira"))
673
+ ctx.log(skippedKeyHint([...new Set(refs.skipped.map((h) => h.value))], tracker));
674
+ ctx.emit({
675
+ source: issue === "" ? "none" : tracker,
676
+ issue,
677
+ ref: issueRef(issue, tracker),
678
+ fidNamed: namedFid(text, fidRoots(ctx.cwd)),
679
+ });
680
+ return EXIT.OK;
681
+ }
200
682
  if (marker === undefined && branch === undefined) {
201
- throw new CommandError(EXIT.USAGE, "give --marker, --branch, or both");
683
+ throw new CommandError(EXIT.USAGE, "give --prompt-file, or --marker, --branch, or both");
202
684
  }
203
685
  const tracker = trackerFlag(str(ctx.flags.tracker), ctx.cwd, false);
204
686
  const viaMarker = marker === undefined ? null : fromMarker(marker, tracker);
@@ -210,7 +692,8 @@ export const fidsCommand = {
210
692
  ctx.log(`no well-formed ${tracker} bkit:fid marker — trying the branch`);
211
693
  if (branch === undefined)
212
694
  return EXIT_NO_FID;
213
- const viaBranch = fromBranch(branch, tracker);
695
+ const top = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? ctx.cwd;
696
+ const viaBranch = fromBranch(branch, tracker, featureIssueIds(top, tracker));
214
697
  if (!viaBranch.ok) {
215
698
  ctx.log(viaBranch.why);
216
699
  return EXIT_NO_FID;
@@ -219,8 +702,129 @@ export const fidsCommand = {
219
702
  return EXIT.OK;
220
703
  },
221
704
  },
705
+ resolve: {
706
+ summary: "The run's FID, first hit wins: a FID the prompt names, the feat/{FID} branch, a FID logged for the issue on dev, a mint from the title (or prompt), a free -b, -c, ... suffix when a finished run used the mint; then the format check (exit 0 resolved, exit 1 fails the check).",
707
+ flags: [
708
+ {
709
+ name: "prompt-file",
710
+ type: "string",
711
+ required: true,
712
+ help: "the session prompt, written verbatim ({SESSION_DIR}/prompt.md)",
713
+ },
714
+ {
715
+ name: "issue",
716
+ type: "string",
717
+ help: 'the run\'s issue id (github: 123; linear / jira: ABC-123), or "" / absent for a run with no issue',
718
+ },
719
+ {
720
+ name: "title-file",
721
+ type: "string",
722
+ help: "the issue title: a JSON object with a title key, else the file's text; drop it for a run with no issue",
723
+ },
724
+ {
725
+ ...WORKFLOW_FLAG,
726
+ help: "the workflow starting; an in-progress run of it continues a used mint instead of suffixing",
727
+ },
728
+ TRACKER_FLAG,
729
+ ],
730
+ output: {
731
+ fid: "the FID to use",
732
+ source: "prompt | branch | logged | minted | suffixed — the link of the chain that gave fid",
733
+ month: "the newest bucket holding logs/{fid}/, else null",
734
+ existing: "true when logs/{fid}/ exists in some bucket",
735
+ fids: "every FID logged for the issue (working tree and dev) when the chain reached that link, else []",
736
+ },
737
+ exitCodes: {
738
+ [EXIT_SEVERAL]: "several features are logged for the issue — name one in the prompt",
739
+ [EXIT_NO_FREE]: "the mint and every -b … -z suffix of it are used by finished runs",
740
+ [EXIT_BARE_NUMBER]: `a wired tracker, no issue, and the prompt holds only a bare number (the mint would be the workflow name) — ${NAME_THE_ISSUE}`,
741
+ [EXIT_NO_FILE]: "the --prompt-file or --title-file is missing",
742
+ },
743
+ run: (ctx) => {
744
+ const tracker = trackerFlag(str(ctx.flags.tracker), ctx.cwd, false);
745
+ const issue = (str(ctx.flags.issue) ?? "").replace(/^#/, "");
746
+ const prompt = readNamed(path.resolve(ctx.cwd, String(ctx.flags.promptFile)), "prompt-file");
747
+ const titleFile = str(ctx.flags.titleFile);
748
+ const title = titleFile === undefined
749
+ ? ""
750
+ : titleOf(readNamed(path.resolve(ctx.cwd, titleFile), "title-file"));
751
+ const workflow = String(ctx.flags.workflow);
752
+ const roots = fidRoots(ctx.cwd);
753
+ const branch = git(ctx.cwd, ["branch", "--show-current"]) || null;
754
+ const prefix = KEYED.has(tracker) ? `${issue.toLowerCase()}-` : `${issue}-`;
755
+ let fids = [];
756
+ let pick = null;
757
+ const named = namedFid(prompt, roots);
758
+ if (named !== null)
759
+ pick = { fid: named, source: "prompt" };
760
+ const onBranch = branch?.startsWith("feat/") ? branch.slice("feat/".length) : null;
761
+ if (pick === null && onBranch !== null && SLUG.test(onBranch)) {
762
+ if (issue === "" || onBranch.startsWith(prefix))
763
+ pick = { fid: onBranch, source: "branch" };
764
+ }
765
+ if (pick === null && issue !== "") {
766
+ fids = [
767
+ ...new Set([...roots.flatMap((r) => logged(r, issue)), ...loggedOnDev(ctx.cwd, issue)]),
768
+ ].sort();
769
+ if (fids.length > 1) {
770
+ ctx.log(`several features logged for ${issue}: ${fids.join(", ")}`);
771
+ ctx.emit({ fid: null, source: null, month: null, existing: false, fids });
772
+ return EXIT_SEVERAL;
773
+ }
774
+ if (fids.length === 1)
775
+ pick = { fid: fids[0], source: "logged" };
776
+ }
777
+ const bareNumber = bareNumbers(prompt)[0];
778
+ if (pick === null &&
779
+ issue === "" &&
780
+ tracker !== "none" &&
781
+ bareNumber !== undefined &&
782
+ slugWords(title).length === 0 &&
783
+ slugWords(prompt).length === 0) {
784
+ ctx.log(`${bareNumberHint(bareNumber, tracker, issueScope(ctx.cwd, tracker).key ?? null)} — refusing to mint a FID from the workflow name alone`);
785
+ return EXIT_BARE_NUMBER;
786
+ }
787
+ if (pick === null) {
788
+ const minted = normaliseFid(mintFid({ issue, title, prompt, branch, workflow }), tracker);
789
+ const free = freeFid(roots, minted, workflow);
790
+ if (free === null) {
791
+ ctx.log(`"${minted}" and every -b … -z suffix of it are used by finished runs`);
792
+ return EXIT_NO_FREE;
793
+ }
794
+ pick = { fid: free, source: free === minted ? "minted" : "suffixed" };
795
+ }
796
+ const fid = normaliseFid(pick.fid, tracker);
797
+ const problem = fidProblem(fid, tracker, issue);
798
+ if (problem !== undefined) {
799
+ ctx.log(`${pick.source} FID: ${problem}`);
800
+ return EXIT.NO;
801
+ }
802
+ const month = roots
803
+ .flatMap((r) => monthBuckets(r, fid))
804
+ .sort()
805
+ .at(-1) ?? null;
806
+ ctx.emit({ fid, source: pick.source, month, existing: month !== null, fids });
807
+ return EXIT.OK;
808
+ },
809
+ },
810
+ plans: {
811
+ summary: "A feature's plan in a month bucket: docs/plans/{YYYYMM}/{FID}-plan.md, or none.",
812
+ flags: [
813
+ { name: "fid", type: "string", required: true, help: "feature id" },
814
+ { name: "month", type: "string", required: true, help: "YYYYMM bucket" },
815
+ ],
816
+ output: {
817
+ source: "single ({FID}-plan.md exists) | none (no plan file)",
818
+ plan: "the repo-relative plan file, or null",
819
+ },
820
+ run: (ctx) => {
821
+ const top = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? ctx.cwd;
822
+ ctx.emit(planFiles(top, String(ctx.flags.fid), String(ctx.flags.month)));
823
+ return EXIT.OK;
824
+ },
825
+ },
222
826
  design: {
223
- summary: "The feature's own design doc, docs/plans/{YYYYMM}/{FID}-design.md: exit 0 found, exit 1 none.",
827
+ summary: "The plan's parent design: the **Parent design:** link in the description or prompt, else the feature's own docs/plans/{YYYYMM}/{FID}-design.md; plus the audit reports they name (exit 0 a parent, exit 1 none).",
224
828
  flags: [
225
829
  { name: "fid", type: "string", required: true, help: "feature id" },
226
830
  {
@@ -228,17 +832,69 @@ export const fidsCommand = {
228
832
  type: "string",
229
833
  help: "YYYYMM bucket checked first; else the newest bucket holding the doc",
230
834
  },
835
+ {
836
+ name: "description-file",
837
+ type: "string",
838
+ help: "the issue description; drop it for a run with no issue",
839
+ },
840
+ {
841
+ name: "prompt-file",
842
+ type: "string",
843
+ help: "the session prompt ({SESSION_DIR}/prompt.md)",
844
+ },
231
845
  ],
232
846
  output: {
233
- fid: "the FID when its design doc exists, else null",
847
+ fid: "the FID when its own design doc exists, else null",
234
848
  month: "the bucket holding it, else null",
235
849
  path: "repo-relative path, else null",
850
+ parentFid: "the parent design's FID (the link's, else the feature's own), else null",
851
+ parentMonth: "its bucket, else null",
852
+ parentPath: "its repo-relative path, else null",
853
+ parentSource: "link | fid | null",
854
+ auditPaths: "every docs/audits/{YYYYMM}/*.md path the description, then the prompt, names, first mention order",
855
+ },
856
+ exitCodes: {
857
+ [EXIT_NO_FILE]: "a --description-file / --prompt-file is missing, or a linked design or named audit path is not a file",
236
858
  },
237
859
  run: (ctx) => {
238
860
  const fid = String(ctx.flags.fid);
239
- const hit = designDoc(repoRoot(ctx.cwd), fid, str(ctx.flags.month));
240
- ctx.emit(hit ? { fid, month: hit.month, path: hit.path } : { fid: null, month: null, path: null });
241
- return hit ? EXIT.OK : EXIT.NO;
861
+ const root = repoRoot(ctx.cwd);
862
+ const texts = ["descriptionFile", "promptFile"].flatMap((k) => {
863
+ const file = str(ctx.flags[k]);
864
+ return file === undefined
865
+ ? []
866
+ : [
867
+ readNamed(path.resolve(ctx.cwd, file), k === "promptFile" ? "prompt-file" : "description-file"),
868
+ ];
869
+ });
870
+ const own = designDoc(root, fid, str(ctx.flags.month));
871
+ const link = texts.map(parentDesignLink).find((l) => l !== null) ?? null;
872
+ const parent = link
873
+ ? {
874
+ fid: link.fid,
875
+ month: link.month,
876
+ path: `docs/plans/${link.month}/${link.fid}-design.md`,
877
+ source: "link",
878
+ }
879
+ : own
880
+ ? { fid, month: own.month, path: own.path, source: "fid" }
881
+ : null;
882
+ const audits = auditPaths(...texts);
883
+ for (const rel of [...(link && parent ? [parent.path] : []), ...audits]) {
884
+ if (!fs.statSync(path.join(root, rel), { throwIfNoEntry: false })?.isFile())
885
+ throw new CommandError(EXIT_NO_FILE, `${rel} is named but is not a file`);
886
+ }
887
+ ctx.emit({
888
+ ...(own
889
+ ? { fid, month: own.month, path: own.path }
890
+ : { fid: null, month: null, path: null }),
891
+ parentFid: parent?.fid ?? null,
892
+ parentMonth: parent?.month ?? null,
893
+ parentPath: parent?.path ?? null,
894
+ parentSource: parent?.source ?? null,
895
+ auditPaths: audits,
896
+ });
897
+ return parent ? EXIT.OK : EXIT.NO;
242
898
  },
243
899
  },
244
900
  find: {