@krysoworks/kryso 0.0.2 → 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 (163) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +146 -6
  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 +55 -22
  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
  163. package/bin/kryso.js +0 -11
@@ -0,0 +1,402 @@
1
+ // Isolation (ADR 0051, amended by ADR 0039): `kryso shift --isolate docker` and `kryso pass
2
+ // --isolate docker`, or `"isolate": "docker"` in the repository's .kryso/config.json (or
3
+ // .claude/ship-pass.json, its old place, where that is absent), run the
4
+ // same driver at the same path inside one kryso-runner container. The repository is mounted
5
+ // read-write at its host path, so worktrees and ledgers land where they land today, and the
6
+ // drivers and the installed skills are mounted read-only. A fixed allowlist of secrets and
7
+ // identity enters through an env file, never through the command line, which `ps` shows.
8
+ // Everything here runs before the launcher execs anything, so a preflight failure claims nothing.
9
+ import { spawnSync } from "node:child_process";
10
+ import { chmodSync, copyFileSync, existsSync, linkSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import { refusal } from "./answer.js";
14
+ import { EX_TEMPFAIL, EX_UNAVAILABLE, EX_USAGE } from "./env.js";
15
+ export const IMAGE = "kryso-runner";
16
+ const CONTAINER_HOME = "/home/kryso";
17
+ /** The repository's config: .kryso/config.json, else its old place until 3.0.0 (ADR 0046). The
18
+ * drivers print the warning that names the move, so this reader stays quiet. */
19
+ const CONFIG = path.join(".kryso", "config.json");
20
+ const CONFIGS = [CONFIG, path.join(".claude", "ship-pass.json")];
21
+ export const MODES = ["docker", "none"];
22
+ const HOSTS = ["claude", "codex"];
23
+ /** The file in the common git directory that says an isolated run is working the repository. */
24
+ export const PID_FILE = "kryso-isolated.json";
25
+ /** How long a pid file counts while its pid is not docker yet: the launcher is about to exec it. */
26
+ const STARTING_MS = 10_000;
27
+ /** A refusal before the container starts: the line, and after "; " the fix when there is one. */
28
+ const fail = (status, line, hint) => refusal(status, "kryso", line, { hint });
29
+ function run(program, args, caller, cwd = caller.cwd) {
30
+ const r = spawnSync(program, args, { cwd, env: caller.env, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
31
+ const missing = r.error?.code === "ENOENT";
32
+ return { ok: !r.error && r.status === 0, missing, out: (r.stdout ?? "").replace(/\n$/, "") };
33
+ }
34
+ const inside = (dir, parent) => {
35
+ const rel = path.relative(parent, dir);
36
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
37
+ };
38
+ const alive = (pid) => {
39
+ try {
40
+ process.kill(pid, 0);
41
+ return true;
42
+ }
43
+ catch (err) {
44
+ return err.code === "EPERM";
45
+ }
46
+ };
47
+ function findRepo(caller) {
48
+ const r = run("git", ["rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir"], caller);
49
+ if (!r.ok)
50
+ return undefined;
51
+ const [top, common] = r.out.split("\n");
52
+ if (!top || !common)
53
+ return undefined;
54
+ return { top, common, main: path.basename(common) === ".git" ? path.dirname(common) : top };
55
+ }
56
+ /** The repository's config at the top of its working tree, and the path it came from. */
57
+ function repoConfig(top) {
58
+ const name = CONFIGS.find((c) => existsSync(path.join(top, c))) ?? CONFIG;
59
+ return { name, config: readJson(path.join(top, name)) };
60
+ }
61
+ function readJson(file) {
62
+ try {
63
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
64
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
65
+ }
66
+ catch {
67
+ // Missing, or one its own reader refuses in its own words.
68
+ return {};
69
+ }
70
+ }
71
+ /** Whether a command line, as ps prints it, is kryso cleanup's: a word of it names cleanup.js, the
72
+ * script bin/kryso execs, so another program with "cleanup" in its arguments is not. */
73
+ const isCleanup = (args) => args.split(/\s+/).some((w) => path.basename(w) === "cleanup.js");
74
+ /** Who holds the repository's isolation guard: the docker client of an isolated run, or kryso
75
+ * cleanup for the length of its removals (#638), whose file says "holder": "cleanup". Undefined
76
+ * when nobody does, removing a stale file, a dead cleanup's as a dead client's. The same reading
77
+ * as ledger.sh's `isolated`, which the host's drivers make. */
78
+ function guardHolder(file, now) {
79
+ if (!existsSync(file))
80
+ return undefined;
81
+ const doc = readJson(file);
82
+ const pid = doc.pid;
83
+ const holder = doc.holder === "cleanup" ? "cleanup" : "docker";
84
+ if (typeof pid === "number" && Number.isInteger(pid) && pid > 0 && alive(pid)) {
85
+ const ps = existsSync("/bin/ps") ? "/bin/ps" : "ps";
86
+ const args = spawnSync(ps, ["-o", "args=", "-p", String(pid)], { encoding: "utf8" }).stdout ?? "";
87
+ if (holder === "cleanup") {
88
+ if (isCleanup(args))
89
+ return { pid, holder };
90
+ }
91
+ else {
92
+ let mtime = 0;
93
+ try {
94
+ mtime = statSync(file).mtimeMs;
95
+ }
96
+ catch {
97
+ // Removed meanwhile.
98
+ }
99
+ if (path.basename(args.trim().split(/\s+/)[0] ?? "") === "docker" || now - mtime < STARTING_MS)
100
+ return { pid, holder };
101
+ }
102
+ }
103
+ rmSync(file, { force: true });
104
+ return undefined;
105
+ }
106
+ /** The refusal for a repository whose guard someone holds. */
107
+ function guardRefusal(by, main) {
108
+ const line = by.holder === "cleanup" ? `kryso cleanup (pid ${by.pid}) holds ${main} while it removes there` : `an isolated kryso run (docker pid ${by.pid}) is already working ${main}`;
109
+ return fail(EX_TEMPFAIL, line, "wait for it to end, or stop it");
110
+ }
111
+ /** The most processes a container may run when KRYSO_PROCESSES names none, so a pass that forks
112
+ * without end stops there and not at the machine's limit (#451). It is runner.sh's default for a
113
+ * context on the host, before that one is capped at half the user's hard limit. Here it counts the
114
+ * container's processes alone, where the host's counts every process of the user. */
115
+ const PROCESSES_DEFAULT = 2048;
116
+ /** The container's --pids-limit: KRYSO_PROCESSES when it is a whole number of at least 64, as
117
+ * runner.sh reads it, else the default. */
118
+ function processesOf(env) {
119
+ const given = env.KRYSO_PROCESSES ?? "";
120
+ return /^[0-9]+$/.test(given) && Number(given) >= 64 ? Number(given) : PROCESSES_DEFAULT;
121
+ }
122
+ /** The profile among the caller's arguments, `--profile <name>` as the drivers read it, the last
123
+ * one winning, and its host, resolved the way runner.sh resolves it. */
124
+ function profileOf(args, env) {
125
+ let name = "claude";
126
+ for (let i = 0; i + 1 < args.length; i++)
127
+ if (args[i] === "--profile")
128
+ name = args[++i];
129
+ const variable = ["KRYSO_PROFILE_FILE", "SHIP_LOOP_PROFILE_FILE"].find((v) => env[v]);
130
+ const file = variable && existsSync(env[variable]) ? [variable, path.resolve(env[variable])] : undefined;
131
+ if (HOSTS.includes(name))
132
+ return { name, host: name, file };
133
+ if (!file) {
134
+ return fail(EX_USAGE, `profile '${name}' is not claude or codex, and no profile file (KRYSO_PROFILE_FILE) names its host`);
135
+ }
136
+ const profiles = readJson(file[1]).profiles;
137
+ const host = profiles?.[name]?.host;
138
+ if (typeof host !== "string" || !HOSTS.includes(host))
139
+ return fail(EX_USAGE, `profile '${name}' has no claude or codex host in ${file[1]}`);
140
+ return { name, host, file };
141
+ }
142
+ /** One field of a --mount value, quoted the way docker's CSV reader reads it back. */
143
+ const csv = (field) => (/[",\n]/.test(field) ? `"${field.replaceAll('"', '""')}"` : field);
144
+ const mount = (source, target, readonly = false) => [
145
+ "--mount",
146
+ ["type=bind", `source=${source}`, `target=${target}`, ...(readonly ? ["readonly"] : [])].map(csv).join(","),
147
+ ];
148
+ /** A per-run directory under ~/.config/kryso/run, named for the docker client's pid, after
149
+ * removing every one whose pid no longer runs, whatever its age. */
150
+ function runDir(userHome, sub, caller) {
151
+ const root = path.join(userHome, ".config", "kryso", "run");
152
+ mkdirSync(root, { recursive: true, mode: 0o700 });
153
+ for (const name of readdirSync(root)) {
154
+ const pid = /^[a-z]+-(\d+)-/.exec(name)?.[1];
155
+ if (pid && !alive(Number(pid)))
156
+ rmSync(path.join(root, name), { recursive: true, force: true });
157
+ }
158
+ const dir = mkdtempSync(path.join(root, `${sub}-${caller.pid}-`));
159
+ chmodSync(dir, 0o700);
160
+ return dir;
161
+ }
162
+ function permissions(userHome) {
163
+ const p = readJson(path.join(userHome, ".claude", "settings.json")).permissions;
164
+ return p && typeof p === "object" && !Array.isArray(p) ? JSON.stringify(p) : "{}";
165
+ }
166
+ /** The container's /etc/passwd and /etc/group: root, nobody, and the caller as kryso. They are
167
+ * mounted read-only, so the image needs no writable /etc/passwd for an unknown uid. */
168
+ function accounts(dir, caller) {
169
+ const passwd = path.join(dir, "passwd");
170
+ const group = path.join(dir, "group");
171
+ writeFileSync(passwd, ["root:x:0:0:root:/root:/bin/sh", "nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin",
172
+ ...(caller.uid > 0 && caller.uid !== 65534 ? [`kryso:x:${caller.uid}:${caller.gid}:kryso:${CONTAINER_HOME}:/bin/bash`] : [])].join("\n") + "\n", { mode: 0o644 });
173
+ writeFileSync(group, ["root:x:0:", "nogroup:x:65534:", ...(caller.gid > 0 && caller.gid !== 65534 ? [`kryso:x:${caller.gid}:`] : [])].join("\n") + "\n", {
174
+ mode: 0o644,
175
+ });
176
+ return { passwd, group };
177
+ }
178
+ /**
179
+ * The target to run for `kryso <sub> [args...]`. Without `--isolate` first in args and without
180
+ * the config key, it is the given target unchanged. With `--isolate none` it is the same target
181
+ * with the flag consumed. With docker it is a `docker run` of the same driver, after a preflight
182
+ * whose every failure is an answer.
183
+ */
184
+ export function isolate(sub, target, args, caller) {
185
+ let mode;
186
+ let consumed = 0;
187
+ const first = args[0];
188
+ if (first === "--isolate") {
189
+ if (args.length < 2)
190
+ return fail(EX_USAGE, `${sub}: --isolate takes docker or none`);
191
+ mode = args[1];
192
+ consumed = 2;
193
+ }
194
+ else if (first?.startsWith("--isolate=")) {
195
+ mode = first.slice("--isolate=".length);
196
+ consumed = 1;
197
+ }
198
+ let repo;
199
+ if (mode === undefined) {
200
+ repo = findRepo(caller);
201
+ if (!repo)
202
+ return target;
203
+ const { name, config } = repoConfig(repo.top);
204
+ const key = config.isolate;
205
+ if (key === undefined)
206
+ return target;
207
+ if (typeof key !== "string" || !MODES.includes(key)) {
208
+ return fail(EX_USAGE, `${name}: isolate must be docker or none, got ${JSON.stringify(key)}`);
209
+ }
210
+ mode = key;
211
+ }
212
+ else if (!MODES.includes(mode)) {
213
+ return fail(EX_USAGE, `${sub}: --isolate takes docker or none, got '${mode}'`);
214
+ }
215
+ const rest = args.slice(consumed);
216
+ const consuming = { ...target, verbs: target.verbs + consumed };
217
+ // A driver's help needs no fence, and asking for it should not need Docker running. Nor does a
218
+ // read-only dry run, which starts nothing and must write nothing: the fence's setup writes a pid
219
+ // file and credentials, and its probe removes a stale pid file that kryso doctor reports.
220
+ const readOnly = rest.includes("--dry-run") && rest.includes("--read-only");
221
+ if (mode === "none" || rest[0] === "-h" || rest[0] === "--help" || readOnly)
222
+ return consuming;
223
+ repo ??= findRepo(caller);
224
+ if (!repo)
225
+ return fail(EX_USAGE, `${sub} --isolate docker runs only inside a git repository`);
226
+ const { config } = repoConfig(repo.top);
227
+ const gate = config.gate && typeof config.gate === "object" ? Object.values(config.gate) : [];
228
+ if ([config.install, ...gate].some((c) => typeof c === "string" && /\bxcodebuild\b/.test(c))) {
229
+ return fail(EX_USAGE, `${repo.top}'s gate runs xcodebuild, which runs on the host, so it cannot run with --isolate docker`);
230
+ }
231
+ const profile = profileOf(rest, caller.env);
232
+ if ("text" in profile)
233
+ return profile;
234
+ const pidFile = path.join(repo.common, PID_FILE);
235
+ const holding = guardHolder(pidFile, caller.now);
236
+ if (holding)
237
+ return guardRefusal(holding, repo.main);
238
+ const image = `${IMAGE}:${caller.version}`;
239
+ const info = run("docker", ["info"], caller);
240
+ if (info.missing)
241
+ return fail(EX_UNAVAILABLE, "--isolate docker needs docker, and docker is not on PATH");
242
+ if (!info.ok)
243
+ return fail(EX_UNAVAILABLE, "docker info cannot reach the Docker daemon", "start Docker and run this again");
244
+ if (!run("docker", ["image", "inspect", image], caller).ok) {
245
+ return fail(EX_UNAVAILABLE, `no ${image} image`, `build it with kryso isolate build`);
246
+ }
247
+ const userHome = caller.env.HOME || os.homedir();
248
+ const codex = profile.host === "codex";
249
+ let claudeToken = "";
250
+ const codexAuth = path.join(userHome, ".codex", "auth.json");
251
+ if (codex) {
252
+ if (!existsSync(codexAuth))
253
+ return fail(EX_UNAVAILABLE, `profile ${profile.name} needs a Codex login at ${codexAuth}`, `run codex login first`);
254
+ }
255
+ else {
256
+ const file = path.join(userHome, ".config", "kryso", "claude-token");
257
+ try {
258
+ claudeToken = readFileSync(file, "utf8").trim();
259
+ }
260
+ catch {
261
+ // Reported below.
262
+ }
263
+ if (!claudeToken)
264
+ return fail(EX_UNAVAILABLE, `profile ${profile.name} needs a Claude token in ${file}`, `make one with claude setup-token and save it there`);
265
+ }
266
+ const skills = path.join(userHome, ".agents", "skills");
267
+ if (!existsSync(skills))
268
+ return fail(EX_UNAVAILABLE, `no installed skills at ${skills}`, `run kryso skills install first`);
269
+ const gh = run("gh", ["auth", "token"], caller, repo.top);
270
+ if (!gh.ok || !gh.out.trim())
271
+ return fail(EX_UNAVAILABLE, "gh auth token failed, so the container would have no GitHub token", "run gh auth login first");
272
+ const identity = {};
273
+ for (const key of ["name", "email"]) {
274
+ const value = run("git", ["config", `user.${key}`], caller, repo.top).out.trim();
275
+ if (!value)
276
+ return fail(EX_UNAVAILABLE, `git has no user.${key} in ${repo.top}`, `set it with git config user.${key}`);
277
+ identity[key] = value;
278
+ }
279
+ // The run directory holds secrets/, the one part the container may write, so the entrypoint
280
+ // can delete what it read, and the account files beside it, which it may only read.
281
+ const dir = runDir(userHome, sub, caller);
282
+ const secrets = path.join(dir, "secrets");
283
+ mkdirSync(secrets, { mode: 0o700 });
284
+ const envFile = path.join(secrets, "env");
285
+ const vars = [
286
+ ["KRYSO_ENV_FILE", envFile],
287
+ ["KRYSO_REPO", repo.main],
288
+ ["KRYSO_CLAUDE_PERMISSIONS", permissions(userHome)],
289
+ ["GH_TOKEN", gh.out.trim()],
290
+ ["GIT_AUTHOR_NAME", identity.name],
291
+ ["GIT_AUTHOR_EMAIL", identity.email],
292
+ ["GIT_COMMITTER_NAME", identity.name],
293
+ ["GIT_COMMITTER_EMAIL", identity.email],
294
+ ...(codex ? [] : [["CLAUDE_CODE_OAUTH_TOKEN", claudeToken]]),
295
+ ];
296
+ // docker reads an env file a line at a time, with no quoting, so a value cannot hold a line break.
297
+ const broken = vars.find(([, v]) => /[\r\n]/.test(v));
298
+ if (broken) {
299
+ rmSync(dir, { recursive: true, force: true });
300
+ return fail(EX_UNAVAILABLE, `${broken[0]} holds a line break, which docker's env file cannot carry`);
301
+ }
302
+ writeFileSync(envFile, vars.map(([k, v]) => `${k}=${v}\n`).join(""), { mode: 0o600, flag: "wx" });
303
+ chmodSync(envFile, 0o600);
304
+ // Names, paths and switches, none of them secret, so they go on the command line.
305
+ const plain = [`HOME=${CONTAINER_HOME}`, "KRYSO_ISOLATED=1"];
306
+ if (codex) {
307
+ const copy = path.join(secrets, "codex-auth.json");
308
+ copyFileSync(codexAuth, copy);
309
+ chmodSync(copy, 0o600);
310
+ plain.push(`KRYSO_CODEX_AUTH=${copy}`);
311
+ }
312
+ if (profile.file)
313
+ plain.push(`${profile.file[0]}=${profile.file[1]}`);
314
+ // The MCP servers a pass keeps, which the drivers read over git config. --mcp travels in the
315
+ // arguments and the config in the mounted repository, so only this one needs carrying.
316
+ if (caller.env.KRYSO_PASS_MCP)
317
+ plain.push(`KRYSO_PASS_MCP=${caller.env.KRYSO_PASS_MCP}`);
318
+ // The runner inside sets the same number as each context's process limit.
319
+ if (caller.env.KRYSO_PROCESSES)
320
+ plain.push(`KRYSO_PROCESSES=${caller.env.KRYSO_PROCESSES}`);
321
+ const { passwd, group } = accounts(dir, caller);
322
+ const mounts = [];
323
+ const targets = new Set();
324
+ const add = (source, dest, readonly = false) => {
325
+ if (targets.has(dest))
326
+ return;
327
+ targets.add(dest);
328
+ mounts.push(...mount(source, dest, readonly));
329
+ };
330
+ // A worktree under the main working tree is covered by its mount. One elsewhere gets its own.
331
+ add(repo.main, repo.main);
332
+ if (!inside(repo.top, repo.main))
333
+ add(repo.top, repo.top);
334
+ // The drivers read-only, unless they sit inside the repository, which is already mounted.
335
+ const drivers = path.join(caller.home, "skills");
336
+ if (![...targets].some((t) => inside(drivers, t)))
337
+ add(drivers, drivers, true);
338
+ add(skills, `${CONTAINER_HOME}/.agents/skills`, true);
339
+ add(skills, `${CONTAINER_HOME}/.claude/skills`, true);
340
+ if (profile.file)
341
+ add(profile.file[1], profile.file[1], true);
342
+ add(secrets, secrets);
343
+ add(passwd, "/etc/passwd", true);
344
+ add(group, "/etc/group", true);
345
+ const name = `kryso-${sub}-${caller.pid}`;
346
+ // Last, once nothing else can refuse: the host's drivers read this file to keep off the
347
+ // repository while the docker client at this pid runs (ADR 0039). Written whole, then linked into place,
348
+ // which fails where a file is already there: a guard kryso cleanup or another run took since
349
+ // the check above is read again, and refuses this run, or is stale and gives way.
350
+ const tmp = `${pidFile}.${caller.pid}.tmp`;
351
+ writeFileSync(tmp, `${JSON.stringify({ pid: caller.pid, holder: "docker", subcommand: sub, container: name, started: new Date(caller.now).toISOString() })}\n`);
352
+ try {
353
+ for (let i = 0;; i++) {
354
+ try {
355
+ linkSync(tmp, pidFile);
356
+ break;
357
+ }
358
+ catch (err) {
359
+ if (err.code !== "EEXIST" || i === 2)
360
+ throw err;
361
+ }
362
+ const taken = guardHolder(pidFile, caller.now);
363
+ if (taken) {
364
+ // Nothing starts, so the secrets written for it go now.
365
+ rmSync(dir, { recursive: true, force: true });
366
+ return guardRefusal(taken, repo.main);
367
+ }
368
+ }
369
+ }
370
+ finally {
371
+ rmSync(tmp, { force: true });
372
+ }
373
+ return {
374
+ program: "docker",
375
+ head: [
376
+ "run",
377
+ "--rm",
378
+ "--init",
379
+ "-i",
380
+ ...(caller.tty ? ["-t"] : []),
381
+ "--name",
382
+ name,
383
+ "--user",
384
+ `${caller.uid}:${caller.gid}`,
385
+ "--security-opt",
386
+ "no-new-privileges",
387
+ "--pids-limit",
388
+ String(processesOf(caller.env)),
389
+ "--workdir",
390
+ caller.cwd,
391
+ ...plain.flatMap((v) => ["--env", v]),
392
+ "--env-file",
393
+ envFile,
394
+ ...mounts,
395
+ image,
396
+ target.program,
397
+ ...target.head,
398
+ ],
399
+ verbs: consuming.verbs,
400
+ script: target.script,
401
+ };
402
+ }
@@ -0,0 +1,5 @@
1
+ import type { Diagnosis } from "@krysoworks/core";
2
+ /** How many dated backups kryso cleanup keeps when the run names no other number. */
3
+ export declare const KEEP_BACKUPS = 5;
4
+ /** The diagnoses for the leftovers, with drivers the directory the drivers are in, when found. */
5
+ export declare function leftovers(drivers: string | undefined, keep: number, env: NodeJS.ProcessEnv): Diagnosis[];
@@ -0,0 +1,156 @@
1
+ // What diagnose.ts reads of the installer's leftovers in the home directory: the dated skill
2
+ // backups past the newest few, and the skill copies under the names 2.0.0 retired. Both are of
3
+ // class cleanup when nothing needs them, and kryso cleanup removes those.
4
+ //
5
+ // A backup is a directory ~/.agents/skills-backup-<date>, one a day the installer replaced a
6
+ // copy. The newest are the latest dates, and five are kept unless the switch names another number.
7
+ //
8
+ // A retired copy is ~/.agents/skills/<old name>, which the installer leaves when the new name
9
+ // installs, because a launch agent or a script may still run it by path. One is cleanup's only
10
+ // when no launch agent in ~/Library/LaunchAgents names its path, no link in ~/bin or
11
+ // ~/.claude/skills points into it (the installer names such a command link as one that still runs
12
+ // the old copy), and the installer's own running-copy check finds no process on it. That check runs once for every retired copy there
13
+ // is, and names each process it finds; a process on a copy the installer would replace, and not
14
+ // on a retired one, holds nothing here. A check that cannot run leaves each copy unknown, which
15
+ // is never cleanup's. Nothing here writes.
16
+ import { spawnSync } from "node:child_process";
17
+ import { existsSync, lstatSync, readdirSync, readFileSync, readlinkSync } from "node:fs";
18
+ import os from "node:os";
19
+ import path from "node:path";
20
+ import { sizeOf } from "./bytes.js";
21
+ import { find, isAnswer } from "./commands.js";
22
+ import { EX_TEMPFAIL } from "./env.js";
23
+ /** How many dated backups kryso cleanup keeps when the run names no other number. */
24
+ export const KEEP_BACKUPS = 5;
25
+ /** The skills 2.0.0 renamed, old name first: kryso.retired in this package's package.json, which
26
+ * the installer reads too, so a rename is one edit. The package.json sits beside dist/ in every
27
+ * install, so doctor reads the list even when the drivers and the installer are missing. */
28
+ const retiredNames = () => {
29
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
30
+ return Object.entries(pkg.kryso?.retired ?? {});
31
+ };
32
+ const BACKUP = /^skills-backup-\d{4}-\d{2}-\d{2}$/;
33
+ /** The diagnoses for the leftovers, with drivers the directory the drivers are in, when found. */
34
+ export function leftovers(drivers, keep, env) {
35
+ const user = env.HOME || os.homedir();
36
+ const agents = path.join(user, ".agents");
37
+ return [...backups(agents, keep), ...retired(user, agents, drivers, env)];
38
+ }
39
+ function backups(agents, keep) {
40
+ if (!existsSync(agents))
41
+ return [];
42
+ const dated = readdirSync(agents)
43
+ .filter((name) => BACKUP.test(name) && lstatSync(path.join(agents, name)).isDirectory())
44
+ .sort()
45
+ .reverse();
46
+ return dated.slice(keep).reverse().map((name) => {
47
+ const at = path.join(agents, name);
48
+ return {
49
+ id: "install.old-backup",
50
+ group: "install",
51
+ severity: "info",
52
+ fix: "cleanup",
53
+ subject: at,
54
+ bytes: sizeOf(at),
55
+ text: `${at} is a skill backup older than the newest ${keep}, so kryso cleanup removes it`,
56
+ };
57
+ });
58
+ }
59
+ /** Whether text names the path as a whole: what follows it cannot continue its last name. */
60
+ const namesPath = (text, at) => {
61
+ for (let i = text.indexOf(at); i >= 0; i = text.indexOf(at, i + 1)) {
62
+ if (!/[\w.~-]/.test(text.charAt(i + at.length)))
63
+ return true;
64
+ }
65
+ return false;
66
+ };
67
+ const entries = (dir) => {
68
+ try {
69
+ return readdirSync(dir).sort().map((name) => path.join(dir, name));
70
+ }
71
+ catch {
72
+ return [];
73
+ }
74
+ };
75
+ /** What names the copy at, as a person reads it: a launch agent whose file names its path in any
76
+ * form a shell or launchd would read, or a link in ~/bin or ~/.claude/skills that points into it. */
77
+ function namedBy(at, user) {
78
+ const forms = [at, ...(at.startsWith(`${user}/`) ? [`~/${path.relative(user, at)}`, `$HOME/${path.relative(user, at)}`] : [])];
79
+ for (const file of entries(path.join(user, "Library", "LaunchAgents"))) {
80
+ let text;
81
+ try {
82
+ text = readFileSync(file, "utf8");
83
+ }
84
+ catch {
85
+ continue;
86
+ }
87
+ if (forms.some((form) => namesPath(text, form)))
88
+ return `the launch agent ${file} names it`;
89
+ }
90
+ for (const link of [...entries(path.join(user, "bin")), ...entries(path.join(user, ".claude", "skills"))]) {
91
+ let to;
92
+ try {
93
+ to = path.resolve(path.dirname(link), readlinkSync(link));
94
+ }
95
+ catch {
96
+ continue;
97
+ }
98
+ if (to === at || to.startsWith(`${at}/`))
99
+ return `the link ${link} points into it`;
100
+ }
101
+ return undefined;
102
+ }
103
+ function running(copies, drivers, env) {
104
+ if (drivers === undefined)
105
+ return { why: "because the drivers are missing, and the installer's running-copy check with them" };
106
+ const target = find("skills").target(drivers, ["install"], env);
107
+ if (isAnswer(target))
108
+ return { why: `because the installer's running-copy check cannot start: ${target.line ?? target.text.trim()}` };
109
+ // The plain lines, which are the ones read below, whatever the caller's colour settings.
110
+ const quiet = { ...env, NO_COLOR: "1" };
111
+ delete quiet.CLICOLOR_FORCE;
112
+ const args = [...target.head, "--check-running", "--no-bin", ...copies.flatMap((c) => ["--also", c]), "--ignore-pid", String(process.pid)];
113
+ const r = spawnSync(target.program, args, { env: quiet, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 60_000 });
114
+ if (r.error || (r.status !== 0 && r.status !== EX_TEMPFAIL)) {
115
+ const said = `${r.stderr ?? ""}${r.stdout ?? ""}`.trim().split("\n")[0];
116
+ return { why: `because the installer's running-copy check failed${said ? `: ${said}` : r.error ? `: ${r.error.message}` : ` with exit ${r.status}`}` };
117
+ }
118
+ // It names each process as its pid, then its command line, and exits 75 when there is one. A
119
+ // process on a copy it would replace, and on no retired one, holds none of these.
120
+ const found = (r.stdout ?? "").split("\n").filter((line) => /^\s*\d+\s/.test(line)).map((line) => line.trim());
121
+ return { lines: new Map(copies.map((c) => [c, found.filter((line) => namesPath(line, c))])) };
122
+ }
123
+ const RETIRED_SKILL = { id: "install.retired-skill", group: "install", severity: "info" };
124
+ function retired(user, agents, drivers, env) {
125
+ const skills = path.join(agents, "skills");
126
+ const copies = retiredNames().map(([old, now]) => ({ old, now, at: path.join(skills, old) })).filter(({ at }) => {
127
+ try {
128
+ return lstatSync(at).isDirectory();
129
+ }
130
+ catch {
131
+ return false;
132
+ }
133
+ });
134
+ if (copies.length === 0)
135
+ return [];
136
+ const named = new Map(copies.map(({ at }) => [at, namedBy(at, user)]));
137
+ // The check runs for the copies nothing names, since one that is named stays either way.
138
+ const checked = copies.filter(({ at }) => named.get(at) === undefined).map(({ at }) => at);
139
+ const procs = checked.length > 0 ? running(checked, drivers, env) : { lines: new Map() };
140
+ return copies.map(({ old, now, at }) => {
141
+ const head = `${at} is the skill ${old}, which 2.0.0 renamed ${now}`;
142
+ const base = { ...RETIRED_SKILL, subject: at, bytes: sizeOf(at) };
143
+ const by = named.get(at);
144
+ if (by !== undefined) {
145
+ return { ...base, id: "install.retired-skill-in-use", fix: "person", text: `${head}, and ${by}, so a person points it at ${path.join(skills, now)} before anything removes it` };
146
+ }
147
+ if ("why" in procs)
148
+ return { ...base, fix: "person", unknown: true, text: `${head}, and whether a process runs it is unknown, ${procs.why}, so kryso cleanup leaves it` };
149
+ const on = procs.lines.get(at) ?? [];
150
+ if (on.length > 0) {
151
+ const pids = on.map((line) => line.split(/\s+/)[0]).join(", ");
152
+ return { ...base, id: "install.retired-skill-in-use", fix: "person", text: `${head}, and ${on.length === 1 ? "process" : "processes"} ${pids} ${on.length === 1 ? "runs" : "run"} a script from it, so kryso cleanup leaves it, and a person points whatever starts that run at ${path.join(skills, now)}` };
153
+ }
154
+ return { ...base, fix: "cleanup", text: `${head}, and no launch agent, link or process uses it, so kryso cleanup removes it` };
155
+ });
156
+ }
@@ -0,0 +1,6 @@
1
+ import type { Diagnosis } from "@krysoworks/core";
2
+ /** The tools group: the required tools, the first bash, gum and docker, and the logins. */
3
+ export declare function toolsGroup(home: string | undefined, offline: boolean, env: NodeJS.ProcessEnv): Diagnosis[];
4
+ /** The images group: each kryso-runner image built for another version than this kryso's, with
5
+ * the command that removes it. With docker missing or its daemon down there is nothing to say. */
6
+ export declare function imagesGroup(version: string, env: NodeJS.ProcessEnv): Diagnosis[];