@moo.md/hum 0.1.0 → 0.3.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 (112) hide show
  1. package/defaults/hum.json +9 -2
  2. package/package.json +2 -2
  3. package/schema/hum.schema.json +208 -7
  4. package/scripts/eval.ts +88 -50
  5. package/src/adapter-api.ts +46 -14
  6. package/src/adapters/admit.ts +2 -2
  7. package/src/adapters/argument.ts +1 -1
  8. package/src/adapters/claim.ts +18 -15
  9. package/src/adapters/claude-bg.ts +50 -27
  10. package/src/adapters/claude-p.ts +18 -23
  11. package/src/adapters/contract.ts +22 -10
  12. package/src/adapters/each-call.ts +9 -0
  13. package/src/adapters/fake.ts +6 -6
  14. package/src/adapters/git.ts +10 -18
  15. package/src/adapters/github-client.ts +102 -0
  16. package/src/adapters/github.ts +61 -146
  17. package/src/adapters/guard.ts +20 -9
  18. package/src/adapters/history.ts +12 -15
  19. package/src/adapters/item-file.ts +1 -1
  20. package/src/adapters/markdown.ts +49 -42
  21. package/src/adapters/marked.ts +6 -12
  22. package/src/adapters/model-call.ts +4 -4
  23. package/src/adapters/once.ts +5 -5
  24. package/src/adapters/owner-commit.ts +13 -11
  25. package/src/adapters/pull-requests.ts +11 -13
  26. package/src/adapters/registry.ts +9 -8
  27. package/src/adapters/roundup.ts +27 -35
  28. package/src/adapters/serial.ts +4 -5
  29. package/src/adapters/transcript.ts +13 -8
  30. package/src/cli/main.ts +1 -0
  31. package/src/cli/ops.ts +32 -14
  32. package/src/cli/service.ts +14 -8
  33. package/src/cli/setup.ts +22 -7
  34. package/src/cli/shared-watch.ts +3 -3
  35. package/src/config/checks.ts +27 -18
  36. package/src/config/machine.ts +5 -7
  37. package/src/config/migrate.ts +5 -2
  38. package/src/config/refusal.ts +15 -2
  39. package/src/config/schema.ts +74 -12
  40. package/src/config/settings.ts +17 -2
  41. package/src/config/state-map.ts +5 -3
  42. package/src/config/wake-job.ts +74 -0
  43. package/src/decide/alignment.ts +4 -4
  44. package/src/decide/answer.ts +24 -22
  45. package/src/decide/kind.ts +1 -6
  46. package/src/decide/labels.ts +9 -9
  47. package/src/decide/merge.ts +6 -7
  48. package/src/decide/prose.ts +4 -4
  49. package/src/decide/question.ts +23 -20
  50. package/src/decide/review.ts +4 -2
  51. package/src/decide/risk.ts +25 -19
  52. package/src/decide/taste.ts +3 -3
  53. package/src/exec.ts +4 -3
  54. package/src/index.ts +14 -13
  55. package/src/loop/check-item.ts +3 -3
  56. package/src/loop/ci.ts +1 -1
  57. package/src/loop/github.ts +2 -2
  58. package/src/loop/groups.ts +13 -6
  59. package/src/loop/memory.ts +40 -28
  60. package/src/loop/notes.ts +5 -5
  61. package/src/loop/pair.ts +1 -1
  62. package/src/loop/pass.ts +18 -12
  63. package/src/loop/proof.ts +9 -7
  64. package/src/loop/prove-item.ts +1 -1
  65. package/src/loop/records.ts +12 -13
  66. package/src/loop/signals.ts +6 -6
  67. package/src/measure/inputs.ts +1 -1
  68. package/src/measure/measure.ts +4 -4
  69. package/src/measure/rate.ts +2 -0
  70. package/src/service/ci-tick.ts +2 -2
  71. package/src/service/supervise.ts +3 -2
  72. package/src/service/token.ts +3 -3
  73. package/src/service/wake.ts +2 -2
  74. package/src/service/workflows.ts +165 -48
  75. package/src/setup/propose.ts +78 -7
  76. package/src/setup/prove.ts +18 -12
  77. package/src/setup/scan.ts +91 -28
  78. package/src/setup/shipped.ts +8 -2
  79. package/src/setup/tables.ts +22 -3
  80. package/src/setup/waits.ts +9 -11
  81. package/src/setup/write.ts +67 -27
  82. package/src/slots/pool.ts +32 -24
  83. package/src/state/events.ts +1 -1
  84. package/src/state/faults.ts +13 -5
  85. package/src/state/format.ts +2 -2
  86. package/src/state/items.ts +9 -10
  87. package/src/state/open.ts +2 -2
  88. package/src/state/ops.ts +16 -10
  89. package/src/state/records.ts +5 -5
  90. package/src/state/runs.ts +33 -26
  91. package/src/state/saved.ts +44 -32
  92. package/src/status/file.ts +20 -1
  93. package/src/status/format.ts +47 -57
  94. package/src/status/sections.ts +2 -2
  95. package/src/worker/alignment-report.ts +4 -5
  96. package/src/worker/answers.ts +26 -24
  97. package/src/worker/base-check.ts +2 -2
  98. package/src/worker/kind.ts +23 -19
  99. package/src/worker/land.ts +114 -126
  100. package/src/worker/merged.ts +9 -7
  101. package/src/worker/open.ts +14 -12
  102. package/src/worker/prose-run.ts +3 -3
  103. package/src/worker/questions.ts +15 -12
  104. package/src/worker/scheduler.ts +4 -4
  105. package/src/worker/signature.ts +3 -3
  106. package/src/worker/tally.ts +0 -2
  107. package/src/worker/taste.ts +6 -15
  108. package/src/worker/thin-path.ts +148 -121
  109. package/src/worker/thread.ts +25 -0
  110. package/src/worker/worker.ts +77 -47
  111. package/surface.json +1091 -2251
  112. package/src/slots/scan.ts +0 -26
