@cbartens/bkit 5.3.0 → 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 (128) hide show
  1. package/.bkit/README.md +3 -2
  2. package/.bkit/core/.agents/docs.md +1 -1
  3. package/.bkit/core/.agents/rules.md +8 -2
  4. package/.bkit/core/.bkit/README.md +2 -1
  5. package/.bkit/core/.bkit/cloud.md +33 -33
  6. package/.bkit/core/.bkit/comparison.md +1 -1
  7. package/.bkit/core/.bkit/install.md +6 -5
  8. package/.bkit/core/.bkit/lite.md +6 -6
  9. package/.bkit/core/.bkit/pipeline.md +4 -3
  10. package/.bkit/core/.bkit/prompts.md +4 -3
  11. package/.bkit/core/.bkit/providers.md +1 -1
  12. package/.bkit/core/.bkit/templates.md +35 -5
  13. package/.bkit/core/.bkit/trackers.md +7 -8
  14. package/.bkit/core/.bkit/workflows.md +106 -86
  15. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +3 -2
  16. package/.bkit/core/docs/templates/bkit-audit-adoption.md +1 -1
  17. package/.bkit/core/docs/templates/bkit-audit-agents.md +1 -1
  18. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +1 -1
  19. package/.bkit/core/docs/templates/bkit-audit-analytics.md +1 -1
  20. package/.bkit/core/docs/templates/bkit-audit-annotations.md +1 -1
  21. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +1 -1
  22. package/.bkit/core/docs/templates/bkit-audit-app-store.md +1 -1
  23. package/.bkit/core/docs/templates/bkit-audit-architecture.md +1 -1
  24. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +4 -2
  25. package/.bkit/core/docs/templates/bkit-audit-config.md +3 -2
  26. package/.bkit/core/docs/templates/bkit-audit-cost.md +3 -2
  27. package/.bkit/core/docs/templates/bkit-audit-coverage.md +1 -1
  28. package/.bkit/core/docs/templates/bkit-audit-database.md +3 -2
  29. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +5 -5
  30. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +1 -1
  31. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +14 -13
  32. package/.bkit/core/docs/templates/bkit-audit-documentation.md +1 -1
  33. package/.bkit/core/docs/templates/bkit-audit-duplication.md +2 -2
  34. package/.bkit/core/docs/templates/bkit-audit-failures.md +1 -1
  35. package/.bkit/core/docs/templates/bkit-audit-flakes.md +3 -2
  36. package/.bkit/core/docs/templates/bkit-audit-gates.md +5 -2
  37. package/.bkit/core/docs/templates/bkit-audit-issues.md +3 -2
  38. package/.bkit/core/docs/templates/bkit-audit-llm.md +3 -2
  39. package/.bkit/core/docs/templates/bkit-audit-logs.md +10 -6
  40. package/.bkit/core/docs/templates/bkit-audit-models.md +1 -1
  41. package/.bkit/core/docs/templates/bkit-audit-privacy.md +1 -1
  42. package/.bkit/core/docs/templates/bkit-audit-prompts.md +5 -5
  43. package/.bkit/core/docs/templates/bkit-audit-red-team.md +3 -2
  44. package/.bkit/core/docs/templates/bkit-audit-reliability.md +3 -2
  45. package/.bkit/core/docs/templates/bkit-audit-repo.md +1 -1
  46. package/.bkit/core/docs/templates/bkit-audit-security.md +11 -9
  47. package/.bkit/core/docs/templates/bkit-audit-slop.md +1 -1
  48. package/.bkit/core/docs/templates/bkit-audit-testing.md +6 -5
  49. package/.bkit/core/docs/templates/bkit-audit-usability.md +1 -1
  50. package/.bkit/core/engine/checks/status-holes.ts +0 -1
  51. package/.bkit/core/engine/checks/tips/catalogue.ts +16 -0
  52. package/.bkit/core/engine/checks/tips/index.ts +49 -27
  53. package/.bkit/core/engine/cli.ts +22 -15
  54. package/.bkit/core/engine/commands/comply.ts +25 -16
  55. package/.bkit/core/engine/commands/install/install.ts +11 -4
  56. package/.bkit/core/engine/commands/land.ts +156 -0
  57. package/.bkit/core/engine/commands/lib.ts +10 -8
  58. package/.bkit/core/engine/commands/registry.ts +2 -0
  59. package/.bkit/core/engine/commands/tips.ts +7 -3
  60. package/.bkit/core/engine/commands/workflow/branches.ts +382 -282
  61. package/.bkit/core/engine/commands/workflow/disk.ts +556 -0
  62. package/.bkit/core/engine/commands/workflow/issues.ts +73 -28
  63. package/.bkit/core/engine/commands/workflow/locks.ts +38 -152
  64. package/.bkit/core/engine/commands/workflow/prs.ts +11 -2
  65. package/.bkit/core/engine/commands/workflow/roadmap.ts +48 -53
  66. package/.bkit/core/engine/commands/workflow/runtime.ts +3 -2
  67. package/.bkit/core/engine/commands/workflow/status.ts +33 -11
  68. package/.bkit/core/engine/commands/workflow/steps.ts +24 -15
  69. package/.bkit/core/engine/commands/workflow/workflows.ts +433 -265
  70. package/.bkit/core/engine/commands/workflow/workstreams.ts +3 -2
  71. package/.bkit/core/engine/commands/workflow/worktrees.ts +11 -1
  72. package/.bkit/core/engine/install/modules/core.ts +15 -0
  73. package/.bkit/core/engine/install/placeholders.ts +13 -17
  74. package/.bkit/core/engine/shared/settings.ts +8 -0
  75. package/.bkit/core/engine/shared/timeouts.ts +8 -7
  76. package/.bkit/core/prompts/bkit-audit-generate.md +47 -4
  77. package/.bkit/core/prompts/bkit-utility-update-decisions.md +1 -1
  78. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +1 -1
  79. package/.bkit/core/prompts/bkit-utility-update-documentation.md +1 -1
  80. package/.bkit/core/prompts/bkit-utility-update-failures.md +1 -1
  81. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +1 -1
  82. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +3 -3
  83. package/.bkit/core/workflows/bkit-auto.md +2 -2
  84. package/.bkit/core/workflows/bkit-build.md +7 -7
  85. package/.bkit/core/workflows/bkit-debug.md +11 -11
  86. package/.bkit/core/workflows/bkit-design.md +20 -11
  87. package/.bkit/core/workflows/bkit-plan.md +23 -13
  88. package/.bkit/core/workflows/bkit-ship.md +82 -93
  89. package/.bkit/shared/.claude/bkit-cloud.md +12 -12
  90. package/.bkit/shared/.claude/settings.json +1 -0
  91. package/.bkit/shared/docs/deployments.md +29 -25
  92. package/.bkit/shared/gitignore +1 -2
  93. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-change.yml +2 -2
  94. package/.bkit/templates/.github/workflows/bkit-ci.yml +7 -2
  95. package/.bkit/templates/.husky/pre-commit +6 -0
  96. package/.bkit/templates/.husky/pre-push +7 -0
  97. package/.bkit/templates/.lintstagedrc.json +5 -1
  98. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.machine.mjs +197 -0
  99. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.mjs +164 -0
  100. package/CHANGELOG.md +48 -0
  101. package/README.md +97 -96
  102. package/dist/checks/status-holes.js +0 -1
  103. package/dist/checks/tips/catalogue.js +14 -0
  104. package/dist/checks/tips/index.js +44 -28
  105. package/dist/cli.js +22 -16
  106. package/dist/commands/comply.js +20 -13
  107. package/dist/commands/install/install.js +10 -4
  108. package/dist/commands/land.js +129 -0
  109. package/dist/commands/lib.js +9 -6
  110. package/dist/commands/registry.js +2 -0
  111. package/dist/commands/tips.js +7 -3
  112. package/dist/commands/workflow/branches.js +300 -243
  113. package/dist/commands/workflow/disk.js +452 -0
  114. package/dist/commands/workflow/issues.js +63 -27
  115. package/dist/commands/workflow/locks.js +35 -130
  116. package/dist/commands/workflow/prs.js +5 -2
  117. package/dist/commands/workflow/roadmap.js +49 -56
  118. package/dist/commands/workflow/runtime.js +3 -2
  119. package/dist/commands/workflow/status.js +32 -12
  120. package/dist/commands/workflow/steps.js +18 -11
  121. package/dist/commands/workflow/workflows.js +388 -247
  122. package/dist/commands/workflow/workstreams.js +3 -2
  123. package/dist/commands/workflow/worktrees.js +11 -1
  124. package/dist/install/modules/core.js +13 -0
  125. package/dist/install/placeholders.js +13 -19
  126. package/dist/shared/settings.js +5 -0
  127. package/dist/shared/timeouts.js +8 -7
  128. package/package.json +1 -1
