@cbartens/bkit 5.3.0 → 5.5.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 (186) hide show
  1. package/.bkit/README.md +20 -7
  2. package/.bkit/core/.agents/docs.md +1 -1
  3. package/.bkit/core/.agents/rules.md +14 -9
  4. package/.bkit/core/.bkit/README.md +19 -6
  5. package/.bkit/core/.bkit/cloud.md +77 -46
  6. package/.bkit/core/.bkit/comparison.md +3 -3
  7. package/.bkit/core/.bkit/install.md +21 -18
  8. package/.bkit/core/.bkit/lite.md +6 -6
  9. package/.bkit/core/.bkit/pipeline.md +6 -3
  10. package/.bkit/core/.bkit/prompts.md +14 -10
  11. package/.bkit/core/.bkit/providers.md +7 -7
  12. package/.bkit/core/.bkit/templates.md +46 -10
  13. package/.bkit/core/.bkit/trackers.md +92 -38
  14. package/.bkit/core/.bkit/workflows.md +140 -116
  15. package/.bkit/core/AGENTS.md +2 -2
  16. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +3 -2
  17. package/.bkit/core/docs/templates/bkit-audit-adoption.md +1 -1
  18. package/.bkit/core/docs/templates/bkit-audit-agents.md +1 -1
  19. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +1 -1
  20. package/.bkit/core/docs/templates/bkit-audit-analytics.md +1 -1
  21. package/.bkit/core/docs/templates/bkit-audit-annotations.md +1 -1
  22. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +2 -2
  23. package/.bkit/core/docs/templates/bkit-audit-app-store.md +1 -1
  24. package/.bkit/core/docs/templates/bkit-audit-architecture.md +1 -1
  25. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +4 -2
  26. package/.bkit/core/docs/templates/bkit-audit-config.md +3 -2
  27. package/.bkit/core/docs/templates/bkit-audit-cost.md +3 -2
  28. package/.bkit/core/docs/templates/bkit-audit-coverage.md +1 -1
  29. package/.bkit/core/docs/templates/bkit-audit-database.md +3 -2
  30. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +5 -5
  31. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +1 -1
  32. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +14 -13
  33. package/.bkit/core/docs/templates/bkit-audit-documentation.md +1 -1
  34. package/.bkit/core/docs/templates/bkit-audit-duplication.md +2 -2
  35. package/.bkit/core/docs/templates/bkit-audit-failures.md +1 -1
  36. package/.bkit/core/docs/templates/bkit-audit-flakes.md +3 -2
  37. package/.bkit/core/docs/templates/bkit-audit-gates.md +5 -2
  38. package/.bkit/core/docs/templates/bkit-audit-issues.md +25 -8
  39. package/.bkit/core/docs/templates/bkit-audit-llm.md +3 -2
  40. package/.bkit/core/docs/templates/bkit-audit-logs.md +10 -6
  41. package/.bkit/core/docs/templates/bkit-audit-models.md +1 -1
  42. package/.bkit/core/docs/templates/bkit-audit-privacy.md +1 -1
  43. package/.bkit/core/docs/templates/bkit-audit-prompts.md +5 -5
  44. package/.bkit/core/docs/templates/bkit-audit-red-team.md +3 -2
  45. package/.bkit/core/docs/templates/bkit-audit-reliability.md +3 -2
  46. package/.bkit/core/docs/templates/bkit-audit-repo.md +1 -1
  47. package/.bkit/core/docs/templates/bkit-audit-security.md +11 -9
  48. package/.bkit/core/docs/templates/bkit-audit-slop.md +1 -1
  49. package/.bkit/core/docs/templates/bkit-audit-testing.md +6 -5
  50. package/.bkit/core/docs/templates/bkit-audit-usability.md +1 -1
  51. package/.bkit/core/engine/checks/after/auth.ts +88 -45
  52. package/.bkit/core/engine/checks/after/github.ts +18 -5
  53. package/.bkit/core/engine/checks/after/index.ts +1 -1
  54. package/.bkit/core/engine/checks/after/tools.ts +1 -1
  55. package/.bkit/core/engine/checks/before/env.ts +28 -18
  56. package/.bkit/core/engine/checks/before/mcp.ts +4 -2
  57. package/.bkit/core/engine/checks/status-holes.ts +0 -1
  58. package/.bkit/core/engine/checks/tips/catalogue.ts +31 -2
  59. package/.bkit/core/engine/checks/tips/index.ts +49 -27
  60. package/.bkit/core/engine/cli.ts +27 -18
  61. package/.bkit/core/engine/commands/ci/ci.ts +107 -0
  62. package/.bkit/core/engine/commands/comply.ts +25 -16
  63. package/.bkit/core/engine/commands/install/install.ts +11 -4
  64. package/.bkit/core/engine/commands/install/uninstall.ts +46 -0
  65. package/.bkit/core/engine/commands/land.ts +156 -0
  66. package/.bkit/core/engine/commands/lib.ts +10 -8
  67. package/.bkit/core/engine/commands/registry.ts +2 -0
  68. package/.bkit/core/engine/commands/tips.ts +7 -3
  69. package/.bkit/core/engine/commands/workflow/branches.ts +382 -282
  70. package/.bkit/core/engine/commands/workflow/disk.ts +556 -0
  71. package/.bkit/core/engine/commands/workflow/fids.ts +23 -15
  72. package/.bkit/core/engine/commands/workflow/issues.ts +106 -42
  73. package/.bkit/core/engine/commands/workflow/ledgers.ts +28 -11
  74. package/.bkit/core/engine/commands/workflow/locks.ts +38 -152
  75. package/.bkit/core/engine/commands/workflow/prs.ts +14 -3
  76. package/.bkit/core/engine/commands/workflow/repo.ts +6 -0
  77. package/.bkit/core/engine/commands/workflow/roadmap.ts +53 -54
  78. package/.bkit/core/engine/commands/workflow/runtime.ts +3 -2
  79. package/.bkit/core/engine/commands/workflow/status.ts +33 -11
  80. package/.bkit/core/engine/commands/workflow/steps.ts +26 -17
  81. package/.bkit/core/engine/commands/workflow/workflows.ts +442 -269
  82. package/.bkit/core/engine/commands/workflow/workstreams.ts +3 -2
  83. package/.bkit/core/engine/commands/workflow/worktrees.ts +11 -1
  84. package/.bkit/core/engine/install/manifest.ts +31 -10
  85. package/.bkit/core/engine/install/modules/cloud.ts +3 -1
  86. package/.bkit/core/engine/install/modules/core.ts +97 -4
  87. package/.bkit/core/engine/install/modules/opencode.ts +5 -0
  88. package/.bkit/core/engine/install/placeholders.ts +13 -17
  89. package/.bkit/core/engine/install/write.ts +37 -1
  90. package/.bkit/core/engine/render/trackers.ts +35 -23
  91. package/.bkit/core/engine/shared/egress.ts +6 -0
  92. package/.bkit/core/engine/shared/settings.ts +96 -1
  93. package/.bkit/core/engine/shared/timeouts.ts +8 -7
  94. package/.bkit/core/hooks/guardrails-tiers.js +1 -1
  95. package/.bkit/core/prompts/bkit-audit-generate.md +80 -7
  96. package/.bkit/core/prompts/bkit-build-challenge-remediate.md +1 -1
  97. package/.bkit/core/prompts/bkit-build-challenge-tests.md +1 -1
  98. package/.bkit/core/prompts/bkit-build-plan-execute.md +1 -1
  99. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +1 -1
  100. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +1 -1
  101. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +1 -1
  102. package/.bkit/core/prompts/bkit-debug-failure-soak.md +1 -1
  103. package/.bkit/core/prompts/bkit-design-generate.md +2 -1
  104. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +1 -1
  105. package/.bkit/core/prompts/bkit-utility-update-decisions.md +4 -2
  106. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +4 -2
  107. package/.bkit/core/prompts/bkit-utility-update-documentation.md +12 -2
  108. package/.bkit/core/prompts/bkit-utility-update-failures.md +4 -2
  109. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +4 -2
  110. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +12 -5
  111. package/.bkit/core/prompts/bkit-utility-update-tracker.md +159 -0
  112. package/.bkit/core/workflows/bkit-auto.md +19 -6
  113. package/.bkit/core/workflows/bkit-build.md +64 -22
  114. package/.bkit/core/workflows/bkit-debug.md +72 -28
  115. package/.bkit/core/workflows/bkit-design.md +101 -37
  116. package/.bkit/core/workflows/bkit-plan.md +82 -31
  117. package/.bkit/core/workflows/bkit-ship.md +127 -108
  118. package/.bkit/shared/.bkit/.env.example +8 -0
  119. package/.bkit/shared/.claude/bkit-cloud.md +12 -12
  120. package/.bkit/shared/.claude/settings.json +4 -1
  121. package/.bkit/shared/.cursor/bkit-cloud.md +2 -2
  122. package/.bkit/shared/.cursor/mcp.json +11 -4
  123. package/.bkit/shared/.mcp.json +11 -4
  124. package/.bkit/shared/.opencode/opencode.json +2 -0
  125. package/.bkit/shared/docs/deployments.md +44 -29
  126. package/.bkit/shared/docs/security.md +1 -1
  127. package/.bkit/shared/docs/testing.md +3 -3
  128. package/.bkit/shared/gitignore +1 -2
  129. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-change.yml +2 -2
  130. package/.bkit/templates/.github/renovate.json5 +1 -1
  131. package/.bkit/templates/.github/workflows/bkit-ci.yml +29 -56
  132. package/.bkit/templates/.github/workflows/bkit-cloud.yml +40 -12
  133. package/.bkit/templates/.husky/pre-commit +10 -4
  134. package/.bkit/templates/.husky/pre-push +69 -12
  135. package/.bkit/templates/.lintstagedrc.json +5 -1
  136. package/.bkit/templates/scripts/ci/lanes/check-tree-cache.mjs +138 -0
  137. package/.bkit/templates/scripts/ci/lanes/check-tree-cache.test.mjs +181 -0
  138. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.machine.mjs +197 -0
  139. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.mjs +164 -0
  140. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +1 -1
  141. package/CHANGELOG.md +85 -1
  142. package/README.md +102 -100
  143. package/dist/checks/after/auth.js +81 -45
  144. package/dist/checks/after/github.js +17 -5
  145. package/dist/checks/after/index.js +1 -1
  146. package/dist/checks/after/tools.js +1 -1
  147. package/dist/checks/before/env.js +24 -17
  148. package/dist/checks/before/mcp.js +4 -2
  149. package/dist/checks/status-holes.js +0 -1
  150. package/dist/checks/tips/catalogue.js +28 -2
  151. package/dist/checks/tips/index.js +44 -28
  152. package/dist/cli.js +27 -19
  153. package/dist/commands/ci/ci.js +100 -0
  154. package/dist/commands/comply.js +20 -13
  155. package/dist/commands/install/install.js +10 -4
  156. package/dist/commands/install/uninstall.js +42 -0
  157. package/dist/commands/land.js +129 -0
  158. package/dist/commands/lib.js +9 -6
  159. package/dist/commands/registry.js +2 -0
  160. package/dist/commands/tips.js +7 -3
  161. package/dist/commands/workflow/branches.js +300 -243
  162. package/dist/commands/workflow/disk.js +452 -0
  163. package/dist/commands/workflow/fids.js +22 -15
  164. package/dist/commands/workflow/issues.js +90 -41
  165. package/dist/commands/workflow/ledgers.js +26 -11
  166. package/dist/commands/workflow/locks.js +35 -130
  167. package/dist/commands/workflow/prs.js +8 -3
  168. package/dist/commands/workflow/repo.js +5 -0
  169. package/dist/commands/workflow/roadmap.js +52 -57
  170. package/dist/commands/workflow/runtime.js +3 -2
  171. package/dist/commands/workflow/status.js +32 -12
  172. package/dist/commands/workflow/steps.js +20 -13
  173. package/dist/commands/workflow/workflows.js +397 -251
  174. package/dist/commands/workflow/workstreams.js +3 -2
  175. package/dist/commands/workflow/worktrees.js +11 -1
  176. package/dist/install/manifest.js +30 -10
  177. package/dist/install/modules/cloud.js +3 -1
  178. package/dist/install/modules/core.js +95 -5
  179. package/dist/install/modules/opencode.js +6 -0
  180. package/dist/install/placeholders.js +13 -19
  181. package/dist/install/write.js +26 -2
  182. package/dist/render/trackers.js +34 -20
  183. package/dist/shared/egress.js +6 -0
  184. package/dist/shared/settings.js +44 -0
  185. package/dist/shared/timeouts.js +8 -7
  186. package/package.json +11 -2
