@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,886 @@
1
+ import { mkdtempSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { z } from "zod";
5
+ import { type AnyActor, createActor, createAsyncLogic } from "xstate";
6
+ import type { Item, Question, Questions, ThreadEntry, WorkSource } from "../adapter-api.ts";
7
+ import { type Finished, type Runner, succeeded } from "../adapters/claude-p.ts";
8
+ import { configuredModelCall, type ModelCall } from "../adapters/model-call.ts";
9
+ import { ADAPTER_API_VERSION } from "../adapter-api.ts";
10
+ import { onceCalls } from "../adapters/once.ts";
11
+ import { visibleText } from "../adapters/marked.ts";
12
+ import { type Git, gitIn, identityEnv, PATCH, push } from "../adapters/git.ts";
13
+ import type { PullRequests } from "../adapters/pull-requests.ts";
14
+ import { pickTier } from "../config/checks.ts";
15
+ import type { Config } from "../config/load.ts";
16
+ import { kindMachine } from "../config/machine.ts";
17
+ import { type Kind, type Naming, OWNER_WAIT_TAG, type PURPOSES, STUCK_TAG } from "../config/schema.ts";
18
+ import { commandTimeoutMs } from "../exec.ts";
19
+ import { leavesDocs } from "../decide/kind.ts";
20
+ import { type EventPick, type JsonSchema, jsonSchemaOf, type ProsePurpose, planHash, requestedChanges } from "../decide/prose.ts";
21
+ import { persistedSnapshot } from "../state/items.ts";
22
+ import type { State } from "../state/open.ts";
23
+ import { HOUR_MS, SECOND_MS } from "../time.ts";
24
+ import { runChecks } from "./checks.ts";
25
+ import { changeOn, type LandContext, land, placementOf, prepareLanding, type ReviewOutcome } from "./land.ts";
26
+ import { OWNER_APPROVAL } from "../decide/merge.ts";
27
+ import { askDecision, askedQuestion, isWaitQuestion, PLAIN_QUESTIONS, type PlainQuestion, RunReason } from "../decide/question.ts";
28
+ import type { Stage } from "../decide/answer.ts";
29
+ import { reviewInput } from "../decide/review.ts";
30
+ import { decideKind, forgetProgress, kindAnswered } from "./kind.ts";
31
+ import { settleAnswers } from "./answers.ts";
32
+ import { queueQuestion, releaseQuestions } from "./questions.ts";
33
+ import { memorySection, readMemory, rulesUsed } from "../loop/memory.ts";
34
+ import { proveCheckItem } from "../loop/prove-item.ts";
35
+ import { tallyOf } from "./tally.ts";
36
+ import { decideProse } from "./prose-run.ts";
37
+ import { footprintOf, type PrefixGate } from "./scheduler.ts";
38
+
39
+ /** How long a claim lasts unless its holder renews it. */
40
+ export const claimTtlMs = (config: Config): number => config.hum.claimExpirySeconds * SECOND_MS;
41
+
42
+ const CARD_EXCERPT = 300;
43
+
44
+ const ERROR_EXCERPT = 500;
45
+
46
+ /** The branch runs start from when none is given. */
47
+ export const DEFAULT_BASE = "main";
48
+
49
+ export const runBranch = ({ runBranchPrefix }: Naming, id: string): string => `${runBranchPrefix}${id}`;
50
+
51
+ /** What the agent run hands back besides its commit. */
52
+ export const RUN_SCHEMA = jsonSchemaOf(z.object({ status: z.enum(["done", "needs-owner"]), question: z.string().optional(), plan: z.string().optional(), reason: RunReason.optional(), memoryUsed: z.array(z.int().positive()).optional() }));
53
+
54
+ /** The comment that carries a run's plan on the item's thread, so the next run reads it. */
55
+ export const PLAN_MARK = "hum plan:";
56
+
57
+ export type ThinPathOptions = {
58
+ readonly workSource: WorkSource;
59
+ readonly questions: Questions;
60
+ readonly state: State;
61
+ readonly runner: Runner;
62
+ readonly config: Config;
63
+ /** The cheap model call; by default the config's decision model through the runner. */
64
+ readonly judge?: ModelCall;
65
+ /** The work repo's remote: a URL or path. Runs clone it; nothing touches the owner's checkout. */
66
+ readonly remote: string;
67
+ readonly base?: string;
68
+ /** The repo's checks as shell commands, run in the clone. All must exit 0. */
69
+ readonly checks: readonly string[];
70
+ readonly holder: string;
71
+ /** Where runs clone to; a temp folder by default. */
72
+ readonly workDir?: string;
73
+ /** Gives the run its working copy on the remote's base branch, and takes it back when the item's pass ends. By default a `git clone` in a temp folder. */
74
+ readonly checkout?: Checkout;
75
+ readonly dir?: string;
76
+ /** Take this item; default the first ready one. */
77
+ readonly itemId?: string;
78
+ readonly now?: () => number;
79
+ /** Aborted when the worker loses the claim or exits for an update; the run stops and the result is `lost`. */
80
+ readonly signal?: AbortSignal;
81
+ /** Lets the first run of a shared prompt prefix reach its first token before the rest start. */
82
+ readonly gate?: PrefixGate;
83
+ /** The remote's pull requests and branch rules, for a remote on GitHub. */
84
+ readonly pulls?: PullRequests;
85
+ /** The names, never the values, of the variables the runs have; a missing secret is checked against them. Default: this process's. */
86
+ readonly runnerVariables?: ReadonlySet<string>;
87
+ /** False while the worker drains for an update: a finished change is saved and pushed, and the next worker lands it under the config it starts with. */
88
+ readonly mayLand?: () => boolean;
89
+ };
90
+
91
+ export type ThinResult =
92
+ | { readonly outcome: "idle" }
93
+ | { readonly outcome: "lost" | "waiting"; readonly item: string }
94
+ /** The item's change showed it is another kind: it runs again from the start as that kind, on the same branch. */
95
+ | { readonly outcome: "moved"; readonly item: string; readonly kind: string }
96
+ | { readonly outcome: "merged" | "asked" | "stuck" | "review" | "landing"; readonly item: string; readonly detail?: string }
97
+ | { readonly outcome: "limited"; readonly item: string; readonly until: number }
98
+ | { readonly outcome: "held"; readonly item: string; readonly why: string };
99
+
100
+ type Answered = { readonly question: string; readonly answer: string; readonly option: string | undefined; readonly plan: string };
101
+
102
+ /** The question, the answer to it and the plan, once the owner has answered the latest question. */
103
+ export const answerTo = (item: Item): Answered | undefined => {
104
+ const lastQuestion = item.thread.findLastIndex((e) => e.kind === "question");
105
+ const answer = item.thread.slice(lastQuestion + 1).find((e) => e.kind === "answer");
106
+
107
+ if (lastQuestion < 0 || !answer) return undefined;
108
+
109
+ const plan = item.thread.findLast((e) => e.kind === "comment" && e.text.startsWith(PLAN_MARK));
110
+
111
+ return {
112
+ question: item.thread[lastQuestion]?.text ?? "",
113
+ answer: answer.option ? `${answer.option}: ${answer.text}` : answer.text,
114
+ option: answer.option,
115
+ plan: plan?.text.slice(PLAN_MARK.length).trim() ?? "",
116
+ };
117
+ };
118
+
119
+ /** The question the item's latest hum question puts, when it is one the item waits on and no applied answer follows it. */
120
+ export const unansweredQuestion = (item: Item): ThreadEntry | undefined => {
121
+ const last = item.thread.findLastIndex((e) => e.kind === "question" && e.author !== "person");
122
+ const question = item.thread[last];
123
+
124
+ return question && isWaitQuestion(visibleText(question.text)) && !item.thread.slice(last + 1).some((e) => e.kind === "answer") ? question : undefined;
125
+ };
126
+
127
+ /** Whether the kind's machine takes the owner's approval of a change in this state. */
128
+ const isApprovalWait = (kind: Kind, state: string | undefined): boolean => state !== undefined && kind.machine.states[state]?.on?.[OWNER_APPROVED] !== undefined;
129
+
130
+ const Wants = z.looseObject({ status: z.string().optional(), question: z.string().optional(), plan: z.string().optional(), reason: RunReason.optional() });
131
+
132
+ /** The kind as it stood at an earlier machine version, kept by `rememberKinds`, so a saved item restores across a change. */
133
+ const earlierKinds = (state: State, kind: Kind) => (machineVersion: string) => state.kinds.get(`${kind.machine.id}@${machineVersion}`);
134
+
135
+ /** Saves every kind under its machine version. Call it whenever a config is loaded. */
136
+ export const rememberKinds = (state: State, config: Config): void => {
137
+ for (const kind of Object.values(config.kinds)) state.kinds.put(`${kind.machine.id}@${kind.machine.version}`, kind);
138
+ };
139
+
140
+ /** Whether the kind's machine tags this state with `tag`. */
141
+ const hasTag = (kind: Kind, state: string | undefined, tag: string): boolean => (state !== undefined && kind.machine.states[state]?.tags?.includes(tag)) ?? false;
142
+
143
+ export const waitsOnOwner = (kind: Kind, state: string | undefined): boolean => hasTag(kind, state, OWNER_WAIT_TAG);
144
+
145
+ export const endedStuck = (kind: Kind, state: string | undefined): boolean => hasTag(kind, state, STUCK_TAG);
146
+
147
+ /** Placeholder sources: enough to restore a snapshot and read its state before the real sources exist. */
148
+ const stubSources = (kind: Kind) => {
149
+ const idle = createAsyncLogic({ run: async () => {} });
150
+
151
+ return Object.fromEntries(Object.values(kind.machine.states).flatMap((node) => (node.invoke ? [[node.invoke.src, idle]] : [])));
152
+ };
153
+
154
+ /**
155
+ * The thin path: a ready markdown item is claimed, built by a `claude -p` run on its run branch,
156
+ * checked by the repo's own checks, and merged in one push that also sets the item's state to done, when its
157
+ * paths are all at the lowest level. A run that needs the owner pushes its branch, asks on the item and
158
+ * ends; the answer starts a fresh run on that branch. Never `--resume`.
159
+ */
160
+ const kindNamed = (config: Config, name: string): Kind => {
161
+ const kind = config.kinds[name];
162
+
163
+ if (!kind) throw new Error(`no kind "${name}" in the config`);
164
+
165
+ return kind;
166
+ };
167
+
168
+ export const runThinPath = async (options: ThinPathOptions): Promise<ThinResult> => {
169
+ const o: WithNow = { ...options, now: options.now ?? Date.now };
170
+ const base = o.base ?? DEFAULT_BASE;
171
+ const id = o.itemId ?? (await o.workSource.listReady())[0]?.id;
172
+
173
+ if (id === undefined) return { outcome: "idle" };
174
+
175
+ // A parked item stays parked until the owner acts: its file still says ready, and a rerun would spend the same tokens again.
176
+ const parked = o.state.parked.get(id);
177
+
178
+ if (parked) return { outcome: parked.why, item: id, detail: parked.cause };
179
+
180
+ // An item gets its kind before its first snapshot, so an item with no saved kind has nothing to restore.
181
+ const known = o.state.itemKinds.get(id);
182
+ const knownKind = known && kindNamed(o.config, known.kind);
183
+ const saved = knownKind ? await o.state.items.restore(id, knownKind, { sources: stubSources(knownKind), kindAt: earlierKinds(o.state, knownKind) }) : ({ ok: true, value: undefined } as const);
184
+
185
+ if (!saved.ok) return { outcome: "held", item: id, why: saved.fault.cause };
186
+
187
+ const at = saved.value === undefined ? undefined : String(saved.value.getSnapshot().value);
188
+
189
+ if (knownKind && endedStuck(knownKind, at)) return park(o, { outcome: "stuck", item: id, detail: "the saved state ended stuck" });
190
+
191
+ const claim = await o.workSource.claim(id, o.holder, claimTtlMs(o.config));
192
+
193
+ if (!claim.won) return { outcome: "lost", item: id };
194
+
195
+ const judge = o.judge ?? configuredModelCall(o.runner, o.config.hum, (item, tokens) => tallyOf(o.state, item).spend(tokens));
196
+ const { now } = o;
197
+ const onSnapshot = saved.value !== undefined;
198
+ const waitingState = knownKind && waitsOnOwner(knownKind, at);
199
+ const stage: Stage = o.state.landings.get(id) ? "approval" : waitingState ? (knownKind && isApprovalWait(knownKind, at) ? "approval" : "waiting") : onSnapshot ? "running" : "waiting";
200
+ const item = await settleAnswers({ state: o.state, workSource: o.workSource, judge, now }, await o.workSource.read(id), { stage });
201
+ const named = known && kindAnswered(known, item, o.config.hum.kinds);
202
+
203
+ if (named) o.state.itemKinds.put(id, named);
204
+
205
+ if (named && named.kind !== known?.kind) {
206
+ forgetProgress(o.state, id);
207
+
208
+ return { outcome: "moved", item: id, kind: named.kind };
209
+ }
210
+
211
+ // With no saved wait, the thread alone says whether the owner has been asked and has not answered; its age is the deadline.
212
+ const unanswered = onSnapshot ? undefined : unansweredQuestion(item);
213
+
214
+ if (unanswered) return unanswered.at + o.config.hum.questionTimeoutHours * HOUR_MS < now() ? park(o, { outcome: "stuck", item: id, detail: `no answer came within ${o.config.hum.questionTimeoutHours} hours` }) : { outcome: "waiting", item: id };
215
+
216
+ const kindName = (named ?? known ?? (await decideKind({ ...o, judge, now }, item))).kind;
217
+ const kind = kindNamed(o.config, kindName);
218
+ const asking = waitsOnOwner(kind, at);
219
+ const answered = asking || !onSnapshot ? answerTo(item) : undefined;
220
+
221
+ if (asking && answered === undefined) return { outcome: "waiting", item: id };
222
+
223
+ const landing = o.state.landings.get(id);
224
+ const branch = runBranch(o.config.hum, id);
225
+ const timeoutMs = commandTimeoutMs(o.config.hum);
226
+ const taken = await (o.checkout ?? clonesIn(o.workDir, timeoutMs))({ remote: o.remote, base, item: id, signal: o.signal }).catch((error: Error) => (o.signal?.aborted ? undefined : Promise.reject(error)));
227
+
228
+ if (taken === undefined) return { outcome: "lost", item: id };
229
+
230
+ const { folder: clone } = taken;
231
+ const { commitIdentity } = o.config.hum;
232
+ /** The agent's own commits take the owner's identity too: a fresh clone holds none of the repo's local git config. */
233
+ const env = { ...identityEnv(commitIdentity), ...taken.env };
234
+ const git = gitIn(clone, { identity: commitIdentity, timeoutMs });
235
+ const g = (args: readonly string[]): Promise<string> => git.raw(args);
236
+
237
+ try {
238
+ await onRunBranch(git, branch);
239
+
240
+ const driven: Driven = { ...o, base, dir: o.dir ?? o.config.hum.itemsDir, kindName, kind, judge, id, item, branch, clone, env, g, git, answered, resume: asking };
241
+
242
+ // A change already finished lands again from its pushed branch; no run is spent on it.
243
+ const result = park(o, landing ? await landAgain(driven) : await drive(driven));
244
+
245
+ if (result.outcome === "moved") forgetProgress(o.state, id);
246
+
247
+ return result;
248
+ } finally {
249
+ await taken.giveBack();
250
+ }
251
+ };
252
+
253
+ /** Where a run's working copy comes from: the remote and the branch it starts on. */
254
+ export type Source = { readonly remote: string; readonly base: string };
255
+
256
+ /** What a checkout is asked for: a working copy of `source` for the item's pass, and the signal that ends the wait for one. */
257
+ export type CheckoutRequest = Source & { readonly item: string; readonly signal: AbortSignal | undefined };
258
+
259
+ /** A run's working copy: its folder, the environment its runs and checks add, and the call that takes it back. */
260
+ export type Checkedout = {
261
+ readonly folder: string;
262
+ readonly env: Readonly<Record<string, string>>;
263
+ readonly giveBack: () => Promise<void>;
264
+ };
265
+
266
+ /**
267
+ * Gives an item's pass its working copy, with the base branch's files. A background run starts only in a repo the
268
+ * owner trusts, which a fresh clone is not; a slot is a worktree of the owner's checkout.
269
+ */
270
+ export type Checkout = (request: CheckoutRequest) => Promise<Checkedout>;
271
+
272
+ /** A fresh `git clone` in a new folder under `workDir` (a temp folder by default), removed when the pass ends. */
273
+ const clonesIn =
274
+ (workDir: string | undefined, timeoutMs: number): Checkout =>
275
+ async ({ remote, base }) => {
276
+ const folder = mkdtempSync(join(workDir ?? tmpdir(), "hum-run-"));
277
+
278
+ await gitIn(tmpdir(), { timeoutMs }).raw(["clone", "-q", "--branch", base, remote, folder]);
279
+
280
+ return { folder, env: {}, giveBack: async () => rmSync(folder, { recursive: true, force: true }) };
281
+ };
282
+
283
+ /**
284
+ * Checks out the run branch: from the remote when it has it, from the folder when only the folder does (a pass that
285
+ * ended before it pushed), and new from the current commit when neither does. A folder and the remote that disagree
286
+ * throw: neither is dropped.
287
+ */
288
+ const onRunBranch = async (git: Git, branch: string): Promise<void> => {
289
+ const onRemote = (await git.raw(["ls-remote", "--heads", "origin", branch])).trim() !== "";
290
+ const onFolder = (await git.run(["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`])).code === 0;
291
+
292
+ if (onRemote) await git.raw(["fetch", "-q", "origin", branch]);
293
+
294
+ if (!onFolder) return void (await git.raw(onRemote ? ["checkout", "-q", "-b", branch, "FETCH_HEAD"] : ["checkout", "-q", "-b", branch]));
295
+
296
+ await git.raw(["checkout", "-q", branch]);
297
+
298
+ if (onRemote) await git.raw(["merge", "--ff-only", "-q", "FETCH_HEAD"]);
299
+ };
300
+
301
+ /** The options with the clock every later step reads. */
302
+ type WithNow = ThinPathOptions & { readonly now: () => number };
303
+
304
+ type Driven = WithNow & {
305
+ readonly kindName: string;
306
+ readonly judge: ModelCall;
307
+ readonly base: string;
308
+ readonly dir: string;
309
+ readonly kind: Kind;
310
+ readonly id: string;
311
+ readonly item: Item;
312
+ readonly branch: string;
313
+ readonly clone: string;
314
+ readonly env: Readonly<Record<string, string>>;
315
+ readonly g: (args: readonly string[]) => Promise<string>;
316
+ readonly git: Git;
317
+ readonly answered: Answered | undefined;
318
+ /** Restore the saved owner-wait snapshot instead of starting the machine. */
319
+ readonly resume: boolean;
320
+ };
321
+
322
+ const drive = async (d: Driven): Promise<ThinResult> => {
323
+ const { state, runner, config, kind, id, item, branch, clone, g, base } = d;
324
+ const maxFixes = config.hum.maxFixRuns;
325
+ const result = Promise.withResolvers<ThinResult>();
326
+
327
+ // The worker lost the claim or is exiting for an update: the run stops, and its actor with it.
328
+ d.signal?.addEventListener("abort", () => result.resolve({ outcome: "lost", item: id }), { once: true });
329
+ // The total over all runs is saved; the cap counts what the item spent since the owner last answered.
330
+ const tally = tallyOf(state, id);
331
+
332
+ if (d.answered) tally.startAfresh();
333
+
334
+ let fixes = 0;
335
+ let lastFailure = "";
336
+ let cause = "";
337
+ let handled = "";
338
+ let pending: Pending | undefined;
339
+ let approvedByOwner = false;
340
+ let actor: AnyActor;
341
+
342
+ const stuckCause = (): string | undefined => cause || lastFailure.slice(0, CARD_EXCERPT) || undefined;
343
+
344
+ const failed = (message: string): Error => {
345
+ cause = message;
346
+
347
+ return new Error(message);
348
+ };
349
+
350
+ /** A plan or build is placed by the files its item declares; a fix or review by the branch's diff so far. */
351
+ const tierFor = async (purpose: Purpose) => {
352
+ const declared = { paths: footprintOf(item) ?? [], size: 0, loosened: false, pinChanged: false };
353
+ const change = PLACED_BY_DIFF[purpose] ? await changeOn(landContext(d)) : declared;
354
+ const { placement } = await placementOf(landContext(d), change);
355
+ const row = pickTier(kind, { purpose, level: placement.level.name, size: "small" });
356
+
357
+ if (!row) throw new Error(`the ${d.kindName} table has no ${purpose} row`);
358
+
359
+ return { model: config.hum.models[row.tier], effort: row.effort };
360
+ };
361
+
362
+
363
+ const branchDiff = (): Promise<string> => g(["diff", ...PATCH, `origin/${base}...HEAD`]);
364
+
365
+ const prompt = async (purpose: "build" | "fix"): Promise<string> => {
366
+ const plan = state.plans.get(id);
367
+
368
+ const parts = [
369
+ roleOf(config, purpose),
370
+ `# Item ${id}: ${item.title}\n\n${item.body}`,
371
+ `Work on the branch ${branch}. Commit the change when it is whole. End with the JSON {"status":"done"}, or {"status":"needs-owner","question":…,"plan":…} when only the owner can answer.`,
372
+ ];
373
+
374
+ if (plan) parts.push(`## The approved plan (${plan.hash})\n${JSON.stringify(plan.plan, null, 2)}`);
375
+
376
+ if (d.answered) {
377
+ const diff = await branchDiff();
378
+
379
+ parts.push(
380
+ `## The owner answered\nQuestion: ${d.answered.question}\nAnswer: ${d.answered.answer}\n\n## The plan so far\n${d.answered.plan || "(none saved)"}\n\n## The branch so far\n${diff.slice(0, config.hum.diffLimit)}`,
381
+ );
382
+ }
383
+
384
+ if (purpose === "fix") parts.push(`## What to fix\n${lastFailure.slice(-config.hum.failureTail)}\nFix the cause and commit.`);
385
+
386
+ return parts.join("\n\n");
387
+ };
388
+
389
+
390
+
391
+ /** Never settles: the driver stops the actor, so the saved snapshot stays at the state it was in. */
392
+ const pause = (outcome: ThinResult): Promise<never> => {
393
+ result.resolve(outcome);
394
+
395
+ return new Promise<never>(() => {});
396
+ };
397
+
398
+ /** The kinds reach their owner-wait state only through the over-cap event, so a run's question uses it too. */
399
+ const ask = (note: Pending) => {
400
+ pending = note;
401
+ actor.send({ type: "token-cap" });
402
+ };
403
+
404
+ /** One agent run of the item. A limit, a hold or a stop pauses the item; passing the token cap asks the owner where the state can, and ends stuck where it cannot. */
405
+ const runAgent = async (purpose: Purpose, text: string, schema: JsonSchema, signal: AbortSignal): Promise<Finished> => {
406
+ const attempt = state.runs.unended(id, purpose)?.attempt ?? state.runs.list(id).length;
407
+ const key = { itemId: id, run: purpose, attempt };
408
+ const begun = state.runs.begin(key, `hum ${id} ${purpose} #${attempt}`, crypto.randomUUID());
409
+ const held = purpose === "build" || purpose === "fix" ? readMemory(join(clone, ".hum", "memory.md")) : [];
410
+ const prefix = config.hum.roles[purpose]?.file ?? purpose;
411
+
412
+ const lease = await d.gate?.enter(prefix, signal);
413
+
414
+ const outcome = await runner
415
+ .run({
416
+ prompt: `${text}${memorySection(held)}`,
417
+ cwd: purpose === "review" ? tmpdir() : clone,
418
+ env: d.env,
419
+ ...(await tierFor(purpose)),
420
+ schema,
421
+ tokenCap: kind.tokenCap.tokens - tally.sinceAnswer(),
422
+ name: begun.record.name,
423
+ // A saved id already has a transcript under it; a fresh run mints its own.
424
+ sessionId: begun.adopted ? undefined : begun.record.sessionId,
425
+ signal,
426
+ onSession: (sessionId) => state.runs.saveSession(key, sessionId),
427
+ onFirstToken: () => lease?.opened(),
428
+ })
429
+ .finally(() => lease?.release());
430
+
431
+ state.runs.end(key, held.length === 0 ? undefined : outcome.kind === "finished" ? rulesUsed(outcome, held) : []);
432
+
433
+ if (outcome.kind === "limited") return pause({ outcome: "limited", item: id, until: outcome.until });
434
+
435
+ if (outcome.kind === "held") return pause({ outcome: "held", item: id, why: outcome.card.cause });
436
+
437
+ if (outcome.kind === "stopped") return pause({ outcome: "lost", item: id });
438
+
439
+ if (outcome.kind === "over-cap") {
440
+ tally.spend(outcome.tokens);
441
+
442
+ const why = `The run passed its token cap (${kind.tokenCap.tokens}) at ${tally.sinceAnswer()} tokens.`;
443
+
444
+ if (!actor.getSnapshot().can({ type: "token-cap" })) throw failed(why);
445
+
446
+ ask({ question: { text: PLAIN_QUESTIONS["over-cap"], detail: why }, plain: "over-cap", plan: "" });
447
+
448
+ return new Promise<never>(() => {});
449
+ }
450
+
451
+ tally.spend(outcome.tokens);
452
+
453
+ return outcome;
454
+ };
455
+
456
+ /** The owner is asked, or the run's choice stands and is listed under the choices made without them. */
457
+ const settleNeed = async (wants: z.infer<typeof Wants>): Promise<{ asked: Pending } | { chose: string }> => {
458
+ const reason = wants.reason ?? { kind: "unsure" as const };
459
+ const change = await changeOn(landContext(d));
460
+ const { placement } = await placementOf(landContext(d), change);
461
+
462
+ const decision = askDecision(reason, {
463
+ runnerVariables: d.runnerVariables ?? new Set(Object.keys(process.env)),
464
+ changedPaths: change.paths,
465
+ level: placement.level.name,
466
+ undoableLevels: config.hum.undoableLevels,
467
+ });
468
+
469
+ if (decision.action === "ask") return { asked: { ...askedQuestion(reason, decision.confirmed, wants.question), plan: wants.plan ?? "" } };
470
+
471
+ const text = `Chose "${decision.choice}" over ${decision.over.filter((word) => word !== decision.choice).join(", ")} without you.`;
472
+ const calls = onceCalls({ apiVersion: ADAPTER_API_VERSION, workSource: d.workSource, questions: d.questions }, state.ops, { run: "decide", attempt: state.runs.list(id).length });
473
+
474
+ await calls.questions?.decide(id, text);
475
+ state.choices.put(`${id}@${text}`, { item: id, text, at: (d.now ?? Date.now)() });
476
+
477
+ return { chose: text };
478
+ };
479
+
480
+ const step = (purpose: "build" | "fix") =>
481
+ createAsyncLogic({
482
+ run: async ({ signal }) => {
483
+ if (purpose === "fix" && ++fixes > maxFixes) throw failed(`the checks still fail after ${maxFixes} fixes`);
484
+
485
+ const before = (await g(["rev-parse", "HEAD"])).trim();
486
+ const chosen: string[] = [];
487
+
488
+ for (;;) {
489
+ const outcome = await runAgent(purpose, `${await prompt(purpose)}${chosenSection(chosen)}`, RUN_SCHEMA, signal);
490
+
491
+ if (!succeeded(outcome)) throw failed(`the ${purpose} run ended as ${outcome.subtype}: ${outcome.text.slice(0, CARD_EXCERPT)}`);
492
+
493
+ const wants = Wants.safeParse(outcome.structured).data;
494
+
495
+ if (wants?.status !== "needs-owner") break;
496
+
497
+ const settled = await settleNeed(wants);
498
+
499
+ if ("asked" in settled) return ask(settled.asked);
500
+
501
+ chosen.push(settled.chose);
502
+ }
503
+
504
+ // Done is a new commit on the branch, not the run's word.
505
+ if ((await g(["rev-parse", "HEAD"])).trim() === before) throw failed(`the ${purpose} run succeeded and committed nothing`);
506
+ },
507
+ });
508
+
509
+ const checksSource = createAsyncLogic({
510
+ run: async () => {
511
+ const failure = await runChecks(d.checks, clone, { env: d.env });
512
+
513
+ if (failure) {
514
+ lastFailure = failure;
515
+ throw new Error(failure.slice(0, ERROR_EXCERPT));
516
+ }
517
+ },
518
+ });
519
+
520
+ const ownerQuestion = (pick: EventPick) => {
521
+ pending = { question: { text: pick.question || pick.reason }, plain: "unsure", plan: "" };
522
+ };
523
+
524
+ /** What a taken pick leaves behind before the machine moves on. */
525
+ const PICKED = new Map<string, (pick: EventPick, models: readonly string[]) => void>([
526
+ ["plan-ready", (pick, models) => pick.plan && state.plans.put(id, { item: id, plan: pick.plan, hash: planHash(pick.plan), models: [...models] })],
527
+ ["plan-blocked", ownerQuestion],
528
+ ["needs-owner", ownerQuestion],
529
+ [
530
+ "request-changes",
531
+ (pick) => {
532
+ lastFailure = requestedChanges(pick);
533
+ },
534
+ ],
535
+ ]);
536
+
537
+ const saveVerdict = (pick: EventPick, models: readonly string[], head: string) =>
538
+ state.verdicts.put(id, { item: id, head, event: pick.event, reason: pick.reason, cites: pick.cites, models: [...models] });
539
+
540
+ /** A plan or review state: its run picks the next event, and a split files the parts and lands the item as done. */
541
+ const decision = (purpose: ProsePurpose) =>
542
+ createAsyncLogic({
543
+ run: async ({ signal }) => {
544
+ const diff = purpose === "review" ? await branchDiff() : "";
545
+ const head = (await g(["rev-parse", "HEAD"])).trim();
546
+
547
+ const { pick, models } = await decideProse({
548
+ purpose,
549
+ prompt: PROSE_PROMPTS[purpose](config, item, diff),
550
+ diff,
551
+ model: (await tierFor(purpose)).model,
552
+ run: (text, schema) => runAgent(purpose, text, schema, signal),
553
+ canTake: (type) => actor.getSnapshot().can({ type }),
554
+ });
555
+
556
+ if (purpose === "review") saveVerdict(pick, models, head);
557
+
558
+ PICKED.get(pick.event)?.(pick, models);
559
+
560
+ if (pick.event === SPLIT) return result.resolve(await split(d, pick.parts, () => actor.send({ type: SPLIT })));
561
+
562
+ actor.send({ type: pick.event });
563
+ },
564
+ });
565
+
566
+ const sources = { build: step("build"), checks: checksSource, fix: step("fix"), plan: decision("plan"), review: decision("review") };
567
+
568
+ if (d.resume) {
569
+ const restored = await state.items.restore(id, kind, { sources, kindAt: earlierKinds(state, kind) });
570
+
571
+ if (!restored.ok) return { outcome: "held", item: id, why: restored.fault.cause };
572
+
573
+ if (!restored.value) return { outcome: "held", item: id, why: `the saved state of ${id} vanished` };
574
+
575
+ actor = restored.value;
576
+ // The wait it was saved in is already handled; only what follows the answer needs a reaction.
577
+ handled = String(actor.getSnapshot().value);
578
+ } else {
579
+ actor = createActor(kindMachine(kind, sources));
580
+ }
581
+
582
+ const react = async (value: string) => {
583
+ if (handled === value) return;
584
+
585
+ handled = value;
586
+
587
+ if (endedStuck(kind, value)) return result.resolve({ outcome: "stuck", item: id, detail: stuckCause() });
588
+
589
+ if (waitsOnOwner(kind, value)) {
590
+ const note = pending ?? { question: { text: "The run stopped for the owner." }, plain: "unsure" as const, plan: "" };
591
+
592
+ if (!(await stillMine(d))) return result.resolve({ outcome: "lost", item: id });
593
+
594
+ await handOff(d, isApprovalWait(kind, value) ? approvalQuestion(note) : note);
595
+
596
+ return result.resolve({ outcome: "asked", item: id, detail: note.question.text });
597
+ }
598
+
599
+ if (value === "merging") return result.resolve(await merge(d, () => actor.send({ type: "merged" }), approvedByOwner));
600
+ };
601
+
602
+ actor.subscribe((snapshot) => {
603
+ const saved = state.items.save(id, kind, persistedSnapshot(actor));
604
+
605
+ if (!saved.ok) result.reject(new Error(saved.fault.cause));
606
+
607
+ if (snapshot.status === "done") {
608
+ state.items.remove(id);
609
+
610
+ return result.resolve({ outcome: "merged", item: id });
611
+ }
612
+
613
+ react(String(snapshot.value)).catch((error) => result.reject(error));
614
+ });
615
+
616
+ actor.start();
617
+
618
+ if (d.answered && d.resume) {
619
+ const resume = resumeEvent(actor.getSnapshot(), d.answered);
620
+
621
+ approvedByOwner = resume === OWNER_APPROVED;
622
+
623
+ if (resume === OWNER_REJECTED) lastFailure = d.answered.answer;
624
+
625
+ actor.send({ type: resume });
626
+ }
627
+
628
+ return result.promise.finally(() => actor.stop());
629
+ };
630
+
631
+ /** What a run left for the owner: the question, the plain one it falls back to, and the plan so far. */
632
+ type Pending = { readonly question: Question; readonly plain: PlainQuestion; readonly plan: string };
633
+
634
+ const chosenSection = (chosen: readonly string[]): string => (chosen.length === 0 ? "" : `\n\n## Decided without the owner\n${chosen.map((text) => `- ${text}`).join("\n")}\nGo on with these choices.`);
635
+
636
+ const OWNER_APPROVED = "owner-approved";
637
+
638
+ const OWNER_REJECTED = "owner-rejected";
639
+
640
+ const ANSWERED = "answered";
641
+
642
+ /** The event an owner's answer sends a saved wait: `answered` where the state takes it, else the owner's approval or rejection of the change. */
643
+ const resumeEvent = (snapshot: { can: (event: { type: string }) => boolean }, answered: Answered) => {
644
+ if (snapshot.can({ type: ANSWERED })) return ANSWERED;
645
+
646
+ return answered.option === OWNER_APPROVAL ? OWNER_APPROVED : OWNER_REJECTED;
647
+ };
648
+
649
+ type Purpose = (typeof PURPOSES)[number];
650
+
651
+ /** Which runs are placed by the branch's diff so far; the others by the files their item declares. */
652
+ const PLACED_BY_DIFF = { plan: false, build: false, fix: true, review: true } as const satisfies Record<Purpose, boolean>;
653
+
654
+ /** The event by which a plan run splits its item into parts. */
655
+ const SPLIT = "needs-split";
656
+
657
+ /** What a run reads from its config: the settings and the role files. */
658
+ export type RunConfig = Pick<Config, "hum" | "roles">;
659
+
660
+ const roleOf = (config: RunConfig, purpose: Purpose): string => {
661
+ const role = config.hum.roles[purpose];
662
+
663
+ return ((role && config.roles[role.file]) ?? "").trim();
664
+ };
665
+
666
+ type ItemText = Pick<Item, "id" | "title" | "body">;
667
+
668
+ /** What a plan or review run reads. A plan run reads the repo too; a review run reads only the item and the diff, so no author's reasoning reaches it. */
669
+ export const PROSE_PROMPTS = {
670
+ plan: (config: RunConfig, item: ItemText): string =>
671
+ [
672
+ roleOf(config, "plan"),
673
+ `# Item ${item.id}: ${item.title}\n\n${item.body}`,
674
+ "Plan the change: read the repo, edit nothing. A plan-ready answer holds the plan; a needs-split answer names each part as a title; a plan-blocked answer asks the owner one question.",
675
+ ].join("\n\n"),
676
+ review: (config: RunConfig, item: ItemText, diff: string): string => [roleOf(config, "review"), reviewInput(item, diff, config.hum)].join("\n\n"),
677
+ } as const satisfies Record<ProsePurpose, (config: RunConfig, item: ItemText, diff: string) => string>;
678
+
679
+ const verdictOf = (id: string, head: string, pick: EventPick, models: readonly string[]) => ({ item: id, head, event: pick.event, reason: pick.reason, cites: pick.cites, models: [...models] });
680
+
681
+ /** A run that ended with no answer to read, carried out of the decision as the result it comes to. */
682
+ class Halted extends Error {
683
+ override name = "Halted";
684
+
685
+ constructor(readonly result: ThinResult) {
686
+ super(`the run halted: ${result.outcome}`);
687
+ }
688
+ }
689
+
690
+ const HALTS = {
691
+ limited: (id: string, outcome: { until: number }): ThinResult => ({ outcome: "limited", item: id, until: outcome.until }),
692
+ held: (id: string, outcome: { card: { cause: string } }): ThinResult => ({ outcome: "held", item: id, why: outcome.card.cause }),
693
+ "over-cap": (id: string, cap: number, spent: number): ThinResult => ({ outcome: "review", item: id, detail: `the review run passed the item's token cap (${cap}) at ${spent} tokens` }),
694
+ } as const;
695
+
696
+ /** A fresh review run at landing, for a level that asks for one: it reads only the item and the diff, and its verdict is saved. */
697
+ const reviewAtLanding =
698
+ (d: Driven) =>
699
+ async ({ head, diff, level }: { head: string; diff: string; level: string }): Promise<ReviewOutcome> => {
700
+ const row = pickTier(d.kind, { purpose: "review", level, size: "small" });
701
+
702
+ if (!row) throw new Error(`the ${d.kindName} table has no review row`);
703
+
704
+ const run = async (prompt: string, schema: JsonSchema): Promise<Finished> => {
705
+ const tally = tallyOf(d.state, d.id);
706
+ const outcome = await d.runner.run({ prompt, cwd: tmpdir(), model: d.config.hum.models[row.tier], effort: row.effort, schema, signal: d.signal, tokenCap: d.kind.tokenCap.tokens - tally.sinceAnswer() });
707
+
708
+ if (outcome.kind === "limited") throw new Halted(HALTS.limited(d.id, outcome));
709
+
710
+ if (outcome.kind === "held") throw new Halted(HALTS.held(d.id, outcome));
711
+
712
+ if (outcome.kind === "over-cap") {
713
+ tally.spend(outcome.tokens);
714
+
715
+ throw new Halted(HALTS["over-cap"](d.id, d.kind.tokenCap.tokens, tally.sinceAnswer()));
716
+ }
717
+
718
+ if (outcome.kind !== "finished") throw new Halted({ outcome: "lost", item: d.id });
719
+
720
+ tally.spend(outcome.tokens);
721
+
722
+ return outcome;
723
+ };
724
+
725
+ try {
726
+ const { pick, models } = await decideProse({ purpose: "review", prompt: PROSE_PROMPTS.review(d.config, d.item, diff), diff, model: d.config.hum.models[row.tier], run });
727
+ const verdict = verdictOf(d.id, head, pick, models);
728
+
729
+ d.state.verdicts.put(d.id, verdict);
730
+
731
+ return { verdict };
732
+ } catch (error) {
733
+ if (error instanceof Halted) return { halted: error.result };
734
+
735
+ throw error;
736
+ }
737
+ };
738
+
739
+ /** Files each part of a split item as its own item, then lands the item as done with no change of its own. */
740
+ const split = async (d: Driven, parts: readonly string[], onMerged: () => void): Promise<ThinResult> => {
741
+ const calls = onceCalls({ apiVersion: ADAPTER_API_VERSION, workSource: d.workSource, questions: d.questions }, d.state.ops, { run: SPLIT, attempt: 0 });
742
+
743
+ for (const title of parts) await calls.workSource?.fileFollowUp(d.id, { title, body: `Split from ${d.id}: ${d.item.title}` });
744
+
745
+ return merge(d, onMerged);
746
+ };
747
+
748
+ /** The owner-review wait asks for the change's approval, whatever the review run wrote. */
749
+ const approvalQuestion = ({ question, plan }: Pending): Pending => ({
750
+ question: { text: PLAIN_QUESTIONS["owner-review"], detail: question.detail ?? question.text },
751
+ plain: "owner-review",
752
+ plan,
753
+ });
754
+
755
+ /** Push the work branch, put the plan on the item, queue the question for room under the daily cap, and end. Each write runs once per key. */
756
+ const handOff = async (d: Driven, { question, plain, plan }: Pending) => {
757
+ const { state, id, g, branch, workSource, questions, git } = d;
758
+ const attempt = state.runs.list(id).length;
759
+ const key = (op: string) => ({ itemId: id, run: "ask", attempt, op });
760
+ const calls = onceCalls({ apiVersion: ADAPTER_API_VERSION, workSource, questions }, state.ops, { run: "ask", attempt });
761
+
762
+ await state.ops.once(key("push-branch"), {
763
+ holds: async () => (await g(["ls-remote", "--heads", "origin", branch])).startsWith((await g(["rev-parse", "HEAD"])).trim()),
764
+ run: async () => {
765
+ if ((await push(git, ["--force", "origin", `HEAD:refs/heads/${branch}`])) !== "pushed") throw new Error(`could not push ${branch}`);
766
+ },
767
+ });
768
+
769
+ if (plan.trim()) await calls.workSource?.comment(id, `${PLAN_MARK}\n${plan.trim()}`);
770
+
771
+ queueQuestion(d, d.item, question, plain);
772
+ await releaseQuestions(d);
773
+ };
774
+
775
+ /** Every act that changes the world checks the claim first. */
776
+ const stillMine = async (d: Pick<Driven, "workSource" | "id" | "holder" | "config">): Promise<boolean> => (await d.workSource.renew(d.id, d.holder, claimTtlMs(d.config))).won;
777
+
778
+ const landContext = (d: Driven): LandContext => ({
779
+ state: d.state,
780
+ config: d.config,
781
+ kind: d.kindName,
782
+ id: d.id,
783
+ item: d.item,
784
+ branch: d.branch,
785
+ base: d.base,
786
+ remote: d.remote,
787
+ clone: d.clone,
788
+ env: d.env,
789
+ dir: d.dir,
790
+ git: d.git,
791
+ checks: d.checks,
792
+ workSource: d.workSource,
793
+ questions: d.questions,
794
+ pulls: d.pulls,
795
+ now: d.now ?? Date.now,
796
+ judge: d.judge,
797
+ reviewRun: reviewAtLanding(d),
798
+ });
799
+
800
+ const DRAINING = "the worker restarts for an update; the next worker lands the change under its config";
801
+
802
+ /**
803
+ * At `merging`: the change is saved and its branch pushed, then landed by its level unless the worker drains. A
804
+ * docs-only item whose change reaches past its globs moves to its real kind first.
805
+ */
806
+ const merge = async (d: Driven, onMerged: () => void, ownerApproved = false): Promise<ThinResult> => {
807
+ if (!(await stillMine(d))) return { outcome: "lost", item: d.id };
808
+
809
+ if (d.kindName === d.config.hum.checkKind) {
810
+ const proof = await proveCheckItem({ state: d.state, config: d.config, git: d.git, item: d.id, base: d.base, checks: d.checks, now: d.now ?? Date.now });
811
+
812
+ if (proof && !proof.passed) return { outcome: "stuck", item: d.id, detail: proof.reason };
813
+ }
814
+
815
+ const isDocsOnly = d.kindName === d.config.hum.docsOnly.kind;
816
+
817
+ if (isDocsOnly && leavesDocs((await changeOn(landContext(d))).paths, d.config.hum)) {
818
+ const real = await decideKind(d, d.item, d.kindName);
819
+
820
+ return { outcome: "moved", item: d.id, kind: real.kind };
821
+ }
822
+
823
+ await prepareLanding(landContext(d), ownerApproved);
824
+
825
+ if (d.mayLand?.() === false) return { outcome: "held", item: d.id, why: DRAINING };
826
+
827
+ const result = await land(landContext(d));
828
+
829
+ if (result.outcome === "merged") onMerged();
830
+
831
+ return result;
832
+ };
833
+
834
+ /** A finished change whose landing did not end: its pushed branch lands again, and once merged its saved state goes. */
835
+ const landAgain = async (d: Driven): Promise<ThinResult> => {
836
+ if (d.mayLand?.() === false) return { outcome: "held", item: d.id, why: DRAINING };
837
+
838
+ const result = await land(landContext(d));
839
+
840
+ if (result.outcome === "merged") d.state.items.remove(d.id);
841
+
842
+ return result;
843
+ };
844
+
845
+ /** The answer option that runs a parked item again from the start. */
846
+ export const RUN_AGAIN = "retry";
847
+
848
+ type Parking = { readonly outcome: "stuck" | "review"; readonly item: string; readonly detail?: string };
849
+
850
+ const isParking = (result: ThinResult): result is ThinResult & Parking => result.outcome === "stuck" || result.outcome === "review";
851
+
852
+ const PARKING = {
853
+ stuck: {
854
+ code: "item-stuck",
855
+ fallback: "a run failed",
856
+ cause: (item: string, why: string) => `${item} ended stuck: ${why}`,
857
+ fix: "Fix the cause, then run it again.",
858
+ action: { label: "Run it again", answer: RUN_AGAIN },
859
+ },
860
+ review: {
861
+ code: "item-review",
862
+ fallback: "its change waits for a review",
863
+ cause: (item: string, why: string) => `${item} is ready to merge but needs your review: ${why}`,
864
+ fix: "Review the branch, then approve it on the item, or answer retry to run it again.",
865
+ action: { label: "Approve", answer: OWNER_APPROVAL },
866
+ },
867
+ } as const satisfies Record<Parking["outcome"], { code: string; fallback: string; cause: (item: string, why: string) => string; fix: string; action: { label: string; answer: string } }>;
868
+
869
+ /** An item that ended stuck, or whose change waits for a review, sits out until the owner acts. One card says why and how to run it again. */
870
+ export const park = (o: Pick<ThinPathOptions, "state" | "now">, result: ThinResult): ThinResult => {
871
+ if (!isParking(result)) return result;
872
+
873
+ const rule = PARKING[result.outcome];
874
+ const cause = result.detail ?? rule.fallback;
875
+
876
+ o.state.parked.put(result.item, { item: result.item, why: result.outcome, cause, since: (o.now ?? Date.now)() });
877
+ o.state.faults.raise({
878
+ code: rule.code,
879
+ item: result.item,
880
+ cause: rule.cause(result.item, cause.slice(0, CARD_EXCERPT)),
881
+ fix: rule.fix,
882
+ action: rule.action,
883
+ });
884
+
885
+ return result;
886
+ };