@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,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
+ });
@@ -0,0 +1,465 @@
1
+ import { isValidCron } from "cron-validator";
2
+ import isGitRefNameValid from "is-git-ref-name-valid";
3
+ import { z } from "zod";
4
+ import shippedConfig from "../../defaults/hum.json" with { type: "json" };
5
+
6
+ /** The `hum.json` schema version this engine writes. */
7
+ export const SCHEMA_VERSION = 1;
8
+
9
+ /** The schema versions this engine reads, each migrated up to `SCHEMA_VERSION` by `migrateConfig`. */
10
+ export const READABLE_SCHEMA_VERSIONS: readonly number[] = [1];
11
+
12
+ /** Parts the engine ships; the owner adds roles, never these. */
13
+ export const FIXED_PARTS = [
14
+ "owner",
15
+ "worker",
16
+ "scheduler",
17
+ "checks",
18
+ "work-source",
19
+ "saved-state",
20
+ "service-unit",
21
+ "run-slots",
22
+ "model-call",
23
+ ] as const;
24
+
25
+ export const PURPOSES = ["plan", "build", "fix", "review"] as const;
26
+ export const SIZES = ["small", "medium", "large"] as const;
27
+ export const TIERS = ["light", "standard", "top"] as const;
28
+ export const EFFORTS = ["low", "medium", "high"] as const;
29
+
30
+ /** A machine state tagged with either of these waits on something outside the run. */
31
+ export const WAIT_TAG = "wait";
32
+
33
+ /** A state tagged with this waits on the owner; it is also a wait. */
34
+ export const OWNER_WAIT_TAG = "owner-wait";
35
+
36
+ /** A state tagged with this ends the item without finishing it. */
37
+ export const STUCK_TAG = "stuck";
38
+
39
+ const name = z.string().min(1);
40
+
41
+ /** Any item id appended to a branch prefix; the prefix is valid when the branch it makes is. */
42
+ const SAMPLE_ITEM_ID = "0";
43
+
44
+ const isBranchPrefix = (prefix: string): boolean => isGitRefNameValid(`refs/heads/${prefix}${SAMPLE_ITEM_ID}`);
45
+
46
+ const branchPrefix = z
47
+ .string()
48
+ .endsWith("/", "a branch prefix ends with '/'")
49
+ .refine(isBranchPrefix, "a branch prefix followed by an item id must make a valid git branch name");
50
+
51
+ /** Where hum runs: a service on the owner's Mac, and a scheduled and event-woken CI workflow. */
52
+ export const RUN_PLACES = ["mac", "ci"] as const;
53
+
54
+ export type RunPlace = (typeof RUN_PLACES)[number];
55
+
56
+ export const MERGE_METHODS = ["merge", "squash", "rebase"] as const;
57
+
58
+ export type MergeMethod = (typeof MERGE_METHODS)[number];
59
+
60
+ /** Who reviews a change before it merges: no one, a fresh agent review run, or that run and then the owner. */
61
+ export const REVIEWS = ["none", "agent", "owner"] as const;
62
+
63
+ /** When a merged change ships: at once, or once the proof its path names arrives. */
64
+ export const RELEASES = ["at-once", "after-proof"] as const;
65
+
66
+ /** What a break after merge becomes: follow-up work, or a block on the path. */
67
+ export const BREAKS = ["follow-up", "block"] as const;
68
+
69
+ /** Each place a model's judgment decides, measured on its own labelled set. */
70
+ export const BOUNDARIES = ["kind", "alignment", "plan-outcome", "review-verdict", "reply-option", "repeat-pair", "taste"] as const;
71
+
72
+ export type Boundary = (typeof BOUNDARIES)[number];
73
+
74
+ /** The categories of a change's merge risk, each graded 1 (sound) to 3 (a concern). */
75
+ export const GRADED = ["impact", "verification", "rollback", "errorDetection", "alignment"] as const;
76
+
77
+ const isRegExp = (source: string): boolean => {
78
+ try {
79
+ return new RegExp(source).source.length > 0;
80
+ } catch {
81
+ return false;
82
+ }
83
+ };
84
+
85
+ const pattern = z.string().min(1).refine(isRegExp, "a pattern is a valid regular expression");
86
+
87
+ const date = z.iso.date();
88
+
89
+ /** When a refresh step runs: after every return, or only when a lockfile changed since the slot was last installed. */
90
+ export const REFRESH_WHEN = ["always", "lockfile-changed"] as const;
91
+
92
+ /** Whether a slot gets its own services, or every slot shares one set and gets its own database. */
93
+ export const SLOT_SERVICES = ["per-slot", "shared"] as const;
94
+
95
+ const RefreshStep = z.strictObject({ run: name, when: z.enum(REFRESH_WHEN) });
96
+
97
+ /** The three commands that make a slot usable, each a shell command run in the slot with the slot's environment. */
98
+ export const SlotRecipe = z.strictObject({
99
+ prepare: z.array(name).describe("Run once when a slot is made: install dependencies, start or attach services, seed data."),
100
+ refresh: z.array(RefreshStep).describe("Run after each return, once the slot is reset to the latest base: reinstall when a lockfile changed, reset the data."),
101
+ ready: z.array(name).describe("Run after prepare and each refresh; a slot where one fails leaves the pool."),
102
+ });
103
+
104
+ const seconds = z.int().positive();
105
+
106
+ const count = z.int().positive();
107
+
108
+ const SERVICE_LABEL = /^[A-Za-z0-9._-]+$/;
109
+
110
+ const isInsideRepo = (path: string): boolean => !path.startsWith("/") && !path.endsWith("/") && !path.split("/").includes("..");
111
+
112
+ const commitIdentity = z.strictObject({ name, email: name }, { error: "the owner's own { name, email }; run /hum to write them from your git config" });
113
+
114
+ const backoff = z
115
+ .strictObject({ firstSeconds: z.number().positive(), maxSeconds: z.number().positive() })
116
+ .refine(({ firstSeconds, maxSeconds }) => firstSeconds <= maxSeconds, "the first pause is at most the longest pause");
117
+
118
+ const fraction = z.number().gt(0).lt(1);
119
+
120
+ const Launch = z.union([
121
+ z.strictObject({ glob: name, level: name, from: date, until: date }).refine(({ from, until }) => from < until, "a launch ends after it starts"),
122
+ z.strictObject({ glob: name, level: name, base: name }),
123
+ ]);
124
+
125
+ export type Launch = z.infer<typeof Launch>;
126
+
127
+ export type SlotRecipe = z.infer<typeof SlotRecipe>;
128
+
129
+ /** Every setting an owner may change, each described for the schema's readers. `defaults/hum.json` holds the shipped value of each. */
130
+ const Shipped = z.object({
131
+ checks: z.array(name).describe("The shell commands that must all exit 0 in a run's clone before its change merges, and on the base after a merge."),
132
+ kindLabels: z.record(name, name).describe("Item label (lower case) → kind name: the kind an item takes from a label of the repo's own, such as { \"bug\": \"fix\" }."),
133
+ runPlaces: z.array(z.enum(RUN_PLACES)).min(1).describe("Where hum runs: 'mac' is a service on the owner's machine, 'ci' a workflow. Only a 'mac' place reads the inbox, so an answer or a changed watch leaves a wake file there only when 'mac' is listed."),
134
+ runBranchPrefix: branchPrefix.describe("Each run builds on the branch this prefix and its item id make."),
135
+ claimPrefix: branchPrefix.describe("A claim is the first push of the branch this prefix and its item id make."),
136
+ readyLabel: name.describe("The label that marks an issue ready for hum."),
137
+ mergeMethod: z.enum(MERGE_METHODS).describe("How a released pull request merges."),
138
+ models: z.record(z.enum(TIERS), name).describe("The model id each tier of a kind's table runs on."),
139
+ runners: count.describe("The most runs that go at once."),
140
+ tickIntervalSeconds: seconds.describe("The time between worker ticks; each tick writes the heartbeat and renews the claims in flight."),
141
+ drainTimeoutSeconds: seconds.describe("How long a worker that has seen an update lets its runs finish before it stops them."),
142
+ claimExpirySeconds: seconds.describe("How long a claim lasts unless its holder renews it."),
143
+ latestVersionCacheSeconds: seconds.describe("How long the newest published engine version is kept before it is read again."),
144
+ watchCacheSeconds: seconds.describe("How long one read of what changed serves every `hum watch` in the repo before the next one reads again."),
145
+ watchLockSeconds: seconds.describe("How long the lock of the one `hum watch` that reads stays held before another may take it over."),
146
+ maxFixRuns: z.int().nonnegative().describe("Fix runs an item gets after failed checks before it ends stuck."),
147
+ serviceLabel: z.string().regex(SERVICE_LABEL, "a service label is letters, digits, dot, dash and underscore").describe("The service unit's label, and the name its file takes."),
148
+ maxCrashes: count.describe("Worker crashes within crashWindowSeconds that stop the service's restarts."),
149
+ crashWindowSeconds: seconds.describe("The window in which maxCrashes crashes stop the service's restarts."),
150
+ workerDownTicks: count.describe("Ticks without a heartbeat before the worker-down card shows."),
151
+ tokenWarnDays: count.describe("Days before the CI token's year ends that the expiry card shows."),
152
+ ciSchedule: z.string().refine((schedule) => isValidCron(schedule), "a cron schedule has five valid fields").describe("The cron schedule of the scheduled CI workflow."),
153
+ ciTickCacheSeconds: seconds.describe("How long the scheduled workflow's last tick is kept before the remote is read again."),
154
+ itemsDir: z.string().min(1).refine(isInsideRepo, "the items folder is a path inside the repo, without a leading or trailing '/'").describe("The folder of the repo that holds the markdown items."),
155
+ providerTimeoutSeconds: seconds.describe("How long a failing provider call is retried before one card shows."),
156
+ providerBackoff: backoff.describe("The pause before a provider call's first retry, doubled each retry up to the longest pause."),
157
+ mergedShown: count.describe("Merged changes the status file lists."),
158
+ choicesShown: count.describe("Choices made without the owner that the status file lists, newest first."),
159
+ statusReadTimeoutSeconds: seconds.describe("How long a read for the status file, such as the newest published version, may take before it is left out."),
160
+ commandTimeoutSeconds: seconds.describe("How long one git, gh, npm or Claude Code management command may run before it is stopped and its call fails naming it. A run's agent and a repo's checks have their own limits."),
161
+ mergeTries: count.describe("Tries to merge a change when the base branch moves under it."),
162
+ writeRaceRetries: z.int().nonnegative().describe("Retries of a markdown write that another writer's push beat."),
163
+ itemReadsAtOnce: count.describe("Item files the markdown source reads at once; each read is a git process."),
164
+ restartBackoff: backoff.describe("The pause before the service's first restart of a crashed worker, doubled each crash up to the longest pause."),
165
+ restartDelaySeconds: seconds.describe("Seconds the service manager waits before it starts a failed start script again."),
166
+ pullRequestTokenSecret: name.describe("The repository secret holding a GitHub App or fine-grained token for CI runs. A pull request opened with the workflow token starts no workflows, so its required checks never run; one opened with this token does. A CI run falls back to the workflow token while the secret is unset."),
167
+ ciWakeTimeoutMinutes: count.describe("Minutes a CI wake may run before GitHub stops it."),
168
+ strictPaths: z.array(name).describe("Globs of data and secrets: a change touching one takes the strictest level."),
169
+ launches: z
170
+ .array(Launch)
171
+ .describe("Raises a path to a level for a launch: between two dates, from 'from' up to 'until', or while the base branch matches 'base'."),
172
+ sizeRange: z
173
+ .strictObject({ changes: count, fewest: count, middle: fraction })
174
+ .describe("A path's usual size: the middle share of the lines its last 'changes' merged changes touched. A change above it goes one level up; a path with fewer than 'fewest' changes has no range."),
175
+ loosenedCheck: z
176
+ .strictObject({ added: z.array(pattern), removed: z.array(pattern) })
177
+ .describe("A change whose added or removed lines match one of these loosens a check and goes one level up; empty lists turn the rule off."),
178
+ changeLabels: z
179
+ .strictObject({ fixWindow: count, fixSubject: pattern, revertSubject: pattern, revertTrailer: pattern })
180
+ .describe("How hum labels a merged change from git: reverted by a commit whose trailer names it or whose subject reverts its subject; fixed by a fix commit within the next 'fixWindow' merged changes on its files that names it or changes its lines."),
181
+ historyDepth: count.describe("Commits of the base branch hum reads for size ranges and fix counts."),
182
+ lockfiles: z.array(name).describe("Lockfiles where a changed line naming the engine package changes hum itself."),
183
+ hookPaths: z.array(name).describe("Globs of tracked git hooks; a change to one changes hum itself."),
184
+ diffLimit: count.describe("The most characters of a change's diff one prompt carries."),
185
+ failureTail: count.describe("The last characters of the checks' output a fix run reads."),
186
+ kindMeanings: z.record(name, z.string().min(1)).describe("One line per kind saying what work it holds; the cheap model call reads these to pick an item's kind."),
187
+ fallbackKind: name.describe("The kind an item runs as when neither its source nor the model call names one."),
188
+ docsOnly: z
189
+ .strictObject({ kind: name, paths: z.array(name) })
190
+ .describe("An item of this kind whose change touches a path outside these globs moves to its real kind."),
191
+ decisionModel: name.describe("The model id of the cheap model call, made through claude -p."),
192
+ modelCallTimeoutSeconds: seconds.describe("How long a cheap model call may take before it counts as an abstention."),
193
+ measuredModels: z
194
+ .record(z.enum(BOUNDARIES), z.record(name, z.number().min(0).max(1)))
195
+ .describe("Per model-judgment boundary, the rate each model id scored on its labelled set; a pick from an id below 'minJudgeRate', or not measured, counts as an abstention."),
196
+ minJudgeRate: z.number().min(0).max(1).describe("The lowest measured rate at which hum trusts a model's pick at a boundary; below it the call abstains."),
197
+ questionLimits: z
198
+ .strictObject({ cells: count, wordCells: count })
199
+ .describe("The most terminal cells a question holds, and the most any one word of it holds; a longer question is replaced by a short one and its text rides folded."),
200
+ questionTimeoutHours: count.describe("Hours after a question that an item with no saved wait still counts as unanswered; past them the item ends stuck."),
201
+ priorityLabels: z.array(name).describe("Item labels that put its question first under the daily cap, highest first."),
202
+ undoableLevels: z.array(name).describe("Levels at which a choice that touches only the change's own files is made without the owner."),
203
+ ownerBranchPrefix: branchPrefix.describe("The branch prefix of a pull request that lands a commit the owner wrote, such as an answer."),
204
+ backgroundRuns: z.boolean().describe("Whether a run on the Mac is a Claude Code background agent, listed in agent view, instead of a claude -p process."),
205
+ backgroundLaunchSeconds: z.number().positive().describe("How long a launch waits for the run it just started to appear in the agent list."),
206
+ backgroundPollSeconds: z.number().positive().describe("The time between reads of a background run's transcript and job state."),
207
+ deniedRunCommands: z.array(name).describe("Shell commands a background run may not run: each is denied as written, with any arguments."),
208
+ runAutoMode: z
209
+ .strictObject({ environment: z.array(z.string().min(1)), allow: z.array(z.string().min(1)), hardDeny: z.array(z.string().min(1)) })
210
+ .describe("What auto mode's classifier is told about a background run: the situation it is in, what it allows, and what it always refuses; '$defaults' keeps Claude Code's own rules."),
211
+ runSlots: z
212
+ .strictObject({
213
+ enabled: z.boolean(),
214
+ pool: z.string().min(1),
215
+ services: z.enum(SLOT_SERVICES),
216
+ ports: z.strictObject({ base: count, stride: count }),
217
+ projectPrefix: name,
218
+ stepTimeoutSeconds: seconds,
219
+ recipe: SlotRecipe,
220
+ })
221
+ .describe(
222
+ "Prewarmed run slots on the Mac: worktrees of the owner's checkout that background runs work in, as many as 'runners'. 'pool' is the folder that holds them, relative to the checkout or absolute, and never inside .git, where Claude Code writes nothing; 'services' gives each slot its own services or one shared set with a database per slot; 'ports' starts each slot's block of ports; 'recipe' is the owner's own setup commands.",
223
+ ),
224
+ ownerLogins: z.array(name).describe("GitHub logins whose pull request reviews and comments are the owner's review notes."),
225
+ repeatAt: count.describe("Review notes stating one rule at which hum files a check item for it."),
226
+ repeatPrecision: fraction.describe("The lowest precision on labelled pairs at which a model's call that two notes state one rule files a check item; below it the pair waits as a possible repeat."),
227
+ tasteRules: z.array(name).describe("The owner's taste rules that have no deterministic check. Each pull request hum opens gets a comment saying whether its diff keeps each rule; the comment reports only and gates nothing."),
228
+ memoryMaxBytes: count.describe("The most bytes memory.md holds; a new entry past it is refused."),
229
+ memoryUnusedRuns: count.describe("Runs without use after which a memory.md entry is listed for the owner."),
230
+ measureWindow: count.describe("Merged changes the per-merge numbers average over, and the window per path."),
231
+ loopIntervalSeconds: seconds.describe("The time between passes that collect review notes, file check items and confirm CI ran their checks."),
232
+ proofTimeoutSeconds: seconds.describe("How long running a new check on one note's commit may take before the proof fails."),
233
+ kindFloors: z.record(name, name).describe("A kind's lowest risk level: its changes take at least this level, as in { \"check\": \"high\" }."),
234
+ checkKind: name.describe("The kind of the work item filed for a rule that review notes repeat: it turns the notes into one check."),
235
+ breakCheck: z.boolean().describe("Whether the repo's checks run on the base after each merge, so a test that breaks there files a follow-up item."),
236
+ mergeRisk: z
237
+ .strictObject({
238
+ weights: z.record(z.enum(GRADED), z.number().positive()),
239
+ cuts: z.tuple([z.number().positive(), z.number().positive()]),
240
+ })
241
+ .describe("How the alignment grade raises a level: each category's grade, 1 to 3, times its weight, averaged; when the alignment call's grades move the average across a cut, the level goes one step up."),
242
+ });
243
+
244
+ /** The defaults hum ships with, read from the default `hum.json`. */
245
+ export const SHIPPED_DEFAULTS = Shipped.parse(shippedConfig);
246
+
247
+ /** The branch prefixes: every branch hum writes starts with one of them. */
248
+ export type Naming = Pick<z.infer<typeof Shipped>, "runBranchPrefix" | "claimPrefix">;
249
+
250
+ type Settings = typeof Shipped extends z.ZodObject<infer Fields> ? Fields : never;
251
+
252
+ const withShippedDefaults = (settings: Settings): { [Key in keyof Settings]: z.ZodDefault<Settings[Key]> } =>
253
+ // SAFETY: `Object.fromEntries` loses the per-key types; each entry is its setting with its own shipped default.
254
+ Object.fromEntries(Object.entries<z.ZodType>(settings).map(([key, setting]) => [key, setting.default(SHIPPED_DEFAULTS[key as keyof Settings])])) as never;
255
+
256
+ export const Role = z.strictObject({
257
+ file: name,
258
+ purpose: z.enum(PURPOSES),
259
+ skills: z.array(name),
260
+ });
261
+
262
+ export const Level = z.strictObject({
263
+ name,
264
+ review: z.enum(REVIEWS),
265
+ release: z.enum(RELEASES),
266
+ onBreak: z.enum(BREAKS),
267
+ });
268
+
269
+ export type Level = z.infer<typeof Level>;
270
+
271
+ export const PathRule = z.strictObject({
272
+ glob: name,
273
+ level: name,
274
+ /** By kind name, or `*` for every kind: what release waits for at a level that releases after proof. */
275
+ proofs: z.record(name, name).optional(),
276
+ /** At most `fixes` fixed or reverted changes among the path's last `of` merged changes; past it the path goes one level up. */
277
+ limit: z.strictObject({ fixes: z.int().nonnegative(), of: count }).optional(),
278
+ });
279
+
280
+ export type PathRule = z.infer<typeof PathRule>;
281
+
282
+ export const HumConfig = z.strictObject({
283
+ schemaVersion: z.literal(SCHEMA_VERSION),
284
+ /** Risk levels, lowest first; the last is the strictest. */
285
+ levels: z.array(Level).min(1),
286
+ /** Risk level per path glob. */
287
+ paths: z.array(PathRule),
288
+ roles: z.record(name, Role),
289
+ /** Each event type names the part that sends it. */
290
+ events: z.record(name, z.strictObject({ source: name })),
291
+ /** Kind names; each kind sits in `kinds/<name>.json`. */
292
+ kinds: z.array(name).min(1),
293
+ /** The owner's safety rule. */
294
+ safety: z.record(z.string(), z.unknown()).optional(),
295
+ dailyQuestionCap: z.number().int().positive().optional(),
296
+ /** Adapter slot → adapter name. */
297
+ integrations: z.record(name, name).optional(),
298
+ /** The day `claude setup-token` made the CI token. Setup records it; the engine warns 30 days before the year ends. */
299
+ ciToken: z.strictObject({ setUp: z.iso.date() }).optional(),
300
+ /** No default: a commit is credited to whichever account lists its email, so only the owner's own is safe. */
301
+ commitIdentity: commitIdentity.describe("The owner's own name and email: the author and committer of every commit hum makes. Setup writes them from git config; hum ships none."),
302
+ ...withShippedDefaults(Shipped.shape),
303
+ });
304
+
305
+ export type HumConfig = z.infer<typeof HumConfig>;
306
+
307
+ /** `HumConfig` without the owner's identity, which hum cannot ship: what `defaults/` parses to. */
308
+ export const DefaultsConfig = HumConfig.omit({ commitIdentity: true });
309
+
310
+ export type DefaultsConfig = z.infer<typeof DefaultsConfig>;
311
+
312
+ const Transition = z.strictObject({
313
+ target: name.optional(),
314
+ guard: z.strictObject({ type: name, params: z.unknown().optional() }).optional(),
315
+ actions: z.array(z.strictObject({ type: name, params: z.unknown().optional() })).optional(),
316
+ description: z.string().optional(),
317
+ });
318
+
319
+ const Transitions = z
320
+ .union([Transition, z.array(Transition)])
321
+ .transform((value) => (Array.isArray(value) ? value : [value]));
322
+
323
+ const StateNode = z.strictObject({
324
+ type: z.enum(["atomic", "final"]).optional(),
325
+ description: z.string().optional(),
326
+ tags: z.array(name).optional(),
327
+ /** A run: `src` names a role. */
328
+ invoke: z
329
+ .strictObject({ src: name, onDone: Transitions.optional(), onError: Transitions.optional() })
330
+ .optional(),
331
+ on: z.record(name, Transitions).optional(),
332
+ always: Transitions.optional(),
333
+ /** Numeric millisecond keys only: the timeout of a wait. */
334
+ after: z.record(z.string().regex(/^\d+$/), Transitions).optional(),
335
+ timeout: z.number().int().positive().optional(),
336
+ onTimeout: Transitions.optional(),
337
+ entry: z.array(z.strictObject({ type: name, params: z.unknown().optional() })).optional(),
338
+ exit: z.array(z.strictObject({ type: name, params: z.unknown().optional() })).optional(),
339
+ });
340
+
341
+ export type StateNodeJSON = z.infer<typeof StateNode>;
342
+
343
+ /** A flat XState JSON machine: a version and a state map. */
344
+ export const MachineJSON = z.strictObject({
345
+ id: name,
346
+ version: name,
347
+ initial: name,
348
+ states: z.record(name, StateNode),
349
+ });
350
+
351
+ export type MachineJSON = z.infer<typeof MachineJSON>;
352
+
353
+ export const Kind = z.strictObject({
354
+ /** Tier and effort by purpose, level and size; an omitted level or size matches all. */
355
+ tiers: z.array(
356
+ z.strictObject({
357
+ purpose: z.enum(PURPOSES),
358
+ level: name.optional(),
359
+ size: z.enum(SIZES).optional(),
360
+ tier: z.enum(TIERS),
361
+ effort: z.enum(EFFORTS),
362
+ }),
363
+ ),
364
+ /** The token cap, and the machine state a run goes to when it passes the cap. */
365
+ tokenCap: z.strictObject({ tokens: z.number().int().positive(), overCap: name }),
366
+ /** Per earlier machine version: renamed or removed states, old name → new name. */
367
+ stateMap: z.record(name, z.record(name, name)).optional(),
368
+ machine: MachineJSON,
369
+ });
370
+
371
+ export type Kind = z.infer<typeof Kind>;
372
+
373
+ /**
374
+ * Every part the owner may change, with the `hum.json` key that holds it.
375
+ * Machines and the kinds' tables sit in `kinds/<name>.json`, listed by `kinds`.
376
+ */
377
+ export const OWNER_CHANGEABLE = {
378
+ machines: "kinds",
379
+ roles: "roles",
380
+ integrations: "integrations",
381
+ "risk levels": "levels",
382
+ "safety rule": "safety",
383
+ "cheap model call": "decisionModel",
384
+ "daily question cap": "dailyQuestionCap",
385
+ "kinds' tables": "kinds",
386
+ "run branch prefix": "runBranchPrefix",
387
+ "claim prefix": "claimPrefix",
388
+ "ready label": "readyLabel",
389
+ "merge method": "mergeMethod",
390
+ "model per tier": "models",
391
+ "runner count": "runners",
392
+ "tick interval": "tickIntervalSeconds",
393
+ "drain timeout": "drainTimeoutSeconds",
394
+ "claim expiry": "claimExpirySeconds",
395
+ "latest-version cache": "latestVersionCacheSeconds",
396
+ "watch cache": "watchCacheSeconds",
397
+ "watch lock": "watchLockSeconds",
398
+ "fix runs": "maxFixRuns",
399
+ "service label": "serviceLabel",
400
+ "crash limit": "maxCrashes",
401
+ "crash window": "crashWindowSeconds",
402
+ "worker-down age": "workerDownTicks",
403
+ "token warning lead": "tokenWarnDays",
404
+ "CI schedule": "ciSchedule",
405
+ "CI tick cache": "ciTickCacheSeconds",
406
+ "commit identity": "commitIdentity",
407
+ "items folder": "itemsDir",
408
+ "provider timeout": "providerTimeoutSeconds",
409
+ "provider backoff": "providerBackoff",
410
+ "merged changes shown": "mergedShown",
411
+ "choices shown": "choicesShown",
412
+ "status read timeout": "statusReadTimeoutSeconds",
413
+ "command timeout": "commandTimeoutSeconds",
414
+ "merge tries": "mergeTries",
415
+ "write race retries": "writeRaceRetries",
416
+ "item reads at once": "itemReadsAtOnce",
417
+ "restart backoff": "restartBackoff",
418
+ "restart delay": "restartDelaySeconds",
419
+ "CI wake timeout": "ciWakeTimeoutMinutes",
420
+ "pull request token secret": "pullRequestTokenSecret",
421
+ "data and secrets paths": "strictPaths",
422
+ "path rules": "paths",
423
+ launches: "launches",
424
+ "size range": "sizeRange",
425
+ "loosened-check rule": "loosenedCheck",
426
+ "change labels": "changeLabels",
427
+ "history depth": "historyDepth",
428
+ lockfiles: "lockfiles",
429
+ "hook paths": "hookPaths",
430
+ "diff limit": "diffLimit",
431
+ "failure tail": "failureTail",
432
+ "kind meanings": "kindMeanings",
433
+ "fallback kind": "fallbackKind",
434
+ "docs-only kind": "docsOnly",
435
+ "model call timeout": "modelCallTimeoutSeconds",
436
+ "measured models": "measuredModels",
437
+ "judge rate bar": "minJudgeRate",
438
+ "merge-risk weights": "mergeRisk",
439
+ "question limits": "questionLimits",
440
+ "question timeout": "questionTimeoutHours",
441
+ "priority labels": "priorityLabels",
442
+ "undoable levels": "undoableLevels",
443
+ "owner branch prefix": "ownerBranchPrefix",
444
+ "background runs": "backgroundRuns",
445
+ "background poll": "backgroundPollSeconds",
446
+ "background launch wait": "backgroundLaunchSeconds",
447
+ "denied run commands": "deniedRunCommands",
448
+ "run auto mode": "runAutoMode",
449
+ "run slots": "runSlots",
450
+ "owner logins": "ownerLogins",
451
+ "repeat threshold": "repeatAt",
452
+ "repeat precision bar": "repeatPrecision",
453
+ "taste rules": "tasteRules",
454
+ "memory size cap": "memoryMaxBytes",
455
+ "memory unused runs": "memoryUnusedRuns",
456
+ "measure window": "measureWindow",
457
+ "loop interval": "loopIntervalSeconds",
458
+ "proof timeout": "proofTimeoutSeconds",
459
+ "kind floors": "kindFloors",
460
+ "check kind": "checkKind",
461
+ "break check": "breakCheck",
462
+ checks: "checks",
463
+ "kind labels": "kindLabels",
464
+ "run places": "runPlaces",
465
+ } as const satisfies Record<string, string>;
@@ -0,0 +1,6 @@
1
+ import { join } from "node:path";
2
+ import type { z } from "zod";
3
+ import { orMissing, readJson } from "../state/fs.ts";
4
+
5
+ /** The settings `schema` names, read from the repo's `.hum/hum.json`. A repo with no `hum.json` gets the schema's own defaults. Throws when the file is unreadable or a value is refused. */
6
+ export const readSettings = <S extends z.ZodType>(repo: string, schema: S): z.output<S> => schema.parse(orMissing(() => readJson(join(repo, ".hum", "hum.json")), {}));