@@ -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
+ };
@@ -6,8 +6,9 @@
6
6
  // it is checked before first use. Its shape follows the tracker that minted it:
7
7
  // github {N}-{slug} ^[0-9]+-[a-z0-9-]+$
8
8
  // linear {team}-{N}-{slug} ^[a-z]+-[0-9]+-[a-z0-9-]+$ (issue id lowercased first)
9
+ // jira {project}-{N}-{slug} ^[a-z][a-z0-9]+-[0-9]+-[a-z0-9-]+$ (issue key lowercased first)
9
10
  // none any slug ^[a-z0-9][a-z0-9-]*$ (no tracker shape; still path-safe)
10
- // any github or linear ^([0-9]+|[a-z]+-[0-9]+)-[a-z0-9-]+$ (auto's CI_DEV allowlist)
11
+ // any any tracker's shape ^([0-9]+|[a-z][a-z0-9]*-[0-9]+)-[a-z0-9-]+$ (auto's CI_DEV allowlist)
11
12
  import * as fs from "node:fs";
12
13
  import * as path from "node:path";
13
14
  import { parseIssueTracker } from "../../install/manifest.js";
@@ -17,9 +18,14 @@ import { str } from "./status.js";
17
18
  export const FID_PATTERNS = {
18
19
  github: /^[0-9]+-[a-z0-9-]+$/,
19
20
  linear: /^[a-z]+-[0-9]+-[a-z0-9-]+$/,
21
+ jira: /^[a-z][a-z0-9]+-[0-9]+-[a-z0-9-]+$/,
20
22
  none: /^[a-z0-9][a-z0-9-]*$/,
21
- any: /^([0-9]+|[a-z]+-[0-9]+)-[a-z0-9-]+$/,
23
+ any: /^([0-9]+|[a-z][a-z0-9]*-[0-9]+)-[a-z0-9-]+$/,
22
24
  };
