@cbartens/bkit 5.2.4 → 5.4.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 (271) hide show
  1. package/.bkit/README.md +27 -11
  2. package/.bkit/core/.agents/context.md +1 -1
  3. package/.bkit/core/.agents/docs.md +1 -1
  4. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-guardrails.cjs +1 -1
  5. package/.bkit/core/.agents/rules.md +18 -1
  6. package/.bkit/core/.bkit/README.md +26 -10
  7. package/.bkit/core/.bkit/cloud.md +40 -39
  8. package/.bkit/core/.bkit/comparison.md +68 -345
  9. package/.bkit/core/.bkit/install.md +16 -9
  10. package/.bkit/core/.bkit/lite.md +73 -0
  11. package/.bkit/core/.bkit/pipeline.md +346 -0
  12. package/.bkit/core/.bkit/prompts.md +90 -74
  13. package/.bkit/core/.bkit/providers.md +42 -23
  14. package/.bkit/core/.bkit/templates.md +138 -19
  15. package/.bkit/core/.bkit/trackers.md +49 -4
  16. package/.bkit/core/.bkit/workflows.md +144 -123
  17. package/.bkit/core/.claude/hooks/bkit-guardrails.cjs +1 -1
  18. package/.bkit/core/.codex/hooks/bkit-guardrails.cjs +7 -4
  19. package/.bkit/core/.cursor/hooks/bkit-guardrails.cjs +8 -5
  20. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +3 -2
  21. package/.bkit/core/docs/templates/bkit-audit-adoption.md +2 -2
  22. package/.bkit/core/docs/templates/bkit-audit-agents.md +1 -1
  23. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +1 -1
  24. package/.bkit/core/docs/templates/bkit-audit-analytics.md +1 -1
  25. package/.bkit/core/docs/templates/bkit-audit-annotations.md +1 -1
  26. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +1 -1
  27. package/.bkit/core/docs/templates/bkit-audit-app-store.md +1 -1
  28. package/.bkit/core/docs/templates/bkit-audit-architecture.md +1 -1
  29. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +4 -2
  30. package/.bkit/core/docs/templates/bkit-audit-config.md +3 -2
  31. package/.bkit/core/docs/templates/bkit-audit-cost.md +3 -2
  32. package/.bkit/core/docs/templates/bkit-audit-coverage.md +1 -1
  33. package/.bkit/core/docs/templates/bkit-audit-database.md +3 -2
  34. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +5 -5
  35. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +1 -1
  36. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +26 -21
  37. package/.bkit/core/docs/templates/bkit-audit-documentation.md +1 -1
  38. package/.bkit/core/docs/templates/bkit-audit-duplication.md +2 -2
  39. package/.bkit/core/docs/templates/bkit-audit-failures.md +1 -1
  40. package/.bkit/core/docs/templates/bkit-audit-flakes.md +3 -2
  41. package/.bkit/core/docs/templates/bkit-audit-gates.md +5 -2
  42. package/.bkit/core/docs/templates/bkit-audit-issues.md +3 -2
  43. package/.bkit/core/docs/templates/bkit-audit-llm.md +22 -15
  44. package/.bkit/core/docs/templates/bkit-audit-logs.md +10 -6
  45. package/.bkit/core/docs/templates/bkit-audit-models.md +1 -1
  46. package/.bkit/core/docs/templates/bkit-audit-privacy.md +1 -1
  47. package/.bkit/core/docs/templates/bkit-audit-prompts.md +7 -7
  48. package/.bkit/core/docs/templates/bkit-audit-red-team.md +12 -9
  49. package/.bkit/core/docs/templates/bkit-audit-reliability.md +3 -2
  50. package/.bkit/core/docs/templates/bkit-audit-repo.md +1 -1
  51. package/.bkit/core/docs/templates/bkit-audit-security.md +14 -12
  52. package/.bkit/core/docs/templates/bkit-audit-slop.md +1 -1
  53. package/.bkit/core/docs/templates/bkit-audit-testing.md +10 -8
  54. package/.bkit/core/docs/templates/bkit-audit-usability.md +1 -1
  55. package/.bkit/core/docs/templates/bkit-plan.md +8 -6
  56. package/.bkit/core/engine/checks/after/auth.ts +9 -9
  57. package/.bkit/core/engine/checks/after/ci-yml.ts +14 -12
  58. package/.bkit/core/engine/checks/after/github.ts +29 -120
  59. package/.bkit/core/engine/checks/after/index.ts +2 -2
  60. package/.bkit/core/engine/checks/after/managed.ts +8 -28
  61. package/.bkit/core/engine/checks/after/tools.ts +3 -15
  62. package/.bkit/core/engine/checks/before/context-fetch.ts +1 -21
  63. package/.bkit/core/engine/checks/before/index.ts +7 -43
  64. package/.bkit/core/engine/checks/before/mcp.ts +17 -8
  65. package/.bkit/core/engine/checks/before/repo.ts +9 -12
  66. package/.bkit/core/engine/checks/status-holes.ts +4 -6
  67. package/.bkit/core/engine/checks/tips/catalogue.ts +76 -24
  68. package/.bkit/core/engine/checks/tips/detect.ts +45 -2
  69. package/.bkit/core/engine/checks/tips/index.ts +77 -26
  70. package/.bkit/core/engine/cli.ts +57 -27
  71. package/.bkit/core/engine/commands/analysis.ts +36 -26
  72. package/.bkit/core/engine/commands/comply.ts +42 -32
  73. package/.bkit/core/engine/commands/harvest.ts +12 -12
  74. package/.bkit/core/engine/commands/install/doctor.ts +57 -28
  75. package/.bkit/core/engine/commands/install/install.ts +73 -130
  76. package/.bkit/core/engine/commands/install/uninstall.ts +191 -33
  77. package/.bkit/core/engine/commands/install/upgrade.ts +49 -43
  78. package/.bkit/core/engine/commands/land.ts +156 -0
  79. package/.bkit/core/engine/commands/lib.ts +45 -18
  80. package/.bkit/core/engine/commands/registry.ts +2 -0
  81. package/.bkit/core/engine/commands/tips.ts +12 -5
  82. package/.bkit/core/engine/commands/workflow/branches.ts +386 -286
  83. package/.bkit/core/engine/commands/workflow/counters.ts +21 -12
  84. package/.bkit/core/engine/commands/workflow/disk.ts +556 -0
  85. package/.bkit/core/engine/commands/workflow/fids.ts +46 -0
  86. package/.bkit/core/engine/commands/workflow/issues.ts +73 -28
  87. package/.bkit/core/engine/commands/workflow/ledgers.ts +3 -1
  88. package/.bkit/core/engine/commands/workflow/locks.ts +38 -152
  89. package/.bkit/core/engine/commands/workflow/prs.ts +15 -4
  90. package/.bkit/core/engine/commands/workflow/repo.ts +2 -2
  91. package/.bkit/core/engine/commands/workflow/roadmap.ts +49 -53
  92. package/.bkit/core/engine/commands/workflow/runs.ts +8 -7
  93. package/.bkit/core/engine/commands/workflow/runtime.ts +3 -2
  94. package/.bkit/core/engine/commands/workflow/status.ts +33 -11
  95. package/.bkit/core/engine/commands/workflow/steps.ts +25 -15
  96. package/.bkit/core/engine/commands/workflow/tests.ts +17 -5
  97. package/.bkit/core/engine/commands/workflow/workflows.ts +436 -267
  98. package/.bkit/core/engine/commands/workflow/workstreams.ts +4 -2
  99. package/.bkit/core/engine/commands/workflow/worktrees.ts +24 -6
  100. package/.bkit/core/engine/install/cloud-env.ts +10 -31
  101. package/.bkit/core/engine/install/manifest.ts +14 -7
  102. package/.bkit/core/engine/install/modules/antigravity.ts +15 -26
  103. package/.bkit/core/engine/install/modules/claude.ts +20 -28
  104. package/.bkit/core/engine/install/modules/cloud.ts +5 -2
  105. package/.bkit/core/engine/install/modules/codex.ts +15 -29
  106. package/.bkit/core/engine/install/modules/core.ts +106 -70
  107. package/.bkit/core/engine/install/modules/cursor.ts +6 -20
  108. package/.bkit/core/engine/install/modules/index.ts +7 -1
  109. package/.bkit/core/engine/install/modules/opencode.ts +48 -70
  110. package/.bkit/core/engine/install/network-allowlist.ts +73 -0
  111. package/.bkit/core/engine/install/placeholders.ts +16 -35
  112. package/.bkit/core/engine/install/write.ts +59 -12
  113. package/.bkit/core/engine/ledgers/telemetry.ts +6 -4
  114. package/.bkit/core/engine/render/hosts.ts +47 -67
  115. package/.bkit/core/engine/render/models.ts +29 -11
  116. package/.bkit/core/engine/shared/branches.ts +13 -0
  117. package/.bkit/core/engine/shared/egress.ts +3 -3
  118. package/.bkit/core/engine/shared/json.ts +18 -1
  119. package/.bkit/core/engine/shared/package-json.ts +63 -0
  120. package/.bkit/core/engine/shared/package-roots.ts +0 -10
  121. package/.bkit/core/engine/shared/protected-paths.ts +5 -130
  122. package/.bkit/core/engine/shared/settings.ts +44 -0
  123. package/.bkit/core/engine/shared/timeouts.ts +8 -7
  124. package/.bkit/core/hooks/antigravity-hook.js +1 -0
  125. package/.bkit/core/hooks/guardrails-shell.js +186 -40
  126. package/.bkit/core/hooks/guardrails-tiers.js +5 -78
  127. package/.bkit/core/prompts/bkit-audit-generate.md +103 -7
  128. package/.bkit/core/prompts/bkit-build-challenge-1.md +1 -1
  129. package/.bkit/core/prompts/bkit-build-challenge-2.md +1 -1
  130. package/.bkit/core/prompts/bkit-build-challenge-reconcile.md +1 -1
  131. package/.bkit/core/prompts/bkit-build-challenge-remediate.md +1 -1
  132. package/.bkit/core/prompts/bkit-build-challenge-tests.md +1 -1
  133. package/.bkit/core/prompts/bkit-build-install-skills.md +1 -1
  134. package/.bkit/core/prompts/bkit-build-plan-current.md +1 -1
  135. package/.bkit/core/prompts/bkit-build-plan-execute.md +4 -4
  136. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +1 -1
  137. package/.bkit/core/prompts/bkit-build-plan-verify.md +2 -2
  138. package/.bkit/core/prompts/bkit-debug-abort-handover.md +1 -1
  139. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +1 -1
  140. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +1 -1
  141. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +78 -0
  142. package/.bkit/core/prompts/bkit-debug-failure-soak.md +1 -1
  143. package/.bkit/core/prompts/bkit-debug-summary.md +3 -3
  144. package/.bkit/core/prompts/bkit-design-spike.md +1 -1
  145. package/.bkit/core/prompts/bkit-design-summary.md +2 -2
  146. package/.bkit/core/prompts/bkit-design-update.md +1 -1
  147. package/.bkit/core/prompts/bkit-plan-complexity-check.md +1 -1
  148. package/.bkit/core/prompts/bkit-plan-generate.md +1 -1
  149. package/.bkit/core/prompts/bkit-plan-scope-check-1.md +1 -1
  150. package/.bkit/core/prompts/bkit-plan-scope-check-2.md +1 -1
  151. package/.bkit/core/prompts/bkit-plan-summary.md +1 -1
  152. package/.bkit/core/prompts/bkit-plan-update.md +1 -1
  153. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +1 -1
  154. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +1 -1
  155. package/.bkit/core/prompts/bkit-ship-update-docs.md +1 -1
  156. package/.bkit/core/prompts/bkit-utility-update-decisions.md +9 -2
  157. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +9 -2
  158. package/.bkit/core/prompts/bkit-utility-update-documentation.md +2 -1
  159. package/.bkit/core/prompts/bkit-utility-update-failures.md +9 -2
  160. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +9 -2
  161. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +11 -4
  162. package/.bkit/core/workflows/bkit-auto.md +2 -2
  163. package/.bkit/core/workflows/bkit-build.md +10 -10
  164. package/.bkit/core/workflows/bkit-debug.md +80 -44
  165. package/.bkit/core/workflows/bkit-design.md +22 -13
  166. package/.bkit/core/workflows/bkit-plan.md +33 -16
  167. package/.bkit/core/workflows/bkit-ship.md +87 -98
  168. package/.bkit/shared/.claude/bkit-cloud.md +58 -25
  169. package/.bkit/shared/.claude/settings.json +19 -0
  170. package/.bkit/shared/.cursor/mcp.json +2 -1
  171. package/.bkit/shared/.opencode/opencode.json +19 -1
  172. package/.bkit/shared/docs/deployments.md +49 -29
  173. package/.bkit/shared/docs/security.md +8 -6
  174. package/.bkit/shared/docs/testing.md +9 -5
  175. package/.bkit/shared/gitignore +1 -2
  176. package/.bkit/templates/.cursor/Dockerfile +30 -16
  177. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-bug.yml +78 -0
  178. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-change.yml +91 -0
  179. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-idea.yml +56 -0
  180. package/.bkit/templates/.github/renovate.json5 +91 -12
  181. package/.bkit/templates/.github/workflows/bkit-ci.yml +73 -55
  182. package/.bkit/templates/.github/workflows/bkit-cloud.yml +3 -1
  183. package/.bkit/templates/.github/workflows/bkit-renovate.yml +8 -1
  184. package/.bkit/templates/.github/workflows/bkit-trivy.yml +67 -0
  185. package/.bkit/templates/.husky/pre-commit +6 -0
  186. package/.bkit/templates/.husky/pre-push +15 -3
  187. package/.bkit/templates/.lintstagedrc.json +5 -1
  188. package/.bkit/templates/.oxlintrc.json +21 -0
  189. package/.bkit/templates/docs/capabilities.md +1 -1
  190. package/.bkit/templates/scripts/ci/check-capstone.mjs +176 -0
  191. package/.bkit/templates/scripts/ci/check-capstone.test.mjs +311 -0
  192. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.machine.mjs +197 -0
  193. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.mjs +164 -0
  194. package/.bkit/templates/scripts/graphify/bkit-graph-eager.py +2 -2
  195. package/.bkit/templates/scripts/graphify/bkit-graph-imports.py +43 -20
  196. package/.bkit/templates/scripts/graphify/bkit-graph-pre-push.sh +33 -11
  197. package/.bkit/templates/scripts/graphify/bkit-graph-repair.py +3 -2
  198. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +5 -5
  199. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +79 -19
  200. package/CHANGELOG.md +98 -3
  201. package/README.md +252 -122
  202. package/dist/checks/after/auth.js +10 -11
  203. package/dist/checks/after/ci-yml.js +11 -14
  204. package/dist/checks/after/github.js +32 -125
  205. package/dist/checks/after/index.js +3 -2
  206. package/dist/checks/after/managed.js +8 -24
  207. package/dist/checks/after/tools.js +3 -16
  208. package/dist/checks/before/context-fetch.js +1 -21
  209. package/dist/checks/before/index.js +6 -42
  210. package/dist/checks/before/mcp.js +14 -9
  211. package/dist/checks/before/repo.js +8 -11
  212. package/dist/checks/status-holes.js +5 -7
  213. package/dist/checks/tips/catalogue.js +65 -18
  214. package/dist/checks/tips/detect.js +41 -2
  215. package/dist/checks/tips/index.js +61 -25
  216. package/dist/cli.js +52 -26
  217. package/dist/commands/analysis.js +21 -5
  218. package/dist/commands/comply.js +40 -31
  219. package/dist/commands/harvest.js +12 -13
  220. package/dist/commands/install/doctor.js +55 -23
  221. package/dist/commands/install/install.js +72 -122
  222. package/dist/commands/install/uninstall.js +165 -31
  223. package/dist/commands/install/upgrade.js +46 -39
  224. package/dist/commands/land.js +129 -0
  225. package/dist/commands/lib.js +41 -16
  226. package/dist/commands/registry.js +2 -0
  227. package/dist/commands/tips.js +10 -3
  228. package/dist/commands/workflow/branches.js +303 -248
  229. package/dist/commands/workflow/counters.js +17 -7
  230. package/dist/commands/workflow/disk.js +452 -0
  231. package/dist/commands/workflow/fids.js +39 -0
  232. package/dist/commands/workflow/issues.js +63 -27
  233. package/dist/commands/workflow/ledgers.js +3 -1
  234. package/dist/commands/workflow/locks.js +35 -130
  235. package/dist/commands/workflow/prs.js +8 -5
  236. package/dist/commands/workflow/repo.js +2 -2
  237. package/dist/commands/workflow/roadmap.js +50 -57
  238. package/dist/commands/workflow/runs.js +5 -5
  239. package/dist/commands/workflow/runtime.js +3 -2
  240. package/dist/commands/workflow/status.js +32 -12
  241. package/dist/commands/workflow/steps.js +19 -11
  242. package/dist/commands/workflow/tests.js +16 -3
  243. package/dist/commands/workflow/workflows.js +390 -249
  244. package/dist/commands/workflow/workstreams.js +4 -2
  245. package/dist/commands/workflow/worktrees.js +15 -6
  246. package/dist/install/cloud-env.js +10 -23
  247. package/dist/install/manifest.js +14 -7
  248. package/dist/install/modules/antigravity.js +15 -26
  249. package/dist/install/modules/claude.js +17 -21
  250. package/dist/install/modules/cloud.js +6 -2
  251. package/dist/install/modules/codex.js +15 -29
  252. package/dist/install/modules/core.js +95 -63
  253. package/dist/install/modules/cursor.js +6 -9
  254. package/dist/install/modules/index.js +6 -1
  255. package/dist/install/modules/opencode.js +41 -72
  256. package/dist/install/network-allowlist.js +62 -0
  257. package/dist/install/placeholders.js +16 -35
  258. package/dist/install/write.js +55 -15
  259. package/dist/ledgers/telemetry.js +5 -4
  260. package/dist/render/hosts.js +30 -55
  261. package/dist/render/models.js +20 -9
  262. package/dist/shared/branches.js +11 -0
  263. package/dist/shared/egress.js +0 -2
  264. package/dist/shared/json.js +14 -0
  265. package/dist/shared/package-json.js +61 -0
  266. package/dist/shared/package-roots.js +0 -8
  267. package/dist/shared/protected-paths.js +5 -122
  268. package/dist/shared/settings.js +23 -1
  269. package/dist/shared/timeouts.js +8 -7
  270. package/package.json +21 -17
  271. package/.bkit/core/.agents/shortcuts.md +0 -73
