@moo.md/hum 0.0.0 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moo.md/hum",
3
- "version": "0.0.0",
3
+ "version": "0.1.0",
4
4
  "description": "The hum engine: work items become Claude Code agent runs, the repo's checks decide what they can, and only what nothing settles becomes a question to the owner.",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -480,7 +480,7 @@
480
480
  "type": "integer",
481
481
  "exclusiveMinimum": 0,
482
482
  "maximum": 9007199254740991,
483
- "description": "How long one git, gh, npm or Claude Code management command may run before it is stopped and its call fails naming it. A run's agent and a repo's checks have their own limits."
483
+ "description": "How long one git, gh, npm or Claude Code management command, one GitHub request or one start check may run before it is stopped and its call fails naming it. A run's agent and a repo's checks have their own limits."
484
484
  },
485
485
  "mergeTries": {
486
486
  "default": 3,
@@ -1251,7 +1251,7 @@
1251
1251
  "type": "integer",
1252
1252
  "exclusiveMinimum": 0,
1253
1253
  "maximum": 9007199254740991,
1254
- "description": "How long running a new check on one note's commit may take before the proof fails."
1254
+ "description": "How long the repo's checks may run, on a run's branch, on the base after a merge or as a new check on one note's commit, before they are stopped and fail."
1255
1255
  },
1256
1256
  "kindFloors": {
1257
1257
  "default": {},
@@ -11,6 +11,7 @@ import { CARD_EXCERPT, type Card } from "../status/format.ts";
11
11
  import { SECOND_MS } from "../time.ts";
12
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
13
  import { type LimitEnded, limitOf, savedLimitUntil, settleLimit } from "./limit.ts";
14
+ import { parseLooseJson } from "./marked.ts";
14
15
  import { billedTokens, cacheReadTokens, modelsOf, outputTokens, type RunTranscript, readTranscript } from "./transcript.ts";
15
16
 
16
17
  /** The plugin a background run turns off, so no run draws the band or polls. */
@@ -24,6 +25,8 @@ const SHORT_ID = /backgrounded\W+([0-9a-f]{8})\b/u;
24
25
 
25
26
  const AGENT_VIEW_KIND = "background";
26
27
 
28
+ const AGENTS_UNREAD = "agents-unread";
29
+
27
30
  const SINGLE_QUOTE = /'/g;
28
31
 
29
32
  const shellQuote = (text: string): string => `'${text.replace(SINGLE_QUOTE, `'\\''`)}'`;
@@ -176,11 +179,22 @@ export const backgroundRunner = ({ binary = "claude", env, state, config, fallba
176
179
  const claude = (args: readonly string[], options: { stdin?: string; cwd?: string } = {}) =>
177
180
  exec(binary, args, { stdin: options.stdin, nodePath: false, timeoutMs: commandTimeoutMs(config), nodeOptions: { cwd: options.cwd, env: { ...process.env, ...env } } });
178
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. */
179
183
  const agents = async (): Promise<Agent[]> => {
180
184
  const { stdout } = await claude(["agents", "--json"]);
181
- const parsed = z.array(Listed).safeParse(JSON.parse(stdout));
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)}`;
182
189
 
183
- return parsed.success ? parsed.data.flatMap(({ kind, id, name, sessionId, state }) => (kind === AGENT_VIEW_KIND && id !== undefined ? [{ id, name, sessionId, state }] : [])) : [];
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 }] : []));
184
198
  };
185
199
 
186
200
  const reportsOf = (sessionId: string): { at: number; event: string; transcriptPath: string | undefined }[] =>
@@ -190,7 +204,7 @@ export const backgroundRunner = ({ binary = "claude", env, state, config, fallba
190
204
  return reported?.success && reported.data.session_id === sessionId ? [{ at: statSync(file).mtimeMs, event: reported.data.hook_event_name, transcriptPath: reported.data.transcript_path }] : [];
191
205
  });
192
206
 
193
- const jobTokens = (id: string): number => orMissing(() => JobFile.safeParse(JSON.parse(readFileSync(join(jobsFolder, id, JOB_STATE_FILE), "utf8"))).data?.tokens ?? 0, 0);
207
+ const jobTokens = (id: string): number => orMissing(() => JobFile.parse(JSON.parse(readFileSync(join(jobsFolder, id, JOB_STATE_FILE), "utf8"))).tokens ?? 0, 0);
194
208
 
195
209
  const readRun = async (id: string, sessionId: string): Promise<Reading> => {
196
210
  // The job is read before the transcript: whatever put it in its state is already written.
@@ -336,9 +350,11 @@ const refusalCard = ({ faults }: Pick<BackgroundOptions, "state">["state"]): Car
336
350
  return card;
337
351
  };
338
352
 
339
- const whyNot = (outcome: RunOutcome): string => {
353
+ const whyNot = (outcome: RunOutcome, timeoutMs: number): string => {
340
354
  if (outcome.kind === "finished") return outcome.text.slice(0, CARD_EXCERPT);
341
355
 
356
+ if (outcome.kind === "stopped") return `no result within ${timeoutMs / SECOND_MS} seconds`;
357
+
342
358
  return outcome.kind === "held" ? outcome.card.cause : outcome.kind;
343
359
  };
344
360
 
@@ -357,7 +373,8 @@ export const startBackgroundRunner = async (options: BackgroundStartOptions): Pr
357
373
  // The check's own fall-back holds with the card that says why the service refused.
358
374
  const refuse: Runner = { run: async () => ({ kind: "held", card: refusalCard(state) }), limitedUntil: started.runner.limitedUntil };
359
375
  const checker = backgroundRunner({ binary, env, state, config, fallback: refuse });
360
- const check = await checker.run({ name: START_NAME, prompt: START_PROMPT, cwd: repo, model: options.model, effort: "low", schema: START_SCHEMA });
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) });
361
378
 