25
+ /** Trackers whose issue id is a `{KEY}-{N}` key, carried lowercased in the FID. */
26
+ const KEYED = new Set(["linear", "jira"]);
27
+ /** The uppercase issue key each keyed tracker mints. */
28
+ const ISSUE_KEY = { linear: /^[A-Z]+-[0-9]+$/, jira: /^[A-Z][A-Z0-9]+-[0-9]+$/ };
23
29
  /** The slug every recovered FID must pass before it touches a path (auto's branch fallback). */
24
30
  const SLUG = FID_PATTERNS.none;
25
31
  /** Exit code: no FID could be recovered from the marker or the branch. */
@@ -28,7 +34,7 @@ export const EXIT_NO_FID = 3;
28
34
  export const EXIT_SEVERAL = 4;
29
35
  /**
30
36
  * Features already logged for an issue: every `docs/plans/{YYYYMM}/logs/{issue}-*`
31
- * folder, the issue id lowercased (a Linear FID carries it lowercased). Sorted, unique.
37
+ * folder, the issue id lowercased (a Linear or Jira FID carries it lowercased). Sorted, unique.
32
38
  */
33
39
  export function logged(root, issue) {
34
40
  const key = `${issue.replace(/^#/, "").toLowerCase()}-`;
@@ -76,26 +82,26 @@ function trackerFlag(value, cwd, allowAny) {
76
82
  return "any";
77
83
  const t = parseIssueTracker(value);
78
84
  if (!t) {
79
- throw new CommandError(EXIT.USAGE, `--tracker must be github, linear, none${allowAny ? ", any" : ""}; got "${value}"`);
85
+ throw new CommandError(EXIT.USAGE, `--tracker must be github, linear, jira, none${allowAny ? ", any" : ""}; got "${value}"`);
80
86
  }
81
87
  return t;
82
88
  }
83
- /** Linear issue ids arrive uppercase (`ABC-123`); the FID carries them lowercased. */
84
- export const normaliseFid = (fid, tracker) => tracker === "linear" ? fid.toLowerCase() : fid;
89
+ /** Linear and Jira issue ids arrive uppercase (`ABC-123`); the FID carries them lowercased. */
90
+ export const normaliseFid = (fid, tracker) => KEYED.has(tracker) ? fid.toLowerCase() : fid;
85
91
  /**
86
92
  * The tracker issue id a FID embeds, or null when it embeds none:
87
- * github the leading numeric segment, linear the first two segments uppercased.
93
+ * github the leading numeric segment, linear and jira the first two segments uppercased.
88
94
  */
89
95
  export function issueIdOf(fid, tracker) {
90
96
  const [first = "", second = ""] = fid.split("-");
91
97
  if (tracker === "github")
92
98
  return /^[0-9]+$/.test(first) ? first : null;
93
- if (tracker === "linear") {
99
+ if (KEYED.has(tracker)) {
94
100
  const id = `${first}-${second}`.toUpperCase();
95
- return /^[A-Z]+-[0-9]+$/.test(id) ? id : null;
101
+ return ISSUE_KEY[tracker].test(id) ? id : null;
96
102
  }
97
103
  if (tracker === "any") {
98
- const m = /^([0-9]+|[a-z]+-[0-9]+)(?=-)/.exec(fid);
104
+ const m = /^([0-9]+|[a-z][a-z0-9]*-[0-9]+)(?=-)/.exec(fid);
99
105
  return m ? m[1].toUpperCase() : null;
100
106
  }
101
107
  return null;
@@ -104,6 +110,7 @@ export function issueIdOf(fid, tracker) {
104
110
  const MARKERS = {
105
111
  github: /<!-- bkit:issue=#([0-9]+) bkit:fid=(\S+) -->/,
106
112
  linear: /<!-- bkit:issue=([A-Za-z]+-[0-9]+) bkit:fid=(\S+) -->/,
113
+ jira: /<!-- bkit:issue=([A-Za-z][A-Za-z0-9]+-[0-9]+) bkit:fid=(\S+) -->/,
107
114
  none: /<!-- bkit:fid=(\S+) -->/,
108
115
  };
109
116
  /** FID from the marker, when present and well-formed for the tracker. */
@@ -114,7 +121,7 @@ export function fromMarker(text, tracker) {
114
121
  const fid = normaliseFid(m[m.length - 1], tracker);
115
122
  if (!FID_PATTERNS[tracker].test(fid))
116
123
  return null;
117
- const issueId = tracker === "none" ? null : tracker === "linear" ? m[1].toUpperCase() : m[1];
124
+ const issueId = tracker === "none" ? null : KEYED.has(tracker) ? m[1].toUpperCase() : m[1];
118
125
  return { fid, issueId, source: "marker" };
119
126
  }
120
127
  /** FID from `feat/{FID}`; the slug check, then the issue id the tracker needs. */
@@ -133,7 +140,7 @@ export function fromBranch(branch, tracker) {
133
140
  const TRACKER_FLAG = {
134
141
  name: "tracker",
135
142
  type: "string",
136
- help: "github | linear | none (default: package.json bkit.issueTracker, else none)",
143
+ help: "github | linear | jira | none (default: package.json bkit.issueTracker, else none)",
137
144
  };
138
145
  export const fidsCommand = {
139
146
  noun: "fids",
@@ -143,10 +150,10 @@ export const fidsCommand = {
143
150
  summary: "Validate a FID for the tracker: exit 0 valid, exit 1 not.",
144
151
  flags: [
145
152
  { name: "fid", type: "string", required: true, help: "feature id to check" },
146
- { ...TRACKER_FLAG, help: `${TRACKER_FLAG.help}; any = github or linear shape (CI_DEV)` },
153
+ { ...TRACKER_FLAG, help: `${TRACKER_FLAG.help}; any = any tracker's shape (CI_DEV)` },
147
154
  ],
148
155
  output: {
149
- fid: "the FID as checked (linear: lowercased)",
156
+ fid: "the FID as checked (linear, jira: lowercased)",
150
157
  tracker: "tracker the shape came from",
151
158
  valid: "true when the FID matches",
152
159
  pattern: "the regex checked",
@@ -241,7 +248,7 @@ export const fidsCommand = {
241
248
  name: "issue",
242
249
  type: "string",
243
250
  required: true,
244
- help: "tracker issue id (github: 123 or #123; linear: ABC-123)",
251
+ help: "tracker issue id (github: 123 or #123; linear / jira: ABC-123)",
245
252
  },
246
253
  ],
247
254
  output: {