@@ -57,23 +57,32 @@ const nonNegativeInt = (v: FlagValue, flag: string): number => {
57
57
  return Number(s);
58
58
  };
59
59
 
60
- /** `--of=<step>:<position>` over `--file` / `--workflow`: the counter at that position. */
60
+ /**
61
+ * `--of=<step>:<position>` over `--file` / `--workflow`: the counter at that position.
62
+ * `--of=<step>,<step>...:count` sums the DONE rows of every listed step.
63
+ */
61
64
  function derivedOf(ctx: RunContext): number {
62
- const [step, position] = String(ctx.flags.of).split(":");
63
- if (!step || !["next", "current", "count"].includes(position ?? ""))
64
- throw new CommandError(EXIT.USAGE, "--of must be <step>:<next|current|count>");
65
+ const [list, position] = String(ctx.flags.of).split(":");
66
+ const steps = (list ?? "").split(",");
67
+ if (steps.some((s) => s === "") || !["next", "current", "count"].includes(position ?? ""))
68
+ throw new CommandError(EXIT.USAGE, "--of must be <step>[,<step>...]:<next|current|count>");
69
+ if (steps.length > 1 && (position !== "count" || new Set(steps).size !== steps.length))
70
+ throw new CommandError(EXIT.USAGE, "--of with several steps takes distinct steps and :count");
65
71
  if (ctx.flags.file === undefined || ctx.flags.workflow === undefined)
66
72
  throw new CommandError(EXIT.USAGE, "--of needs --file and --workflow");
67
- const count = activeDoneSteps(
68
- readRuns(statusFile(ctx)),
69
- String(ctx.flags.workflow),
70
- { step, subPlan: positiveInt(ctx.flags.subPlan, "sub-plan") },
71
- str(ctx.flags.since),
72
- ).length;
73
+ const runs = readRuns(statusFile(ctx));
74
+ const subPlan = positiveInt(ctx.flags.subPlan, "sub-plan");
75
+ const count = steps.reduce(
76
+ (n, step) =>
77
+ n +
78
+ activeDoneSteps(runs, String(ctx.flags.workflow), { step, subPlan }, str(ctx.flags.since))
79
+ .length,
80
+ 0,
81
+ );
73
82
  if (position === "current" && count === 0)
74
83
  throw new CommandError(
75
84
  EXIT_NO_OWN_ROW,
76
- `${step}: no DONE row in the active run — the step's own row is missing`,
85
+ `${steps[0]}: no DONE row in the active run — the step's own row is missing`,
77
86
  );
78
87
  return position === "next" ? count + 1 : count;
79
88
  }
