@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.
- package/defaults/hum.json +321 -0
- package/defaults/kinds/check.json +183 -0
- package/defaults/kinds/docs.json +151 -0
- package/defaults/kinds/feature.json +202 -0
- package/defaults/kinds/fix.json +183 -0
- package/defaults/kinds/hotfix.json +164 -0
- package/defaults/roles/build.md +3 -0
- package/defaults/roles/fix.md +1 -0
- package/defaults/roles/plan.md +3 -0
- package/defaults/roles/review.md +3 -0
- package/evals/alignment/RESULTS.md +8 -0
- package/evals/alignment/cases.jsonl +128 -0
- package/evals/alignment/sample.jsonl +20 -0
- package/evals/kind/RESULTS.md +5 -0
- package/evals/kind/cases.jsonl +24 -0
- package/evals/plan-outcome/RESULTS.md +4 -0
- package/evals/plan-outcome/cases.jsonl +12 -0
- package/evals/repeat-pair/RESULTS.md +4 -0
- package/evals/repeat-pair/cases.jsonl +51 -0
- package/evals/reply-option/RESULTS.md +3 -0
- package/evals/reply-option/cases.jsonl +45 -0
- package/evals/review-verdict/RESULTS.md +4 -0
- package/evals/review-verdict/cases.jsonl +12 -0
- package/package.json +88 -4
- package/schema/hum.schema.json +1355 -0
- package/scripts/eval.ts +244 -0
- package/src/adapter-api.ts +134 -0
- package/src/adapters/admit.ts +111 -0
- package/src/adapters/argument.ts +11 -0
- package/src/adapters/claim.ts +93 -0
- package/src/adapters/claude-bg.ts +375 -0
- package/src/adapters/claude-p.ts +593 -0
- package/src/adapters/contract.ts +231 -0
- package/src/adapters/fake.ts +157 -0
- package/src/adapters/git.ts +155 -0
- package/src/adapters/github.ts +457 -0
- package/src/adapters/guard.ts +152 -0
- package/src/adapters/history.ts +215 -0
- package/src/adapters/item-file.ts +102 -0
- package/src/adapters/limit.ts +67 -0
- package/src/adapters/markdown.ts +365 -0
- package/src/adapters/marked.ts +119 -0
- package/src/adapters/model-call.ts +75 -0
- package/src/adapters/once.ts +45 -0
- package/src/adapters/owner-commit.ts +60 -0
- package/src/adapters/pull-requests.ts +253 -0
- package/src/adapters/registry.ts +156 -0
- package/src/adapters/roundup.ts +291 -0
- package/src/adapters/serial.ts +22 -0
- package/src/adapters/transcript.ts +99 -0
- package/src/cli/commands.ts +46 -0
- package/src/cli/main.ts +8 -0
- package/src/cli/ops.ts +224 -0
- package/src/cli/service.ts +156 -0
- package/src/cli/setup.ts +141 -0
- package/src/cli/shared-watch.ts +127 -0
- package/src/config/change.ts +54 -0
- package/src/config/checks.ts +217 -0
- package/src/config/git-ref-name.d.ts +3 -0
- package/src/config/hash.ts +6 -0
- package/src/config/json.ts +6 -0
- package/src/config/load.ts +88 -0
- package/src/config/machine.ts +20 -0
- package/src/config/migrate.ts +61 -0
- package/src/config/refusal.ts +58 -0
- package/src/config/schema.ts +465 -0
- package/src/config/settings.ts +6 -0
- package/src/config/state-map.ts +76 -0
- package/src/decide/alignment.ts +79 -0
- package/src/decide/answer.ts +131 -0
- package/src/decide/kind.ts +39 -0
- package/src/decide/labels.ts +137 -0
- package/src/decide/merge.ts +102 -0
- package/src/decide/prose.ts +109 -0
- package/src/decide/question.ts +159 -0
- package/src/decide/review.ts +10 -0
- package/src/decide/risk.ts +216 -0
- package/src/decide/taste.ts +37 -0
- package/src/exec.ts +80 -0
- package/src/index.ts +200 -0
- package/src/loop/breaks.ts +8 -0
- package/src/loop/check-item.ts +76 -0
- package/src/loop/ci.ts +8 -0
- package/src/loop/github.ts +81 -0
- package/src/loop/groups.ts +108 -0
- package/src/loop/memory.ts +70 -0
- package/src/loop/notes.ts +76 -0
- package/src/loop/pair.ts +39 -0
- package/src/loop/pass.ts +99 -0
- package/src/loop/proof.ts +85 -0
- package/src/loop/prove-item.ts +33 -0
- package/src/loop/records.ts +75 -0
- package/src/loop/signals.ts +130 -0
- package/src/measure/inputs.ts +28 -0
- package/src/measure/measure.ts +68 -0
- package/src/service/cards.ts +24 -0
- package/src/service/ci-tick.ts +28 -0
- package/src/service/launchd.ts +16 -0
- package/src/service/supervise.ts +145 -0
- package/src/service/systemd.ts +44 -0
- package/src/service/token.ts +21 -0
- package/src/service/unit.ts +29 -0
- package/src/service/wake.ts +30 -0
- package/src/service/workflows.ts +97 -0
- package/src/setup/propose.ts +120 -0
- package/src/setup/prove.ts +216 -0
- package/src/setup/scan.ts +186 -0
- package/src/setup/scratch.ts +81 -0
- package/src/setup/shipped.ts +15 -0
- package/src/setup/tables.ts +101 -0
- package/src/setup/waits.ts +58 -0
- package/src/setup/write.ts +161 -0
- package/src/slots/env.ts +42 -0
- package/src/slots/pool.ts +329 -0
- package/src/slots/scan.ts +26 -0
- package/src/slots/worktree.ts +17 -0
- package/src/state/events.ts +52 -0
- package/src/state/faults.ts +73 -0
- package/src/state/format.ts +50 -0
- package/src/state/fs.ts +100 -0
- package/src/state/items.ts +189 -0
- package/src/state/open.ts +80 -0
- package/src/state/ops.ts +76 -0
- package/src/state/records.ts +35 -0
- package/src/state/runs.ts +99 -0
- package/src/state/saved.ts +119 -0
- package/src/status/file.ts +49 -0
- package/src/status/format.ts +132 -0
- package/src/status/sections.ts +14 -0
- package/src/status/version.ts +2 -0
- package/src/time.ts +7 -0
- package/src/worker/alignment-report.ts +18 -0
- package/src/worker/answers.ts +153 -0
- package/src/worker/base-check.ts +46 -0
- package/src/worker/checks.ts +26 -0
- package/src/worker/kind.ts +68 -0
- package/src/worker/land.ts +508 -0
- package/src/worker/lifecycle.ts +97 -0
- package/src/worker/merged.ts +29 -0
- package/src/worker/open.ts +100 -0
- package/src/worker/prose-run.ts +56 -0
- package/src/worker/questions.ts +89 -0
- package/src/worker/scheduler.ts +135 -0
- package/src/worker/signature.ts +41 -0
- package/src/worker/tally.ts +25 -0
- package/src/worker/taste.ts +38 -0
- package/src/worker/thin-path.ts +886 -0
- package/src/worker/worker.ts +728 -0
- package/surface.json +8787 -0
- package/README.md +0 -3
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import type { GitIdentityRead } from "../adapters/git.ts";
|
|
6
|
+
import { type Config, loadConfig, type RawConfig, readConfigDir } from "../config/load.ts";
|
|
7
|
+
import { hashJson } from "../config/hash.ts";
|
|
8
|
+
import { Json } from "../config/json.ts";
|
|
9
|
+
import { migrateConfig } from "../config/migrate.ts";
|
|
10
|
+
import type { Refusal, Result } from "../config/refusal.ts";
|
|
11
|
+
import { Kind, READABLE_SCHEMA_VERSIONS, SCHEMA_VERSION } from "../config/schema.ts";
|
|
12
|
+
import { ciWorkflows } from "../service/workflows.ts";
|
|
13
|
+
import { renderUnit, type UnitKind } from "../service/unit.ts";
|
|
14
|
+
import { atomicWrite } from "../state/fs.ts";
|
|
15
|
+
import { shippedRaw } from "./shipped.ts";
|
|
16
|
+
import { withTimeouts } from "./waits.ts";
|
|
17
|
+
|
|
18
|
+
const WORKFLOW_FOLDER = join(".github", "workflows");
|
|
19
|
+
|
|
20
|
+
const HumObject = z.record(z.string(), Json);
|
|
21
|
+
|
|
22
|
+
/** The answers come from a model's JSON, so no answer may name the identity every commit is credited to: it comes from the owner's git config or their own hum.json. */
|
|
23
|
+
const AnsweredSettings = HumObject.refine((hum) => !("commitIdentity" in hum), "commitIdentity is never an answer: setup reads it from git config");
|
|
24
|
+
|
|
25
|
+
/** What the owner decided: the `hum.json` keys they set, the hours of each wait, and the schema the writer targets. */
|
|
26
|
+
export const SetupAnswers = z.strictObject({
|
|
27
|
+
hum: AnsweredSettings.default({}),
|
|
28
|
+
waitHours: z.record(z.string(), z.number().positive()).default({}),
|
|
29
|
+
/** The schema version the writing skill produces; a newer one than this engine reads is refused. */
|
|
30
|
+
schemaVersion: z.int().optional(),
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
export type SetupAnswers = z.infer<typeof SetupAnswers>;
|
|
34
|
+
|
|
35
|
+
export type SetupEnv = {
|
|
36
|
+
readonly hopeSkills: ReadonlySet<string>;
|
|
37
|
+
/** Where a Mac or Linux service unit is written; default the user's home. */
|
|
38
|
+
readonly home?: string;
|
|
39
|
+
readonly platform?: NodeJS.Platform;
|
|
40
|
+
/** The program and PATH a unit starts `hum serve` with. */
|
|
41
|
+
readonly runtime?: { readonly bun: string; readonly path: string };
|
|
42
|
+
/** The owner's name and email as git config holds them: the identity hum.json takes unless it names one already. */
|
|
43
|
+
readonly gitIdentity: GitIdentityRead;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
export type SetupResult = { readonly ok: true; readonly written: readonly string[]; readonly config: Config } | { readonly ok: false; readonly refusal: Refusal };
|
|
47
|
+
|
|
48
|
+
const UPDATE_ENGINE = "Update the engine: bun add --exact @moo.md/hum@latest.";
|
|
49
|
+
|
|
50
|
+
/** Refuses a schema the installed engine does not read, whether the existing file has it or the writer would produce it. */
|
|
51
|
+
const schemaRefusal = (existing: Json | undefined, target: number): Refusal | undefined => {
|
|
52
|
+
if (!READABLE_SCHEMA_VERSIONS.includes(target)) {
|
|
53
|
+
return {
|
|
54
|
+
code: "unknown-schema-version",
|
|
55
|
+
found: target,
|
|
56
|
+
readable: READABLE_SCHEMA_VERSIONS,
|
|
57
|
+
message: `Setup would write hum.json schemaVersion ${target}, and this engine reads ${READABLE_SCHEMA_VERSIONS.join(", ")}. ${UPDATE_ENGINE} Nothing was written.`,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const migrated = existing === undefined ? undefined : migrateConfig(existing);
|
|
62
|
+
|
|
63
|
+
return migrated && !migrated.ok ? { ...migrated.refusal, message: `${migrated.refusal.message} Nothing was written.` } : undefined;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const noGitIdentity = (missing: readonly string[]): Refusal => ({
|
|
67
|
+
code: "no-git-identity",
|
|
68
|
+
missing,
|
|
69
|
+
message: `hum commits as you, and git config holds no ${missing.join(" or ")}. Set ${missing.length === 1 ? "it" : "each"}, then run setup again: ${missing.map((key) => `git config --global ${key} "<yours>"`).join("; ")}. Nothing was written.`,
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
/** The identity hum.json already holds, else the one git config holds, else the refusal that says what to set. */
|
|
73
|
+
const identityOf = (hum: Readonly<Record<string, Json>>, git: GitIdentityRead): Result<Json> => {
|
|
74
|
+
if (hum.commitIdentity !== undefined) return { ok: true, value: hum.commitIdentity };
|
|
75
|
+
|
|
76
|
+
return git.found ? { ok: true, value: asJson(git.identity) } : { ok: false, refusal: noGitIdentity(git.missing) };
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const readExisting = (repo: string): RawConfig | undefined => (existsSync(join(repo, ".hum", "hum.json")) ? readConfigDir(join(repo, ".hum")) : undefined);
|
|
80
|
+
|
|
81
|
+
type FileToWrite = { readonly path: string; readonly text: string };
|
|
82
|
+
|
|
83
|
+
const unitPath = (kind: UnitKind, label: string, home: string): string =>
|
|
84
|
+
kind === "launchd" ? join(home, "Library", "LaunchAgents", `${label}.plist`) : join(home, ".config", "systemd", "user", `${label}.service`);
|
|
85
|
+
|
|
86
|
+
const jsonText = (value: Json): string => `${JSON.stringify(value, null, "\t")}\n`;
|
|
87
|
+
|
|
88
|
+
/** The keys of `hum.json` the owner's file holds: the structure every config needs, and each setting that is not the shipped default. */
|
|
89
|
+
const STRUCTURE = ["schemaVersion", "levels", "paths", "roles", "events", "kinds", "integrations"] as const;
|
|
90
|
+
|
|
91
|
+
const STRUCTURAL = new Set<string>(STRUCTURE);
|
|
92
|
+
|
|
93
|
+
const ownerKeys = (hum: Readonly<Record<string, Json>>, shipped: Readonly<Record<string, Json>>): Record<string, Json> =>
|
|
94
|
+
Object.fromEntries(Object.entries(hum).filter(([key, value]) => STRUCTURAL.has(key) || hashJson(value) !== hashJson(shipped[key] ?? null)));
|
|
95
|
+
|
|
96
|
+
const asJson = (value: Kind | Readonly<Record<string, Json>>): Json => Json.parse(JSON.parse(JSON.stringify(value)));
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Writes `.hum/` and the service files from the owner's answers, or writes nothing: the config must pass every check
|
|
100
|
+
* with every wait timed out, and must be a schema the installed engine reads (and the one already in the repo).
|
|
101
|
+
*/
|
|
102
|
+
export const writeSetup = (repo: string, answers: SetupAnswers, env: SetupEnv): SetupResult => {
|
|
103
|
+
const existing = readExisting(repo);
|
|
104
|
+
const refused = schemaRefusal(existing?.hum, answers.schemaVersion ?? SCHEMA_VERSION);
|
|
105
|
+
|
|
106
|
+
if (refused) return { ok: false, refusal: refused };
|
|
107
|
+
|
|
108
|
+
const shipped = shippedRaw();
|
|
109
|
+
const base = existing ?? shipped;
|
|
110
|
+
const shippedHum = HumObject.parse(shipped.hum);
|
|
111
|
+
const given = { ...HumObject.parse(base.hum), ...answers.hum };
|
|
112
|
+
const identity = identityOf(given, env.gitIdentity);
|
|
113
|
+
|
|
114
|
+
if (!identity.ok) return identity;
|
|
115
|
+
|
|
116
|
+
const hum = { ...given, commitIdentity: identity.value };
|
|
117
|
+
const kinds = Object.fromEntries(Object.entries(withTimeouts(parseKinds(base), answers.waitHours)).map(([name, kind]) => [name, asJson(kind)]));
|
|
118
|
+
const roles = { ...shipped.roles, ...existing?.roles };
|
|
119
|
+
const loaded = loadConfig({ hum: asJson(hum), kinds, roles }, { env: { hopeSkills: env.hopeSkills } });
|
|
120
|
+
|
|
121
|
+
if (!loaded.ok) return { ok: false, refusal: loaded.refusal };
|
|
122
|
+
|
|
123
|
+
const files = [
|
|
124
|
+
{ path: join(repo, ".hum", "hum.json"), text: jsonText(ownerKeys(hum, shippedHum)) },
|
|
125
|
+
...Object.entries(kinds).map(([name, kind]) => ({ path: join(repo, ".hum", "kinds", `${name}.json`), text: jsonText(kind) })),
|
|
126
|
+
...Object.entries(roles).map(([file, text]) => ({ path: join(repo, ".hum", file), text })),
|
|
127
|
+
...(existsSync(join(repo, ".hum", "memory.md")) ? [] : [{ path: join(repo, ".hum", "memory.md"), text: "" }]),
|
|
128
|
+
...(existsSync(join(repo, loaded.value.hum.itemsDir, ".gitkeep")) ? [] : [{ path: join(repo, loaded.value.hum.itemsDir, ".gitkeep"), text: "" }]),
|
|
129
|
+
...(loaded.value.hum.runPlaces.includes("ci") ? ciWorkflows(loaded.value.hum).map(({ file, text }) => ({ path: join(repo, WORKFLOW_FOLDER, file), text })) : []),
|
|
130
|
+
...(loaded.value.hum.runPlaces.includes("mac") ? [serviceFile(repo, loaded.value, env)] : []),
|
|
131
|
+
];
|
|
132
|
+
|
|
133
|
+
for (const { path, text } of files) atomicWrite(path, text);
|
|
134
|
+
|
|
135
|
+
return { ok: true, written: files.map(({ path }) => path), config: loaded.value };
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
const parseKinds = (raw: RawConfig): Record<string, Kind> => Object.fromEntries(Object.entries(raw.kinds).map(([name, file]) => [name, Kind.parse(file)]));
|
|
139
|
+
|
|
140
|
+
const serviceFile = (repo: string, config: Config, env: SetupEnv): FileToWrite => {
|
|
141
|
+
const kind: UnitKind = (env.platform ?? process.platform) === "darwin" ? "launchd" : "systemd";
|
|
142
|
+
const home = env.home ?? homedir();
|
|
143
|
+
const bun = env.runtime?.bun ?? process.execPath;
|
|
144
|
+
const label = config.hum.serviceLabel;
|
|
145
|
+
|
|
146
|
+
return {
|
|
147
|
+
path: unitPath(kind, label, home),
|
|
148
|
+
text: renderUnit(kind, {
|
|
149
|
+
label,
|
|
150
|
+
repo,
|
|
151
|
+
command: [bun, join(repo, "node_modules", ".bin", "hum"), "serve"],
|
|
152
|
+
path: env.runtime?.path ?? [dirname(bun), dirname(Bun.which("git") ?? "/usr/bin/git"), dirname(Bun.which("claude") ?? "/usr/local/bin/claude"), "/usr/bin", "/bin"].join(":"),
|
|
153
|
+
env: {},
|
|
154
|
+
log: join(home, kind === "launchd" ? join("Library", "Logs") : join(".local", "state"), `${label}.log`),
|
|
155
|
+
restartDelaySeconds: config.hum.restartDelaySeconds,
|
|
156
|
+
}),
|
|
157
|
+
};
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
/** The answers file the skill writes: `{ "hum": {...}, "waitHours": {...}, "schemaVersion": 1 }`. */
|
|
161
|
+
export const readAnswers = (file: string): SetupAnswers => SetupAnswers.parse(JSON.parse(readFileSync(file, "utf8")));
|
package/src/slots/env.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { basename, join, resolve } from "node:path";
|
|
2
|
+
import type { HumConfig } from "../config/schema.ts";
|
|
3
|
+
|
|
4
|
+
/** The variables a slot's recipe commands, repo checks and runs read. The recipe is written against these names. */
|
|
5
|
+
export const SLOT_ENV = {
|
|
6
|
+
slot: "HUM_SLOT",
|
|
7
|
+
folder: "HUM_SLOT_FOLDER",
|
|
8
|
+
portBase: "HUM_SLOT_PORT_BASE",
|
|
9
|
+
database: "HUM_SLOT_DATABASE",
|
|
10
|
+
composeProject: "COMPOSE_PROJECT_NAME",
|
|
11
|
+
} as const;
|
|
12
|
+
|
|
13
|
+
export type SlotIdentity = { readonly name: string; readonly index: number; readonly folder: string };
|
|
14
|
+
|
|
15
|
+
type Settings = Pick<HumConfig["runSlots"], "services" | "ports" | "projectPrefix">;
|
|
16
|
+
|
|
17
|
+
const NOT_NAME_CHARACTER = /[^A-Za-z0-9]+/g;
|
|
18
|
+
|
|
19
|
+
/** The name of the slot at this position among the slots. */
|
|
20
|
+
export const slotName = (index: number): string => `slot-${index + 1}`;
|
|
21
|
+
|
|
22
|
+
/** Where a slot's worktree is: in the pool folder, named for the checkout it belongs to and the slot. */
|
|
23
|
+
export const slotFolder = (repo: string, pool: string, name: string): string => join(resolve(repo, pool), `${basename(repo)}-${name}`);
|
|
24
|
+
|
|
25
|
+
const isShared = ({ services }: Settings): boolean => services === "shared";
|
|
26
|
+
|
|
27
|
+
/** The port a slot's services start from: the start of its own block, or the one block every slot shares. */
|
|
28
|
+
const portBaseOf = (settings: Settings, index: number): number => settings.ports.base + (isShared(settings) ? 0 : index * settings.ports.stride);
|
|
29
|
+
|
|
30
|
+
/** One compose project for the slot, or for all slots when they share one set of services. */
|
|
31
|
+
const projectOf = (settings: Settings, name: string): string => `${settings.projectPrefix}-${isShared(settings) ? "shared" : name}`;
|
|
32
|
+
|
|
33
|
+
/** The database only this slot's runs reach on a shared set of services. */
|
|
34
|
+
const databaseOf = ({ projectPrefix }: Settings, name: string): string => `${projectPrefix}_${name}`.replace(NOT_NAME_CHARACTER, "_");
|
|
35
|
+
|
|
36
|
+
export const slotEnv = (settings: Settings, { name, index, folder }: SlotIdentity) => ({
|
|
37
|
+
[SLOT_ENV.slot]: name,
|
|
38
|
+
[SLOT_ENV.folder]: folder,
|
|
39
|
+
[SLOT_ENV.portBase]: String(portBaseOf(settings, index)),
|
|
40
|
+
[SLOT_ENV.database]: databaseOf(settings, name),
|
|
41
|
+
[SLOT_ENV.composeProject]: projectOf(settings, name),
|
|
42
|
+
});
|
|
@@ -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
|
+
}
|