@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,14 +10,37 @@
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
 
13
25
  import * as fs from "node:fs";
14
26
  import * as path from "node:path";
15
27
 
16
28
  import { parseIssueTracker, type IssueTracker } from "../../install/manifest.js";
17
- import { CommandError, EXIT, git, repoRoot, type CommandSpec, type FlagSpec } from "../lib.js";
29
+ import {
30
+ CommandError,
31
+ EXIT,
32
+ git,
33
+ parseJson,
34
+ repoRoot,
35
+ statusRelPath,
36
+ type CommandSpec,
37
+ type FlagSpec,
38
+ } from "../lib.js";
18
39
  import { readBkitConfig } from "../../shared/settings.js";
19
- import { str } from "./status.js";
40
+ import { originOwnerRepo } from "./repo.js";
41
+ import { lastRun } from "../../ledgers/status.js";
42
+ import { monthBuckets, readRunsLenient } from "./locks.js";
43
+ import { WORKFLOW_FLAG, str } from "./status.js";
20
44
 
21
45
  export type FidTracker = IssueTracker | "any";
22
46
 
@@ -36,10 +60,62 @@ const ISSUE_KEY = { linear: /^[A-Z]+-[0-9]+$/, jira: /^[A-Z][A-Z0-9]+-[0-9]+$/ }
36
60
  /** The slug every recovered FID must pass before it touches a path (auto's branch fallback). */
37
61
  const SLUG = FID_PATTERNS.none;
38
62
 
63
+ /** An issue-less FID: a slug with no all-digit `-`-separated word, so it never parses as an issue id. */
64
+ export const ISSUE_LESS_FID = /^(?!.*(?:^|-)[0-9]+(?:-|$))[a-z0-9][a-z0-9-]*$/;
65
+
66
+ /** The issue id each wired tracker mints (`#` stripped; linear and jira keys are uppercase). */
67
+ export const ISSUE_ID_PATTERNS: Readonly<Record<Exclude<IssueTracker, "none">, RegExp>> = {
68
+ github: /^[0-9]+$/,
69
+ linear: /^[A-Z]+-[0-9]+$/,
70
+ jira: /^[A-Z][A-Z0-9]+-[0-9]+$/,
71
+ };
72
+
73
+ /**
74
+ * The problem with a FID for the tracker and the run's issue, or undefined when it is valid.
75
+ * `issue` absent: the tracker's FID shape alone. A non-empty `issue`: the issue id and the
76
+ * FID both match the tracker, and the issue id the FID embeds is that issue. An empty
77
+ * `issue` (a run with no issue): the FID is any slug (a minted one is held to
78
+ * `ISSUE_LESS_FID` by `fids resolve`). The `none` tracker has no issue-id shape, so `issue`
79
+ * is ignored.
80
+ */
81
+ export function fidProblem(fid: string, tracker: FidTracker, issue?: string): string | undefined {
82
+ const shape = FID_PATTERNS[tracker];
83
+ const shapeProblem = shape.test(fid)
84
+ ? undefined
85
+ : `FID "${fid}" does not match the ${tracker} shape ${shape.source}`;
86
+ if (issue === undefined || tracker === "none") return shapeProblem;
87
+ if (issue === "") {
88
+ return SLUG.test(fid)
89
+ ? undefined
90
+ : `FID "${fid}" is not a slug (${SLUG.source}): a run with no issue needs a lowercase slug`;
91
+ }
92
+ const idShapes =
93
+ tracker === "any" ? Object.values(ISSUE_ID_PATTERNS) : [ISSUE_ID_PATTERNS[tracker]];
94
+ if (!idShapes.some((re) => re.test(issue))) {
95
+ return `issue "${issue}" is not a ${tracker} issue id`;
96
+ }
97
+ if (shapeProblem !== undefined) return shapeProblem;
98
+ const embedded = issueIdOf(fid, tracker);
99
+ return embedded === issue
100
+ ? undefined
101
+ : `FID "${fid}" embeds issue ${embedded ?? "none"}, not the run's issue ${issue}`;
102
+ }
103
+
39
104
  /** Exit code: no FID could be recovered from the marker or the branch. */
40
105
  export const EXIT_NO_FID = 3;
41
106
  /** Exit code (find): more than one feature is logged for the issue. */
42
107
  export const EXIT_SEVERAL = 4;
108
+ /** Exit code (resolve): the minted name and every suffix of it are used. */
109
+ export const EXIT_NO_FREE = 5;
110
+ /** Exit code: a file a flag names is missing. */
111
+ export const EXIT_NO_FILE = 7;
112
+ /** Exit code (parse --prompt-file): the prompt names more than one issue. */
113
+ export const EXIT_AMBIGUOUS = 8;
114
+ /** Exit code (resolve): the prompt holds only a bare number, so the FID would mint from the workflow name. */
115
+ export const EXIT_BARE_NUMBER = 9;
116
+
117
+ /** The stop message for a prompt that does not say which issue it means. */
118
+ const NAME_THE_ISSUE = "name the issue as #N, its key or its URL";
43
119
 