@@ -160,7 +169,7 @@ export const countersCommand: CommandSpec = {
160
169
  {
161
170
  name: "of",
162
171
  type: "string",
163
- help: "<step>:<next|current|count> — derive the value from --file (active run)",
172
+ help: "<step>:<next|current|count> — derive the value from --file (active run); <step>,<step>...:count sums the listed steps",
164
173
  },
165
174
  { ...FILE_FLAG, required: false, help: "status.jsonl, with --of" },
166
175
  { ...WORKFLOW_FLAG, required: false, help: "workflow, with --of" },
@@ -0,0 +1,556 @@
1
+ // bkit disk prune — runs the person's own cleanup steps. bkit itself deletes nothing.
2
+ //
3
+ // Steps live in two optional files the person owns, copied from
4
+ // `.bkit/templates/scripts/cleanup/`: the checkout's `scripts/cleanup/bkit-disk-prune.mjs`
5
+ // (steps for this checkout, run from its top) and `disk-prune.mjs` in the bkit config folder
6
+ // (`~/.config/bkit/`; steps for tools every repo on the machine shares, run from the home
7
+ // folder). Each exports a list of steps; `max` also runs every `min` step. No file → nothing
8
+ // runs, and worktree setup checks nothing.
9
+ //
10
+ // `--auto` is the hooks' entry: a mode runs at most once a day per machine, and `max` at
11
+ // most once an hour while free disk is under `bkit.disk.minFreeGb`; the sweep then runs
12
+ // detached and logs to the bkit cache folder, so the hook does not wait. `bkit worktrees
13
+ // setup` calls `ensureDiskSpace` before it mints. A lock in the cache folder keeps one sweep
14
+ // at a time across every repo. CI and cloud sessions run nothing.
15
+ //
16
+ // A step calls `note()` for what it found but would not delete on its own (a worktree with
17
+ // uncommitted files, say). Each sweep replaces its checkout's notes in the cache folder;
18
+ // `bkit tips` lists them first, so the workflow that prints its tips surfaces them.
19
+
20
+ import { spawn, spawnSync } from "node:child_process";
21
+ import * as fs from "node:fs";
22
+ import * as os from "node:os";
23
+ import * as path from "node:path";
24
+ import { pathToFileURL } from "node:url";
25
+
26
+ import { isCloudOrCi } from "../../checks/before/env.js";
27
+ import { readJsonFile } from "../../shared/json.js";
28
+ import { readBkitConfig } from "../../shared/settings.js";
29
+ import { CommandError, EXIT, git, type CommandSpec } from "../lib.js";
30
+ import { tryCreate } from "./locks.js";
31
+
32
+ export type Mode = "min" | "max";
33
+ const MODES: readonly string[] = ["min", "max"];
34
+
35
+ export const REPO_STEPS = "scripts/cleanup/bkit-disk-prune.mjs";
36
+ const TEMPLATES = ".bkit/templates/scripts/cleanup/";
37
+ const SETTING = "bkit.disk.minFreeGb";
38
+
39
+ const HOUR_MS = 60 * 60 * 1000;
40
+ const DAY_MS = 24 * HOUR_MS;
41
+ /** A lock this old, or whose process is gone, belongs to a sweep that died. */
42
+ const LOCK_STALE_MS = HOUR_MS;
43
+ const GB = 1e9;
44
+
45
+ const configDir = () =>
46
+ path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "bkit");
47
+ const cacheDir = () =>
48
+ path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache"), "bkit");
49
+ export const machineStepsPath = () => path.join(configDir(), "disk-prune.mjs");
50
+ export const sweepLogPath = () => path.join(cacheDir(), "disk-prune.log");
51
+ const lockPath = () => path.join(cacheDir(), "disk-prune.lock");
52
+ const stampPath = (name: string) => path.join(cacheDir(), `disk-prune-${name}.stamp`);
53
+ const notesPath = () => path.join(cacheDir(), "disk-prune-notes.json");
54
+ /** Notes older than this are dropped: no sweep has run there since. */
55
+ const NOTES_STALE_MS = 7 * DAY_MS;
56
+
57
+ const gb = (bytes: number | null) => (bytes === null ? "?" : `${(bytes / GB).toFixed(1)} GB`);
58
+ const errorText = (err: unknown) => (err instanceof Error ? err.message : String(err));
59
+
60
+ // ---------------------------------------------------------------------------
61
+ // Step files
62
+ // ---------------------------------------------------------------------------
63
+
64
+ export interface StepContext {
65
+ /** Where the step runs: the checkout top (repo file) or the home folder (machine file). */
66
+ cwd: string;
67
+ log(message: string): void;
68
+ /** Something the step left for the person to decide; `bkit tips` lists it. */
69
+ note(message: string): void;
70
+ }
71
+
72
+ /** A shell command run with `sh -c`, or a function; a skip check returns a reason to skip. */
73
+ type Action = string | ((ctx: StepContext) => unknown);
74
+
75
+ export interface Step {
76
+ name: string;
77
+ mode: Mode;
78
+ run: Action;
79
+ skip?: Action;
80
+ /** Paths the step frees, for `--dry-run` sizes: relative to `cwd`, `~/…`, or globs. */
81
+ paths?: string[];
82
+ }
83
+
84
+ type Scope = "repo" | "machine";
85
+
86
+ interface StepFile {
87
+ scope: Scope;
88
+ file: string;
89
+ cwd: string;
90
+ steps: Step[];
91
+ /** Why the file, or some of its steps, could not be used; null when all loaded. */
92
+ error: string | null;
93
+ }
94
+
95
+ const checkoutTop = (cwd: string) => git(cwd, ["rev-parse", "--show-toplevel"]) ?? cwd;
96
+
97
+ /** The step files that exist for `cwd`, repo first. */
98
+ function stepFilePaths(cwd: string): { scope: Scope; file: string; cwd: string }[] {
99
+ const top = checkoutTop(cwd);
100
+ return [
101
+ { scope: "repo" as const, file: path.join(top, REPO_STEPS), cwd: top },
102
+ { scope: "machine" as const, file: machineStepsPath(), cwd: os.homedir() },
103
+ ].filter((f) => fs.existsSync(f.file));
104
+ }
105
+
106
+ const isAction = (v: unknown) => typeof v === "string" || typeof v === "function";
107
+
108
+ function stepProblem(step: unknown): string | null {
109
+ if (step === null || typeof step !== "object") return "not an object";
110
+ const s = step as Record<string, unknown>;
111
+ if (typeof s.name !== "string" || s.name.trim() === "") return "name must be a non-empty string";
112
+ if (!MODES.includes(s.mode as string)) return `${s.name}: mode must be "min" or "max"`;
113
+ if (!isAction(s.run)) return `${s.name}: run must be a shell command or a function`;
114
+ if (s.skip !== undefined && !isAction(s.skip))
115
+ return `${s.name}: skip must be a shell command or a function`;
116
+ if (
117
+ s.paths !== undefined &&
118
+ !(Array.isArray(s.paths) && s.paths.every((p) => typeof p === "string"))
119
+ )
120
+ return `${s.name}: paths must be a list of strings`;
121
+ return null;
122
+ }
123
+
124
+ async function loadStepFile(at: { scope: Scope; file: string; cwd: string }): Promise<StepFile> {
125
+ let list: unknown;
126
+ try {
127
+ list = ((await import(pathToFileURL(at.file).href)) as { default?: unknown }).default;
128
+ } catch (err) {
129
+ return { ...at, steps: [], error: `could not load: ${errorText(err)}` };
130
+ }
131
+ if (!Array.isArray(list)) {
132
+ return { ...at, steps: [], error: "its default export is not a list of steps" };
133
+ }
134
+ const steps: Step[] = [];
135
+ const problems: string[] = [];
136
+ for (const [i, step] of list.entries()) {
137
+ const problem = stepProblem(step);
138
+ if (problem === null) steps.push(step as Step);
139
+ else problems.push(`step ${i + 1}: ${problem}`);
140
+ }
141
+ return { ...at, steps, error: problems.length > 0 ? problems.join("; ") : null };
142
+ }
143
+
144
+ // ---------------------------------------------------------------------------
145
+ // Disk, sizes, stamps, lock
146
+ // ---------------------------------------------------------------------------
147
+
148
+ /** Bytes free to this user on the filesystem holding `dir`; null when `dir` is gone. */
149
+ export function freeBytes(dir: string): number | null {
150
+ if (!fs.existsSync(dir)) return null;
151
+ const s = fs.statfsSync(dir);
152
+ return s.bavail * s.bsize;
153
+ }
154
+
155
+ /** Total size of everything `patterns` match under `cwd`; null when `du` cannot answer. */
156
+ function sizeOf(patterns: string[], cwd: string): number | null {
157
+ const matches = patterns.flatMap((p) => {
158
+ const abs = p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : path.resolve(cwd, p);
159
+ return fs.globSync(abs);
160
+ });
161
+ if (matches.length === 0) return 0;
162
+ const r = spawnSync("du", ["-sk", ...matches], { encoding: "utf-8" });
163
+ if (r.error || r.stdout === "") return null;
164
+ return r.stdout
165
+ .trim()
166
+ .split("\n")
167
+ .reduce((sum, line) => sum + Number(line.split(/\s/)[0] ?? 0) * 1024, 0);
168
+ }
169
+
170
+ function due(name: string, everyMs: number, now: number): boolean {
171
+ const st = fs.statSync(stampPath(name), { throwIfNoEntry: false });
172
+ return st === undefined || now - st.mtimeMs >= everyMs;
173
+ }
174
+
175
+ function touch(...names: string[]): void {
176
+ fs.mkdirSync(cacheDir(), { recursive: true });
177
+ for (const name of names) fs.writeFileSync(stampPath(name), `${new Date().toISOString()}\n`);
178
+ }
179
+
180
+ function pidAlive(pid: number): boolean {
181
+ try {
182
+ process.kill(pid, 0);
183
+ return true;
184
+ } catch (err) {
185
+ return (err as NodeJS.ErrnoException).code === "EPERM";
186
+ }
187
+ }
188
+
189
+ /** Take the sweep lock; a dead or hour-old holder's lock is replaced. False when held. */
190
+ function takeLock(): boolean {
191
+ const file = lockPath();
192
+ const line = `${new Date().toISOString()} ${process.pid}`;
193
+ if (tryCreate(file, line)) return true;
194
+ const st = fs.statSync(file, { throwIfNoEntry: false });
195
+ const holder = st === undefined ? "" : fs.readFileSync(file, "utf-8");
196
+ const pid = Number(holder.split(/\s+/)[1]);
197
+ const live = st !== undefined && Date.now() - st.mtimeMs < LOCK_STALE_MS;
198
+ if (live && Number.isInteger(pid) && pid > 0 && pidAlive(pid)) return false;
199
+ fs.rmSync(file, { force: true });
200
+ return tryCreate(file, line);
201
+ }
202
+
203
+ function releaseLock(): void {
204
+ const file = lockPath();
205
+ const pid = fs.existsSync(file) ? fs.readFileSync(file, "utf-8").split(/\s+/)[1] : undefined;
206
+ if (pid === String(process.pid)) fs.rmSync(file, { force: true });
207
+ }
208
+
209
+ // ---------------------------------------------------------------------------
210
+ // Sweep
211
+ // ---------------------------------------------------------------------------
212
+
213
+ type Outcome = "ran" | "failed" | "skipped" | "would-run";
214
+
215
+ export interface StepResult {
216
+ scope: Scope;
217
+ name: string;
218
+ mode: Mode;
219
+ outcome: Outcome;
220
+ /** Why it failed or was skipped; null otherwise. */
221
+ detail: string | null;
222
+ /** `--dry-run`: size of the step's paths; null when it lists none or `du` failed. */
223
+ bytes: number | null;
224
+ }
225
+
226
+ export interface SweepResult {
227
+ /** Why nothing ran: ci | no-steps | locked; null when the steps ran. */
228
+ reason: "ci" | "no-steps" | "locked" | null;
229
+ files: { scope: Scope; file: string; steps: number; error: string | null }[];
230
+ steps: StepResult[];
231
+ /** What steps left for the person to decide, in step order. */
232
+ notes: string[];
233
+ freeBefore: number | null;
234
+ freeAfter: number | null;
235
+ }
236
+
237
+ function shell(command: string, cwd: string, log: (m: string) => void) {
238
+ const r = spawnSync("sh", ["-c", command], { cwd, encoding: "utf-8", maxBuffer: 1 << 26 });
239
+ const out = `${r.stdout ?? ""}${r.stderr ?? ""}`.trim();
240
+ if (out !== "") for (const line of out.split("\n").slice(-20)) log(` ${line}`);
241
+ return r.error ? 127 : (r.status ?? 1);
242
+ }
243
+
244
+ async function skipReason(step: Step, ctx: StepContext): Promise<string | null> {
245
+ if (step.skip === undefined) return null;
246
+ if (typeof step.skip === "string") {
247
+ return shell(step.skip, ctx.cwd, ctx.log) === 0 ? `skip check passed: ${step.skip}` : null;
248
+ }
249
+ const answer = await step.skip(ctx);
250
+ if (!answer) return null;
251
+ return typeof answer === "string" ? answer : "its skip check said so";
252
+ }
253
+
254
+ async function runStep(
255
+ step: Step,
256
+ ctx: StepContext,
257
+ ): Promise<Pick<StepResult, "outcome" | "detail">> {
258
+ try {
259
+ const reason = await skipReason(step, ctx);
260
+ if (reason !== null) return { outcome: "skipped", detail: reason };
261
+ if (typeof step.run === "string") {
262
+ const status = shell(step.run, ctx.cwd, ctx.log);
263
+ if (status !== 0) return { outcome: "failed", detail: `exit ${status}` };
264
+ } else {
265
+ await step.run(ctx);
266
+ }
267
+ return { outcome: "ran", detail: null };
268
+ } catch (err) {
269
+ return { outcome: "failed", detail: errorText(err) };
270
+ }
271
+ }
272
+
273
+ /**
274
+ * Run the `mode` steps from every step file for `cwd`, one at a time, repo file first.
275
+ * `dryRun` runs nothing and sizes each step's paths instead.
276
+ */
277
+ export async function sweep(opts: {
278
+ cwd: string;
279
+ mode: Mode;
280
+ dryRun: boolean;
281
+ log: (m: string) => void;
282
+ }): Promise<SweepResult> {
283
+ const result: SweepResult = {
284
+ reason: null,
285
+ files: [],
286
+ steps: [],
287
+ notes: [],
288
+ freeBefore: null,
289
+ freeAfter: null,
290
+ };
291
+ if (isCloudOrCi()) return { ...result, reason: "ci" };
292
+ const files = await Promise.all(stepFilePaths(opts.cwd).map(loadStepFile));
293
+ result.files = files.map((f) => ({
294
+ scope: f.scope,
295
+ file: f.file,
296
+ steps: f.steps.length,
297
+ error: f.error,
298
+ }));
299
+ for (const f of files) if (f.error !== null) opts.log(`${f.file}: ${f.error}`);
300
+ if (files.length === 0) {
301
+ opts.log(
302
+ `no cleanup steps: copy ${TEMPLATES}bkit-disk-prune.mjs to ${REPO_STEPS} and/or ${TEMPLATES}bkit-disk-prune.machine.mjs to ${machineStepsPath()}`,
303
+ );
304
+ return { ...result, reason: "no-steps" };
305
+ }
306
+ const chosen = files.flatMap((f) =>
307
+ f.steps.filter((s) => s.mode === "min" || opts.mode === "max").map((step) => ({ f, step })),
308
+ );
309
+ if (opts.dryRun) {
310
+ for (const { f, step } of chosen) {
311
+ const bytes = step.paths ? sizeOf(step.paths, f.cwd) : null;
312
+ result.steps.push({
313
+ scope: f.scope,
314
+ name: step.name,
315
+ mode: step.mode,
316
+ outcome: "would-run",
317
+ detail: null,
318
+ bytes,
319
+ });
320
+ opts.log(`${f.scope}: ${step.name} (${step.mode})${bytes === null ? "" : ` — ${gb(bytes)}`}`);
321
+ }
322
+ return result;
323
+ }
324
+ if (!takeLock()) {
325
+ opts.log(`another sweep is running (${lockPath()})`);
326
+ return { ...result, reason: "locked" };
327
+ }
328
+ try {
329
+ result.freeBefore = freeBytes(opts.cwd);
330
+ opts.log(`${new Date().toISOString()} ${opts.mode} sweep, ${gb(result.freeBefore)} free`);
331
+ const note = (message: string) => {
332
+ result.notes.push(message);
333
+ opts.log(`to review: ${message}`);
334
+ };
335
+ for (const { f, step } of chosen) {
336
+ const r = await runStep(step, { cwd: f.cwd, log: opts.log, note });
337
+ result.steps.push({ scope: f.scope, name: step.name, mode: step.mode, ...r, bytes: null });
338
+ opts.log(
339
+ `${f.scope}: ${step.name} — ${r.outcome}${r.detail === null ? "" : ` (${r.detail})`}`,
340
+ );
341
+ }
342
+ result.freeAfter = freeBytes(opts.cwd);
343
+ opts.log(`${gb(result.freeBefore)} → ${gb(result.freeAfter)} free`);
344
+ saveNotes(checkoutTop(opts.cwd), result.notes);
345
+ } finally {
346
+ releaseLock();
347
+ }
348
+ return result;
349
+ }
350
+
351
+ // ---------------------------------------------------------------------------
352
+ // Notes
353
+ // ---------------------------------------------------------------------------
354
+
355
+ type NotesFile = Record<string, { at: string; notes: string[] }>;
356
+
357
+ /** The notes file; `{}` when missing or not a JSON object (the next sweep rewrites it). */
358
+ function readNotesFile(): NotesFile {
359
+ const r = readJsonFile(notesPath());
360
+ return r.ok && r.value !== null && typeof r.value === "object" && !Array.isArray(r.value)
361
+ ? (r.value as NotesFile)
362
+ : {};
363
+ }
364
+
365
+ /** Replace `top`'s notes with `notes`; none clears its entry. */
366
+ function saveNotes(top: string, notes: string[]): void {
367
+ const all = readNotesFile();
368
+ if (notes.length === 0) delete all[top];
369
+ else all[top] = { at: new Date().toISOString(), notes };
370
+ fs.mkdirSync(cacheDir(), { recursive: true });
371
+ fs.writeFileSync(notesPath(), `${JSON.stringify(all, null, 2)}\n`);
372
+ }
373
+
374
+ /**
375
+ * The last sweep's notes for the checkout holding `cwd` and for the main checkout (where
376
+ * the worktree step runs), so a workflow inside its worktree sees both; stale or absent
377
+ * entries add none.
378
+ */
379
+ export function readNotes(cwd: string, now = Date.now()): string[] {
380
+ const all = readNotesFile();
381
+ const tops = new Set([checkoutTop(cwd)]);
382
+ // The main checkout is the folder holding the shared .git; outside git, none.
383
+ const common = git(cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
384
+ if (common !== null) tops.add(path.dirname(common));
385
+ const notes: string[] = [];
386
+ for (const top of tops) {
387
+ const entry = all[top];
388
+ if (!entry || !Array.isArray(entry.notes)) continue;
389
+ const at = Date.parse(entry.at);
390
+ if (!Number.isFinite(at) || now - at >= NOTES_STALE_MS) continue;
391
+ for (const n of entry.notes) if (typeof n === "string" && !notes.includes(n)) notes.push(n);
392
+ }
393
+ return notes;
394
+ }
395
+
396
+ /** `notes` as the markdown block `bkit tips` prints first; "" when none. */
397
+ export function formatNotes(notes: readonly string[]): string {
398
+ if (notes.length === 0) return "";
399
+ return [
400
+ "**Found by the disk clean-up, left for you to decide** (`bkit disk prune`):",
401
+ ...notes.map((n) => `- ${n}`),
402
+ 'Ask your agent: "Show me each of these and remove the ones I no longer need."',
403
+ ].join("\n");
404
+ }
405
+
406
+ // ---------------------------------------------------------------------------
407
+ // Scheduling (hooks) and the worktree check
408
+ // ---------------------------------------------------------------------------
409
+
410
+ /** Start `bkit disk prune --mode=<mode>` detached, its output appended to the sweep log. */
411
+ function spawnDetached(mode: Mode, cwd: string): void {
412
+ fs.mkdirSync(cacheDir(), { recursive: true });
413
+ const fd = fs.openSync(sweepLogPath(), "a");
414
+ const child = spawn(
415
+ process.execPath,
416
+ [...process.execArgv, process.argv[1]!, "disk", "prune", `--mode=${mode}`],
417
+ { cwd, detached: true, stdio: ["ignore", fd, fd] },
418
+ );
419
+ child.unref();
420
+ fs.closeSync(fd);
421
+ }
422
+
423
+ export interface Schedule {
424
+ /** The mode started in the background; null when nothing started. */
425
+ started: Mode | null;
426
+ /** ci | no-steps | not-due | low-disk | due. */
427
+ reason: "ci" | "no-steps" | "not-due" | "low-disk" | "due";
428
+ }
429
+
430
+ /**
431
+ * `--auto`: start a detached sweep when one is due. Under `minFreeGb` free → `max`, at
432
+ * most hourly; else `mode`, at most daily. A `max` run also counts as that day's `min`.
433
+ */
434
+ export function schedule(opts: {
435
+ cwd: string;
436
+ mode: Mode;
437
+ minFreeGb: number;
438
+ now?: number;
439
+ start?: (mode: Mode, cwd: string) => void;
440
+ }): Schedule {
441
+ if (isCloudOrCi()) return { started: null, reason: "ci" };
442
+ if (stepFilePaths(opts.cwd).length === 0) return { started: null, reason: "no-steps" };
443
+ const now = opts.now ?? Date.now();
444
+ const start = opts.start ?? spawnDetached;
445
+ const free = freeBytes(opts.cwd);
446
+ if (free !== null && free < opts.minFreeGb * GB) {
447
+ if (!due("low", HOUR_MS, now)) return { started: null, reason: "not-due" };
448
+ touch("low", "max", "min");
449
+ start("max", opts.cwd);
450
+ return { started: "max", reason: "low-disk" };
451
+ }
452
+ if (!due(opts.mode, DAY_MS, now)) return { started: null, reason: "not-due" };
453
+ touch(...(opts.mode === "max" ? ["max", "min"] : ["min"]));
454
+ start(opts.mode, opts.cwd);
455
+ return { started: opts.mode, reason: "due" };
456
+ }
457
+
458
+ /**
459
+ * Before worktree setup mints: under `minFreeGb` free with step files present, run the
460
+ * `max` steps and check again. Null = carry on; else why the worktree must not be made.
461
+ */
462
+ export async function ensureDiskSpace(opts: {
463
+ cwd: string;
464
+ minFreeGb: number;
465
+ log: (m: string) => void;
466
+ }): Promise<string | null> {
467
+ if (isCloudOrCi() || stepFilePaths(opts.cwd).length === 0) return null;
468
+ const min = opts.minFreeGb * GB;
469
+ const before = freeBytes(opts.cwd);
470
+ if (before === null || before >= min) return null;
471
+ opts.log(
472
+ `${gb(before)} free, under ${SETTING} (${opts.minFreeGb} GB) — running your max cleanup steps`,
473
+ );
474
+ touch("low", "max", "min");
475
+ const ran = await sweep({ cwd: opts.cwd, mode: "max", dryRun: false, log: opts.log });
476
+ const after = freeBytes(opts.cwd);
477
+ if (after === null || after >= min) return null;
478
+ opts.log("what your max steps still cover:");
479
+ await sweep({ cwd: opts.cwd, mode: "max", dryRun: true, log: opts.log });
480
+ const locked =
481
+ ran.reason === "locked" ? " (another sweep was running — re-run once it ends)" : "";
482
+ return `${gb(after)} free after your max cleanup steps, still under ${SETTING} (${opts.minFreeGb} GB)${locked} — free space by hand or add steps (.bkit/templates.md § Disk prune), then re-run`;
483
+ }
484
+
485
+ // ---------------------------------------------------------------------------
486
+ // Command
487
+ // ---------------------------------------------------------------------------
488
+
489
+ export const diskCommand: CommandSpec = {
490
+ noun: "disk",
491
+ summary: "Free disk with your own cleanup steps; bkit itself deletes nothing.",
492
+ verbs: {
493
+ prune: {
494
+ summary: `Run the min or max steps from ${REPO_STEPS} and ~/.config/bkit/disk-prune.mjs.`,
495
+ flags: [
496
+ {
497
+ name: "mode",
498
+ type: "string",
499
+ required: true,
500
+ help: "min (stale, cheap) or max (min plus everything that comes back by itself)",
501
+ },
502
+ {
503
+ name: "dry-run",
504
+ type: "boolean",
505
+ help: "run nothing; list each step with the size of its paths",
506
+ },
507
+ {
508
+ name: "auto",
509
+ type: "boolean",
510
+ help: `for hooks: run detached, at most once a day per mode; max at most hourly while free disk is under ${SETTING}`,
511
+ },
512
+ ],
513
+ output: {
514
+ mode: "the mode asked for",
515
+ reason:
516
+ "why nothing ran: ci | no-steps | locked, --auto also not-due; low-disk | due when --auto started a sweep; null when the steps ran",
517
+ started: "--auto: the mode started in the background (max when disk is low); else null",
518
+ files: "step files found: [{scope: repo|machine, file, steps, error}]",
519
+ steps: "[{scope, name, mode, outcome: ran|failed|skipped|would-run, detail, bytes}]",
520
+ notes: "what steps left for you to decide (`bkit tips` lists them until the next sweep)",
521
+ freeBefore: "bytes free before the steps ran; null when they did not",
522
+ freeAfter: "bytes free after the steps ran; null when they did not",
523
+ },
524
+ run: async (ctx) => {
525
+ const mode = String(ctx.flags.mode);
526
+ if (!MODES.includes(mode)) throw new CommandError(EXIT.USAGE, "--mode must be min or max");
527
+ const dryRun = ctx.flags.dryRun === true;
528
+ if (ctx.flags.auto === true) {
529
+ if (dryRun) throw new CommandError(EXIT.USAGE, "give --auto or --dry-run, not both");
530
+ const plan = schedule({
531
+ cwd: ctx.cwd,
532
+ mode: mode as Mode,
533
+ minFreeGb: readBkitConfig(checkoutTop(ctx.cwd)).diskMinFreeGb,
534
+ });
535
+ if (plan.started !== null)
536
+ ctx.log(`${plan.started} cleanup started in the background — log: ${sweepLogPath()}`);
537
+ ctx.emit({
538
+ mode,
539
+ ...plan,
540
+ files: [],
541
+ steps: [],
542
+ notes: [],
543
+ freeBefore: null,
544
+ freeAfter: null,
545
+ });
546
+ return EXIT.OK;
547
+ }
548
+ const r = await sweep({ cwd: ctx.cwd, mode: mode as Mode, dryRun, log: ctx.log });
549
+ ctx.emit({ mode, started: null, ...r });
550
+ const failed =
551
+ r.files.some((f) => f.error !== null) || r.steps.some((s) => s.outcome === "failed");
552
+ return failed ? EXIT.NO : EXIT.OK;
553
+ },
554
+ },
555
+ },
556
+ };
@@ -53,6 +53,27 @@ export function logged(root: string, issue: string): string[] {
53
53
  return [...found].sort();
54
54
  }
55
55
 
56
+ /**
57
+ * The canonical design doc for a feature, `docs/plans/{YYYYMM}/{fid}-design.md`: the
58
+ * `month` bucket first, else the newest bucket holding one. null when none exists.
59
+ */
60
+ export function designDoc(
61
+ root: string,
62
+ fid: string,
63
+ month?: string,
64
+ ): { month: string; path: string } | null {
65
+ const plans = path.join(root, "docs", "plans");
66
+ if (!fs.existsSync(plans)) return null;
67
+ const at = (m: string) => fs.existsSync(path.join(plans, m, `${fid}-design.md`));
68
+ const months = fs
69
+ .readdirSync(plans)
70
+ .filter((m) => /^[0-9]{6}$/.test(m))
71
+ .sort()
72
+ .reverse();
73
+ const hit = month !== undefined && months.includes(month) && at(month) ? month : months.find(at);
74
+ return hit === undefined ? null : { month: hit, path: `docs/plans/${hit}/${fid}-design.md` };
75
+ }
76
+
56
77
  /** `package.json` `bkit.issueTracker` at the main checkout (cwd outside git); default `none`. */
57
78
  export function readIssueTracker(cwd: string): IssueTracker {
58
79
  const common = git(cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
@@ -214,6 +235,31 @@ export const fidsCommand: CommandSpec = {
214
235
  return EXIT.OK;
215
236
  },
216
237
  },
238
+ design: {
239
+ summary:
240
+ "The feature's own design doc, docs/plans/{YYYYMM}/{FID}-design.md: exit 0 found, exit 1 none.",
241
+ flags: [
242
+ { name: "fid", type: "string", required: true, help: "feature id" },
243
+ {
244
+ name: "month",
245
+ type: "string",
246
+ help: "YYYYMM bucket checked first; else the newest bucket holding the doc",
247
+ },
248
+ ],
249
+ output: {
250
+ fid: "the FID when its design doc exists, else null",
251
+ month: "the bucket holding it, else null",
252
+ path: "repo-relative path, else null",
253
+ },
254
+ run: (ctx) => {
255
+ const fid = String(ctx.flags.fid);
256
+ const hit = designDoc(repoRoot(ctx.cwd), fid, str(ctx.flags.month));
257
+ ctx.emit(
258
+ hit ? { fid, month: hit.month, path: hit.path } : { fid: null, month: null, path: null },
259
+ );
260
+ return hit ? EXIT.OK : EXIT.NO;
261
+ },
262
+ },
217
263
  find: {
218
264
  summary: "The feature already logged for an issue: exit 0 one, exit 1 none, exit 4 several.",
219
265
  flags: [