@@ -9,12 +9,10 @@ const placeholder = createAsyncLogic({ run: async () => {} });
9
9
  * Throws with xstate's message when the machine is illegal.
10
10
  */
11
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
12
  // 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 });
13
+ return machineFromJSON(kind.machine as Parameters<typeof machineFromJSON>[0], { actors: invokedSources(kind, placeholder, sources) });
20
14
  };
15
+
16
+ /** An actor for each source the kind's machine invokes: the one `sources` gives, else `fallback`. */
17
+ export const invokedSources = (kind: Kind, fallback: AnyActorLogic, sources: Readonly<Record<string, AnyActorLogic>> = {}): Record<string, AnyActorLogic> =>
18
+ Object.fromEntries(Object.values(kind.machine.states).flatMap(({ invoke }) => (invoke ? [[invoke.src, sources[invoke.src] ?? fallback]] : [])));
@@ -21,8 +21,11 @@ export const climb = <T extends object>(value: T, from: number, to: number, step
21
21
  /** Per earlier schema version: rewrites a config at that version into the next version's shape. */
22
22
  export type Migrations = Steps<ConfigJson>;
23
23
 
24
- /** One entry per earlier schema version. Empty while version 1 is the first. */
25
- export const MIGRATIONS: Migrations = {};
24
+ /** One entry per earlier schema version. Setup climbs the owner's answers, a part of a config, through the same steps, so a step rewrites only the keys it finds. */
25
+ export const MIGRATIONS = {
26
+ /** 2 holds the pull request token as one of its sources: the secret 1 named becomes `{ from: "secret", secret }`. */
27
+ 1: ({ pullRequestTokenSecret, ...config }) => (pullRequestTokenSecret === undefined ? config : { ...config, pullRequestToken: { from: "secret", secret: pullRequestTokenSecret } }),
28
+ } satisfies Migrations;
26
29
 
27
30
  const Raw = z.record(z.string(), Json);
28
31
  const Version = z.int();
@@ -14,7 +14,9 @@ export type Problem =
14
14
  | { readonly problem: "missing-file"; readonly file: string }
15
15
  | { readonly problem: "unknown-level"; readonly level: string }
16
16
  | { readonly problem: "path-without-proof"; readonly glob: string; readonly level: string }
17
- | { readonly problem: "overlapping-prefixes"; readonly run: string; readonly claim: string };
17
+ | { readonly problem: "overlapping-prefixes"; readonly run: string; readonly claim: string }
18
+ | { readonly problem: "wake-env-taken"; readonly name: string }
19
+ | { readonly problem: "wake-outlasts-app-token"; readonly minutes: number; readonly tokenMinutes: number };
18
20
 
19
21
  /** A config change the engine will not take. The caller keeps the last good config. */
20
22
  export type Refusal =
@@ -23,7 +25,8 @@ export type Refusal =
23
25
  | { readonly code: "invalid-config"; readonly problems: readonly Problem[]; readonly message: string }
24
26
  | { readonly code: "unmapped-state"; readonly items: readonly { readonly kind: string; readonly state: string }[]; readonly message: string }
25
27
  | { readonly code: "change-from-run"; readonly branch: string; readonly message: string }
26
- | { readonly code: "no-git-identity"; readonly missing: readonly string[]; readonly message: string };
28
+ | { readonly code: "no-git-identity"; readonly missing: readonly string[]; readonly message: string }
29
+ | { readonly code: "own-runner-on-public-repo"; readonly message: string };
27
30
 
28
31
  export type Result<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly refusal: Refusal };
29
32
 
@@ -46,11 +49,21 @@ const DESCRIPTIONS = {
46
49
  "unknown-level": (p) => `risk level "${p.level}" is not in levels`,
47
50
  "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
51
  "overlapping-prefixes": (p) => `the run branch prefix "${p.run}" and the claim prefix "${p.claim}" overlap: one starts with the other`,
52
+ "wake-env-taken": (p) => `ciEnv sets ${p.name}, which the CI wake job sets itself`,
53
+ "wake-outlasts-app-token": (p) =>
54
+ `ciWakeTimeoutMinutes is ${p.minutes}, and the token a GitHub App mints lasts ${p.tokenMinutes} minutes: a longer wake loses GitHub before it ends`,
49
55
  } as const satisfies Describe;
50
56
 
51
57
  // SAFETY: each description is keyed by the problem name it reads, so the lookup by `problem.problem` takes its own variant.
52
58
  export const describeProblem = (problem: Problem): string => (DESCRIPTIONS[problem.problem] as (problem: Problem) => string)(problem);
53
59
 