362
379
  if (isOk(check)) {
363
380
  state.faults.clear(BACKGROUND_CHECK_CODE);
@@ -366,7 +383,7 @@ export const startBackgroundRunner = async (options: BackgroundStartOptions): Pr
366
383
  }
367
384
 
368
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.
369
- const why = whyNot(check);
386
+ const why = whyNot(check, timeoutMs);
370
387
 
371
388
  state.faults.clear(FALLBACK_CODE);
372
389
  state.faults.raise(startCheckFault(repo, why));
@@ -320,7 +320,7 @@ export type RunnerOptions = {
320
320
  /** The model the start check runs on. */
321
321
  readonly model: string;
322
322
  readonly binary?: string;
323
- /** The limit of `claude --version`, which the version floor reads; the owner's `commandTimeoutSeconds` in milliseconds. */
323
+ /** The limit of `claude --version`, which the version floor reads, and of the start check; the owner's `commandTimeoutSeconds` in milliseconds. */
324
324
  readonly timeoutMs?: number;
325
325
  /** Added to the process environment. An API key in the environment is passed on untouched. */
326
326
  readonly env?: Readonly<Record<string, string>>;
@@ -377,6 +377,8 @@ const recordCredential = (state: RunnerOptions["state"], credential: string): vo
377
377
  });
378
378
  };
379
379
 
380
+ const START_TIMED_OUT = "start-check-timed-out";
381
+
380
382
  export const START_PROMPT = 'Reply with the JSON {"ok":true}.';
381
383
 
382
384
  export const START_SCHEMA = {
@@ -535,8 +537,11 @@ const startChecked = async (options: RunnerOptions): Promise<Started> => {
535
537
  model: options.model,
536
538
  effort: "low",
537
539
  schema: START_SCHEMA,
540
+ signal: AbortSignal.timeout(timeoutMs),
538
541
  });
539
542
 
543
+ if (check.kind === "stopped") return held(hold(START_TIMED_OUT, `The start check got no answer within ${timeoutMs / SECOND_MS} seconds and was stopped.`, "hum makes the check again on the next run; if this card stays, check that claude -p answers in a terminal."));
544
+
540
545
  if (check.kind === "held") return held(check);
541
546
 
542
547
  if (check.kind === "limited") return { check, runner: { run: async () => check, limitedUntil } };
@@ -558,12 +563,13 @@ const startChecked = async (options: RunnerOptions): Promise<Started> => {
558
563
  recordCredential(state, credentialOf(check.keySource, env));
559
564
 
560
565
  state.faults.clear(LIMIT_UNPARSED);
566
+ state.faults.clear(START_TIMED_OUT);
561
567
 
562
568
  return { check, runner: { run, limitedUntil } };
563
569
  };
564
570
 
565
- /** A start check that a usage limit refused says nothing about the install: it is made again once the limit has ended. */
566
- const isUnsettled = ({ check }: Started): boolean => check.kind === "limited" || (check.kind === "held" && check.card.code === LIMIT_UNPARSED);
571
+ /** A start check that a usage limit refused or that got no answer says nothing about the install: it is made again on the next run. */
572
+ const isUnsettled = ({ check }: Started): boolean => check.kind === "limited" || (check.kind === "held" && (check.card.code === LIMIT_UNPARSED || check.card.code === START_TIMED_OUT));
567
573
 
568
574
  /**
569
575
  * A runner. Its start check is made again on the next run for as long as a usage limit refuses it, and a saved
@@ -4,7 +4,8 @@ import { exec } from "../exec.ts";
4
4
  /** No hook runs: the hooks path points nowhere, whatever the clone's own config says. */
5
5
  const HOOKS_OFF = "core.hooksPath=/dev/null";
6
6
 
7
- const CONFLICT = /non-fast-forward|fetch first|already exists|stale info|failed to update ref|cannot lock ref/i;
7
+ /** The words git uses when another push moved the ref first; git 2.50 and later say `incorrect old value provided` when two pushes race at the update. */
8
+ const CONFLICT = /non-fast-forward|fetch first|already exists|stale info|failed to update ref|cannot lock ref|incorrect old value/i;
8
9
  const REFUSED = /remote rejected|declined|protected|GH006|denied|not permitted/i;
9
10
  const ABSENT = /does not exist|not a valid object name/i;
10
11
 
@@ -12,7 +12,7 @@ import type { MERGE_METHODS } from "../config/schema.ts";
12
12
  import { exec } from "../exec.ts";
13
13
  import { parseArgument } from "./argument.ts";
14
14
  import { claimCommit, claimCommitMessage, claimer, claimOfCommit, isLive } from "./claim.ts";
15
- import { answerMarker, commentText, filedFollowUp, followUpBody, followUpNote, type Marker, marked, parseComment, questionMarker, questionText } from "./marked.ts";
15
+ import { answerMarker, commentText, filedFollowUp, followUpBody, followUpNote, isFollowUpOf, type Marker, marked, parseComment, questionMarker, questionText } from "./marked.ts";
16
16
 