@@ -0,0 +1,452 @@
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
+ import { spawn, spawnSync } from "node:child_process";
20
+ import * as fs from "node:fs";
21
+ import * as os from "node:os";
22
+ import * as path from "node:path";
23
+ import { pathToFileURL } from "node:url";
24
+ import { isCloudOrCi } from "../../checks/before/env.js";
25
+ import { readJsonFile } from "../../shared/json.js";
26
+ import { readBkitConfig } from "../../shared/settings.js";
27
+ import { CommandError, EXIT, git } from "../lib.js";
28
+ import { tryCreate } from "./locks.js";
29
+ const MODES = ["min", "max"];
30
+ export const REPO_STEPS = "scripts/cleanup/bkit-disk-prune.mjs";
31
+ const TEMPLATES = ".bkit/templates/scripts/cleanup/";
32
+ const SETTING = "bkit.disk.minFreeGb";
33
+ const HOUR_MS = 60 * 60 * 1000;
34
+ const DAY_MS = 24 * HOUR_MS;
35
+ /** A lock this old, or whose process is gone, belongs to a sweep that died. */
36
+ const LOCK_STALE_MS = HOUR_MS;
37
+ const GB = 1e9;
38
+ const configDir = () => path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "bkit");
39
+ const cacheDir = () => path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache"), "bkit");
40
+ export const machineStepsPath = () => path.join(configDir(), "disk-prune.mjs");
41
+ export const sweepLogPath = () => path.join(cacheDir(), "disk-prune.log");
42
+ const lockPath = () => path.join(cacheDir(), "disk-prune.lock");
43
+ const stampPath = (name) => path.join(cacheDir(), `disk-prune-${name}.stamp`);
44
+ const notesPath = () => path.join(cacheDir(), "disk-prune-notes.json");
45
+ /** Notes older than this are dropped: no sweep has run there since. */
46
+ const NOTES_STALE_MS = 7 * DAY_MS;
47
+ const gb = (bytes) => (bytes === null ? "?" : `${(bytes / GB).toFixed(1)} GB`);
48
+ const errorText = (err) => (err instanceof Error ? err.message : String(err));
49
+ const checkoutTop = (cwd) => git(cwd, ["rev-parse", "--show-toplevel"]) ?? cwd;
50
+ /** The step files that exist for `cwd`, repo first. */
51
+ function stepFilePaths(cwd) {
52
+ const top = checkoutTop(cwd);
53
+ return [
54
+ { scope: "repo", file: path.join(top, REPO_STEPS), cwd: top },
55
+ { scope: "machine", file: machineStepsPath(), cwd: os.homedir() },
56
+ ].filter((f) => fs.existsSync(f.file));
57
+ }
58
+ const isAction = (v) => typeof v === "string" || typeof v === "function";
59
+ function stepProblem(step) {
60
+ if (step === null || typeof step !== "object")
61
+ return "not an object";
62
+ const s = step;
63
+ if (typeof s.name !== "string" || s.name.trim() === "")
64
+ return "name must be a non-empty string";
65
+ if (!MODES.includes(s.mode))
66
+ return `${s.name}: mode must be "min" or "max"`;
67
+ if (!isAction(s.run))
68
+ return `${s.name}: run must be a shell command or a function`;
69
+ if (s.skip !== undefined && !isAction(s.skip))
70
+ return `${s.name}: skip must be a shell command or a function`;
71
+ if (s.paths !== undefined &&
72
+ !(Array.isArray(s.paths) && s.paths.every((p) => typeof p === "string")))
73
+ return `${s.name}: paths must be a list of strings`;
74
+ return null;
75
+ }
76
+ async function loadStepFile(at) {
77
+ let list;
78
+ try {
79
+ list = (await import(pathToFileURL(at.file).href)).default;
80
+ }
81
+ catch (err) {
82
+ return { ...at, steps: [], error: `could not load: ${errorText(err)}` };
83
+ }
84
+ if (!Array.isArray(list)) {
85
+ return { ...at, steps: [], error: "its default export is not a list of steps" };
86
+ }
87
+ const steps = [];
88
+ const problems = [];
89
+ for (const [i, step] of list.entries()) {
90
+ const problem = stepProblem(step);
91
+ if (problem === null)
92
+ steps.push(step);
93
+ else
94
+ problems.push(`step ${i + 1}: ${problem}`);
95
+ }
96
+ return { ...at, steps, error: problems.length > 0 ? problems.join("; ") : null };
97
+ }
98
+ // ---------------------------------------------------------------------------
99
+ // Disk, sizes, stamps, lock
100
+ // ---------------------------------------------------------------------------
101
+ /** Bytes free to this user on the filesystem holding `dir`; null when `dir` is gone. */
102
+ export function freeBytes(dir) {
103
+ if (!fs.existsSync(dir))
104
+ return null;
105
+ const s = fs.statfsSync(dir);
106
+ return s.bavail * s.bsize;
107
+ }
108
+ /** Total size of everything `patterns` match under `cwd`; null when `du` cannot answer. */
109
+ function sizeOf(patterns, cwd) {
110
+ const matches = patterns.flatMap((p) => {
111
+ const abs = p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : path.resolve(cwd, p);
112
+ return fs.globSync(abs);
113
+ });
114
+ if (matches.length === 0)
115
+ return 0;
116
+ const r = spawnSync("du", ["-sk", ...matches], { encoding: "utf-8" });
117
+ if (r.error || r.stdout === "")
118
+ return null;
119
+ return r.stdout
120
+ .trim()
121
+ .split("\n")
122
+ .reduce((sum, line) => sum + Number(line.split(/\s/)[0] ?? 0) * 1024, 0);
123
+ }
124
+ function due(name, everyMs, now) {
125
+ const st = fs.statSync(stampPath(name), { throwIfNoEntry: false });
126
+ return st === undefined || now - st.mtimeMs >= everyMs;
127
+ }
128
+ function touch(...names) {
129
+ fs.mkdirSync(cacheDir(), { recursive: true });
130
+ for (const name of names)
131
+ fs.writeFileSync(stampPath(name), `${new Date().toISOString()}\n`);
132
+ }
133
+ function pidAlive(pid) {
134
+ try {
135
+ process.kill(pid, 0);
136
+ return true;
137
+ }
138
+ catch (err) {
139
+ return err.code === "EPERM";
140
+ }
141
+ }
142
+ /** Take the sweep lock; a dead or hour-old holder's lock is replaced. False when held. */
143
+ function takeLock() {
144
+ const file = lockPath();
145
+ const line = `${new Date().toISOString()} ${process.pid}`;
146
+ if (tryCreate(file, line))
147
+ return true;
148
+ const st = fs.statSync(file, { throwIfNoEntry: false });
149
+ const holder = st === undefined ? "" : fs.readFileSync(file, "utf-8");
150
+ const pid = Number(holder.split(/\s+/)[1]);
151
+ const live = st !== undefined && Date.now() - st.mtimeMs < LOCK_STALE_MS;
152
+ if (live && Number.isInteger(pid) && pid > 0 && pidAlive(pid))
153
+ return false;
154
+ fs.rmSync(file, { force: true });
155
+ return tryCreate(file, line);
156
+ }
157
+ function releaseLock() {
158
+ const file = lockPath();
159
+ const pid = fs.existsSync(file) ? fs.readFileSync(file, "utf-8").split(/\s+/)[1] : undefined;
160
+ if (pid === String(process.pid))
161
+ fs.rmSync(file, { force: true });
162
+ }
163
+ function shell(command, cwd, log) {
164
+ const r = spawnSync("sh", ["-c", command], { cwd, encoding: "utf-8", maxBuffer: 1 << 26 });
165
+ const out = `${r.stdout ?? ""}${r.stderr ?? ""}`.trim();
166
+ if (out !== "")
167
+ for (const line of out.split("\n").slice(-20))
168
+ log(` ${line}`);
169
+ return r.error ? 127 : (r.status ?? 1);
170
+ }
171
+ async function skipReason(step, ctx) {
172
+ if (step.skip === undefined)
173
+ return null;
174
+ if (typeof step.skip === "string") {
175
+ return shell(step.skip, ctx.cwd, ctx.log) === 0 ? `skip check passed: ${step.skip}` : null;
176
+ }
177
+ const answer = await step.skip(ctx);
178
+ if (!answer)
179
+ return null;
180
+ return typeof answer === "string" ? answer : "its skip check said so";
181
+ }
182
+ async function runStep(step, ctx) {
183
+ try {
184
+ const reason = await skipReason(step, ctx);
185
+ if (reason !== null)
186
+ return { outcome: "skipped", detail: reason };
187
+ if (typeof step.run === "string") {
188
+ const status = shell(step.run, ctx.cwd, ctx.log);
189
+ if (status !== 0)
190
+ return { outcome: "failed", detail: `exit ${status}` };
191
+ }
192
+ else {
193
+ await step.run(ctx);
194
+ }
195
+ return { outcome: "ran", detail: null };
196
+ }
197
+ catch (err) {
198
+ return { outcome: "failed", detail: errorText(err) };
199
+ }
200
+ }
201
+ /**
202
+ * Run the `mode` steps from every step file for `cwd`, one at a time, repo file first.
203
+ * `dryRun` runs nothing and sizes each step's paths instead.
204
+ */
205
+ export async function sweep(opts) {
206
+ const result = {
207
+ reason: null,
208
+ files: [],
209
+ steps: [],
210
+ notes: [],
211
+ freeBefore: null,
212
+ freeAfter: null,
213
+ };
214
+ if (isCloudOrCi())
215
+ return { ...result, reason: "ci" };
216
+ const files = await Promise.all(stepFilePaths(opts.cwd).map(loadStepFile));
217
+ result.files = files.map((f) => ({
218
+ scope: f.scope,
219
+ file: f.file,
220
+ steps: f.steps.length,
221
+ error: f.error,
222
+ }));
223
+ for (const f of files)
224
+ if (f.error !== null)
225
+ opts.log(`${f.file}: ${f.error}`);
226
+ if (files.length === 0) {
227
+ opts.log(`no cleanup steps: copy ${TEMPLATES}bkit-disk-prune.mjs to ${REPO_STEPS} and/or ${TEMPLATES}bkit-disk-prune.machine.mjs to ${machineStepsPath()}`);
228
+ return { ...result, reason: "no-steps" };
229
+ }
230
+ const chosen = files.flatMap((f) => f.steps.filter((s) => s.mode === "min" || opts.mode === "max").map((step) => ({ f, step })));
231
+ if (opts.dryRun) {
232
+ for (const { f, step } of chosen) {
233
+ const bytes = step.paths ? sizeOf(step.paths, f.cwd) : null;
234
+ result.steps.push({
235
+ scope: f.scope,
236
+ name: step.name,
237
+ mode: step.mode,
238
+ outcome: "would-run",
239
+ detail: null,
240
+ bytes,
241
+ });
242
+ opts.log(`${f.scope}: ${step.name} (${step.mode})${bytes === null ? "" : ` — ${gb(bytes)}`}`);
243
+ }
244
+ return result;
245
+ }
246
+ if (!takeLock()) {
247
+ opts.log(`another sweep is running (${lockPath()})`);
248
+ return { ...result, reason: "locked" };
249
+ }
250
+ try {
251
+ result.freeBefore = freeBytes(opts.cwd);
252
+ opts.log(`${new Date().toISOString()} ${opts.mode} sweep, ${gb(result.freeBefore)} free`);
253
+ const note = (message) => {
254
+ result.notes.push(message);
255
+ opts.log(`to review: ${message}`);
256
+ };
257
+ for (const { f, step } of chosen) {
258
+ const r = await runStep(step, { cwd: f.cwd, log: opts.log, note });
259
+ result.steps.push({ scope: f.scope, name: step.name, mode: step.mode, ...r, bytes: null });
260
+ opts.log(`${f.scope}: ${step.name} — ${r.outcome}${r.detail === null ? "" : ` (${r.detail})`}`);
261
+ }
262
+ result.freeAfter = freeBytes(opts.cwd);
263
+ opts.log(`${gb(result.freeBefore)} → ${gb(result.freeAfter)} free`);
264
+ saveNotes(checkoutTop(opts.cwd), result.notes);
265
+ }
266
+ finally {
267
+ releaseLock();
268
+ }
269
+ return result;
270
+ }
271
+ /** The notes file; `{}` when missing or not a JSON object (the next sweep rewrites it). */
272
+ function readNotesFile() {
273
+ const r = readJsonFile(notesPath());
274
+ return r.ok && r.value !== null && typeof r.value === "object" && !Array.isArray(r.value)
275
+ ? r.value
276
+ : {};
277
+ }
278
+ /** Replace `top`'s notes with `notes`; none clears its entry. */
279
+ function saveNotes(top, notes) {
280
+ const all = readNotesFile();
281
+ if (notes.length === 0)
282
+ delete all[top];
283
+ else
284
+ all[top] = { at: new Date().toISOString(), notes };
285
+ fs.mkdirSync(cacheDir(), { recursive: true });
286
+ fs.writeFileSync(notesPath(), `${JSON.stringify(all, null, 2)}\n`);
287
+ }
288
+ /**
289
+ * The last sweep's notes for the checkout holding `cwd` and for the main checkout (where
290
+ * the worktree step runs), so a workflow inside its worktree sees both; stale or absent
291
+ * entries add none.
292
+ */
293
+ export function readNotes(cwd, now = Date.now()) {
294
+ const all = readNotesFile();
295
+ const tops = new Set([checkoutTop(cwd)]);
296
+ // The main checkout is the folder holding the shared .git; outside git, none.
297
+ const common = git(cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
298
+ if (common !== null)
299
+ tops.add(path.dirname(common));
300
+ const notes = [];
301
+ for (const top of tops) {
302
+ const entry = all[top];
303
+ if (!entry || !Array.isArray(entry.notes))
304
+ continue;
305
+ const at = Date.parse(entry.at);
306
+ if (!Number.isFinite(at) || now - at >= NOTES_STALE_MS)
307
+ continue;
308
+ for (const n of entry.notes)
309
+ if (typeof n === "string" && !notes.includes(n))
310
+ notes.push(n);
311
+ }
312
+ return notes;
313
+ }
314
+ /** `notes` as the markdown block `bkit tips` prints first; "" when none. */
315
+ export function formatNotes(notes) {
316
+ if (notes.length === 0)
317
+ return "";
318
+ return [
319
+ "**Found by the disk clean-up, left for you to decide** (`bkit disk prune`):",
320
+ ...notes.map((n) => `- ${n}`),
321
+ 'Ask your agent: "Show me each of these and remove the ones I no longer need."',
322
+ ].join("\n");
323
+ }
324
+ // ---------------------------------------------------------------------------
325
+ // Scheduling (hooks) and the worktree check
326
+ // ---------------------------------------------------------------------------
327
+ /** Start `bkit disk prune --mode=<mode>` detached, its output appended to the sweep log. */
328
+ function spawnDetached(mode, cwd) {
329
+ fs.mkdirSync(cacheDir(), { recursive: true });
330
+ const fd = fs.openSync(sweepLogPath(), "a");
331
+ const child = spawn(process.execPath, [...process.execArgv, process.argv[1], "disk", "prune", `--mode=${mode}`], { cwd, detached: true, stdio: ["ignore", fd, fd] });
332
+ child.unref();
333
+ fs.closeSync(fd);
334
+ }
335
+ /**
336
+ * `--auto`: start a detached sweep when one is due. Under `minFreeGb` free → `max`, at
337
+ * most hourly; else `mode`, at most daily. A `max` run also counts as that day's `min`.
338
+ */
339
+ export function schedule(opts) {
340
+ if (isCloudOrCi())
341
+ return { started: null, reason: "ci" };
342
+ if (stepFilePaths(opts.cwd).length === 0)
343
+ return { started: null, reason: "no-steps" };
344
+ const now = opts.now ?? Date.now();
345
+ const start = opts.start ?? spawnDetached;
346
+ const free = freeBytes(opts.cwd);
347
+ if (free !== null && free < opts.minFreeGb * GB) {
348
+ if (!due("low", HOUR_MS, now))
349
+ return { started: null, reason: "not-due" };
350
+ touch("low", "max", "min");
351
+ start("max", opts.cwd);
352
+ return { started: "max", reason: "low-disk" };
353
+ }
354
+ if (!due(opts.mode, DAY_MS, now))
355
+ return { started: null, reason: "not-due" };
356
+ touch(...(opts.mode === "max" ? ["max", "min"] : ["min"]));
357
+ start(opts.mode, opts.cwd);
358
+ return { started: opts.mode, reason: "due" };
359
+ }
360
+ /**
361
+ * Before worktree setup mints: under `minFreeGb` free with step files present, run the
362
+ * `max` steps and check again. Null = carry on; else why the worktree must not be made.
363
+ */
364
+ export async function ensureDiskSpace(opts) {
365
+ if (isCloudOrCi() || stepFilePaths(opts.cwd).length === 0)
366
+ return null;
367
+ const min = opts.minFreeGb * GB;
368
+ const before = freeBytes(opts.cwd);
369
+ if (before === null || before >= min)
370
+ return null;
371
+ opts.log(`${gb(before)} free, under ${SETTING} (${opts.minFreeGb} GB) — running your max cleanup steps`);
372
+ touch("low", "max", "min");
373
+ const ran = await sweep({ cwd: opts.cwd, mode: "max", dryRun: false, log: opts.log });
374
+ const after = freeBytes(opts.cwd);
375
+ if (after === null || after >= min)
376
+ return null;
377
+ opts.log("what your max steps still cover:");
378
+ await sweep({ cwd: opts.cwd, mode: "max", dryRun: true, log: opts.log });
379
+ const locked = ran.reason === "locked" ? " (another sweep was running — re-run once it ends)" : "";
380
+ 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`;
381
+ }
382
+ // ---------------------------------------------------------------------------
383
+ // Command
384
+ // ---------------------------------------------------------------------------
385
+ export const diskCommand = {
386
+ noun: "disk",
387
+ summary: "Free disk with your own cleanup steps; bkit itself deletes nothing.",
388
+ verbs: {
389
+ prune: {
390
+ summary: `Run the min or max steps from ${REPO_STEPS} and ~/.config/bkit/disk-prune.mjs.`,
391
+ flags: [
392
+ {
393
+ name: "mode",
394
+ type: "string",
395
+ required: true,
396
+ help: "min (stale, cheap) or max (min plus everything that comes back by itself)",
397
+ },
398
+ {
399
+ name: "dry-run",
400
+ type: "boolean",
401
+ help: "run nothing; list each step with the size of its paths",
402
+ },
403
+ {
404
+ name: "auto",
405
+ type: "boolean",
406
+ help: `for hooks: run detached, at most once a day per mode; max at most hourly while free disk is under ${SETTING}`,
407
+ },
408
+ ],
409
+ output: {
410
+ mode: "the mode asked for",
411
+ reason: "why nothing ran: ci | no-steps | locked, --auto also not-due; low-disk | due when --auto started a sweep; null when the steps ran",
412
+ started: "--auto: the mode started in the background (max when disk is low); else null",
413
+ files: "step files found: [{scope: repo|machine, file, steps, error}]",
414
+ steps: "[{scope, name, mode, outcome: ran|failed|skipped|would-run, detail, bytes}]",
415
+ notes: "what steps left for you to decide (`bkit tips` lists them until the next sweep)",
416
+ freeBefore: "bytes free before the steps ran; null when they did not",
417
+ freeAfter: "bytes free after the steps ran; null when they did not",
418
+ },
419
+ run: async (ctx) => {
420
+ const mode = String(ctx.flags.mode);
421
+ if (!MODES.includes(mode))
422
+ throw new CommandError(EXIT.USAGE, "--mode must be min or max");
423
+ const dryRun = ctx.flags.dryRun === true;
424
+ if (ctx.flags.auto === true) {
425
+ if (dryRun)
426
+ throw new CommandError(EXIT.USAGE, "give --auto or --dry-run, not both");
427
+ const plan = schedule({
428
+ cwd: ctx.cwd,
429
+ mode: mode,
430
+ minFreeGb: readBkitConfig(checkoutTop(ctx.cwd)).diskMinFreeGb,
431
+ });
432
+ if (plan.started !== null)
433
+ ctx.log(`${plan.started} cleanup started in the background — log: ${sweepLogPath()}`);
434
+ ctx.emit({
435
+ mode,
436
+ ...plan,
437
+ files: [],
438
+ steps: [],
439
+ notes: [],
440
+ freeBefore: null,
441
+ freeAfter: null,
442
+ });
443
+ return EXIT.OK;
444
+ }
445
+ const r = await sweep({ cwd: ctx.cwd, mode: mode, dryRun, log: ctx.log });
446
+ ctx.emit({ mode, started: null, ...r });
447
+ const failed = r.files.some((f) => f.error !== null) || r.steps.some((s) => s.outcome === "failed");
448
+ return failed ? EXIT.NO : EXIT.OK;
449
+ },
450
+ },
451
+ },
452
+ };
@@ -125,7 +125,16 @@ function textVerb(ctx) {
125
125
  // labels
126
126
  // ---------------------------------------------------------------------------
127
127
  /** Mutually exclusive: setting one drops the others. */
128
- export const PHASE_LABELS = ["bkit:design", "bkit:plan", "bkit:build", "bkit:ship", "bkit:merged"];
128
+ export const PHASE_LABELS = [
129
+ "bkit:design",
130
+ "bkit:plan",
131
+ "bkit:build",
132
+ "bkit:debug",
133
+ "bkit:ship",
134
+ "bkit:merged",
135
+ ];
136
+ /** Prefix of the labels naming an issue's next best workflow; setting a phase drops them. */
137
+ export const NEXT_LABEL_PREFIX = "next:";
129
138
  /** The issue label that opts a feature into CI auto-routing. */
130
139
  export const AUTO_LABEL = "bkit:auto";
131
140
  /** Commit-subject suffix the CI auto-route gate matches; carried only while the issue has `AUTO_LABEL`. */
@@ -145,12 +154,15 @@ export function transitionLabels(current, t) {
145
154
  for (const l of have)
146
155
  if (PHASE_LABELS.includes(l) && l !== label)
147
156
  remove.add(l);
157
+ for (const l of have)
158
+ if (l.startsWith(NEXT_LABEL_PREFIX))
159
+ remove.add(l);
148
160
  want(label, true);
149
161
  }
150
- if (t.failed !== undefined)
151
- want("bkit:failed", t.failed);
152
- if (t.debug !== undefined)
153
- want("bkit:debug", t.debug);
162
+ // A phase starting supersedes any earlier Failure Path.
163
+ const failed = t.failed ?? (t.phase !== undefined ? false : undefined);
164
+ if (failed !== undefined)
165
+ want("bkit:failed", failed);
154
166
  return {
155
167
  add,
156
168
  remove: [...remove],
@@ -159,11 +171,11 @@ export function transitionLabels(current, t) {
159
171
  }
160
172
  /**
161
173
  * Linear's issue state for the same transition, as the workflows set it: a
162
- * shipped, failed or debugged issue waits on a human ("In Review"); a phase
174
+ * shipped or failed issue waits on a human ("In Review"); a phase
163
175
  * starting is "In Progress". Null when the transition sets no state.
164
176
  */
165
177
  export function linearState(t, board) {
166
- if (t.phase === "merged" || t.failed === true || t.debug === true)
178
+ if (t.phase === "merged" || t.failed === true)
167
179
  return "In Review";
168
180
  if (t.phase !== undefined)
169
181
  return "In Progress";
@@ -253,21 +265,16 @@ function boardPayload(ctx, status) {
253
265
  function labelsVerb(ctx) {
254
266
  const phase = str(ctx.flags.phase);
255
267
  if (phase !== undefined && !PHASE_LABELS.includes(`bkit:${phase}`)) {
256
- throw new CommandError(EXIT.USAGE, "--phase must be design, plan, build, ship, or merged");
257
- }
258
- let failed = onOff(ctx.flags.failed, "failed");
259
- const debug = onOff(ctx.flags.debug, "debug");
260
- // A merged issue must not keep a stale Failure Path marker.
261
- if (phase === "merged") {
262
- if (failed === true)
263
- throw new CommandError(EXIT.USAGE, "--phase=merged clears bkit:failed; drop --failed=on");
264
- failed = false;
268
+ throw new CommandError(EXIT.USAGE, "--phase must be design, plan, build, debug, ship, or merged");
265
269
  }
270
+ const failed = onOff(ctx.flags.failed, "failed");
271
+ if (phase !== undefined && failed === true)
272
+ throw new CommandError(EXIT.USAGE, "--phase clears bkit:failed; drop --failed=on");
266
273
  const board = str(ctx.flags.board);
267
274
  if (board !== undefined && BOARD_OPTION[board] === undefined) {
268
275
  throw new CommandError(EXIT.USAGE, "--board must be progress or review");
269
276
  }
270
- const t = { phase, failed, debug };
277
+ const t = { phase, failed };
271
278
  const { add, remove, labels } = transitionLabels(ctx.flags.label ?? [], t);
272
279
  const { board: payload, boardSkipped } = board === undefined ? { board: null, boardSkipped: null } : boardPayload(ctx, board);
273
280
  ctx.emit({
@@ -360,12 +367,33 @@ function links(o) {
360
367
  const ref = o.ref ?? o.tree;
361
368
  if (ref === undefined)
362
369
  throw new CommandError(EXIT.USAGE, "--artifact needs --ref (or --tree)");
363
- for (const a of artifacts)
364
- out.push(`[${path.basename(a)}](${gh}/blob/${ref}/${a.replace(/^\/+/, "")})`);
370
+ for (const a of artifacts) {
371
+ const hash = a.indexOf("#");
372
+ const file = (hash < 0 ? a : a.slice(0, hash)).replace(/^\/+/, "");
373
+ const heading = hash < 0 ? undefined : a.slice(hash + 1).trim();
374
+ if (heading === "")
375
+ throw new CommandError(EXIT.USAGE, `--artifact "${a}" has an empty #Heading`);
376
+ const url = `${gh}/blob/${ref}/${file}`;
377
+ out.push(heading === undefined
378
+ ? `[${path.basename(file)}](${url})`
379
+ : `[${path.basename(file)} § ${heading}](${url}#${headingAnchor(heading)})`);
380
+ }
365
381
  }
