@moo.md/hum 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +392 -0
- package/src/adapters/claude-p.ts +599 -0
- package/src/adapters/contract.ts +231 -0
- package/src/adapters/fake.ts +157 -0
- package/src/adapters/git.ts +156 -0
- package/src/adapters/github.ts +479 -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 +127 -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 +293 -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 +85 -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 +195 -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 +45 -0
- package/src/worker/checks.ts +40 -0
- package/src/worker/kind.ts +68 -0
- package/src/worker/land.ts +509 -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 +750 -0
- package/surface.json +8787 -0
- package/README.md +0 -3
|
@@ -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,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,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
|
+
};
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { Json } from "./json.ts";
|
|
3
|
+
import { READABLE_SCHEMA_VERSIONS, SCHEMA_VERSION } from "./schema.ts";
|
|
4
|
+
import type { Result } from "./refusal.ts";
|
|
5
|
+
|
|
6
|
+
type ConfigJson = Readonly<Record<string, Json>>;
|
|
7
|
+
|
|
8
|
+
/** Per earlier version: rewrites a value at that version into the next version's shape. */
|
|
9
|
+
export type Steps<T> = Readonly<Record<number, (value: T) => T>>;
|
|
10
|
+
|
|
11
|
+
/** Applies each step from version `from` up to `to`, stamping the version under `versionKey`. A missing step is an engine bug and throws. */
|
|
12
|
+
export const climb = <T extends object>(value: T, from: number, to: number, steps: Steps<T>, versionKey: string): T =>
|
|
13
|
+
Array.from({ length: Math.max(to - from, 0) }, (_, offset) => from + offset).reduce((current, at) => {
|
|
14
|
+
const step = steps[at];
|
|
15
|
+
|
|
16
|
+
if (!step) throw new Error(`no migration from ${versionKey} ${at}; the engine ships a gap`);
|
|
17
|
+
|
|
18
|
+
return { ...step(current), [versionKey]: at + 1 };
|
|
19
|
+
}, value);
|
|
20
|
+
|
|
21
|
+
/** Per earlier schema version: rewrites a config at that version into the next version's shape. */
|
|
22
|
+
export type Migrations = Steps<ConfigJson>;
|
|
23
|
+
|
|
24
|
+
/** One entry per earlier schema version. Empty while version 1 is the first. */
|
|
25
|
+
export const MIGRATIONS: Migrations = {};
|
|
26
|
+
|
|
27
|
+
const Raw = z.record(z.string(), Json);
|
|
28
|
+
const Version = z.int();
|
|
29
|
+
|
|
30
|
+
/** Reads `schemaVersion` and migrates the config up to `current`, or refuses a version it does not read. */
|
|
31
|
+
export const migrateConfig = (
|
|
32
|
+
raw: Json,
|
|
33
|
+
{
|
|
34
|
+
current = SCHEMA_VERSION,
|
|
35
|
+
readable = READABLE_SCHEMA_VERSIONS,
|
|
36
|
+
migrations = MIGRATIONS,
|
|
37
|
+
}: { current?: number; readable?: readonly number[]; migrations?: Migrations } = {},
|
|
38
|
+
): Result<ConfigJson> => {
|
|
39
|
+
const parsed = Raw.safeParse(raw);
|
|
40
|
+
const version = parsed.success ? Version.safeParse(parsed.data.schemaVersion) : undefined;
|
|
41
|
+
const found = version?.success ? version.data : undefined;
|
|
42
|
+
|
|
43
|
+
if (!parsed.success || found === undefined || !readable.includes(found)) {
|
|
44
|
+
const step =
|
|
45
|
+
found !== undefined && found > current
|
|
46
|
+
? "Update the engine: bun add --exact @moo.md/hum@latest."
|
|
47
|
+
: "Run /hum to rewrite it.";
|
|
48
|
+
|
|
49
|
+
return {
|
|
50
|
+
ok: false,
|
|
51
|
+
refusal: {
|
|
52
|
+
code: "unknown-schema-version",
|
|
53
|
+
found,
|
|
54
|
+
readable,
|
|
55
|
+
message: `hum.json schemaVersion ${found ?? "missing"} is not one this engine reads (reads ${readable.join(", ")}). ${step}`,
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return { ok: true, value: climb(parsed.data, found, current, migrations, "schemaVersion") };
|
|
61
|
+
};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/** One thing a config check found wrong. */
|
|
2
|
+
export type Problem =
|
|
3
|
+
| { readonly problem: "unreachable-state"; readonly kind: string; readonly state: string }
|
|
4
|
+
| { readonly problem: "dead-end-state"; readonly kind: string; readonly state: string }
|
|
5
|
+
| { readonly problem: "wait-without-timeout"; readonly kind: string; readonly state: string }
|
|
6
|
+
| { readonly problem: "event-without-source"; readonly event: string; readonly source: string | undefined }
|
|
7
|
+
| { readonly problem: "event-without-handler"; readonly event: string }
|
|
8
|
+
| { readonly problem: "run-and-owner-wait"; readonly kind: string; readonly state: string }
|
|
9
|
+
| { readonly problem: "missing-hope-skill"; readonly skill: string; readonly role: string }
|
|
10
|
+
| { readonly problem: "unknown-state"; readonly kind: string; readonly state: string; readonly why: string }
|
|
11
|
+
| { readonly problem: "unknown-run-source"; readonly kind: string; readonly state: string; readonly src: string }
|
|
12
|
+
| { readonly problem: "tier-table-gap"; readonly kind: string; readonly purpose: string; readonly level: string; readonly size: string }
|
|
13
|
+
| { readonly problem: "machine-rejected"; readonly kind: string; readonly why: string }
|
|
14
|
+
| { readonly problem: "missing-file"; readonly file: string }
|
|
15
|
+
| { readonly problem: "unknown-level"; readonly level: string }
|
|
16
|
+
| { readonly problem: "path-without-proof"; readonly glob: string; readonly level: string }
|
|
17
|
+
| { readonly problem: "overlapping-prefixes"; readonly run: string; readonly claim: string };
|
|
18
|
+
|
|
19
|
+
/** A config change the engine will not take. The caller keeps the last good config. */
|
|
20
|
+
export type Refusal =
|
|
21
|
+
| { readonly code: "malformed-config"; readonly where: string; readonly message: string }
|
|
22
|
+
| { readonly code: "unknown-schema-version"; readonly found: number | undefined; readonly readable: readonly number[]; readonly message: string }
|
|
23
|
+
| { readonly code: "invalid-config"; readonly problems: readonly Problem[]; readonly message: string }
|
|
24
|
+
| { readonly code: "unmapped-state"; readonly items: readonly { readonly kind: string; readonly state: string }[]; readonly message: string }
|
|
25
|
+
| { readonly code: "change-from-run"; readonly branch: string; readonly message: string }
|
|
26
|
+
| { readonly code: "no-git-identity"; readonly missing: readonly string[]; readonly message: string };
|
|
27
|
+
|
|
28
|
+
export type Result<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly refusal: Refusal };
|
|
29
|
+
|
|
30
|
+
type Describe = { readonly [Name in Problem["problem"]]: (problem: Extract<Problem, { problem: Name }>) => string };
|
|
31
|
+
|
|
32
|
+
const DESCRIPTIONS = {
|
|
33
|
+
"unreachable-state": (p) => `${p.kind}: state "${p.state}" cannot be reached from the start`,
|
|
34
|
+
"dead-end-state": (p) => `${p.kind}: state "${p.state}" never reaches done or stuck`,
|
|
35
|
+
"wait-without-timeout": (p) => `${p.kind}: wait "${p.state}" has no timeout and timeout action`,
|
|
36
|
+
"event-without-source": (p) =>
|
|
37
|
+
p.source === undefined ? `event "${p.event}" is waited on but declared nowhere` : `event "${p.event}" has no source: "${p.source}" is not a part or role`,
|
|
38
|
+
"event-without-handler": (p) => `event "${p.event}" has no handler in any kind`,
|
|
39
|
+
"run-and-owner-wait": (p) => `${p.kind}: state "${p.state}" starts a run and waits on the owner`,
|
|
40
|
+
"missing-hope-skill": (p) => `role "${p.role}" names hope skill "${p.skill}", which hope's installed copy lacks`,
|
|
41
|
+
"unknown-state": (p) => `${p.kind}: ${p.why} names state "${p.state}", which does not exist`,
|
|
42
|
+
"unknown-run-source": (p) => `${p.kind}: state "${p.state}" invokes "${p.src}", which is neither a role nor a part`,
|
|
43
|
+
"tier-table-gap": (p) => `${p.kind}: no tier for purpose "${p.purpose}", level "${p.level}", size "${p.size}"`,
|
|
44
|
+
"machine-rejected": (p) => `${p.kind}: the machine does not load: ${p.why}`,
|
|
45
|
+
"missing-file": (p) => `file "${p.file}" is missing`,
|
|
46
|
+
"unknown-level": (p) => `risk level "${p.level}" is not in levels`,
|
|
47
|
+
"path-without-proof": (p) => `path "${p.glob}" is at level "${p.level}", whose release waits for proof, and names no proof for every kind`,
|
|
48
|
+
"overlapping-prefixes": (p) => `the run branch prefix "${p.run}" and the claim prefix "${p.claim}" overlap: one starts with the other`,
|
|
49
|
+
} as const satisfies Describe;
|
|
50
|
+
|
|
51
|
+
// SAFETY: each description is keyed by the problem name it reads, so the lookup by `problem.problem` takes its own variant.
|
|
52
|
+
export const describeProblem = (problem: Problem): string => (DESCRIPTIONS[problem.problem] as (problem: Problem) => string)(problem);
|
|
53
|
+
|
|
54
|
+
export const invalidConfig = (problems: readonly Problem[]): Refusal => ({
|
|
55
|
+
code: "invalid-config",
|
|
56
|
+
problems,
|
|
57
|
+
message: `Config refused:\n${problems.map((p) => `- ${describeProblem(p)}`).join("\n")}`,
|
|
58
|
+
});
|