@krysoworks/kryso 0.0.0-stage → 2.0.0-rc.1

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 (162) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +152 -2
  3. package/bin/kryso +31 -0
  4. package/bin/ship-it-status +14 -0
  5. package/bin/ship-ledger +14 -0
  6. package/bin/ship-loop +14 -0
  7. package/bin/ship-pass +14 -0
  8. package/bin/warden +14 -0
  9. package/dist/answer.d.ts +38 -0
  10. package/dist/answer.js +48 -0
  11. package/dist/bytes.d.ts +5 -0
  12. package/dist/bytes.js +35 -0
  13. package/dist/cleanup.d.ts +1 -0
  14. package/dist/cleanup.js +629 -0
  15. package/dist/commands.d.ts +48 -0
  16. package/dist/commands.js +293 -0
  17. package/dist/completions.d.ts +24 -0
  18. package/dist/completions.js +239 -0
  19. package/dist/daemon.d.ts +15 -0
  20. package/dist/daemon.js +23 -0
  21. package/dist/diagnose.d.ts +47 -0
  22. package/dist/diagnose.js +314 -0
  23. package/dist/doctor.d.ts +1 -0
  24. package/dist/doctor.js +241 -0
  25. package/dist/env.d.ts +9 -0
  26. package/dist/env.js +17 -0
  27. package/dist/evidence.d.ts +39 -0
  28. package/dist/evidence.js +327 -0
  29. package/dist/home.d.ts +3 -0
  30. package/dist/home.js +27 -0
  31. package/dist/install.d.ts +59 -0
  32. package/dist/install.js +137 -0
  33. package/dist/isolate.d.ts +28 -0
  34. package/dist/isolate.js +402 -0
  35. package/dist/leftovers.d.ts +5 -0
  36. package/dist/leftovers.js +156 -0
  37. package/dist/machine.d.ts +6 -0
  38. package/dist/machine.js +185 -0
  39. package/dist/palette.d.ts +147 -0
  40. package/dist/palette.js +167 -0
  41. package/dist/plan.d.ts +1 -0
  42. package/dist/plan.js +133 -0
  43. package/dist/proc.d.ts +23 -0
  44. package/dist/proc.js +23 -0
  45. package/dist/read.d.ts +1 -0
  46. package/dist/read.js +297 -0
  47. package/dist/readiness.d.ts +5 -0
  48. package/dist/readiness.js +64 -0
  49. package/dist/remote.d.ts +6 -0
  50. package/dist/remote.js +85 -0
  51. package/dist/self-update.d.ts +1 -0
  52. package/dist/self-update.js +224 -0
  53. package/dist/semver.d.ts +7 -0
  54. package/dist/semver.js +42 -0
  55. package/dist/style.d.ts +71 -0
  56. package/dist/style.js +187 -0
  57. package/dist/update.d.ts +47 -0
  58. package/dist/update.js +190 -0
  59. package/dist/work.d.ts +25 -0
  60. package/dist/work.js +449 -0
  61. package/dist/workflows.d.ts +4 -0
  62. package/dist/workflows.js +73 -0
  63. package/docker/entrypoint.sh +44 -0
  64. package/docker/runner.Dockerfile +39 -0
  65. package/package.json +65 -4
  66. package/scripts/install-skills.sh +607 -0
  67. package/skills/code-review/SKILL.md +231 -0
  68. package/skills/kryso/SKILL.md +107 -0
  69. package/skills/kryso/golden/help.rounded.ansi +23 -0
  70. package/skills/kryso/golden/help.square.ansi +23 -0
  71. package/skills/kryso/golden/help.txt +23 -0
  72. package/skills/kryso/golden/table-narrow.json +11 -0
  73. package/skills/kryso/golden/table-narrow.rounded.ansi +4 -0
  74. package/skills/kryso/golden/table-narrow.square.ansi +4 -0
  75. package/skills/kryso/golden/table.ansi +5 -0
  76. package/skills/kryso/golden/table.json +11 -0
  77. package/skills/kryso/ledger.sh +2146 -0
  78. package/skills/kryso/palette.json +57 -0
  79. package/skills/kryso/reference/resuming.md +30 -0
  80. package/skills/kryso/reference/routing.md +23 -0
  81. package/skills/kryso/reference/stage-1-claim.md +79 -0
  82. package/skills/kryso/reference/stage-2-build.md +133 -0
  83. package/skills/kryso/reference/stage-3-prove.md +51 -0
  84. package/skills/kryso/reference/stage-4-pr.md +76 -0
  85. package/skills/kryso/reference/stage-5-reconcile.md +81 -0
  86. package/skills/kryso/reference/stage-6-merge-or-park.md +73 -0
  87. package/skills/kryso/reference/stage-7-close-out.md +62 -0
  88. package/skills/kryso/reference/terminal.md +7 -0
  89. package/skills/kryso/ship-it-status.sh +1503 -0
  90. package/skills/kryso/ui.py +274 -0
  91. package/skills/kryso/ui.sh +609 -0
  92. package/skills/kryso-build/SKILL.md +168 -0
  93. package/skills/kryso-shift/SKILL.md +167 -0
  94. package/skills/kryso-shift/archive.py +2784 -0
  95. package/skills/kryso-shift/archive_checker.py +462 -0
  96. package/skills/kryso-shift/archive_checker_lambda.py +155 -0
  97. package/skills/kryso-shift/archive_health.py +364 -0
  98. package/skills/kryso-shift/archive_launchd.py +140 -0
  99. package/skills/kryso-shift/archive_remote.py +990 -0
  100. package/skills/kryso-shift/archiving-checker.md +140 -0
  101. package/skills/kryso-shift/archiving-keep.md +115 -0
  102. package/skills/kryso-shift/archiving-recovery.md +112 -0
  103. package/skills/kryso-shift/archiving-remote.md +166 -0
  104. package/skills/kryso-shift/archiving.md +146 -0
  105. package/skills/kryso-shift/coverage.schema.json +225 -0
  106. package/skills/kryso-shift/deadline.sh +254 -0
  107. package/skills/kryso-shift/feedback.schema.json +35 -0
  108. package/skills/kryso-shift/feedback.sh +228 -0
  109. package/skills/kryso-shift/history-manifest.schema.json +331 -0
  110. package/skills/kryso-shift/keep-after.sh +55 -0
  111. package/skills/kryso-shift/measure.sh +611 -0
  112. package/skills/kryso-shift/merge-ready.sh +207 -0
  113. package/skills/kryso-shift/outcome.schema.json +16 -0
  114. package/skills/kryso-shift/pass-rules.md +8 -0
  115. package/skills/kryso-shift/profile.schema.json +42 -0
  116. package/skills/kryso-shift/reader.sh +692 -0
  117. package/skills/kryso-shift/reads.sh +151 -0
  118. package/skills/kryso-shift/reference/allowance.md +21 -0
  119. package/skills/kryso-shift/reference/driver.md +95 -0
  120. package/skills/kryso-shift/reference/measuring.md +67 -0
  121. package/skills/kryso-shift/reference/outputs.md +21 -0
  122. package/skills/kryso-shift/reference/pass-script.md +115 -0
  123. package/skills/kryso-shift/reference/reconcile-and-merge.md +55 -0
  124. package/skills/kryso-shift/reference/second-reader.md +9 -0
  125. package/skills/kryso-shift/reference/sweeps.md +83 -0
  126. package/skills/kryso-shift/repair.schema.json +14 -0
  127. package/skills/kryso-shift/report-template.html +679 -0
  128. package/skills/kryso-shift/report.py +389 -0
  129. package/skills/kryso-shift/report_fixture.py +65 -0
  130. package/skills/kryso-shift/reporting.md +58 -0
  131. package/skills/kryso-shift/result.sh +91 -0
  132. package/skills/kryso-shift/runner.sh +1178 -0
  133. package/skills/kryso-shift/ship-loop.sh +3977 -0
  134. package/skills/kryso-shift/ship-pass.sh +4987 -0
  135. package/skills/kryso-shift/steps.jq +19 -0
  136. package/skills/kryso-shift/workflow.mjs +830 -0
  137. package/skills/kryso-shift/workflows/default.json +22 -0
  138. package/skills/kryso-shift/workflows/ralph.json +13 -0
  139. package/skills/kryso-watch/SKILL.md +100 -0
  140. package/skills/kryso-watch/answer.schema.json +23 -0
  141. package/skills/kryso-watch/base-refs.sh +44 -0
  142. package/skills/kryso-watch/board.sh +58 -0
  143. package/skills/kryso-watch/reference/config.md +23 -0
  144. package/skills/kryso-watch/reference/outputs.md +30 -0
  145. package/skills/kryso-watch/reference/report.md +29 -0
  146. package/skills/kryso-watch/reference/scheduler.md +32 -0
  147. package/skills/kryso-watch/reference/settlement.md +29 -0
  148. package/skills/kryso-watch/reference/shift.md +44 -0
  149. package/skills/kryso-watch/reference/shim-limits.md +22 -0
  150. package/skills/kryso-watch/reference/triage.md +26 -0
  151. package/skills/kryso-watch/schema.jq +40 -0
  152. package/skills/kryso-watch/settle.schema.json +36 -0
  153. package/skills/kryso-watch/stage-common.sh +187 -0
  154. package/skills/kryso-watch/stages/report.sh +525 -0
  155. package/skills/kryso-watch/stages/settle.sh +722 -0
  156. package/skills/kryso-watch/stages/shift.sh +466 -0
  157. package/skills/kryso-watch/stages/triage.sh +379 -0
  158. package/skills/kryso-watch/tracker.sh +27 -0
  159. package/skills/kryso-watch/triage.schema.json +77 -0
  160. package/skills/kryso-watch/warden.launchd.plist +50 -0
  161. package/skills/kryso-watch/warden.schema.json +98 -0
  162. package/skills/kryso-watch/warden.sh +1004 -0