366
382
  return out;
367
383
  }
368
- const KINDS = ["step", "failure", "handover"];
384
+ /**
385
+ * GitHub's anchor for a markdown heading: lowercased, punctuation dropped,
386
+ * spaces to hyphens. A repeated heading's later copies take `-1`, `-2`; this
387
+ * names the first.
388
+ */
389
+ export function headingAnchor(heading) {
390
+ return heading
391
+ .trim()
392
+ .toLowerCase()
393
+ .replace(/[^\p{L}\p{M}\p{N}\p{Pc} -]/gu, "")
394
+ .replace(/ /g, "-");
395
+ }
396
+ const KINDS = ["step", "failure", "handover", "audit"];
369
397
  /** The exact comment body; files (`bodyFile`, `sections`, `stderrFile`, `errorFile`) resolve against `cwd`. */
370
398
  export function buildComment(cwd, o) {
371
399
  const kind = o.kind ?? "step";
@@ -406,6 +434,13 @@ export function buildComment(cwd, o) {
406
434
  lines.push("Stderr:", fenced(captured));
407
435
  }
408
436
  }
437
+ else if (kind === "audit") {
438
+ const slug = o.auditSlug;
439
+ if (slug === undefined || !/^[a-z0-9-]+$/.test(slug)) {
440
+ throw new CommandError(EXIT.USAGE, "--kind=audit needs --audit-slug=<template slug>");
441
+ }
442
+ lines.push([`### Audit Summary: ${slug}`, ...(o.fields ?? []).map(([k, v]) => `${k}: ${v}`)].join(" - "));
443
+ }
409
444
  else {
410
445
  lines.push("### Workflow Handover");
411
446
  }
