faberun 0.8.0 → 0.10.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.
@@ -3,11 +3,13 @@
3
3
  * rule 12).
4
4
  *
5
5
  * `contract.finalVerification` is the contract-wide proof that the phase as a
6
- * whole closes: the controller runs it before the judge on the phase-terminal
7
- * node (the node no other node depends on), so no final checkpoint is ever
8
- * approved on partial verification. `contract.sharedVerification` carries the
9
- * same command schema but is appended to every node's attempt and integration
10
- * candidate, for the fast repository ratchets a node's write set can break.
6
+ * whole closes: the controller runs it before the judge, once, on whichever
7
+ * phase-terminal node (a node no other node depends on) is the last of them
8
+ * to settle, so no final checkpoint is ever approved on partial verification
9
+ * and a flake on one phase-terminal node cannot also cost its siblings a
10
+ * revision. `contract.sharedVerification` carries the same command schema but
11
+ * is appended to every node's attempt and integration candidate, for the fast
12
+ * repository ratchets a node's write set can break.
11
13
  * The persisted node-snapshot shape for verification evidence lives here too,
12
14
  * next to the schema it records.
13
15
  */
@@ -58,20 +60,49 @@ export function sharedVerificationCommands(contract) {
58
60
  return contract.sharedVerification ?? [];
59
61
  }
60
62
 
63
+ /**
64
+ * Whether no other node in the contract depends on this one. `finalVerification`
65
+ * is a candidate to run on a phase-terminal node only; a node with a dependant
66
+ * never carries it, no matter which of its siblings settles last.
67
+ *
68
+ * @param {{nodes: {id: string, dependsOn: string[]}[]}} contract
69
+ * @param {{id: string}} node
70
+ * @returns {boolean}
71
+ */
72
+ export function phaseTerminalNode(contract, node) {
73
+ return !contract.nodes.some((candidate) => candidate.dependsOn.includes(node.id));
74
+ }
75
+
61
76
  /**
62
77
  * The contract's `finalVerification` commands when this node is the one that
63
- * closes the phase, otherwise none. A node is phase-terminal when no other
64
- * node in the contract depends on it.
78
+ * closes the phase, otherwise none. A phase can have several phase-terminal
79
+ * nodes (several nodes no other node depends on); the suite runs once for the
80
+ * phase, on whichever of them is the last to settle, not on every one of them.
81
+ *
82
+ * `settledIds` is the set of sibling node ids (any status a node does not
83
+ * leave on its own -- see `SETTLED` in `engine/prompts.mjs`) already reached
84
+ * at the moment this call is made. A phase-terminal node carries the suite
85
+ * exactly when every *other* phase-terminal node is already in that set --
86
+ * whichever node that is true for, in whatever order nodes actually settle,
87
+ * including a node retried after every sibling has already closed. Omitting
88
+ * `settledIds` (the scheduler's budget estimate, which has no run to inspect)
89
+ * falls back to the old per-node-shape answer: any phase-terminal node may
90
+ * still turn out to be the one that carries it, so the estimate stays an
91
+ * upper bound.
65
92
  *
66
93
  * @param {{finalVerification?: VerificationCommand[], nodes: {id: string, dependsOn: string[]}[]}} contract
67
94
  * @param {{id: string}} node
95
+ * @param {Set<string>} [settledIds]
68
96
  * @returns {VerificationCommand[]}
69
97
  */