@@ -0,0 +1,629 @@
1
+ // kryso cleanup: remove what kryso doctor names as cleanup's (ADR 0044). It builds the same
2
+ // diagnoses doctor prints, through diagnose.ts, for the same scope: this machine and the
3
+ // repository of the current directory, or with --all every repository doctor --all reads. It keeps
4
+ // those of class cleanup in the groups it can remove and the run names, prints them as a plan with
5
+ // a size a line and a total, grouped by repository under --all, asks once, and removes them.
6
+ // --dry-run stops after the plan, and --force answers the question and relaxes no rule, so a
7
+ // forced run removes exactly what a dry run prints. With no terminal and no --force it removes
8
+ // nothing and exits 64. After a person answers, which can take any time, it builds the diagnoses
9
+ // again and removes only what is still cleanup's, so a copy a run started on while the question
10
+ // waited stays, as a removal that failed. A removal that fails is one line with its reason, the
11
+ // others still run, and the run exits 1. bin/kryso execs this file, and kryso runs it with the
12
+ // drivers missing, as it does doctor.
13
+ //
14
+ // A diagnosis whose state is unknown, because a read it needed was refused, is never planned, and
15
+ // the plan names each one it left out, with its count. A repository an isolated run holds gets
16
+ // nothing planned, the same guard an isolated run takes, and the plan says so with the run's pid.
17
+ // Once answered, cleanup holds that guard in each repository it removes in until its last
18
+ // removal, and a signal stops it between removals (ADR 0049).
19
+ //
20
+ // It closes out the passes whose pull request merged and whose worktree is left, removes the pass
21
+ // lock files nothing holds whose issue is closed, deletes the local branches that are merged, and
22
+ // removes the installer's leftovers in the home directory: the skill backups past the newest five
23
+ // and the retired skill copies nothing uses. None of those is a repository's evidence.
24
+ //
25
+ // Evidence is planned by --evidence alone, never by a group name, all included (ADR 0044). It
26
+ // needs the keep configuration, named with --config or by the keep launch agent, with a remote,
27
+ // and refuses in one line without. It plans a shift folder or a shipped copy that doctor names as
28
+ // past the retention, 90 days unless --older-than names another, with every file held by a
29
+ // snapshot the remote has verified, and names each copy past the retention it keeps whole. Its
30
+ // question comes after the plan's own, each answer stands alone, and --force answers only the
31
+ // plan's: with evidence planned and no terminal nothing goes, and the run says so and exits 64.
32
+ // The archive is read through doctor's diagnoses, its status verb and its manifests, and never
33
+ // changed.
34
+ //
35
+ // A merged pass's worktree goes through the pass's own closeout and nothing of cleanup's: it runs
36
+ // `kryso pass <issue> --resume` in the repository, one pass at a time, which verifies the merge on
37
+ // origin, closes the issue, copies the ledger out and removes the worktree and the branch. It reads the
38
+ // outcome block the pass prints, and where the closeout stopped part-way it reads the disk for
39
+ // whether the worktree is still there before it says what finishes the closeout. The pass's stdout
40
+ // is its outcome block and nothing else, which is the driver's contract.
41
+ //
42
+ // A pass lock file goes through the ledger module's drop, which removes it while it holds its
43
+ // lock, and never through an unlink of cleanup's own: a file read as unheld and then unlinked can
44
+ // be locked in between, and two passes would then hold one issue. A branch goes at the tip the
45
+ // plan showed and no other, so a commit made on it since keeps it.
46
+ import { spawnSync } from "node:child_process";
47
+ import { existsSync, readFileSync, readSync, rmSync, writeFileSync } from "node:fs";
48
+ import path from "node:path";
49
+ import { isatty } from "node:tty";
50
+ import { descriptor, give, helpAnswer, refusal, say } from "./answer.js";
51
+ import { size, sizeOf } from "./bytes.js";
52
+ import { diagnose, everywhere, here, mainOf } from "./diagnose.js";
53
+ import { keepOf, RETENTION_DAYS } from "./evidence.js";
54
+ import { EX_SOFTWARE, EX_USAGE } from "./env.js";
55
+ import { findHome } from "./home.js";
56
+ import { packageRoot } from "./install.js";
57
+ import { PID_FILE } from "./isolate.js";
58
+ import { capture, failure } from "./proc.js";
59
+ import { ledgerModule as moduleAt, lockFiles, passOf, tipOf } from "./work.js";
60
+ const NAME = "kryso cleanup";
61
+ /** The groups, in the order the plan lists them, and the diagnosis each removes. */
62
+ const GROUPS = {
63
+ worktrees: "work.merged",
64
+ locks: "locks.pass-closed",
65
+ branches: "branches.merged",
66
+ backups: "install.old-backup",
67
+ skills: "install.retired-skill",
68
+ evidence: "evidence.past-retention",
69
+ };
70
+ const ALL = Object.keys(GROUPS);
71
+ /** The groups a run can name. Evidence is not one: only --evidence plans it. */
72
+ const NAMES = ALL.filter((g) => g !== "evidence");
73
+ /** A copy past the retention that --evidence keeps whole, which the plan names. */
74
+ const KEPT = "evidence.past-retention-unheld";
75
+ /** The diagnoses each group reads, by the start of their id: an unknown one is what the group
76
+ * left out. */
77
+ const FAMILY = {
78
+ worktrees: "work.",
79
+ locks: "locks.pass-",
80
+ branches: "branches.",
81
+ backups: "install.old-backup",
82
+ skills: "install.retired-skill",
83
+ evidence: "evidence.",
84
+ };
85
+ const USAGE = `Usage: kryso cleanup [--all] [--dry-run] [--force] [--keep-backups N]
86
+ [--evidence [--config FILE] [--older-than N]] [group...]
87
+
88
+ It removes what kryso doctor names as cleanup's on this machine and in the
89
+ repository of the current directory. It prints the plan first, one line per
90
+ removal with its size and a total, then asks once. Nothing is removed until
91
+ you answer yes. Nothing whose state is unknown is planned, and the plan names
92
+ what it left out. A repository an isolated run holds gets nothing planned.
93
+
94
+ Groups:
95
+ worktrees the worktrees of passes whose pull request merged, each closed
96
+ out by kryso pass <issue> --resume, which closes the issue and
97
+ deletes the branch here and on origin
98
+ locks the pass lock files no process holds, for closed issues with no
99
+ worktree left, each removed by the ledger module under its lock
100
+ branches the local branches whose tip is on origin's default branch, or
101
+ whose pull request merged at that tip; never integration/*, the
102
+ default or current branch, or one a worktree has checked out
103
+ backups the dated skill backups in ~/.agents past the newest five
104
+ skills the skill copies under names 2.0.0 retired that no launch agent,
105
+ link or running process uses
106
+ all every group, which is what no name means, and never evidence
107
+
108
+ --all cover every repository kryso doctor --all reads, with the
109
+ plan grouped by repository and one question for it all
110
+ --dry-run print the plan, and remove nothing, even with --force
111
+ --force remove without asking, for a run nobody attends; it
112
+ removes exactly what --dry-run prints, evidence aside
113
+ --keep-backups N keep the newest N skill backups for this run, not five
114
+ --evidence plan evidence too: each shift folder and shipped copy
115
+ past the retention whose every file, byte for byte, is in
116
+ an archive snapshot the remote archive has verified. It
117
+ asks its own question after the plan's, which --force
118
+ does not answer, so with no terminal nothing goes
119
+ --config FILE with --evidence, the keep configuration to read, not the
120
+ one the keep launch agent names; it must name a remote
121
+ --older-than N with --evidence, the retention for this run: N days, not ${RETENTION_DAYS}
122
+ -h, --help print this help
123
+
124
+ It exits 0 when it removed all it planned, planned nothing or was told no, 1
125
+ when a removal failed or a closeout did not finish, and 64 on a bad argument,
126
+ or with no terminal when there is no --force or evidence is planned.
127
+ `;
128
+ /** The option, as its own word before its value or as --option=value. */
129
+ const valued = (a, flag) => a === flag || a.startsWith(`${flag}=`);
130
+ function parse(argv) {
131
+ const opts = { groups: new Set(), all: false, dryRun: false, force: false, evidence: false };
132
+ const usage = (line) => refusal(EX_USAGE, NAME, line, { usage: USAGE });
133
+ for (let i = 0; i < argv.length; i++) {
134
+ const a = argv[i];
135
+ // An option's value, the next word or what follows its =.
136
+ const valueOf = (flag) => (a === flag ? argv[++i] : a.slice(flag.length + 1));
137
+ if (a === "-h" || a === "--help")
138
+ return helpAnswer(USAGE, "cleanup", "help");
139
+ if (a === "--all")
140
+ opts.all = true;
141
+ else if (a === "--dry-run")
142
+ opts.dryRun = true;
143
+ else if (a === "--force")
144
+ opts.force = true;
145
+ else if (valued(a, "--keep-backups")) {
146
+ const value = valueOf("--keep-backups");
147
+ if (value === undefined || !/^\d+$/.test(value))
148
+ return usage(`--keep-backups takes a number of backups${value === undefined ? "" : `, got '${value}'`}`);
149
+ opts.keepBackups = Number(value);
150
+ }
151
+ else if (a === "--evidence")
152
+ opts.evidence = true;
153
+ else if (valued(a, "--config")) {
154
+ const value = valueOf("--config");
155
+ if (!value)
156
+ return usage("--config takes the keep configuration's file");
157
+ opts.config = value;
158
+ }
159
+ else if (valued(a, "--older-than")) {
160
+ const value = valueOf("--older-than");
161
+ if (value === undefined || !/^\d+$/.test(value))
162
+ return usage(`--older-than takes a number of days${value === undefined ? "" : `, got '${value}'`}`);
163
+ opts.olderThan = Number(value);
164
+ }
165
+ else if (a === "--remote")
166
+ return usage("has no --remote: it removes on this machine alone, and the daemon's API removes nothing");
167
+ else if (a.startsWith("-"))
168
+ return usage(`unknown option ${a}`);
169
+ else if (a === "all")
170
+ NAMES.forEach((g) => opts.groups.add(g));
171
+ else if (NAMES.includes(a))
172
+ opts.groups.add(a);
173
+ else
174
+ return usage(`unknown group '${a}': the groups are ${NAMES.join(", ")} and all`);
175
+ }
176
+ if (opts.groups.size === 0)
177
+ NAMES.forEach((g) => opts.groups.add(g));
178
+ if (!opts.evidence && opts.olderThan !== undefined)
179
+ return usage("--older-than sets the retention of --evidence, so it needs --evidence");
180
+ if (!opts.evidence && opts.config !== undefined)
181
+ return usage("--config names the keep configuration of --evidence, so it needs --evidence");
182
+ if (opts.evidence)
183
+ opts.groups.add("evidence");
184
+ return opts;
185
+ }
186
+ // Written straight to the descriptors, so the plan is out before the question waits on stdin.
187
+ const stdout = descriptor(1);
188
+ const stderr = descriptor(2);
189
+ /** What makes two plans' removals the same one: where it is, what, and a branch's tip. */
190
+ const keyOf = (r) => [r.repository ?? "", r.subject, r.tip ?? ""].join("\0");
191
+ /** The ledger module among the drivers, or undefined when kryso cannot find it. */
192
+ function ledgerModule(env) {
193
+ let home;
194
+ try {
195
+ home = findHome(env);
196
+ }
197
+ catch {
198
+ return undefined;
199
+ }
200
+ return moduleAt(home);
201
+ }
202
+ /** The diagnoses for the run's scope, read into a plan. */
203
+ function read(opts, env) {
204
+ const doc = diagnose(opts.all ? everywhere(env) : here(env), { offline: false, readiness: false, keepBackups: opts.keepBackups, keepConfig: opts.config, retentionDays: opts.olderThan }, env);
205
+ const mains = [...new Set(doc.repositories.map((repo) => mainOf(repo, env) ?? repo))];
206
+ const held = guarded(mains, env);
207
+ const named = (d, g) => opts.groups.has(g) && !held.has(d.repository ?? "") && d.id.startsWith(FAMILY[g]);
208
+ const left = doc.diagnoses.filter((d) => d.unknown && ALL.some((g) => named(d, g)));
209
+ const kept = doc.diagnoses.filter((d) => d.id === KEPT && named(d, "evidence"));
210
+ return { doc, mains, plan: planOf(doc.diagnoses, opts.groups, held, env), held, left, kept };
211
+ }
212
+ /** Each repository an isolated run holds, with why cleanup plans nothing there: the pid of the
213
+ * run the ledger module names, or why it could not tell. A stale isolation file stays, as doctor
214
+ * leaves it, for a person. */
215
+ function guarded(mains, env) {
216
+ const module = ledgerModule(env);
217
+ const held = new Map();
218
+ for (const main of mains) {
219
+ if (!module) {
220
+ held.set(main, "whether an isolated run holds it is unknown, because kryso cannot find its ledger module");
221
+ continue;
222
+ }
223
+ const r = capture("bash", [module, "isolated", main], { ...env, KRYSO_READ_ONLY: "1" }, main);
224
+ const why = heldBy(r);
225
+ if (why)
226
+ held.set(main, why);
227
+ }
228
+ return held;
229
+ }
230
+ /** Why the ledger module's `isolated` keeps cleanup off a repository, or undefined when nothing
231
+ * does: an isolated run's docker client, or another cleanup's guard. This run's own is no reason. */
232
+ function heldBy(r) {
233
+ if (r.status === 0)
234
+ return `an isolated run holds it: pid ${r.out}`;
235
+ if (r.status === 2)
236
+ return r.out === String(process.pid) ? undefined : `kryso cleanup (pid ${r.out}) is removing there`;
237
+ if (r.status !== 1)
238
+ return `whether an isolated run holds it is unknown: ${failure(r)}`;
239
+ return undefined;
240
+ }
241
+ /** Take the isolation guard in each repository, by creating kryso-isolated.json only where none
242
+ * is, so an isolated run's file and another cleanup's are never overwritten. An existing file is
243
+ * read through the ledger module's `isolated`, as a driver reads it, which removes a stale one, and
244
+ * the take is tried again. */
245
+ function takeGuards(repositories, env, guards) {
246
+ const module = ledgerModule(env);
247
+ for (const repo of repositories) {
248
+ const common = capture("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], env, repo);
249
+ if (!common.ok || !common.out) {
250
+ guards.set(repo, { why: `cleanup could not find its git directory to take the isolation guard: ${failure(common)}` });
251
+ continue;
252
+ }
253
+ const file = path.join(common.out, PID_FILE);
254
+ const body = `${JSON.stringify({ pid: process.pid, holder: "cleanup", started: new Date().toISOString() })}\n`;
255
+ let taken = { why: `${file} was made again each time cleanup cleared a stale one` };
256
+ for (let i = 0; i < 3; i++) {
257
+ try {
258
+ writeFileSync(file, body, { flag: "wx" });
259
+ taken = { file };
260
+ break;
261
+ }
262
+ catch (err) {
263
+ if (err.code !== "EEXIST") {
264
+ taken = { why: `cleanup could not take the isolation guard ${file}: ${err instanceof Error ? err.message : String(err)}` };
265
+ break;
266
+ }
267
+ }
268
+ if (!module) {
269
+ taken = { why: "whether an isolated run holds it is unknown, because kryso cannot find its ledger module" };
270
+ break;
271
+ }
272
+ const why = heldBy(capture("bash", [module, "isolated", repo], env, repo));
273
+ if (why) {
274
+ taken = { why };
275
+ break;
276
+ }
277
+ }
278
+ guards.set(repo, taken);
279
+ }
280
+ }
281
+ /** Release each guard this run took, where the file still names this run. */
282
+ function releaseGuards(guards) {
283
+ for (const g of guards.values()) {
284
+ if (!("file" in g))
285
+ continue;
286
+ try {
287
+ const doc = JSON.parse(readFileSync(g.file, "utf8"));
288
+ if (doc.pid === process.pid && doc.holder === "cleanup")
289
+ rmSync(g.file, { force: true });
290
+ }
291
+ catch {
292
+ // Gone already, or no longer this run's.
293
+ }
294
+ }
295
+ }
296
+ /** The signals that stop a run between removals, with their numbers for the exit status. */
297
+ const STOPS = { SIGHUP: 1, SIGINT: 2, SIGTERM: 15 };
298
+ /** The diagnoses this run removes: of class cleanup, of a known state, in a group it names and in
299
+ * no repository an isolated run holds. A worktree carries the pass its ledger names and a branch
300
+ * its tip, both read when the plan is made, and a locks diagnosis is one removal a file. */
301
+ function planOf(diagnoses, groups, held, env) {
302
+ let home;
303
+ return ALL.filter((g) => groups.has(g)).flatMap((group) => diagnoses
304
+ .filter((d) => d.id === GROUPS[group] && d.fix === "cleanup" && !d.unknown && !held.has(d.repository ?? ""))
305
+ .flatMap((d) => {
306
+ const removal = { group, subject: d.subject, bytes: d.bytes ?? 0, ...(d.repository ? { repository: d.repository } : {}) };
307
+ switch (group) {
308
+ case "worktrees":
309
+ home ??= findHome(env);
310
+ return [{ ...removal, pass: passOf(d.subject, home, env) }];
311
+ case "locks":
312
+ return lockFiles(d).map(({ issue, file }) => ({ ...removal, subject: file, issue, bytes: sizeOf(file) }));
313
+ case "branches": {
314
+ const tip = tipOf(d);
315
+ return [{ ...removal, ...(tip ? { tip } : {}) }];
316
+ }
317
+ default:
318
+ return [removal];
319
+ }
320
+ }));
321
+ }
322
+ /** What the plan says of a removal after its size: its path or name, and for a worktree what its
323
+ * closeout does. */
324
+ function planned(r) {
325
+ if (r.pass)
326
+ return `${r.subject}: kryso pass ${r.pass.issue} --resume closes #${r.pass.issue} and deletes ${r.pass.branch ?? "its branch"} on origin`;
327
+ if (r.issue)
328
+ return `${r.subject}, for the closed issue #${r.issue}`;
329
+ if (r.group === "branches")
330
+ return `${r.subject} at ${r.tip?.slice(0, 7) ?? "a tip that could not be read"}`;
331
+ return r.subject;
332
+ }
333
+ const removals = (n) => `${n} removal${n === 1 ? "" : "s"}`;
334
+ /** The plan in its sections: the machine's removals, then under --all each repository's under its
335
+ * path, as kryso doctor --all lists them. Without --all it is one section. */
336
+ function sections(plan, mains, all) {
337
+ if (!all)
338
+ return [{ removals: plan }];
339
+ const named = [...mains, ...plan.map((r) => r.repository).filter((r) => r !== undefined && !mains.includes(r))];
340
+ return [undefined, ...new Set(named)].map((repository) => ({ repository, removals: plan.filter((r) => r.repository === repository) })).filter((s) => s.removals.length > 0);
341
+ }
342
+ /** The plan: one line a removal, its group, its size and its path, then the total. */
343
+ function show(plan, mains, all) {
344
+ const total = `${removals(plan.length)}, ${size(plan.reduce((sum, r) => sum + r.bytes, 0))} in all`;
345
+ const gw = Math.max(...plan.map((r) => r.group.length));
346
+ const sw = Math.max(...plan.map((r) => size(r.bytes).length));
347
+ const parts = sections(plan, mains, all);
348
+ say({
349
+ text: [
350
+ ...parts.flatMap(({ repository, removals: these }) => [
351
+ ...(repository === undefined ? [] : [`in ${repository}:`]),
352
+ ...these.map((r) => `${r.group.padEnd(gw)} ${size(r.bytes).padStart(sw)} ${planned(r)}`),
353
+ ]),
354
+ total,
355
+ "",
356
+ ].join("\n"),
357
+ draw: (s) => {
358
+ s.brand("cleanup", "the plan");
359
+ for (const { repository, removals: section } of parts) {
360
+ if (repository !== undefined) {
361
+ s.write("\n");
362
+ s.pill("secondary", repository);
363
+ }
364
+ for (const group of ALL) {
365
+ const these = section.filter((r) => r.group === group);
366
+ if (these.length === 0)
367
+ continue;
368
+ s.write("\n");
369
+ s.pill("primary", group.toUpperCase());
370
+ for (const r of these)
371
+ s.info(`${s.val(size(r.bytes).padStart(sw))} ${planned(r)}`);
372
+ }
373
+ }
374
+ s.write("\n");
375
+ s.info(total);
376
+ },
377
+ }, stdout);
378
+ }
379
+ /** A line of kryso cleanup's own, plain after its name or drawn after its mark. */
380
+ const tell = (line, mark) => say({ text: `${NAME}: ${line}\n`, draw: (s) => s[mark](line) }, stdout);
381
+ /** What the plan left out and why: each repository an isolated run holds, then each diagnosis of
382
+ * a named group whose state is unknown, in its own words, which give its count. */
383
+ function notes({ held, left, kept }, all) {
384
+ for (const [repo, why] of held)
385
+ tell(`planned nothing in ${repo}, because ${why}`, "info");
386
+ for (const d of left)
387
+ tell(`left out${all && d.repository ? ` in ${d.repository}` : ""}, because its state is unknown: ${d.text}`, "info");
388
+ for (const d of kept)
389
+ tell(`kept${all && d.repository ? ` in ${d.repository}` : ""}: ${d.text}`, "info");
390
+ }
391
+ /** One line read from stdin, which a terminal hands over when the person presses return. */
392
+ function answer() {
393
+ const buf = Buffer.alloc(256);
394
+ let text = "";
395
+ for (;;) {
396
+ let n = 0;
397
+ try {
398
+ n = readSync(0, buf, 0, buf.length, null);
399
+ }
400
+ catch (err) {
401
+ if (err.code === "EAGAIN")
402
+ continue;
403
+ throw err;
404
+ }
405
+ if (n === 0)
406
+ return text;
407
+ text += buf.toString("utf8", 0, n);
408
+ if (text.includes("\n"))
409
+ return text.slice(0, text.indexOf("\n"));
410
+ }
411
+ }
412
+ /** The answer to a question is yes. */
413
+ const yes = (typed) => /^\s*y(es)?\s*$/i.test(typed);
414
+ async function cleanup(argv, env) {
415
+ const opts = parse(argv);
416
+ if ("text" in opts) {
417
+ give(opts, env, stdout, stderr);
418
+ return opts.status;
419
+ }
420
+ if (opts.evidence) {
421
+ // Evidence goes only where a remote archive holds it, so a machine with none has no way to remove it.
422
+ const keep = keepOf(env, opts.config);
423
+ const why = "why" in keep
424
+ ? `--evidence needs the keep configuration, named with --config or by the keep launch agent, and ${keep.why}`
425
+ : keep.remote
426
+ ? undefined
427
+ : `--evidence needs a remote archive, and the keep configuration ${keep.file} names none`;
428
+ if (why) {
429
+ give(refusal(EX_USAGE, NAME, `${why}, so nothing was removed`), env, stdout, stderr);
430
+ return EX_USAGE;
431
+ }
432
+ }
433
+ const first = read(opts, env);
434
+ const { plan } = first;
435
+ if (plan.length === 0) {
436
+ say({ text: "", draw: (s) => s.brand("cleanup") }, stdout);
437
+ notes(first, opts.all);
438
+ tell("nothing to remove", "ok");
439
+ return 0;
440
+ }
441
+ show(plan, first.mains, opts.all);
442
+ notes(first, opts.all);
443
+ if (opts.dryRun) {
444
+ tell("a dry run, so nothing was removed", "info");
445
+ return 0;
446
+ }
447
+ const terminal = isatty(0) && isatty(1);
448
+ const evidence = plan.filter((r) => r.group === "evidence");
449
+ if (!terminal && (!opts.force || evidence.length > 0)) {
450
+ const line = evidence.length > 0
451
+ ? refusal(EX_USAGE, NAME, "there is no terminal to ask the evidence question on, and --force does not answer it, so nothing was removed", {
452
+ hint: "run it at a terminal, or without --evidence",
453
+ })
454
+ : refusal(EX_USAGE, NAME, "there is no terminal to ask on, so nothing was removed", {
455
+ hint: "run it at a terminal, or with --force to remove the plan without asking",
456
+ });
457
+ give(line, env, stdout, stderr);
458
+ return EX_USAGE;
459
+ }
460
+ // The plan's question, which --force answers, then the evidence's, which only a person does.
461
+ const rest = plan.filter((r) => r.group !== "evidence");
462
+ let chosen = plan;
463
+ let asked = false;
464
+ if (!opts.force && rest.length > 0) {
465
+ stdout.write(`Remove ${evidence.length === 0 ? (rest.length === 1 ? "it" : `these ${rest.length}`) : `the ${rest.length} that ${rest.length === 1 ? "is" : "are"} not evidence`}? [y/N] `);
466
+ asked = true;
467
+ if (!yes(answer()))
468
+ chosen = evidence;
469
+ }
470
+ if (evidence.length > 0) {
471
+ const one = evidence.length === 1;
472
+ stdout.write(`Remove the ${evidence.length} evidence ${one ? "copy" : "copies"} too? The remote archive holds ${one ? "it" : "them"}, and this machine will not. [y/N] `);
473
+ asked = true;
474
+ if (!yes(answer()))
475
+ chosen = chosen.filter((r) => r.group !== "evidence");
476
+ }
477
+ if (chosen.length === 0) {
478
+ tell("nothing was removed", "info");
479
+ return 0;
480
+ }
481
+ // A signal waits for the removal it arrives in, then stops the run, so the guard is released.
482
+ let stop;
483
+ const stopping = Object.keys(STOPS).map((sig) => [sig, () => (stop ??= sig)]);
484
+ for (const [sig, on] of stopping)
485
+ process.on(sig, on);
486
+ const guards = new Map();
487
+ try {
488
+ takeGuards([...new Set(chosen.flatMap((r) => (r.repository ? [r.repository] : [])))], env, guards);
489
+ // A person can take any time to answer, so what is removed is what is still cleanup's once they have.
490
+ const still = new Set((asked ? read(opts, env).plan : plan).map(keyOf));
491
+ let freed = 0;
492
+ let failed = 0;
493
+ let ran = 0;
494
+ for (const r of chosen) {
495
+ // A turn of the event loop, where a signal that came during the last removal is heard.
496
+ await new Promise((resolve) => setImmediate(resolve));
497
+ if (stop) {
498
+ tell(`stopped on ${stop} after ${ran} of ${removals(chosen.length)}, so ${chosen.length - ran} did not run`, "fail");
499
+ return 128 + STOPS[stop];
500
+ }
501
+ ran++;
502
+ const guard = r.repository ? guards.get(r.repository) : undefined;
503
+ if (guard && "why" in guard) {
504
+ failed++;
505
+ tell(`could not remove ${r.subject}: ${guard.why}`, "fail");
506
+ continue;
507
+ }
508
+ if (!still.has(keyOf(r))) {
509
+ failed++;
510
+ tell(`could not remove ${r.subject}: kryso doctor no longer names it as cleanup's, so it stays`, "fail");
511
+ continue;
512
+ }
513
+ if (REMOVE[r.group](r, env))
514
+ freed += r.bytes;
515
+ else
516
+ failed++;
517
+ }
518
+ const done = `removed ${chosen.length - failed} of ${chosen.length}, ${size(freed)}${failed > 0 ? `, and ${failed} failed` : ""}`;
519
+ tell(done, failed > 0 ? "fail" : "ok");
520
+ return failed > 0 ? 1 : 0;
521
+ }
522
+ finally {
523
+ releaseGuards(guards);
524
+ for (const [sig, on] of stopping)
525
+ process.off(sig, on);
526
+ }
527
+ }
528
+ /** A backup or a retired copy, removed from the disk. */
529
+ function remove(r) {
530
+ try {
531
+ rmSync(r.subject, { recursive: true });
532
+ tell(`removed ${r.subject}`, "ok");
533
+ return true;
534
+ }
535
+ catch (err) {
536
+ const why = err instanceof Error ? err.message : String(err);
537
+ tell(`could not remove ${r.subject}: ${why}`, "fail");
538
+ return false;
539
+ }
540
+ }
541
+ /** A pass lock file, removed by the ledger module's drop, which holds the file's lock while it
542
+ * removes it and refuses while a live pass holds it. */
543
+ function drop(r, env) {
544
+ const module = ledgerModule(env);
545
+ const run = module ? capture("bash", [module, "drop", r.repository, r.issue], env, r.repository) : undefined;
546
+ if (run?.ok) {
547
+ tell(`removed ${r.subject}`, "ok");
548
+ return true;
549
+ }
550
+ tell(`could not remove ${r.subject}: ${run ? failure(run) : "kryso cannot find its ledger module"}`, "fail");
551
+ return false;
552
+ }
553
+ /** A merged branch, deleted at the tip the plan showed: a commit made on it since, or a worktree
554
+ * that checked it out since, keeps it. Its settings go with it, as git branch -D takes them. */
555
+ function deleteBranch(r, env) {
556
+ const git = (args) => capture("git", args, env, r.repository);
557
+ const kept = (why) => {
558
+ tell(`could not delete the branch ${r.subject} in ${r.repository}: ${why}`, "fail");
559
+ return false;
560
+ };
561
+ if (!r.tip)
562
+ return kept("doctor named no tip it judged it merged at");
563
+ if (git(["worktree", "list", "--porcelain"]).out.split("\n").includes(`branch refs/heads/${r.subject}`))
564
+ return kept("a worktree has it checked out now");
565
+ const deleted = git(["update-ref", "-d", `refs/heads/${r.subject}`, r.tip]);
566
+ if (!deleted.ok)
567
+ return kept(failure(deleted));
568
+ git(["config", "--remove-section", `branch.${r.subject}`]);
569
+ tell(`deleted the branch ${r.subject} at ${r.tip.slice(0, 7)}`, "ok");
570
+ return true;
571
+ }
572
+ /** How each group removes what it planned, true when it did. */
573
+ const REMOVE = {
574
+ worktrees: closeOut,
575
+ locks: drop,
576
+ branches: deleteBranch,
577
+ backups: remove,
578
+ skills: remove,
579
+ evidence: remove,
580
+ };
581
+ /** A merged pass's worktree, closed out by the pass's own resume in its repository, and one line
582
+ * for how it ended. True when the pass shipped with its closeout complete. */
583
+ function closeOut(r, env) {
584
+ if (!r.pass) {
585
+ tell(`could not close out ${r.subject}: the ledger module could not read the issue its ledger names`, "fail");
586
+ return false;
587
+ }
588
+ const { issue } = r.pass;
589
+ const resume = `kryso pass ${issue} --resume`;
590
+ // The pass's progress goes to the person's stderr, and its stdout is the block alone.
591
+ const run = spawnSync(path.join(packageRoot(), "bin", "kryso"), ["pass", issue, "--resume"], { cwd: r.repository, env, encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] });
592
+ let block;
593
+ try {
594
+ block = JSON.parse(run.stdout ?? "");
595
+ }
596
+ catch {
597
+ // No block, which the line below says.
598
+ }
599
+ if (!block?.outcome) {
600
+ tell(`could not close out ${r.subject}: ${resume} printed no outcome block, and exited ${run.status ?? "on a signal"}`, "fail");
601
+ return false;
602
+ }
603
+ const step = /^incomplete (.+)$/.exec(block.closeout ?? "")?.[1];
604
+ if (block.outcome === "shipped" && block.closeout === "complete") {
605
+ tell(`removed ${r.subject}: ${resume} finished its closeout`, "ok");
606
+ return true;
607
+ }
608
+ if (block.outcome === "shipped" && step) {
609
+ // The closeout stops before or after it removes the worktree, so the disk says which.
610
+ if (existsSync(r.subject))
611
+ tell(`the closeout of #${issue} stopped at its ${step} step and kept ${r.subject}, so ${resume} finishes it`, "fail");
612
+ else
613
+ tell(`the closeout of #${issue} stopped at its ${step} step after it removed ${r.subject}, so a person finishes that step by hand: ${evidenceOf(block.reason ?? "")}`, "fail");
614
+ return false;
615
+ }
616
+ tell(`could not close out ${r.subject}: ${resume} ended ${block.outcome}: ${block.reason ?? "with no reason"}`, "fail");
617
+ return false;
618
+ }
619
+ /** Where the closeout copied a worktree's evidence, as the pass's reason names it. */
620
+ function evidenceOf(reason) {
621
+ const copy = /The evidence is at (\S+?)\.?$/.exec(reason)?.[1];
622
+ return copy ? `the evidence is at ${copy}` : `the pass named no copy of its evidence: ${reason}`;
623
+ }
624
+ cleanup(process.argv.slice(2), process.env).then((status) => {
625
+ process.exitCode = status;
626
+ }, (err) => {
627
+ process.stderr.write(`${NAME}: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}\n`);
628
+ process.exitCode = EX_SOFTWARE;
629
+ });
@@ -0,0 +1,48 @@
1
+ import { type Answer } from "./answer.js";
2
+ export type Group = "work" | "evidence" | "setup";
3
+ /** What to start: the program and the arguments that come before the caller's own, how many of
4
+ * the caller's arguments after the subcommand's name are verbs kryso consumed, and the script,
5
+ * for error messages. bin/kryso appends the caller's remaining arguments itself. */
6
+ export interface Target {
7
+ program: string;
8
+ head: string[];
9
+ verbs: number;
10
+ script: string;
11
+ }
12
+ export type { Answer } from "./answer.js";
13
+ export declare const isAnswer: (t: Target | Answer) => t is Answer;
14
+ /** A subcommand's target among the drivers at home, when it can start: kryso resolves it and every
15
+ * file it names is there. A driver that is missing is the install group's error in kryso doctor. */
16
+ export declare function startable(home: string, name: string, args: string[], env: NodeJS.ProcessEnv): Target | undefined;
17
+ export declare function version(): string;
18
+ export interface Command {
19
+ name: string;
20
+ group: Group;
21
+ summary: string;
22
+ /** The scripts it runs, as `kryso --help` names them. */
23
+ runs: string;
24
+ /** The target for the caller's arguments after the subcommand's name. */
25
+ target(home: string, args: string[], env: NodeJS.ProcessEnv): Target | Answer;
26
+ /** Whether it reads through the daemon's API instead of running its script while a remote
27
+ * is set (`kryso remote`). */
28
+ reads?: boolean;
29
+ /** Whether `--isolate` first among the arguments, or the repository's config, can run it in
30
+ * the kryso-runner container (ADR 0051). */
31
+ isolates?: boolean;
32
+ /** Whether it runs without the drivers, so kryso runs it even when they are missing. Its
33
+ * target gets an empty home. */
34
+ withoutDrivers?: boolean;
35
+ /** Verbs kryso handles before the driver, which the driver's help does not name. Shell
36
+ * completion offers them with the help's own. */
37
+ verbs?: readonly string[];
38
+ /** The argument lists kryso doctor resolves this command's target for, to check that each can
39
+ * start: one per verb that runs a script of its own. None for a command that runs kryso itself
40
+ * and reads no file. Unset is one list, the empty one. */
41
+ checks?: readonly (readonly string[])[];
42
+ /** Whether each verb has a help of its own, `kryso <command> <verb> --help`, that completion
43
+ * may run to find the verb's options. Only a driver whose verb help runs nothing else sets it. */
44
+ verbHelp?: boolean;
45
+ }
46
+ export declare const COMMANDS: readonly Command[];
47
+ export declare const find: (name: string) => Command | undefined;
48
+ export declare function help(): string;