@moo.md/hum 0.0.0-stage → 0.0.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 +375 -0
  32. package/src/adapters/claude-p.ts +593 -0
  33. package/src/adapters/contract.ts +231 -0
  34. package/src/adapters/fake.ts +157 -0
  35. package/src/adapters/git.ts +155 -0
  36. package/src/adapters/github.ts +457 -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 +119 -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 +291 -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 +80 -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 +189 -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 +46 -0
  135. package/src/worker/checks.ts +26 -0
  136. package/src/worker/kind.ts +68 -0
  137. package/src/worker/land.ts +508 -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 +728 -0
  149. package/surface.json +8787 -0
  150. package/README.md +0 -3
@@ -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
+ };
@@ -0,0 +1,189 @@
1
+ import { rmSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { type AnyActor, type AnyActorLogic } from "xstate";
4
+ import { restoreActor } from "xstate/persist";
5
+ import { Json } from "../config/json.ts";
6
+ import { climb } from "../config/migrate.ts";
7
+ import { migrateSnapshot } from "../config/state-map.ts";
8
+ import { kindMachine } from "../config/machine.ts";
9
+ import type { Kind } from "../config/schema.ts";
10
+ import { type Faults, type Outcome } from "./faults.ts";
11
+ import { atomicWrite, isMissing, listRecords, readJson, slug } from "./fs.ts";
12
+ import {
13
+ ENGINE_VERSION,
14
+ Envelope,
15
+ EnvelopeJson,
16
+ ENVELOPE_FORMAT,
17
+ ENVELOPE_MIGRATIONS,
18
+ type EnvelopeMigrations,
19
+ Header,
20
+ isFromNewerEngine,
21
+ SavedHeader,
22
+ } from "./format.ts";
23
+
24
+ type ActorClock = NonNullable<Parameters<typeof restoreActor>[2]>["clock"];
25
+
26
+ /** What the engine writes and reads as the envelope; tests set another to play a different release. */
27
+ export type Codec = {
28
+ readonly engineVersion?: string;
29
+ readonly format?: number;
30
+ readonly migrations?: EnvelopeMigrations;
31
+ };
32
+
33
+ export type RestoreOptions = {
34
+ /** The earlier version of the kind, by machine version, for a snapshot saved under it. */
35
+ readonly kindAt?: (machineVersion: string) => Kind | undefined;
36
+ readonly sources?: Readonly<Record<string, AnyActorLogic>>;
37
+ readonly clock?: ActorClock;
38
+ };
39
+
40
+ /** An item with a saved snapshot, from the envelope header. */
41
+ export type SavedSnapshot = {
42
+ readonly itemId: string;
43
+ readonly kind: string;
44
+ readonly machineVersion: string;
45
+ readonly savedAt: number;
46
+ /** The machine's state, when it is a plain state name. */
47
+ readonly state: string | undefined;
48
+ };
49
+
50
+ /** The snapshot of a running item actor, as the JSON `saveItem` writes. */
51
+ export const persistedSnapshot = (actor: AnyActor): Json => Json.parse(JSON.parse(JSON.stringify(actor.getPersistedSnapshot())));
52
+
53
+ const reason = (cause: unknown): string => (cause instanceof Error ? cause.message : String(cause));
54
+
55
+ const DAMAGED_FIX = "Restore the file from a backup, or delete it to start the item over; the other items go on.";
56
+
57
+ /** Per-item snapshots under `items/`. Every failure becomes one fault card; nothing is thrown for bad data. */
58
+ export class Items {
59
+ readonly #folder: string;
60
+ readonly #faults: Faults;
61
+ readonly #now: () => number;
62
+ readonly #engineVersion: string;
63
+ readonly #format: number;
64
+ readonly #migrations: EnvelopeMigrations;
65
+
66
+ constructor(folder: string, faults: Faults, now: () => number, { engineVersion = ENGINE_VERSION, format = ENVELOPE_FORMAT, migrations = ENVELOPE_MIGRATIONS }: Codec = {}) {
67
+ this.#folder = folder;
68
+ this.#faults = faults;
69
+ this.#now = now;
70
+ this.#engineVersion = engineVersion;
71
+ this.#format = format;
72
+ this.#migrations = migrations;
73
+ }
74
+
75
+ path(itemId: string): string {
76
+ return join(this.#folder, `${slug(itemId)}.json`);
77
+ }
78
+
79
+ /** A failed write leaves the old snapshot and raises one card. */
80
+ save(itemId: string, kind: Kind, snapshot: Json): Outcome<void> {
81
+ const key = `snapshot-write-failed:${itemId}`;
82
+ const envelope = { format: this.#format, engineVersion: this.#engineVersion, itemId, kind: kind.machine.id, machineVersion: kind.machine.version, savedAt: this.#now(), snapshot };
83
+
84
+ try {
85
+ atomicWrite(this.path(itemId), `${JSON.stringify(envelope)}\n`);
86
+ } catch (error) {
87
+ return {
88
+ ok: false,
89
+ fault: this.#faults.raise({
90
+ code: "snapshot-write-failed",
91
+ item: itemId,
92
+ cause: `The state of ${itemId} could not be saved: ${reason(error)}. The last saved state is kept.`,
93
+ fix: "Free disk space where hum keeps its state; the next change saves it again.",
94
+ }),
95
+ };
96
+ }
97
+
98
+ this.#faults.clear(key);
99
+
100
+ return { ok: true, value: undefined };
101
+ }
102
+
103
+ /** The items with a saved snapshot, read from each envelope header. A damaged file is left to `restore`, which raises its card. */
104
+ saved(): SavedSnapshot[] {
105
+ return listRecords(this.#folder).flatMap((file) => {
106
+ try {
107
+ const header = SavedHeader.safeParse(readJson(file));
108
+
109
+ if (!header.success) return [];
110
+
111
+ const { itemId, kind, machineVersion, savedAt, snapshot } = header.data;
112
+
113
+ return [{ itemId, kind, machineVersion, savedAt, state: snapshot.value }];
114
+ } catch {
115
+ return [];
116
+ }
117
+ });
118
+ }
119
+
120
+ /** Removes an item's snapshot once the item has finished. */
121
+ remove(itemId: string): void {
122
+ rmSync(this.path(itemId), { force: true });
123
+ }
124
+
125
+ #fault(itemId: string, code: string, cause: string, fix: string): Outcome<never> {
126
+ return { ok: false, fault: this.#faults.raise({ code, item: itemId, cause, fix }) };
127
+ }
128
+
129
+ /**
130
+ * Reads the item's snapshot and restores its actor, not started. Returns `undefined` when nothing is saved.
131
+ * A snapshot that cannot be restored stays on disk, and the caller starts nothing for that item.
132
+ */
133
+ async restore(itemId: string, kind: Kind, { kindAt, sources = {}, clock }: RestoreOptions = {}): Promise<Outcome<AnyActor | undefined>> {
134
+ const file = this.path(itemId);
135
+ const unreadable = (why: string) => this.#fault(itemId, "snapshot-unreadable", `The saved state of ${itemId} at ${file} is damaged: ${why}.`, DAMAGED_FIX);
136
+ const unrestorable = (why: string) => this.#fault(itemId, "snapshot-restore-error", `The saved state of ${itemId} does not restore: ${why}.`, DAMAGED_FIX);
137
+ let parsed: Json;
138
+
139
+ try {
140
+ parsed = readJson(file);
141
+ } catch (error) {
142
+ if (isMissing(error)) return { ok: true, value: undefined };
143
+
144
+ if (error instanceof SyntaxError) return unreadable(error.message);
145
+
146
+ return this.#fault(itemId, "snapshot-unreadable", `The saved state of ${itemId} at ${file} cannot be read: ${reason(error)}.`, "Fix the file's permissions or restore it from a backup; the other items go on.");
147
+ }
148
+
149
+ const header = Header.safeParse(parsed);
150
+
151
+ if (!header.success) return unreadable("it has no format or engine version");
152
+
153
+ if (header.data.format > this.#format || isFromNewerEngine(header.data.engineVersion, this.#engineVersion)) {
154
+ return this.#fault(itemId, "snapshot-from-newer-engine", `The saved state of ${itemId} was written by hum ${header.data.engineVersion}, which is newer than the running ${this.#engineVersion}.`, "Update the engine to that version or later: bun add --exact @moo.md/hum@latest.");
155
+ }
156
+
157
+ const envelope = Envelope.safeParse(climb(EnvelopeJson.parse(parsed), header.data.format, this.#format, this.#migrations, "format"));
158
+
159
+ if (!envelope.success) return unreadable(envelope.error.message);
160
+
161
+ const { snapshot, machineVersion } = envelope.data;
162
+ let current = snapshot;
163
+
164
+ if (machineVersion !== kind.machine.version) {
165
+ const previous = kindAt?.(machineVersion);
166
+
167
+ if (!previous) {
168
+ return this.#fault(itemId, "snapshot-machine-unknown", `${itemId} was saved under version ${machineVersion} of its machine, and this config holds no map from it.`, "Add a stateMap for that version to the kind file, or delete the item's saved state.");
169
+ }
170
+
171
+ try {
172
+ current = await migrateSnapshot(previous, kind, snapshot, sources);
173
+ } catch (error) {
174
+ return this.#fault(itemId, "snapshot-restore-error", `${itemId} could not move from machine version ${machineVersion} to ${kind.machine.version}: ${reason(error)}.`, "Map the state in the kind's stateMap, or delete the item's saved state.");
175
+ }
176
+ }
177
+
178
+ try {
179
+ // SAFETY: the snapshot is JSON the machine's own schema validates; xstate reports a bad one as an 'error' status, checked below.
180
+ const restored = current as never;
181
+ const actor = restoreActor(kindMachine(kind, sources), restored, clock ? { clock } : undefined);
182
+ const status = actor.getSnapshot();
183
+
184
+ return status.status === "error" ? unrestorable(reason(status.error)) : { ok: true, value: actor };
185
+ } catch (error) {
186
+ return unrestorable(reason(error));
187
+ }
188
+ }
189
+ }
@@ -0,0 +1,80 @@
1
+ import { join, resolve } from "node:path";
2
+ import { gitIn } from "../adapters/git.ts";
3
+ import { Kind } from "../config/schema.ts";
4
+ import { SHIPPED_COMMAND_TIMEOUT_MS } from "../exec.ts";
5
+ import { EventLog } from "./events.ts";
6
+ import { Faults } from "./faults.ts";
7
+ import { type Codec, Items } from "./items.ts";
8
+ import { Break, Merge, PossibleRepeat, Proof, RepeatGroup, ReviewNote } from "../loop/records.ts";
9
+ import { Choice } from "../status/format.ts";
10
+ import { OpKeys } from "./ops.ts";
11
+ import { Records } from "./records.ts";
12
+ import { RunRecords } from "./runs.ts";
13
+ import { ItemKind, Landing, Learned, Limit, Parked, QueuedQuestion, ReadyList, SavedPlan, SettledAnswer, Slot, Spent, Verdict } from "./saved.ts";
14
+
15
+ /** On the Mac and in a clone, state lives in the repo's git common dir, so every worktree shares it. */
16
+ export const defaultStateDir = async (cwd: string): Promise<string> => {
17
+ const found = await gitIn(cwd, { timeoutMs: SHIPPED_COMMAND_TIMEOUT_MS }).run(["rev-parse", "--git-common-dir"]);
18
+
19
+ if (found.code !== 0) throw new Error(`${cwd} is not inside a git repository: ${found.stderr.trim()}`);
20
+
21
+ return join(resolve(cwd, found.stdout.trim()), "hum");
22
+ };
23
+
24
+ export type StateOptions = Codec & { readonly now?: () => number };
25
+
26
+ /** Everything the engine saves between runs, under one folder. */
27
+ export const openState = (dir: string, { now = Date.now, ...codec }: StateOptions = {}) => {
28
+ const faults = new Faults(join(dir, "faults"), now);
29
+
30
+ return {
31
+ dir,
32
+ /** The one status file for the repo. */
33
+ statusPath: join(dir, "status.json"),
34
+ /** The worker's heartbeat, one file the service unit reads. */
35
+ heartbeatPath: join(dir, "heartbeat.json"),
36
+ /** The answer hook drops one file here per posted answer; its content is the item id. */
37
+ inbox: join(dir, "inbox"),
38
+ /** A background run's Stop hook drops one file here per stop: the run's session id and transcript path. */
39
+ stops: join(dir, "stops"),
40
+ faults,
41
+ items: new Items(join(dir, "items"), faults, now, codec),
42
+ events: new EventLog(join(dir, "events"), now),
43
+ ops: new OpKeys(join(dir, "ops"), now),
44
+ runs: new RunRecords(join(dir, "runs"), now),
45
+ parked: new Records(join(dir, "parked"), Parked),
46
+ spent: new Records(join(dir, "spent"), Spent),
47
+ /** Earlier kinds by `<machine id>@<version>`, for `items.restore`. */
48
+ kinds: new Records(join(dir, "kinds"), Kind),
49
+ limit: new Records(join(dir, "limit"), Limit),
50
+ ready: new Records(join(dir, "ready"), ReadyList),
51
+ /** The run slots, by name. */
52
+ slots: new Records(join(dir, "slots"), Slot),
53
+ landings: new Records(join(dir, "landings"), Landing),
54
+ /** Path rules by glob. */
55
+ learned: new Records(join(dir, "learned"), Learned),
56
+ /** Each item's kind, by item id. */
57
+ itemKinds: new Records(join(dir, "item-kinds"), ItemKind),
58
+ plans: new Records(join(dir, "plans"), SavedPlan),
59
+ verdicts: new Records(join(dir, "verdicts"), Verdict),
60
+ /** Questions by item, waiting for room under the daily cap or asked within the day. */
61
+ questions: new Records(join(dir, "questions"), QueuedQuestion),
62
+ /** Choices made without the owner, by item and time. */
63
+ choices: new Records(join(dir, "choices"), Choice),
64
+ /** Each answer's disposition, by item and ordinal. */
65
+ answers: new Records(join(dir, "answers"), SettledAnswer),
66
+ /** Review notes, by source and source id. */
67
+ notes: new Records(join(dir, "notes"), ReviewNote),
68
+ /** Notes that state one rule, by the key of the first. */
69
+ repeats: new Records(join(dir, "repeats"), RepeatGroup),
70
+ possibleRepeats: new Records(join(dir, "possible-repeats"), PossibleRepeat),
71
+ /** Merged changes, by item. */
72
+ merges: new Records(join(dir, "merges"), Merge),
73
+ /** Tests of the base that failed after a merge, by item. */
74
+ breaks: new Records(join(dir, "breaks"), Break),
75
+ /** What proving a check item cost, by item. */
76
+ proofs: new Records(join(dir, "proofs"), Proof),
77
+ };
78
+ };
79
+
80
+ export type State = ReturnType<typeof openState>;
@@ -0,0 +1,76 @@
1
+ import { join } from "node:path";
2
+ import { z } from "zod";
3
+ import { atomicWrite, createOnce, listRecords, orMissing, readJson, slug } from "./fs.ts";
4
+
5
+ /** One external op of one attempt of one run of one item. */
6
+ export const OpKey = z.strictObject({
7
+ itemId: z.string().min(1),
8
+ run: z.string().min(1),
9
+ attempt: z.int().nonnegative(),
10
+ op: z.string().min(1),
11
+ });
12
+
13
+ export type OpKey = z.infer<typeof OpKey>;
14
+
15
+ const Record = OpKey.extend({ state: z.enum(["started", "done"]), at: z.int().nonnegative() });
16
+
17
+ export type OpProvider = {
18
+ /** True when the provider already holds the effect of this op, found by its key. */
19
+ readonly holds: () => Promise<boolean>;
20
+ readonly run: () => Promise<void>;
21
+ };
22
+
23
+ /** The key is saved before the op, so a restart after a kill finds the op started and asks the provider before it runs it again. */
24
+ export class OpKeys {
25
+ readonly #folder: string;
26
+ readonly #now: () => number;
27
+
28
+ constructor(folder: string, now: () => number) {
29
+ this.#folder = folder;
30
+ this.#now = now;
31
+ }
32
+
33
+ #path(key: OpKey): string {
34
+ return join(this.#folder, `${slug(JSON.stringify([key.itemId, key.run, key.attempt, key.op]))}.json`);
35
+ }
36
+
37
+ #write(key: OpKey, state: "started" | "done", create: boolean): boolean {
38
+ const text = `${JSON.stringify({ ...key, state, at: this.#now() })}\n`;
39
+
40
+ if (create) return createOnce(this.#path(key), text);
41
+
42
+ atomicWrite(this.#path(key), text);
43
+
44
+ return true;
45
+ }
46
+
47
+ /** Every op saved. */
48
+ list(): z.infer<typeof Record>[] {
49
+ return listRecords(this.#folder).map((file) => Record.parse(readJson(file)));
50
+ }
51
+
52
+ state(key: OpKey): "started" | "done" | undefined {
53
+ return orMissing(() => Record.parse(readJson(this.#path(OpKey.parse(key)))).state, undefined);
54
+ }
55
+
56
+ /** Runs the op once per key, across restarts: `skipped` when it is done or the provider already holds it. */
57
+ async once(key: OpKey, { holds, run }: OpProvider): Promise<"ran" | "skipped"> {
58
+ const checked = OpKey.parse(key);
59
+ const fresh = this.#write(checked, "started", true);
60
+
61
+ if (!fresh) {
62
+ if (this.state(checked) === "done") return "skipped";
63
+
64
+ if (await holds()) {
65
+ this.#write(checked, "done", false);
66
+
67
+ return "skipped";
68
+ }
69
+ }
70
+
71
+ await run();
72
+ this.#write(checked, "done", false);
73
+
74
+ return "ran";
75
+ }
76
+ }
@@ -0,0 +1,35 @@
1
+ import { join } from "node:path";
2
+ import { rmSync } from "node:fs";
3
+ import type { z } from "zod";
4
+ import { atomicWrite, listRecords, orMissing, readJson, slug } from "./fs.ts";
5
+
6
+ /** One JSON file per key under a folder, written whole. The schema checks every read. */
7
+ export class Records<S extends z.ZodType> {
8
+ readonly #folder: string;
9
+ readonly #schema: S;
10
+
11
+ constructor(folder: string, schema: S) {
12
+ this.#folder = folder;
13
+ this.#schema = schema;
14
+ }
15
+
16
+ #path(key: string): string {
17
+ return join(this.#folder, `${slug(key)}.json`);
18
+ }
19
+
20
+ get(key: string): z.output<S> | undefined {
21
+ return orMissing(() => this.#schema.parse(readJson(this.#path(key))), undefined);
22
+ }
23
+
24
+ put(key: string, value: z.input<S>): void {
25
+ atomicWrite(this.#path(key), `${JSON.stringify(this.#schema.parse(value))}\n`);
26
+ }
27
+
28
+ remove(key: string): void {
29
+ rmSync(this.#path(key), { force: true });
30
+ }
31
+
32
+ list(): z.output<S>[] {
33
+ return listRecords(this.#folder).map((file) => this.#schema.parse(readJson(file)));
34
+ }
35
+ }