@moo.md/hum 0.0.0-stage → 0.1.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 (150) hide show
  1. package/defaults/hum.json +321 -0
  2. package/defaults/kinds/check.json +183 -0
  3. package/defaults/kinds/docs.json +151 -0
  4. package/defaults/kinds/feature.json +202 -0
  5. package/defaults/kinds/fix.json +183 -0
  6. package/defaults/kinds/hotfix.json +164 -0
  7. package/defaults/roles/build.md +3 -0
  8. package/defaults/roles/fix.md +1 -0
  9. package/defaults/roles/plan.md +3 -0
  10. package/defaults/roles/review.md +3 -0
  11. package/evals/alignment/RESULTS.md +8 -0
  12. package/evals/alignment/cases.jsonl +128 -0
  13. package/evals/alignment/sample.jsonl +20 -0
  14. package/evals/kind/RESULTS.md +5 -0
  15. package/evals/kind/cases.jsonl +24 -0
  16. package/evals/plan-outcome/RESULTS.md +4 -0
  17. package/evals/plan-outcome/cases.jsonl +12 -0
  18. package/evals/repeat-pair/RESULTS.md +4 -0
  19. package/evals/repeat-pair/cases.jsonl +51 -0
  20. package/evals/reply-option/RESULTS.md +3 -0
  21. package/evals/reply-option/cases.jsonl +45 -0
  22. package/evals/review-verdict/RESULTS.md +4 -0
  23. package/evals/review-verdict/cases.jsonl +12 -0
  24. package/package.json +88 -4
  25. package/schema/hum.schema.json +1355 -0
  26. package/scripts/eval.ts +244 -0
  27. package/src/adapter-api.ts +134 -0
  28. package/src/adapters/admit.ts +111 -0
  29. package/src/adapters/argument.ts +11 -0
  30. package/src/adapters/claim.ts +93 -0
  31. package/src/adapters/claude-bg.ts +392 -0
  32. package/src/adapters/claude-p.ts +599 -0
  33. package/src/adapters/contract.ts +231 -0
  34. package/src/adapters/fake.ts +157 -0
  35. package/src/adapters/git.ts +156 -0
  36. package/src/adapters/github.ts +479 -0
  37. package/src/adapters/guard.ts +152 -0
  38. package/src/adapters/history.ts +215 -0
  39. package/src/adapters/item-file.ts +102 -0
  40. package/src/adapters/limit.ts +67 -0
  41. package/src/adapters/markdown.ts +365 -0
  42. package/src/adapters/marked.ts +127 -0
  43. package/src/adapters/model-call.ts +75 -0
  44. package/src/adapters/once.ts +45 -0
  45. package/src/adapters/owner-commit.ts +60 -0
  46. package/src/adapters/pull-requests.ts +253 -0
  47. package/src/adapters/registry.ts +156 -0
  48. package/src/adapters/roundup.ts +293 -0
  49. package/src/adapters/serial.ts +22 -0
  50. package/src/adapters/transcript.ts +99 -0
  51. package/src/cli/commands.ts +46 -0
  52. package/src/cli/main.ts +8 -0
  53. package/src/cli/ops.ts +224 -0
  54. package/src/cli/service.ts +156 -0
  55. package/src/cli/setup.ts +141 -0
  56. package/src/cli/shared-watch.ts +127 -0
  57. package/src/config/change.ts +54 -0
  58. package/src/config/checks.ts +217 -0
  59. package/src/config/git-ref-name.d.ts +3 -0
  60. package/src/config/hash.ts +6 -0
  61. package/src/config/json.ts +6 -0
  62. package/src/config/load.ts +88 -0
  63. package/src/config/machine.ts +20 -0
  64. package/src/config/migrate.ts +61 -0
  65. package/src/config/refusal.ts +58 -0
  66. package/src/config/schema.ts +465 -0
  67. package/src/config/settings.ts +6 -0
  68. package/src/config/state-map.ts +76 -0
  69. package/src/decide/alignment.ts +79 -0
  70. package/src/decide/answer.ts +131 -0
  71. package/src/decide/kind.ts +39 -0
  72. package/src/decide/labels.ts +137 -0
  73. package/src/decide/merge.ts +102 -0
  74. package/src/decide/prose.ts +109 -0
  75. package/src/decide/question.ts +159 -0
  76. package/src/decide/review.ts +10 -0
  77. package/src/decide/risk.ts +216 -0
  78. package/src/decide/taste.ts +37 -0
  79. package/src/exec.ts +85 -0
  80. package/src/index.ts +200 -0
  81. package/src/loop/breaks.ts +8 -0
  82. package/src/loop/check-item.ts +76 -0
  83. package/src/loop/ci.ts +8 -0
  84. package/src/loop/github.ts +81 -0
  85. package/src/loop/groups.ts +108 -0
  86. package/src/loop/memory.ts +70 -0
  87. package/src/loop/notes.ts +76 -0
  88. package/src/loop/pair.ts +39 -0
  89. package/src/loop/pass.ts +99 -0
  90. package/src/loop/proof.ts +85 -0
  91. package/src/loop/prove-item.ts +33 -0
  92. package/src/loop/records.ts +75 -0
  93. package/src/loop/signals.ts +130 -0
  94. package/src/measure/inputs.ts +28 -0
  95. package/src/measure/measure.ts +68 -0
  96. package/src/service/cards.ts +24 -0
  97. package/src/service/ci-tick.ts +28 -0
  98. package/src/service/launchd.ts +16 -0
  99. package/src/service/supervise.ts +145 -0
  100. package/src/service/systemd.ts +44 -0
  101. package/src/service/token.ts +21 -0
  102. package/src/service/unit.ts +29 -0
  103. package/src/service/wake.ts +30 -0
  104. package/src/service/workflows.ts +97 -0
  105. package/src/setup/propose.ts +120 -0
  106. package/src/setup/prove.ts +216 -0
  107. package/src/setup/scan.ts +186 -0
  108. package/src/setup/scratch.ts +81 -0
  109. package/src/setup/shipped.ts +15 -0
  110. package/src/setup/tables.ts +101 -0
  111. package/src/setup/waits.ts +58 -0
  112. package/src/setup/write.ts +161 -0
  113. package/src/slots/env.ts +42 -0
  114. package/src/slots/pool.ts +329 -0
  115. package/src/slots/scan.ts +26 -0
  116. package/src/slots/worktree.ts +17 -0
  117. package/src/state/events.ts +52 -0
  118. package/src/state/faults.ts +73 -0
  119. package/src/state/format.ts +50 -0
  120. package/src/state/fs.ts +100 -0
  121. package/src/state/items.ts +195 -0
  122. package/src/state/open.ts +80 -0
  123. package/src/state/ops.ts +76 -0
  124. package/src/state/records.ts +35 -0
  125. package/src/state/runs.ts +99 -0
  126. package/src/state/saved.ts +119 -0
  127. package/src/status/file.ts +49 -0
  128. package/src/status/format.ts +132 -0
  129. package/src/status/sections.ts +14 -0
  130. package/src/status/version.ts +2 -0
  131. package/src/time.ts +7 -0
  132. package/src/worker/alignment-report.ts +18 -0
  133. package/src/worker/answers.ts +153 -0
  134. package/src/worker/base-check.ts +45 -0
  135. package/src/worker/checks.ts +40 -0
  136. package/src/worker/kind.ts +68 -0
  137. package/src/worker/land.ts +509 -0
  138. package/src/worker/lifecycle.ts +97 -0
  139. package/src/worker/merged.ts +29 -0
  140. package/src/worker/open.ts +100 -0
  141. package/src/worker/prose-run.ts +56 -0
  142. package/src/worker/questions.ts +89 -0
  143. package/src/worker/scheduler.ts +135 -0
  144. package/src/worker/signature.ts +41 -0
  145. package/src/worker/tally.ts +25 -0
  146. package/src/worker/taste.ts +38 -0
  147. package/src/worker/thin-path.ts +886 -0
  148. package/src/worker/worker.ts +750 -0
  149. package/surface.json +8787 -0
  150. package/README.md +0 -3