44
120
  /**
45
121
  * Features already logged for an issue: every `docs/plans/{YYYYMM}/logs/{issue}-*`
@@ -60,6 +136,351 @@ export function logged(root: string, issue: string): string[] {
60
136
  return [...found].sort();
61
137
  }
62
138
 
139
+ /** Suffixes tried after a minted name that an earlier run used: `-b` … `-z`. */
140
+ const MINT_SUFFIXES = [..."bcdefghijklmnopqrstuvwxyz"];
141
+
142
+ /**
143
+ * The FID a minted issue-less run takes: `fid` itself, or the first of `fid-b`, `fid-c`, ...
144
+ * that no earlier run used. A name is used when it has a log folder (any month bucket) in
145
+ * one of `roots` whose last `workflow` run is not IN_PROGRESS; an in-progress one is
146
+ * continued. null when every name is used.
147
+ */
148
+ export function freeFid(roots: string[], fid: string, workflow: string): string | null {
149
+ for (const name of [fid, ...MINT_SUFFIXES.map((x) => `${fid}-${x}`)]) {
150
+ let used = false;
151
+ for (const root of roots) {
152
+ for (const month of monthBuckets(root, name)) {
153
+ const run = lastRun(readRunsLenient(path.join(root, statusRelPath(month, name))), workflow);
154
+ if (run?.status === "IN_PROGRESS") return name;
155
+ used = true;
156
+ }
157
+ }
158
+ if (!used) return name;
159
+ }
160
+ return null;
161
+ }
162
+
163
+ /** A file a flag names, or exit 7 when it is missing. */
164
+ function readNamed(file: string, flag: string): string {
165
+ if (!fs.existsSync(file) || !fs.statSync(file).isFile())
166
+ throw new CommandError(EXIT_NO_FILE, `--${flag}: no file at ${file}`);
167
+ return fs.readFileSync(file, "utf-8");
168
+ }
169
+
170
+ /** The issue title a `--title-file` holds: a JSON object's `title`, else the text itself. */
171
+ export function titleOf(text: string): string {
172
+ const parsed = parseJson(text);
173
+ if (parsed.ok && typeof parsed.value === "object" && parsed.value !== null) {
174
+ const title = (parsed.value as Record<string, unknown>).title;
175
+ if (typeof title === "string") return title;
176
+ }
177
+ return text.trim();
178
+ }
179
+
180
+ /** English words a minted slug drops. */
181
+ export const STOPWORDS: ReadonlySet<string> = new Set(
182
+ (
183
+ "a about after all also an and any are as at be been before being but by can could " +
184
+ "did do does doing for from had has have he her his how i if in into is it its just " +
185
+ "let me more most my no nor not now of off on once only or other our out over per " +
186
+ "please same she should so some such than that the their them then there these they " +
187
+ "this those through to too under until up us very via was we were what when where " +
188
+ "which while who why will with would you your"
189
+ ).split(" "),
190
+ );
191
+
192
+ /**
193
+ * The slug words of free text in order: URLs, `<tags>` and `/commands` removed, letters
194
+ * folded to ASCII, lowercased, split on anything else; stopwords and all-digit words dropped.
195
+ */
196
+ export function slugWords(text: string): string[] {
197
+ return text
198
+ .replace(/\S+:\/\/\S+/g, " ")
199
+ .replace(/<[^>]*>/g, " ")
200
+ .replace(/(^|\s)\/\S+/g, " ")
201
+ .normalize("NFKD")
202
+ .replace(/[\u0300-\u036f]/g, "")
203
+ .toLowerCase()
204
+ .split(/[^a-z0-9]+/)
205
+ .filter((w) => w !== "" && !STOPWORDS.has(w) && !/^[0-9]+$/.test(w));
206
+ }
207
+
208
+ /** The FID a run mints; see the header comment for the rules. */
209
+ export function mintFid(o: {
210
+ issue: string;
211
+ title?: string;
212
+ prompt: string;
213
+ branch?: string | null;
214
+ workflow?: string;
215
+ }): string {
216
+ const fromTitle = slugWords(o.title ?? "");
217
+ const words = (fromTitle.length > 0 ? fromTitle : slugWords(o.prompt)).slice(0, 3);
218
+ const slug = (words.length > 0 ? words : [o.workflow ?? "feature"]).join("-");
219
+ if (o.issue !== "") return `${o.issue.replace(/^#/, "").toLowerCase()}-${slug}`;
220
+ const suffix = (o.branch ?? "")
221
+ .split("/")
222
+ .at(-1)!
223
+ .toLowerCase()
224
+ .split(/[^a-z0-9]+/)
225
+ .filter((w) => w !== "" && !/^[0-9]+$/.test(w));
226
+ return [...suffix, slug].join("-");
227
+ }
228
+
229
+ const MONTH = /^[0-9]{6}$/;
230
+
231
+ /** Every `docs/plans/{YYYYMM}/logs/{name}` folder name under the roots. */
232
+ function loggedNames(roots: string[]): Set<string> {
233
+ const names = new Set<string>();
234
+ for (const root of roots) {
235
+ const plans = path.join(root, "docs", "plans");
236
+ if (!fs.existsSync(plans)) continue;
237
+ for (const month of fs.readdirSync(plans).filter((m) => MONTH.test(m))) {
238
+ const logs = path.join(plans, month, "logs");
239
+ if (!fs.existsSync(logs)) continue;
240
+ for (const name of fs.readdirSync(logs)) {
241
+ if (fs.statSync(path.join(logs, name)).isDirectory()) names.add(name);
242
+ }
243
+ }
244
+ }
245
+ return names;
246
+ }
247
+
248
+ /** Features logged for an issue on `origin/dev` (else local `dev`), read from git, not the working tree. */
249
+ export function loggedOnDev(cwd: string, issue: string): string[] {
250
+ const ref = git(cwd, ["rev-parse", "--verify", "-q", "origin/dev"]) ? "origin/dev" : "dev";
251
+ const out = git(cwd, ["ls-tree", "-r", "-d", "--name-only", ref, "--", "docs/plans"]);
252
+ if (!out) return [];
253
+ const key = `${issue.replace(/^#/, "").toLowerCase()}-`;
254
+ const found = new Set<string>();
255
+ for (const line of out.split("\n")) {
256
+ const m = /^docs\/plans\/[0-9]{6}\/logs\/([^/]+)$/.exec(line.trim());
257
+ if (m && m[1]!.startsWith(key)) found.add(m[1]!);
258
+ }
259
+ return [...found].sort();
260
+ }
261
+
262
+ type Hit = { value: string; at: number };
263
+
264
+ function hits(text: string, re: RegExp, map: (m: RegExpExecArray) => string | null): Hit[] {
265
+ const out: Hit[] = [];
266
+ for (const m of text.matchAll(re)) {
267
+ const value = map(m);
268
+ if (value !== null) out.push({ value, at: m.index });
269
+ }
270
+ return out;
271
+ }
272
+
273
+ /** The line text before a `#N` ends in a CSS colour property (`color: `, `background-color: `). */
274
+ const CSS_COLOUR_LEAD = /(?:colou?r|background|border|fill|stroke|outline|shadow)[\w-]*\s*:\s*$/i;
275
+
276
+ /** A `#N` hit that is a 3- or 6-digit CSS colour (`color: #123456`), not an issue. */
277
+ function cssColour(text: string, h: Hit): boolean {
278
+ if (h.value.length !== 3 && h.value.length !== 6) return false;
279
+ return CSS_COLOUR_LEAD.test(text.slice(text.lastIndexOf("\n", h.at) + 1, h.at));
280
+ }
281
+
282
+ const byPosition = (a: Hit, b: Hit) => a.at - b.at;
283
+
284
+ /** Where this repo's issues live: what a tracker URL and a bare key must match to count. */
285
+ export interface IssueScope {
286
+ /** `bkit.tracker.linear.team` / `bkit.tracker.jira.project`: the prefix a key must carry. null = unset. */
287
+ key?: string | null;
288
+ /** `owner/repo` from the `origin` remote (github). null = no origin. */
289
+ ownerRepo?: string | null;
290
+ /** `bkit.tracker.jira.site` (jira). null = unset. */
291
+ site?: string | null;
292
+ }
293
+
294
+ /** Start and end of every match of `re` in `text`. */
295
+ const spans = (text: string, re: RegExp): [number, number][] =>
296
+ [...text.matchAll(re)].map((m) => [m.index, m.index + m[0].length]);
297
+
298
+ /** The host of a URL or bare host, lowercased: `https://Acme.atlassian.net/` -> `acme.atlassian.net`. */
299
+ const hostOf = (site: string) =>
300
+ site
301
+ .replace(/^[a-z][a-z0-9+.-]*:\/\//i, "")
302
+ .split("/")[0]!
303
+ .toLowerCase();
304
+
305
+ /** A URL in prose: a bare key or `#N` inside one is part of the URL, not a mention. */
306
+ const ANY_URL = /\b[a-z][a-z0-9+.-]*:\/\/\S+/gi;
307
+
308
+ /**
309
+ * Every issue reference the prompt makes for the tracker, in text order (ids may repeat),
310
+ * split by form. `explicit`: an `<id>` / `<{tracker}_issue>` tag, a labelled form
311
+ * (`GitHub issue: #N`, `issue #N`, `issue ABC-12`, `ISSUE-N`), or a tracker issue URL /
312
+ * `owner/repo#N` pointing at this repo / team / site (`scope`). `bare`: a `#N` (a CSS
313
+ * colour after `color:` and the like dropped), `owner/repo#N` with no origin to compare,
314
+ * or a bare Linear / Jira key carrying the `scope.key` prefix; with no prefix configured a
315
+ * bare key never counts and lands in `skipped` instead. A tracker URL or `owner/repo#N`
316
+ * pointing elsewhere counts as neither, and a key or `#N` inside any URL is never bare.
317
+ */
318
+ export function issueRefs(
319
+ text: string,
320
+ tracker: IssueTracker,
321
+ scope: IssueScope = {},
322
+ ): { explicit: Hit[]; bare: Hit[]; skipped: Hit[] } {
323
+ const id = (m: RegExpExecArray) => m[1]!;
324
+ const upper = (m: RegExpExecArray) => {
325
+ const k = m[1]!.toUpperCase();
326
+ return k.startsWith("ISSUE-") && !/^ISSUE-[0-9]+$/.test(k) ? null : k;
327
+ };
328
+ const prefix = scope.key ? `${scope.key.toUpperCase()}-` : null;
329
+ let explicit: Hit[];
330
+ let bare: Hit[];
331
+ let skipped: Hit[] = [];
332
+ let urlForm: RegExp;
333
+ if (tracker === "github") {
334
+ // With no origin to compare against, a URL to any repo counts and `owner/repo#N` stays bare.
335
+ const ours = scope.ownerRepo?.toLowerCase() ?? null;
336
+ const isOurs = (m: RegExpExecArray) => m[1]!.toLowerCase() === ours;
337
+ urlForm = /https?:\/\/[^\s/]+\/([^\s/]+\/[^\s/]+)\/issues\/([0-9]+)(?![\w])/g;
338
+ const shortRef = /(?<![\w&#/])([\w.-]+\/[\w.-]+)#([0-9]+)(?![\w-])/g;
339
+ const inShortRef = spans(text, shortRef);
340
+ explicit = [
341
+ ...hits(text, /<id>\s*#?([0-9]+)\s*<\/id>/gi, id),
342
+ ...hits(text, /<github_issue>\s*#?([0-9]+)\s*<\/github_issue>/gi, id),
343
+ ...hits(text, /GitHub issue:\s*#?([0-9]+)\b/gi, id),
344
+ ...hits(text, /\bissue:?\s*#([0-9]+)\b/gi, id),
345
+ ...hits(text, /\bISSUE-([0-9]+)\b/g, id),
346
+ ...hits(text, urlForm, (m) => (ours === null || isOurs(m) ? m[2]! : null)),
347
+ ...hits(text, shortRef, (m) => (ours !== null && isOurs(m) ? m[2]! : null)),
348
+ ];
349
+ bare = [
350
+ ...hits(text, /(?<![\w&#/])#([0-9]+)(?![\w-])/g, id).filter(
351
+ (h) => !cssColour(text, h) && !inShortRef.some(([from, to]) => h.at >= from && h.at < to),
352
+ ),
353
+ ...hits(text, shortRef, (m) => (ours === null ? m[2]! : null)),
354
+ ];
355
+ } else if (tracker === "linear" || tracker === "jira") {
356
+ const k = tracker === "linear" ? "[A-Za-z]+-[0-9]+" : "[A-Za-z][A-Za-z0-9]+-[0-9]+";
357
+ const plain = tracker === "linear" ? "[A-Z]+-[0-9]+" : "[A-Z][A-Z0-9]+-[0-9]+";
358
+ // bkit has no Linear workspace setting, so a Linear URL is matched on the team key alone.
359
+ // With no team / project / site configured, that part of the URL is not compared.
360
+ const site = tracker === "jira" && scope.site ? hostOf(scope.site) : null;
361
+ urlForm =
362
+ tracker === "linear"
363
+ ? new RegExp(`()linear\\.app\\/[^\\s/]+\\/issue\\/(${k})`, "gi")
364
+ : new RegExp(
365
+ `(?:[a-z][a-z0-9+.-]*:\\/\\/)?([^\\s/]+)(?:\\/\\S*?)?\\/browse\\/(${k})`,
366
+ "gi",
367
+ );
368
+ const ourUrl = (m: RegExpExecArray) => {
369
+ const key = m[2]!.toUpperCase();
370
+ if (prefix !== null && !key.startsWith(prefix)) return null;
371
+ if (site !== null && m[1]!.toLowerCase() !== site) return null;
372
+ return key;
373
+ };
374
+ explicit = [
375
+ ...hits(text, new RegExp(`<id>\\s*(${k})\\s*<\\/id>`, "gi"), upper),
376
+ ...hits(
377
+ text,
378
+ new RegExp(`<${tracker}_issue>\\s*(${k})\\s*<\\/${tracker}_issue>`, "gi"),
379
+ upper,
380
+ ),
381
+ ...hits(text, new RegExp(`${tracker} issue:\\s*(${k})\\b`, "gi"), upper),
382
+ ...hits(text, new RegExp(`\\b[Ii]ssue:?\\s+(${plain})\\b`, "g"), upper),
383
+ ...hits(text, new RegExp(`\\bISSUE-(${plain})\\b`, "g"), upper),
384
+ ...hits(text, urlForm, ourUrl),
385
+ ];
386
+ bare = hits(text, new RegExp(`(?<![\\w-])(${plain})(?![\\w-])`, "g"), upper);
387
+ if (prefix === null) {
388
+ skipped = bare;
389
+ bare = [];
390
+ } else {
391
+ bare = bare.filter((h) => h.value.startsWith(prefix));
392
+ }
393
+ } else {
394
+ return { explicit: [], bare: [], skipped: [] };
395
+ }
396
+ const urls = [...spans(text, ANY_URL), ...spans(text, urlForm)];
397
+ const outsideUrls = (h: Hit) => !urls.some(([from, to]) => h.at >= from && h.at < to);
398
+ const shape = ISSUE_ID_PATTERNS[tracker];
399
+ const keep = (list: Hit[]) => list.filter((h) => shape.test(h.value)).sort(byPosition);
400
+ return {
401
+ explicit: keep(explicit),
402
+ bare: keep(bare.filter(outsideUrls)),
403
+ skipped: keep(skipped.filter(outsideUrls)),
404
+ };
405
+ }
406
+
407
+ /** The issues a prompt names: the distinct explicit ids, else the distinct bare ones, in text order. */
408
+ export function issueCandidates(refs: { explicit: Hit[]; bare: Hit[] }): string[] {
409
+ const pool = refs.explicit.length > 0 ? refs.explicit : refs.bare;
410
+ return [...new Set(pool.map((h) => h.value))];
411
+ }
412
+
413
+ /** All-digit words a prompt holds outside URLs, tags, `/commands` and `#N`: an issue typed without its `#`. */
414
+ export function bareNumbers(text: string): string[] {
415
+ const plain = text
416
+ .replace(/\S+:\/\/\S+/g, " ")
417
+ .replace(/<[^>]*>/g, " ")
418
+ .replace(/(^|\s)\/\S+/g, " ");
419
+ return [...plain.matchAll(/(?<![\w#/.-])([0-9]+)(?![\w/.-])/g)].map((m) => m[1]!);
420
+ }
421
+
422
+ /** The stderr hint for a bare number: how to write it so it names the issue. */
423
+ function bareNumberHint(n: string, tracker: IssueTracker, key: string | null): string {
424
+ const write = tracker === "github" ? `#${n}` : `its issue key (${key ?? "KEY"}-${n})`;
425
+ return `${n} reads as a bare number; write ${write}`;
426
+ }
427
+
428
+ /** The FID a prompt names explicitly: `feat/` and `docs/plans/` paths always, a bare word only when `logs/{word}/` exists. */
429
+ export function namedFid(text: string, roots: string[]): string | null {
430
+ const fid = (m: RegExpExecArray) => {
431
+ const f = m[1]!.replace(/-+$/, "");
432
+ return SLUG.test(f) ? f : null;
433
+ };
434
+ const logged = loggedNames(roots);
435
+ const found = [
436
+ ...hits(text, /\bfeat\/([a-z0-9][a-z0-9-]*)/g, fid),
437
+ ...hits(text, /docs\/plans\/[0-9]{6}\/logs\/([a-z0-9][a-z0-9-]*)/g, fid),
438
+ ...hits(
439
+ text,
440
+ /docs\/plans\/[0-9]{6}\/([a-z0-9][a-z0-9-]*?)-(?:design|plan)(?:-[0-9]+)?\.md/g,
441
+ fid,
442
+ ),
443
+ ...hits(text, /(?<![\w/-])([a-z0-9][a-z0-9-]*[a-z0-9])(?![\w/-])/g, (m) =>
444
+ logged.has(m[1]!) ? m[1]! : null,
445
+ ),
446
+ ].sort((a, b) => a.at - b.at);
447
+ return found[0]?.value ?? null;
448
+ }
449
+
450
+ /** `#N` for GitHub, the key itself for Linear and Jira, "" with no issue. */
451
+ export const issueRef = (issue: string, tracker: IssueTracker) =>
452
+ issue === "" ? "" : tracker === "github" ? `#${issue}` : issue;
453
+
454
+ /** A feature's plan in a month bucket, as ship reads it: `{FID}-plan.md`, or none. */
455
+ export function planFiles(
456
+ root: string,
457
+ fid: string,
458
+ month: string,
459
+ ): { source: "single" | "none"; plan: string | null } {
460
+ const name = `${fid}-plan.md`;
461
+ return fs.existsSync(path.join(root, "docs", "plans", month, name))
462
+ ? { source: "single", plan: `docs/plans/${month}/${name}` }
463
+ : { source: "none", plan: null };
464
+ }
465
+
466
+ /** The `**Parent design:**` link target's FID and month in the text, or null. */
467
+ export function parentDesignLink(text: string): { fid: string; month: string } | null {
468
+ const m =
469
+ /\*\*Parent design:\*\*[^\n]*?docs\/plans\/([0-9]{6})\/([a-z0-9][a-z0-9-]*)-design\.md/.exec(
470
+ text,
471
+ );
472
+ return m ? { month: m[1]!, fid: m[2]! } : null;
473
+ }
474
+
475
+ /** Every `docs/audits/{YYYYMM}/*.md` path in the texts, first mention order, unique. */
476
+ export function auditPaths(...texts: string[]): string[] {
477
+ const seen = new Set<string>();
478
+ for (const text of texts) {
479
+ for (const m of text.matchAll(/docs\/audits\/[0-9]{6}\/[A-Za-z0-9._-]+\.md/g)) seen.add(m[0]);
480
+ }
481
+ return [...seen];
482
+ }
483
+
63
484
  /**
64
485
  * The canonical design doc for a feature, `docs/plans/{YYYYMM}/{fid}-design.md`: the
65
486
  * `month` bucket first, else the newest bucket holding one. null when none exists.
@@ -81,10 +502,46 @@ export function designDoc(
81
502
  return hit === undefined ? null : { month: hit, path: `docs/plans/${hit}/${fid}-design.md` };
82
503
  }
83
504
 
84
- /** `package.json` `bkit.issueTracker` at the main checkout (cwd outside git); default `none`. */
85
- export function readIssueTracker(cwd: string): IssueTracker {
505
+ /** `package.json` `bkit` config at the main checkout (cwd outside git). */
506
+ function mainConfig(cwd: string) {
86
507
  const common = git(cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
87
- return readBkitConfig(common ? path.dirname(common) : cwd).issueTracker;
508
+ return readBkitConfig(common ? path.dirname(common) : cwd);
509
+ }
510
+
511
+ /** `package.json` `bkit.tracker.default` at the main checkout (cwd outside git); default `none`. */
512
+ export function readIssueTracker(cwd: string): IssueTracker {
513
+ return mainConfig(cwd).issueTracker;
514
+ }
515
+
516
+ /**
517
+ * Where this repo's issues live, per tracker: github the `origin` owner/repo (read from the
518
+ * remote, not gh, so a prompt parse makes no network call); linear `bkit.tracker.linear.team`; jira
519
+ * `bkit.tracker.jira.project` and `bkit.tracker.jira.site`. Each is null when unset.
520
+ */
521
+ function issueScope(cwd: string, tracker: IssueTracker): IssueScope {
522
+ if (tracker === "github") return { key: null, ownerRepo: originOwnerRepo(cwd), site: null };
523
+ if (tracker !== "linear" && tracker !== "jira") return { key: null };
524
+ const cfg = mainConfig(cwd);
525
+ return tracker === "linear"
526
+ ? { key: cfg.linear.team }
527
+ : { key: cfg.jira.project, site: cfg.jira.site };
528
+ }
529
+
530
+ /** The setting that names the issue-key prefix of a keyed tracker. */
531
+ const KEY_SETTING = {
532
+ linear: "bkit.tracker.linear.team",
533
+ jira: "bkit.tracker.jira.project",
534
+ } as const;
535
+
536
+ /** The stderr hint for bare keys skipped because no key prefix is configured. */
537
+ function skippedKeyHint(skipped: string[], tracker: "linear" | "jira"): string {
538
+ 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"`;
539
+ }
540
+
541
+ /** The current tree and the main checkout: where log folders are looked for. */
542
+ function fidRoots(cwd: string): string[] {
543
+ const top = git(cwd, ["rev-parse", "--show-toplevel"]) ?? cwd;
544
+ return [...new Set([top, repoRoot(cwd)])];
88
545
  }
89
546
 
90
547
  function trackerFlag(value: string | undefined, cwd: string, allowAny: boolean): FidTracker {
@@ -136,27 +593,69 @@ export interface ParsedFid {
136
593
  source: "marker" | "branch";
137
594
  }
138
595
 
139
- /** FID from the marker, when present and well-formed for the tracker. */
596
+ /**
597
+ * FID from the marker, when present and well-formed for the tracker. A wired tracker also
598
+ * accepts the FID-only marker of an issue-less run: its FID must be issue-less, and it
599
+ * resolves to `issueId: null`.
600
+ */
140
601
  export function fromMarker(text: string, tracker: IssueTracker): ParsedFid | null {
141
602
  const m = MARKERS[tracker].exec(text);
142
- if (!m) return null;
603
+ if (!m) {
604
+ if (tracker === "none") return null;
605
+ const bare = MARKERS.none.exec(text);
606
+ const fid = bare?.[1];
607
+ return fid !== undefined && ISSUE_LESS_FID.test(fid)
608
+ ? { fid, issueId: null, source: "marker" }
609
+ : null;
610
+ }
143
611
  const fid = normaliseFid(m[m.length - 1]!, tracker);
144
612
  if (!FID_PATTERNS[tracker].test(fid)) return null;
145
613
  const issueId = tracker === "none" ? null : KEYED.has(tracker) ? m[1]!.toUpperCase() : m[1]!;
146
614
  return { fid, issueId, source: "marker" };
147
615
  }
148
616
 
149
- /** FID from `feat/{FID}`; the slug check, then the issue id the tracker needs. */
617
+ /**
618
+ * The issue ids a repo's feature rows in `.bkit/issues.jsonl` carry in their FID keys,
619
+ * per the tracker's FID shape (`650-x` -> `650`; linear and jira keys uppercased).
620
+ */
621
+ export function featureIssueIds(root: string, tracker: IssueTracker): ReadonlySet<string> {
622
+ const file = path.join(root, ".bkit", "issues.jsonl");
623
+ const ids = new Set<string>();
624
+ if (tracker === "none" || !fs.existsSync(file) || !fs.statSync(file).isFile()) return ids;
625
+ for (const line of fs.readFileSync(file, "utf-8").split("\n")) {
626
+ if (line.trim() === "") continue;
627
+ const row = parseJson(line);
628
+ if (!row.ok || typeof row.value !== "object" || row.value === null) continue;
629
+ const { kind, key } = row.value as Record<string, unknown>;
630
+ if (kind !== "feature" || typeof key !== "string") continue;
631
+ const id = issueIdOf(key, tracker);
632
+ if (id !== null) ids.add(id);
633
+ }
634
+ return ids;
635
+ }
636
+
637
+ /**
638
+ * FID from `feat/{FID}`; the slug check, then the issue id the tracker needs. A wired
639
+ * tracker also accepts an issue-less FID (no issue id embedded, no all-digit word) as `issueId: null`.
640
+ * With `known` (the issue ids the repo's feature rows carry), the FID is the suffix verbatim
641
+ * for any slug: the issue id its shape embeds counts only when `known` holds it, else the
642
+ * run is issue-less (`issueId: null`).
643
+ */
150
644
  export function fromBranch(
151
645
  branch: string,
152
646
  tracker: IssueTracker,
647
+ known?: ReadonlySet<string>,
153
648
  ): { ok: true; parsed: ParsedFid } | { ok: false; why: string } {
154
649
  if (!branch.startsWith("feat/"))
155
650
  return { ok: false, why: `branch "${branch}" is not feat/{FID}` };
156
651
  const fid = branch.slice("feat/".length);
157
652
  if (!SLUG.test(fid)) return { ok: false, why: `"${fid}" is not a slug (${SLUG.source})` };
158
653
  const issueId = issueIdOf(fid, tracker);
159
- if (tracker !== "none" && issueId === null) {
654
+ if (known !== undefined) {
655
+ const linked = issueId !== null && known.has(issueId) ? issueId : null;
656
+ return { ok: true, parsed: { fid, issueId: linked, source: "branch" } };
657
+ }
658
+ if (tracker !== "none" && issueId === null && !ISSUE_LESS_FID.test(fid)) {
160
659
  return { ok: false, why: `"${fid}" embeds no ${tracker} issue id` };
161
660
  }
162
661
  return { ok: true, parsed: { fid, issueId, source: "branch" } };
@@ -165,32 +664,40 @@ export function fromBranch(
165
664
  const TRACKER_FLAG: FlagSpec = {
166
665
  name: "tracker",
167
666
  type: "string",
168
- help: "github | linear | jira | none (default: package.json bkit.issueTracker, else none)",
667
+ help: "github | linear | jira | none (default: package.json bkit.tracker.default, else none)",
169
668
  };
170
669
 
171
670
  export const fidsCommand: CommandSpec = {
172
671
  noun: "fids",
173
- summary: "Feature-id format per tracker, and FID recovery from a branch or PR-body marker.",
672
+ summary:
673
+ "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.",
174
674
  verbs: {
175
675
  check: {
176
676
  summary: "Validate a FID for the tracker: exit 0 valid, exit 1 not.",
177
677
  flags: [
178
678
  { name: "fid", type: "string", required: true, help: "feature id to check" },
179
679
  { ...TRACKER_FLAG, help: `${TRACKER_FLAG.help}; any = any tracker's shape (CI_DEV)` },
680
+ {
681
+ name: "issue",
682
+ type: "string",
683
+ 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',
684
+ },
180
685
  ],
181
686
  output: {
182
687
  fid: "the FID as checked (linear, jira: lowercased)",
183
688
  tracker: "tracker the shape came from",
184
689
  valid: "true when the FID matches",
185
- pattern: "the regex checked",
690
+ pattern: "the regex checked (the slug rule when --issue is empty)",
186
691
  issueId: "issue id the FID embeds (null under none, or when invalid)",
187
692
  },
188
693
  run: (ctx) => {
189
694
  const tracker = trackerFlag(str(ctx.flags.tracker), ctx.cwd, true);
190
695
  const fid = normaliseFid(String(ctx.flags.fid), tracker);
191
- const pattern = FID_PATTERNS[tracker];
192
- const valid = pattern.test(fid);
193
- if (!valid) ctx.log(`FID "${fid}" does not match the ${tracker} shape ${pattern.source}`);
696
+ const issue = str(ctx.flags.issue)?.replace(/^#/, "");
697
+ const pattern = issue === "" && tracker !== "none" ? SLUG : FID_PATTERNS[tracker];
698
+ const problem = fidProblem(fid, tracker, issue);
699
+ const valid = problem === undefined;
700
+ if (!valid) ctx.log(problem);
194
701
  ctx.emit({
195
702
  fid,
196
703
  tracker,
@@ -202,8 +709,14 @@ export const fidsCommand: CommandSpec = {
202
709
  },
203
710
  },
204
711
  parse: {
205
- summary: "Recover FID and issue id: the PR-body marker first, then a feat/{FID} branch.",
712
+ summary:
713
+ "--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).",
206
714
  flags: [
715
+ {
716
+ name: "prompt-file",
717
+ type: "string",
718
+ help: "the session prompt, written verbatim (Step 1: {SESSION_DIR}/prompt.md); not with --marker / --branch",
719
+ },
207
720
  {
208
721
  name: "marker",
209
722
  type: "string",
@@ -213,17 +726,77 @@ export const fidsCommand: CommandSpec = {
213
726
  TRACKER_FLAG,
214
727
  ],
215
728
  output: {
216
- fid: "the recovered FID",
217
- issueId: "tracker issue id (null under none)",
218
- source: "marker | branch",
219
- tracker: "tracker the shapes came from",
729
+ source:
730
+ "--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",
731
+ issue:
732
+ '--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 ""',
733
+ ambiguous:
734
+ "--prompt-file, exit 8 only: the issues named, as a person types them (then no other key prints)",
735
+ ref: '--prompt-file: the issue as a person types it (github: #N, linear / jira: the key), else ""',
736
+ fidNamed:
737
+ "--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",
738
+ fid: "--marker / --branch: the recovered FID",
739
+ issueId:
740
+ "--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)",
741
+ tracker: "--marker / --branch: tracker the shapes came from",
742
+ },
743
+ exitCodes: {
744
+ [EXIT_NO_FID]:
745
+ "neither the marker nor the branch yielded a FID (a branch that is not feat/ or whose suffix is not a slug)",
746
+ [EXIT_NO_FILE]: "the --prompt-file is missing",
747
+ [EXIT_AMBIGUOUS]: `--prompt-file names more than one issue (explicit forms first) — ${NAME_THE_ISSUE}`,
220
748
  },
221
- exitCodes: { [EXIT_NO_FID]: "neither the marker nor the branch yielded a valid FID" },
222
749
  run: (ctx) => {
223
750
  const marker = str(ctx.flags.marker);
224
751
  const branch = str(ctx.flags.branch);
752
+ const promptFile = str(ctx.flags.promptFile);
753
+ if (promptFile !== undefined) {
754
+ if (marker !== undefined || branch !== undefined)
755
+ throw new CommandError(
756
+ EXIT.USAGE,
757
+ "--prompt-file goes alone, without --marker / --branch",
758
+ );
759
+ const text = readNamed(path.resolve(ctx.cwd, promptFile), "prompt-file");
760
+ const tracker = trackerFlag(str(ctx.flags.tracker), ctx.cwd, false) as IssueTracker;
761
+ const scope = issueScope(ctx.cwd, tracker);
762
+ const key = scope.key ?? null;
763
+ const refs = issueRefs(text, tracker, scope);
764
+ const candidates = issueCandidates(refs);
765
+ if (candidates.length > 1) {
766
+ const named = candidates.map((c) => issueRef(c, tracker));
767
+ ctx.log(
768
+ `the prompt names more than one issue (${named.join(", ")}); ${NAME_THE_ISSUE}`,
769
+ );
770
+ ctx.emit({ ambiguous: named });
771
+ return EXIT_AMBIGUOUS;
772
+ }
773
+ const issue = candidates[0] ?? "";
774
+ const others = [...new Set([...refs.explicit, ...refs.bare].map((r) => r.value))].filter(
775
+ (v) => v !== issue,
776
+ );
777
+ if (others.length > 0)
778
+ ctx.log(
779
+ `taking ${issueRef(issue, tracker)}, named explicitly; not the bare mention ${others.map((o) => issueRef(o, tracker)).join(", ")}`,
780
+ );
781
+ const bareNumber = bareNumbers(text)[0];
782
+ if (issue === "" && tracker !== "none" && bareNumber !== undefined)
783
+ ctx.log(bareNumberHint(bareNumber, tracker, key));
784
+ if (
785
+ issue === "" &&
786
+ refs.skipped.length > 0 &&
787
+ (tracker === "linear" || tracker === "jira")
788
+ )
789
+ ctx.log(skippedKeyHint([...new Set(refs.skipped.map((h) => h.value))], tracker));
790
+ ctx.emit({
791
+ source: issue === "" ? "none" : tracker,
792
+ issue,
793
+ ref: issueRef(issue, tracker),
794
+ fidNamed: namedFid(text, fidRoots(ctx.cwd)),
795
+ });
796
+ return EXIT.OK;
797
+ }
225
798
  if (marker === undefined && branch === undefined) {
226
- throw new CommandError(EXIT.USAGE, "give --marker, --branch, or both");
799
+ throw new CommandError(EXIT.USAGE, "give --prompt-file, or --marker, --branch, or both");
227
800
  }
228
801
  const tracker = trackerFlag(str(ctx.flags.tracker), ctx.cwd, false) as IssueTracker;
229
802
  const viaMarker = marker === undefined ? null : fromMarker(marker, tracker);
@@ -234,7 +807,8 @@ export const fidsCommand: CommandSpec = {
234
807
  if (marker !== undefined)
235
808
  ctx.log(`no well-formed ${tracker} bkit:fid marker — trying the branch`);
236
809
  if (branch === undefined) return EXIT_NO_FID;
237
- const viaBranch = fromBranch(branch, tracker);
810
+ const top = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? ctx.cwd;
811
+ const viaBranch = fromBranch(branch, tracker, featureIssueIds(top, tracker));
238
812
  if (!viaBranch.ok) {
239
813
  ctx.log(viaBranch.why);
240
814
  return EXIT_NO_FID;
@@ -243,9 +817,140 @@ export const fidsCommand: CommandSpec = {
243
817
  return EXIT.OK;
244
818
  },
245
819
  },
820
+ resolve: {
821
+ summary:
822
+ "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).",
823
+ flags: [
824
+ {
825
+ name: "prompt-file",
826
+ type: "string",
827
+ required: true,
828
+ help: "the session prompt, written verbatim ({SESSION_DIR}/prompt.md)",
829
+ },
830
+ {
831
+ name: "issue",
832
+ type: "string",
833
+ help: 'the run\'s issue id (github: 123; linear / jira: ABC-123), or "" / absent for a run with no issue',
834
+ },
835
+ {
836
+ name: "title-file",
837
+ type: "string",
838
+ help: "the issue title: a JSON object with a title key, else the file's text; drop it for a run with no issue",
839
+ },
840
+ {
841
+ ...WORKFLOW_FLAG,
842
+ help: "the workflow starting; an in-progress run of it continues a used mint instead of suffixing",
843
+ },
844
+ TRACKER_FLAG,
845
+ ],
846
+ output: {
847
+ fid: "the FID to use",
848
+ source:
849
+ "prompt | branch | logged | minted | suffixed — the link of the chain that gave fid",
850
+ month: "the newest bucket holding logs/{fid}/, else null",
851
+ existing: "true when logs/{fid}/ exists in some bucket",
852
+ fids: "every FID logged for the issue (working tree and dev) when the chain reached that link, else []",
853
+ },
854
+ exitCodes: {
855
+ [EXIT_SEVERAL]: "several features are logged for the issue — name one in the prompt",
856
+ [EXIT_NO_FREE]: "the mint and every -b … -z suffix of it are used by finished runs",
857
+ [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}`,
858
+ [EXIT_NO_FILE]: "the --prompt-file or --title-file is missing",
859
+ },
860
+ run: (ctx) => {
861
+ const tracker = trackerFlag(str(ctx.flags.tracker), ctx.cwd, false) as IssueTracker;
862
+ const issue = (str(ctx.flags.issue) ?? "").replace(/^#/, "");
863
+ const prompt = readNamed(
864
+ path.resolve(ctx.cwd, String(ctx.flags.promptFile)),
865
+ "prompt-file",
866
+ );
867
+ const titleFile = str(ctx.flags.titleFile);
868
+ const title =
869
+ titleFile === undefined
870
+ ? ""
871
+ : titleOf(readNamed(path.resolve(ctx.cwd, titleFile), "title-file"));
872
+ const workflow = String(ctx.flags.workflow);
873
+ const roots = fidRoots(ctx.cwd);
874
+ const branch = git(ctx.cwd, ["branch", "--show-current"]) || null;
875
+ const prefix = KEYED.has(tracker) ? `${issue.toLowerCase()}-` : `${issue}-`;
876
+
877
+ let fids: string[] = [];
878
+ let pick: { fid: string; source: string } | null = null;
879
+ const named = namedFid(prompt, roots);
880
+ if (named !== null) pick = { fid: named, source: "prompt" };
881
+ const onBranch = branch?.startsWith("feat/") ? branch.slice("feat/".length) : null;
882
+ if (pick === null && onBranch !== null && SLUG.test(onBranch)) {
883
+ if (issue === "" || onBranch.startsWith(prefix))
884
+ pick = { fid: onBranch, source: "branch" };
885
+ }
886
+ if (pick === null && issue !== "") {
887
+ fids = [
888
+ ...new Set([...roots.flatMap((r) => logged(r, issue)), ...loggedOnDev(ctx.cwd, issue)]),
889
+ ].sort();
890
+ if (fids.length > 1) {
891
+ ctx.log(`several features logged for ${issue}: ${fids.join(", ")}`);
892
+ ctx.emit({ fid: null, source: null, month: null, existing: false, fids });
893
+ return EXIT_SEVERAL;
894
+ }
895
+ if (fids.length === 1) pick = { fid: fids[0]!, source: "logged" };
896
+ }
897
+ const bareNumber = bareNumbers(prompt)[0];
898
+ if (
899
+ pick === null &&
900
+ issue === "" &&
901
+ tracker !== "none" &&
902
+ bareNumber !== undefined &&
903
+ slugWords(title).length === 0 &&
904
+ slugWords(prompt).length === 0
905
+ ) {
906
+ ctx.log(
907
+ `${bareNumberHint(bareNumber, tracker, issueScope(ctx.cwd, tracker).key ?? null)} — refusing to mint a FID from the workflow name alone`,
908
+ );
909
+ return EXIT_BARE_NUMBER;
910
+ }
911
+ if (pick === null) {
912
+ const minted = normaliseFid(mintFid({ issue, title, prompt, branch, workflow }), tracker);
913
+ const free = freeFid(roots, minted, workflow);
914
+ if (free === null) {
915
+ ctx.log(`"${minted}" and every -b … -z suffix of it are used by finished runs`);
916
+ return EXIT_NO_FREE;
917
+ }
918
+ pick = { fid: free, source: free === minted ? "minted" : "suffixed" };
919
+ }
920
+ const fid = normaliseFid(pick.fid, tracker);
921
+ const problem = fidProblem(fid, tracker, issue);
922
+ if (problem !== undefined) {
923
+ ctx.log(`${pick.source} FID: ${problem}`);
924
+ return EXIT.NO;
925
+ }
926
+ const month =
927
+ roots
928
+ .flatMap((r) => monthBuckets(r, fid))
929
+ .sort()
930
+ .at(-1) ?? null;
931
+ ctx.emit({ fid, source: pick.source, month, existing: month !== null, fids });
932
+ return EXIT.OK;
933
+ },
934
+ },
935
+ plans: {
936
+ summary: "A feature's plan in a month bucket: docs/plans/{YYYYMM}/{FID}-plan.md, or none.",
937
+ flags: [
938
+ { name: "fid", type: "string", required: true, help: "feature id" },
939
+ { name: "month", type: "string", required: true, help: "YYYYMM bucket" },
940
+ ],
941
+ output: {
942
+ source: "single ({FID}-plan.md exists) | none (no plan file)",
943
+ plan: "the repo-relative plan file, or null",
944
+ },
945
+ run: (ctx) => {
946
+ const top = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? ctx.cwd;
947
+ ctx.emit(planFiles(top, String(ctx.flags.fid), String(ctx.flags.month)));
948
+ return EXIT.OK;
949
+ },
950
+ },
246
951
  design: {
247
952
  summary:
248
- "The feature's own design doc, docs/plans/{YYYYMM}/{FID}-design.md: exit 0 found, exit 1 none.",
953
+ "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).",
249
954
  flags: [
250
955
  { name: "fid", type: "string", required: true, help: "feature id" },
251
956
  {
@@ -253,19 +958,74 @@ export const fidsCommand: CommandSpec = {
253
958
  type: "string",
254
959
  help: "YYYYMM bucket checked first; else the newest bucket holding the doc",
255
960
  },
961
+ {
962
+ name: "description-file",
963
+ type: "string",
964
+ help: "the issue description; drop it for a run with no issue",
965
+ },
966
+ {
967
+ name: "prompt-file",
968
+ type: "string",
969
+ help: "the session prompt ({SESSION_DIR}/prompt.md)",
970
+ },
256
971
  ],
257
972
  output: {
258
- fid: "the FID when its design doc exists, else null",
973
+ fid: "the FID when its own design doc exists, else null",
259
974
  month: "the bucket holding it, else null",
260
975
  path: "repo-relative path, else null",
976
+ parentFid: "the parent design's FID (the link's, else the feature's own), else null",
977
+ parentMonth: "its bucket, else null",
978
+ parentPath: "its repo-relative path, else null",
979
+ parentSource: "link | fid | null",
980
+ auditPaths:
981
+ "every docs/audits/{YYYYMM}/*.md path the description, then the prompt, names, first mention order",
982
+ },
983
+ exitCodes: {
984
+ [EXIT_NO_FILE]:
985
+ "a --description-file / --prompt-file is missing, or a linked design or named audit path is not a file",
261
986
  },
262
987
  run: (ctx) => {
263
988
  const fid = String(ctx.flags.fid);
264
- const hit = designDoc(repoRoot(ctx.cwd), fid, str(ctx.flags.month));
265
- ctx.emit(
266
- hit ? { fid, month: hit.month, path: hit.path } : { fid: null, month: null, path: null },
267
- );
268
- return hit ? EXIT.OK : EXIT.NO;
989
+ const root = repoRoot(ctx.cwd);
990
+ const texts = (["descriptionFile", "promptFile"] as const).flatMap((k) => {
991
+ const file = str(ctx.flags[k]);
992
+ return file === undefined
993
+ ? []
994
+ : [
995
+ readNamed(
996
+ path.resolve(ctx.cwd, file),
997
+ k === "promptFile" ? "prompt-file" : "description-file",
998
+ ),
999
+ ];
1000
+ });
1001
+ const own = designDoc(root, fid, str(ctx.flags.month));
1002
+ const link = texts.map(parentDesignLink).find((l) => l !== null) ?? null;
1003
+ const parent = link
1004
+ ? {
1005
+ fid: link.fid,
1006
+ month: link.month,
1007
+ path: `docs/plans/${link.month}/${link.fid}-design.md`,
1008
+ source: "link",
1009
+ }
1010
+ : own
1011
+ ? { fid, month: own.month, path: own.path, source: "fid" }
1012
+ : null;
1013
+ const audits = auditPaths(...texts);
1014
+ for (const rel of [...(link && parent ? [parent.path] : []), ...audits]) {
1015
+ if (!fs.statSync(path.join(root, rel), { throwIfNoEntry: false })?.isFile())
1016
+ throw new CommandError(EXIT_NO_FILE, `${rel} is named but is not a file`);
1017
+ }
1018
+ ctx.emit({
1019
+ ...(own
1020
+ ? { fid, month: own.month, path: own.path }
1021
+ : { fid: null, month: null, path: null }),
1022
+ parentFid: parent?.fid ?? null,
1023
+ parentMonth: parent?.month ?? null,
1024
+ parentPath: parent?.path ?? null,
1025
+ parentSource: parent?.source ?? null,
1026
+ auditPaths: audits,
1027
+ });
1028
+ return parent ? EXIT.OK : EXIT.NO;
269
1029
  },
270
1030
  },
271
1031
  find: {