17
17
  const RATE_LIMIT_RETRIES = 1;
18
18
  const NOT_MODIFIED = 304;
@@ -69,6 +69,8 @@ const CreatedLabel = z.object({ createLabel: z.object({ label: z.object({ id: z.
69
69
 
70
70
  const CreatedIssue = z.object({ createIssue: z.object({ issue: z.object({ number: z.int().positive() }) }) });
71
71
 
72
+ const RecentIssuesReply = z.object({ repository: z.object({ issues: z.object({ nodes: z.array(z.object({ number: z.int().positive(), title: z.string(), body: z.string() })) }) }) });
73
+
72
74
  const PullsReply = z.object({
73
75
  repository: z.object({
74
76
  id: z.string(),
@@ -143,6 +145,11 @@ const CREATE_LABEL = `mutation CreateLabel($repository: ID!, $name: String!, $co
143
145
  createLabel(input: { repositoryId: $repository, name: $name, color: $color, description: $description }) { label { id } }
144
146
  }`;
145
147
 
148
+ /** The newest issues: a follow-up whose note was never written is among them, since the note is written right after it. */
149
+ const RECENT_ISSUES = `query RecentIssues($owner: String!, $name: String!) {
150
+ repository(owner: $owner, name: $name) { issues(first: 20, orderBy: { field: CREATED_AT, direction: DESC }) { nodes { number title body } } }
151
+ }`;
152
+
146
153
  const CREATE_ISSUE = `mutation CreateIssue($repository: ID!, $title: String!, $body: String!, $labels: [ID!]!) {
147
154
  createIssue(input: { repositoryId: $repository, title: $title, body: $body, labelIds: $labels }) { issue { number } }
148
155
  }`;
@@ -214,22 +221,31 @@ export const ownerToken = async (timeoutMs: number): Promise<string> => {
214
221
 
215
222
  const retryOnce: NonNullable<ThrottlingOptions["onRateLimit"]> = (_retryAfter, _options, _octokit, retryCount) => retryCount < RATE_LIMIT_RETRIES;
216
223
 
224
+ type Send = (url: string, init?: RequestInit) => Promise<Response>;
225
+
217
226
  export type GitHubClientOptions = {
218
227
  readonly token: string;
219
228
  readonly baseUrl?: string;
220
229
  /** Replaces `fetch`, for a GitHub that is not github.com. */
221
- readonly fetch?: typeof fetch;
230
+ readonly fetch?: Send;
222
231
  /** Whether writes are spaced as GitHub asks; only a GitHub with no secondary rate limit may go without. */
223
232
  readonly spaced?: boolean;
233
+ /** The owner's `commandTimeoutSeconds` in milliseconds: how long one request may wait for GitHub's answer. */
234
+ readonly timeoutMs: number;
224
235
  };
225
236
 
226
- /** A GitHub client that waits out rate limits and spaces its writes as GitHub asks. */
227
- export const gitHubClient = ({ token, baseUrl, fetch, spaced = true }: GitHubClientOptions): GitHubClient =>
237
+ const bounded =
238
+ (send: Send, timeoutMs: number): Send =>
239
+ (url, init) =>
240
+ send(url, { ...init, signal: AbortSignal.any([AbortSignal.timeout(timeoutMs), ...(init?.signal ? [init.signal] : [])]) });
241
+
242
+ /** A GitHub client that waits out rate limits, spaces its writes as GitHub asks, and gives up on a request GitHub has not answered within `timeoutMs`. */
243
+ export const gitHubClient = ({ token, baseUrl, fetch = globalThis.fetch, spaced = true, timeoutMs }: GitHubClientOptions): GitHubClient =>
228
244
  new HumOctokit({
229
245
  auth: token,
230
246
  userAgent: "hum",
231
247
  baseUrl,
232
- request: { fetch },
248
+ request: { fetch: bounded(fetch, timeoutMs) },
233
249
  throttle: { enabled: spaced, onRateLimit: retryOnce, onSecondaryRateLimit: retryOnce },
234
250
  });
235
251
 
@@ -276,7 +292,7 @@ export const githubAdapter = (options: GitHubOptions, { now }: AdapterContext):
276
292
  let spent = 0;
277
293
 
278
294
  const client = pMemoize(async () => {
279
- const made = options.client ?? gitHubClient({ token: await ownerToken(timeoutMs) });
295
+ const made = options.client ?? gitHubClient({ token: await ownerToken(timeoutMs), timeoutMs });
280
296
 
281
297
  made.hook.after("request", () => void spent++);
282
298
  made.hook.error("request", (error) => {
@@ -408,13 +424,19 @@ export const githubAdapter = (options: GitHubOptions, { now }: AdapterContext):
408
424
 
409
425
  if (filed !== undefined) return { id: filed, title };
410
426
 
411
- const { repository, label } = await labelled();
412
- const made = await mutate(CreatedIssue, CREATE_ISSUE, { repository, title, body: followUpBody(body, `#${from}`), labels: [label] });
413
- const note = followUpNote(title, String(made.createIssue.issue.number));
427
+ const created = async () => {
428
+ const { repository, label } = await labelled();
429
+
430
+ return (await mutate(CreatedIssue, CREATE_ISSUE, { repository, title, body: followUpBody(body, `#${from}`), labels: [label] })).createIssue.issue.number;
431
+ };
432
+
433
+ const recent = (await query(RecentIssuesReply, RECENT_ISSUES, {})).repository.issues.nodes;
434
+ const id = String(recent.find(isFollowUpOf(`#${from}`, title))?.number ?? (await created()));
435
+ const note = followUpNote(title, id);
414
436
 
415
437
  await commentMarked(from, note.marker, note.text);
416
438
 
417
- return { id: String(made.createIssue.issue.number), title };
439
+ return { id, title };
418
440
  },
419
441
  },
420
442
  questions: {
@@ -69,8 +69,16 @@ export const commentText = (text: string): string => text.trim() || EMPTY_COMMEN
69
69
  /** The same follow-up title from the same item always has the same key, so filing it twice files it once. */
70
70
  export const followUpKey = (title: string): string => createHash("sha256").update(title).digest("hex").slice(0, FOLLOW_UP_KEY_LENGTH);
71
71
 
72
+ const filedFrom = (from: string): string => `Filed from ${from}.`;
73
+
72
74
  /** A follow-up's body, which names the item it came from. */
73
- export const followUpBody = (body: string, from: string): string => `${body.trim()}\n\nFiled from ${from}.`;
75
+ export const followUpBody = (body: string, from: string): string => `${body.trim()}\n\n${filedFrom(from)}`;
76
+
77
+ /** Whether an item is the follow-up with this title filed from `from`, read from the item itself: it finds a follow-up whose note on `from` was never written. */
78
+ export const isFollowUpOf =
79
+ (from: string, title: string) =>
80
+ (found: { readonly title: string; readonly body: string }): boolean =>
81
+ found.title === title && found.body.trimEnd().endsWith(filedFrom(from));
74
82
 
75
83
  /** The note left on the item a follow-up came from; its marker carries the key that finds the follow-up again. */
76
84
  export const followUpNote = (title: string, item: string) => ({
@@ -147,7 +147,7 @@ export const gitHubPullRequests = (
147
147
  const [owner = "", name = ""] = repo.split("/");
148
148
 
149
149
  const connect = pMemoize(
150
- async () => client ?? gitHubClient({ token: await ownerToken(timeoutMs) }),
150
+ async () => client ?? gitHubClient({ token: await ownerToken(timeoutMs), timeoutMs }),
151
151
  );
152
152
 
153
153
  const rulesCache = new Map<string, BranchRules>();
@@ -12,6 +12,7 @@ import {
12
12
  filedFollowUp,
13
13
  followUpBody,
14
14
  followUpNote,
15
+ isFollowUpOf,
15
16
  type Marker,
16
17
  cutLine,
17
18
  markedLine,
@@ -266,12 +267,13 @@ export const roundupAdapter = (options: RoundupOptions, { now }: AdapterContext)
266
267
 
267
268
  if (filed !== undefined) return { id: filed, title };
268
269
 
269
- const made = Todo.parse(await call("todo_create", { title, body: followUpBody(body, `#${from}`) }));
270
- const note = followUpNote(title, String(made.id));
270
+ const created = async () => Todo.parse(await call("todo_create", { title, body: followUpBody(body, `#${from}`) })).id;
271
+ const id = String((await todos()).find(isFollowUpOf(`#${from}`, title))?.id ?? (await created()));
272
+ const note = followUpNote(title, id);
271
273
 
272
274
  await postMarked(from, note.marker, note.text);
273
275
 
274
- return { id: String(made.id), title };
276
+ return { id, title };
275
277
  },
276
278
  },
277
279
  questions: {
@@ -157,7 +157,7 @@ const Shipped = z.object({
157
157
  mergedShown: count.describe("Merged changes the status file lists."),
158
158
  choicesShown: count.describe("Choices made without the owner that the status file lists, newest first."),
159
159
  statusReadTimeoutSeconds: seconds.describe("How long a read for the status file, such as the newest published version, may take before it is left out."),
160
- commandTimeoutSeconds: seconds.describe("How long one git, gh, npm or Claude Code management command may run before it is stopped and its call fails naming it. A run's agent and a repo's checks have their own limits."),
160
+ commandTimeoutSeconds: seconds.describe("How long one git, gh, npm or Claude Code management command, one GitHub request or one start check may run before it is stopped and its call fails naming it. A run's agent and a repo's checks have their own limits."),
161
161
  mergeTries: count.describe("Tries to merge a change when the base branch moves under it."),
162
162
  writeRaceRetries: z.int().nonnegative().describe("Retries of a markdown write that another writer's push beat."),
163
163
  itemReadsAtOnce: count.describe("Item files the markdown source reads at once; each read is a git process."),
@@ -229,7 +229,7 @@ const Shipped = z.object({
229
229
  memoryUnusedRuns: count.describe("Runs without use after which a memory.md entry is listed for the owner."),
230
230
  measureWindow: count.describe("Merged changes the per-merge numbers average over, and the window per path."),
231
231
  loopIntervalSeconds: seconds.describe("The time between passes that collect review notes, file check items and confirm CI ran their checks."),
232
- proofTimeoutSeconds: seconds.describe("How long running a new check on one note's commit may take before the proof fails."),
232
+ proofTimeoutSeconds: seconds.describe("How long the repo's checks may run, on a run's branch, on the base after a merge or as a new check on one note's commit, before they are stopped and fail."),
233
233
  kindFloors: z.record(name, name).describe("A kind's lowest risk level: its changes take at least this level, as in { \"check\": \"high\" }."),
234
234
  checkKind: name.describe("The kind of the work item filed for a rule that review notes repeat: it turns the notes into one check."),
235
235
  breakCheck: z.boolean().describe("Whether the repo's checks run on the base after each merge, so a test that breaks there files a follow-up item."),
package/src/exec.ts CHANGED
@@ -31,11 +31,16 @@ export type ExecOptions = Partial<Omit<Options, "timeout" | "signal" | "persist"
31
31
  readonly graceMs?: number;
32
32
  };
33
33
 
34
+ /**
35
+ * Signals every process in the group, and answers false once none is left to signal. macOS answers EPERM, not ESRCH,
36
+ * while the group holds only processes that have exited and wait to be reaped, as the command itself does until Bun
37
+ * reaps it.
38
+ */
34
39
  const signalGroup = (group: number, signal: "SIGTERM" | "SIGKILL" | 0): boolean => {
35
40
  try {
36
41
  return process.kill(-group, signal);
37
42
  } catch (error) {
38
- if (error instanceof Error && "code" in error && error.code === "ESRCH") return false;
43
+ if (error instanceof Error && "code" in error && (error.code === "ESRCH" || error.code === "EPERM")) return false;
39
44
 
40
45
  throw error;
41
46
  }
@@ -1,7 +1,7 @@
1
1
  import type { Git } from "../adapters/git.ts";
2
2
  import type { Config } from "../config/load.ts";
3
3
  import type { State } from "../state/open.ts";
4
- import { SECOND_MS } from "../time.ts";
4
+ import { checksTimeoutMs } from "../worker/checks.ts";
5
5
  import { proveCheck } from "./proof.ts";
6
6
 
7
7
  export type ProveItem = {
@@ -25,7 +25,7 @@ export const proveCheckItem = async ({ state, config, git, item, base, checks, n
25
25
 
26
26
  const notes = group.notes.flatMap((key) => state.notes.get(key) ?? []);
27
27
  const head = (await git.raw(["rev-parse", "HEAD"])).trim();
28
- const proof = await proveCheck({ git, head, base: `origin/${base}`, notes, checks, timeoutMs: config.hum.proofTimeoutSeconds * SECOND_MS, now });
28
+ const proof = await proveCheck({ git, head, base: `origin/${base}`, notes, checks, timeoutMs: checksTimeoutMs(config.hum), now });
29
29
 
30
30
  state.proofs.put(item, { item, at: now(), passed: proof.passed, reason: proof.reason, worktrees: proof.worktrees, ms: proof.ms });
31
31
 
@@ -10,7 +10,7 @@ import { commandTimeoutMs, exec, SHIPPED_COMMAND_TIMEOUT_MS } from "../exec.ts";
10
10
  import { SlotPool } from "../slots/pool.ts";
11
11
  import { orMissing } from "../state/fs.ts";
12
12
  import { openState } from "../state/open.ts";
13
- import { runChecks } from "../worker/checks.ts";
13
+ import { checksTimeoutMs, runChecks } from "../worker/checks.ts";
14
14
  import { openWorker } from "../worker/open.ts";
15
15
  import { Scratch } from "./scratch.ts";
16
16
 
@@ -82,7 +82,7 @@ const checksStep = async (repo: string, config: Config): Promise<Outcome> => {
82
82
  if (config.hum.checks.length === 0) return failed('hum.json names no checks: set "checks"');
83
83
 
84
84
  for (const check of config.hum.checks) {
85
- const failure = await runChecks([check], repo);
85
+ const failure = await runChecks([check], repo, { timeoutMs: checksTimeoutMs(config.hum) });
86
86
 
87
87
  if (failure) return failed(failure);
88
88
  }
@@ -154,7 +154,13 @@ export class Items {
154
154
  return this.#fault(itemId, "snapshot-from-newer-engine", `The saved state of ${itemId} was written by hum ${header.data.engineVersion}, which is newer than the running ${this.#engineVersion}.`, "Update the engine to that version or later: bun add --exact @moo.md/hum@latest.");
155
155
  }
156
156
 
157
- const envelope = Envelope.safeParse(climb(EnvelopeJson.parse(parsed), header.data.format, this.#format, this.#migrations, "format"));
157
+ let envelope: ReturnType<typeof Envelope.safeParse>;
158
+
159
+ try {
160
+ envelope = Envelope.safeParse(climb(EnvelopeJson.parse(parsed), header.data.format, this.#format, this.#migrations, "format"));
161
+ } catch (error) {
162
+ return unreadable(reason(error));
163
+ }
158
164
 
159
165
  if (!envelope.success) return unreadable(envelope.error.message);
160
166
 
@@ -162,13 +168,13 @@ export class Items {
162
168
  let current = snapshot;
163
169
 
164
170
  if (machineVersion !== kind.machine.version) {
165
- const previous = kindAt?.(machineVersion);
171
+ try {
172
+ const previous = kindAt?.(machineVersion);
166
173
 
167
- if (!previous) {
168
- return this.#fault(itemId, "snapshot-machine-unknown", `${itemId} was saved under version ${machineVersion} of its machine, and this config holds no map from it.`, "Add a stateMap for that version to the kind file, or delete the item's saved state.");
169
- }
174
+ if (!previous) {
175
+ return this.#fault(itemId, "snapshot-machine-unknown", `${itemId} was saved under version ${machineVersion} of its machine, and this config holds no map from it.`, "Add a stateMap for that version to the kind file, or delete the item's saved state.");
176
+ }
170
177
 
171
- try {
172
178
  current = await migrateSnapshot(previous, kind, snapshot, sources);
173
179
  } catch (error) {
174
180
  return this.#fault(itemId, "snapshot-restore-error", `${itemId} could not move from machine version ${machineVersion} to ${kind.machine.version}: ${reason(error)}.`, "Map the state in the kind's stateMap, or delete the item's saved state.");
@@ -3,8 +3,7 @@ import { type Git } from "../adapters/git.ts";
3
3
  import type { Config } from "../config/load.ts";
4
4
  import { inWorktreeAt } from "../loop/proof.ts";
5
5
  import type { State } from "../state/open.ts";
6
- import { SECOND_MS } from "../time.ts";
7
- import { runChecks } from "./checks.ts";
6
+ import { checksTimeoutMs, runChecks } from "./checks.ts";
8
7
  import { placementOf } from "./land.ts";
9
8
 
10
9
  export type BaseCheckOptions = {
@@ -34,7 +33,7 @@ export const checkBaseAfterMerge = async ({ state, config, workSource, git, remo
34
33
 
35
34
  await git.raw(["fetch", "-q", remote, base]);
36
35
 
37
- const failure = await inWorktreeAt(git, merge.sha, (folder) => runChecks(checks, folder, { timeoutMs: config.hum.proofTimeoutSeconds * SECOND_MS }));
36
+ const failure = await inWorktreeAt(git, merge.sha, (folder) => runChecks(checks, folder, { timeoutMs: checksTimeoutMs(config.hum) }));
38
37
 
39
38
  if (failure === undefined) return;
40
39
 
@@ -1,25 +1,39 @@
1
- import { x } from "tinyexec";
1
+ import type { HumConfig } from "../config/schema.ts";
2
+ import { CommandTimedOut, exec } from "../exec.ts";
3
+ import { SECOND_MS } from "../time.ts";
2
4
 
3
5
  export type ShellOptions = {
4
6
  /** Added to the worker's own environment. */
5
7
  readonly env?: Readonly<Record<string, string>>;
6
- /** A command still running after this many ms is killed and counts as failed. */
7
- readonly timeoutMs?: number;
8
+ /** A command still running after this many ms is stopped, with every process it started, and counts as failed. */
9
+ readonly timeoutMs: number;
8
10
  };
9
11
 
10
- /** A check runs with no stdin and the worker's own PATH, as in the owner's shell; the clone's `node_modules/.bin` is not added. */
11
- const shellOut = async (command: string, cwd: string, { env, timeoutMs }: ShellOptions): Promise<{ code: number | undefined; output: string }> => {
12
- const { exitCode, stdout, stderr } = await x("sh", ["-c", command], { nodePath: false, timeout: timeoutMs, nodeOptions: { cwd, env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "pipe"] } });
12
+ /**
13
+ * One check's failure as its command, exit code and output, or as the limit it ran past; undefined when it passes.
14
+ * It runs with no stdin and the worker's own PATH, as in the owner's shell; the clone's `node_modules/.bin` is not added.
15
+ */
16
+ const failureOf = async (command: string, cwd: string, { env, timeoutMs }: ShellOptions): Promise<string | undefined> => {
17
+ try {
18
+ const { exitCode, stdout, stderr } = await exec("sh", ["-c", command], { nodePath: false, timeoutMs, nodeOptions: { cwd, env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "pipe"] } });
13
19
 
14
- return { code: exitCode, output: `${stdout}${stderr}` };
20
+ return exitCode === 0 ? undefined : `${command} exited ${exitCode}:\n${stdout}${stderr}`;
21
+ } catch (error) {
22
+ if (error instanceof CommandTimedOut) return error.message;
23
+
24
+ throw error;
25
+ }
15
26
  };
16
27
 
17
- /** The first failing check as its command, exit code and output; undefined when all pass. */
18
- export const runChecks = async (commands: readonly string[], cwd: string, options: ShellOptions = {}): Promise<string | undefined> => {
28
+ /** How long the repo's checks may run: the owner's `proofTimeoutSeconds` in milliseconds. */
29
+ export const checksTimeoutMs = ({ proofTimeoutSeconds }: Pick<HumConfig, "proofTimeoutSeconds">): number => proofTimeoutSeconds * SECOND_MS;
30
+
31
+ /** The first failing check; undefined when all pass. */
32
+ export const runChecks = async (commands: readonly string[], cwd: string, options: ShellOptions): Promise<string | undefined> => {
19
33
  for (const command of commands) {
20
- const ran = await shellOut(command, cwd, options);
34
+ const failure = await failureOf(command, cwd, options);
21
35
 
22
- if (ran.code !== 0) return `${command} exited ${ran.code}:\n${ran.output}`;
36
+ if (failure !== undefined) return failure;
23
37
  }
24
38
 
25
39
  return undefined;
@@ -50,7 +50,7 @@ import {
50
50
  import type { State } from "../state/open.ts";
51
51
  import type { Landing as SavedLanding, Verdict } from "../state/saved.ts";
52
52
  import { PLAIN_QUESTIONS } from "../decide/question.ts";
53
- import { runChecks } from "./checks.ts";
53
+ import { checksTimeoutMs, runChecks } from "./checks.ts";
54
54
  import { recordMerged } from "./merged.ts";
55
55
  import { blockedPaths, brokenCommits } from "../loop/breaks.ts";
56
56
  import { queueQuestion, releaseQuestions } from "./questions.ts";
@@ -281,6 +281,7 @@ const pushOntoNewestBase = async ({
281
281
  clone,
282
282
  env,
283
283
  checks,
284
+ config,
284
285
  }: LandContext): Promise<void> => {
285
286
  await git.raw(["fetch", "-q", "origin", base]);
286
287
 
@@ -295,7 +296,7 @@ const pushOntoNewestBase = async ({
295
296
  );
296
297
  }
297
298
 
298
- const failure = await runChecks(checks, clone, { env });
299
+ const failure = await runChecks(checks, clone, { env, timeoutMs: checksTimeoutMs(config.hum) });
299
300
 
300
301
  if (failure)
301
302
  throw new StaleMerge(
@@ -87,14 +87,14 @@ export const openWorker = async (repo: string, options: OpenWorkerOptions): Prom
87
87
 
88
88
  if (!workSource || !questions) throw new Error("hum.json names no work source or no questions integration");
89
89
 
90
- const runnerOptions = { state, model: config.hum.models.light, binary, env, now };
90
+ const runnerOptions = { state, model: config.hum.models.light, binary, env, now, timeoutMs };
91
91
  const { runner } = isInBackground(config.hum, rest.where) ? await startBackgroundRunner({ ...runnerOptions, config: config.hum, repo }) : await startRunner(runnerOptions);
92
92
 
93
93
  // A slot is a worktree a background run starts in, so the pool stands only where runs are background agents.
94
94
  const slots = config.hum.runSlots.enabled && isInBackground(config.hum, rest.where) ? new SlotPool({ repo, state, config: config.hum, base: rest.base ?? DEFAULT_BASE, liveRuns: runner.liveRuns, now }) : undefined;
95
95
  const github = repoFromRemote(remote);
96
96
  const pulls = github === undefined ? undefined : gitHubPullRequests(github, { timeoutMs });
97
- const loop = github === undefined ? undefined : githubLoopReads(github, rest.base ?? DEFAULT_BASE, config.hum.measureWindow, async () => gitHubClient({ token: await ownerToken(timeoutMs) }));
97
+ const loop = github === undefined ? undefined : githubLoopReads(github, rest.base ?? DEFAULT_BASE, config.hum.measureWindow, async () => gitHubClient({ token: await ownerToken(timeoutMs), timeoutMs }));
98
98
 
99
99
  return new Worker({ ...rest, checks: config.hum.checks, checkout: rest.checkout ?? slots?.checkout, slots, repo, state, config, adapters: { workSource, questions, answers }, runner, remote, pulls, loop });
100
100
  };
@@ -21,7 +21,7 @@ import { type EventPick, type JsonSchema, jsonSchemaOf, type ProsePurpose, planH
21
21
  import { persistedSnapshot } from "../state/items.ts";
22
22
  import type { State } from "../state/open.ts";
23
23
  import { HOUR_MS, SECOND_MS } from "../time.ts";
24
- import { runChecks } from "./checks.ts";
24
+ import { checksTimeoutMs, runChecks } from "./checks.ts";
25
25
  import { changeOn, type LandContext, land, placementOf, prepareLanding, type ReviewOutcome } from "./land.ts";
26
26
  import { OWNER_APPROVAL } from "../decide/merge.ts";
27
27
  import { askDecision, askedQuestion, isWaitQuestion, PLAIN_QUESTIONS, type PlainQuestion, RunReason } from "../decide/question.ts";
@@ -508,7 +508,7 @@ const drive = async (d: Driven): Promise<ThinResult> => {
508
508
 
509
509
  const checksSource = createAsyncLogic({
510
510
  run: async () => {
511
- const failure = await runChecks(d.checks, clone, { env: d.env });
511
+ const failure = await runChecks(d.checks, clone, { env: d.env, timeoutMs: checksTimeoutMs(d.config.hum) });
512
512
 
513
513
  if (failure) {
514
514
  lastFailure = failure;
@@ -103,6 +103,7 @@ type InFlight = {
103
103
  };
104
104
 
105
105
  const ERROR_EXCERPT = 300;
106
+ const UNREAD_CODE = "item-unread";
106
107
 
107
108
  /** Reads `read` at most once per `everyMs`; a failed read, or one slower than `timeoutMs`, shows no value, and that too is kept for the period. */
108
109
  const readEvery = <T>(read: (() => Promise<T | undefined>) | undefined, { everyMs, timeoutMs }: { everyMs: number; timeoutMs: number }): (() => Promise<T | undefined>) =>
@@ -148,6 +149,8 @@ export class Worker {
148
149
  readonly #answered = new Set<string>();
149
150
  /** Saved changes that land again under this worker's config before anything else starts. */
150
151
  readonly #relanding = new Set<string>();
152
+ /** Items whose thread a tick failed to read; the next tick reads them again whatever the watch says. */
153
+ readonly #unread = new Set<string>();
151
154
  readonly #merged: Status["merged"] = [];
152
155
  readonly #wakes = new EventTarget();
153
156
  readonly #latest: () => Promise<string | undefined>;
@@ -352,12 +355,15 @@ export class Worker {
352
355
  }
353
356
  }
354
357
 
355
- /** Reads the threads that can have changed, settles each new answer, and releases a parked item the owner answered. */
358
+ /**
359
+ * Reads the threads that can have changed, settles each new answer, and releases a parked item the owner answered.
360
+ * Each item is read on its own: one that fails raises a card naming it and is read again next tick, and the rest go on.
361
+ */
356
362
  async #readAnswers(sleeping: readonly SavedSnapshot[], changed: boolean): Promise<void> {
357
363
  const { state, adapters, config } = this.#o;
358
364
  const inbox = this.#inbox();
359
365
 
360
- if (!changed && inbox.length === 0) return;
366
+ if (!changed && inbox.length === 0 && this.#unread.size === 0) return;
361
367
 
362
368
  const waiting = new Set(sleeping.map((s) => s.itemId));
363
369
  const asleep = new Map(sleeping.map((s) => [s.itemId, s]));
@@ -365,35 +371,51 @@ export class Worker {
365
371
  const asked = recentlyAsked({ state, config, now: this.#now });
366
372
 
367
373
  await Promise.all(
368
- [...new Set([...waiting, ...parked.map((p) => p.item), ...inbox, ...asked])].map(async (id) => {
369
- const raw = await adapters.workSource.read(id);
370
- const item = await settleAnswers({ state, workSource: adapters.workSource, judge: this.#judge, now: this.#now }, raw, this.#stageOf(id, raw.ready, asleep));
371
- const held = parked.find((p) => p.item === id);
372
- const lastAnswer = item.thread.findLast((e) => e.kind === "answer");
373
- const lastAnswerAt = lastAnswer?.at;
374
-
375
- if (held) {
376
- if (isAnsweredSince(lastAnswerAt, held.since)) this.#unpark(id, lastAnswer?.option);
377
-
378
- return;
379
- }
380
-
381
- const hasNewAnswer = waiting.has(id) && answerTo(item) !== undefined && lastAnswerAt !== undefined;
382
-
383
- if (hasNewAnswer) {
384
- state.events.add({
385
- source: "thread",
386
- sourceId: `answer:${lastAnswerAt}`,
387
- itemId: id,
388
- type: "answered",
389
- payload: {},
390
- });
391
- this.#answered.add(id);
392
- }
393
- }),
374
+ [...new Set([...waiting, ...parked.map((p) => p.item), ...inbox, ...asked, ...this.#unread])].map((id) =>
375
+ this.#readThread(id, async () => {
376
+ const raw = await adapters.workSource.read(id);
377
+ const item = await settleAnswers({ state, workSource: adapters.workSource, judge: this.#judge, now: this.#now }, raw, this.#stageOf(id, raw.ready, asleep));
378
+ const held = parked.find((p) => p.item === id);
379
+ const lastAnswer = item.thread.findLast((e) => e.kind === "answer");
380
+ const lastAnswerAt = lastAnswer?.at;
381
+
382
+ if (held) {
383
+ if (isAnsweredSince(lastAnswerAt, held.since)) this.#unpark(id, lastAnswer?.option);
384
+
385
+ return;
386
+ }
387
+
388
+ const hasNewAnswer = waiting.has(id) && answerTo(item) !== undefined && lastAnswerAt !== undefined;
389
+
390
+ if (hasNewAnswer) {
391
+ state.events.add({
392
+ source: "thread",
393
+ sourceId: `answer:${lastAnswerAt}`,
394
+ itemId: id,
395
+ type: "answered",
396
+ payload: {},
397
+ });
398
+ this.#answered.add(id);
399
+ }
400
+ }),
401
+ ),
394
402
  );
395
403
  }
396
404
 
405
+ /** Runs one item's read; a failure raises the card that names the item, and the item is read again next tick. */
406
+ async #readThread(id: string, read: () => Promise<void>): Promise<void> {
407
+ const { faults } = this.#o.state;
408
+
409
+ try {
410
+ await read();
411
+ this.#unread.delete(id);
412
+ faults.clear(`${UNREAD_CODE}:${id}`);
413
+ } catch (error) {
414
+ this.#unread.add(id);
415
+ faults.raise({ code: UNREAD_CODE, item: id, cause: `The thread of ${id} could not be read: ${error instanceof Error ? error.message : String(error)}`.slice(0, ERROR_EXCERPT), fix: "hum reads it again each tick and goes on with the other items." });
416
+ }
417
+ }
418
+
397
419
  /** Every claim in flight is renewed; a run whose claim is gone stops. */
398
420
  async #renew(): Promise<void> {
399
421
  const { adapters, holder, config } = this.#o;
package/surface.json CHANGED
@@ -3913,7 +3913,7 @@
3913
3913
  "type": "(options: GitHubOptions, { now }: AdapterContext) => Whole"
3914
3914
  },
3915
3915
  "gitHubClient": {
3916
- "type": "({ token, baseUrl, fetch, spaced }: GitHubClientOptions) => Octokit & paginateGraphQLInterface"
3916
+ "type": "({ token, baseUrl, fetch, spaced, timeoutMs }: GitHubClientOptions) => Octokit & paginateGraphQLInterface"
3917
3917
  },
3918
3918
  "GitHubClient": {
3919
3919
  "type": "export type GitHubClient = InstanceType<typeof HumOctokit>;"