@@ -0,0 +1,329 @@
1
+ import { existsSync, mkdirSync, readFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import PQueue from "p-queue";
4
+ import { type Git, gitIn, whenGitFailed } from "../adapters/git.ts";
5
+ import { hashJson } from "../config/hash.ts";
6
+ import type { HumConfig } from "../config/schema.ts";
7
+ import { commandTimeoutMs } from "../exec.ts";
8
+ import type { State } from "../state/open.ts";
9
+ import type { Slot } from "../state/saved.ts";
10
+ import { SECOND_MS } from "../time.ts";
11
+ import { runChecks } from "../worker/checks.ts";
12
+ import type { Checkedout, Checkout } from "../worker/thin-path.ts";
13
+ import { slotEnv, slotFolder, slotName } from "./env.ts";
14
+ import { isWorktreeOf } from "./worktree.ts";
15
+
16
+ export const SLOT_OUT_CODE = "slot-out";
17
+
18
+ export const SLOT_KEPT_CODE = "slot-kept";
19
+
20
+ export const SLOT_MAINTENANCE_CODE = "slot-maintenance";
21
+
22
+ const CARD_OUTPUT = 400;
23
+
24
+ const CHANGE = "change";
25
+
26
+ export type PoolOptions = {
27
+ /** The owner's checkout: the repo every slot is a worktree of. */
28
+ readonly repo: string;
29
+ readonly state: Pick<State, "slots" | "faults" | "runs">;
30
+ readonly config: Pick<HumConfig, "runners" | "runSlots" | "lockfiles" | "commandTimeoutSeconds">;
31
+ readonly base: string;
32
+ /** The names of the runs alive outside this process; a taken slot whose item has none of them is returned. */
33
+ readonly liveRuns?: () => Promise<ReadonlySet<string>>;
34
+ readonly now?: () => number;
35
+ };
36
+
37
+ const nextChange = (changes: EventTarget, signal: AbortSignal | undefined): Promise<void> =>
38
+ new Promise((resolveChange, reject) => {
39
+ const changed = () => {
40
+ signal?.removeEventListener("abort", aborted);
41
+ resolveChange();
42
+ };
43
+
44
+ const aborted = () => {
45
+ changes.removeEventListener(CHANGE, changed);
46
+ reject(signal?.reason);
47
+ };
48
+
49
+ changes.addEventListener(CHANGE, changed, { once: true });
50
+ signal?.addEventListener("abort", aborted, { once: true });
51
+ });
52
+
53
+ const isHeld = ({ status }: Slot): boolean => status === "taken" || status === "kept";
54
+
55
+ /**
56
+ * The run slots: git worktrees of the owner's checkout, kept prepared so a run starts in one at once. A slot serves
57
+ * one item's pass at a time. It is saved as taken before the pass starts and returned once the pass ends, when its
58
+ * branch holds nothing the remote lacks. Heavy work (installs, data resets, ready checks) runs between passes.
59
+ */
60
+ export class SlotPool {
61
+ readonly #o: PoolOptions;
62
+ readonly #queue = new PQueue({ concurrency: 1 });
63
+ readonly #changes = new EventTarget();
64
+ /** Slots whose pass runs in this process, by slot name. */
65
+ readonly #active = new Map<string, string>();
66
+ readonly #returning = new Set<string>();
67
+ readonly #now: () => number;
68
+ #recheckOut = true;
69
+
70
+ constructor(options: PoolOptions) {
71
+ this.#o = options;
72
+ this.#now = options.now ?? Date.now;
73
+ }
74
+
75
+ get #settings(): HumConfig["runSlots"] {
76
+ return this.#o.config.runSlots;
77
+ }
78
+
79
+ #slots(): Slot[] {
80
+ return this.#o.state.slots
81
+ .list()
82
+ .filter(({ index }) => index < this.#o.config.runners)
83
+ .sort((a, b) => a.index - b.index);
84
+ }
85
+
86
+ #save(slot: Slot, patch: Partial<Slot>): Slot {
87
+ const saved = { ...slot, ...patch, since: this.#now() };
88
+
89
+ this.#o.state.slots.put(slot.name, saved);
90
+ this.#changes.dispatchEvent(new Event(CHANGE));
91
+
92
+ return saved;
93
+ }
94
+
95
+ #envOf(slot: Slot): Record<string, string> {
96
+ return slotEnv(this.#settings, slot);
97
+ }
98
+
99
+ #run(slot: Slot, commands: readonly string[]): Promise<string | undefined> {
100
+ return runChecks(commands, slot.folder, { env: this.#envOf(slot), timeoutMs: this.#settings.stepTimeoutSeconds * SECOND_MS });
101
+ }
102
+
103
+ #git(folder: string): Git {
104
+ return gitIn(folder, { timeoutMs: commandTimeoutMs(this.#o.config) });
105
+ }
106
+
107
+ #lockfiles(folder: string): string {
108
+ const present = this.#o.config.lockfiles.filter((file) => existsSync(join(folder, file)));
109
+
110
+ return hashJson(Object.fromEntries(present.map((file) => [file, readFileSync(join(folder, file), "utf8")])));
111
+ }
112
+
113
+ #out(slot: Slot, cause: string, fix: string): void {
114
+ this.#save(slot, { status: "out", item: undefined });
115
+ this.#o.state.faults.raise({ code: SLOT_OUT_CODE, item: slot.name, cause: `${slot.name} (${slot.folder}) left the pool: ${cause}`.slice(0, CARD_OUTPUT), fix });
116
+ }
117
+
118
+ #ready(slot: Slot, lockfiles: string): void {
119
+ this.#o.state.faults.clear(`${SLOT_OUT_CODE}:${slot.name}`);
120
+ this.#save(slot, { status: "free", item: undefined, lockfiles });
121
+ }
122
+
123
+ /** Makes the slot's worktree if it is not there, runs the recipe's prepare and ready; a failure takes the slot out. */
124
+ async #prepare(slot: Slot): Promise<void> {
125
+ const { repo, base } = this.#o;
126
+
127
+ if (existsSync(slot.folder)) {
128
+ if (!(await isWorktreeOf(repo, slot.folder, commandTimeoutMs(this.#o.config)).catch(whenGitFailed(false))))
129
+ return this.#out(slot, `${slot.folder} is not a git worktree of ${repo}.`, "A slot is a worktree of the checkout: Claude Code trusts a worktree of a trusted repo and refuses a repo of its own. Remove the folder; hum makes the slot again at its next start.");
130
+ } else {
131
+ mkdirSync(dirname(slot.folder), { recursive: true });
132
+ await this.#git(repo).raw(["fetch", "-q", "origin"]);
133
+ await this.#git(repo).raw(["worktree", "add", "-q", "--detach", slot.folder, `origin/${base}`]);
134
+ }
135
+
136
+ const { prepare, ready } = this.#settings.recipe;
137
+ const failure = await this.#run(slot, prepare);
138
+
139
+ if (failure) return this.#out(slot, `its prepare failed: ${failure}`, "Fix the recipe's prepare command or what it needs, then restart the worker.");
140
+
141
+ await this.#check(slot, ready, this.#lockfiles(slot.folder));
142
+ }
143
+
144
+ async #check(slot: Slot, ready: readonly string[], lockfiles: string): Promise<void> {
145
+ const failure = await this.#run(slot, ready);
146
+
147
+ return failure ? this.#out(slot, `its ready check failed: ${failure}`, "The other slots go on. Fix what the check reads, then restart the worker.") : this.#ready(slot, lockfiles);
148
+ }
149
+
150
+ /** Resets the returned slot to the latest base, runs the steps its lockfile change calls for, then the ready check. */
151
+ async #refresh(slot: Slot): Promise<void> {
152
+ const { base } = this.#o;
153
+ const git = this.#git(slot.folder);
154
+
155
+ await git.raw(["fetch", "-q", "origin"]);
156
+ await git.raw(["reset", "-q", "--hard"]);
157
+ await git.raw(["clean", "-fdq"]);
158
+ await git.raw(["checkout", "-q", "--detach", `origin/${base}`]);
159
+
160
+ const lockfiles = this.#lockfiles(slot.folder);
161
+ const changed = lockfiles !== slot.lockfiles;
162
+ const steps = this.#settings.recipe.refresh.filter(({ when }) => when === "always" || changed).map(({ run }) => run);
163
+ const failure = await this.#run(slot, steps);
164
+
165
+ if (failure) return this.#out(slot, `its refresh failed: ${failure}`, "Fix the recipe's refresh command or what it needs, then restart the worker.");
166
+
167
+ await this.#check(slot, this.#settings.recipe.ready, lockfiles);
168
+ }
169
+
170
+ #keep(slot: Slot, cause: string, fix: string): void {
171
+ this.#save(slot, { status: "kept" });
172
+ this.#o.state.faults.raise({ code: SLOT_KEPT_CODE, item: slot.name, cause: `${slot.name} (${slot.folder}) stays taken: ${cause}`.slice(0, CARD_OUTPUT), fix });
173
+ }
174
+
175
+ /**
176
+ * Returns the slot to the pool once its branch holds no commit the remote lacks: resets it, detaches it at the base
177
+ * and deletes the run's branch. A slot that cannot be returned stays taken with one card, and its commits are left alone.
178
+ */
179
+ async #give(slot: Slot): Promise<void> {
180
+ if (this.#returning.has(slot.name)) return;
181
+
182
+ this.#returning.add(slot.name);
183
+ this.#active.delete(slot.name);
184
+
185
+ try {
186
+ const git = this.#git(slot.folder);
187
+
188
+ await git.raw(["fetch", "-q", "origin"]);
189
+
190
+ const ahead = Number((await git.raw(["rev-list", "--count", "HEAD", "--not", "--remotes=origin"])).trim());
191
+ const branch = (await git.run(["symbolic-ref", "-q", "--short", "HEAD"])).stdout.trim();
192
+
193
+ if (ahead > 0) return this.#keep(slot, `${branch || "its checkout"} holds ${ahead} commit(s) the remote lacks.`, `Push them from the slot, or delete the branch to drop them; hum returns the slot at its next tick.`);
194
+
195
+ await git.raw(["reset", "-q", "--hard"]);
196
+ await git.raw(["clean", "-fdq"]);
197
+ await git.raw(["checkout", "-q", "--detach", `origin/${this.#o.base}`]);
198
+
199
+ if (branch) await git.raw(["branch", "-q", "-D", branch]);
200
+
201
+ this.#o.state.faults.clear(`${SLOT_KEPT_CODE}:${slot.name}`);
202
+ this.#save(slot, { status: "stale", item: undefined });
203
+ } catch (error) {
204
+ this.#keep(slot, `it could not be returned: ${error instanceof Error ? error.message : String(error)}`, "Fix what git reports in the slot; hum returns the slot at its next tick.");
205
+ } finally {
206
+ this.#returning.delete(slot.name);
207
+ }
208
+
209
+ this.keepReady();
210
+ }
211
+
212
+ /** A taken slot with no pass in this process and no run alive for its item is returned. A run alive for it is adopted. */
213
+ async #reclaim(): Promise<void> {
214
+ const orphans = this.#slots().filter((slot) => isHeld(slot) && !this.#active.has(slot.name) && !this.#returning.has(slot.name));
215
+
216
+ if (orphans.length === 0) return;
217
+
218
+ const alive = (await this.#o.liveRuns?.()) ?? new Set<string>();
219
+
220
+ for (const slot of orphans) {
221
+ const adopted = slot.item !== undefined && this.#o.state.runs.list(slot.item).some(({ name, endedAt }) => endedAt === undefined && alive.has(name));
222
+
223
+ if (!adopted) await this.#give(slot);
224
+ }
225
+ }
226
+
227
+ #settle(slot: Slot): Promise<void> {
228
+ if (slot.status === "new") return this.#prepare(slot);
229
+
230
+ return slot.status === "stale" ? this.#refresh(slot) : Promise.resolve();
231
+ }
232
+
233
+ async #maintain(): Promise<void> {
234
+ const { state, config } = this.#o;
235
+ const recheck = this.#recheckOut;
236
+
237
+ this.#recheckOut = false;
238
+
239
+ await this.#reclaim().catch((error: Error) => this.#maintenanceFailed("reclaim", error));
240
+
241
+ for (let index = 0; index < config.runners; index++) {
242
+ const name = slotName(index);
243
+
244
+ if (!state.slots.get(name)) this.#save({ name, index, folder: slotFolder(this.#o.repo, this.#settings.pool, name), status: "new", since: 0 }, {});
245
+ }
246
+
247
+ for (const listed of this.#slots()) {
248
+ const slot = recheck && listed.status === "out" ? this.#save(listed, { status: "new" }) : listed;
249
+
250
+ await this.#settle(slot).then(
251
+ () => state.faults.clear(`${SLOT_MAINTENANCE_CODE}:${slot.name}`),
252
+ (error: Error) => this.#maintenanceFailed(slot.name, error),
253
+ );
254
+ }
255
+ }
256
+
257
+ #maintenanceFailed(name: string, error: Error): void {
258
+ this.#o.state.faults.raise({ code: SLOT_MAINTENANCE_CODE, item: name, cause: `Run slot upkeep for ${name} failed: ${error.message}`.slice(0, CARD_OUTPUT), fix: "hum tries again at its next tick." });
259
+ }
260
+
261
+ /** One upkeep pass: slots made, returned slots refreshed, orphans returned. Resolves when the pass has run. */
262
+ maintain(): Promise<void> {
263
+ return this.#queue.add(() => this.#maintain());
264
+ }
265
+
266
+ /** Asks for an upkeep pass without waiting for it; one already waiting covers the ask. */
267
+ keepReady(): void {
268
+ if (this.#queue.size === 0) void this.maintain();
269
+ }
270
+
271
+ /** Resolves when no upkeep is running or waiting. */
272
+ idle(): Promise<void> {
273
+ return this.#queue.onIdle();
274
+ }
275
+
276
+ /** The slots, in order. */
277
+ list(): Slot[] {
278
+ return this.#slots();
279
+ }
280
+
281
+ /** The slot for the item's pass: the one that already holds the item, else the first free one, waiting for a return when none is. */
282
+ async #take(request: Parameters<Checkout>[0]): Promise<{ readonly slot: Slot; readonly held: boolean }> {
283
+ const { signal, item } = request;
284
+
285
+ for (;;) {
286
+ signal?.throwIfAborted();
287
+
288
+ const slots = this.#slots();
289
+ const held = slots.find((slot) => isHeld(slot) && slot.item === item && !this.#returning.has(slot.name));
290
+ const taking = held ?? slots.find(({ status }) => status === "free");
291
+
292
+ if (taking) {
293
+ this.#active.set(taking.name, item);
294
+
295
+ return held ? { slot: held, held: true } : { slot: this.#save(taking, { status: "taken", item }), held: false };
296
+ }
297
+
298
+ if (slots.length === this.#o.config.runners && slots.every(({ status }) => status === "out")) throw new Error(`every run slot is out of the pool: ${this.#o.state.faults.list().filter(({ code }) => code === SLOT_OUT_CODE).map(({ cause }) => cause).join("; ")}`);
299
+
300
+ this.keepReady();
301
+ await nextChange(this.#changes, signal);
302
+ }
303
+ }
304
+
305
+ /** The seam a thin-path pass takes its working copy from: a slot, at the latest base, with its own ports and database. */
306
+ readonly checkout: Checkout = async (request): Promise<Checkedout> => {
307
+ const { repo, base } = this.#o;
308
+ const origin = (await this.#git(repo).raw(["remote", "get-url", "origin"])).trim();
309
+
310
+ if (request.remote !== origin) throw new Error(`run slots work from origin (${origin}), and this pass asks for ${request.remote}`);
311
+
312
+ if (request.base !== base) throw new Error(`run slots keep ${base} ready, and this pass asks for ${request.base}`);
313
+
314
+ const { slot, held } = await this.#take(request);
315
+ const git = this.#git(slot.folder);
316
+
317
+ try {
318
+ await git.raw(["fetch", "-q", "origin"]);
319
+ // A slot the item already held keeps its commits; any other starts at the latest base.
320
+ await git.raw(["checkout", "-q", "--detach", ...(held ? [] : [`origin/${base}`])]);
321
+ } catch (error) {
322
+ await this.#give(slot);
323
+
324
+ throw error;
325
+ }
326
+
327
+ return { folder: slot.folder, env: this.#envOf(slot), giveBack: () => this.#give(slot) };
328
+ };
329
+ }
@@ -0,0 +1,26 @@
1
+ import { accessSync, constants } from "node:fs";
2
+ import { join } from "node:path";
3
+ import type { SlotRecipe } from "../config/schema.ts";
4
+
5
+ /** Where owners keep a script that sets up a working environment, in the order a repo's own convention is preferred. */
6
+ export const ENV_SCRIPTS = ["bin/setup", "script/setup", "scripts/setup", "scripts/setup.sh", "bin/env", "scripts/env", "scripts/env.sh"] as const;
7
+
8
+ const isRunnable = (path: string): boolean => {
9
+ try {
10
+ accessSync(path, constants.X_OK);
11
+
12
+ return true;
13
+ } catch {
14
+ return false;
15
+ }
16
+ };
17
+
18
+ /**
19
+ * The slot recipe a repo already holds. When the owner has an environment script of their own, the recipe calls it
20
+ * and rebuilds nothing; a repo with none gets an empty recipe for setup to fill from its other evidence.
21
+ */
22
+ export const proposeRecipe = (repo: string): SlotRecipe => {
23
+ const script = ENV_SCRIPTS.find((candidate) => isRunnable(join(repo, candidate)));
24
+
25
+ return { prepare: script === undefined ? [] : [`./${script}`], refresh: [], ready: [] };
26
+ };
@@ -0,0 +1,17 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { gitIn } from "../adapters/git.ts";
4
+
5
+ const commonDirOf = async (folder: string, timeoutMs: number): Promise<string> => realpathSync(resolve(folder, (await gitIn(folder, { timeoutMs }).raw(["rev-parse", "--git-common-dir"])).trim()));
6
+
7
+ const gitDirOf = async (folder: string, timeoutMs: number): Promise<string> => realpathSync(resolve(folder, (await gitIn(folder, { timeoutMs }).raw(["rev-parse", "--git-dir"])).trim()));
8
+
9
+ /**
10
+ * Whether `folder` is a linked worktree of the repo at `repo`. Claude Code trusts a worktree of a trusted repo and
11
+ * refuses a repo of its own: a clone shares no git directory with the repo, and a repo's own folder is no linked worktree.
12
+ */
13
+ export const isWorktreeOf = async (repo: string, folder: string, timeoutMs: number): Promise<boolean> => {
14
+ const [repoCommon, folderCommon, folderDir] = await Promise.all([commonDirOf(repo, timeoutMs), commonDirOf(folder, timeoutMs), gitDirOf(folder, timeoutMs)]);
15
+
16
+ return repoCommon === folderCommon && folderDir !== folderCommon;
17
+ };
@@ -0,0 +1,52 @@
1
+ import { join } from "node:path";
2
+ import { z } from "zod";
3
+ import { Json } from "../config/json.ts";
4
+ import { createOnce, listRecords, readJson, slug } from "./fs.ts";
5
+
6
+ export const SavedEvent = z.strictObject({
7
+ /** Where the event came from, such as a thread comment id: a second read of it adds nothing. */
8
+ source: z.string().min(1),
9
+ sourceId: z.string().min(1),
10
+ itemId: z.string().min(1),
11
+ type: z.string().min(1),
12
+ receivedAt: z.int().nonnegative(),
13
+ payload: Json,
14
+ });
15
+
16
+ export type SavedEvent = z.infer<typeof SavedEvent>;
17
+
18
+ export type NewEvent = Omit<SavedEvent, "receivedAt">;
19
+
20
+ /** Every event is saved before anything acts on it, keyed by source, so reading one twice adds nothing. */
21
+ export class EventLog {
22
+ readonly #folder: string;
23
+ readonly #now: () => number;
24
+
25
+ constructor(folder: string, now: () => number) {
26
+ this.#folder = folder;
27
+ this.#now = now;
28
+ }
29
+
30
+ #path({ itemId, source, sourceId }: Pick<SavedEvent, "itemId" | "source" | "sourceId">): string {
31
+ return join(this.#folder, slug(itemId), `${slug(`${source}\u0000${sourceId}`)}.json`);
32
+ }
33
+
34
+ /** Saves the event. `added` is false when this source and id are already in the log. */
35
+ add(event: NewEvent): { readonly added: boolean; readonly event: SavedEvent } {
36
+ const saved = SavedEvent.parse({ ...event, receivedAt: this.#now() });
37
+ const added = createOnce(this.#path(saved), `${JSON.stringify(saved)}\n`);
38
+
39
+ return added ? { added, event: saved } : { added, event: this.get(saved) };
40
+ }
41
+
42
+ get(key: Pick<SavedEvent, "itemId" | "source" | "sourceId">): SavedEvent {
43
+ return SavedEvent.parse(readJson(this.#path(key)));
44
+ }
45
+
46
+ /** An item's events in the order they arrived. */
47
+ list(itemId: string): SavedEvent[] {
48
+ return listRecords(join(this.#folder, slug(itemId)))
49
+ .map((file) => SavedEvent.parse(readJson(file)))
50
+ .sort((a, b) => a.receivedAt - b.receivedAt || (a.sourceId < b.sourceId ? -1 : 1));
51
+ }
52
+ }
@@ -0,0 +1,73 @@
1
+ import { rmSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { Card } from "../status/format.ts";
4
+ import { atomicWrite, listRecords, readJson, slug } from "./fs.ts";
5
+
6
+ /** The fault card for one failure. `key` makes it one card per cause and item. */
7
+ export type FaultInput = {
8
+ readonly code: string;
9
+ readonly item?: string;
10
+ readonly cause: string;
11
+ readonly fix: string;
12
+ readonly action?: Card["action"];
13
+ };
14
+
15
+ export type Outcome<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly fault: Card };
16
+
17
+ /** The fault cards currently raised. One card per cause, kept in memory and, when the disk allows, on it. */
18
+ export class Faults {
19
+ readonly #folder: string;
20
+ readonly #now: () => number;
21
+ readonly #cards = new Map<string, Card>();
22
+
23
+ constructor(folder: string, now: () => number) {
24
+ this.#folder = folder;
25
+ this.#now = now;
26
+
27
+ for (const file of listRecords(folder)) {
28
+ try {
29
+ const card = Card.safeParse(readJson(file));
30
+
31
+ if (card.success) this.#cards.set(card.data.key, card.data);
32
+ } catch {
33
+ // A damaged card file is dropped; the cause raises it again if it still holds.
34
+ }
35
+ }
36
+ }
37
+
38
+ #path(key: string): string {
39
+ return join(this.#folder, `${slug(key)}.json`);
40
+ }
41
+
42
+ /**
43
+ * Raises the card, or returns the one already raised for this cause. A card that cannot be
44
+ * written because the disk is full still stands in memory, and the caller puts it in the status file.
45
+ */
46
+ raise({ code, item, cause, fix, action }: FaultInput): Card {
47
+ const key = item === undefined ? code : `${code}:${item}`;
48
+ const raised = this.#cards.get(key);
49
+
50
+ if (raised) return raised;
51
+
52
+ const card = Card.parse({ kind: "fault", key, item, code, cause, fix, action, since: this.#now() });
53
+
54
+ this.#cards.set(key, card);
55
+
56
+ try {
57
+ atomicWrite(this.#path(key), `${JSON.stringify(card)}\n`);
58
+ } catch {
59
+ // The card stays in memory; the disk that would hold it is the failure it reports.
60
+ }
61
+
62
+ return card;
63
+ }
64
+
65
+ /** Removes the card once its cause is gone. */
66
+ clear(key: string): void {
67
+ if (this.#cards.delete(key)) rmSync(this.#path(key), { force: true });
68
+ }
69
+
70
+ list(): Card[] {
71
+ return [...this.#cards.values()].sort((a, b) => a.since - b.since || (a.key < b.key ? -1 : 1));
72
+ }
73
+ }
@@ -0,0 +1,50 @@
1
+ import semver from "semver";
2
+ import { z } from "zod";
3
+ import pkg from "../../package.json" with { type: "json" };
4
+ import { Json } from "../config/json.ts";
5
+ import type { Steps } from "../config/migrate.ts";
6
+
7
+ /** The engine that is running; every snapshot records it. */
8
+ export const ENGINE_VERSION: string = pkg.version;
9
+
10
+ /** The envelope shape version this engine writes. A change here is public surface. */
11
+ export const ENVELOPE_FORMAT = 1;
12
+
13
+ /** What every format of the envelope carries, enough to refuse a file from a newer engine before reading the rest. */
14
+ export const Header = z.looseObject({ format: z.int().nonnegative(), engineVersion: z.string().min(1) });
15
+
16
+ /** One saved item: the machine's persisted snapshot and what is needed to restore it later. */
17
+ export const Envelope = z.strictObject({
18
+ format: z.literal(ENVELOPE_FORMAT),
19
+ engineVersion: z.string().min(1),
20
+ itemId: z.string().min(1),
21
+ kind: z.string().min(1),
22
+ /** The kind machine's version when the snapshot was taken; `migrateSnapshot` moves it across a change. */
23
+ machineVersion: z.string().min(1),
24
+ savedAt: z.int().nonnegative(),
25
+ snapshot: Json,
26
+ });
27
+
28
+ export type Envelope = z.infer<typeof Envelope>;
29
+
30
+ export const EnvelopeJson = z.record(z.string(), Json);
31
+
32
+ export type EnvelopeJson = z.infer<typeof EnvelopeJson>;
33
+
34
+ /** Per earlier envelope format: rewrites an envelope at that format into the next format's shape. */
35
+ export type EnvelopeMigrations = Steps<EnvelopeJson>;
36
+
37
+ /** One entry per earlier format, from format 0 up. Empty while format 1 is the first shipped. */
38
+ export const ENVELOPE_MIGRATIONS: EnvelopeMigrations = {};
39
+
40
+ /** True when a file was written by an engine newer than the running one, or by one whose version is unreadable. */
41
+ export const isFromNewerEngine = (written: string, running: string): boolean => semver.valid(written) === null || semver.gt(written, running);
42
+
43
+ /** The part of an envelope that names the item and its machine, enough to list what is saved without restoring it. */
44
+ export const SavedHeader = z.looseObject({
45
+ itemId: z.string().min(1),
46
+ kind: z.string().min(1),
47
+ machineVersion: z.string().min(1),
48
+ savedAt: z.int().nonnegative(),
49
+ snapshot: z.looseObject({ value: z.string().optional().catch(undefined) }),
50
+ });
@@ -0,0 +1,100 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { closeSync, fsyncSync, linkSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import writeFileAtomic from "write-file-atomic";
5
+ import { Json } from "../config/json.ts";
6
+
7
+ const RECORD_EXTENSION = ".json";
8
+
9
+ /** Hex characters of the hash a slug keeps. A change renames every saved file. */
10
+ const SLUG_LENGTH = 32;
11
+
12
+ /** A file name for any string: the same string always names the same file, and no string escapes its folder. */
13
+ export const slug = (text: string): string => createHash("sha256").update(text).digest("hex").slice(0, SLUG_LENGTH);
14
+
15
+ export const hasCode = (cause: unknown, code: string): boolean => cause instanceof Error && "code" in cause && cause.code === code;
16
+
17
+ /** True when the error says the file or folder is not there. */
18
+ export const isMissing = (cause: unknown): boolean => hasCode(cause, "ENOENT");
19
+
20
+ /** What `read` returns, or `absent` when it finds no file. Any other failure throws. */
21
+ export const orMissing = <T, Absent>(read: () => T, absent: Absent): T | Absent => {
22
+ try {
23
+ return read();
24
+ } catch (error) {
25
+ if (isMissing(error)) return absent;
26
+
27
+ throw error;
28
+ }
29
+ };
30
+
31
+ /** The JSON in a file; the caller parses it with its schema. */
32
+ export const readJson = (path: string): Json => Json.parse(JSON.parse(readFileSync(path, "utf8")));
33
+
34
+ /** write-file-atomic renames a synced temp file over the target; the rename itself reaches disk only once its folder is synced. */
35
+ const syncFolder = (folder: string): void => {
36
+ const fd = openSync(folder, "r");
37
+
38
+ try {
39
+ fsyncSync(fd);
40
+ } finally {
41
+ closeSync(fd);
42
+ }
43
+ };
44
+
45
+ /** A reader sees the old file or the new one, never a part; when any step throws, the old file stays as it was. */
46
+ export const atomicWrite = (path: string, data: string): void => {
47
+ mkdirSync(dirname(path), { recursive: true });
48
+ writeFileAtomic.sync(path, data);
49
+ syncFolder(dirname(path));
50
+ };
51
+
52
+ /**
53
+ * Creates `path` whole or not at all: the data is written to a temp file, then linked into place, which fails
54
+ * when `path` exists. Returns false, changing nothing, in that case.
55
+ */
56
+ export const createOnce = (path: string, data: string): boolean => {
57
+ const temp = `${path}.${randomUUID()}`;
58
+
59
+ atomicWrite(temp, data);
60
+
61
+ try {
62
+ linkSync(temp, path);
63
+ syncFolder(dirname(path));
64
+
65
+ return true;
66
+ } catch (error) {
67
+ if (hasCode(error, "EEXIST")) return false;
68
+
69
+ throw error;
70
+ } finally {
71
+ rmSync(temp, { force: true });
72
+ }
73
+ };
74
+
75
+ /** The files in a folder; empty when the folder does not exist. */
76
+ export const listFiles = (folder: string): string[] =>
77
+ orMissing(
78
+ () =>
79
+ readdirSync(folder)
80
+ .sort()
81
+ .map((name) => join(folder, name)),
82
+ [],
83
+ );
84
+
85
+ /** The record files in a folder, without the half-written temp files a crash leaves beside them. */
86
+ export const listRecords = (folder: string): string[] => listFiles(folder).filter((file) => file.endsWith(RECORD_EXTENSION));
87
+
88
+ /**
89
+ * Puts a new file holding `data` into `folder` whole: it is written beside the folder and renamed in, so a reader
90
+ * that lists the folder and removes what it read never meets a part, nor a temp file of the write.
91
+ */
92
+ export const dropInto = (folder: string, data: string): void => {
93
+ const name = randomUUID();
94
+ const staged = join(`${folder}.staged`, name);
95
+
96
+ atomicWrite(staged, data);
97
+ mkdirSync(folder, { recursive: true });
98
+ renameSync(staged, join(folder, name));
99
+ syncFolder(folder);
100
+ };