70
- export function finalVerificationCommands(contract, node) {
98
+ export function finalVerificationCommands(contract, node, settledIds) {
71
99
  const commands = contract.finalVerification ?? [];
72
100
  if (commands.length === 0) return [];
73
- const hasDependant = contract.nodes.some((candidate) => candidate.dependsOn.includes(node.id));
74
- return hasDependant ? [] : commands;
101
+ if (!phaseTerminalNode(contract, node)) return [];
102
+ if (!settledIds) return commands;
103
+ const siblings = contract.nodes.filter((candidate) => candidate.id !== node.id && phaseTerminalNode(contract, candidate));
104
+ const isLastToClose = siblings.every((sibling) => settledIds.has(sibling.id));
105
+ return isLastToClose ? commands : [];
75
106
  }
76
107
 
77
108
  /**
@@ -432,7 +432,7 @@ function renderDiscoveryPrompt(packet, nodeId) {
432
432
  ...bulletOrNone(packet.nonGoals),
433
433
  "",
434
434
  "## Required output",
435
- 'Return exactly one worker-result JSON object, with no markdown or prose. Set status to "done", missingContext to [], and artifacts to an array containing exactly one JSON-stringified execution task packet with every required taskPacket field. The packet readFiles and writeFiles must be non-empty and scoped to this repository.',
435
+ 'Return exactly one worker-result JSON object, with no markdown or prose. Set status to "done", missingContext to [], and artifacts to an array containing exactly one JSON-stringified execution task packet with every required taskPacket field. The packet readFiles and writeFiles must be non-empty and scoped to this repository. Put structured findings meant to inform that packet in `output` (a JSON object, at most 65536 bytes); prose belongs in `summary`.',
436
436
  "",
437
437
  "## Verification",
438
438
  VERIFICATION_PARAGRAPH,
@@ -1,6 +1,6 @@
1
1
  import { Buffer } from "node:buffer";
2
2
  import { validateTaskPacket } from "./task-packet.mjs";
3
- import { requireText } from "./assert.mjs";
3
+ import { assertObject, requireText } from "./assert.mjs";
4
4
 
5
5
  const RESULT_LIMITS = Object.freeze({
6
6
  bytes: 32 * 1024,
@@ -9,6 +9,10 @@ const RESULT_LIMITS = Object.freeze({
9
9
  itemBytes: 2 * 1024,
10
10
  artifactBytes: 16 * 1024,
11
11
  missingContextItems: 16,
12
+ // A discovery worker's structured findings are the deliverable, not
13
+ // incidental prose, so `output` gets its own ceiling outside the 32 KiB
14
+ // envelope instead of competing with summary/verification for it.
15
+ outputBytes: 64 * 1024,
12
16
  });
13
17
 
14
18
  /**
@@ -26,9 +30,11 @@ export const DERIVED_WORKER_RESULT_FIELDS = Object.freeze(["changedFiles"]);
26
30
  /**
27
31
  * The worker-result protocol: exactly one JSON object returned as the only
28
32
  * content of the final worker message. `blocked_context` requires at least one
29
- * missingContext entry; `done` requires none.
33
+ * missingContext entry; `done` requires none. `output` is optional and carries
34
+ * a discovery node's structured findings; an execution result must not
35
+ * declare it (enforced where the node's mode is known, not here).
30
36
  *
31
- * @typedef {{status: WorkerResultStatus, summary: string, verification: string[], artifacts: string[], missingContext: string[]}} WorkerResult
37
+ * @typedef {{status: WorkerResultStatus, summary: string, verification: string[], artifacts: string[], missingContext: string[], output?: Record<string, unknown>}} WorkerResult
32
38
  */
33
39
 
34
40
  /**
@@ -37,8 +43,9 @@ export const DERIVED_WORKER_RESULT_FIELDS = Object.freeze(["changedFiles"]);
37
43
  */
38
44
  export function parseWorkerResult(value) {
39
45
  if (typeof value !== "string") throw new TypeError("worker result must be JSON text");
40
- if (Buffer.byteLength(value, "utf8") > RESULT_LIMITS.bytes) {
41
- throw new TypeError(`worker result exceeds ${RESULT_LIMITS.bytes} bytes`);
46
+ const maxRawBytes = RESULT_LIMITS.bytes + RESULT_LIMITS.outputBytes;
47
+ if (Buffer.byteLength(value, "utf8") > maxRawBytes) {
48
+ throw new TypeError(`worker result exceeds ${maxRawBytes} bytes`);
42
49
  }
43
50
  let parsed;
44
51
  try {
@@ -86,17 +93,42 @@ export function validateWorkerResult(value) {
86
93
  if (record.status === "done" && missingContext.length > 0) {
87
94
  throw new TypeError("worker result.missingContext must be empty for done");
88
95
  }
89
- const normalized = {
96
+ // `output` is accepted on any result here: the schema does not know which
97
+ // node mode produced it. Refusing it for execution results happens exactly
98
+ // once, at the ingestion point that does know the mode (resolveWorkerResult).
99
+ let output;
100
+ if (Object.hasOwn(record, "output") && record.output !== undefined) {
101
+ assertObject(record.output, "worker result.output");
102
+ if (Buffer.byteLength(JSON.stringify(record.output), "utf8") > RESULT_LIMITS.outputBytes) {
103
+ throw new TypeError(`worker result.output exceeds ${RESULT_LIMITS.outputBytes} bytes`);
104
+ }
105
+ output = /** @type {Record<string, unknown>} */ (record.output);
106
+ }
107
+ const envelope = {
90
108
  status: /** @type {WorkerResultStatus} */ (record.status),
91
109
  summary: /** @type {string} */ (record.summary),
92
110
  verification: [.../** @type {string[]} */ (record.verification)],
93
111
  artifacts: [.../** @type {string[]} */ (record.artifacts)],
94
112
  missingContext: [...missingContext],
95
113
  };
96
- if (Buffer.byteLength(JSON.stringify(normalized), "utf8") > RESULT_LIMITS.bytes) {
114
+ // `output` is bounded on its own above and kept outside this envelope cap:
115
+ // it is a discovery node's deliverable, not incidental prose competing with
116
+ // summary/verification for the same 32 KiB budget.
117
+ if (Buffer.byteLength(JSON.stringify(envelope), "utf8") > RESULT_LIMITS.bytes) {
97
118
  throw new TypeError(`worker result exceeds ${RESULT_LIMITS.bytes} bytes`);
98
119
  }
99
- return normalized;
120
+ return output === undefined ? envelope : { ...envelope, output };
121
+ }
122
+
123
+ /**
124
+ * A discovery node's structured findings, or null when the result carries
125
+ * none. The one accessor for `output` so callers never read the raw field.
126
+ *
127
+ * @param {WorkerResult} result
128
+ * @returns {Record<string, unknown>|null}
129
+ */
130
+ export function discoveryOutput(result) {
131
+ return result.output ?? null;
100
132
  }
101
133
 
102
134
  /**
@@ -54,6 +54,7 @@ import { appendUsageRecord, invocationCost, invocationUsage, recordInvocationUsa
54
54
  import { attemptWorkspace } from "../repo/worktree.mjs";
55
55
  import { executeControllerVerification } from "./verify.mjs";
56
56
  import {
57
+ ExecutionOutputNotAllowedError,
57
58
  materializeAttemptResult,
58
59
  readWorkerResultFile,
59
60
  resolveWorkerResult,
@@ -528,6 +529,16 @@ export async function finalizeClosedJobs(contract, runDir, states, running, lock
528
529
  try {
529
530
  workerResult = resolveWorkerResult(runDir, job.node, envelope.result);
530
531
  } catch (error) {
532
+ // A definitive protocol violation, not a malformed result: an
533
+ // execution node has no legitimate way to earn the repair path here.
534
+ if (error instanceof ExecutionOutputNotAllowedError) {
535
+ clearTierExhaustion(state);
536
+ transition(runDir, state, "failed", {
537
+ phase: "worker",
538
+ error: { code: "execution_output_not_allowed", message: errorMessage(error) },
539
+ }, lock);
540
+ continue;
541
+ }
531
542
  if (job.resultMaterialization) {
532
543
  clearTierExhaustion(state);
533
544
  transition(runDir, state, "failed", {
@@ -19,10 +19,18 @@ import { extractJson } from "../harnesses/protocol.mjs";
19
19
  import { invocationResult } from "./process.mjs";
20
20
  import { join } from "node:path";
21
21
  import { parseJudge } from "./prompts.mjs";
22
- import { parseWorkerResult } from "../contract/worker-result.mjs";
22
+ import { discoveryOutput, parseWorkerResult } from "../contract/worker-result.mjs";
23
23
  import { readJson, writeJsonAtomic, writeTextAtomic } from "../run/store.mjs";
24
24
  import { routeRuntimeForState, runtimeSnapshot } from "./failover.mjs";
25
25
 
26
+ /**
27
+ * Thrown by `resolveWorkerResult` when an execution result declares `output`.
28
+ * A distinct type, not a plain TypeError: this is a definitive protocol
29
+ * violation the engine can fail terminally on sight, not a malformed result
30
+ * worth the generic invalid-result repair attempt.
31
+ */
32
+ export class ExecutionOutputNotAllowedError extends TypeError {}
33
+
26
34
  /** @typedef {import("./lifecycle.mjs").Invocation} Invocation */
27
35
  /** @typedef {import("../contract/index.mjs").NodeSnapshot} NodeSnapshot */
28
36
  /** @typedef {import("../contract/index.mjs").ValidatedContract} ValidatedContract */
@@ -115,6 +123,10 @@ export function isResultMaterializationInvocation(invocation) {
115
123
  }
116
124
  }
117
125
  /**
126
+ * The single ingestion point that knows the node's mode, so it is the one
127
+ * place `output` is refused for an execution result: the schema itself
128
+ * accepts the field on any result, mode-blind.
129
+ *
118
130
  * @param {string} runDir
119
131
  * @param {ValidatedNode} node
120
132
  * @param {unknown} providerResult
@@ -122,9 +134,11 @@ export function isResultMaterializationInvocation(invocation) {
122
134
  */
123
135
  export function resolveWorkerResult(runDir, node, providerResult) {
124
136
  const fromFile = readWorkerResultFile(runDir, node.id);
125
- if (fromFile) return fromFile;
126
- const result = parseWorkerResult(String(extractJson(providerResult) ?? providerResult ?? ""));
127
- persistWorkerResultFile(runDir, node.id, result);
137
+ const result = fromFile ?? parseWorkerResult(String(extractJson(providerResult) ?? providerResult ?? ""));
138
+ if (node.taskPacket.mode === "execution" && discoveryOutput(result) !== null) {
139
+ throw new ExecutionOutputNotAllowedError("worker result.output is only allowed for a discovery node, not execution");
140
+ }
141
+ if (!fromFile) persistWorkerResultFile(runDir, node.id, result);
128
142
  return result;
129
143
  }
130
144
  /**
@@ -31,15 +31,15 @@ import {
31
31
  terminalErrorCode,
32
32
  } from "./lifecycle.mjs";
33
33
  import { delay, errorCode } from "../util.mjs";
34
- import { alreadyNotified, notifyQueueFor, notifyQueuesByRun, renderCampaignHandoffSafely } from "./notify-queue.mjs";
35
- import { detectStalls, terminateProcess } from "./process.mjs";
34
+ import { alreadyNotified, emitNodeAdvisories, notifyQueueFor, notifyQueuesByRun, renderCampaignHandoffSafely } from "./notify-queue.mjs";
35
+ import { detectStalls, invocationAlive, terminateProcess } from "./process.mjs";
36
36
  import { transition, writeNode } from "./state.mjs";
37
37
  import { listNodeSnapshots, readNodeSnapshot } from "../run/node-store.mjs";
38
38
  import { render, renderFinalReport, writeFindingsArtifact } from "../report/final.mjs";
39
39
  import { operationNextState, providerReceipts, settleInvocation } from "../run/operations.mjs";
40
40
  import { appendUsageRecord, invocationCost, invocationUsage, recordInvocationUsage } from "../run/usage.mjs";
41
41
  import { captureNodeScopeBoundaries, checkWorkerScope, emptyScope } from "./scope.mjs";
42
- import { validateContract } from "../contract/index.mjs";
42
+ import { validateContractForLaunch } from "../campaign/chain.mjs";
43
43
  import { validateNodeSnapshot } from "../contract/snapshot.mjs";
44
44
  import { finalVerificationCommands, sharedVerificationCommands } from "../contract/final-verification.mjs";
45
45
  import { startJudge, startWorker } from "./dispatch.mjs";
@@ -131,16 +131,22 @@ export function nodeBudgetBasisMs(contract, node) {
131
131
  * never touches phase 2's parked `blocked`/`failed`/`exhausted`/`stalled`
132
132
  * states, and never overwrites the `runtime_tier_exhausted` waiting shape.
133
133
  *
134
+ * A node whose closed job is being settled in the background (its id is a key
135
+ * of `pendingSettlements`) is not this dead end either: its invocation has
136
+ * already exited and left `running`, but the settlement promise still owns
137
+ * deciding what happens to it, so it is left alone until that promise resolves.
138
+ *
134
139
  * @param {string} runDir
135
140
  * @param {Map<string, NodeSnapshot>} states
136
141
  * @param {Map<string, Job>} running
137
142
  * @param {LockHandle|null} lock
143
+ * @param {Map<string, Promise<void>>} [pendingSettlements]
138
144
  * @returns {string[]} the node ids this pass parked
139
145
  */
140
- export function enforceRunningInvariant(runDir, states, running, lock) {
146
+ export function enforceRunningInvariant(runDir, states, running, lock, pendingSettlements = new Map()) {
141
147
  const parked = [];
142
148
  for (const [nodeId, state] of states) {
143
- if (state.status !== "running" || running.has(nodeId)) continue;
149
+ if (state.status !== "running" || running.has(nodeId) || pendingSettlements.has(nodeId)) continue;
144
150
  transition(runDir, state, "blocked", {
145
151
  phase: state.phase,
146
152
  error: {
@@ -175,14 +181,17 @@ function renderFingerprint(states) {
175
181
 
176
182
  /**
177
183
  * @param {string} contractPath
178
- * @param {{detachedBootstrap?: boolean}} [options] `detachedBootstrap` is set
179
- * only by the CLI entry when this process is its own detached child, and
180
- * makes the controller wait for the launcher's acknowledgement
184
+ * @param {{detachedBootstrap?: boolean, baseRef?: string}} [options]
185
+ * `detachedBootstrap` is set only by the CLI entry when this process is its
186
+ * own detached child, and makes the controller wait for the launcher's
187
+ * acknowledgement; `baseRef` is the CLI's own `--base-ref`, re-validated
188
+ * here so a launch and the run it starts agree about what the contract was
189
+ * checked against
181
190
  * @returns {Promise<RunOutcome>}
182
191
  */
183
192
  export async function runContract(contractPath, options = {}) {
184
193
  const absoluteContractPath = resolve(contractPath);
185
- const contract = validateContract(JSON.parse(readFileSync(absoluteContractPath, "utf8")), absoluteContractPath);
194
+ const contract = validateContractForLaunch(JSON.parse(readFileSync(absoluteContractPath, "utf8")), absoluteContractPath, { baseRef: options.baseRef });
186
195
  const runDir = join(contract.cwd, ".runs", contract.id);
187
196
  if (existsSync(runDir)) throw new Error(`run already exists: ${runDir}`);
188
197
  mkdirSync(join(contract.cwd, ".runs"), { recursive: true });
@@ -319,12 +328,13 @@ export async function driveRun(contract, runDir, states, campaign, lock, sourceI
319
328
  statusFingerprint = fingerprint;
320
329
  render(runDir, runsDir, contract, states, renderLock);
321
330
  };
322
- // The tick that owns a running node's verification can be minutes long
323
- // (`executeControllerVerification` is awaited on the critical path below),
324
- // and that whole time status.json would otherwise report whatever the last
325
- // tick left it at. A timer renders between ticks too; it is cheap even when
326
- // idle because `renderFingerprint` still change-detects, so a quiet run
327
- // writes nothing extra.
331
+ // A node's own settlement (its controller verification, its judge round) can
332
+ // be minutes long, and it now runs off the tick's critical path in
333
+ // `pendingSettlements` so dispatch never waits behind it -- but that whole
334
+ // time status.json would otherwise report whatever the last tick left it at.
335
+ // A timer renders between ticks too; it is cheap even when idle because
336
+ // `renderFingerprint` still change-detects, so a quiet run writes nothing
337
+ // extra.
328
338
  const statusTimer = setInterval(() => renderStatusIfChanged(), contract.pollIntervalMs);
329
339
  statusTimer.unref();
330
340
  let handoffFingerprint = statesFingerprint(states);
@@ -364,14 +374,31 @@ export async function driveRun(contract, runDir, states, campaign, lock, sourceI
364
374
 
365
375
  /** @type {Map<string, Job>} */
366
376
  const running = new Map();
377
+ // One promise per node currently settling a closed job -- its controller
378
+ // verification, its candidate verification, its judge round -- kept off the
379
+ // tick's critical path so an eligible sibling still dispatches into a free
380
+ // slot while this node's own invocation has already exited. A node's own
381
+ // steps stay ordered because only one settlement per node is ever in flight
382
+ // (see the dispatch loop below); a *different* node's settlement is queued
383
+ // behind whichever one is already running (`settlementQueue`), not run
384
+ // alongside it -- `finalizeClosedJobs` shares state a concurrent second call
385
+ // would corrupt: the phase-continuation selection that picks at most one
386
+ // live node to carry a session forward, and `repo/integrate.mjs`'s one
387
+ // candidate ref and worktree per run. Only *dispatching a sibling* skips
388
+ // ahead of a node's settlement; two nodes' settlements never interleave.
389
+ /** @type {Map<string, Promise<void>>} */
390
+ const pendingSettlements = new Map();
391
+ /** @type {Promise<void>} */
392
+ let settlementQueue = Promise.resolve();
367
393
  let canceled = false;
368
394
  const cancel = () => { canceled = true; };
369
395
  process.once("SIGINT", cancel);
370
396
  process.once("SIGTERM", cancel);
371
397
  process.once("SIGHUP", cancel);
372
398
  // The heartbeat's `at` is owned by an unref'd timer inside this writer, never
373
- // by the loop body below: the loop awaits controller verification on its own
374
- // critical path and must keep answering "the process is alive" while it does.
399
+ // by the loop body below: a node's settlement can still run for minutes off
400
+ // the tick's critical path (`pendingSettlements`), and the heartbeat must
401
+ // keep answering "the process is alive" while it does.
375
402
  const heartbeat = createHeartbeat({ runDir, intervalMs: HEARTBEAT_INTERVAL_MS });
376
403
  const heartbeatNodes = new Map(contract.nodes.map((node) => [node.id, node]));
377
404
  let heartbeatFingerprint = statesFingerprint(states);
@@ -380,11 +407,89 @@ export async function driveRun(contract, runDir, states, campaign, lock, sourceI
380
407
  const activeHeartbeatNodes = () => [...states.values()]
381
408
  .filter((state) => state.status === "running" && heartbeatNodes.has(state.id))
382
409
  .map((state) => ({ nodeId: state.id, budgetBasis: nodeBudgetBasisMs(contract, /** @type {ValidatedNode} */ (heartbeatNodes.get(state.id))) }));
410
+ // A programmer error surfacing inside a background settlement must still
411
+ // crash the whole run, exactly as an unguarded `await finalizeClosedJobs`
412
+ // used to: it is recorded here and thrown from the top of the loop on the
413
+ // very next tick, rather than immediately, so it cannot itself become the
414
+ // block a sibling's dispatch is waiting behind. A lost lock is not this --
415
+ // the loop's own `lock.assert()` calls surface that same condition on their
416
+ // own schedule, so it is left for them.
417
+ /** @type {unknown} */
418
+ let backgroundSettlementFailure = null;
419
+ // Mark every job that closed this tick as settling, and free its slot,
420
+ // without waiting for any of them: that alone is what lets an eligible
421
+ // sibling dispatch into the freed slot while this node's minutes-long
422
+ // controller verification or judge round is still running. The actual
423
+ // settlement work is chained onto `settlementQueue`, one node at a time in
424
+ // the order its job closed, so it still runs exactly as serialized against
425
+ // every *other* node's settlement as it did when this loop awaited
426
+ // `finalizeClosedJobs` directly -- `finalizeClosedJobs` runs against a
427
+ // one-entry map per node, so this is one call per node rather than the one
428
+ // batched call it used to be, but the chain still runs them one at a time.
429
+ // A settlement may itself dispatch the node's next phase (a judge, a
430
+ // revision) through the same `startJudge`/`startWorker` calls dispatch below
431
+ // uses; those land in `slot`, not the real `running`, so they are copied
432
+ // back into `running` in a `finally` -- unconditionally, win or lose, so a
433
+ // job a settlement started before failing (a lost lock, a programmer error)
434
+ // is still visible to the cleanup sweeps below rather than leaked. The
435
+ // node's own steps stay ordered by never starting a second settlement for a
436
+ // node whose first has not yet cleared `pendingSettlements`.
437
+ const settleClosedJobsInBackground = () => {
438
+ for (const [nodeId, job] of [...running]) {
439
+ if (pendingSettlements.has(nodeId) || !job.closed || invocationAlive(job.invocation)) continue;
440
+ running.delete(nodeId);
441
+ const slot = new Map([[nodeId, job]]);
442
+ const settlement = settlementQueue
443
+ .then(() => finalizeClosedJobs(contract, runDir, states, slot, lock, campaign.path))
444
+ .finally(() => {
445
+ for (const [settledId, settledJob] of slot) running.set(settledId, settledJob);
446
+ pendingSettlements.delete(nodeId);
447
+ });
448
+ // The queue itself must never reject -- a rejected settlement (a lost
449
+ // lock, a programmer error) would otherwise wedge every node queued
450
+ // behind it. The rejection still reaches whoever awaits the real
451
+ // `settlement` promise (`pendingSettlements`, below).
452
+ settlementQueue = settlement.catch(() => {});
453
+ // Handled here so an in-flight settlement never becomes an unhandled
454
+ // rejection when nobody happens to await `pendingSettlements` before the
455
+ // process exits; the original promise, still held below, carries the
456
+ // rejection to whichever checkpoint (cancel, shutdown) awaits it.
457
+ settlement.catch((error) => {
458
+ if (!(error instanceof LockLostError) && backgroundSettlementFailure === null) backgroundSettlementFailure = error;
459
+ });
460
+ pendingSettlements.set(nodeId, settlement);
461
+ }
462
+ };
463
+ // Captured once, before the loop, rather than re-derived every tick: it is
464
+ // "parked when this controller invocation started" (autoRetryParkedNodes's
465
+ // own contract), and a node a background settlement parks between two ticks
466
+ // -- rather than synchronously within one, as it always did before
467
+ // settlement moved off the tick's critical path -- must still read as newly
468
+ // parked whichever later tick first observes it, not as already-parked
469
+ // because a per-tick snapshot happened to be taken after it landed.
470
+ const parkedBefore = new Set([...states.values()].filter((state) => PARKED.has(state.status)).map((state) => state.id));
471
+ const anyUnsettled = () => [...states.values()].some((state) => !SETTLED.has(state.status));
383
472
  try {
384
- while ([...states.values()].some((state) => !SETTLED.has(state.status))) {
473
+ // A `while` that re-checked this at the very top of every tick would exit
474
+ // the instant a background settlement flips the run's last unsettled node
475
+ // straight to a terminal status between two ticks -- before the tick body
476
+ // that would have run `autoRetryParkedNodes` against that new status ever
477
+ // gets to. The entry guard skips the loop entirely when there is nothing
478
+ // to do at all (a resume of an already-settled run still does zero
479
+ // iterations); once inside, the exit check moves to the bottom, after the
480
+ // body, so that body always sees a freshly-parked node at least once
481
+ // before the loop is allowed to end.
482
+ if (anyUnsettled()) for (;;) {
385
483
  lock.assert();
484
+ if (backgroundSettlementFailure !== null) throw backgroundSettlementFailure;
386
485
  if (existsSync(join(runDir, "cancel.request.json"))) canceled = true;
387
486
  if (canceled) {
487
+ // A settlement already in flight owns the one decision a cancellation
488
+ // must not race: what this node's own invocation resolved to. Let it
489
+ // land on its real terminal status (and, when it re-dispatched a judge
490
+ // or a revision, on the new job that landed in `running`) before this
491
+ // branch decides which nodes are merely canceled.
492
+ await Promise.all([...pendingSettlements.values()]);
388
493
  const jobs = [...running.values()];
389
494
  await Promise.all(jobs.map((job) => terminateProcess(job)));
390
495
  const envelopes = new Map();
@@ -408,8 +513,14 @@ export async function driveRun(contract, runDir, states, campaign, lock, sourceI
408
513
  break;
409
514
  }
410
515
 
411
- const parkedBefore = new Set([...states.values()].filter((state) => PARKED.has(state.status)).map((state) => state.id));
412
- await finalizeClosedJobs(contract, runDir, states, running, lock, campaign.path);
516
+ // Advisory spend lines are checked every tick, closed job or not: a
517
+ // crossing must be visible while the spend is happening on a node still
518
+ // running, not only once it closes. `finalizeClosedJobs` used to open
519
+ // with this same check; calling it once here, rather than once per
520
+ // node settled this tick, is what keeps it at one pass per tick now
521
+ // that settlement runs per node in `settleClosedJobsInBackground`.
522
+ await emitNodeAdvisories(contract, runDir, states);
523
+ settleClosedJobsInBackground();
413
524
  await detectStalls(contract, running, async (job, status, error) => {
414
525
  const envelope = recordInvocationUsage(job);
415
526
  job.state.usage = invocationUsage(job.state);
@@ -450,8 +561,11 @@ export async function driveRun(contract, runDir, states, campaign, lock, sourceI
450
561
  writeNode(runDir, job.state, lock);
451
562
  });
452
563
  // A node left `running` with no job is a dead end; park it before the
453
- // dispatch pass so it cannot hide behind a healthy sibling.
454
- enforceRunningInvariant(runDir, states, running, lock);
564
+ // dispatch pass so it cannot hide behind a healthy sibling. A node
565
+ // whose closed job is settling in the background is not that dead end
566
+ // -- `pendingSettlements` is what tells this apart from one truly
567
+ // abandoned.
568
+ enforceRunningInvariant(runDir, states, running, lock, pendingSettlements);
455
569
  // Before dependants are blocked, a node that parked on this tick gets
456
570
  // its one automatic retry: it becomes pending, so `blockDependents` sees
457
571
  // nothing to block and the dependants stay `pending`/`phase: "waiting"`
@@ -463,14 +577,37 @@ export async function driveRun(contract, runDir, states, campaign, lock, sourceI
463
577
  if (slots > 0) {
464
578
  const ready = contract.nodes.filter((node) => {
465
579
  const state = states.get(node.id);
466
- return state?.status === "pending" && node.dependsOn.every((id) => states.get(id)?.status === "done");
580
+ return state?.status === "pending" && !pendingSettlements.has(node.id)
581
+ && node.dependsOn.every((id) => states.get(id)?.status === "done");
467
582
  });
468
583
  for (const node of ready.slice(0, slots)) {
469
584
  const state = states.get(node.id);
470
585
  if (!state || routingBackoffActive(state, state.phase)) continue;
586
+ // A node recovered pending a re-ask judge (its own worker attempt
587
+ // already accepted, `state.result` durable) reaches `settleDone` /
588
+ // `integrateAttempt` exactly like a closed job's own settlement
589
+ // does, on the same per-run candidate ref and worktree
590
+ // `settlementQueue` exists to serialize -- so it is dispatched the
591
+ // same way: chained onto the queue rather than awaited here, using
592
+ // its own one-entry `slot` merged back into `running` in a
593
+ // `finally`. The node's own order is untouched (still one entry at
594
+ // a time, gated by `pendingSettlements`); only the tick stops
595
+ // waiting behind it.
471
596
  if (state.phase === "judge" && state.result) {
472
- await applyJudgeRound(await startJudge(contract, node, state, runDir, running, state.result, lock, states, campaign.path),
473
- contract, node, state, runDir, running, lock, states, campaign.path, state.result);
597
+ const workerResult = state.result;
598
+ const slot = new Map();
599
+ const settlement = settlementQueue
600
+ .then(() => startJudge(contract, node, state, runDir, slot, workerResult, lock, states, campaign.path))
601
+ .then((round) => applyJudgeRound(round, contract, node, state, runDir, slot, lock, states, campaign.path, workerResult))
602
+ .finally(() => {
603
+ for (const [settledId, settledJob] of slot) running.set(settledId, settledJob);
604
+ pendingSettlements.delete(node.id);
605
+ });
606
+ settlementQueue = settlement.catch(() => {});
607
+ settlement.catch((error) => {
608
+ if (!(error instanceof LockLostError) && backgroundSettlementFailure === null) backgroundSettlementFailure = error;
609
+ });
610
+ pendingSettlements.set(node.id, settlement);
474
611
  continue;
475
612
  }
476
613
  state.attempt += 1;
@@ -499,10 +636,46 @@ export async function driveRun(contract, runDir, states, campaign, lock, sourceI
499
636
  }
500
637
  }
501
638
  heartbeat.setActive(activeHeartbeatNodes());
502
- if ([...states.values()].some((state) => !SETTLED.has(state.status))) await delay(contract.pollIntervalMs);
639
+ // A background settlement can flip a node straight to a parked
640
+ // terminal status during this same tick's own later awaits
641
+ // (`detectStalls`, `notifyStateChanges`), after the auto-retry pass
642
+ // above already ran and saw it as not-yet-parked. Running it once more
643
+ // here, immediately before the exit check, is what stops the loop from
644
+ // mistaking that freshly-parked node for settled and exiting before it
645
+ // ever got its automatic retry; a node it reopens dispatches on the
646
+ // next tick rather than this one, which `anyUnsettled()` below still
647
+ // correctly keeps the loop alive for.
648
+ autoRetryParkedNodes(contract, runDir, states, lock, parkedBefore);
649
+ if (!anyUnsettled()) break;
650
+ await delay(contract.pollIntervalMs);
503
651
  }
652
+ // The loop above exits (by the bottom check above or the cancel branch's
653
+ // `break`) the instant every node's state looks settled, but a
654
+ // settlement's own trailing work -- sealing a candidate's acceptance,
655
+ // removing its worktree, enqueueing its terminal notification -- can
656
+ // still be running after the transition that made the state look
657
+ // terminal. Nothing past this point (the final render, the findings
658
+ // artifact, the run-terminal notification, releasing the lock) may run
659
+ // ahead of that trailing work.
660
+ await Promise.all([...pendingSettlements.values()]);
661
+ // A settlement's own `finally` deletes it from `pendingSettlements` the
662
+ // instant it settles, win or lose -- so a rejection recorded here can
663
+ // already be gone from the map above by the time this line runs, with
664
+ // nothing left to await it. The loop's own top-of-tick check
665
+ // (`if (backgroundSettlementFailure !== null) throw ...`) cannot save
666
+ // that case either: the loop has already exited. Checked again here,
667
+ // once, so a background settlement failure can never read as a clean
668
+ // finish just because it settled on the same tick the run's last node
669
+ // did.
670
+ if (backgroundSettlementFailure !== null) throw backgroundSettlementFailure;
504
671
  } catch (error) {
505
672
  if (!(error instanceof LockLostError)) throw error;
673
+ // A settlement still merges whatever it started into `running` in its own
674
+ // `finally`, win or lose, regardless of whether anything awaits it; wait
675
+ // for that to land (never rejecting itself, so a second lock-loss here
676
+ // cannot mask the one already being handled) before the termination sweep
677
+ // reads `running`.
678
+ await Promise.allSettled([...pendingSettlements.values()]);
506
679
  await Promise.all([...running.values()].map((job) => terminateProcess(job)));
507
680
  notifyQueuesByRun.delete(runDir);
508
681
  return { runDir, states, ok: false, error };
@@ -165,7 +165,7 @@ export async function settleDone(contract, node, state, runDir, lock, states, ca
165
165
  attemptSha: sealed.sha,
166
166
  branch: state.worktree.branch,
167
167
  verificationEvidence: state.verification,
168
- verifyCandidate: (candidateWorkspace) => verifyCandidateWorkspace(contract, node, state, runDir, candidateWorkspace),
168
+ verifyCandidate: (candidateWorkspace) => verifyCandidateWorkspace(contract, node, state, runDir, candidateWorkspace, lock),
169
169
  onAccepted: async (transaction) => {
170
170
  const acceptedPath = state.worktree?.path ?? attemptWorktreePath(runDir, contract.id, node.id, transaction.attempt);
171
171
  if (state.attempt === transaction.attempt && state.status !== "done") {