@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.
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 +392 -0
  32. package/src/adapters/claude-p.ts +599 -0
  33. package/src/adapters/contract.ts +231 -0
  34. package/src/adapters/fake.ts +157 -0
  35. package/src/adapters/git.ts +156 -0
  36. package/src/adapters/github.ts +479 -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 +127 -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 +293 -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 +85 -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 +195 -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 +45 -0
  135. package/src/worker/checks.ts +40 -0
  136. package/src/worker/kind.ts +68 -0
  137. package/src/worker/land.ts +509 -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 +750 -0
  149. package/surface.json +8787 -0
  150. package/README.md +0 -3
@@ -0,0 +1,509 @@
1
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import pRetry from "p-retry";
5
+ import { z } from "zod";
6
+ import {
7
+ type Item,
8
+ type Questions,
9
+ type WorkSource,
10
+ } from "../adapter-api.ts";
11
+ import {
12
+ type Git,
13
+ gitIn,
14
+ isAncestor,
15
+ PATCH,
16
+ push,
17
+ PushRefused,
18
+ } from "../adapters/git.ts";
19
+ import { type CommitLanded, landOwnerCommit } from "../adapters/owner-commit.ts";
20
+ import { commandTimeoutMs } from "../exec.ts";
21
+ import { changeOf, historiesOf, readHistory } from "../adapters/history.ts";
22
+ import { markDone } from "../adapters/item-file.ts";
23
+ import {
24
+ type BranchRules,
25
+ methodFor,
26
+ type PullRequests,
27
+ } from "../adapters/pull-requests.ts";
28
+ import type { ModelCall } from "../adapters/model-call.ts";
29
+ import type { Config } from "../config/load.ts";
30
+ import type { Boundary } from "../config/schema.ts";
31
+ import { alignedPlacement, alignmentQuestion, gatesAlignment } from "../decide/alignment.ts";
32
+ import {
33
+ isCleared,
34
+ type Landing,
35
+ landingOf,
36
+ needsReviewRun,
37
+ OWNER_APPROVAL,
38
+ type Route,
39
+ routeOf,
40
+ type Unclear,
41
+ waitReason,
42
+ } from "../decide/merge.ts";
43
+ import { isTrusted } from "../decide/prose.ts";
44
+ import {
45
+ type Change,
46
+ placeChange,
47
+ type Placement,
48
+ type Policy,
49
+ } from "../decide/risk.ts";
50
+ import type { State } from "../state/open.ts";
51
+ import type { Landing as SavedLanding, Verdict } from "../state/saved.ts";
52
+ import { PLAIN_QUESTIONS } from "../decide/question.ts";
53
+ import { checksTimeoutMs, runChecks } from "./checks.ts";
54
+ import { recordMerged } from "./merged.ts";
55
+ import { blockedPaths, brokenCommits } from "../loop/breaks.ts";
56
+ import { queueQuestion, releaseQuestions } from "./questions.ts";
57
+ import { reportAlignment } from "./alignment-report.ts";
58
+ import { reportTaste } from "./taste.ts";
59
+ import type { ThinResult } from "./thin-path.ts";
60
+
61
+ const SHORT_EXCERPT = 200;
62
+
63
+ const HUM_CONFIG = ".hum/hum.json";
64
+
65
+ const NO_RULES: BranchRules = {
66
+ requiresPullRequest: false,
67
+ mergeMethods: undefined,
68
+ };
69
+
70
+ /** Everything landing a finished change reads and writes. The clone has the run branch checked out and the base fetched. */
71
+ export type LandContext = {
72
+ readonly state: State;
73
+ readonly config: Config;
74
+ readonly kind: string;
75
+ readonly id: string;
76
+ readonly item: Item;
77
+ readonly branch: string;
78
+ readonly base: string;
79
+ readonly remote: string;
80
+ readonly clone: string;
81
+ /** What the run's folder adds to the environment of the repo's checks. */
82
+ readonly env: Readonly<Record<string, string>>;
83
+ readonly dir: string;
84
+ readonly git: Git;
85
+ readonly checks: readonly string[];
86
+ readonly workSource: WorkSource;
87
+ readonly questions: Questions;
88
+ /** The remote's pull requests and branch rules; undefined for a remote that is not on GitHub. */
89
+ readonly pulls: PullRequests | undefined;
90
+ readonly now: () => number;
91
+ readonly judge: ModelCall;
92
+ /** A fresh review run on the change that ends at `head`, at its level's tier; it saves its verdict. */
93
+ readonly reviewRun: (change: { readonly head: string; readonly diff: string; readonly level: string }) => Promise<ReviewOutcome>;
94
+ };
95
+
96
+ /** What a review run at landing came to: its verdict, or the result that stopped it, such as a usage limit. */
97
+ export type ReviewOutcome = { readonly verdict: Verdict } | { readonly halted: ThinResult };
98
+
99
+ /** The review verdict that lets a change merge. */
100
+ export const REVIEW_APPROVAL = "approve";
101
+
102
+ /** The change cannot merge on the newest base: it conflicts, or its checks fail there. */
103
+ class StaleMerge extends Error {
104
+ override name = "StaleMerge";
105
+ }
106
+
107
+ /** Another writer moved the base between the fetch and the push. */
108
+ class BaseMoved extends Error {
109
+ override name = "BaseMoved";
110
+ }
111
+
112
+ /** The glob a new path rule takes for a path no rule places: its folder, or the file itself at the top. */
113
+ export const ruleGlobFor = (path: string): string =>
114
+ dirname(path) === "." ? path : `${dirname(path)}/**`;
115
+
116
+ const levelNames = (config: Config): readonly string[] =>
117
+ config.hum.levels.map(({ name }) => name);
118
+
119
+ /** The config's risk policy with every rule the owner's answers added since it was loaded. */
120
+ const policyOf = ({
121
+ config,
122
+ state,
123
+ }: Pick<LandContext, "config" | "state">): Policy => ({
124
+ ...config.hum,
125
+ paths: [
126
+ ...config.hum.paths,
127
+ ...state.learned.list().map(({ glob, level }) => ({ glob, level })),
128
+ ],
129
+ });
130
+
131
+ /** The change's level under the current policy and the base's own history. */
132
+ export const placementOf = async (
133
+ ctx: Pick<LandContext, "config" | "state" | "git" | "base" | "now"> & { readonly kind?: string },
134
+ change: Change,
135
+ ): Promise<{ placement: Placement; policy: Policy }> => {
136
+ const policy = policyOf(ctx);
137
+
138
+ const histories = historiesOf(
139
+ await readHistory(ctx.git, `origin/${ctx.base}`, ctx.config.hum),
140
+ { ...ctx.config.hum, paths: policy.paths },
141
+ brokenCommits(ctx.state),
142
+ );
143
+
144
+ return {
145
+ placement: placeChange(change, policy, histories, {
146
+ now: ctx.now(),
147
+ base: ctx.base,
148
+ kindFloor: ctx.kind === undefined ? undefined : ctx.config.hum.kindFloors[ctx.kind],
149
+ blocked: blockedPaths(ctx.state),
150
+ }),
151
+ policy,
152
+ };
153
+ };
154
+
155
+ /** The diff of the run branch against the base, read as the risk level reads it. */
156
+ export const changeOn = async ({
157
+ git,
158
+ base,
159
+ config,
160
+ }: Pick<LandContext, "git" | "base" | "config">): Promise<Change> =>
161
+ changeOf(await git.raw(["diff", ...PATCH, `origin/${base}...HEAD`]), config.hum);
162
+
163
+ const isOwnerApproval =
164
+ (since: number) =>
165
+ (entry: Item["thread"][number]): boolean =>
166
+ entry.kind === "answer" &&
167
+ entry.option === OWNER_APPROVAL &&
168
+ entry.at >= since;
169
+
170
+ /** The level the owner picked for unclear paths, answered since the change was saved. */
171
+ const answeredLevel = (
172
+ item: Item,
173
+ since: number,
174
+ levels: readonly string[],
175
+ ): string | undefined =>
176
+ item.thread.findLast(
177
+ (entry) =>
178
+ entry.kind === "answer" &&
179
+ entry.at >= since &&
180
+ entry.option !== undefined &&
181
+ levels.includes(entry.option),
182
+ )?.option;
183
+
184
+ const askUnclear = async (ctx: LandContext, unclear: readonly string[]): Promise<void> => {
185
+ const globs = [...new Set(unclear.map(ruleGlobFor))];
186
+
187
+ queueQuestion(ctx, ctx.item, { text: PLAIN_QUESTIONS.level, options: levelNames(ctx.config), detail: `${globs.join(", ")} match no path rule.` }, "level");
188
+ await releaseQuestions(ctx);
189
+ };
190
+
191
+ const RawPaths = z.looseObject({ paths: z.array(z.unknown()).default([]) });
192
+
193
+ /** Commits the owner's answer as path rules in the base's `hum.json`, with hooks off, and saves them for the view's undo. */
194
+ const learnRules = async (
195
+ ctx: LandContext,
196
+ unclear: readonly string[],
197
+ level: string,
198
+ ): Promise<CommitLanded> => {
199
+ const { state, config, id, base, remote, now } = ctx;
200
+ const globs = [...new Set(unclear.map(ruleGlobFor))];
201
+ const scratch = mkdtempSync(join(tmpdir(), "hum-rule-"));
202
+ const timeoutMs = commandTimeoutMs(config.hum);
203
+ const git = gitIn(scratch, { identity: config.hum.commitIdentity, timeoutMs });
204
+
205
+ try {
206
+ await gitIn(tmpdir(), { timeoutMs }).raw([
207
+ "clone",
208
+ "-q",
209
+ "--depth",
210
+ "1",
211
+ "--branch",
212
+ base,
213
+ remote,
214
+ scratch,
215
+ ]);
216
+
217
+ const file = join(scratch, HUM_CONFIG);
218
+ const raw = RawPaths.parse(JSON.parse(readFileSync(file, "utf8")));
219
+
220
+ writeFileSync(
221
+ file,
222
+ `${JSON.stringify({ ...raw, paths: [...raw.paths, ...globs.map((glob) => ({ glob, level }))] }, null, "\t")}\n`,
223
+ );
224
+ await git.raw([
225
+ "commit",
226
+ "-q",
227
+ "-a",
228
+ "-m",
229
+ `hum: ${globs.join(", ")} at level ${level}`,
230
+ "-m",
231
+ `The owner answered on item ${id}.`,
232
+ ]);
233
+
234
+ const commit = (await git.raw(["rev-parse", "HEAD"])).trim();
235
+
236
+ const landed = await landOwnerCommit({
237
+ sha: commit,
238
+ base,
239
+ label: id,
240
+ title: `hum: ${globs.join(", ")} at level ${level}`,
241
+ body: `The owner answered on item ${id}: ${globs.join(", ")} at level ${level}.`,
242
+ branchPrefix: config.hum.ownerBranchPrefix,
243
+ mergeMethod: config.hum.mergeMethod,
244
+ pulls: ctx.pulls,
245
+ push: (refspecs) => push(git, ["origin", ...refspecs]),
246
+ });
247
+
248
+ if (landed.via === "conflict")
249
+ throw new Error(
250
+ `another push moved ${base} before the path rule for ${id} landed`,
251
+ );
252
+
253
+ for (const glob of globs)
254
+ state.learned.put(glob, { glob, level, item: id, commit, pull: landed.via === "pull-request" ? landed.pull.url : undefined, at: now() });
255
+
256
+ return landed;
257
+ } finally {
258
+ rmSync(scratch, { recursive: true, force: true });
259
+ }
260
+ };
261
+
262
+ /** Marks the item done on the run branch, pushes the branch and saves what its diff showed, so a retry lands it without a run. `ownerApproved` records that the owner approved this change in its review state. */
263
+ export const prepareLanding = async (ctx: LandContext, ownerApproved = false): Promise<void> => {
264
+ const { git, clone, dir, id, branch, state, now } = ctx;
265
+ const change = await changeOn(ctx);
266
+ const head = (await git.raw(["rev-parse", "HEAD"])).trim();
267
+ const file = join(clone, dir, `${id}.md`);
268
+
269
+ writeFileSync(file, markDone(readFileSync(file, "utf8")));
270
+ await git.raw(["add", `${dir}/${id}.md`]);
271
+ await git.raw(["commit", "-q", "-m", `hum: finish ${id}`]);
272
+ await push(git, ["--force", "origin", `HEAD:refs/heads/${branch}`]);
273
+ state.landings.put(id, { item: id, branch, since: now(), change: { ...change, paths: [...change.paths] }, head, ownerApproved });
274
+ };
275
+
276
+ /** A merge is rechecked on the newest base: when the base moved, the change is rebased and the checks run again. */
277
+ const pushOntoNewestBase = async ({
278
+ git,
279
+ base,
280
+ branch,
281
+ clone,
282
+ env,
283
+ checks,
284
+ config,
285
+ }: LandContext): Promise<void> => {
286
+ await git.raw(["fetch", "-q", "origin", base]);
287
+
288
+ if (!(await isAncestor(git, `origin/${base}`, "HEAD"))) {
289
+ const rebased = await git.run(["rebase", "-q", `origin/${base}`]);
290
+
291
+ if (rebased.code !== 0) {
292
+ await git.run(["rebase", "--abort"]);
293
+
294
+ throw new StaleMerge(
295
+ `the change conflicts with the newest ${base}: ${rebased.stderr.trim().slice(0, SHORT_EXCERPT)}`,
296
+ );
297
+ }
298
+
299
+ const failure = await runChecks(checks, clone, { env, timeoutMs: checksTimeoutMs(config.hum) });
300
+
301
+ if (failure)
302
+ throw new StaleMerge(
303
+ `the checks fail on the newest ${base}: ${failure.slice(0, SHORT_EXCERPT)}`,
304
+ );
305
+ }
306
+
307
+ await push(git, ["--force", "origin", `HEAD:refs/heads/${branch}`]);
308
+
309
+ if ((await push(git, ["origin", `HEAD:refs/heads/${base}`])) === "conflict")
310
+ throw new BaseMoved(`another push moved ${base} first`);
311
+ };
312
+
313
+ const finish = async ({ state, git, id, now }: LandContext): Promise<ThinResult> => {
314
+ recordMerged(state, id, (await git.raw(["rev-parse", "HEAD"])).trim(), now());
315
+
316
+ return { outcome: "merged", item: id };
317
+ };
318
+
319
+ const pushToBase = async (ctx: LandContext): Promise<void> => {
320
+ await ctx.state.ops.once(
321
+ { itemId: ctx.id, run: "merge", attempt: 0, op: "push-base" },
322
+ {
323
+ holds: async () => {
324
+ await ctx.git.raw(["fetch", "-q", "origin", ctx.base]);
325
+
326
+ return isAncestor(ctx.git, "HEAD", `origin/${ctx.base}`);
327
+ },
328
+ run: () =>
329
+ pRetry(() => pushOntoNewestBase(ctx), {
330
+ retries: ctx.config.hum.mergeTries - 1,
331
+ minTimeout: 0,
332
+ shouldRetry: ({ error }) => error instanceof BaseMoved,
333
+ }),
334
+ },
335
+ );
336
+ };
337
+
338
+ /** One pull request from the run branch: it merges itself once GitHub's required checks pass when the change is cleared, and waits for the owner otherwise. */
339
+ const throughPullRequest = async (
340
+ ctx: LandContext,
341
+ pulls: PullRequests,
342
+ autoMerge: boolean,
343
+ route: Route,
344
+ rules: BranchRules,
345
+ why: string,
346
+ ): Promise<ThinResult> => {
347
+ const { id, branch, base, item, config } = ctx;
348
+ const body = `${autoMerge ? `Level ${route.level.name}: it merges once the required checks pass.` : `Not merged by hum: ${why}.`}\n\nItem ${id}.`;
349
+
350
+ const pull =
351
+ (await pulls.find(branch)) ??
352
+ (await pulls.open({
353
+ head: branch,
354
+ base,
355
+ title: `hum: ${item.title}`,
356
+ body,
357
+ }));
358
+
359
+ if (pull.state === "MERGED") return finish(ctx);
360
+
361
+ if (pull.state === "CLOSED")
362
+ return {
363
+ outcome: "review",
364
+ item: id,
365
+ detail: `its pull request was closed unmerged: ${pull.url}`,
366
+ };
367
+
368
+ const head = ctx.state.landings.get(id)?.head ?? branch;
369
+
370
+ await reportTaste(ctx, pulls, pull, head);
371
+ await reportAlignment(ctx, pulls, pull, head);
372
+
373
+ const armed = await pulls.autoMerge(
374
+ pull,
375
+ autoMerge,
376
+ methodFor(config.hum.mergeMethod, rules.mergeMethods),
377
+ );
378
+
379
+ if (armed === "merged") return finish(ctx);
380
+
381
+ if (armed === "armed" && pull.behind) await pulls.update(pull);
382
+
383
+ return { outcome: "landing", item: id, detail: pull.url };
384
+ };
385
+
386
+ /** A push the remote refused, on GitHub: the rules are read again and the change goes through a pull request. */
387
+ const afterRefusal = async (
388
+ ctx: LandContext,
389
+ cleared: boolean,
390
+ route: Route,
391
+ why: string,
392
+ ): Promise<ThinResult> => {
393
+ if (!ctx.pulls)
394
+ throw new PushRefused(
395
+ `the remote refused the push of ${ctx.id} to ${ctx.base}, and it is not on GitHub`,
396
+ );
397
+
398
+ return throughPullRequest(
399
+ ctx,
400
+ ctx.pulls,
401
+ cleared,
402
+ route,
403
+ await ctx.pulls.rules(ctx.base, true),
404
+ why,
405
+ );
406
+ };
407
+
408
+ const landBy = async (
409
+ ctx: LandContext,
410
+ landing: Landing,
411
+ route: Route,
412
+ rules: BranchRules,
413
+ why: string,
414
+ ): Promise<ThinResult> => {
415
+ if (landing.via === "wait")
416
+ return { outcome: "review", item: ctx.id, detail: why };
417
+
418
+ if (landing.via === "pull-request" && ctx.pulls)
419
+ return throughPullRequest(ctx, ctx.pulls, landing.autoMerge, route, rules, why);
420
+
421
+ try {
422
+ await pushToBase(ctx);
423
+
424
+ return await finish(ctx);
425
+ } catch (error) {
426
+ if (error instanceof StaleMerge)
427
+ return { outcome: "review", item: ctx.id, detail: error.message };
428
+
429
+ if (error instanceof PushRefused) return afterRefusal(ctx, true, route, why);
430
+
431
+ throw error;
432
+ }
433
+ };
434
+
435
+ /**
436
+ * Lands a change saved by `prepareLanding`, by its level under the policy as it stands now: an answered level
437
+ * becomes a path rule first, an unclear change asks once, and the target branch's rules pick a push or a pull request.
438
+ */
439
+ export const land = async (ctx: LandContext): Promise<ThinResult> => {
440
+ const saved = ctx.state.landings.get(ctx.id);
441
+
442
+ if (!saved) throw new Error(`no landing is saved for ${ctx.id}`);
443
+
444
+ const first = await placementOf(ctx, saved.change);
445
+ const answered = answeredLevel(ctx.item, saved.since, levelNames(ctx.config));
446
+ const learns = first.placement.unclear.length > 0 && answered !== undefined;
447
+
448
+ if (learns) await learnRules(ctx, first.placement.unclear, answered);
449
+
450
+ const { placement, policy } = learns
451
+ ? await placementOf(ctx, saved.change)
452
+ : first;
453
+
454
+ if (placement.unclear.length > 0) await askUnclear(ctx, placement.unclear);
455
+
456
+ const diff = await ctx.git.raw(["diff", ...PATCH, `origin/${ctx.base}...${saved.head}`]);
457
+ const alignment = saved.change.paths.length > 0 ? await alignmentOf(ctx, saved, diff) : undefined;
458
+ const aligned = gatesAlignment(ctx.config.hum) && alignment && "graded" in alignment ? alignedPlacement(placement, alignment.graded, ctx.config.hum) : placement;
459
+ const routeWith = (verdict?: Verdict): Route => routeOf(aligned, policy.paths, ctx.kind, saved.change.paths, abstentionsOf(ctx, alignment, verdict));
460
+ const placed = routeWith();
461
+ const reviewed = needsReviewRun(placed) ? await verdictOn(ctx, { head: saved.head, diff, level: placed.level.name }) : undefined;
462
+
463
+ if (reviewed && "halted" in reviewed) return reviewed.halted;
464
+
465
+ const verdict = reviewed?.verdict;
466
+ const route = routeWith(verdict);
467
+ const approvals = { review: verdict?.event === REVIEW_APPROVAL, owner: saved.ownerApproved || ctx.item.thread.some(isOwnerApproval(saved.since)) };
468
+ const why = verdict && verdict.event !== REVIEW_APPROVAL ? `the review run answered ${verdict.event}: ${verdict.reason}` : waitReason(route);
469
+ const rules = ctx.pulls ? await ctx.pulls.rules(ctx.base) : NO_RULES;
470
+
471
+ return landBy(ctx, landingOf(rules.requiresPullRequest, isCleared(route, approvals)), route, rules, why);
472
+ };
473
+
474
+ /** The alignment call's grades for a saved change, made once and kept with the landing. */
475
+ const alignmentOf = async (ctx: LandContext, saved: SavedLanding, diff: string): Promise<NonNullable<SavedLanding["alignment"]>> => {
476
+ if (saved.alignment) return saved.alignment;
477
+
478
+ const judged = await ctx.judge({ ...alignmentQuestion(ctx.item, diff, ctx.config.hum), item: ctx.id });
479
+ const alignment = judged.kind === "picked" ? { graded: judged.value } : { abstained: judged.why };
480
+
481
+ ctx.state.landings.put(ctx.id, { ...saved, alignment });
482
+
483
+ return alignment;
484
+ };
485
+
486
+ /** The verdict on the change at `head`: the one saved for it, else a fresh review run. */
487
+ const verdictOn = async (ctx: LandContext, change: Parameters<LandContext["reviewRun"]>[0]): Promise<ReviewOutcome> => {
488
+ const saved = ctx.state.verdicts.get(ctx.id);
489
+
490
+ return saved?.head === change.head ? { verdict: saved } : ctx.reviewRun(change);
491
+ };
492
+
493
+ const abstained = (boundary: Boundary, why: string): Unclear => ({ cause: "abstained", boundary, why });
494
+
495
+ const unmeasured = (models: readonly string[]): string => `${models.join(", ") || "no model"} has no measured rate that meets the bar`;
496
+
497
+ /** Every model judgment behind the change that abstained, or came from a model id its boundary was not measured on. */
498
+ const abstentionsOf = (ctx: LandContext, alignment: SavedLanding["alignment"], verdict: Verdict | undefined): Unclear[] => {
499
+ const measured = (boundary: Boundary, models: readonly string[]): boolean => isTrusted(models, boundary, ctx.config.hum);
500
+ const kind = ctx.state.itemKinds.get(ctx.id);
501
+ const plan = ctx.state.plans.get(ctx.id);
502
+
503
+ return [
504
+ ...(kind?.from === "fallback" ? [abstained("kind", kind.why)] : []),
505
+ ...(gatesAlignment(ctx.config.hum) && alignment && "abstained" in alignment ? [abstained("alignment", alignment.abstained)] : []),
506
+ ...(plan && !measured("plan-outcome", plan.models) ? [abstained("plan-outcome", unmeasured(plan.models))] : []),
507
+ ...(verdict && !measured("review-verdict", verdict.models) ? [abstained("review-verdict", unmeasured(verdict.models))] : []),
508
+ ];
509
+ };
@@ -0,0 +1,97 @@
1
+ import { createActor, createAsyncLogic, setup, toPromise } from "xstate";
2
+ import { z } from "zod";
3
+
4
+ export type TickResult =
5
+ | { readonly kind: "ran"; readonly started: readonly string[] }
6
+ /** An update was seen; no new run starts, and the worker exits once its runs end. */
7
+ | { readonly kind: "draining"; readonly reason: string }
8
+ | { readonly kind: "exit"; readonly reason: string };
9
+
10
+ export type Exit = { readonly reason: string };
11
+
12
+ export type LifecycleOptions = {
13
+ readonly tick: () => Promise<TickResult>;
14
+ /** Stops every run in flight and resolves once they have ended. */
15
+ readonly stopRuns: () => Promise<void>;
16
+ readonly tickIntervalMs: number;
17
+ readonly drainTimeoutMs: number;
18
+ };
19
+
20
+ type Phase = "serving" | "draining" | "exited";
21
+
22
+ /** Where a tick's result leads, whichever phase the worker was in. */
23
+ const PHASE_AFTER = { ran: "serving", draining: "draining", exit: "exited" } as const satisfies Record<TickResult["kind"], Phase>;
24
+
25
+ const Context = z.object({ woken: z.boolean(), reason: z.string() });
26
+
27
+ type Context = z.infer<typeof Context>;
28
+
29
+ const STOPPED: Exit = { reason: "stopped" };
30
+
31
+ /** The transition after a tick: to the phase its result names, else straight into the next tick when woken, else to rest. */
32
+ const afterTick = (phase: Exclude<Phase, "exited">, context: Context, result: TickResult) => {
33
+ const next = PHASE_AFTER[result.kind];
34
+ const reason = result.kind === "ran" ? context.reason : result.reason;
35
+
36
+ if (next === "exited") return { target: "#worker.exited", context: { ...context, reason } };
37
+
38
+ if (next !== phase) return { target: `#worker.${next}.resting`, context: { ...context, reason } };
39
+
40
+ return context.woken ? { target: "ticking", reenter: true } : { target: "resting" };
41
+ };
42
+
43
+ /**
44
+ * The worker's life as a machine. It ticks, rests for the tick interval, and ticks again at once when woken; a
45
+ * wake that arrives during a tick makes one more tick, however many arrive. A tick that sees an update moves it to
46
+ * draining, where it still ticks, so claims are renewed and the heartbeat stays fresh, and the runs still going
47
+ * are stopped once the drain timeout passes. It ends when a tick finds nothing left to wait for, or on `stop`.
48
+ */
49
+ const lifecycleMachine = ({ tick, stopRuns, tickIntervalMs, drainTimeoutMs }: LifecycleOptions) => {
50
+ const worker = setup({
51
+ schemas: { context: Context, events: { wake: z.object({}), stop: z.object({}) } },
52
+ delays: { tickInterval: tickIntervalMs, drainTimeout: drainTimeoutMs },
53
+ actors: { tick: createAsyncLogic({ run: tick }), stopRuns: createAsyncLogic({ run: stopRuns }) },
54
+ });
55
+
56
+ const cycle = (phase: Exclude<Phase, "exited">) =>
57
+ ({
58
+ ticking: {
59
+ entry: ({ context }: { context: Context }) => ({ context: { ...context, woken: false } }),
60
+ invoke: { src: "tick", onDone: ({ context, event }: { context: Context; event: { output: TickResult } }) => afterTick(phase, context, event.output) },
61
+ on: { wake: ({ context }: { context: Context }) => ({ context: { ...context, woken: true } }) },
62
+ },
63
+ resting: {
64
+ after: { tickInterval: { target: "ticking" } },
65
+ on: { wake: { target: "ticking" } },
66
+ },
67
+ }) as const;
68
+
69
+ return worker.createMachine({
70
+ id: "worker",
71
+ context: { woken: false, reason: "" },
72
+ initial: "serving",
73
+ on: { stop: { target: "#worker.stopping" } },
74
+ states: {
75
+ serving: { initial: "ticking", states: cycle("serving") },
76
+ draining: { initial: "ticking", states: cycle("draining"), after: { drainTimeout: (_, enq) => void enq(() => void stopRuns()) } },
77
+ stopping: { on: { stop: undefined }, invoke: { src: "stopRuns", onDone: { target: "stopped" } } },
78
+ exited: { type: "final", output: ({ context }): Exit => ({ reason: context.reason }) },
79
+ stopped: { type: "final", output: STOPPED },
80
+ },
81
+ });
82
+ };
83
+
84
+ export type Lifecycle = { readonly wake: () => void; readonly ended: Promise<Exit> };
85
+
86
+ /** Starts the machine. `stop` ends it after the runs have stopped; `wake` asks for a tick now. */
87
+ export const runLifecycle = (options: LifecycleOptions, stop?: AbortSignal): Lifecycle => {
88
+ const actor = createActor(lifecycleMachine(options)).start();
89
+ const halt = () => actor.send({ type: "stop" });
90
+
91
+ if (stop?.aborted) halt();
92
+ else stop?.addEventListener("abort", halt, { once: true });
93
+
94
+ const ended: Promise<Exit> = toPromise(actor).finally(() => stop?.removeEventListener("abort", halt));
95
+
96
+ return { wake: () => actor.send({ type: "wake" }), ended };
97
+ };
@@ -0,0 +1,29 @@
1
+ import type { PullRequests } from "../adapters/pull-requests.ts";
2
+ import type { State } from "../state/open.ts";
3
+
4
+ /**
5
+ * An item's change reached the base: the merge is kept for the measure, the saved landing, plan and verdict go,
6
+ * and the merge is logged once per commit.
7
+ */
8
+ export const recordMerged = (state: State, item: string, sha: string, at: number): void => {
9
+ const landing = state.landings.get(item);
10
+
11
+ state.merges.put(item, { item, sha, at, paths: landing?.change.paths ?? [] });
12
+ state.landings.remove(item);
13
+ state.plans.remove(item);
14
+ state.verdicts.remove(item);
15
+ state.events.add({ source: "work-source", sourceId: `merged:${sha}`, itemId: item, type: "merged", payload: {} });
16
+ };
17
+
18
+ /**
19
+ * A change that landed through a pull request is merged by GitHub after the worker has moved on, and the item is never
20
+ * listed again. Each saved landing whose pull request has merged is recorded as merged, so the measure counts it.
21
+ */
22
+ export const settleMergedPulls = async (state: State, pulls: Pick<PullRequests, "find">, at: number): Promise<void> => {
23
+ for (const { item, branch, head } of state.landings.list()) {
24
+ if ((await pulls.find(branch))?.state !== "MERGED") continue;
25
+
26
+ recordMerged(state, item, head, at);
27
+ state.items.remove(item);
28
+ }
29
+ };