@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,392 @@
1
+ import { mkdirSync, readFileSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { stripVTControlCharacters } from "node:util";
5
+ import { z } from "zod";
6
+ import type { HumConfig } from "../config/schema.ts";
7
+ import { commandTimeoutMs, exec } from "../exec.ts";
8
+ import { listRecords, orMissing } from "../state/fs.ts";
9
+ import type { State } from "../state/open.ts";
10
+ import { CARD_EXCERPT, type Card } from "../status/format.ts";
11
+ import { SECOND_MS } from "../time.ts";
12
+ import { type Finished, type RunOutcome, type RunRequest, type Runner, type RunnerOptions, START_ANSWER, START_PROMPT, START_SCHEMA, startRunner, succeeded } from "./claude-p.ts";
13
+ import { type LimitEnded, limitOf, savedLimitUntil, settleLimit } from "./limit.ts";
14
+ import { parseLooseJson } from "./marked.ts";
15
+ import { billedTokens, cacheReadTokens, modelsOf, outputTokens, type RunTranscript, readTranscript } from "./transcript.ts";
16
+
17
+ /** The plugin a background run turns off, so no run draws the band or polls. */
18
+ export const HUM_PLUGIN = "hum@moo.md";
19
+
20
+ /** The hook events that tell the engine where a run's transcript is: at its first prompt and at each stop. */
21
+ const HOOK_EVENTS = ["UserPromptSubmit", "Stop"] as const;
22
+
23
+ /** `claude --bg` prints the id in colour, so the line is read after its terminal codes are dropped. */
24
+ const SHORT_ID = /backgrounded\W+([0-9a-f]{8})\b/u;
25
+
26
+ const AGENT_VIEW_KIND = "background";
27
+
28
+ const AGENTS_UNREAD = "agents-unread";
29
+
30
+ const SINGLE_QUOTE = /'/g;
31
+
32
+ const shellQuote = (text: string): string => `'${text.replace(SINGLE_QUOTE, `'\\''`)}'`;
33
+
34
+ /** A hook command that saves the hook's input, which names the session and its transcript, as a file of its own. */
35
+ const dropInto = (folder: string): string => `cat > ${shellQuote(folder)}/$$.json`;
36
+
37
+ /** The settings every background run starts with: hum's plugin off, the deny rules and auto mode's rules, and a hook that reports the run. */
38
+ export const backgroundSettings = ({ deniedRunCommands, runAutoMode }: Pick<HumConfig, "deniedRunCommands" | "runAutoMode">, stopsFolder: string, env: Readonly<Record<string, string>> = {}) => ({
39
+ enabledPlugins: { [HUM_PLUGIN]: false },
40
+ // A project's own settings may name an editor that waits for a window; a run has none, so its git would wait for good.
41
+ env: { GIT_EDITOR: "true", ...env },
42
+ permissions: { deny: deniedRunCommands.map((command) => `Bash(${command} *)`) },
43
+ autoMode: { classifyAllShell: true, environment: runAutoMode.environment, allow: runAutoMode.allow, hard_deny: runAutoMode.hardDeny },
44
+ hooks: Object.fromEntries(HOOK_EVENTS.map((event) => [event, [{ hooks: [{ type: "command", command: dropInto(stopsFolder) }] }]])),
45
+ });
46
+
47
+ export type LaunchSpec = {
48
+ readonly name: string;
49
+ readonly model: string;
50
+ readonly effort: string;
51
+ readonly schema: object;
52
+ readonly settings: object;
53
+ };
54
+
55
+ /** The flags of `claude --bg`. The prompt goes on stdin: a flag that takes a list swallows a prompt placed after it. */
56
+ export const launchArgs = ({ name, model, effort, schema, settings }: LaunchSpec): string[] => [
57
+ "--bg",
58
+ "-n",
59
+ name,
60
+ "--model",
61
+ model,
62
+ "--effort",
63
+ effort,
64
+ "--permission-mode",
65
+ "auto",
66
+ "--json-schema",
67
+ JSON.stringify(schema),
68
+ "--settings",
69
+ JSON.stringify(settings),
70
+ ];
71
+
72
+ const Listed = z.looseObject({ id: z.string().optional(), kind: z.string(), name: z.string().nullish(), sessionId: z.string(), state: z.string().nullish() });
73
+
74
+ type Agent = { readonly id: string; readonly name: string | null | undefined; readonly sessionId: string; readonly state: string | null | undefined };
75
+
76
+ /** The folder of Claude Code's config that holds one folder per background job, each with the job's `state.json`. */
77
+ const JOBS_FOLDER = "jobs";
78
+
79
+ const JOB_STATE_FILE = "state.json";
80
+
81
+ const JobFile = z.looseObject({ tokens: z.number().optional() });
82
+
83
+ const Reported = z.looseObject({ hook_event_name: z.string(), session_id: z.string(), transcript_path: z.string().optional() });
84
+
85
+ const STOP_EVENT = "Stop";
86
+
87
+ /** What the engine reads of a run at one moment. */
88
+ export type Reading = {
89
+ readonly transcript: RunTranscript;
90
+ /** Epoch ms of each hook file the run dropped. */
91
+ readonly stops: readonly number[];
92
+ /** The job's state in `claude agents --json`, or undefined once the run has left the list. */
93
+ readonly job: string | undefined;
94
+ /** The output tokens the job counts, which its transcript can lack: a subagent's, and the call that writes agent view's summary lines. */
95
+ readonly jobOutputTokens: number;
96
+ };
97
+
98
+ export type Progress =
99
+ | { readonly kind: "waiting" }
100
+ | { readonly kind: "over-cap"; readonly tokens: number }
101
+ | { readonly kind: "limit"; readonly ended: LimitEnded }
102
+ | { readonly kind: "done"; readonly structured: unknown }
103
+ | { readonly kind: "failed"; readonly why: string };
104
+
105
+ const FAILED_STATE = "failed";
106
+
107
+ const ENDED_STATES = ["done", "stopped"];
108
+
109
+ /**
110
+ * Where a run stands. Done is a `structured_output` attachment and then a `Stop`: under a schema the hook fires
111
+ * twice, and only the second follows the attachment. Failed is the job's state or an API error row.
112
+ */
113
+ export const progressOf = ({ transcript, stops, job, jobOutputTokens }: Reading, tokenCap: number | undefined): Progress => {
114
+ const tokens = tokensOf(transcript, jobOutputTokens);
115
+
116
+ if (tokenCap !== undefined && tokens > tokenCap) return { kind: "over-cap", tokens };
117
+
118
+ const { structured } = transcript;
119
+
120
+ if (structured !== undefined && stops.some((at) => at >= structured.at)) return { kind: "done", structured: structured.data };
121
+
122
+ if (transcript.limit !== undefined) return { kind: "limit", ended: limitOf(transcript.limit.text, transcript.limit.resetsAt) };
123
+
124
+ if (transcript.apiError !== undefined) return { kind: "failed", why: transcript.apiError };
125
+
126
+ if (job === FAILED_STATE) return { kind: "failed", why: "the job's state is failed" };
127
+
128
+ if (job !== undefined && ENDED_STATES.includes(job) && structured === undefined) return { kind: "failed", why: `the run ended as ${job} with no structured result` };
129
+
130
+ // A run the owner stopped in agent view, or one that died, leaves the list with no result.
131
+ if (job === undefined) return { kind: "failed", why: "the run left claude agents with no structured result" };
132
+
133
+ return { kind: "waiting" };
134
+ };
135
+
136
+ /** What the run billed: its transcript's tokens, and the output tokens the job counts beyond them. */
137
+ const tokensOf = (transcript: RunTranscript, jobOutputTokens: number): number => billedTokens(transcript) + Math.max(0, jobOutputTokens - outputTokens(transcript));
138
+
139
+ const finishedOf = (sessionId: string, { transcript, jobOutputTokens }: Pick<Reading, "transcript" | "jobOutputTokens">, { subtype, isError, text, structured }: Pick<Finished, "subtype" | "isError" | "text" | "structured">): Finished => ({
140
+ kind: "finished",
141
+ subtype,
142
+ isError,
143
+ sessionId,
144
+ text,
145
+ structured,
146
+ tokens: tokensOf(transcript, jobOutputTokens),
147
+ cacheReadTokens: cacheReadTokens(transcript),
148
+ plugins: [],
149
+ keySource: undefined,
150
+ models: modelsOf(transcript),
151
+ });
152
+
153
+ const succeededWith = (structured: Finished["structured"]): Pick<Finished, "subtype" | "isError" | "text" | "structured"> => ({ subtype: "success", isError: false, text: "", structured });
154
+
155
+ const failedWith = (why: string): Pick<Finished, "subtype" | "isError" | "text" | "structured"> => ({ subtype: "error_during_execution", isError: true, text: why, structured: undefined });
156
+
157
+ /** What `claude --bg` said: the id of the run it started, or why it did not start one. */
158
+ type Launched = { readonly kind: "started"; readonly id: string } | { readonly kind: "refused"; readonly why: string };
159
+
160
+ export const FALLBACK_CODE = "background-run-fell-back";
161
+
162
+ export type BackgroundOptions = Pick<RunnerOptions, "binary" | "env" | "now"> & {
163
+ readonly state: Pick<State, "stops" | "faults" | "limit">;
164
+ readonly config: Pick<HumConfig, "deniedRunCommands" | "runAutoMode" | "backgroundPollSeconds" | "backgroundLaunchSeconds" | "commandTimeoutSeconds">;
165
+ /** The runner for everything that is not a named agent run, and for the runs a missing background service cannot take. */
166
+ readonly fallback: Runner;
167
+ };
168
+
169
+ /**
170
+ * Runs a named agent run as a Claude Code background agent, so the owner sees it in agent view. The run's name is
171
+ * saved before it launches: a run found under that name is adopted, never started twice. The engine reads the
172
+ * transcript, enforces the token cap by `claude stop`, and stops and removes the run once its outcome is taken.
173
+ * A cheap model call, a run with no name, and a run the background service cannot take go to `fallback`.
174
+ */
175
+ export const backgroundRunner = ({ binary = "claude", env, state, config, fallback, now = Date.now }: BackgroundOptions): Runner => {
176
+ const pollMs = config.backgroundPollSeconds * SECOND_MS;
177
+ const jobsFolder = join({ ...process.env, ...env }.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude"), JOBS_FOLDER);
178
+
179
+ const claude = (args: readonly string[], options: { stdin?: string; cwd?: string } = {}) =>
180
+ exec(binary, args, { stdin: options.stdin, nodePath: false, timeoutMs: commandTimeoutMs(config), nodeOptions: { cwd: options.cwd, env: { ...process.env, ...env } } });
181
+
182
+ /** The background runs Claude Code lists. A list hum cannot read throws, with one card: read as empty, it would start a run that is already going. */
183
+ const agents = async (): Promise<Agent[]> => {
184
+ const { stdout } = await claude(["agents", "--json"]);
185
+ const found = parseLooseJson(z.array(Listed), stdout);
186
+
187
+ if (found === undefined) {
188
+ const cause = `claude agents --json replied in a shape hum does not read: ${stdout.slice(0, CARD_EXCERPT)}`;
189
+
190
+ state.faults.raise({ code: AGENTS_UNREAD, cause, fix: "No background run starts until hum reads the list again; update hum to a version that reads this Claude Code's list." });
191
+
192
+ throw new Error(cause);
193
+ }
194
+
195
+ state.faults.clear(AGENTS_UNREAD);
196
+
197
+ return found.flatMap(({ kind, id, name, sessionId, state }) => (kind === AGENT_VIEW_KIND && id !== undefined ? [{ id, name, sessionId, state }] : []));
198
+ };
199
+
200
+ const reportsOf = (sessionId: string): { at: number; event: string; transcriptPath: string | undefined }[] =>
201
+ listRecords(state.stops).flatMap((file) => {
202
+ const reported = orMissing(() => Reported.safeParse(JSON.parse(readFileSync(file, "utf8"))), undefined);
203
+
204
+ return reported?.success && reported.data.session_id === sessionId ? [{ at: statSync(file).mtimeMs, event: reported.data.hook_event_name, transcriptPath: reported.data.transcript_path }] : [];
205
+ });
206
+
207
+ const jobTokens = (id: string): number => orMissing(() => JobFile.parse(JSON.parse(readFileSync(join(jobsFolder, id, JOB_STATE_FILE), "utf8"))).tokens ?? 0, 0);
208
+
209
+ const readRun = async (id: string, sessionId: string): Promise<Reading> => {
210
+ // The job is read before the transcript: whatever put it in its state is already written.
211
+ const job = (await agents()).find((agent) => agent.id === id)?.state ?? undefined;
212
+ const jobOutputTokens = jobTokens(id);
213
+ const reports = reportsOf(sessionId);
214
+ const path = reports.find(({ transcriptPath }) => transcriptPath !== undefined)?.transcriptPath;
215
+ const text = path === undefined ? "" : orMissing(() => readFileSync(path, "utf8"), "");
216
+
217
+ return { transcript: readTranscript(text), stops: reports.filter(({ event }) => event === STOP_EVENT).map(({ at }) => at), job, jobOutputTokens };
218
+ };
219
+
220
+ const end = async (id: string): Promise<void> => {
221
+ await claude(["stop", id]);
222
+ await claude(["rm", id]);
223
+ };
224
+
225
+ const launch = async (request: RunRequest & { name: string }): Promise<Launched> => {
226
+ // The run's hook writes into this folder and does not make it.
227
+ mkdirSync(state.stops, { recursive: true });
228
+
229
+ const settings = backgroundSettings(config, state.stops, request.env);
230
+ const { stdout, stderr } = await claude(launchArgs({ ...request, settings }), { stdin: request.prompt, cwd: request.cwd });
231
+ const said = stripVTControlCharacters(`${stdout}\n${stderr}`).trim();
232
+ const id = SHORT_ID.exec(said)?.[1];
233
+
234
+ return id === undefined ? { kind: "refused", why: said.slice(0, CARD_EXCERPT) } : { kind: "started", id };
235
+ };
236
+
237
+ /** The run goes on as `claude -p`, which agent view does not list; the owner is told once, with the reason. */
238
+ const fellBack = (request: RunRequest, why: string): Promise<RunOutcome> => {
239
+ state.faults.raise({
240
+ code: FALLBACK_CODE,
241
+ cause: `claude --bg did not take "${request.name}" in ${request.cwd}: ${why}`,
242
+ fix: "The run goes on as claude -p and is missing from agent view. A background run starts only in a folder of a repo whose trust the owner accepted.",
243
+ });
244
+
245
+ return fallback.run(request);
246
+ };
247
+
248
+ const listed = async (id: string, signal: AbortSignal | undefined): Promise<Agent | undefined> => {
249
+ const until = Date.now() + config.backgroundLaunchSeconds * SECOND_MS;
250
+
251
+ while (Date.now() < until && !signal?.aborted) {
252
+ const found = (await agents()).find((agent) => agent.id === id);
253
+
254
+ if (found) return found;
255
+
256
+ await Bun.sleep(pollMs);
257
+ }
258
+
259
+ return undefined;
260
+ };
261
+
262
+ const watch = async (request: RunRequest, id: string, sessionId: string): Promise<RunOutcome> => {
263
+ let announced = false;
264
+
265
+ for (;;) {
266
+ if (request.signal?.aborted) return { kind: "stopped" };
267
+
268
+ const reading = await readRun(id, sessionId);
269
+
270
+ if (!announced && Object.keys(reading.transcript.messages).length > 0) {
271
+ announced = true;
272
+ request.onFirstToken?.();
273
+ }
274
+
275
+ const progress = progressOf(reading, request.tokenCap);
276
+
277
+ if (progress.kind === "over-cap") return progress;
278
+
279
+ if (progress.kind === "limit") return settleLimit(state, progress.ended);
280
+
281
+ if (progress.kind === "done") return finishedOf(sessionId, reading, succeededWith(progress.structured));
282
+
283
+ if (progress.kind === "failed") return finishedOf(sessionId, reading, failedWith(progress.why));
284
+
285
+ await Bun.sleep(pollMs);
286
+ }
287
+ };
288
+
289
+ const run = async (request: RunRequest): Promise<RunOutcome> => {
290
+ const { name } = request;
291
+
292
+ if (request.call === "judgment" || name === undefined) return fallback.run(request);
293
+
294
+ // A limit that stands holds a named run as it holds any other: no background run starts before it ends.
295
+ if (now() < savedLimitUntil(state)) return { kind: "limited", until: savedLimitUntil(state) };
296
+
297
+ const adopted = (await agents()).find((agent) => agent.name === name);
298
+ const launched = adopted ? ({ kind: "started", id: adopted.id } as const) : await launch({ ...request, name });
299
+
300
+ if (launched.kind === "refused") return fellBack(request, launched.why);
301
+
302
+ const { id } = launched;
303
+ const session = adopted ?? (await listed(id, request.signal));
304
+
305
+ if (session === undefined) return request.signal?.aborted ? { kind: "stopped" } : fellBack(request, "the run never appeared in claude agents");
306
+
307
+ state.faults.clear(FALLBACK_CODE);
308
+
309
+ request.onSession?.(session.sessionId);
310
+
311
+ try {
312
+ return await watch(request, id, session.sessionId);
313
+ } finally {
314
+ await end(id);
315
+ }
316
+ };
317
+
318
+ /** The names of the background runs `claude agents` lists. */
319
+ const liveRuns = async (): Promise<ReadonlySet<string>> => new Set((await agents()).flatMap(({ name }) => (name ? [name] : [])));
320
+
321
+ return { run, limitedUntil: fallback.limitedUntil, liveRuns };
322
+ };
323
+
324
+ const START_NAME = "hum start check";
325
+
326
+ export const BACKGROUND_CHECK_CODE = "background-start-check-failed";
327
+
328
+ export type StartedBackground = { readonly check: RunOutcome; readonly runner: Runner };
329
+
330
+ export type BackgroundStartOptions = Omit<RunnerOptions, "state"> &
331
+ Pick<BackgroundOptions, "config" | "state"> & {
332
+ readonly state: RunnerOptions["state"];
333
+ /** The owner's repo: a background run starts only in a trusted folder, and a git repo of its own is not one. */
334
+ readonly repo: string;
335
+ };
336
+
337
+ const isOk = (outcome: RunOutcome): boolean => outcome.kind === "finished" && succeeded(outcome) && START_ANSWER.safeParse(outcome.structured).success;
338
+
339
+ const startCheckFault = (repo: string, why: string) => ({
340
+ code: BACKGROUND_CHECK_CODE,
341
+ cause: `A background run in ${repo} left no structured result: ${why}.`,
342
+ fix: `Runs go on as claude -p and are missing from agent view. Run claude in ${repo} once and accept its trust prompt, then restart the worker.`,
343
+ });
344
+
345
+ const refusalCard = ({ faults }: Pick<BackgroundOptions, "state">["state"]): Card => {
346
+ const card = faults.list().find(({ code }) => code === FALLBACK_CODE);
347
+
348
+ if (!card) throw new Error("the fall-back ran without raising its card");
349
+
350
+ return card;
351
+ };
352
+
353
+ const whyNot = (outcome: RunOutcome, timeoutMs: number): string => {
354
+ if (outcome.kind === "finished") return outcome.text.slice(0, CARD_EXCERPT);
355
+
356
+ if (outcome.kind === "stopped") return `no result within ${timeoutMs / SECOND_MS} seconds`;
357
+
358
+ return outcome.kind === "held" ? outcome.card.cause : outcome.kind;
359
+ };
360
+
361
+ /**
362
+ * The runner for the Mac: the `claude -p` runner, with named agent runs taken by the background service. Its start
363
+ * check also starts one background run with the exact flags, which must leave a `structured_output` attachment.
364
+ * The check may not fall back to `claude -p`: when it fails, one card says why and every run goes on as `claude -p`,
365
+ * missing from agent view.
366
+ */
367
+ export const startBackgroundRunner = async (options: BackgroundStartOptions): Promise<StartedBackground> => {
368
+ const { config, repo, state, binary, env } = options;
369
+ const started = await startRunner(options);
370
+
371
+ if (started.check.kind !== "finished") return started;
372
+
373
+ // The check's own fall-back holds with the card that says why the service refused.
374
+ const refuse: Runner = { run: async () => ({ kind: "held", card: refusalCard(state) }), limitedUntil: started.runner.limitedUntil };
375
+ const checker = backgroundRunner({ binary, env, state, config, fallback: refuse });
376
+ const timeoutMs = commandTimeoutMs(config);
377
+ const check = await checker.run({ name: START_NAME, prompt: START_PROMPT, cwd: repo, model: options.model, effort: "low", schema: START_SCHEMA, signal: AbortSignal.timeout(timeoutMs) });
378
+
379
+ if (isOk(check)) {
380
+ state.faults.clear(BACKGROUND_CHECK_CODE);
381
+
382
+ return { check, runner: backgroundRunner({ binary, env, state, config, fallback: started.runner }) };
383
+ }
384
+
385
+ // The start check's card says why for every run, so the card for the check's own fall-back would only repeat it.
386
+ const why = whyNot(check, timeoutMs);
387
+
388
+ state.faults.clear(FALLBACK_CODE);
389
+ state.faults.raise(startCheckFault(repo, why));
390
+
391
+ return { check, runner: started.runner };
392
+ };