@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,216 @@
|
|
|
1
|
+
import { mkdtempSync, readFileSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import type { AdapterContext } from "../adapter-api.ts";
|
|
6
|
+
import { runContract } from "../adapters/contract.ts";
|
|
7
|
+
import { markdownAdapter } from "../adapters/markdown.ts";
|
|
8
|
+
import { type Config, loadConfig, readConfigDir } from "../config/load.ts";
|
|
9
|
+
import { commandTimeoutMs, exec, SHIPPED_COMMAND_TIMEOUT_MS } from "../exec.ts";
|
|
10
|
+
import { SlotPool } from "../slots/pool.ts";
|
|
11
|
+
import { orMissing } from "../state/fs.ts";
|
|
12
|
+
import { openState } from "../state/open.ts";
|
|
13
|
+
import { runChecks } from "../worker/checks.ts";
|
|
14
|
+
import { openWorker } from "../worker/open.ts";
|
|
15
|
+
import { Scratch } from "./scratch.ts";
|
|
16
|
+
|
|
17
|
+
export type StepStatus = "passed" | "failed" | "skipped";
|
|
18
|
+
|
|
19
|
+
/** One thing setup proved, with how long it took. A skip says why, so nothing passes silently. */
|
|
20
|
+
export type Step = { readonly name: string; readonly status: StepStatus; readonly detail: string; readonly ms: number };
|
|
21
|
+
|
|
22
|
+
type Outcome = { readonly status: StepStatus; readonly detail: string };
|
|
23
|
+
|
|
24
|
+
const passed = (detail: string): Outcome => ({ status: "passed", detail });
|
|
25
|
+
|
|
26
|
+
const failed = (detail: string): Outcome => ({ status: "failed", detail });
|
|
27
|
+
|
|
28
|
+
const skipped = (detail: string): Outcome => ({ status: "skipped", detail });
|
|
29
|
+
|
|
30
|
+
/** Runs one step; a throw is the step failing, in the error's own words. */
|
|
31
|
+
const stepOf = (name: string, outcome: Outcome, started: number): Step => ({ name, status: outcome.status, detail: outcome.detail, ms: Math.round(performance.now() - started) });
|
|
32
|
+
|
|
33
|
+
const timed = async (name: string, run: () => Promise<Outcome>): Promise<Step> => {
|
|
34
|
+
const started = performance.now();
|
|
35
|
+
|
|
36
|
+
return stepOf(name, await run().catch((error: Error) => failed(error.message)), started);
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
export type ProveEnv = {
|
|
40
|
+
readonly hopeSkills: ReadonlySet<string>;
|
|
41
|
+
readonly base: string;
|
|
42
|
+
/** Whether to run one item end to end through the real `claude`; each run spends live calls. */
|
|
43
|
+
readonly item: boolean;
|
|
44
|
+
/** Reads the registry for the pinned engine: the package's versions, or undefined while it is not published. */
|
|
45
|
+
readonly published?: (pin: string) => Promise<"found" | "missing-version" | "unpublished">;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const Manifest = z.looseObject({
|
|
49
|
+
dependencies: z.record(z.string(), z.string()).default({}),
|
|
50
|
+
devDependencies: z.record(z.string(), z.string()).default({}),
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
const ENGINE = "@moo.md/hum";
|
|
54
|
+
|
|
55
|
+
/** A pin that is a folder or tarball on disk rather than a registry version. */
|
|
56
|
+
const LOCAL_PIN = /^(file|link):/;
|
|
57
|
+
|
|
58
|
+
/** What the registry says about the pinned version: found, or the package exists without it, or the package is not published. */
|
|
59
|
+
export const npmPublished = async (pin: string): Promise<"found" | "missing-version" | "unpublished"> => {
|
|
60
|
+
const viewed = await exec("npm", ["view", `${ENGINE}@${pin}`, "version"], { throwOnError: false, timeoutMs: SHIPPED_COMMAND_TIMEOUT_MS });
|
|
61
|
+
|
|
62
|
+
if (viewed.exitCode === 0) return "found";
|
|
63
|
+
|
|
64
|
+
const package_ = await exec("npm", ["view", ENGINE, "name"], { throwOnError: false, timeoutMs: SHIPPED_COMMAND_TIMEOUT_MS });
|
|
65
|
+
|
|
66
|
+
return package_.exitCode === 0 ? "missing-version" : "unpublished";
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const pinOf = (repo: string): string | undefined => {
|
|
70
|
+
const manifest = Manifest.parse(orMissing(() => JSON.parse(readFileSync(join(repo, "package.json"), "utf8")), {}));
|
|
71
|
+
|
|
72
|
+
return { ...manifest.dependencies, ...manifest.devDependencies }[ENGINE];
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const configStep = (repo: string, env: ProveEnv): Outcome & { readonly config?: Config } => {
|
|
76
|
+
const loaded = loadConfig(readConfigDir(join(repo, ".hum")), { env: { hopeSkills: env.hopeSkills } });
|
|
77
|
+
|
|
78
|
+
return loaded.ok ? { ...passed("every state is reachable, reaches done or stuck, and every wait has a timeout"), config: loaded.value } : failed(loaded.refusal.message);
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
const checksStep = async (repo: string, config: Config): Promise<Outcome> => {
|
|
82
|
+
if (config.hum.checks.length === 0) return failed('hum.json names no checks: set "checks"');
|
|
83
|
+
|
|
84
|
+
for (const check of config.hum.checks) {
|
|
85
|
+
const failure = await runChecks([check], repo);
|
|
86
|
+
|
|
87
|
+
if (failure) return failed(failure);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return passed(`${config.hum.checks.length} check(s), each run alone`);
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const markdownOver = (repo: string, base: string, hum: Config["hum"], context: AdapterContext) =>
|
|
94
|
+
markdownAdapter({ repo, base, claimPrefix: hum.claimPrefix, itemsDir: hum.itemsDir, identity: hum.commitIdentity, writeRaceRetries: hum.writeRaceRetries, itemReadsAtOnce: hum.itemReadsAtOnce, mergeMethod: hum.mergeMethod, ownerBranchPrefix: hum.ownerBranchPrefix, timeoutMs: commandTimeoutMs(hum) }, context);
|
|
95
|
+
|
|
96
|
+
const contractStep = async (config: Config, scratch: Scratch, base: string): Promise<Outcome> => {
|
|
97
|
+
const others = Object.entries(config.hum.integrations ?? {}).filter(([, adapter]) => adapter !== "markdown");
|
|
98
|
+
|
|
99
|
+
if (others.length > 0) return skipped(`${others.map(([slot, adapter]) => `${slot}: ${adapter}`).join(", ")} write to a live target; run its contract suite there`);
|
|
100
|
+
|
|
101
|
+
let skew = 0;
|
|
102
|
+
let count = 0;
|
|
103
|
+
|
|
104
|
+
const context: AdapterContext = { report: () => {}, now: () => Date.now() + skew };
|
|
105
|
+
const first = markdownOver(await scratch.worker(), base, config.hum, context);
|
|
106
|
+
const second = markdownOver(await scratch.worker(), base, config.hum, context);
|
|
107
|
+
|
|
108
|
+
const results = await runContract({
|
|
109
|
+
name: "markdown",
|
|
110
|
+
adapter: first,
|
|
111
|
+
other: async () => second,
|
|
112
|
+
seed: (title) => scratch.seed(`contract-${++count}`, title, "body"),
|
|
113
|
+
advance: async (ms) => void (skew += ms),
|
|
114
|
+
spent: () => first.spent(),
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
const broken = results.filter(({ failure }) => failure !== undefined);
|
|
118
|
+
|
|
119
|
+
return broken.length === 0 ? passed(`${results.length} contract checks on the markdown source`) : failed(broken.map(({ name, failure }) => `${name}: ${failure}`).join("\n"));
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
const pinStep = async (repo: string, env: ProveEnv): Promise<Outcome> => {
|
|
123
|
+
const pin = pinOf(repo);
|
|
124
|
+
|
|
125
|
+
if (pin === undefined) return failed(`package.json pins no ${ENGINE}: run bun add --exact ${ENGINE}@<version>`);
|
|
126
|
+
|
|
127
|
+
if (LOCAL_PIN.test(pin)) return passed(`${ENGINE} is pinned to ${pin}, a path on this machine`);
|
|
128
|
+
|
|
129
|
+
const found = await (env.published ?? npmPublished)(pin);
|
|
130
|
+
|
|
131
|
+
if (found === "found") return passed(`${ENGINE}@${pin} is on the registry, so each runner installs it`);
|
|
132
|
+
|
|
133
|
+
return found === "unpublished" ? skipped(`${ENGINE} is not published yet, so no runner can install it; run this step again after the first publish`) : failed(`${ENGINE}@${pin} is not on the registry`);
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const slotStep = async (config: Config, scratch: Scratch, env: ProveEnv): Promise<Outcome> => {
|
|
137
|
+
if (!config.hum.runSlots.enabled) return skipped("run slots are off in hum.json");
|
|
138
|
+
|
|
139
|
+
const pool = mkdtempSync(join(tmpdir(), "hum-prove-slots-"));
|
|
140
|
+
const state = openState(mkdtempSync(join(tmpdir(), "hum-prove-state-")));
|
|
141
|
+
const slots = new SlotPool({ repo: scratch.owner, state, config: { ...config.hum, runners: 1, runSlots: { ...config.hum.runSlots, pool } }, base: env.base });
|
|
142
|
+
const started = performance.now();
|
|
143
|
+
|
|
144
|
+
await slots.maintain();
|
|
145
|
+
|
|
146
|
+
const [slot] = slots.list();
|
|
147
|
+
const cards = state.faults.list().map(({ cause }) => cause);
|
|
148
|
+
|
|
149
|
+
return slot?.status === "free" ? passed(`one slot prepared and ready in ${Math.round(performance.now() - started)} ms`) : failed(`the slot ended ${slot?.status ?? "missing"}: ${cards.join("; ")}`);
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const SETUP_ITEM = { id: "hum-setup-proof", title: "Add a file named hum-setup-proof.md that says hello", body: "Kind: docs\n\nAdd a file named hum-setup-proof.md at the repo root with the single line: hello." } as const;
|
|
153
|
+
|
|
154
|
+
/** The item runs on a copy of its own, since the contract suite leaves ready items on the copy it used. */
|
|
155
|
+
const itemStep = async (repo: string, config: Config, env: ProveEnv): Promise<Outcome> => {
|
|
156
|
+
if (!env.item) return skipped("run without --item: no live run was made");
|
|
157
|
+
|
|
158
|
+
if (Bun.which("claude") === null) return skipped("claude is not installed on this machine");
|
|
159
|
+
|
|
160
|
+
const scratch = await Scratch.from(repo, env.base, config.hum);
|
|
161
|
+
|
|
162
|
+
try {
|
|
163
|
+
return await runItem(scratch, env);
|
|
164
|
+
} finally {
|
|
165
|
+
scratch.dispose();
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
const runItem = async (scratch: Scratch, env: ProveEnv): Promise<Outcome> => {
|
|
170
|
+
await scratch.seed(SETUP_ITEM.id, SETUP_ITEM.title, SETUP_ITEM.body);
|
|
171
|
+
|
|
172
|
+
const results: string[] = [];
|
|
173
|
+
|
|
174
|
+
const worker = await openWorker(scratch.owner, {
|
|
175
|
+
hopeSkills: env.hopeSkills,
|
|
176
|
+
holder: "setup-proof",
|
|
177
|
+
base: env.base,
|
|
178
|
+
where: "ci",
|
|
179
|
+
stateDir: mkdtempSync(join(tmpdir(), "hum-prove-state-")),
|
|
180
|
+
workDir: mkdtempSync(join(tmpdir(), "hum-prove-work-")),
|
|
181
|
+
onResult: (result) => results.push(result.outcome),
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
await worker.tick();
|
|
185
|
+
await worker.idle();
|
|
186
|
+
|
|
187
|
+
return results.includes("merged") ? passed("one item ran end to end and merged") : failed(`the item ended as ${results.join(", ") || "nothing"}`);
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Proves a written setup: the config passes every check, each repo check passes alone, the markdown source passes its
|
|
192
|
+
* contract suite on a scratch copy, the pinned engine is installable, one slot is ready, and one item runs end to end
|
|
193
|
+
* on the scratch copy. Each part is its own step, so one failing hides no other.
|
|
194
|
+
*/
|
|
195
|
+
export const proveSetup = async (repo: string, env: ProveEnv): Promise<Step[]> => {
|
|
196
|
+
const started = performance.now();
|
|
197
|
+
const { config, ...outcome } = configStep(repo, env);
|
|
198
|
+
const configured = stepOf("config", outcome, started);
|
|
199
|
+
|
|
200
|
+
if (!config) return [configured];
|
|
201
|
+
|
|
202
|
+
const scratch = await Scratch.from(repo, env.base, config.hum);
|
|
203
|
+
|
|
204
|
+
try {
|
|
205
|
+
return [
|
|
206
|
+
configured,
|
|
207
|
+
await timed("checks", () => checksStep(repo, config)),
|
|
208
|
+
await timed("contract", () => contractStep(config, scratch, env.base)),
|
|
209
|
+
await timed("engine pin", () => pinStep(repo, env)),
|
|
210
|
+
await timed("slot", () => slotStep(config, scratch, env)),
|
|
211
|
+
await timed("item", () => itemStep(repo, config, env)),
|
|
212
|
+
];
|
|
213
|
+
} finally {
|
|
214
|
+
scratch.dispose();
|
|
215
|
+
}
|
|
216
|
+
};
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { accessSync, constants, readFileSync } from "node:fs";
|
|
2
|
+
import { basename, join } from "node:path";
|
|
3
|
+
import { parse as parseYaml } from "yaml";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { gitIn } from "../adapters/git.ts";
|
|
6
|
+
import { readHistory } from "../adapters/history.ts";
|
|
7
|
+
import { SHIPPED_DEFAULTS } from "../config/schema.ts";
|
|
8
|
+
import { SHIPPED_COMMAND_TIMEOUT_MS } from "../exec.ts";
|
|
9
|
+
import { orMissing } from "../state/fs.ts";
|
|
10
|
+
import { ENV_SCRIPTS } from "../slots/scan.ts";
|
|
11
|
+
import {
|
|
12
|
+
CODEOWNERS_FILES,
|
|
13
|
+
COMPOSE_FILES,
|
|
14
|
+
ENV_EXAMPLE_FILES,
|
|
15
|
+
ENV_TOOLING_FILES,
|
|
16
|
+
ISSUE_TEMPLATE_FOLDER,
|
|
17
|
+
LOCKFILES,
|
|
18
|
+
type PackageManager,
|
|
19
|
+
SETUP_TARGETS,
|
|
20
|
+
TOOL_VERSION_FILES,
|
|
21
|
+
TRACKED_FILE_LIMIT,
|
|
22
|
+
WORKFLOW_FOLDER,
|
|
23
|
+
} from "./tables.ts";
|
|
24
|
+
|
|
25
|
+
/** One job of a CI workflow: when it runs and the shell commands its steps run. */
|
|
26
|
+
export type CiJob = { readonly file: string; readonly job: string; readonly triggers: readonly string[]; readonly commands: readonly string[] };
|
|
27
|
+
|
|
28
|
+
export type FolderHistory = { readonly folder: string; readonly changes: number; readonly sizes: readonly number[] };
|
|
29
|
+
|
|
30
|
+
/** What a repo already holds that setup reads before it asks. */
|
|
31
|
+
export type RepoScan = {
|
|
32
|
+
readonly packageManager: PackageManager | undefined;
|
|
33
|
+
readonly scripts: Readonly<Record<string, string>>;
|
|
34
|
+
readonly ci: readonly CiJob[];
|
|
35
|
+
readonly codeowners: readonly { readonly glob: string; readonly owners: readonly string[] }[];
|
|
36
|
+
readonly composeServices: readonly { readonly name: string; readonly image: string | undefined }[];
|
|
37
|
+
readonly envScripts: readonly string[];
|
|
38
|
+
readonly setupTargets: readonly string[];
|
|
39
|
+
readonly toolVersions: readonly string[];
|
|
40
|
+
readonly envExamples: readonly string[];
|
|
41
|
+
readonly envTooling: readonly string[];
|
|
42
|
+
readonly issueTemplates: readonly { readonly file: string; readonly labels: readonly string[] }[];
|
|
43
|
+
readonly tracked: readonly string[];
|
|
44
|
+
readonly folders: readonly FolderHistory[];
|
|
45
|
+
/** The engine version `package.json` pins, and the schema version `.hum/hum.json` has. */
|
|
46
|
+
readonly engine: { readonly pinned: string | undefined };
|
|
47
|
+
readonly hum: { readonly schemaVersion: number | undefined };
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const textOf = (repo: string, path: string): string => (path === "" ? "" : orMissing(() => readFileSync(join(repo, path), "utf8"), ""));
|
|
51
|
+
|
|
52
|
+
const exists = (repo: string, path: string): boolean => orMissing(() => (accessSync(join(repo, path)), true), false);
|
|
53
|
+
|
|
54
|
+
const isRunnable = (repo: string, path: string): boolean => orMissing(() => (accessSync(join(repo, path), constants.X_OK), true), false);
|
|
55
|
+
|
|
56
|
+
const filesIn = (repo: string, pattern: string): string[] => [...new Bun.Glob(pattern).scanSync({ cwd: repo, onlyFiles: true, dot: true })].sort();
|
|
57
|
+
|
|
58
|
+
const PackageJson = z.looseObject({
|
|
59
|
+
scripts: z.record(z.string(), z.string()).default({}),
|
|
60
|
+
dependencies: z.record(z.string(), z.string()).default({}),
|
|
61
|
+
devDependencies: z.record(z.string(), z.string()).default({}),
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
const Workflow = z.looseObject({
|
|
65
|
+
on: z.union([z.string().transform((trigger) => [trigger]), z.array(z.string()), z.record(z.string(), z.unknown()).transform((triggers) => Object.keys(triggers))]).default([]),
|
|
66
|
+
jobs: z.record(z.string(), z.looseObject({ steps: z.array(z.looseObject({ run: z.string().optional() })).default([]) })).default({}),
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
const Compose = z.looseObject({ services: z.record(z.string(), z.looseObject({ image: z.string().optional() })).default({}) });
|
|
70
|
+
|
|
71
|
+
const Template = z.looseObject({ labels: z.union([z.string(), z.array(z.string())]).default([]) });
|
|
72
|
+
|
|
73
|
+
const TEMPLATE_FRONT_MATTER = /^---\n([\s\S]*?)\n---/;
|
|
74
|
+
|
|
75
|
+
const commandsOf = (run: string): string[] =>
|
|
76
|
+
run
|
|
77
|
+
.split("\n")
|
|
78
|
+
.map((line) => line.trim())
|
|
79
|
+
.filter((line) => line !== "" && !line.startsWith("#"));
|
|
80
|
+
|
|
81
|
+
/** The CI workflows' jobs. A workflow that does not parse is skipped, because the owner's CI is not setup's to judge. */
|
|
82
|
+
const ciJobsOf = (repo: string): CiJob[] =>
|
|
83
|
+
filesIn(repo, `${WORKFLOW_FOLDER}/*.{yml,yaml}`).flatMap((file) => {
|
|
84
|
+
const parsed = Workflow.safeParse(parseYaml(textOf(repo, file)));
|
|
85
|
+
|
|
86
|
+
if (!parsed.success) return [];
|
|
87
|
+
|
|
88
|
+
const triggers = parsed.data.on;
|
|
89
|
+
|
|
90
|
+
return Object.entries(parsed.data.jobs).map(([job, { steps }]) => ({
|
|
91
|
+
file: basename(file),
|
|
92
|
+
job,
|
|
93
|
+
triggers,
|
|
94
|
+
commands: steps.flatMap((step) => commandsOf(step.run ?? "")),
|
|
95
|
+
}));
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
const codeownersOf = (repo: string): RepoScan["codeowners"] => {
|
|
99
|
+
const file = CODEOWNERS_FILES.find((candidate) => exists(repo, candidate));
|
|
100
|
+
|
|
101
|
+
return textOf(repo, file ?? "")
|
|
102
|
+
.split("\n")
|
|
103
|
+
.map((line) => line.replace(/#.*/, "").trim().split(/\s+/))
|
|
104
|
+
.flatMap(([glob, ...owners]) => (glob === undefined || glob === "" || owners.length === 0 ? [] : [{ glob, owners }]));
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
const composeOf = (repo: string): RepoScan["composeServices"] => {
|
|
108
|
+
const file = COMPOSE_FILES.find((candidate) => exists(repo, candidate));
|
|
109
|
+
const parsed = Compose.safeParse(parseYaml(textOf(repo, file ?? "")));
|
|
110
|
+
|
|
111
|
+
return parsed.success ? Object.entries(parsed.data.services).map(([name, { image }]) => ({ name, image })) : [];
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
/** The environment scripts a repo is built to run: executable files in the usual places. */
|
|
115
|
+
const envScriptsOf = (repo: string): string[] => ENV_SCRIPTS.filter((script) => isRunnable(repo, script));
|
|
116
|
+
|
|
117
|
+
/** Makefile and justfile targets, and package scripts, that set up or seed an environment. */
|
|
118
|
+
const setupTargetsOf = (repo: string, scripts: Readonly<Record<string, string>>): string[] => {
|
|
119
|
+
const targets = ["Makefile", "justfile"].flatMap((file) => [...textOf(repo, file).matchAll(/^([\w:.-]+):/gm)].map(([, target]) => target ?? ""));
|
|
120
|
+
|
|
121
|
+
const wanted = new Set<string>(SETUP_TARGETS);
|
|
122
|
+
|
|
123
|
+
return [...new Set([...Object.keys(scripts), ...targets])].filter((target) => wanted.has(target));
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
const templatesOf = (repo: string): RepoScan["issueTemplates"] =>
|
|
127
|
+
filesIn(repo, `${ISSUE_TEMPLATE_FOLDER}/*`).flatMap((file) => {
|
|
128
|
+
const text = textOf(repo, file);
|
|
129
|
+
const front = file.endsWith(".md") ? TEMPLATE_FRONT_MATTER.exec(text)?.[1] ?? "" : text;
|
|
130
|
+
const parsed = Template.safeParse(parseYaml(front));
|
|
131
|
+
|
|
132
|
+
return parsed.success ? [{ file: basename(file), labels: [parsed.data.labels].flat().flatMap((label) => label.split(",").map((one) => one.trim()).filter(Boolean)) }] : [];
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
const trackedOf = async (repo: string): Promise<string[]> => (await gitIn(repo, { timeoutMs: SHIPPED_COMMAND_TIMEOUT_MS }).raw(["ls-files"])).split("\n").filter(Boolean).slice(0, TRACKED_FILE_LIMIT);
|
|
136
|
+
|
|
137
|
+
const topFolder = (path: string): string => (path.includes("/") ? (path.split("/")[0] ?? path) : "");
|
|
138
|
+
|
|
139
|
+
/** Each top-level folder's merged changes on the base, from the history setup reads. */
|
|
140
|
+
const foldersOf = async (repo: string, base: string): Promise<FolderHistory[]> => {
|
|
141
|
+
const git = gitIn(repo, { timeoutMs: SHIPPED_COMMAND_TIMEOUT_MS });
|
|
142
|
+
const log = await git.run(["rev-parse", "--verify", "-q", base]);
|
|
143
|
+
|
|
144
|
+
if (log.code !== 0) return [];
|
|
145
|
+
|
|
146
|
+
const changes = await readHistory(git, base, SHIPPED_DEFAULTS);
|
|
147
|
+
const folders = new Map<string, number[]>();
|
|
148
|
+
|
|
149
|
+
for (const change of changes) {
|
|
150
|
+
for (const folder of new Set(change.files.map(topFolder).filter(Boolean))) folders.set(folder, [...(folders.get(folder) ?? []), change.size]);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return [...folders].map(([folder, sizes]) => ({ folder, changes: sizes.length, sizes: sizes.toReversed() }));
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
const humSchemaOf = (repo: string): number | undefined => {
|
|
157
|
+
const parsed = z.looseObject({ schemaVersion: z.number().optional() }).safeParse(orMissing(() => JSON.parse(textOf(repo, ".hum/hum.json") || "null"), null));
|
|
158
|
+
|
|
159
|
+
return parsed.success ? parsed.data.schemaVersion : undefined;
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
/** Reads the repo's package manager, CI, scripts, owners, services, environment tooling, issue templates and per-folder history. */
|
|
163
|
+
export const scanRepo = async (repo: string, base: string): Promise<RepoScan> => {
|
|
164
|
+
const manifest = PackageJson.safeParse(orMissing(() => JSON.parse(textOf(repo, "package.json") || "null"), null));
|
|
165
|
+
const scripts = manifest.success ? manifest.data.scripts : {};
|
|
166
|
+
const pinned = manifest.success ? { ...manifest.data.dependencies, ...manifest.data.devDependencies }["@moo.md/hum"] : undefined;
|
|
167
|
+
const lockfile = Object.entries(LOCKFILES).find(([file]) => exists(repo, file));
|
|
168
|
+
|
|
169
|
+
return {
|
|
170
|
+
packageManager: lockfile?.[1],
|
|
171
|
+
scripts,
|
|
172
|
+
ci: ciJobsOf(repo),
|
|
173
|
+
codeowners: codeownersOf(repo),
|
|
174
|
+
composeServices: composeOf(repo),
|
|
175
|
+
envScripts: envScriptsOf(repo),
|
|
176
|
+
setupTargets: setupTargetsOf(repo, scripts),
|
|
177
|
+
toolVersions: TOOL_VERSION_FILES.filter((file) => exists(repo, file)),
|
|
178
|
+
envExamples: ENV_EXAMPLE_FILES.filter((file) => exists(repo, file)),
|
|
179
|
+
envTooling: ENV_TOOLING_FILES.filter((file) => exists(repo, file)),
|
|
180
|
+
issueTemplates: templatesOf(repo),
|
|
181
|
+
tracked: await trackedOf(repo),
|
|
182
|
+
folders: await foldersOf(repo, base),
|
|
183
|
+
engine: { pinned },
|
|
184
|
+
hum: { schemaVersion: humSchemaOf(repo) },
|
|
185
|
+
};
|
|
186
|
+
};
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { cpSync, existsSync, mkdtempSync, rmSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { type Git, gitIn } from "../adapters/git.ts";
|
|
5
|
+
import { newItemFile } from "../adapters/item-file.ts";
|
|
6
|
+
import type { HumConfig } from "../config/schema.ts";
|
|
7
|
+
import { commandTimeoutMs } from "../exec.ts";
|
|
8
|
+
import { atomicWrite } from "../state/fs.ts";
|
|
9
|
+
|
|
10
|
+
type ScratchSettings = Pick<HumConfig, "commitIdentity" | "itemsDir" | "commandTimeoutSeconds">;
|
|
11
|
+
|
|
12
|
+
/** What the owner's checkout contributes to a scratch copy beyond its commits: setup's files, which may not be committed yet. */
|
|
13
|
+
const SETUP_FILES = [".hum", ".github/workflows"] as const;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* A throwaway copy of the owner's repo with its own bare remote, so setup can run an item or a contract suite without
|
|
17
|
+
* touching the owner's remote. The copy holds the owner's commits and their uncommitted `.hum/` and workflows.
|
|
18
|
+
*/
|
|
19
|
+
export class Scratch {
|
|
20
|
+
readonly root = mkdtempSync(join(tmpdir(), "hum-prove-"));
|
|
21
|
+
readonly remote = join(this.root, "remote.git");
|
|
22
|
+
readonly owner = join(this.root, "owner");
|
|
23
|
+
readonly #base: string;
|
|
24
|
+
readonly #settings: ScratchSettings;
|
|
25
|
+
#workers = 0;
|
|
26
|
+
|
|
27
|
+
private constructor(base: string, settings: ScratchSettings) {
|
|
28
|
+
this.#base = base;
|
|
29
|
+
this.#settings = settings;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
static async from(repo: string, base: string, settings: ScratchSettings): Promise<Scratch> {
|
|
33
|
+
const scratch = new Scratch(base, settings);
|
|
34
|
+
const git = scratch.#git(scratch.root);
|
|
35
|
+
|
|
36
|
+
await git.raw(["clone", "-q", "--bare", repo, scratch.remote]);
|
|
37
|
+
await git.raw(["clone", "-q", scratch.remote, scratch.owner]);
|
|
38
|
+
|
|
39
|
+
for (const file of SETUP_FILES) {
|
|
40
|
+
if (existsSync(join(repo, file))) cpSync(join(repo, file), join(scratch.owner, file), { recursive: true });
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
await scratch.publish("scratch: the owner's setup files");
|
|
44
|
+
|
|
45
|
+
return scratch;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
#git(folder: string): Git {
|
|
49
|
+
return gitIn(folder, { identity: this.#settings.commitIdentity, timeoutMs: commandTimeoutMs(this.#settings) });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async publish(message: string): Promise<void> {
|
|
53
|
+
const git = this.#git(this.owner);
|
|
54
|
+
|
|
55
|
+
await git.raw(["add", "-A"]);
|
|
56
|
+
await git.raw(["commit", "-q", "--allow-empty", "-m", message]);
|
|
57
|
+
await git.raw(["pull", "-q", "--rebase", "origin", this.#base]);
|
|
58
|
+
await git.raw(["push", "-q", "origin", `HEAD:refs/heads/${this.#base}`]);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** A ready item on the scratch remote's base; returns its id. */
|
|
62
|
+
async seed(id: string, title: string, body: string): Promise<string> {
|
|
63
|
+
atomicWrite(join(this.owner, this.#settings.itemsDir, `${id}.md`), newItemFile(title, body));
|
|
64
|
+
await this.publish(`scratch: item ${id}`);
|
|
65
|
+
|
|
66
|
+
return id;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Another checkout of the scratch remote, for a second worker. */
|
|
70
|
+
async worker(): Promise<string> {
|
|
71
|
+
const folder = join(this.root, `worker-${++this.#workers}`);
|
|
72
|
+
|
|
73
|
+
await this.#git(this.root).raw(["clone", "-q", this.remote, folder]);
|
|
74
|
+
|
|
75
|
+
return folder;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
dispose(): void {
|
|
79
|
+
rmSync(this.root, { recursive: true, force: true });
|
|
80
|
+
}
|
|
81
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { type RawConfig, readConfigDir } from "../config/load.ts";
|
|
3
|
+
import { DefaultsConfig, Kind } from "../config/schema.ts";
|
|
4
|
+
|
|
5
|
+
/** Where the shipped defaults sit, in the package or in the owner's `node_modules`. */
|
|
6
|
+
export const DEFAULTS_DIR = join(import.meta.dir, "..", "..", "defaults");
|
|
7
|
+
|
|
8
|
+
export const shippedRaw = (): RawConfig => readConfigDir(DEFAULTS_DIR);
|
|
9
|
+
|
|
10
|
+
/** The config hum ships with, parsed: its settings and its kinds. */
|
|
11
|
+
export const shippedConfig = () => {
|
|
12
|
+
const raw = shippedRaw();
|
|
13
|
+
|
|
14
|
+
return { hum: DefaultsConfig.parse(raw.hum), kinds: Object.fromEntries(Object.entries(raw.kinds).map(([name, file]) => [name, Kind.parse(file)])) };
|
|
15
|
+
};
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/** The package manager each lockfile says. */
|
|
2
|
+
export const LOCKFILES = {
|
|
3
|
+
"bun.lock": "bun",
|
|
4
|
+
"bun.lockb": "bun",
|
|
5
|
+
"pnpm-lock.yaml": "pnpm",
|
|
6
|
+
"yarn.lock": "yarn",
|
|
7
|
+
"package-lock.json": "npm",
|
|
8
|
+
"uv.lock": "uv",
|
|
9
|
+
"poetry.lock": "poetry",
|
|
10
|
+
"Cargo.lock": "cargo",
|
|
11
|
+
"go.sum": "go",
|
|
12
|
+
} as const satisfies Record<string, string>;
|
|
13
|
+
|
|
14
|
+
export type PackageManager = (typeof LOCKFILES)[keyof typeof LOCKFILES];
|
|
15
|
+
|
|
16
|
+
/** The command that installs from the lockfile alone, per package manager. */
|
|
17
|
+
export const INSTALL_COMMANDS = {
|
|
18
|
+
bun: "bun install --frozen-lockfile",
|
|
19
|
+
pnpm: "pnpm install --frozen-lockfile",
|
|
20
|
+
yarn: "yarn install --immutable",
|
|
21
|
+
npm: "npm ci",
|
|
22
|
+
uv: "uv sync --frozen",
|
|
23
|
+
poetry: "poetry install --sync",
|
|
24
|
+
cargo: "cargo fetch --locked",
|
|
25
|
+
go: "go mod download",
|
|
26
|
+
} as const satisfies Record<PackageManager, string>;
|
|
27
|
+
|
|
28
|
+
/** The command that runs a package script, per package manager that has scripts. */
|
|
29
|
+
export const RUN_SCRIPT: Readonly<Record<PackageManager, string | undefined>> = { bun: "bun run", pnpm: "pnpm run", yarn: "yarn", npm: "npm run", uv: undefined, poetry: undefined, cargo: undefined, go: undefined };
|
|
30
|
+
|
|
31
|
+
/** Package scripts that check a change, in the order a repo's own run gives them. */
|
|
32
|
+
export const CHECK_SCRIPTS = ["check", "typecheck", "lint", "test"] as const;
|
|
33
|
+
|
|
34
|
+
/** Package scripts, justfile and Makefile targets that set up or seed an environment. */
|
|
35
|
+
export const SETUP_TARGETS = ["setup", "bootstrap", "seed", "dev:setup", "db:seed", "db:setup"] as const;
|
|
36
|
+
|
|
37
|
+
/** A CI command line that checks the change. */
|
|
38
|
+
export const CHECK_COMMAND = /\b(test|tests|lint|typecheck|type-check|tsc|check|vitest|jest|pytest|clippy|eslint|oxlint|biome|ruff|mypy|vet)\b/;
|
|
39
|
+
|
|
40
|
+
/** A CI command line that is not a check, whatever words it holds: installs, publishing, shell plumbing. */
|
|
41
|
+
export const NOT_A_CHECK = /^(echo|export|cd|mkdir|cp|mv|rm|curl|wget|sudo|gh|git)\b|\b(install|publish|deploy|release|upload|setup)\b/;
|
|
42
|
+
|
|
43
|
+
/** The files that hold a repo's tool versions. */
|
|
44
|
+
export const TOOL_VERSION_FILES = [".tool-versions", ".nvmrc", ".node-version", ".bun-version", ".python-version", "mise.toml", ".mise.toml", "rust-toolchain.toml", ".go-version"] as const;
|
|
45
|
+
|
|
46
|
+
export const ENV_EXAMPLE_FILES = [".env.example", ".env.sample", ".env.template"] as const;
|
|
47
|
+
|
|
48
|
+
/** The owner's own environment tooling: a recipe calls it and rebuilds nothing. */
|
|
49
|
+
export const ENV_TOOLING_FILES = [".envrc", "mise.toml", ".mise.toml", "devbox.json", "flake.nix", ".devcontainer/devcontainer.json", "Tiltfile"] as const;
|
|
50
|
+
|
|
51
|
+
export const COMPOSE_FILES = ["compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"] as const;
|
|
52
|
+
|
|
53
|
+
export const CODEOWNERS_FILES = [".github/CODEOWNERS", "CODEOWNERS", "docs/CODEOWNERS"] as const;
|
|
54
|
+
|
|
55
|
+
export const WORKFLOW_FOLDER = ".github/workflows";
|
|
56
|
+
|
|
57
|
+
export const ISSUE_TEMPLATE_FOLDER = ".github/ISSUE_TEMPLATE";
|
|
58
|
+
|
|
59
|
+
/** Paths that hold data or secrets, as globs; setup proposes the ones a repo's tracked files match. */
|
|
60
|
+
export const DATA_AND_SECRET_GLOBS = [
|
|
61
|
+
"**/migrations/**",
|
|
62
|
+
"**/*.sql",
|
|
63
|
+
"**/.env",
|
|
64
|
+
"**/.env.*",
|
|
65
|
+
"**/*.pem",
|
|
66
|
+
"**/*.key",
|
|
67
|
+
"**/secrets/**",
|
|
68
|
+
"**/credentials*",
|
|
69
|
+
"**/*.tfstate",
|
|
70
|
+
"**/schema.prisma",
|
|
71
|
+
] as const;
|
|
72
|
+
|
|
73
|
+
/** A file that shows the shape of a secret without holding one. */
|
|
74
|
+
export const SECRET_TEMPLATE = /\.(example|sample|template)$/;
|
|
75
|
+
|
|
76
|
+
/** How careful a top-level folder is, as a position among the risk levels: 0 is the lowest. */
|
|
77
|
+
export const FOLDER_RANKS = [
|
|
78
|
+
{ rank: 0, folder: /^(docs?|documentation|examples?|samples?)$/ },
|
|
79
|
+
{ rank: 2, folder: /^(infra|infrastructure|deploy|deployment|terraform|k8s|helm|ops|\.github|\.circleci)$/ },
|
|
80
|
+
] as const;
|
|
81
|
+
|
|
82
|
+
export const DEFAULT_FOLDER_RANK = 1;
|
|
83
|
+
|
|
84
|
+
/** The risk level position of a root-level markdown file, and of any other root file. */
|
|
85
|
+
export const ROOT_MARKDOWN_RANK = 0;
|
|
86
|
+
|
|
87
|
+
/** The words a repo's labels use for a kind of work, per kind name. A label the table lacks goes to the kind question. */
|
|
88
|
+
export const KIND_LABEL_WORDS = {
|
|
89
|
+
fix: ["bug", "bugfix", "defect", "regression", "fix", "type: bug", "kind/bug"],
|
|
90
|
+
feature: ["feature", "enhancement", "feat", "improvement", "type: feature", "kind/feature"],
|
|
91
|
+
docs: ["docs", "documentation", "doc", "type: docs", "kind/documentation"],
|
|
92
|
+
hotfix: ["hotfix", "urgent", "incident", "p0", "critical"],
|
|
93
|
+
} as const satisfies Record<string, readonly string[]>;
|
|
94
|
+
|
|
95
|
+
/** Hours a wait gets before it ends stuck, by who it waits on. */
|
|
96
|
+
export const WAIT_HOURS = { owner: 72, other: 24 } as const;
|
|
97
|
+
|
|
98
|
+
export const HOUR_MS = 3_600_000;
|
|
99
|
+
|
|
100
|
+
/** Tracked files setup reads the repo's shape from, at most. */
|
|
101
|
+
export const TRACKED_FILE_LIMIT = 50_000;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { OWNER_WAIT_TAG, STUCK_TAG, WAIT_TAG, type Kind, type StateNodeJSON } from "../config/schema.ts";
|
|
2
|
+
import { HOUR_MS, WAIT_HOURS } from "./tables.ts";
|
|
3
|
+
|
|
4
|
+
/** A state a kind's machine waits in, with the hours its timeout proposes. */
|
|
5
|
+
export type Wait = { readonly kind: string; readonly state: string; readonly waitsOn: "owner" | "other"; readonly hours: number };
|
|
6
|
+
|
|
7
|
+
/** The answer for one wait: the hours after which the item ends stuck. */
|
|
8
|
+
export type WaitAnswers = Readonly<Record<string, number>>;
|
|
9
|
+
|
|
10
|
+
/** The key a wait's answer sits under. */
|
|
11
|
+
export const waitKey = ({ kind, state }: Pick<Wait, "kind" | "state">): string => `${kind}/${state}`;
|
|
12
|
+
|
|
13
|
+
const isOwnerWait = (tags: readonly string[] | undefined): boolean => tags?.includes(OWNER_WAIT_TAG) ?? false;
|
|
14
|
+
|
|
15
|
+
const isWait = (tags: readonly string[] | undefined): boolean => isOwnerWait(tags) || (tags?.includes(WAIT_TAG) ?? false);
|
|
16
|
+
|
|
17
|
+
/** Every waiting state of the kinds, each with a proposed timeout; setup asks the owner one question per wait. */
|
|
18
|
+
export const waitsOf = (kinds: Readonly<Record<string, Kind>>): Wait[] =>
|
|
19
|
+
Object.entries(kinds).flatMap(([kind, config]) =>
|
|
20
|
+
Object.entries(config.machine.states).flatMap(([state, node]): Wait[] => {
|
|
21
|
+
if (!isWait(node.tags)) return [];
|
|
22
|
+
|
|
23
|
+
const waitsOn = isOwnerWait(node.tags) ? "owner" : "other";
|
|
24
|
+
|
|
25
|
+
return [{ kind, state, waitsOn, hours: WAIT_HOURS[waitsOn] }];
|
|
26
|
+
}),
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
/** The state a timed-out wait goes to: the kind's first stuck state. */
|
|
30
|
+
const stuckStateOf = (kind: string, config: Kind): string => {
|
|
31
|
+
const stuck = Object.entries(config.machine.states).find(([, node]) => node.tags?.includes(STUCK_TAG));
|
|
32
|
+
|
|
33
|
+
if (!stuck) throw new Error(`kind "${kind}" has no state tagged "${STUCK_TAG}" for a timed-out wait to go to`);
|
|
34
|
+
|
|
35
|
+
return stuck[0];
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const hasTimeout = (node: StateNodeJSON): boolean => node.timeout !== undefined || Object.keys(node.after ?? {}).length > 0;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The kinds with a timeout on every wait: the hours answered, else the proposed hours. A timed-out wait ends stuck.
|
|
42
|
+
* A wait that already has a timeout keeps it.
|
|
43
|
+
*/
|
|
44
|
+
export const withTimeouts = (kinds: Readonly<Record<string, Kind>>, answers: WaitAnswers): Record<string, Kind> =>
|
|
45
|
+
Object.fromEntries(
|
|
46
|
+
Object.entries(kinds).map(([kind, config]) => {
|
|
47
|
+
const stuck = stuckStateOf(kind, config);
|
|
48
|
+
const hoursOf = new Map(waitsOf({ [kind]: config }).map((wait) => [wait.state, answers[waitKey(wait)] ?? wait.hours]));
|
|
49
|
+
|
|
50
|
+
const states = Object.entries(config.machine.states).map(([state, node]): [string, StateNodeJSON] => {
|
|
51
|
+
const hours = hoursOf.get(state);
|
|
52
|
+
|
|
53
|
+
return [state, hours === undefined || hasTimeout(node) ? node : { ...node, after: { [String(hours * HOUR_MS)]: [{ target: stuck }] } }];
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
return [kind, { ...config, machine: { ...config.machine, states: Object.fromEntries(states) } }];
|
|
57
|
+
}),
|
|
58
|
+
);
|