@@ -436,11 +471,12 @@ export function commentBody(ctx) {
436
471
  }
437
472
  return buildComment(ctx.cwd, {
438
473
  kind: kind,
474
+ auditSlug: str(ctx.flags.auditSlug),
439
475
  workflow: str(ctx.flags.workflow),
440
476
  workflowHeading: ctx.flags.workflowHeading === true,
441
477
  stepNumber: str(ctx.flags.stepNumber),
442
478
  stepTitle: str(ctx.flags.stepTitle),
443
- fields: kind === "step" ? headerFields(ctx) : [],
479
+ fields: kind === "step" || kind === "audit" ? headerFields(ctx) : [],
444
480
  subStep: str(ctx.flags.subStep),
445
481
  error: str(ctx.flags.error),
446
482
  errorFile: str(ctx.flags.errorFile),
@@ -490,10 +526,9 @@ export const issuesCommand = {
490
526
  {
491
527
  name: "phase",
492
528
  type: "string",
493
- help: "set this phase: design | plan | build | ship | merged",
529
+ help: "set this phase: design | plan | build | debug | ship | merged (drops next:* and bkit:failed)",
494
530
  },
495
- { name: "failed", type: "string", help: "bkit:failed on | off (merged implies off)" },
496
- { name: "debug", type: "string", help: "bkit:debug on | off" },
531
+ { name: "failed", type: "string", help: "bkit:failed on | off (a phase implies off)" },
497
532
  {
498
533
  name: "board",
499
534
  type: "string",
@@ -515,9 +550,10 @@ export const issuesCommand = {
515
550
  run: labelsVerb,
516
551
  },
517
552
  comment: {
518
- summary: "The exact body of a ###### bkit:generated step, failure, or handover comment.",
553
+ summary: "The exact body of a ###### bkit:generated step, failure, handover, or audit comment.",
519
554
  flags: [
520
- { name: "kind", type: "string", help: "step (default) | failure | handover" },
555
+ { name: "kind", type: "string", help: "step (default) | failure | handover | audit" },
556
+ { name: "audit-slug", type: "string", help: "audit: template slug, e.g. security" },
521
557
  { name: "step-number", type: "string", help: "step number in the heading" },
522
558
  { name: "step-title", type: "string", help: "step title in the heading, e.g. Plan Verify" },
523
559
  { name: "workflow", type: "string", help: "design | plan | build | debug | ship | auto" },
@@ -548,7 +584,7 @@ export const issuesCommand = {
548
584
  name: "artifact",
549
585
  type: "string",
550
586
  repeatable: true,
551
- help: "link this repo path at --ref",
587
+ help: "link this repo path at --ref; path#Heading links that section",
552
588
  },
553
589
  { name: "ref", type: "string", help: "ref the --artifact links point at (default --tree)" },
554
590
  { name: "line", type: "string", repeatable: true, help: "a raw line after the links" },