60
+ /** hum commits as the owner and invents no identity: this names each git config key that holds none, and how to set it. */
61
+ export const noGitIdentity = (missing: readonly string[]): Refusal => ({
62
+ code: "no-git-identity",
63
+ missing,
64
+ message: `hum commits as you, and git config holds no ${missing.join(" or ")}. Set ${missing.length === 1 ? "it" : "each"}, then run again: ${missing.map((key) => `git config --global ${key} "<yours>"`).join("; ")}.`,
65
+ });
66
+
54
67
  export const invalidConfig = (problems: readonly Problem[]): Refusal => ({
55
68
  code: "invalid-config",
56
69
  problems,
@@ -4,10 +4,10 @@ import { z } from "zod";
4
4
  import shippedConfig from "../../defaults/hum.json" with { type: "json" };
5
5
 
6
6
  /** The `hum.json` schema version this engine writes. */
7
- export const SCHEMA_VERSION = 1;
7
+ export const SCHEMA_VERSION = 2;
8
8
 
9
9
  /** The schema versions this engine reads, each migrated up to `SCHEMA_VERSION` by `migrateConfig`. */
10
- export const READABLE_SCHEMA_VERSIONS: readonly number[] = [1];
10
+ export const READABLE_SCHEMA_VERSIONS: readonly number[] = [1, 2];
11
11
 
12
12
  /** Parts the engine ships; the owner adds roles, never these. */
13
13
  export const FIXED_PARTS = [
@@ -24,7 +24,7 @@ export const FIXED_PARTS = [
24
24
 
25
25
  export const PURPOSES = ["plan", "build", "fix", "review"] as const;
26
26
  export const SIZES = ["small", "medium", "large"] as const;
27
- export const TIERS = ["light", "standard", "top"] as const;
27
+ const TIERS = ["light", "standard", "top"] as const;
28
28
  export const EFFORTS = ["low", "medium", "high"] as const;
29
29
 
30
30
  /** A machine state tagged with either of these waits on something outside the run. */
@@ -49,7 +49,7 @@ const branchPrefix = z
49
49
  .refine(isBranchPrefix, "a branch prefix followed by an item id must make a valid git branch name");
50
50
 
51
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;
52
+ const RUN_PLACES = ["mac", "ci"] as const;
53
53
 
54
54
  export type RunPlace = (typeof RUN_PLACES)[number];
55
55
 
@@ -57,14 +57,18 @@ export const MERGE_METHODS = ["merge", "squash", "rebase"] as const;
57
57
 
58
58
  export type MergeMethod = (typeof MERGE_METHODS)[number];
59
59
 
60
+ const CLAUDE_AUTHS = ["oauth-token", "env"] as const;
61
+
62
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
63
+
60
64
  /** Who reviews a change before it merges: no one, a fresh agent review run, or that run and then the owner. */
61
65
  export const REVIEWS = ["none", "agent", "owner"] as const;
62
66
 
63
67
  /** 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;
68
+ const RELEASES = ["at-once", "after-proof"] as const;
65
69
 
66
70
  /** What a break after merge becomes: follow-up work, or a block on the path. */
67
- export const BREAKS = ["follow-up", "block"] as const;
71
+ const BREAKS = ["follow-up", "block"] as const;
68
72
 
69
73
  /** Each place a model's judgment decides, measured on its own labelled set. */
70
74
  export const BOUNDARIES = ["kind", "alignment", "plan-outcome", "review-verdict", "reply-option", "repeat-pair", "taste"] as const;
@@ -87,10 +91,10 @@ const pattern = z.string().min(1).refine(isRegExp, "a pattern is a valid regular
87
91
  const date = z.iso.date();
88
92
 
89
93
  /** 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;
94
+ const REFRESH_WHEN = ["always", "lockfile-changed"] as const;
91
95
 
92
96
  /** 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;
97
+ const SLOT_SERVICES = ["per-slot", "shared"] as const;
94
98
 
95
99
  const RefreshStep = z.strictObject({ run: name, when: z.enum(REFRESH_WHEN) });
96
100
 
@@ -117,6 +121,40 @@ const backoff = z
117
121
 
118
122
  const fraction = z.number().gt(0).lt(1);
119
123
 
124
+ /** A name GitHub stores a secret under: a workflow reads it as `secrets.<name>`, and GitHub keeps the `GITHUB_` prefix for its own. */
125
+ const secretName = z
126
+ .string()
127
+ .regex(ENV_NAME, "a secret's name is letters, digits and underscores, and starts with no digit")
128
+ .refine((secret) => !/^GITHUB_/i.test(secret), "a secret's name may not start with GITHUB_, which GitHub keeps for its own");
129
+
130
+ const runnerLabels = z.union([name, z.array(name).min(1)]);
131
+
132
+ /** What a job's `runs-on` holds: one label, every label the runner must carry, or a runner group with the labels wanted in it. */
133
+ const Runner = z.union([runnerLabels, z.strictObject({ group: name, labels: runnerLabels.optional() })]);
134
+
135
+ const envName = z.string().regex(ENV_NAME, "an env name is letters, digits and underscores, and starts with no digit");
136
+
137
+ /** A job's container: its image alone, or the image with what a workflow's `container` holds beside it, each as written there. */
138
+ const Container = z.union([
139
+ name,
140
+ z.strictObject({
141
+ image: name,
142
+ credentials: z.strictObject({ username: name, password: name }).optional(),
143
+ env: z.record(envName, z.string()).optional(),
144
+ ports: z.array(z.union([name, z.int().positive()])).optional(),
145
+ volumes: z.array(name).optional(),
146
+ options: name.optional(),
147
+ }),
148
+ ]);
149
+
150
+ /** Where a CI run's GitHub token comes from: a secret that holds one, or a GitHub App that mints one per run from its client ID and private key. */
151
+ const PullRequestToken = z.discriminatedUnion("from", [
152
+ z.strictObject({ from: z.literal("secret"), secret: secretName }),
153
+ z.strictObject({ from: z.literal("app"), clientIdSecret: secretName, privateKeySecret: secretName }),
154
+ ]);
155
+
156
+ export type PullRequestToken = z.infer<typeof PullRequestToken>;
157
+
120
158
  const Launch = z.union([
121
159
  z.strictObject({ glob: name, level: name, from: date, until: date }).refine(({ from, until }) => from < until, "a launch ends after it starts"),
122
160
  z.strictObject({ glob: name, level: name, base: name }),
@@ -163,8 +201,24 @@ const Shipped = z.object({
163
201
  itemReadsAtOnce: count.describe("Item files the markdown source reads at once; each read is a git process."),
164
202
  restartBackoff: backoff.describe("The pause before the service's first restart of a crashed worker, doubled each crash up to the longest pause."),
165
203
  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."),
204
+ pullRequestToken: PullRequestToken.describe(
205
+ "Where a CI run's GitHub token comes from: { from: 'secret', secret } names a repository secret that holds a fine-grained token; { from: 'app', clientIdSecret, privateKeySecret } names the two secrets a GitHub App mints a token from each run, with the workflow's own permissions. clientIdSecret holds the App's client ID or its older App ID: the action that mints the token reads either as the same input. 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, or the client ID secret, is unset.",
206
+ ),
167
207
  ciWakeTimeoutMinutes: count.describe("Minutes a CI wake may run before GitHub stops it."),
208
+ ciRunner: Runner.describe(
209
+ "What the CI wake job runs on, as a workflow's runs-on holds it: one runner label, a list of labels the runner must carry all of, or { group, labels } for a runner group. On a public repo, a runner GitHub does not host keeps what a wake leaves on it, and setup asks before it writes one.",
210
+ ),
211
+ ciContainer: Container.nullable().describe(
212
+ "The container the CI wake job runs in: its image, or { image, credentials: { username, password }, env, ports, volumes, options } as a workflow's container holds them, or null to run on the runner itself. The image needs git, node and npm; a container that runs as root needs IS_SANDBOX=1 in ciEnv, or Claude Code refuses to skip its permission prompts.",
213
+ ),
214
+ ciEnv: z
215
+ .record(envName, z.string())
216
+ .describe(
217
+ "Env the CI wake job sets, such as a gateway's settings; a value may be a workflow expression. A value that reads a secret reaches only the step that runs hum; every other value reaches every step, the installs too. A name the job sets itself, such as GH_TOKEN, is refused.",
218
+ ),
219
+ ciClaudeAuth: z
220
+ .enum(CLAUDE_AUTHS)
221
+ .describe("How a CI run's Claude Code signs in: 'oauth-token' requires the CLAUDE_CODE_OAUTH_TOKEN secret, from `claude setup-token`; 'env' asks for no secret, and ciEnv carries the credentials, such as a gateway's settings."),
168
222
  strictPaths: z.array(name).describe("Globs of data and secrets: a change touching one takes the strictest level."),
169
223
  launches: z
170
224
  .array(Launch)
@@ -221,7 +275,11 @@ const Shipped = z.object({
221
275
  .describe(
222
276
  "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
277
  ),
224
- ownerLogins: z.array(name).describe("GitHub logins whose pull request reviews and comments are the owner's review notes."),
278
+ ownerLogins: z
279
+ .array(name)
280
+ .describe(
281
+ "GitHub logins whose pull request reviews and comments are the owner's review notes, and whose issue comments hum reads as replies. hum also reads the issue comments of the repo's owner, the owning organisation's members and invited collaborators, and reads no one else's.",
282
+ ),
225
283
  repeatAt: count.describe("Review notes stating one rule at which hum files a check item for it."),
226
284
  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
285
  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."),
@@ -253,7 +311,7 @@ const withShippedDefaults = (settings: Settings): { [Key in keyof Settings]: z.Z
253
311
  // SAFETY: `Object.fromEntries` loses the per-key types; each entry is its setting with its own shipped default.
254
312
  Object.fromEntries(Object.entries<z.ZodType>(settings).map(([key, setting]) => [key, setting.default(SHIPPED_DEFAULTS[key as keyof Settings])])) as never;
255
313
 
256
- export const Role = z.strictObject({
314
+ const Role = z.strictObject({
257
315
  file: name,
258
316
  purpose: z.enum(PURPOSES),
259
317
  skills: z.array(name),
@@ -417,7 +475,11 @@ export const OWNER_CHANGEABLE = {
417
475
  "restart backoff": "restartBackoff",
418
476
  "restart delay": "restartDelaySeconds",
419
477
  "CI wake timeout": "ciWakeTimeoutMinutes",
420
- "pull request token secret": "pullRequestTokenSecret",
478
+ "pull request token": "pullRequestToken",
479
+ "CI runner": "ciRunner",
480
+ "CI container": "ciContainer",
481
+ "CI env": "ciEnv",
482
+ "CI Claude auth": "ciClaudeAuth",
421
483
  "data and secrets paths": "strictPaths",
422
484
  "path rules": "paths",
423
485
  launches: "launches",
@@ -1,6 +1,21 @@
1
1
  import { join } from "node:path";
2
2
  import type { z } from "zod";
3
3
  import { orMissing, readJson } from "../state/fs.ts";
4
+ import { migrateConfig } from "./migrate.ts";
4
5
 
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")), {}));
6
+ /**
7
+ * The settings `schema` names, read from the repo's `.hum/hum.json` after it is migrated to the schema version this
8
+ * engine runs. A repo with no `hum.json` gets the schema's own defaults. Throws when the file is unreadable, its
9
+ * schema version is one this engine does not read, or a value is refused.
10
+ */
11
+ export const readSettings = <S extends z.ZodType>(repo: string, schema: S): z.output<S> => {
12
+ const raw = orMissing(() => readJson(join(repo, ".hum", "hum.json")), undefined);
13
+
14
+ if (raw === undefined) return schema.parse({});
15
+
16
+ const migrated = migrateConfig(raw);
17
+
18
+ if (!migrated.ok) throw new Error(migrated.refusal.message);
19
+
20
+ return schema.parse(migrated.value);
21
+ };
@@ -5,9 +5,11 @@ import type { Config } from "./load.ts";
5
5
  import { kindMachine } from "./machine.ts";
6
6
  import type { Kind } from "./schema.ts";
7
7
 
8
- /** A work item saved in a state of a kind. */
8
+ /** A work item saved in a state of a kind. `kind` is the kind's `machine.id`, as a saved snapshot records it, which need not be its file name. */
9
9
  export type SavedItem = { readonly kind: string; readonly state: string };
10
10
 
11
+ const kindWithId = (config: Config, id: string): Kind | undefined => Object.values(config.kinds).find((kind) => kind.machine.id === id);
12
+
11
13
  /** Where a saved state goes under the new kind: itself, its mapped name, or nowhere. */
12
14
  const mappedState = (previous: Kind, next: Kind, state: string): string | undefined => {
13
15
  if (state in next.machine.states) return state;
@@ -19,8 +21,8 @@ const mappedState = (previous: Kind, next: Kind, state: string): string | undefi
19
21
  /** The saved items whose state the new config neither keeps nor maps. */
20
22
  export const unmappedItems = (current: Config, next: Config, saved: readonly SavedItem[]): SavedItem[] =>
21
23
  saved.filter(({ kind, state }) => {
22
- const previous = current.kinds[kind];
23
- const target = next.kinds[kind];
24
+ const previous = kindWithId(current, kind);
25
+ const target = kindWithId(next, kind);
24
26
 
25
27
  return previous !== undefined && (target === undefined || mappedState(previous, target, state) === undefined);
26
28
  });
@@ -0,0 +1,74 @@
1
+ import type { HumConfig } from "./schema.ts";
2
+
3
+ /** The secret Claude Code's OAuth token is stored in, under the env name Claude Code reads it from. */
4
+ export const CLAUDE_TOKEN = "CLAUDE_CODE_OAUTH_TOKEN";
5
+
6
+ /** The env the wake job sets itself. */
7
+ export const WAKE_ENV = {
8
+ claudeToken: CLAUDE_TOKEN,
9
+ githubToken: "GH_TOKEN",
10
+ event: "HUM_EVENT",
11
+ /** Whether the App's client ID secret is set, because a step's `if` cannot read a secret. */
12
+ hasApp: "HUM_HAS_APP",
13
+ gitName: "HUM_GIT_NAME",
14
+ gitEmail: "HUM_GIT_EMAIL",
15
+ /** Set from env, so no shell expands the token's name before git runs the helper. */
16
+ gitCredentialHelper: "HUM_GIT_CREDENTIAL_HELPER",
17
+ /** Git's own name for the file `git config --global` writes: the job points it into the runner's temp folder. */
18
+ gitConfig: "GIT_CONFIG_GLOBAL",
19
+ } as const;
20
+
21
+ /** The env names the wake job sets itself, which `ciEnv` may not set. */
22
+ export const WAKE_OWN_ENV: ReadonlySet<string> = new Set(Object.values(WAKE_ENV));
23
+
24
+ /** The action that mints a GitHub App's token, named without its version. */
25
+ export const APP_TOKEN_ACTION = "actions/create-github-app-token";
26
+
27
+ /** GitHub's fixed life of an App's installation token. */
28
+ export const APP_TOKEN_MINUTES = 60;
29
+
30
+ /** The workflow files hum writes: the wake job, and one trigger per event that starts it. */
31
+ export const WORKFLOW_FILES = {
32
+ wake: "hum-wake.yml",
33
+ comment: "hum-comment.yml",
34
+ push: "hum-push.yml",
35
+ dispatch: "hum-dispatch.yml",
36
+ schedule: "hum-schedule.yml",
37
+ } as const;
38
+
39
+ /** The names of the workflow files hum writes. */
40
+ export const CI_WORKFLOW_FILES: ReadonlySet<string> = new Set(Object.values(WORKFLOW_FILES));
41
+
42
+ /**
43
+ * How GitHub relates a comment's author to the repo, for the people hum hears: the owner, a member of the owning
44
+ * organisation and an invited collaborator. Anyone else's comment starts no wake and is no reply.
45
+ */
46
+ export const TRUSTED_ASSOCIATIONS = ["OWNER", "MEMBER", "COLLABORATOR"] as const;
47
+
48
+ /** What the wake job takes from the owner as written, where a workflow expression may sit: the runner, the container and env. */
49
+ export type WakeJobSetting = HumConfig["ciRunner"] | HumConfig["ciContainer"] | HumConfig["ciEnv"];
50
+
51
+ /** `secrets.NAME` or `secrets['NAME']`; the quote may follow a backslash, as it does in a setting's JSON. */
52
+ const NAMED_SECRET = /\bsecrets\s*(?:\.\s*|\[\s*\\?['"])([A-Za-z_][A-Za-z0-9_]*)/g;
53
+
54
+ /** The secrets the workflow expressions in the settings name. */
55
+ export const secretsNamed = (...settings: readonly WakeJobSetting[]): string[] => [...JSON.stringify(settings).matchAll(NAMED_SECRET)].flatMap(([, name]) => name ?? []);
56
+
57
+ /** Whether `text` reads the secrets context at all, named or whole. */
58
+ export const readsSecrets = (text: string): boolean => /\bsecrets\b/.test(text);
59
+
60
+ /** A workflow expression that reads a context the wake job lacks: it has no matrix, no earlier job, and takes no inputs. */
61
+ const FOREIGN_CONTEXT = /\$\{\{[^}]*\b(matrix|strategy|needs|steps|inputs)\s*[.[]/;
62
+
63
+ /** Whether a setting holds an expression that means nothing in the wake job, so a value copied from another job would break it. */
64
+ export const readsForeignContext = (setting: WakeJobSetting): boolean => FOREIGN_CONTEXT.test(JSON.stringify(setting));
65
+
66
+ type Runner = HumConfig["ciRunner"];
67
+
68
+ const isGroup = (runner: Runner): runner is Extract<Runner, { readonly group: string }> => runner instanceof Object && "group" in runner;
69
+
70
+ /** The labels of the runners GitHub hosts start with the system they run. */
71
+ const HOSTED_LABEL = /^(ubuntu|windows|macos)-/;
72
+
73
+ /** Whether GitHub hosts the runner: a fresh machine per job. A group, or any other label, may be a machine that outlives the job. */
74
+ export const isGitHubHosted = (runner: Runner): boolean => !isGroup(runner) && [runner].flat().every((label) => HOSTED_LABEL.test(label));
@@ -15,12 +15,12 @@ export const AlignmentAnswer = z.strictObject({ alignment: Grade, verification:
15
15
  export type AlignmentAnswer = z.infer<typeof AlignmentAnswer>;
16
16
 
17
17
  /** Whether the alignment call may raise a level: the decision model's measured rate at this boundary meets the bar. */
18
- export const gatesAlignment = (config: Pick<HumConfig, "decisionModel" | "measuredModels" | "minJudgeRate">): boolean => isTrusted([config.decisionModel], "alignment", config);
18
+ export const doesGateAlignment = (config: Pick<HumConfig, "decisionModel" | "measuredModels" | "minJudgeRate">): boolean => isTrusted([config.decisionModel], "alignment", config);
19
19
 
20
20
  /** The cheap model call that grades a change against the item it answers. Below the bar its grades go in a report and decide nothing. */
21
21
  export const alignmentQuestion = (item: Pick<Item, "title" | "body">, diff: string, config: Pick<HumConfig, "diffLimit" | "decisionModel" | "measuredModels" | "minJudgeRate">) => ({
22
22
  boundary: "alignment" as const,
23
- reportOnly: !gatesAlignment(config) || undefined,
23
+ reportOnly: !doesGateAlignment(config) || undefined,
24
24
  prompt: [
25
25
  "Grade this change against the item it answers. alignment: does the diff do what the item asked, no more and no less? verification: do the tests or proof in the diff show it works? Grade each sound, partial or concern.",
26
26
  DATA_RULE,
@@ -61,7 +61,7 @@ const gradeOfRank = (rank: number, levels: number): number => (levels < 2 ? GRAD
61
61
  * Whether the alignment call's grades raise the level one step: they put the merge-risk score in a higher band than
62
62
  * sound grades would at the same level. The call never lowers a level.
63
63
  */
64
- export const raisesLevel = (rank: number, levels: number, answer: AlignmentAnswer, { mergeRisk }: Pick<HumConfig, "mergeRisk">): boolean => {
64
+ export const doesRaiseLevel = ({ rank, levels, answer, config: { mergeRisk } }: { readonly rank: number; readonly levels: number; readonly answer: AlignmentAnswer; readonly config: Pick<HumConfig, "mergeRisk"> }): boolean => {
65
65
  const fromLevel = gradeOfRank(rank, levels);
66
66
 
67
67
  const scored = (alignment: number, verification: number): number =>
@@ -75,5 +75,5 @@ export const alignedPlacement = (placement: Placement, answer: AlignmentAnswer,
75
75
  const rank = config.levels.findIndex(({ name }) => name === placement.level.name);
76
76
  const above = config.levels[Math.min(rank + 1, config.levels.length - 1)];
77
77
 
78
- return above && raisesLevel(rank, config.levels.length, answer, config) ? { ...placement, level: above, steps: [...placement.steps, { step: "alignment" }] } : placement;
78
+ return above && doesRaiseLevel({ rank, levels: config.levels.length, answer, config }) ? { ...placement, level: above, steps: [...placement.steps, { step: "alignment" }] } : placement;
79
79
  };
@@ -2,6 +2,7 @@ import { z } from "zod";
2
2
  import type { ThreadEntry } from "../adapter-api.ts";
3
3
  import { OWNER_APPROVAL } from "./merge.ts";
4
4
  import { DATA_RULE, fenced } from "./prose.ts";
5
+ import { bareWord } from "./question.ts";
5
6
 
6
7
  /** What the model call answers when none of the question's options fits the reply. */
7
8
  export const NONE_OF_THESE = "none of these";
@@ -15,10 +16,17 @@ export type Resolution =
15
16
  | { readonly source: "none-of-these" }
16
17
  | { readonly source: "abstained"; readonly why: string };
17
18
 
18
- const WORD_EDGES = /^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu;
19
+ /** Each way an answer comes to pick its option, by the name its settled answer is saved under. */
20
+ export const RESOLUTION_SOURCES = {
21
+ marker: "marker",
22
+ free: "free",
23
+ "first-word": "first-word",
24
+ model: "model",
25
+ "none-of-these": "none-of-these",
26
+ abstained: "abstained",
27
+ } as const satisfies { readonly [S in Resolution["source"]]: S };
19
28
 
20
- const firstWordOf = (text: string): string =>
21
- (text.trim().split(/\s+/)[0] ?? "").replaceAll(WORD_EDGES, "").toLowerCase();
29
+ const firstWordOf = (text: string): string => bareWord(text.trim().split(/\s+/)[0] ?? "").toLowerCase();
22
30
 
23
31
  /** The option an answer picks by its hidden marker, else by its first word matching an option exactly. */
24
32
  export const matchOption = (
@@ -39,9 +47,7 @@ export const matchOption = (
39
47
 
40
48
  /** The cheap model call that picks one of a question's options for a reply no marker or exact word settles. */
41
49
  export const replyQuestion = (
42
- question: string,
43
- options: readonly string[],
44
- reply: string,
50
+ { question, options, reply }: { readonly question: string; readonly options: readonly string[]; readonly reply: string },
45
51
  ) => ({
46
52
  boundary: "reply-option" as const,
47
53
  prompt: [
@@ -65,12 +71,14 @@ export type Stage =
65
71
  /** It has merged, or otherwise ended. */
66
72
  | "ended";
67
73
 
74
+ export const DISPOSITIONS = ["applied", "held", "dropped"] as const;
75
+
68
76
  export type Disposition = {
69
- readonly disposition: "applied" | "held" | "dropped";
77
+ readonly disposition: (typeof DISPOSITIONS)[number];
70
78
  readonly why: string;
71
79
  };
72
80
 
73
- export type DisposeFacts = {
81
+ type DisposeFacts = {
74
82
  readonly resolution: Resolution;
75
83
  /** An earlier answer to the same question was applied. */
76
84
  readonly answeredBefore: boolean;
@@ -79,6 +87,11 @@ export type DisposeFacts = {
79
87
 
80
88
  const dropped = (why: string): Disposition => ({ disposition: "dropped", why });
81
89
 
90
+ const isUnmatched = ({ source }: Resolution): boolean => source === "none-of-these" || source === "abstained";
91
+
92
+ /** Whether a model call, not the owner's own word, picked the approval. */
93
+ const isModelApproval = (resolution: Resolution): boolean => resolution.source === "model" && resolution.option === OWNER_APPROVAL;
94
+
82
95
  /** D4: every answer is applied, held for the next state, or dropped with its reason. A model's pick never approves a change that waits for the owner's approval. */
83
96
  export const dispose = ({
84
97
  resolution,
@@ -87,20 +100,9 @@ export const dispose = ({
87
100
  }: DisposeFacts): Disposition => {
88
101
  if (answeredBefore) return dropped("The question already has an answer.");
89
102
 
90
- if (
91
- resolution.source === "none-of-these" ||
92
- resolution.source === "abstained"
93
- )
94
- return dropped("No option matched the reply.");
95
-
96
- if (
97
- resolution.source === "model" &&
98
- resolution.option === OWNER_APPROVAL &&
99
- stage === "approval"
100
- )
101
- return dropped(
102
- `a model cannot approve it; reply with the word ${OWNER_APPROVAL}`,
103
- );
103
+ if (isUnmatched(resolution)) return dropped("No option matched the reply.");
104
+
105
+ if (isModelApproval(resolution) && stage === "approval") return dropped(`a model cannot approve it; reply with the word ${OWNER_APPROVAL}`);
104
106
 
105
107
  if (stage === "ended") return dropped("The item has ended.");
106
108
 
@@ -9,11 +9,6 @@ const TEMPLATE_FIELD = /^(?:kind:[ \t]*(\S+)|#{1,6}[ \t]*kind[ \t]*\n+[ \t]*(\S+
9
9
  /** The answer a model call gives when no kind fits. */
10
10
  export const UNSURE = "unsure";
11
11
 
12
- /** Where an item's kind came from. A fallback is an abstention: the item is unclear and runs on the fallback kind. */
13
- export type KindOf =
14
- | { readonly kind: string; readonly from: "source" | "model" }
15
- | { readonly kind: string; readonly from: "fallback"; readonly why: string };
16
-
17
12
  /** The kind an item names itself: a label the owner mapped to a kind or that is a kind's name, else its template field. */
18
13
  export const declaredKind = (item: Pick<Item, "body" | "labels">, kinds: readonly string[], kindLabels: HumConfig["kindLabels"]): string | undefined => {
19
14
  const field = TEMPLATE_FIELD.exec(item.body);
@@ -35,5 +30,5 @@ export const kindQuestion = (item: Pick<Item, "title" | "body">, { kinds, kindMe
35
30
  });
36
31
 
37
32
  /** A change of the docs-only kind that touches a path outside its globs is not docs. */
38
- export const leavesDocs = (paths: readonly string[], { docsOnly }: Pick<HumConfig, "docsOnly">): boolean =>
33
+ export const doesLeaveDocs = (paths: readonly string[], { docsOnly }: Pick<HumConfig, "docsOnly">): boolean =>
39
34
  paths.some((path) => !docsOnly.paths.some((glob) => new Bun.Glob(glob).match(path)));
@@ -22,15 +22,15 @@ const SHA_IN_TEXT = /\b[0-9a-f]{7,40}\b/g;
22
22
  const shasIn = (text: string): readonly string[] =>
23
23
  text.match(SHA_IN_TEXT) ?? [];
24
24
 
25
- const names = (later: PastChange, earlier: PastChange): boolean =>
25
+ const doesName = (later: PastChange, earlier: PastChange): boolean =>
26
26
  shasIn(`${later.subject}\n${later.body}`).some((sha) =>
27
27
  earlier.sha.startsWith(sha),
28
28
  );
29
29
 
30
- const sharesAFile = (a: PastChange, b: PastChange): boolean =>
30
+ const doShareAFile = (a: PastChange, b: PastChange): boolean =>
31
31
  a.files.some((file) => b.files.includes(file));
32
32
 
33
- const revertsByTrailer = (
33
+ const doesRevertByTrailer = (
34
34
  later: PastChange,
35
35
  earlier: PastChange,
36
36
  { revertTrailer }: LabelRules,
@@ -39,14 +39,14 @@ const revertsByTrailer = (
39
39
  ([, sha]) => sha !== undefined && earlier.sha.startsWith(sha),
40
40
  );
41
41
 
42
- const revertsByTitle = (
42
+ const doesRevertByTitle = (
43
43
  later: PastChange,
44
44
  earlier: PastChange,
45
45
  { revertSubject }: LabelRules,
46
46
  ): boolean =>
47
47
  new RegExp(revertSubject).test(later.subject) &&
48
48
  (later.subject.includes(`"${earlier.subject}"`) ||
49
- names(later, earlier) ||
49
+ doesName(later, earlier) ||
50
50
  later.blamed.includes(earlier.sha));
51
51
 
52
52
  const isRevertOf = (
@@ -54,8 +54,8 @@ const isRevertOf = (
54
54
  earlier: PastChange,
55
55
  rules: LabelRules,
56
56
  ): boolean =>
57
- revertsByTrailer(later, earlier, rules) ||
58
- revertsByTitle(later, earlier, rules);
57
+ doesRevertByTrailer(later, earlier, rules) ||
58
+ doesRevertByTitle(later, earlier, rules);
59
59
 
60
60
  const isFixOf = (
61
61
  later: PastChange,
@@ -63,7 +63,7 @@ const isFixOf = (
63
63
  { fixSubject }: LabelRules,
64
64
  ): boolean =>
65
65
  new RegExp(fixSubject).test(later.subject) &&
66
- (names(later, earlier) || later.blamed.includes(earlier.sha));
66
+ (doesName(later, earlier) || later.blamed.includes(earlier.sha));
67
67
 
68
68
  /** The later change that breaks `changes[at]`, and how: a revert of it, else a fix among the next `fixWindow` changes on its files. */
69
69
  export const breakOf = (
@@ -81,7 +81,7 @@ export const breakOf = (
81
81
  if (reverting) return { by: reverting, label: "reverted" };
82
82
 
83
83
  const fixing = later
84
- .filter((next) => sharesAFile(next, change))
84
+ .filter((next) => doShareAFile(next, change))
85
85
  .slice(0, rules.fixWindow)
86
86
  .find((next) => isFixOf(next, change, rules));
87
87
 
@@ -30,11 +30,11 @@ const STRICTEST_PROOF = "the owner's word that the change is proven";
30
30
  export type Approvals = { readonly review: boolean; readonly owner: boolean };
31
31
 
32
32
  /** What clears a clear change without the owner, by its level's review. The owner's approval clears any change. */
33
- const CLEARED_BY: Readonly<Record<(typeof REVIEWS)[number], (approvals: Approvals) => boolean>> = {
33
+ const CLEARED_BY = {
34
34
  none: () => true,
35
35
  agent: (approvals) => approvals.review,
36
36
  owner: () => false,
37
- };
37
+ } as const satisfies Record<(typeof REVIEWS)[number], (approvals: Approvals) => boolean>;
38
38
 
39
39
  const NO_APPROVALS: Approvals = { review: false, owner: false };
40
40
 
@@ -60,7 +60,7 @@ export const routeOf = (
60
60
  return {
61
61
  level,
62
62
  unclear,
63
- mergesAlone: unclear.length === 0 && CLEARED_BY[level.review](NO_APPROVALS),
63
+ mergesAlone: isCleared({ level, unclear }, NO_APPROVALS),
64
64
  proof:
65
65
  level.release === "after-proof"
66
66
  ? proofs.join("; ") || STRICTEST_PROOF
@@ -69,16 +69,15 @@ export const routeOf = (
69
69
  };
70
70
 
71
71
  /** A route merges once nothing waits: on its own, once a fresh review approved a clear change at an agent-reviewed level, or once the owner approved it. */
72
- export const isCleared = (route: Route, approvals: Approvals): boolean =>
72
+ export const isCleared = (route: Pick<Route, "level" | "unclear">, approvals: Approvals): boolean =>
73
73
  approvals.owner || (route.unclear.length === 0 && CLEARED_BY[route.level.review](approvals));
74
74
 
75
75
  /** Every level that asks for a review gets a fresh review run first; the owner's review comes after it. */
76
- export const needsReviewRun = (route: Route): boolean => route.level.review !== "none";
76
+ export const doesNeedReviewRun = (route: Route): boolean => route.level.review !== "none";
77
77
 
78
78
  /** Where the target branch requires a pull request, every change lands through one, merging itself only when cleared; elsewhere a cleared change is pushed. */
79
79
  export const landingOf = (
80
- requiresPullRequest: boolean,
81
- cleared: boolean,
80
+ { requiresPullRequest, cleared }: { readonly requiresPullRequest: boolean; readonly cleared: boolean },
82
81
  ): Landing => {
83
82
  if (requiresPullRequest) return { via: "pull-request", autoMerge: cleared };
84
83