@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,141 @@
1
+ import { join } from "node:path";
2
+ import type { Command } from "commander";
3
+ import { x } from "tinyexec";
4
+ import { z } from "zod";
5
+ import type { Item } from "../adapter-api.ts";
6
+ import { gitIn, readGitIdentity } from "../adapters/git.ts";
7
+ import { listHopeSkills } from "../config/load.ts";
8
+ import { HumConfig } from "../config/schema.ts";
9
+ import { CommandTimedOut, exec, SHIPPED_COMMAND_TIMEOUT_MS } from "../exec.ts";
10
+ import { readSettings } from "../config/settings.ts";
11
+ import { kindCoverage, proposeSetup } from "../setup/propose.ts";
12
+ import { proveSetup, type Step } from "../setup/prove.ts";
13
+ import { scanRepo } from "../setup/scan.ts";
14
+ import { shippedConfig } from "../setup/shipped.ts";
15
+ import { waitsOf } from "../setup/waits.ts";
16
+ import { readAnswers, writeSetup } from "../setup/write.ts";
17
+ import type { Io } from "./ops.ts";
18
+ import { hopeRoot } from "./service.ts";
19
+
20
+ const EXIT_OK = 0;
21
+ const EXIT_FAILED = 1;
22
+
23
+ const DEFAULT_BASE = "main";
24
+
25
+ const GH_LIST_LIMIT = "200";
26
+
27
+ const GhIssues = z.array(z.object({ body: z.string().default(""), labels: z.array(z.object({ name: z.string() })).default([]) }));
28
+
29
+ const GhLabels = z.array(z.object({ name: z.string() }));
30
+
31
+ const EVAL_SCRIPT = join(import.meta.dir, "..", "..", "scripts", "eval.ts");
32
+
33
+ type GithubFacts = {
34
+ readonly items: readonly Pick<Item, "body" | "labels">[];
35
+ readonly labels: readonly string[];
36
+ /** Whether the repo lets a workflow open pull requests; off, a CI run cannot open one at all. */
37
+ readonly workflowsMayOpenPullRequests: boolean;
38
+ };
39
+
40
+ const WorkflowPermissions = z.object({ can_approve_pull_request_reviews: z.boolean() });
41
+
42
+ /** Setup reads before any `hum.json` is written, so its commands run on the shipped time limit. */
43
+ const setupGit = (repo: string) => gitIn(repo, { timeoutMs: SHIPPED_COMMAND_TIMEOUT_MS });
44
+
45
+ /** `gh` in the repo, or nothing where `gh` is not installed; a `gh` that outruns its limit is an error. */
46
+ const gh = async (repo: string, args: readonly string[]) => {
47
+ try {
48
+ return await exec("gh", args, { throwOnError: false, timeoutMs: SHIPPED_COMMAND_TIMEOUT_MS, nodeOptions: { cwd: repo } });
49
+ } catch (error) {
50
+ if (error instanceof CommandTimedOut) throw error;
51
+
52
+ return undefined;
53
+ }
54
+ };
55
+
56
+ /** The repo's open issues and its label names, from `gh`. Without `gh` or a GitHub remote there are none, and the scan prints no coverage. */
57
+ const githubFacts = async (repo: string): Promise<GithubFacts | undefined> => {
58
+ const issues = await gh(repo, ["issue", "list", "--state", "open", "--limit", GH_LIST_LIMIT, "--json", "body,labels"]);
59
+ const labels = await gh(repo, ["label", "list", "--limit", GH_LIST_LIMIT, "--json", "name"]);
60
+
61
+ const permissions = await gh(repo, ["api", "repos/{owner}/{repo}/actions/permissions/workflow"]);
62
+
63
+ if (issues?.exitCode !== 0 || labels?.exitCode !== 0 || permissions?.exitCode !== 0) return undefined;
64
+
65
+ return {
66
+ items: GhIssues.parse(JSON.parse(issues.stdout)).map(({ body, labels: on }) => ({ body, labels: on.map(({ name }) => name) })),
67
+ labels: GhLabels.parse(JSON.parse(labels.stdout)).map(({ name }) => name),
68
+ workflowsMayOpenPullRequests: WorkflowPermissions.parse(JSON.parse(permissions.stdout)).can_approve_pull_request_reviews,
69
+ };
70
+ };
71
+
72
+ const printStep = ({ name, status, detail, ms }: Step): string => `${status.padEnd(7)} ${name} (${ms} ms): ${detail}`;
73
+
74
+ const ModelSettings = z.looseObject({ models: HumConfig.shape.models, decisionModel: HumConfig.shape.decisionModel });
75
+
76
+ /** The distinct model ids the owner's tiers and cheap call run on. */
77
+ const modelsOf = (repo: string): string[] => {
78
+ const { models, decisionModel } = readSettings(repo, ModelSettings);
79
+
80
+ return [...new Set([...Object.values(models), decisionModel])];
81
+ };
82
+
83
+ /** `hum setup scan | write | prove | measure`: the facts and writes behind the /hum skill. */
84
+ export const addSetupCommands = (root: Command, io: Io, done: (code: number) => void): void => {
85
+ const setup = root.command("setup").description("What the /hum skill calls: read the repo, write .hum/, prove it, measure the owner's models.");
86
+
87
+ setup
88
+ .command("scan")
89
+ .description("Read the repo and print what setup proposes: checks, paths, data and secrets globs, kind labels, the slot recipe, and a timeout question per wait.")
90
+ .option("--base <branch>", "the branch items merge into", DEFAULT_BASE)
91
+ .action(async ({ base }: { base: string }) => {
92
+ const shipped = shippedConfig();
93
+ const scan = await scanRepo(io.cwd, base);
94
+ const facts = await githubFacts(io.cwd);
95
+ const proposal = proposeSetup(scan, shipped.hum, facts?.labels);
96
+ const { tracked, folders, ...shown } = scan;
97
+ const coverage = facts && kindCoverage(facts.items, shipped.hum.kinds, proposal.kindLabels);
98
+ const gitIdentity = await readGitIdentity(setupGit(io.cwd));
99
+
100
+ io.stdout(`${JSON.stringify({ scan: { ...shown, trackedFiles: tracked.length, folders: folders.map(({ folder, changes }) => ({ folder, changes })) }, proposal, waits: waitsOf(shipped.kinds), coverage: coverage ?? null, workflowsMayOpenPullRequests: facts?.workflowsMayOpenPullRequests ?? null, gitIdentity }, null, "\t")}\n`);
101
+ });
102
+
103
+ setup
104
+ .command("write")
105
+ .description("Write .hum/ and the service files from the answers file, or write nothing and say why.")
106
+ .requiredOption("--answers <file>", 'JSON: { "hum": {settings}, "waitHours": { "kind/state": hours }, "schemaVersion": 1 }')
107
+ .option("--home <folder>", "where the service unit goes; default the user's home")
108
+ .action(async ({ answers, home }: { answers: string; home?: string }) => {
109
+ const result = writeSetup(io.cwd, readAnswers(answers), { hopeSkills: listHopeSkills(await hopeRoot()), home, gitIdentity: await readGitIdentity(setupGit(io.cwd)) });
110
+
111
+ io.stdout(`${JSON.stringify(result.ok ? { written: result.written } : { refused: result.refusal.message }, null, "\t")}\n`);
112
+ done(result.ok ? EXIT_OK : EXIT_FAILED);
113
+ });
114
+
115
+ setup
116
+ .command("prove")
117
+ .description("Prove the written setup: config checks, each check alone, the contract suite, the pinned engine, one slot, and with --item one item end to end.")
118
+ .option("--base <branch>", "the branch items merge into", DEFAULT_BASE)
119
+ .option("--item", "run one item through the real claude on a scratch copy; spends live calls")
120
+ .action(async ({ base, item }: { base: string; item?: true }) => {
121
+ const steps = await proveSetup(io.cwd, { hopeSkills: listHopeSkills(await hopeRoot()), base, item: item === true });
122
+
123
+ io.stdout(`${steps.map(printStep).join("\n")}\n`);
124
+ done(steps.some(({ status }) => status === "failed") ? EXIT_FAILED : EXIT_OK);
125
+ });
126
+
127
+ setup
128
+ .command("measure")
129
+ .description("Measure the owner's models on every labelled set and record the pooled rates in .hum/hum.json.")
130
+ .option("--runs <n>", "runs pooled per boundary", "3")
131
+ .option("--model <id...>", "model ids to measure; default every model the tiers and the cheap call use")
132
+ .action(async ({ runs, model }: { runs: string; model?: string[] }) => {
133
+ for (const id of model ?? modelsOf(io.cwd)) {
134
+ const ran = await x(process.execPath, [EVAL_SCRIPT, "--model", id, "--runs", runs, "--write", join(io.cwd, ".hum")], { throwOnError: false, nodeOptions: { stdio: "inherit" } });
135
+
136
+ if (ran.exitCode !== 0) return done(EXIT_FAILED);
137
+ }
138
+
139
+ done(EXIT_OK);
140
+ });
141
+ };
@@ -0,0 +1,127 @@
1
+ import { mkdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { lock } from "proper-lockfile";
4
+ import { z } from "zod";
5
+ import type { Watch } from "../adapter-api.ts";
6
+ import { atomicWrite, hasCode, orMissing, readJson } from "../state/fs.ts";
7
+
8
+ const Outcome = z.discriminatedUnion("kind", [
9
+ z.strictObject({ kind: z.literal("read"), changed: z.boolean() }),
10
+ z.strictObject({ kind: z.literal("failed"), cause: z.string().min(1) }),
11
+ ]);
12
+
13
+ /** The last read of what changed, kept for every `hum watch` in the repo. The token is the last one a read returned. */
14
+ export const SavedWatch = z.strictObject({
15
+ token: z.string().optional(),
16
+ checkedAt: z.number().int().nonnegative(),
17
+ outcome: Outcome,
18
+ });
19
+
20
+ export type SavedWatch = z.infer<typeof SavedWatch>;
21
+
22
+ export type SharedWatchOptions = {
23
+ readonly stateDir: string;
24
+ readonly now: () => number;
25
+ /** How long one read serves every caller. */
26
+ readonly cacheMs: number;
27
+ /** How long the reader's lock stands before another caller may take it over. */
28
+ readonly lockMs: number;
29
+ /** The one read of the work source, from the token the last read returned. */
30
+ readonly read: (since: string | undefined) => Promise<Watch>;
31
+ /** Called once per read that saw a change, so the worker reads now instead of on its next tick. */
32
+ readonly changed: () => void;
33
+ };
34
+
35
+ const cachePath = (stateDir: string): string => join(stateDir, "watch.json");
36
+
37
+ const lockPath = (stateDir: string): string => join(stateDir, "watch.lock");
38
+
39
+ export const loadSavedWatch = (stateDir: string): SavedWatch | undefined =>
40
+ orMissing(() => SavedWatch.parse(readJson(cachePath(stateDir))), undefined);
41
+
42
+ const save = (stateDir: string, saved: SavedWatch): void =>
43
+ atomicWrite(cachePath(stateDir), `${JSON.stringify(saved)}\n`);
44
+
45
+ /** The saved read while it still serves callers; none once it is older than `cacheMs`. */
46
+ const servable = (
47
+ saved: SavedWatch | undefined,
48
+ now: number,
49
+ cacheMs: number,
50
+ ): SavedWatch | undefined => saved !== undefined && now - saved.checkedAt < cacheMs ? saved : undefined;
51
+
52
+ /** What a saved read answers a caller: the same change, or the same failure. */
53
+ const replay = (saved: SavedWatch): Watch => {
54
+ if (saved.outcome.kind === "failed") throw new Error(saved.outcome.cause);
55
+
56
+ return { token: saved.token ?? "", changed: saved.outcome.changed };
57
+ };
58
+
59
+ /** proper-lockfile refuses a staleness under two seconds. */
60
+ const STALE_FLOOR_MS = 2000;
61
+
62
+ /**
63
+ * One read of what changed serves every caller in the repo for `cacheMs`. Only the caller holding the lock reads;
64
+ * the others answer from the saved read. A lock left by a reader that died stands for `lockMs`, then goes.
65
+ */
66
+ export async function sharedWatch(o: SharedWatchOptions): Promise<Watch> {
67
+ const before = loadSavedWatch(o.stateDir);
68
+
69
+ const served = servable(before, o.now(), o.cacheMs);
70
+
71
+ if (served !== undefined) return replay(served);
72
+
73
+ mkdirSync(o.stateDir, { recursive: true });
74
+
75
+ const release = await lock(o.stateDir, {
76
+ lockfilePath: lockPath(o.stateDir),
77
+ realpath: false,
78
+ retries: 0,
79
+ stale: Math.max(o.lockMs, STALE_FLOOR_MS),
80
+ }).catch((error: Error) => {
81
+ if (hasCode(error, "ELOCKED")) return undefined;
82
+
83
+ throw error;
84
+ });
85
+
86
+ if (release === undefined) {
87
+ if (before === undefined)
88
+ throw new Error(
89
+ "another hum watch is making the first read; ask again shortly",
90
+ );
91
+
92
+ return replay(before);
93
+ }
94
+
95
+ try {
96
+ const saved = loadSavedWatch(o.stateDir);
97
+
98
+ const servedMeanwhile = servable(saved, o.now(), o.cacheMs);
99
+
100
+ if (servedMeanwhile !== undefined) return replay(servedMeanwhile);
101
+
102
+ const read = await o.read(saved?.token).catch((error: Error) => {
103
+ save(o.stateDir, {
104
+ token: saved?.token,
105
+ checkedAt: o.now(),
106
+ outcome: {
107
+ kind: "failed",
108
+ cause: error.message,
109
+ },
110
+ });
111
+
112
+ throw error;
113
+ });
114
+
115
+ save(o.stateDir, {
116
+ token: read.token,
117
+ checkedAt: o.now(),
118
+ outcome: { kind: "read", changed: read.changed },
119
+ });
120
+
121
+ if (read.changed) o.changed();
122
+
123
+ return read;
124
+ } finally {
125
+ await release();
126
+ }
127
+ }
@@ -0,0 +1,54 @@
1
+ import type { Refusal } from "./refusal.ts";
2
+ import { type Config, type LoadOptions, loadConfig, type RawConfig } from "./load.ts";
3
+ import { type Naming, SHIPPED_DEFAULTS } from "./schema.ts";
4
+ import { type SavedItem, unmappedItems } from "./state-map.ts";
5
+
6
+ /** A branch hum itself writes: a run's or a claim's. */
7
+ export const isHumBranch = (branch: string, { runBranchPrefix, claimPrefix }: Naming): boolean =>
8
+ [runBranchPrefix, claimPrefix].some((prefix) => branch.startsWith(prefix));
9
+
10
+ export type ConfigChange = {
11
+ readonly candidate: RawConfig;
12
+ /** The branch the change sits on. */
13
+ readonly branch: string;
14
+ /** Items saved now, so a removed or renamed state can be checked. */
15
+ readonly saved?: readonly SavedItem[];
16
+ };
17
+
18
+ /** Accepted: `config` is the new one. Refused: `config` is the last good one, untouched. */
19
+ export type ConfigResult =
20
+ | { readonly accepted: true; readonly config: Config }
21
+ | { readonly accepted: false; readonly config: Config | undefined; readonly refusals: readonly Refusal[] };
22
+
23
+ /**
24
+ * One path for start and for every change. Refuses a change from a branch hum writes, judged by the last good
25
+ * config's prefixes so a change cannot rename its own way out; a config that fails a check; and a state map
26
+ * that strands a saved item.
27
+ */
28
+ export const applyConfigChange = (current: Config | undefined, change: ConfigChange, options: LoadOptions): ConfigResult => {
29
+ const refuse = (...refusals: Refusal[]): ConfigResult => ({ accepted: false, config: current, refusals });
30
+
31
+ if (isHumBranch(change.branch, current?.hum ?? SHIPPED_DEFAULTS)) {
32
+ return refuse({
33
+ code: "change-from-run",
34
+ branch: change.branch,
35
+ message: `The config change came from a branch hum writes, "${change.branch}". Only the owner changes hum; the last good config stays.`,
36
+ });
37
+ }
38
+
39
+ const loaded = loadConfig(change.candidate, options);
40
+
41
+ if (!loaded.ok) return refuse(loaded.refusal);
42
+ const stranded = current ? unmappedItems(current, loaded.value, change.saved ?? []) : [];
43
+
44
+ if (stranded.length > 0) {
45
+ return refuse({
46
+ code: "unmapped-state",
47
+ items: stranded,
48
+ message: `Saved items sit in states the new config removes with no map: ${stranded.map((i) => `${i.kind}/${i.state}`).join(", ")}. Add a stateMap for the earlier version.`,
49
+ });
50
+ }
51
+
52
+ return { accepted: true, config: loaded.value };
53
+ };
54
+
@@ -0,0 +1,217 @@
1
+ import { toDirectedGraph } from "xstate/graph";
2
+ import { kindMachine } from "./machine.ts";
3
+ import type { Problem } from "./refusal.ts";
4
+ import {
5
+ FIXED_PARTS,
6
+ type HumConfig,
7
+ type Kind,
8
+ type Naming,
9
+ OWNER_WAIT_TAG,
10
+ type PathRule,
11
+ SIZES,
12
+ STUCK_TAG,
13
+ type StateNodeJSON,
14
+ WAIT_TAG,
15
+ } from "./schema.ts";
16
+
17
+ /** What the checks read besides the config: hope's installed skills, by bare name (`intent`, not `hope:intent`). */
18
+ export type CheckEnv = { readonly hopeSkills: ReadonlySet<string> };
19
+
20
+ type Transitions = StateNodeJSON["onTimeout"];
21
+
22
+ const FIXED = new Set<string>(FIXED_PARTS);
23
+
24
+ const isWait = (node: StateNodeJSON) => node.tags?.includes(WAIT_TAG) || node.tags?.includes(OWNER_WAIT_TAG);
25
+ const isTerminal = (node: StateNodeJSON) => node.type === "final" || node.tags?.includes(STUCK_TAG);
26
+
27
+ const settles = (value: Transitions) =>
28
+ (value ?? []).some((t) => t.target !== undefined || (t.actions?.length ?? 0) > 0);
29
+
30
+ /** Every state is reachable and reaches done or stuck; every wait has a timeout and an action. */
31
+ const graphProblems = (kind: string, config: Kind): Problem[] => {
32
+ const { states, initial } = config.machine;
33
+ const graph = toDirectedGraph(kindMachine(config));
34
+ const forward = new Map<string, string[]>();
35
+ const backward = new Map<string, string[]>();
36
+
37
+ for (const node of graph.children) {
38
+ for (const edge of node.edges) {
39
+ forward.set(edge.source.key, [...(forward.get(edge.source.key) ?? []), edge.target.key]);
40
+ backward.set(edge.target.key, [...(backward.get(edge.target.key) ?? []), edge.source.key]);
41
+ }
42
+ }
43
+
44
+ const walk = (from: Iterable<string>, edges: Map<string, string[]>) => {
45
+ const seen = new Set<string>(from);
46
+ const todo = [...seen];
47
+
48
+ for (let key = todo.pop(); key !== undefined; key = todo.pop()) {
49
+ for (const next of edges.get(key) ?? []) {
50
+ if (seen.has(next)) continue;
51
+
52
+ seen.add(next);
53
+ todo.push(next);
54
+ }
55
+ }
56
+
57
+ return seen;
58
+ };
59
+
60
+ const reachable = walk([initial], forward);
61
+
62
+ const finishing = walk(
63
+ Object.entries(states).flatMap(([name, node]) => (isTerminal(node) ? [name] : [])),
64
+ backward,
65
+ );
66
+
67
+ return Object.entries(states).flatMap(([state, node]): Problem[] => [
68
+ ...(reachable.has(state) ? [] : [{ problem: "unreachable-state", kind, state } as const]),
69
+ ...(finishing.has(state) ? [] : [{ problem: "dead-end-state", kind, state } as const]),
70
+ ...(isWait(node) && !(settles(node.onTimeout) && node.timeout !== undefined) && !Object.values(node.after ?? {}).some(settles)
71
+ ? [{ problem: "wait-without-timeout", kind, state } as const]
72
+ : []),
73
+ ]);
74
+ };
75
+
76
+ const kindProblems = (kind: string, config: Kind, hum: HumConfig): Problem[] => {
77
+ const { states } = config.machine;
78
+ const problems: Problem[] = [];
79
+
80
+ if (!(config.tokenCap.overCap in states)) {
81
+ problems.push({ problem: "unknown-state", kind, state: config.tokenCap.overCap, why: "tokenCap.overCap" });
82
+ }
83
+
84
+ const purposes = new Set<string>();
85
+
86
+ for (const [state, node] of Object.entries(states)) {
87
+ if (node.invoke) {
88
+ const role = hum.roles[node.invoke.src];
89
+
90
+ if (role) purposes.add(role.purpose);
91
+ else if (!FIXED.has(node.invoke.src)) {
92
+ problems.push({ problem: "unknown-run-source", kind, state, src: node.invoke.src });
93
+ }
94
+
95
+ if (role && node.tags?.includes(OWNER_WAIT_TAG)) {
96
+ problems.push({ problem: "run-and-owner-wait", kind, state });
97
+ }
98
+ }
99
+ }
100
+
101
+ const levels = levelNames(hum);
102
+
103
+ for (const row of config.tiers) {
104
+ if (row.level !== undefined && !levels.has(row.level)) {
105
+ problems.push({ problem: "unknown-level", level: row.level });
106
+ }
107
+ }
108
+
109
+ for (const purpose of purposes) {
110
+ for (const level of levels) {
111
+ for (const size of SIZES) {
112
+ if (!pickTier(config, { purpose, level, size })) {
113
+ problems.push({ problem: "tier-table-gap", kind, purpose, level, size });
114
+ }
115
+ }
116
+ }
117
+ }
118
+
119
+ try {
120
+ kindMachine(config);
121
+ } catch (error) {
122
+ return [...problems, { problem: "machine-rejected", kind, why: error instanceof Error ? error.message : String(error) }];
123
+ }
124
+
125
+ return [...problems, ...graphProblems(kind, config)];
126
+ };
127
+
128
+ /** The most specific tier row for a run, or undefined when the table has a gap. */
129
+ export const pickTier = (kind: Pick<Kind, "tiers">, key: { purpose: string; level: string; size: string }) =>
130
+ kind.tiers
131
+ .filter(
132
+ (row) =>
133
+ row.purpose === key.purpose &&
134
+ (row.level === undefined || row.level === key.level) &&
135
+ (row.size === undefined || row.size === key.size),
136
+ )
137
+ .sort((a, b) => Number(b.level !== undefined) + Number(b.size !== undefined) - (Number(a.level !== undefined) + Number(a.size !== undefined)))[0];
138
+
139
+ /** Every event has a source and a handler, and every event a machine waits on has a source. */
140
+ const eventProblems = (hum: HumConfig, kinds: Readonly<Record<string, Kind>>): Problem[] => {
141
+ const parts = new Set<string>([...FIXED_PARTS, ...Object.keys(hum.roles)]);
142
+ const handled = new Set<string>();
143
+
144
+ for (const kind of Object.values(kinds)) {
145
+ for (const node of Object.values(kind.machine.states)) {
146
+ for (const event of Object.keys(node.on ?? {})) handled.add(event);
147
+ }
148
+ }
149
+
150
+ return [
151
+ ...Object.entries(hum.events).flatMap(([event, { source }]): Problem[] => [
152
+ ...(parts.has(source) ? [] : [{ problem: "event-without-source", event, source } as const]),
153
+ ...(handled.has(event) ? [] : [{ problem: "event-without-handler", event } as const]),
154
+ ]),
155
+ ...[...handled].flatMap((event): Problem[] =>
156
+ event in hum.events || event.startsWith("xstate.") || event.startsWith("@xstate.")
157
+ ? []
158
+ : [{ problem: "event-without-source", event, source: undefined }],
159
+ ),
160
+ ];
161
+ };
162
+
163
+ /** Each `hope:<skill>` a role names exists in hope's installed copy. */
164
+ const skillProblems = (hum: HumConfig, env: CheckEnv): Problem[] =>
165
+ Object.entries(hum.roles).flatMap(([role, { skills }]) =>
166
+ skills.flatMap((skill): Problem[] =>
167
+ skill.startsWith("hope:") && !env.hopeSkills.has(skill.slice("hope:".length))
168
+ ? [{ problem: "missing-hope-skill", skill, role }]
169
+ : [],
170
+ ),
171
+ );
172
+
173
+ /** A run branch could then share a name, or a folder, with a claim branch. */
174
+ const prefixesOverlap = ({ runBranchPrefix, claimPrefix }: Naming): boolean =>
175
+ runBranchPrefix.startsWith(claimPrefix) || claimPrefix.startsWith(runBranchPrefix);
176
+
177
+ const namingProblems = (hum: HumConfig): Problem[] =>
178
+ prefixesOverlap(hum) ? [{ problem: "overlapping-prefixes", run: hum.runBranchPrefix, claim: hum.claimPrefix }] : [];
179
+
180
+ const levelNames = (hum: HumConfig): ReadonlySet<string> => new Set(hum.levels.map(({ name }) => name));
181
+
182
+ const ALL_KINDS = "*";
183
+
184
+ /** A path whose level releases only after proof names a proof for every kind, or for each kind there is. */
185
+ const provesEveryKind = (rule: PathRule, kinds: readonly string[]): boolean =>
186
+ rule.proofs?.[ALL_KINDS] !== undefined || kinds.every((kind) => rule.proofs?.[kind] !== undefined);
187
+
188
+ const pathProblems = (hum: HumConfig): Problem[] => {
189
+ const levels = levelNames(hum);
190
+ const afterProof = new Set(hum.levels.filter(({ release }) => release === "after-proof").map(({ name }) => name));
191
+
192
+ return [
193
+ ...[...hum.paths, ...hum.launches, ...Object.values(hum.kindFloors).map((level) => ({ level }))].flatMap(({ level }): Problem[] => (levels.has(level) ? [] : [{ problem: "unknown-level", level }])),
194
+ ...hum.paths.flatMap((rule): Problem[] =>
195
+ afterProof.has(rule.level) && !provesEveryKind(rule, hum.kinds) ? [{ problem: "path-without-proof", glob: rule.glob, level: rule.level }] : [],
196
+ ),
197
+ ];
198
+ };
199
+
200
+ /** The proof a path names for a kind: its own, else the one for every kind. */
201
+ export const proofFor = (rule: PathRule, kind: string): string | undefined => rule.proofs?.[kind] ?? rule.proofs?.[ALL_KINDS];
202
+
203
+ /** Every config check at start and on every change; returns all problems found. */
204
+ export const checkConfig = (
205
+ hum: HumConfig,
206
+ kinds: Readonly<Record<string, Kind>>,
207
+ roleFiles: ReadonlySet<string>,
208
+ env: CheckEnv,
209
+ ): Problem[] => [
210
+ ...Object.values(hum.roles)
211
+ .flatMap(({ file }): Problem[] => (roleFiles.has(file) ? [] : [{ problem: "missing-file", file }])),
212
+ ...pathProblems(hum),
213
+ ...Object.entries(kinds).flatMap(([name, kind]) => kindProblems(name, kind, hum)),
214
+ ...eventProblems(hum, kinds),
215
+ ...skillProblems(hum, env),
216
+ ...namingProblems(hum),
217
+ ];
@@ -0,0 +1,3 @@
1
+ declare module "is-git-ref-name-valid" {
2
+ export default function isGitRefNameValid(name: string, oneLevel?: boolean): boolean;
3
+ }
@@ -0,0 +1,6 @@
1
+ import { createHash } from "node:crypto";
2
+ import stringify from "safe-stable-stringify";
3
+ import type { Json } from "./json.ts";
4
+
5
+ /** SHA-256 of the JSON with object keys sorted at every depth, so key order never changes it. */
6
+ export const hashJson = (value: Json): string => createHash("sha256").update(stringify(value)).digest("hex");
@@ -0,0 +1,6 @@
1
+ import { z } from "zod";
2
+
3
+ /** Any JSON value; the type of config read from disk before it is parsed. */
4
+ export const Json = z.json();
5
+
6
+ export type Json = z.infer<typeof Json>;
@@ -0,0 +1,88 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { basename, dirname, join } from "node:path";
3
+ import { z } from "zod";
4
+ import { type CheckEnv, checkConfig } from "./checks.ts";
5
+ import { hashJson } from "./hash.ts";
6
+ import { type Migrations, migrateConfig } from "./migrate.ts";
7
+ import { invalidConfig, type Problem, type Result } from "./refusal.ts";
8
+ import { orMissing, readJson } from "../state/fs.ts";
9
+ import { Json } from "./json.ts";
10
+ import { HumConfig, Kind } from "./schema.ts";
11
+
12
+ /** A config as read from disk, before any check: `.hum/` files by their path. */
13
+ export type RawConfig = {
14
+ readonly hum: Json;
15
+ /** `kinds/<name>.json` contents, keyed by `<name>`. */
16
+ readonly kinds: Readonly<Record<string, Json>>;
17
+ /** `roles/<name>.md` contents, keyed by `roles/<name>.md`. */
18
+ readonly roles: Readonly<Record<string, string>>;
19
+ };
20
+
21
+ /** A config that passed every check. */
22
+ export type Config = {
23
+ readonly hum: HumConfig;
24
+ readonly kinds: Readonly<Record<string, Kind>>;
25
+ readonly roles: Readonly<Record<string, string>>;
26
+ /** Same hash for the same content, whatever the key order. */
27
+ readonly hash: string;
28
+ };
29
+
30
+ export type LoadOptions = { readonly env: CheckEnv; readonly migrations?: Migrations; readonly current?: number; readonly readable?: readonly number[] };
31
+
32
+ const malformed = (where: string, error: z.ZodError): Result<never> => ({
33
+ ok: false,
34
+ refusal: { code: "malformed-config", where, message: `${where} is malformed:\n${z.prettifyError(error)}` },
35
+ });
36
+
37
+ /** Migrates, parses and checks a config. Refuses with one typed value; never throws on bad input. */
38
+ export const loadConfig = (raw: RawConfig, { env, ...migration }: LoadOptions): Result<Config> => {
39
+ const migrated = migrateConfig(raw.hum, migration);
40
+
41
+ if (!migrated.ok) return migrated;
42
+ const hum = HumConfig.safeParse(migrated.value);
43
+
44
+ if (!hum.success) return malformed("hum.json", hum.error);
45
+
46
+ const kinds: Record<string, Kind> = {};
47
+ const listed: Record<string, Json> = {};
48
+ const missing: Problem[] = [];
49
+
50
+ for (const name of hum.data.kinds) {
51
+ const file = raw.kinds[name];
52
+
53
+ if (file === undefined) {
54
+ missing.push({ problem: "missing-file", file: `kinds/${name}.json` });
55
+ continue;
56
+ }
57
+
58
+ const kind = Kind.safeParse(file);
59
+
60
+ if (!kind.success) return malformed(`kinds/${name}.json`, kind.error);
61
+ kinds[name] = kind.data;
62
+ listed[name] = file;
63
+ }
64
+
65
+ const problems = [...missing, ...checkConfig(hum.data, kinds, new Set(Object.keys(raw.roles)), env)];
66
+
67
+ if (problems.length > 0) return { ok: false, refusal: invalidConfig(problems) };
68
+
69
+ return {
70
+ ok: true,
71
+ value: { hum: hum.data, kinds, roles: raw.roles, hash: hashJson({ hum: migrated.value, kinds: listed, roles: raw.roles }) },
72
+ };
73
+ };
74
+
75
+ const scan = (pattern: string, cwd: string): string[] => orMissing(() => [...new Bun.Glob(pattern).scanSync({ cwd, onlyFiles: true })].sort(), []);
76
+
77
+ const filesIn = (folder: string, extension: string): string[] => scan(`*${extension}`, folder);
78
+
79
+ /** Reads `hum.json`, `kinds/*.json` and `roles/*.md` from a `.hum/`-shaped folder. */
80
+ export const readConfigDir = (dir: string): RawConfig => ({
81
+ hum: readJson(join(dir, "hum.json")),
82
+ kinds: Object.fromEntries(filesIn(join(dir, "kinds"), ".json").map((file) => [basename(file, ".json"), readJson(join(dir, "kinds", file))])),
83
+ roles: Object.fromEntries(filesIn(join(dir, "roles"), ".md").map((file) => [`roles/${file}`, readFileSync(join(dir, "roles", file), "utf8")])),
84
+ });
85
+
86
+ /** The skill names (`intent`, not `hope:intent`) in a hope plugin folder's `skills/*\/SKILL.md`. */
87
+ export const listHopeSkills = (hopeRoot: string): ReadonlySet<string> =>
88
+ new Set(scan("*/SKILL.md", join(hopeRoot, "skills")).map((file) => dirname(file)));
@@ -0,0 +1,20 @@
1
+ import { type AnyActorLogic, type AnyStateMachine, createAsyncLogic, machineFromJSON } from "xstate";
2
+ import type { Kind } from "./schema.ts";
3
+
4
+ const placeholder = createAsyncLogic({ run: async () => {} });
5
+
6
+ /**
7
+ * A kind's machine. `machineFromJSON` needs an actor for every `invoke.src`; any
8
+ * `sources` not given stand in as placeholders, which is enough to check the graph.
9
+ * Throws with xstate's message when the machine is illegal.
10
+ */
11
+ export const kindMachine = (kind: Kind, sources: Readonly<Record<string, AnyActorLogic>> = {}): AnyStateMachine => {
12
+ const actors: Record<string, AnyActorLogic> = {};
13
+
14
+ for (const node of Object.values(kind.machine.states)) {
15
+ if (node.invoke) actors[node.invoke.src] = sources[node.invoke.src] ?? placeholder;
16
+ }
17
+
18
+ // SAFETY: the zod machine schema is a subset of xstate's MachineJSON, and machineFromJSON validates the rest.
19
+ return machineFromJSON(kind.machine as Parameters<typeof machineFromJSON>[0], { actors });
20
+ };