opencode-model-router 1.14.0 → 1.15.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/CHANGELOG.md +115 -0
- package/README.md +3 -3
- package/package.json +2 -1
- package/src/index.ts +377 -58
- package/src/router/config.ts +211 -12
- package/src/router/protocol.ts +11 -2
- package/src/verify/baseline.ts +143 -25
- package/src/verify/batch.ts +2226 -0
- package/src/verify/deterministic.ts +1378 -20
- package/src/verify/directives.ts +207 -0
- package/src/verify/dispatch.ts +387 -90
- package/src/verify/exec.ts +654 -35
- package/src/verify/pending.ts +1834 -0
- package/src/verify/reference.ts +2117 -0
- package/src/verify/risk.ts +271 -0
- package/src/verify/runner.ts +5315 -0
- package/src/verify/slot.ts +1603 -0
- package/src/verify/tree.ts +215 -11
- package/src/verify/types.ts +301 -4
- package/src/verify/wiring.ts +1881 -51
- package/tiers.json +1 -2
package/src/verify/wiring.ts
CHANGED
|
@@ -13,20 +13,81 @@
|
|
|
13
13
|
* settings that were active when the plugin loaded, and `/preset` would
|
|
14
14
|
* silently stop applying to graded work.
|
|
15
15
|
*/
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
16
|
+
import { createHash } from "node:crypto";
|
|
17
|
+
import { access, readdir, readFile as fsReadFile, realpath, stat, unlink } from "node:fs/promises";
|
|
18
|
+
import { isAbsolute, join, relative, resolve } from "node:path";
|
|
19
|
+
import { createBatchCoordinator, type BatchCoordinatorOptions, type BatchPlanner } from "./batch";
|
|
20
|
+
import {
|
|
21
|
+
createDeadline,
|
|
22
|
+
createDirectTestsPassHook,
|
|
23
|
+
createMutexRegistry,
|
|
24
|
+
createScopeOpener,
|
|
25
|
+
DEFAULT_ALLOWLIST,
|
|
26
|
+
isCommandAllowed,
|
|
27
|
+
RECHECK_MIN_REMAINING_MS,
|
|
28
|
+
resolveRepoCommand,
|
|
29
|
+
type OwnedDeadline,
|
|
30
|
+
} from "./deterministic";
|
|
31
|
+
import { parseVerifyDirectives, type VerifyDirectives } from "./directives";
|
|
32
|
+
import {
|
|
33
|
+
ABANDONED_REASON,
|
|
34
|
+
ABSENT_DIGEST as PENDING_ABSENT_DIGEST,
|
|
35
|
+
buildDeferredFooter,
|
|
36
|
+
DISPOSED_REASON,
|
|
37
|
+
buildLineageCaveat,
|
|
38
|
+
createBackgroundQueue,
|
|
39
|
+
createPendingRegistry,
|
|
40
|
+
driftedPaths,
|
|
41
|
+
EXPIRED_HANDLE_TEXT,
|
|
42
|
+
MAX_HANDLES_PER_CALL,
|
|
43
|
+
MAX_STORED_CHANGED_FILES,
|
|
44
|
+
neutralizeDirectives,
|
|
45
|
+
normalizeHandle,
|
|
46
|
+
sanitizeDescription,
|
|
47
|
+
unattributedRisk,
|
|
48
|
+
UNKNOWN_HANDLE_TEXT,
|
|
49
|
+
VERIFYING_ELSEWHERE_TEXT,
|
|
50
|
+
VERIFYING_GRACE_MS,
|
|
51
|
+
type BackgroundOutcome,
|
|
52
|
+
type BackgroundQueue,
|
|
53
|
+
type BackgroundQueueOptions,
|
|
54
|
+
type FileDigests,
|
|
55
|
+
type PendingEntry,
|
|
56
|
+
type PendingRegistry,
|
|
57
|
+
type PendingRegistryOptions,
|
|
58
|
+
type SettledVerification,
|
|
59
|
+
type VerificationResult,
|
|
60
|
+
} from "./pending";
|
|
61
|
+
import { assessRisk, type RiskAssessment } from "./risk";
|
|
62
|
+
import { resolveBaseDir } from "./paths";
|
|
63
|
+
import { DEFAULT_IDLE_TTL_MS } from "../router/idle-sweep";
|
|
64
|
+
import {
|
|
65
|
+
buildAcceptedSuffix,
|
|
66
|
+
buildForcingNote,
|
|
67
|
+
tierModel,
|
|
68
|
+
toolLabel,
|
|
69
|
+
type ChangedFile,
|
|
70
|
+
type createChangedFileStore,
|
|
71
|
+
type DispatchCaptureDeps,
|
|
72
|
+
type TreeSnapshot,
|
|
73
|
+
} from "./dispatch";
|
|
74
|
+
import { runArgv, runShell } from "./exec";
|
|
21
75
|
import { snapshotTree } from "./tree";
|
|
76
|
+
import { captureReference, DEFAULT_CAPTURE_TIMEOUT_MS, gcStaleReferences, nodeReferenceFs, type DispatchReference } from "./reference";
|
|
77
|
+
import type { PluginLogger } from "../router/logger";
|
|
78
|
+
import { REFERENCE_NONE } from "./baseline";
|
|
79
|
+
import { scrubText } from "../guard/scrub";
|
|
22
80
|
import type { DoD } from "./dod";
|
|
23
|
-
import type {
|
|
81
|
+
import type { ArgvSeam, Deadline, ExecOptions, ExecResult as SeamResult, ExecSeam, ReferenceState, TestsPassHook, Verdict } from "./types";
|
|
82
|
+
import { planScopedRun, planStaticScoping, type ChangedPath, type RunnerFs, type StaticScoping, type TestSearchSeam } from "./runner";
|
|
24
83
|
import {
|
|
84
|
+
DEFAULT_GATE_BUDGET_MS,
|
|
25
85
|
graderTimeoutMs,
|
|
86
|
+
RouterTimeoutError,
|
|
26
87
|
withTimeout,
|
|
27
88
|
} from "./timeout";
|
|
28
|
-
import type
|
|
29
|
-
import type
|
|
89
|
+
import { resolveVerifyBudget, type RouterConfig, type VerifyBudget } from "../router/config";
|
|
90
|
+
import { accept, gateResult, unverifiableGateResult, type GateDeps, type GateResult } from "./gate";
|
|
30
91
|
// The grader request shape is owned by checker.ts, which builds it. Re-exported
|
|
31
92
|
// here because this module is where it is consumed, and because keeping a
|
|
32
93
|
// second local copy is exactly how `cwd` got dropped: the checker set it, the
|
|
@@ -62,13 +123,746 @@ export function extractAssistantText(res: any): string {
|
|
|
62
123
|
.join("\n");
|
|
63
124
|
}
|
|
64
125
|
|
|
126
|
+
/** P0 (deterministic.ts header, T2): what a gate needs from its dispatch. */
|
|
127
|
+
export interface PreparedVerification {
|
|
128
|
+
/**
|
|
129
|
+
* The producer's changed files: the tool-observed paths of every attempt judged against this
|
|
130
|
+
* dispatch (QA-2.1-1), the paths the current snapshot added since dispatch, and the paths dirty
|
|
131
|
+
* or untracked at dispatch whose content digest changed or which left the listing (QA-2.1-2);
|
|
132
|
+
* each with the snapshot's status letters and rename source when the snapshot lists it.
|
|
133
|
+
*/
|
|
134
|
+
changedFiles: ChangedFile[];
|
|
135
|
+
changeBaseline: "available" | "unavailable";
|
|
136
|
+
/** Settled: the dispatch reference, or why there is none. */
|
|
137
|
+
reference: ReferenceState;
|
|
138
|
+
/** The current tree snapshot (materialize's drift check); undefined when unavailable. */
|
|
139
|
+
snapshot: TreeSnapshot | undefined;
|
|
140
|
+
/**
|
|
141
|
+
* QA-3.1-2: other dispatches in the same git tree that were live during this dispatch's window
|
|
142
|
+
* (the change set holds their edits too). Absent or 0: none.
|
|
143
|
+
*/
|
|
144
|
+
concurrentDispatches?: number;
|
|
145
|
+
/** QA-3.1-3: the tool whose call discarded the dispatch snapshot, which left the change set unavailable. */
|
|
146
|
+
contaminatedBy?: string;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* QA-3.1-2: appended to a rejection that lists introduced failures when other delegations were live in
|
|
151
|
+
* the same working tree during the dispatch: the tree delta is not partitioned between them.
|
|
152
|
+
*/
|
|
153
|
+
export function concurrentDispatchesCaveat(count: number): string {
|
|
154
|
+
return `other delegations ran in this working tree concurrently (${count}); introduced failures may come from their edits`;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** QA-3.1-3: an unverifiable verdict whose change baseline a tool call discarded names that tool. */
|
|
158
|
+
export function contaminatedBaselineCaveat(tool: string): string {
|
|
159
|
+
return `the dispatch-time change baseline was discarded: tool "${toolLabel(tool)}" ran in an overlapping directory before it resolved`;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* QA-3.1-2 / QA-3.1-3: router caveats from the dispatch's own context, on a gate result. A fail that
|
|
164
|
+
* lists introduced failures gains concurrentDispatchesCaveat when other dispatches overlapped it; an
|
|
165
|
+
* unverifiable verdict gains contaminatedBaselineCaveat (reasons and caveats) when a tool call
|
|
166
|
+
* discarded its change baseline. The outcome and `accepted` never change. Pure; the text goes through
|
|
167
|
+
* neutralizeDirectives like all router text.
|
|
168
|
+
*/
|
|
169
|
+
export function applyDispatchCaveats(
|
|
170
|
+
res: GateResult,
|
|
171
|
+
ctx: { readonly concurrentDispatches?: number; readonly contaminatedBy?: string },
|
|
172
|
+
): GateResult {
|
|
173
|
+
const verdict = res.verdict;
|
|
174
|
+
if (verdict.skipped === true) return res;
|
|
175
|
+
const outcome = verdict.outcome ?? (verdict.pass ? "pass" : "fail");
|
|
176
|
+
const concurrent = ctx.concurrentDispatches ?? 0;
|
|
177
|
+
if (outcome === "fail" && concurrent > 0 && (verdict.failures?.introduced.length ?? 0) > 0) {
|
|
178
|
+
return { ...res, verdict: { ...verdict, reasons: [...verdict.reasons, neutralizeDirectives(concurrentDispatchesCaveat(concurrent))] } };
|
|
179
|
+
}
|
|
180
|
+
if (outcome === "unverifiable" && ctx.contaminatedBy !== undefined) {
|
|
181
|
+
const caveat = neutralizeDirectives(contaminatedBaselineCaveat(ctx.contaminatedBy));
|
|
182
|
+
return { ...res, verdict: { ...verdict, reasons: [...verdict.reasons, caveat], caveats: [...(verdict.caveats ?? []), caveat] } };
|
|
183
|
+
}
|
|
184
|
+
return res;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* QA-3.1-3: single flight for the dispatch-time snapshot and capture. Each dispatch spawns 7 git
|
|
189
|
+
* processes for its snapshot and 8 for its capture; 20 parallel dispatches spawned 300, and on
|
|
190
|
+
* Windows each then took 130-560 ms instead of ~60 ms (p50 2.9 s per dispatch).
|
|
191
|
+
*
|
|
192
|
+
* Requests with one key share one run, but a run is only ever shared by requests made BEFORE it
|
|
193
|
+
* started: a request that arrives while a run is in flight waits for the next run, which starts when
|
|
194
|
+
* the current one settled and serves every request that arrived meanwhile. A shared result is so
|
|
195
|
+
* always taken after each sharer's request began, as its own run would have been. A request's signal
|
|
196
|
+
* ends only its own wait (undefined); a started run is aborted once every sharer has left, and a
|
|
197
|
+
* queued run nobody waits for any more never starts. The returned function never rejects.
|
|
198
|
+
*
|
|
199
|
+
* QA-3.1-24: a started run whose last sharer left is also detached from its lane, so a run that
|
|
200
|
+
* ignores its abort (snapshotTree's lstat/readlink/realpath take no signal) cannot hold every later
|
|
201
|
+
* request with its key. Known limit: a request that arrives just after a run started waits for that
|
|
202
|
+
* run and then its own, while its timeout counts from its own request; when one snapshot or capture
|
|
203
|
+
* takes longer than half of the caller's timeout (baselineTimeoutMs, default 15 s), such an early
|
|
204
|
+
* arrival can time out before its own run ends. That fails closed: no change baseline, reference
|
|
205
|
+
* none, verdict unverifiable.
|
|
206
|
+
*/
|
|
207
|
+
export function createSharedFlight<T>(): (
|
|
208
|
+
key: string,
|
|
209
|
+
run: (signal: AbortSignal) => Promise<T | undefined>,
|
|
210
|
+
signal: AbortSignal,
|
|
211
|
+
) => Promise<T | undefined> {
|
|
212
|
+
interface Flight {
|
|
213
|
+
readonly controller: AbortController;
|
|
214
|
+
readonly result: Promise<T | undefined>;
|
|
215
|
+
readonly start: () => void;
|
|
216
|
+
sharers: number;
|
|
217
|
+
started: boolean;
|
|
218
|
+
}
|
|
219
|
+
interface Lane {
|
|
220
|
+
running?: Flight;
|
|
221
|
+
next?: Flight;
|
|
222
|
+
}
|
|
223
|
+
const lanes = new Map<string, Lane>();
|
|
224
|
+
const makeFlight = (run: (signal: AbortSignal) => Promise<T | undefined>): Flight => {
|
|
225
|
+
const controller = new AbortController();
|
|
226
|
+
let settle = (_value: T | undefined): void => undefined;
|
|
227
|
+
const result = new Promise<T | undefined>(ok => {
|
|
228
|
+
settle = ok;
|
|
229
|
+
});
|
|
230
|
+
const flight: Flight = {
|
|
231
|
+
controller,
|
|
232
|
+
result,
|
|
233
|
+
// Synchronous: the run's own start-up (the first git spawn) happens inside the call that
|
|
234
|
+
// starts it, so a VERIFY_WAIT counted from the dispatch's start covers it (ab81633).
|
|
235
|
+
start: () => {
|
|
236
|
+
flight.started = true;
|
|
237
|
+
let running: Promise<T | undefined>;
|
|
238
|
+
try {
|
|
239
|
+
running = run(controller.signal);
|
|
240
|
+
} catch {
|
|
241
|
+
running = Promise.resolve(undefined);
|
|
242
|
+
}
|
|
243
|
+
running.then(settle, () => settle(undefined));
|
|
244
|
+
},
|
|
245
|
+
sharers: 0,
|
|
246
|
+
started: false,
|
|
247
|
+
};
|
|
248
|
+
return flight;
|
|
249
|
+
};
|
|
250
|
+
// The lane's running flight is done with (settled, or detached by its last sharer): start the
|
|
251
|
+
// queued one, or retire an idle lane.
|
|
252
|
+
const advance = (key: string, lane: Lane): void => {
|
|
253
|
+
lane.running = undefined;
|
|
254
|
+
const next = lane.next;
|
|
255
|
+
lane.next = undefined;
|
|
256
|
+
if (next !== undefined) launch(key, lane, next);
|
|
257
|
+
else if (lanes.get(key) === lane) lanes.delete(key);
|
|
258
|
+
};
|
|
259
|
+
const launch = (key: string, lane: Lane, flight: Flight): void => {
|
|
260
|
+
lane.running = flight;
|
|
261
|
+
flight.start();
|
|
262
|
+
void flight.result.then(() => {
|
|
263
|
+
// QA-3.1-24: a flight its last sharer detached no longer owns the lane.
|
|
264
|
+
if (lane.running === flight) advance(key, lane);
|
|
265
|
+
});
|
|
266
|
+
};
|
|
267
|
+
return (key, run, signal) => {
|
|
268
|
+
if (signal.aborted) return Promise.resolve(undefined);
|
|
269
|
+
let lane = lanes.get(key);
|
|
270
|
+
if (lane === undefined) {
|
|
271
|
+
lane = {};
|
|
272
|
+
lanes.set(key, lane);
|
|
273
|
+
}
|
|
274
|
+
let flight: Flight;
|
|
275
|
+
if (lane.next !== undefined) flight = lane.next;
|
|
276
|
+
else if (lane.running !== undefined) flight = lane.next = makeFlight(run);
|
|
277
|
+
else {
|
|
278
|
+
flight = makeFlight(run);
|
|
279
|
+
launch(key, lane, flight);
|
|
280
|
+
}
|
|
281
|
+
flight.sharers += 1;
|
|
282
|
+
const owner = lane;
|
|
283
|
+
return new Promise<T | undefined>(settle => {
|
|
284
|
+
const onAbort = (): void => {
|
|
285
|
+
flight.sharers -= 1;
|
|
286
|
+
if (flight.sharers === 0) {
|
|
287
|
+
// Nobody waits for it any more: stop a started run; never start a queued one.
|
|
288
|
+
if (flight.started) {
|
|
289
|
+
flight.controller.abort();
|
|
290
|
+
// QA-3.1-24: a run that ignores its abort must not hold the lane until it settles.
|
|
291
|
+
// Detach it, so the queued run (whose sharers all asked after it started) goes now.
|
|
292
|
+
if (owner.running === flight) advance(key, owner);
|
|
293
|
+
} else if (owner.next === flight) owner.next = undefined;
|
|
294
|
+
}
|
|
295
|
+
settle(undefined);
|
|
296
|
+
};
|
|
297
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
298
|
+
void flight.result.then(value => {
|
|
299
|
+
signal.removeEventListener("abort", onAbort);
|
|
300
|
+
settle(value);
|
|
301
|
+
});
|
|
302
|
+
});
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* QA-2.1-11: the start-up reference GC runs this long after plugin start, so the start itself never
|
|
308
|
+
* holds the project directory with a git child process.
|
|
309
|
+
*/
|
|
310
|
+
export const REFERENCE_GC_START_DELAY_MS = 45_000;
|
|
311
|
+
/** How long the gate-time tree snapshot may take (bounded further by a gate deadline). */
|
|
312
|
+
export const GRADE_SNAPSHOT_TIMEOUT_MS = 10_000;
|
|
313
|
+
/** T3: each git test search, bounded further by a gate deadline. */
|
|
314
|
+
export const TEST_SEARCH_TIMEOUT_MS = 10_000;
|
|
315
|
+
/** QA-2.1-12: the `git diff <dispatch head> HEAD` of a gate whose HEAD moved, bounded further by a gate deadline. */
|
|
316
|
+
export const COMMIT_DIFF_TIMEOUT_MS = 10_000;
|
|
317
|
+
/**
|
|
318
|
+
* QA-2.2-21: the effective batch window is at most gateBudgetMs / this. config.ts accepts any
|
|
319
|
+
* batchWindowMs up to the timer limit, and a window close to the gate budget would spend most of
|
|
320
|
+
* it waiting (batch.ts W3 still keeps each member's recheck reserve).
|
|
321
|
+
*/
|
|
322
|
+
export const BATCH_WINDOW_BUDGET_DIVISOR = 10;
|
|
323
|
+
|
|
324
|
+
/** QA-2.2-21: batchWindowMs, capped at a tenth of the gate budget; <= 0 disables batching. */
|
|
325
|
+
export function effectiveBatchWindowMs(budget: Pick<VerifyBudget, "batchWindowMs" | "gateBudgetMs">): number {
|
|
326
|
+
return Math.min(budget.batchWindowMs, Math.floor(budget.gateBudgetMs / BATCH_WINDOW_BUDGET_DIVISOR));
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// -----------------------------------------------------------------------------------------------
|
|
330
|
+
// 2.4.2 deferred verification (plan Phase 2.4, sections 1.5-14..17; pending.ts R3, R10, R11)
|
|
331
|
+
// -----------------------------------------------------------------------------------------------
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* phase-2.4.md gather item 11: the bound on a deferred finish (tree snapshot, commit diff, static
|
|
335
|
+
* scoping). On expiry the change set is "unavailable" and the risk is unattributedRisk(), never [].
|
|
336
|
+
*/
|
|
337
|
+
export const DEFERRED_FINISH_MS = 2_000;
|
|
338
|
+
/** Upper bound on remembered native `task` dispatch starts (before hook -> after hook). */
|
|
339
|
+
export const DISPATCH_STARTS_MAX = 1_024;
|
|
340
|
+
/** Drift digests read at most this many bytes in total (tree.ts MAX_DIGEST_BYTES); beyond it: no digests. */
|
|
341
|
+
export const DRIFT_DIGEST_MAX_BYTES = 64 * 1024 * 1024;
|
|
342
|
+
/** Static scoping could not finish inside DEFERRED_FINISH_MS: counted as impossible (conservative). */
|
|
343
|
+
export const STATIC_SCOPING_UNFINISHED_REASON = "static scoping did not finish within the deferred-finish bound";
|
|
344
|
+
/** Section 1.4 pendingTtlMs default, used when the config cannot be read at plugin start. */
|
|
345
|
+
export const DEFAULT_PENDING_TTL_MS = 3_600_000;
|
|
346
|
+
/**
|
|
347
|
+
* QA-2.4-9: the capture wait when the config cannot be read: section 1.4's captureWaitMs default
|
|
348
|
+
* (5000 ms), clamped to the default baselineTimeoutMs (DEFAULT_CAPTURE_TIMEOUT_MS), as config.ts does.
|
|
349
|
+
*/
|
|
350
|
+
export const FALLBACK_CAPTURE_WAIT_MS = Math.min(5_000, DEFAULT_CAPTURE_TIMEOUT_MS);
|
|
351
|
+
|
|
352
|
+
/** What the orchestrator asked for at dispatch (directives.ts, parsed from its own prompt only). */
|
|
353
|
+
export interface DispatchStart {
|
|
354
|
+
readonly directives: VerifyDirectives;
|
|
355
|
+
/** Clock value when the dispatch started (pending.ts R3 dispatchedAt, R11 lineage). */
|
|
356
|
+
readonly dispatchedAt: number;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** What a deferred producer's return hands to finishDeferred (pending.ts R3). */
|
|
360
|
+
export interface DeferredFinishInput {
|
|
361
|
+
readonly dispatchID: string;
|
|
362
|
+
/** The session that called `task` / `delegate`; never the producer. */
|
|
363
|
+
readonly orchestratorSessionID: string;
|
|
364
|
+
readonly producerSessionID: string;
|
|
365
|
+
/** As received; canonicalised here (canonicalTier, 1.6 handoff item 8). */
|
|
366
|
+
readonly producerTier: string;
|
|
367
|
+
readonly description: string;
|
|
368
|
+
readonly cwd: string | undefined;
|
|
369
|
+
readonly dod: DoD;
|
|
370
|
+
readonly dispatchedAt: number;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* What finishDeferred decided. `deferred: false` means the delegation is NOT deferred and the
|
|
375
|
+
* caller runs today's required gate on it (QA-2.4-4, QA-2.4-10): the dispatch record is left in the
|
|
376
|
+
* store for that gate. Deferred or background verification is never weaker than that gate.
|
|
377
|
+
*/
|
|
378
|
+
export type DeferredFinish =
|
|
379
|
+
| {
|
|
380
|
+
readonly deferred: true;
|
|
381
|
+
/** The section 1.5-16 footer, naming the handle. */
|
|
382
|
+
readonly footer: string;
|
|
383
|
+
readonly handle: string;
|
|
384
|
+
readonly risk: RiskAssessment;
|
|
385
|
+
}
|
|
386
|
+
| {
|
|
387
|
+
readonly deferred: false;
|
|
388
|
+
/**
|
|
389
|
+
* "unregistered": the registry refused the entry (registry-full, handle-collision,
|
|
390
|
+
* invalid-input); "no-change": an attributed empty change set of a testsPass-only DoD, which
|
|
391
|
+
* the required gate passes with no process (section 1.5-6; QA-G-1: any other DoD is deferred
|
|
392
|
+
* with the empty set instead, noChangeGateSpawnsNothing); "error": the finish itself failed.
|
|
393
|
+
*/
|
|
394
|
+
readonly reason: "unregistered" | "no-change" | "error";
|
|
395
|
+
readonly detail: string;
|
|
396
|
+
};
|
|
397
|
+
|
|
398
|
+
/** What R11 lineage needs from a required gate's dispatch. */
|
|
399
|
+
export interface LineageContext {
|
|
400
|
+
readonly orchestratorSessionID: string;
|
|
401
|
+
/** Git top-level of the gate-time snapshot (TreeSnapshot.root); undefined -> no lineage either way. */
|
|
402
|
+
readonly root: string | undefined;
|
|
403
|
+
readonly dispatchID: string;
|
|
404
|
+
readonly dispatchedAt: number;
|
|
405
|
+
/** When the producer returned: the landedAt of a rejection recorded now. */
|
|
406
|
+
readonly returnedAt: number;
|
|
407
|
+
readonly strictUnverifiable: boolean | undefined;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** 1.6 handoff item 8: the canonical tier id is lowercase and trimmed. */
|
|
411
|
+
export function canonicalTier(tier: string): string {
|
|
412
|
+
return tier.trim().toLowerCase();
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* The text directives are parsed from: the orchestrator-authored `prompt` argument, or its
|
|
417
|
+
* `description` when the prompt is blank (the prompt-repair hook copies it in that case). Never a
|
|
418
|
+
* tool result or a subagent's text (directives.ts SECURITY).
|
|
419
|
+
*/
|
|
420
|
+
export function dispatchDirectiveText(prompt: string | undefined, description: string | undefined): string {
|
|
421
|
+
return prompt !== undefined && prompt.trim() !== "" ? prompt : (description ?? "");
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/** A DoD whose deferral section 1.5-14/16 governs: it carries a testsPass check. */
|
|
425
|
+
export function hasTestsPass(dod: DoD): boolean {
|
|
426
|
+
return dod.checks.some(c => c.kind === "testsPass");
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* QA-G-1: whether the required gate passes an attributed empty change set of this DoD with no
|
|
431
|
+
* process and no grader: every check is testsPass (its "no changed files" pass, section 1.5-6) and
|
|
432
|
+
* there is no criterion. Only such a delegation takes finishDeferred's "no-change" answer
|
|
433
|
+
* (QA-2.4-10); any other deferred DoD is registered with the empty change set instead, so its
|
|
434
|
+
* build, lint, run, file and criteria checks run on router_verify, never synchronously.
|
|
435
|
+
*/
|
|
436
|
+
export function noChangeGateSpawnsNothing(dod: DoD): boolean {
|
|
437
|
+
return dod.checks.length > 0 && dod.checks.every(c => c.kind === "testsPass") && dod.criteria.length === 0;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* pending.ts R3 `digests`: sha256 hex of each path's bytes, ABSENT_DIGEST for a missing path.
|
|
442
|
+
* fs reads only. Undefined (no drift claim either way) when a path is not a regular file or cannot
|
|
443
|
+
* be read, or when the set exceeds MAX_STORED_CHANGED_FILES paths or DRIFT_DIGEST_MAX_BYTES bytes.
|
|
444
|
+
* Never rejects. 2.4.3 computes the "after" side with the same function.
|
|
445
|
+
*/
|
|
446
|
+
export async function digestFiles(paths: readonly string[]): Promise<FileDigests | undefined> {
|
|
447
|
+
if (paths.length > MAX_STORED_CHANGED_FILES) return undefined;
|
|
448
|
+
const out = new Map<string, string>();
|
|
449
|
+
let total = 0;
|
|
450
|
+
for (const path of paths) {
|
|
451
|
+
try {
|
|
452
|
+
const info = await stat(path);
|
|
453
|
+
if (!info.isFile()) return undefined;
|
|
454
|
+
total += info.size;
|
|
455
|
+
if (total > DRIFT_DIGEST_MAX_BYTES) return undefined;
|
|
456
|
+
out.set(path, createHash("sha256").update(await fsReadFile(path)).digest("hex"));
|
|
457
|
+
} catch (err) {
|
|
458
|
+
if (err instanceof Error && "code" in err && err.code === "ENOENT") {
|
|
459
|
+
out.set(path, PENDING_ABSENT_DIGEST);
|
|
460
|
+
continue;
|
|
461
|
+
}
|
|
462
|
+
return undefined;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
return out;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// -----------------------------------------------------------------------------------------------
|
|
469
|
+
// 2.4.3a router_verify (plan section 1.5-18; pending.ts R2, R4, R6, R8, R9, R11)
|
|
470
|
+
// -----------------------------------------------------------------------------------------------
|
|
471
|
+
|
|
472
|
+
/** What one router_verify call asks for (index.ts builds it with parseRouterVerifyArgs). */
|
|
473
|
+
export type VerifyTarget =
|
|
474
|
+
| { readonly kind: "handles"; readonly handles: readonly unknown[] }
|
|
475
|
+
| { readonly kind: "pending" };
|
|
476
|
+
|
|
477
|
+
/** One line of a router_verify report, in the order the handles were named. */
|
|
478
|
+
export type HandleReport =
|
|
479
|
+
| {
|
|
480
|
+
readonly kind: "verdict";
|
|
481
|
+
readonly handle: string;
|
|
482
|
+
readonly description: string;
|
|
483
|
+
readonly producerTier: string;
|
|
484
|
+
/** "run": judged by this call; "joined": another call's run; "cached": settled earlier, nothing ran. */
|
|
485
|
+
readonly via: "run" | "joined" | "cached";
|
|
486
|
+
readonly result: SettledVerification;
|
|
487
|
+
}
|
|
488
|
+
/** Malformed, never issued, or issued to another session (R6): nothing distinguishes them. */
|
|
489
|
+
| { readonly kind: "unknown"; readonly input: string }
|
|
490
|
+
| { readonly kind: "expired"; readonly handle: string }
|
|
491
|
+
/** Joined another call's run, which outlived this call's deadline (R8). */
|
|
492
|
+
| { readonly kind: "elsewhere"; readonly handle: string; readonly description: string };
|
|
493
|
+
|
|
494
|
+
export interface VerifyReport {
|
|
495
|
+
readonly items: readonly HandleReport[];
|
|
496
|
+
/** Distinct handles beyond MAX_HANDLES_PER_CALL: reported, never run (R2). */
|
|
497
|
+
readonly excess: number;
|
|
498
|
+
readonly text: string;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
export const ROUTER_VERIFY_ARGS_TEXT =
|
|
502
|
+
"[router] router_verify: pass exactly one of `handles` (a non-empty list of vrf_ handles) or `pending: true`; nothing was run.";
|
|
503
|
+
export const ROUTER_VERIFY_NO_PENDING_TEXT = "[router] router_verify: no unverified delegations in this session; nothing was run.";
|
|
504
|
+
export const ROUTER_VERIFY_NO_RETRY_TEXT = "[router] Nothing was retried or escalated; whether to re-dispatch is your call.";
|
|
505
|
+
/** Section 1.5-18. The run always uses the current tree. */
|
|
506
|
+
export const DRIFT_NOTICE = "tree drifted since delegation; verdict reflects current state";
|
|
507
|
+
/** No per-file proof either way (no stored or current digests): a pass is never kept then. */
|
|
508
|
+
export const DRIFT_UNCHECKED_NOTICE = "drift since delegation could not be checked; verdict reflects current state";
|
|
509
|
+
export const ROUTER_VERIFY_CANCELLED_REASON = "router_verify was cancelled before a verdict";
|
|
510
|
+
export const ROUTER_VERIFY_RELEASED_REASON = "the delegation's verification data was released";
|
|
511
|
+
/** Drifted paths named per handle; the rest are counted. */
|
|
512
|
+
export const DRIFT_MAX_PATHS = 10;
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* index.ts `router_verify` args. The SDK's arg root is an object shape (phase-2.4.md gather item
|
|
516
|
+
* 1), so "exactly one of handles / pending" is checked here: both, neither, `pending` other than
|
|
517
|
+
* true, and `handles` that is not a non-empty array are errors. Pure; never throws.
|
|
518
|
+
*/
|
|
519
|
+
export function parseRouterVerifyArgs(args: unknown): VerifyTarget | { readonly error: string } {
|
|
520
|
+
const a = args !== null && typeof args === "object" ? (args as Record<string, unknown>) : {};
|
|
521
|
+
const hasHandles = a.handles !== undefined && a.handles !== null;
|
|
522
|
+
const hasPending = a.pending !== undefined && a.pending !== null;
|
|
523
|
+
if (hasHandles === hasPending) return { error: ROUTER_VERIFY_ARGS_TEXT };
|
|
524
|
+
if (hasPending) return a.pending === true ? { kind: "pending" } : { error: ROUTER_VERIFY_ARGS_TEXT };
|
|
525
|
+
if (!Array.isArray(a.handles) || a.handles.length === 0) return { error: ROUTER_VERIFY_ARGS_TEXT };
|
|
526
|
+
return { kind: "handles", handles: a.handles };
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/** A literal phrase inside a RegExp source. */
|
|
530
|
+
function escapeRegExp(text: string): string {
|
|
531
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* pending.ts R4: reasons that say nothing about the producer's work (slot busy, the deadline or an
|
|
536
|
+
* abort, a timeout, an executor or coordinator error). Matched on 2.1/2.2's stable phrases
|
|
537
|
+
* (deterministic.ts u6, u7, u13, u14, u16; batch.ts BATCH_REASONS; baseline.ts
|
|
538
|
+
* REFERENCE_NONE.gateBudget) and this module's own. REFERENCE_NONE.failed ("failed or timed out" at
|
|
539
|
+
* dispatch) is deliberately not matched: that reference cannot be recaptured, so it is terminal.
|
|
540
|
+
*
|
|
541
|
+
* QA-2.4-14: only where the ROUTER writes it: at the start of a reason, after at most one check-kind
|
|
542
|
+
* word ("testsPass: ", "testsPass "). Producer-controlled text (failing test ids, "file > title")
|
|
543
|
+
* only ever follows a router phrase ("introduced failures: ", "; observed failures: "), so a test
|
|
544
|
+
* titled "verification slot busy" can never make a terminal verdict retryable.
|
|
545
|
+
*/
|
|
546
|
+
const TRANSIENT_REASON = new RegExp(
|
|
547
|
+
"^(?:[A-Za-z]+:? )?(?:" +
|
|
548
|
+
[
|
|
549
|
+
"gate budget exhausted", // u7, u14 (deadline cut)
|
|
550
|
+
"verification slot busy", // u14
|
|
551
|
+
"timed out after \\d+ ?ms", // u13: "testsPass timed out after <n>ms: <command>"
|
|
552
|
+
"check errored", // u16: "testsPass check errored: <reason>"
|
|
553
|
+
"cannot attribute failures: the reference rerun timed out after \\d+ ?ms", // u6
|
|
554
|
+
`(?:no reference: pre-existing failures cannot be told apart \\()?${escapeRegExp(REFERENCE_NONE.gateBudget)}`,
|
|
555
|
+
"verification gate timed out after \\d+ ?ms",
|
|
556
|
+
"verification coordinator (?:disposed|failed)",
|
|
557
|
+
"verification batch (?:failed|ended without an outcome|produced no outcome)",
|
|
558
|
+
"verification unavailable:",
|
|
559
|
+
escapeRegExp(ABANDONED_REASON),
|
|
560
|
+
escapeRegExp(DISPOSED_REASON),
|
|
561
|
+
"router_verify was cancelled",
|
|
562
|
+
].join("|") +
|
|
563
|
+
")",
|
|
564
|
+
"i",
|
|
565
|
+
);
|
|
566
|
+
|
|
567
|
+
/**
|
|
568
|
+
* pending.ts R4 `retryable`: only an unverifiable (or skipped) verdict can be retryable, and only
|
|
569
|
+
* when the call was cut (deadline, abort) or a reason is transient. A pass or a fail is a verdict on
|
|
570
|
+
* the work and always terminal. Misclassification is never a false pass either way: a retryable
|
|
571
|
+
* entry is re-run later, a terminal unverifiable is replayed.
|
|
572
|
+
*/
|
|
573
|
+
export function isRetryableVerdict(verdict: Verdict, cut: boolean): boolean {
|
|
574
|
+
if (verdict.skipped === true) return true;
|
|
575
|
+
const outcome = verdict.outcome ?? (verdict.pass ? "pass" : "fail");
|
|
576
|
+
if (outcome !== "unverifiable") return false;
|
|
577
|
+
if (cut) return true;
|
|
578
|
+
return [...verdict.reasons, ...(verdict.caveats ?? [])].some(r => TRANSIENT_REASON.test(r));
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
function formatPaths(paths: readonly string[], base: string): string {
|
|
582
|
+
const shown = paths.slice(0, DRIFT_MAX_PATHS).map(p => {
|
|
583
|
+
const rel = relative(base, p);
|
|
584
|
+
return sanitizeDescription(rel !== "" && !rel.startsWith("..") && !isAbsolute(rel) ? rel : p);
|
|
585
|
+
});
|
|
586
|
+
const rest = paths.length - shown.length;
|
|
587
|
+
return rest > 0 ? `${shown.join(", ")} (+${rest} more)` : shown.join(", ");
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
function indent(text: string): string {
|
|
591
|
+
return text.split("\n").map(line => ` ${line}`).join("\n");
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/**
|
|
595
|
+
* Section 1.5-18 / R9: one block per handle, in call order. A judged handle carries the required
|
|
596
|
+
* gate's own wording: buildAcceptedSuffix when accepted, buildForcingNote (with the next tier on a
|
|
597
|
+
* fail) plus ROUTER_VERIFY_NO_RETRY_TEXT when not. A retryable result is "not judged" and the
|
|
598
|
+
* delegation stays unverified. Pure.
|
|
599
|
+
*/
|
|
600
|
+
export function formatVerifyReport(
|
|
601
|
+
items: readonly HandleReport[],
|
|
602
|
+
excess: number,
|
|
603
|
+
strictUnverifiable: boolean,
|
|
604
|
+
cwdOf: (handle: string) => string | undefined = () => undefined,
|
|
605
|
+
): string {
|
|
606
|
+
const blocks: string[] = [];
|
|
607
|
+
for (const item of items) {
|
|
608
|
+
if (item.kind === "unknown") {
|
|
609
|
+
blocks.push(`- ${sanitizeDescription(item.input)} \u00b7 ${UNKNOWN_HANDLE_TEXT}`);
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
if (item.kind === "expired") {
|
|
613
|
+
blocks.push(`- ${item.handle} \u00b7 ${EXPIRED_HANDLE_TEXT}`);
|
|
614
|
+
continue;
|
|
615
|
+
}
|
|
616
|
+
if (item.kind === "elsewhere") {
|
|
617
|
+
blocks.push(`- ${item.handle} \u00b7 ${item.description} \u00b7 ${VERIFYING_ELSEWHERE_TEXT}`);
|
|
618
|
+
continue;
|
|
619
|
+
}
|
|
620
|
+
const { result } = item;
|
|
621
|
+
const verdict = result.verdict;
|
|
622
|
+
const via = item.via === "joined" ? " (joined a run already in progress)" : item.via === "cached" ? " (cached verdict; nothing was run)" : "";
|
|
623
|
+
if (result.retryable) {
|
|
624
|
+
const why = scrubText([...new Set([...(verdict.caveats ?? []), ...verdict.reasons])].join("; ") || "no verdict");
|
|
625
|
+
blocks.push(
|
|
626
|
+
`- ${item.handle} \u00b7 ${item.description} \u00b7 not judged${via}: ${why}\n` +
|
|
627
|
+
" [router] The delegation is still unverified; call `router_verify` again for a verdict.",
|
|
628
|
+
);
|
|
629
|
+
continue;
|
|
630
|
+
}
|
|
631
|
+
const judged = gateResult(verdict, "explicit", strictUnverifiable);
|
|
632
|
+
const outcome = judged.verdict.outcome ?? "fail";
|
|
633
|
+
const lines = [`- ${item.handle} \u00b7 ${item.description} \u00b7 ${outcome}${via}`];
|
|
634
|
+
const base = cwdOf(item.handle) ?? "";
|
|
635
|
+
if (result.driftedPaths !== undefined && result.driftedPaths.length > 0) {
|
|
636
|
+
lines.push(indent(`[router] ${DRIFT_NOTICE} (changed after the producer returned: ${formatPaths(result.driftedPaths, base)})`));
|
|
637
|
+
} else if ((verdict.caveats ?? []).includes(DRIFT_UNCHECKED_NOTICE)) {
|
|
638
|
+
lines.push(indent(`[router] ${DRIFT_UNCHECKED_NOTICE}`));
|
|
639
|
+
}
|
|
640
|
+
if (judged.accepted) {
|
|
641
|
+
lines.push(indent(buildAcceptedSuffix(verdict.method, judged.verdict.outcome, judged.verdict.caveats, verdict.notes).trim()));
|
|
642
|
+
} else {
|
|
643
|
+
lines.push(indent(scrubText(buildForcingNote(verdict.reasons, { producerTier: item.producerTier, nextTier: result.nextTier ?? null }))));
|
|
644
|
+
lines.push(indent(ROUTER_VERIFY_NO_RETRY_TEXT));
|
|
645
|
+
}
|
|
646
|
+
blocks.push(lines.join("\n"));
|
|
647
|
+
}
|
|
648
|
+
if (excess > 0) {
|
|
649
|
+
blocks.push(`- ${excess} more handle(s) not run: at most ${MAX_HANDLES_PER_CALL} per call; call \`router_verify\` again with the rest.`);
|
|
650
|
+
}
|
|
651
|
+
// QA-2.4-6 (R9): reasons, caveats and notes quote producer-controlled text (failing test ids).
|
|
652
|
+
// An orchestrator that quotes this report before its own `VERIFY:` must not change its mode.
|
|
653
|
+
return neutralizeDirectives(
|
|
654
|
+
[`[router] router_verify: one verdict per handle (${items.length}${excess > 0 ? ` of ${items.length + excess}` : ""}).`, ...blocks].join("\n"),
|
|
655
|
+
);
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
/**
|
|
659
|
+
* 2.4.5 (pending.ts R14): a background run's report as queue outcomes. Only this run's own verdict
|
|
660
|
+
* ("run") is "judged"; a verdict another router_verify call produced or had cached, and a run that
|
|
661
|
+
* call still owns ("elsewhere"), are "reported" (that caller has or gets it); unknown and expired
|
|
662
|
+
* handles are "gone". Pure.
|
|
663
|
+
*/
|
|
664
|
+
export function backgroundOutcomes(items: readonly HandleReport[]): BackgroundOutcome[] {
|
|
665
|
+
return items.map((item): BackgroundOutcome => {
|
|
666
|
+
if (item.kind === "verdict") {
|
|
667
|
+
return item.via === "run"
|
|
668
|
+
? { kind: "judged", handle: item.handle, description: item.description, result: item.result }
|
|
669
|
+
: { kind: "reported", handle: item.handle };
|
|
670
|
+
}
|
|
671
|
+
if (item.kind === "elsewhere") return { kind: "reported", handle: item.handle };
|
|
672
|
+
return { kind: "gone", handle: item.kind === "unknown" ? item.input : item.handle };
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
/** A never-rejecting wait for `promise` that ends with `fallback()` once `signal` aborts. */
|
|
677
|
+
function untilAborted<T>(promise: Promise<T>, signal: AbortSignal, fallback: () => T): Promise<T> {
|
|
678
|
+
if (signal.aborted) return Promise.resolve(fallback());
|
|
679
|
+
return new Promise<T>(settle => {
|
|
680
|
+
const onAbort = (): void => settle(fallback());
|
|
681
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
682
|
+
promise.then(
|
|
683
|
+
value => {
|
|
684
|
+
signal.removeEventListener("abort", onAbort);
|
|
685
|
+
settle(value);
|
|
686
|
+
},
|
|
687
|
+
() => {
|
|
688
|
+
signal.removeEventListener("abort", onAbort);
|
|
689
|
+
settle(fallback());
|
|
690
|
+
},
|
|
691
|
+
);
|
|
692
|
+
});
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
function unverifiableVerdict(reason: string): Verdict {
|
|
696
|
+
return { pass: false, outcome: "unverifiable", method: "none", reasons: [reason], caveats: [reason] };
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
/** Drift of one delegation's files since its producer returned (pending.ts R3 digests). */
|
|
700
|
+
type DriftCheck = { readonly kind: "none" } | { readonly kind: "drifted"; readonly paths: readonly string[] } | { readonly kind: "unchecked" };
|
|
701
|
+
|
|
702
|
+
/** A full object name (SHA-1 or SHA-256); anything else (e.g. an unborn HEAD) is an unknown head. */
|
|
703
|
+
const OBJECT_NAME = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i;
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* QA-2.1-12: parses `git diff --name-status -z -M` into absolute paths under `root`: one status
|
|
707
|
+
* token, then one path, or two (source, destination) for a rename or copy. Undefined when malformed.
|
|
708
|
+
*/
|
|
709
|
+
export function parseNameStatusZ(out: string, root: string): ChangedFile[] | undefined {
|
|
710
|
+
const tokens = out.split("\0");
|
|
711
|
+
if (tokens[tokens.length - 1] === "") tokens.pop();
|
|
712
|
+
const files: ChangedFile[] = [];
|
|
713
|
+
for (let i = 0; i < tokens.length;) {
|
|
714
|
+
const status = tokens[i++];
|
|
715
|
+
if (!/^[A-Z][0-9]*$/.test(status)) return undefined;
|
|
716
|
+
const letter = status[0];
|
|
717
|
+
if (letter === "R" || letter === "C") {
|
|
718
|
+
const source = tokens[i++];
|
|
719
|
+
const dest = tokens[i++];
|
|
720
|
+
if (!source || !dest) return undefined;
|
|
721
|
+
files.push({ path: resolve(root, dest), status: letter, previousPath: resolve(root, source) });
|
|
722
|
+
} else {
|
|
723
|
+
const path = tokens[i++];
|
|
724
|
+
if (!path) return undefined;
|
|
725
|
+
files.push({ path: resolve(root, path), status: letter });
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
return files;
|
|
729
|
+
}
|
|
730
|
+
/** P5: the per-check timeout (DeterministicDeps.timeoutMs default). */
|
|
731
|
+
const CHECK_TIMEOUT_MS = 120_000;
|
|
732
|
+
|
|
65
733
|
export interface VerificationWiring {
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
734
|
+
/**
|
|
735
|
+
* Starts the dispatch's background work: the tree snapshot and, only for a DoD with an
|
|
736
|
+
* allowlisted testsPass check and failureRecheck on, a git-only reference capture bounded by
|
|
737
|
+
* baselineTimeoutMs. Resolves when both settled; never rejects. No test command runs (G6).
|
|
738
|
+
*/
|
|
739
|
+
beginVerification(store: ReturnType<typeof createChangedFileStore>, id: string, cwd: string | undefined, dod: DoD): Promise<void>;
|
|
740
|
+
/**
|
|
741
|
+
* 2.1.5b: beginVerification, awaited for at most `waitMs` (2.4.2a: the dispatch's VERIFY_WAIT;
|
|
742
|
+
* default captureWaitMs). The capture keeps running (up to baselineTimeoutMs) in the store after
|
|
743
|
+
* a timeout; a timeout or error only means "no reference yet" and is logged. Never rejects.
|
|
744
|
+
*/
|
|
745
|
+
beginVerificationBounded(
|
|
746
|
+
store: ReturnType<typeof createChangedFileStore>,
|
|
747
|
+
id: string,
|
|
748
|
+
cwd: string | undefined,
|
|
749
|
+
dod: DoD,
|
|
750
|
+
waitMs?: number,
|
|
751
|
+
): Promise<void>;
|
|
752
|
+
/**
|
|
753
|
+
* 2.4.2a: parseVerifyDirectives over `text` with the config defaults (defaultVerify,
|
|
754
|
+
* captureWaitMs, baselineTimeoutMs). `text` MUST be the orchestrator's own prompt
|
|
755
|
+
* (dispatchDirectiveText). Unknown values are logged. Never throws: when the config cannot be
|
|
756
|
+
* read, the mode is "required" (today's gate) and the wait FALLBACK_CAPTURE_WAIT_MS (QA-2.4-9).
|
|
757
|
+
*/
|
|
758
|
+
resolveDirectives(text: string): VerifyDirectives;
|
|
759
|
+
/**
|
|
760
|
+
* 2.4.2a: resolveDirectives, then beginVerificationBounded for at most the directives' waitMs
|
|
761
|
+
* (section 1.5-14: VERIFY_WAIT, 0 allowed), counted from this call, so the directive read and
|
|
762
|
+
* the capture's synchronous start-up are inside it. `remember` keeps the start for takeDispatch
|
|
763
|
+
* (the native `task` after hook). Never rejects.
|
|
764
|
+
*/
|
|
765
|
+
startDispatch(
|
|
766
|
+
store: ReturnType<typeof createChangedFileStore>,
|
|
767
|
+
id: string,
|
|
768
|
+
cwd: string | undefined,
|
|
769
|
+
dod: DoD,
|
|
770
|
+
text: string,
|
|
771
|
+
remember: boolean,
|
|
772
|
+
): Promise<DispatchStart>;
|
|
773
|
+
/**
|
|
774
|
+
* 2.4.2b: the start remembered by startDispatch, forgotten on read. When none is remembered (the
|
|
775
|
+
* before hook did not run, or the entry was swept), `text` is parsed again (same orchestrator
|
|
776
|
+
* prompt) and dispatchedAt is now: a later dispatchedAt can only widen R11 lineage (fewer
|
|
777
|
+
* passes), never narrow it.
|
|
778
|
+
*/
|
|
779
|
+
takeDispatch(id: string, text: string): DispatchStart;
|
|
780
|
+
/**
|
|
781
|
+
* 2.4.2a: whether this delegation defers (section 1.5-16): mode "deferred", a testsPass check
|
|
782
|
+
* in the DoD, and verification not disabled (`require: "never"`). Everything else is gated
|
|
783
|
+
* exactly as before 2.4.
|
|
784
|
+
* QA-2.4-10: only what the required gate would actually judge defers. `trivial` is the gate's own
|
|
785
|
+
* input (the native path's dispatch-time classification; delegate passes none): the gate skips a
|
|
786
|
+
* trivial dispatch whose DoD was inferred (gate.ts), so that one is not deferred and takes the
|
|
787
|
+
* required path, with the same outcome. (An attributed empty change set of a testsPass-only DoD
|
|
788
|
+
* is the other case; finishDeferred answers "no-change" for it. QA-G-1: a DoD with any other
|
|
789
|
+
* check or a criterion stays deferred with that empty set.)
|
|
790
|
+
*/
|
|
791
|
+
isDeferred(dod: DoD, directives: VerifyDirectives, trivial?: boolean): boolean;
|
|
792
|
+
/**
|
|
793
|
+
* 2.4.2a: the deferred finish. No gate, no test command, no slot: a tree snapshot and the commit
|
|
794
|
+
* diff (git only, as prepareVerification) under DEFERRED_FINISH_MS, the static scoping plan
|
|
795
|
+
* (runner.ts: no spawn), the risk (pending.ts R10), the drift digests (fs reads, awaited inside
|
|
796
|
+
* the same bound so the baseline predates the result, QA-2.4-8),
|
|
797
|
+
* `pending.register`, and the section 1.5-16 footer. The dispatch's reference promise is
|
|
798
|
+
* registered un-awaited, and the dispatch record is cleared only after it settles (clearing it
|
|
799
|
+
* earlier would abort the capture). Never rejects. QA-2.4-4: when the registry refuses the entry
|
|
800
|
+
* or the finish fails, the result is `deferred: false` and the caller runs the required gate on
|
|
801
|
+
* the dispatch (whose record is then left in the store); there is no footer without a handle.
|
|
802
|
+
*/
|
|
803
|
+
finishDeferred(store: ReturnType<typeof createChangedFileStore>, input: DeferredFinishInput): Promise<DeferredFinish>;
|
|
804
|
+
/**
|
|
805
|
+
* 2.4.2b/c, pending.ts R11 on a required gate's result:
|
|
806
|
+
* - outcome "fail" with proven-introduced ids -> pending.recordRejection (label
|
|
807
|
+
* "dispatch <id>", landedAt = returnedAt); the result is returned unchanged;
|
|
808
|
+
* - otherwise, proven pre-existing ids that an earlier rejection of the same session and root
|
|
809
|
+
* introduced (findLineage) -> the verdict becomes unverifiable with buildLineageCaveat; it
|
|
810
|
+
* stays accepted unless strictUnverifiable. It never creates a pass or a fail.
|
|
811
|
+
* A verdict without `failures` (checker verdicts, a timed-out gate) and an unknown root are
|
|
812
|
+
* returned unchanged and record nothing.
|
|
813
|
+
*/
|
|
814
|
+
applyLineage(res: GateResult, ctx: LineageContext): GateResult;
|
|
815
|
+
/**
|
|
816
|
+
* 2.4.3a, section 1.5-18: router_verify for `sessionID` (the calling orchestrator; "" = none, so
|
|
817
|
+
* every handle is unknown). Never rejects; never retries or escalates.
|
|
818
|
+
* - Handles are normalized, deduped and capped at MAX_HANDLES_PER_CALL; `pending` is listOpen, so
|
|
819
|
+
* runs already in flight are joined (R8). Lookups are scoped by session (R6).
|
|
820
|
+
* - ONE Deadline of gateBudgetMs per call, created before any preparation (section 1.5-13) and
|
|
821
|
+
* shared by every claimed handle, so their testsPass requests meet in one S5 window.
|
|
822
|
+
* - Each claimed handle runs the required gate's path: its stored changed files, its stored
|
|
823
|
+
* reference (awaited under the deadline), a fresh tree snapshot, buildGateDeps + accept under
|
|
824
|
+
* withTimeout(deadline.remaining()). All preparations finish before any gate starts.
|
|
825
|
+
* - R11 lineage can only turn a pass into unverifiable; drift (stored vs current digests) or
|
|
826
|
+
* unprovable drift never lets a pass stand (DRIFT_NOTICE / DRIFT_UNCHECKED_NOTICE).
|
|
827
|
+
* - QA-2.4-1: judged in two phases. Every gate of the call returns, every terminal fail with
|
|
828
|
+
* proven-introduced ids is recorded in the R11 ledger, and only then are lineage, drift and the
|
|
829
|
+
* next tier applied to every result, so the handle order and the gates' finishing order never
|
|
830
|
+
* decide a verdict. A background run is one such call.
|
|
831
|
+
* - claim.settle runs in a `finally`; a transient unverifiable (isRetryableVerdict) returns the
|
|
832
|
+
* entry to unverified. A fail carries buildForcingNote with the next tier, and nothing else.
|
|
833
|
+
* `signal` (the tool call's abort) aborts the deadline. `background` (2.4.5, the background
|
|
834
|
+
* queue's own runs only) runs the gates at low priority whatever `lowPriority` says; any other
|
|
835
|
+
* call marks the handles it reported, so no late notice repeats a verdict the caller received.
|
|
836
|
+
*/
|
|
837
|
+
verifyHandles(
|
|
838
|
+
sessionID: string,
|
|
839
|
+
target: VerifyTarget,
|
|
840
|
+
options?: { readonly signal?: AbortSignal; readonly background?: boolean },
|
|
841
|
+
): Promise<VerifyReport>;
|
|
842
|
+
/** 2.4.1: the plugin instance's pending registry (sweep, forgetSession, dispose are wired in index.ts). */
|
|
843
|
+
pending: PendingRegistry;
|
|
844
|
+
/**
|
|
845
|
+
* 2.4.5 (pending.ts R14): the background queue, constructed only when `background` is true at
|
|
846
|
+
* plugin start; undefined otherwise, and nothing then refers to one. The deferred finish feeds
|
|
847
|
+
* it; index.ts reads its late notices in the system transform and forgets a deleted session.
|
|
848
|
+
*/
|
|
849
|
+
background: BackgroundQueue | undefined;
|
|
850
|
+
/**
|
|
851
|
+
* 2.1.5b: the crash GC of stale reference dirs, fire-and-forget. QA-2.1-11: it runs `delayMs`
|
|
852
|
+
* (default REFERENCE_GC_START_DELAY_MS) after the call, on an unref'd timer, so plugin start
|
|
853
|
+
* never spawns a git process in the project directory (a process's cwd holds the directory on
|
|
854
|
+
* Windows: EBUSY for whoever removes it). Returns a cancel function for plugin dispose: it
|
|
855
|
+
* clears a pending timer and aborts the git calls of a GC in flight. Never throws.
|
|
856
|
+
*/
|
|
857
|
+
startReferenceGc(delayMs?: number): () => void;
|
|
858
|
+
/** P0: the snapshot, the changed files and the settled reference, each bounded by `deadline` when given. */
|
|
859
|
+
prepareVerification(
|
|
860
|
+
store: ReturnType<typeof createChangedFileStore>,
|
|
861
|
+
id: string,
|
|
862
|
+
childID: string,
|
|
863
|
+
cwd?: string,
|
|
864
|
+
deadline?: Deadline,
|
|
865
|
+
): Promise<PreparedVerification>;
|
|
72
866
|
/** Session ids currently running a grader prompt, so hooks can skip them. */
|
|
73
867
|
graderSessions: Set<string>;
|
|
74
868
|
/** Abort then delete a plugin-created child session. Never throws. */
|
|
@@ -87,8 +881,56 @@ export interface VerificationWiring {
|
|
|
87
881
|
* grader finishes. A caller enforcing a gate budget aborts THAT set — never
|
|
88
882
|
* the wiring-global one, which belongs to every concurrent delegation at
|
|
89
883
|
* once.
|
|
884
|
+
*
|
|
885
|
+
* `prepared` supplies the testsPass inputs (changed files, reference, current tree); without it
|
|
886
|
+
* the changed files are "unavailable" and the reference is the untracked default. `deadline`
|
|
887
|
+
* bounds every testsPass step (T3); without it each testsPass check owns one of gateBudgetMs.
|
|
888
|
+
*/
|
|
889
|
+
buildGateDeps(parentSessionID?: string, inFlight?: Set<string>, prepared?: PreparedVerification, deadline?: Deadline): GateDeps;
|
|
890
|
+
/**
|
|
891
|
+
* 2.2.3: the idle-TTL sweep's hook into the plugin's one S5 batch coordinator (batch.ts B11):
|
|
892
|
+
* evicts windows with no live member and batches whose seam hung past BATCH_STALE_GRACE_MS.
|
|
893
|
+
* Returns the number evicted. Never throws.
|
|
894
|
+
*/
|
|
895
|
+
sweepVerification(): number;
|
|
896
|
+
/**
|
|
897
|
+
* 2.2.3: plugin dispose. Settles pending batched requests, kills running batches and awaits
|
|
898
|
+
* their scope closes (batch.ts B11). Idempotent; never rejects.
|
|
90
899
|
*/
|
|
91
|
-
|
|
900
|
+
disposeVerification(): Promise<void>;
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/** How a bounded wait ended (awaitBounded). */
|
|
904
|
+
export type BoundedOutcome = { kind: "settled" } | { kind: "timeout" } | { kind: "error"; error: unknown };
|
|
905
|
+
|
|
906
|
+
/**
|
|
907
|
+
* Wait for `promise` for at most `ms`. Never rejects; clears its timer; the timer is unref'd so a
|
|
908
|
+
* pending wait never keeps the process alive. The promise itself keeps running after a timeout.
|
|
909
|
+
*/
|
|
910
|
+
export function awaitBounded(promise: Promise<unknown>, ms: number): Promise<BoundedOutcome> {
|
|
911
|
+
return new Promise<BoundedOutcome>(resolveOutcome => {
|
|
912
|
+
let done = false;
|
|
913
|
+
const finish = (outcome: BoundedOutcome): void => {
|
|
914
|
+
if (done) return;
|
|
915
|
+
done = true;
|
|
916
|
+
clearTimeout(timer);
|
|
917
|
+
resolveOutcome(outcome);
|
|
918
|
+
};
|
|
919
|
+
const timer = setTimeout(() => finish({ kind: "timeout" }), Math.max(0, ms));
|
|
920
|
+
timer.unref?.();
|
|
921
|
+
promise.then(() => finish({ kind: "settled" }), (error: unknown) => finish({ kind: "error", error }));
|
|
922
|
+
});
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
/** Logging for the dispatch-time wait and the start-up GC. `debug` is optional (PluginLogger has none). */
|
|
926
|
+
export type WiringLogger = Pick<PluginLogger, "warn"> & { debug?: (message: string, extra?: Record<string, unknown>) => void };
|
|
927
|
+
|
|
928
|
+
function splitZ(out: string): string[] {
|
|
929
|
+
return out.split("\0").filter(s => s.length > 0);
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
function errorText(err: unknown): string {
|
|
933
|
+
return scrubText(err instanceof Error ? err.message : String(err));
|
|
92
934
|
}
|
|
93
935
|
|
|
94
936
|
export function createVerificationWiring(deps: {
|
|
@@ -96,37 +938,192 @@ export function createVerificationWiring(deps: {
|
|
|
96
938
|
/** Project root; relative paths in checks resolve against it. */
|
|
97
939
|
directory: string;
|
|
98
940
|
getConfig: () => RouterConfig;
|
|
941
|
+
/** Default: console.warn, no debug output. */
|
|
942
|
+
logger?: WiringLogger;
|
|
943
|
+
/** Test seams of the S5 batch coordinator (clock, timers, platform, maximum window size). */
|
|
944
|
+
batch?: Omit<BatchCoordinatorOptions, "logger">;
|
|
945
|
+
/** Test seams of the pending registry (clock, random source). */
|
|
946
|
+
pending?: Pick<PendingRegistryOptions, "now" | "random">;
|
|
947
|
+
/** Test seams of the 2.4.5 background queue; used only when `background` is true. */
|
|
948
|
+
background?: Pick<BackgroundQueueOptions, "now" | "timers" | "settleMs" | "retryBaseMs" | "maxAttempts" | "platform">;
|
|
99
949
|
}): VerificationWiring {
|
|
100
950
|
const { client, directory, getConfig } = deps;
|
|
951
|
+
const logger: WiringLogger = deps.logger ?? { warn: (message, extra) => console.warn(message, extra ?? "") };
|
|
101
952
|
const graderSessions = new Set<string>();
|
|
102
953
|
/** Child sessions already torn down; see disposeChildSession. */
|
|
103
954
|
const disposed = new Set<string>();
|
|
104
955
|
const mutex = createMutexRegistry();
|
|
956
|
+
/**
|
|
957
|
+
* 2.2.3: one S5 batch coordinator per plugin instance (batch.ts D6). Each gate hands it its own
|
|
958
|
+
* runtime, so a config reload reaches the next window without a new coordinator.
|
|
959
|
+
*/
|
|
960
|
+
const coordinator = createBatchCoordinator({ ...deps.batch, logger });
|
|
961
|
+
/**
|
|
962
|
+
* 2.4.1/2.4.2a: one pending registry per plugin instance. Its TTL and abandonment bound are read
|
|
963
|
+
* from the config at plugin start (a reload applies after a restart; the registry holds no timer).
|
|
964
|
+
*/
|
|
965
|
+
let pendingBudget: Pick<VerifyBudget, "pendingTtlMs" | "gateBudgetMs" | "background">;
|
|
966
|
+
try {
|
|
967
|
+
pendingBudget = resolveVerifyBudget(getConfig());
|
|
968
|
+
} catch (err) {
|
|
969
|
+
// Plugin start never fails on config: the section 1.4 defaults (background off).
|
|
970
|
+
logger.debug?.("[verify] pending registry uses default bounds: config unreadable", { error: errorText(err) });
|
|
971
|
+
pendingBudget = { pendingTtlMs: DEFAULT_PENDING_TTL_MS, gateBudgetMs: DEFAULT_GATE_BUDGET_MS, background: false };
|
|
972
|
+
}
|
|
973
|
+
const pending = createPendingRegistry({
|
|
974
|
+
ttlMs: pendingBudget.pendingTtlMs,
|
|
975
|
+
maxVerifyingMs: pendingBudget.gateBudgetMs + VERIFYING_GRACE_MS,
|
|
976
|
+
...deps.pending,
|
|
977
|
+
onEvict: (entry, cause) => logger.debug?.("[verify] pending delegation evicted", { handle: entry.handle, cause }),
|
|
978
|
+
});
|
|
979
|
+
const pendingNow = deps.pending?.now ?? Date.now;
|
|
980
|
+
/**
|
|
981
|
+
* 2.4.5: assigned once verifyHandles exists, and only when `background` is true at plugin start
|
|
982
|
+
* (pending.ts R14). With background off this stays undefined: no queue, no timer, no run.
|
|
983
|
+
*/
|
|
984
|
+
let background: BackgroundQueue | undefined;
|
|
985
|
+
/** QA-2.4-5: foreground testsPass requests in flight (the background queue's `busy`). */
|
|
986
|
+
const foreground = { tests: 0 };
|
|
987
|
+
/** 2.4.2b: native `task` dispatch starts, before hook -> after hook (bounded FIFO, swept). */
|
|
988
|
+
const dispatchStarts = new Map<string, DispatchStart>();
|
|
989
|
+
/**
|
|
990
|
+
* pending.ts R10: the settled value of each dispatch reference promise, recorded when it settles,
|
|
991
|
+
* so a deferred finish can tell "already captured at return" without awaiting (0 ms). Keyed by
|
|
992
|
+
* the promise object (the store returns the same one), so it holds nothing once the store drops it.
|
|
993
|
+
*/
|
|
994
|
+
const settledReferences = new WeakMap<Promise<ReferenceState>, ReferenceState>();
|
|
995
|
+
/**
|
|
996
|
+
* QA-3.1-8: VerifyBudget.lowPriority for the tree snapshots; the section 1.4 default (true) when
|
|
997
|
+
* the config cannot be read, so a snapshot never fails over it.
|
|
998
|
+
*/
|
|
999
|
+
const configuredLowPriority = (): boolean => {
|
|
1000
|
+
try {
|
|
1001
|
+
return resolveVerifyBudget(getConfig()).lowPriority;
|
|
1002
|
+
} catch {
|
|
1003
|
+
return true;
|
|
1004
|
+
}
|
|
1005
|
+
};
|
|
1006
|
+
/** QA-3.1-3: dispatches starting together share their snapshot and capture (createSharedFlight). */
|
|
1007
|
+
const sharedSnapshots = createSharedFlight<TreeSnapshot>();
|
|
1008
|
+
const sharedCaptures = createSharedFlight<DispatchReference>();
|
|
105
1009
|
|
|
106
|
-
const
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
): Promise<ExecResult> =>
|
|
1010
|
+
const abs = (p: string): string => (isAbsolute(p) ? p : join(directory, p));
|
|
1011
|
+
|
|
1012
|
+
// QA-1.2-13: lowPriority and env reach the process; no per-call maxBuffer (QA-1.5-25).
|
|
1013
|
+
const execSeam: ExecSeam = (command: string, opts?: ExecOptions): Promise<ExecResult> =>
|
|
110
1014
|
runShell(command, {
|
|
111
1015
|
cwd: opts?.cwd ?? directory,
|
|
112
|
-
timeoutMs: opts?.timeoutMs ??
|
|
1016
|
+
timeoutMs: opts?.timeoutMs ?? CHECK_TIMEOUT_MS,
|
|
113
1017
|
signal: opts?.signal,
|
|
1018
|
+
lowPriority: opts?.lowPriority,
|
|
1019
|
+
env: opts?.env,
|
|
114
1020
|
});
|
|
115
1021
|
|
|
116
|
-
const
|
|
1022
|
+
const argvSeam: ArgvSeam = (file, args, opts) =>
|
|
1023
|
+
runArgv(file, args, {
|
|
1024
|
+
cwd: opts?.cwd ?? directory,
|
|
1025
|
+
timeoutMs: opts?.timeoutMs ?? CHECK_TIMEOUT_MS,
|
|
1026
|
+
signal: opts?.signal,
|
|
1027
|
+
lowPriority: opts?.lowPriority,
|
|
1028
|
+
env: opts?.env,
|
|
1029
|
+
});
|
|
1030
|
+
|
|
1031
|
+
// T9 1.3: PlannerFs + unlink over fs.promises. realpath is the native one; fileExists accepts
|
|
1032
|
+
// directories (access does).
|
|
1033
|
+
const fsSeam: RunnerFs = {
|
|
117
1034
|
async fileExists(p: string): Promise<boolean> {
|
|
118
1035
|
try {
|
|
119
|
-
await access(
|
|
1036
|
+
await access(abs(p));
|
|
120
1037
|
return true;
|
|
121
1038
|
} catch {
|
|
122
1039
|
return false;
|
|
123
1040
|
}
|
|
124
1041
|
},
|
|
125
1042
|
async readFile(p: string): Promise<string> {
|
|
126
|
-
return await fsReadFile(
|
|
1043
|
+
return await fsReadFile(abs(p), "utf-8");
|
|
1044
|
+
},
|
|
1045
|
+
realpath: p => realpath(abs(p)),
|
|
1046
|
+
async stat(p) {
|
|
1047
|
+
const s = await stat(abs(p), { bigint: true });
|
|
1048
|
+
return { isFile: s.isFile(), size: s.size, dev: s.dev, ino: s.ino };
|
|
1049
|
+
},
|
|
1050
|
+
readdir: p => readdir(abs(p)),
|
|
1051
|
+
async unlink(p) {
|
|
1052
|
+
try {
|
|
1053
|
+
await unlink(abs(p));
|
|
1054
|
+
} catch (err) {
|
|
1055
|
+
// Already gone resolves (RunnerFs contract); anything else is the caller's to report.
|
|
1056
|
+
if (!(err instanceof Error && "code" in err && err.code === "ENOENT")) throw err;
|
|
1057
|
+
}
|
|
127
1058
|
},
|
|
128
1059
|
};
|
|
129
1060
|
|
|
1061
|
+
/**
|
|
1062
|
+
* QA-2.1-12: the files of the commits made since the dispatch snapshot. A shell edit to a file
|
|
1063
|
+
* clean at dispatch, then committed, is invisible to `git status`. Undefined when HEAD did not
|
|
1064
|
+
* move (nothing is spawned) or either snapshot is missing (delta is unavailable then anyway).
|
|
1065
|
+
* "unavailable" when HEAD moved and the diff failed, timed out, or could not run, or when either
|
|
1066
|
+
* head is unknown (e.g. an unborn repository at dispatch).
|
|
1067
|
+
*/
|
|
1068
|
+
const committedSinceDispatch = async (
|
|
1069
|
+
before: TreeSnapshot | undefined,
|
|
1070
|
+
now: TreeSnapshot | undefined,
|
|
1071
|
+
deadline: Deadline | undefined,
|
|
1072
|
+
): Promise<ChangedFile[] | "unavailable" | undefined> => {
|
|
1073
|
+
if (!before || !now || before.head === now.head) return undefined;
|
|
1074
|
+
const root = now.root;
|
|
1075
|
+
if (!root || !OBJECT_NAME.test(before.head) || !OBJECT_NAME.test(now.head)) return "unavailable";
|
|
1076
|
+
const timeoutMs = deadline ? deadline.bound(COMMIT_DIFF_TIMEOUT_MS) : COMMIT_DIFF_TIMEOUT_MS;
|
|
1077
|
+
if (timeoutMs <= 0 || deadline?.signal.aborted) return "unavailable";
|
|
1078
|
+
try {
|
|
1079
|
+
const r = await argvSeam("git", ["--no-optional-locks", "-C", root, "diff", "--name-status", "-z", "-M", before.head, "HEAD"], {
|
|
1080
|
+
cwd: root,
|
|
1081
|
+
timeoutMs,
|
|
1082
|
+
lowPriority: resolveVerifyBudget(getConfig()).lowPriority,
|
|
1083
|
+
...(deadline ? { signal: deadline.signal } : {}),
|
|
1084
|
+
});
|
|
1085
|
+
if (r.timedOut === true || r.code !== 0) return "unavailable";
|
|
1086
|
+
return parseNameStatusZ(r.stdout, root) ?? "unavailable";
|
|
1087
|
+
} catch {
|
|
1088
|
+
return "unavailable"; // The diff could not run: never the same as "no commit touched a file".
|
|
1089
|
+
}
|
|
1090
|
+
};
|
|
1091
|
+
|
|
1092
|
+
/** T9 1.3: the planners' git searches through the argv seam; no shell, no optional locks. */
|
|
1093
|
+
const testSearch = (budget: VerifyBudget, deadline: Deadline | undefined): TestSearchSeam => {
|
|
1094
|
+
const git = async (root: string, args: readonly string[]): Promise<SeamResult | undefined> => {
|
|
1095
|
+
const timeoutMs = deadline ? deadline.bound(TEST_SEARCH_TIMEOUT_MS) : TEST_SEARCH_TIMEOUT_MS;
|
|
1096
|
+
if (timeoutMs <= 0 || deadline?.signal.aborted) return undefined;
|
|
1097
|
+
try {
|
|
1098
|
+
const r = await argvSeam("git", ["--no-optional-locks", "-C", root, ...args], {
|
|
1099
|
+
cwd: root,
|
|
1100
|
+
timeoutMs,
|
|
1101
|
+
lowPriority: budget.lowPriority,
|
|
1102
|
+
...(deadline ? { signal: deadline.signal } : {}),
|
|
1103
|
+
});
|
|
1104
|
+
return r.timedOut === true ? undefined : r;
|
|
1105
|
+
} catch {
|
|
1106
|
+
return undefined; // The search could not run: never the same as "no match".
|
|
1107
|
+
}
|
|
1108
|
+
};
|
|
1109
|
+
return {
|
|
1110
|
+
async findByName(gitRoot, names) {
|
|
1111
|
+
// QA-G-3: a name is literal, so its glob metacharacters are bracketed ([*], [[], [\\]):
|
|
1112
|
+
// git on Windows reads a backslash in a pathspec as a separator, not an escape.
|
|
1113
|
+
const lit = (n: string) => n.replace(/[*?[\]\\]/g, c => (c === "\\" ? "[\\\\]" : `[${c}]`));
|
|
1114
|
+
const r = await git(gitRoot, ["ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", ...names.map(n => `:(glob)**/${lit(n)}`)]);
|
|
1115
|
+
return r && r.code === 0 ? splitZ(r.stdout).map(rel => resolve(gitRoot, rel)) : undefined;
|
|
1116
|
+
},
|
|
1117
|
+
async findByContent(gitRoot, needle, globs, options) {
|
|
1118
|
+
const word = options?.word === true ? ["-w"] : [];
|
|
1119
|
+
const r = await git(gitRoot, ["grep", "-l", "-z", "-F", ...word, "--untracked", "-e", needle, "--", ...globs]);
|
|
1120
|
+
if (!r) return undefined;
|
|
1121
|
+
if (r.code === 1) return [];
|
|
1122
|
+
return r.code === 0 ? splitZ(r.stdout).map(rel => resolve(gitRoot, rel)) : undefined;
|
|
1123
|
+
},
|
|
1124
|
+
};
|
|
1125
|
+
};
|
|
1126
|
+
|
|
130
1127
|
// Best-effort disposal of a plugin-created child session: abort any in-flight
|
|
131
1128
|
// work, then delete it so it does not linger forever as a top-level session in
|
|
132
1129
|
// the TUI. Fail-soft by contract — never throws, so it is safe to call from a
|
|
@@ -219,17 +1216,116 @@ export function createVerificationWiring(deps: {
|
|
|
219
1216
|
}
|
|
220
1217
|
};
|
|
221
1218
|
|
|
1219
|
+
/** What beginDispatch captures for `dod` under the current config (T9 1.1: resolveVerifyBudget). */
|
|
1220
|
+
const captureDepsFor = (dod: DoD): DispatchCaptureDeps => {
|
|
1221
|
+
const cfg = getConfig();
|
|
1222
|
+
const budget = resolveVerifyBudget(cfg);
|
|
1223
|
+
// Only a dispatch that will be judged by testsPass captures a reference (G6: a git-only
|
|
1224
|
+
// capture, never a test run). Read-only fan-outs capture nothing.
|
|
1225
|
+
const judgedByTests = cfg.enforcement?.verify?.require !== "never" && dod.checks.some(
|
|
1226
|
+
c => c.kind === "testsPass" && isCommandAllowed(resolveRepoCommand(c, "testsPass", undefined), DEFAULT_ALLOWLIST),
|
|
1227
|
+
);
|
|
1228
|
+
// QA-3.1-3: one run per key serves every dispatch that asked before it started (same cwd and
|
|
1229
|
+
// the same priority and bound, so the same git processes).
|
|
1230
|
+
const flightKey = (at: string): string => `${budget.lowPriority ? "low" : "normal"}\0${budget.baselineTimeoutMs}\0${at}`;
|
|
1231
|
+
const base = {
|
|
1232
|
+
// QA-3.1-8: the snapshot's git processes run at the configured priority, as the capture's do.
|
|
1233
|
+
snapshot: (at: string, signal: AbortSignal) =>
|
|
1234
|
+
sharedSnapshots(flightKey(at), shared => snapshotTree(at, shared, { lowPriority: budget.lowPriority }), signal),
|
|
1235
|
+
timeoutMs: budget.baselineTimeoutMs,
|
|
1236
|
+
};
|
|
1237
|
+
if (!judgedByTests) return { ...base, uncaptured: { kind: "none", reason: REFERENCE_NONE.notRequested } };
|
|
1238
|
+
if (!budget.failureRecheck) return { ...base, uncaptured: { kind: "disabled" } };
|
|
1239
|
+
// QA-1.2-13: the capture's git processes run at the configured priority too.
|
|
1240
|
+
const argv: ArgvSeam = (file, args, opts) => argvSeam(file, args, { ...opts, lowPriority: budget.lowPriority });
|
|
1241
|
+
return {
|
|
1242
|
+
...base,
|
|
1243
|
+
capture: (at, signal) =>
|
|
1244
|
+
sharedCaptures(flightKey(at), shared => captureReference(at, shared, { argv, fs: nodeReferenceFs, timeoutMs: budget.baselineTimeoutMs }), signal),
|
|
1245
|
+
};
|
|
1246
|
+
};
|
|
1247
|
+
|
|
222
1248
|
const buildGateDeps = (
|
|
223
1249
|
parentSessionID?: string,
|
|
224
1250
|
inFlight?: Set<string>,
|
|
1251
|
+
prepared?: PreparedVerification,
|
|
1252
|
+
deadline?: Deadline,
|
|
1253
|
+
forceLowPriority = false,
|
|
225
1254
|
): GateDeps => {
|
|
226
1255
|
const cfg = getConfig();
|
|
1256
|
+
const resolved = resolveVerifyBudget(cfg);
|
|
1257
|
+
// 2.4.5 (section 1.5-19): background runs are low priority whatever `lowPriority` says.
|
|
1258
|
+
// QA-2.4-5: and they never wait for the slot (waitMs 0): busy means back off and retry later.
|
|
1259
|
+
const budget: VerifyBudget = forceLowPriority ? { ...resolved, lowPriority: true, slotWaitMs: 0 } : resolved;
|
|
1260
|
+
// QA-2.1-5: the recheck's git processes (GC, materialize, dispose) run at the configured
|
|
1261
|
+
// priority too, like the capture and the start-up GC (QA-1.2-13).
|
|
1262
|
+
const referenceArgv: ArgvSeam = (file, args, opts) => argvSeam(file, args, { ...opts, lowPriority: budget.lowPriority });
|
|
1263
|
+
const openScope = createScopeOpener({
|
|
1264
|
+
argv: argvSeam, exec: execSeam, fs: fsSeam, budget, checkTimeoutMs: CHECK_TIMEOUT_MS,
|
|
1265
|
+
reference: { argv: referenceArgv },
|
|
1266
|
+
});
|
|
1267
|
+
const currentTree = prepared?.snapshot !== undefined ? { currentTree: prepared.snapshot } : {};
|
|
1268
|
+
const direct = createDirectTestsPassHook({
|
|
1269
|
+
openScope,
|
|
1270
|
+
plannerFs: fsSeam,
|
|
1271
|
+
search: testSearch(budget, deadline),
|
|
1272
|
+
budget,
|
|
1273
|
+
...currentTree,
|
|
1274
|
+
});
|
|
1275
|
+
// 2.2.3 (S5): with a batch window, concurrent testsPass checks of this plugin instance meet in
|
|
1276
|
+
// the coordinator; the direct hook stays behind it for "full" scope and single requests (B2).
|
|
1277
|
+
// The planner is the direct hook's (planScopedRun over the same PlannerFs and budget), with
|
|
1278
|
+
// its git searches bound to whichever deadline the coordinator plans under (B6).
|
|
1279
|
+
let testsPass: TestsPassHook = direct;
|
|
1280
|
+
const batchWindowMs = effectiveBatchWindowMs(budget);
|
|
1281
|
+
if (batchWindowMs > 0) {
|
|
1282
|
+
const plan: BatchPlanner = (input, planDeadline) => planScopedRun({
|
|
1283
|
+
command: input.command,
|
|
1284
|
+
cwd: input.cwd,
|
|
1285
|
+
changedFiles: input.changedFiles,
|
|
1286
|
+
budget: { maxWorkers: budget.maxWorkers },
|
|
1287
|
+
fs: fsSeam,
|
|
1288
|
+
search: testSearch(budget, planDeadline),
|
|
1289
|
+
});
|
|
1290
|
+
testsPass = coordinator.hook({
|
|
1291
|
+
direct,
|
|
1292
|
+
plan,
|
|
1293
|
+
openScope,
|
|
1294
|
+
batchWindowMs,
|
|
1295
|
+
recheckMinRemainingMs: RECHECK_MIN_REMAINING_MS,
|
|
1296
|
+
failureRecheck: budget.failureRecheck,
|
|
1297
|
+
...currentTree,
|
|
1298
|
+
});
|
|
1299
|
+
}
|
|
1300
|
+
// QA-2.4-5: foreground testsPass (a required gate, router_verify) takes precedence over a
|
|
1301
|
+
// background run: the run in flight is preempted before this request plans or asks for the
|
|
1302
|
+
// slot, and no background run starts while one is active.
|
|
1303
|
+
if (!forceLowPriority) {
|
|
1304
|
+
const inner = testsPass;
|
|
1305
|
+
testsPass = async request => {
|
|
1306
|
+
foreground.tests += 1;
|
|
1307
|
+
try {
|
|
1308
|
+
void background?.preempt();
|
|
1309
|
+
return await inner(request);
|
|
1310
|
+
} finally {
|
|
1311
|
+
foreground.tests -= 1;
|
|
1312
|
+
}
|
|
1313
|
+
};
|
|
1314
|
+
}
|
|
227
1315
|
return {
|
|
228
1316
|
deterministic: {
|
|
229
1317
|
exec: execSeam,
|
|
230
1318
|
fs: fsSeam,
|
|
231
1319
|
cwd: directory,
|
|
232
1320
|
mutex,
|
|
1321
|
+
argv: argvSeam,
|
|
1322
|
+
budget,
|
|
1323
|
+
openScope,
|
|
1324
|
+
testsPass,
|
|
1325
|
+
// Section 1.5-6: without a change baseline, shell edits are unattributed.
|
|
1326
|
+
changedFiles: prepared?.changeBaseline === "available" ? prepared.changedFiles : "unavailable",
|
|
1327
|
+
...(prepared !== undefined ? { reference: prepared.reference } : {}),
|
|
1328
|
+
...(deadline !== undefined ? { deadline } : {}),
|
|
233
1329
|
},
|
|
234
1330
|
checker: {
|
|
235
1331
|
dispatchGrader: (req: GraderRequest) =>
|
|
@@ -242,44 +1338,778 @@ export function createVerificationWiring(deps: {
|
|
|
242
1338
|
};
|
|
243
1339
|
};
|
|
244
1340
|
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
// the
|
|
251
|
-
//
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
1341
|
+
const beginVerification: VerificationWiring["beginVerification"] = async (store, id, cwd, dod) => {
|
|
1342
|
+
let deps: DispatchCaptureDeps;
|
|
1343
|
+
try {
|
|
1344
|
+
deps = captureDepsFor(dod);
|
|
1345
|
+
} catch (err) {
|
|
1346
|
+
// Never blocks or fails the dispatch: snapshot only (at the section 1.4 default low priority,
|
|
1347
|
+
// QA-3.1-8), and no reference.
|
|
1348
|
+
deps = {
|
|
1349
|
+
snapshot: (at, signal) => snapshotTree(at, signal, { lowPriority: true }),
|
|
1350
|
+
timeoutMs: DEFAULT_CAPTURE_TIMEOUT_MS,
|
|
1351
|
+
uncaptured: { kind: "none", reason: `${REFERENCE_NONE.failed} (${errorText(err)})` },
|
|
1352
|
+
};
|
|
1353
|
+
}
|
|
1354
|
+
const begun = store.beginDispatch(id, resolve(directory, cwd || "."), deps);
|
|
1355
|
+
// pending.ts R10: remember the reference's settled value (the store hands out one promise).
|
|
1356
|
+
const reference = store.reference(id);
|
|
1357
|
+
if (!settledReferences.has(reference)) void reference.then(state => settledReferences.set(reference, state));
|
|
1358
|
+
await begun;
|
|
1359
|
+
};
|
|
1360
|
+
|
|
1361
|
+
/**
|
|
1362
|
+
* The producer's change since the dispatch: the gate-time snapshot (bounded by `deadline`), the
|
|
1363
|
+
* commits since the dispatch head, and the store's delta. Shared by prepareVerification and the
|
|
1364
|
+
* deferred finish, so both attribute exactly the same files.
|
|
1365
|
+
*/
|
|
1366
|
+
const observeChange = async (
|
|
1367
|
+
store: ReturnType<typeof createChangedFileStore>,
|
|
1368
|
+
id: string,
|
|
1369
|
+
childID: string,
|
|
1370
|
+
cwd: string | undefined,
|
|
1371
|
+
deadline: Deadline | undefined,
|
|
1372
|
+
): Promise<Omit<PreparedVerification, "reference">> => {
|
|
1373
|
+
const base = resolve(directory, cwd || ".");
|
|
1374
|
+
const controller = new AbortController();
|
|
1375
|
+
const onAbort = (): void => controller.abort();
|
|
1376
|
+
deadline?.signal.addEventListener("abort", onAbort, { once: true });
|
|
1377
|
+
let snapshot: TreeSnapshot | undefined;
|
|
1378
|
+
try {
|
|
1379
|
+
const bound = deadline ? deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS) : GRADE_SNAPSHOT_TIMEOUT_MS;
|
|
1380
|
+
// QA-2.1-2: digest exactly the paths the dispatch snapshot digested (<= MAX_DIGEST_FILES),
|
|
1381
|
+
// so delta can tell which already-dirty file a shell edit changed.
|
|
1382
|
+
const digests = store.baselineSnapshot(id)?.digests;
|
|
1383
|
+
// QA-3.1-8: at the configured priority, like every other verification process.
|
|
1384
|
+
const lowPriority = configuredLowPriority();
|
|
1385
|
+
const options = digests === undefined
|
|
1386
|
+
? { lowPriority }
|
|
1387
|
+
: { lowPriority, digestPaths: digests === "unavailable" ? [] : [...digests.keys()] };
|
|
1388
|
+
snapshot = bound > 0 && !controller.signal.aborted
|
|
1389
|
+
? await withTimeout(snapshotTree(base, controller.signal, options), bound, "grade fingerprint")
|
|
1390
|
+
: undefined;
|
|
1391
|
+
} catch {
|
|
1392
|
+
snapshot = undefined; // Explicit unavailable disclaimer, never a raw tree.
|
|
1393
|
+
} finally {
|
|
1394
|
+
deadline?.signal.removeEventListener("abort", onAbort);
|
|
1395
|
+
controller.abort();
|
|
1396
|
+
}
|
|
1397
|
+
const committed = await committedSinceDispatch(store.baselineSnapshot(id), snapshot, deadline);
|
|
1398
|
+
const contaminatedBy = store.snapshotContaminatedBy(id);
|
|
1399
|
+
return {
|
|
1400
|
+
...store.delta(id, childID, snapshot, base, committed),
|
|
1401
|
+
snapshot,
|
|
1402
|
+
concurrentDispatches: store.concurrentDispatches(id, snapshot?.root),
|
|
1403
|
+
...(contaminatedBy !== undefined ? { contaminatedBy } : {}),
|
|
1404
|
+
};
|
|
1405
|
+
};
|
|
1406
|
+
|
|
1407
|
+
/**
|
|
1408
|
+
* beginVerificationBounded, with the wait counted from `startedAt` (a Date.now() value): the
|
|
1409
|
+
* dispatch waits at most `waitMs` from its start, not `waitMs` after the capture's synchronous
|
|
1410
|
+
* start-up returned. That start-up (config, the snapshot's first git spawn) is the dispatch's
|
|
1411
|
+
* time too, and under load it is not negligible (CI round 1, 3.1.2.f: 20 parallel dispatches on
|
|
1412
|
+
* a 4-core runner held their before hooks up to 104 ms past VERIFY_WAIT). Date.now rather than
|
|
1413
|
+
* performance.now, so fake clocks drive it together with the timer.
|
|
1414
|
+
*/
|
|
1415
|
+
const boundedCaptureWait = async (
|
|
1416
|
+
store: ReturnType<typeof createChangedFileStore>,
|
|
1417
|
+
id: string,
|
|
1418
|
+
cwd: string | undefined,
|
|
1419
|
+
dod: DoD,
|
|
1420
|
+
waitOverrideMs: number | undefined,
|
|
1421
|
+
startedAt: number,
|
|
1422
|
+
): Promise<void> => {
|
|
1423
|
+
let waitMs: number;
|
|
1424
|
+
let begun: Promise<void>;
|
|
1425
|
+
try {
|
|
1426
|
+
waitMs = waitOverrideMs ?? resolveVerifyBudget(getConfig()).captureWaitMs;
|
|
1427
|
+
begun = beginVerification(store, id, cwd, dod);
|
|
1428
|
+
} catch (err) {
|
|
1429
|
+
logger.warn("[verify] dispatch reference capture could not start", { id, error: errorText(err) });
|
|
1430
|
+
return;
|
|
1431
|
+
}
|
|
1432
|
+
// A clock stepped backwards never lengthens the wait past waitMs.
|
|
1433
|
+
const remaining = Math.min(waitMs, Math.max(0, waitMs - (Date.now() - startedAt)));
|
|
1434
|
+
const outcome = await awaitBounded(begun, remaining);
|
|
1435
|
+
if (outcome.kind === "timeout") {
|
|
1436
|
+
logger.debug?.("[verify] dispatch reference not ready; proceeding without waiting further", { id, waitMs });
|
|
1437
|
+
} else if (outcome.kind === "error") {
|
|
1438
|
+
logger.warn("[verify] dispatch reference capture failed; proceeding without a reference", { id, error: errorText(outcome.error) });
|
|
1439
|
+
}
|
|
1440
|
+
};
|
|
1441
|
+
|
|
1442
|
+
const beginVerificationBounded: VerificationWiring["beginVerificationBounded"] = (store, id, cwd, dod, waitOverrideMs) =>
|
|
1443
|
+
boundedCaptureWait(store, id, cwd, dod, waitOverrideMs, Date.now());
|
|
1444
|
+
|
|
1445
|
+
const resolveDirectives = (text: string): VerifyDirectives => {
|
|
1446
|
+
try {
|
|
1447
|
+
const budget = resolveVerifyBudget(getConfig());
|
|
1448
|
+
return parseVerifyDirectives(
|
|
1449
|
+
text,
|
|
1450
|
+
{ defaultVerify: budget.defaultVerify, captureWaitMs: budget.captureWaitMs, baselineTimeoutMs: budget.baselineTimeoutMs },
|
|
1451
|
+
message => logger.warn(message),
|
|
1452
|
+
);
|
|
1453
|
+
} catch (err) {
|
|
1454
|
+
// No config, no deferral: today's synchronous gate. QA-2.4-9: with the section 1.4 default
|
|
1455
|
+
// capture wait (clamped to the default baselineTimeoutMs), as 2.1 waited: a producer started
|
|
1456
|
+
// before its capture resolves contaminates it, and pre-existing failures could no longer be
|
|
1457
|
+
// told apart.
|
|
1458
|
+
logger.warn("[verify] dispatch directives could not be resolved; verifying synchronously", { error: errorText(err) });
|
|
1459
|
+
return { mode: "required", waitMs: FALLBACK_CAPTURE_WAIT_MS, modeSource: "default", waitSource: "default" };
|
|
1460
|
+
}
|
|
1461
|
+
};
|
|
1462
|
+
|
|
1463
|
+
/**
|
|
1464
|
+
* Section 1.5-17 "scoping impossible", decided with no process (runner.ts:11): planStaticScoping
|
|
1465
|
+
* for each testsPass check, with the command and cwd the gate would use. The first S6 result wins;
|
|
1466
|
+
* a command outside the allowlist is S6 too (the gate reports it unverifiable). Bounded by the
|
|
1467
|
+
* deferred-finish deadline; an unfinished plan counts as impossible (raises the risk, never lowers it).
|
|
1468
|
+
*/
|
|
1469
|
+
const staticScoping = async (
|
|
1470
|
+
dod: DoD,
|
|
1471
|
+
cwd: string | undefined,
|
|
1472
|
+
changedFiles: readonly ChangedPath[],
|
|
1473
|
+
deadline: Deadline,
|
|
1474
|
+
): Promise<StaticScoping> => {
|
|
1475
|
+
const unfinished: StaticScoping = { unverifiable: true, code: "search-failed", reason: STATIC_SCOPING_UNFINISHED_REASON };
|
|
1476
|
+
const budget = resolveVerifyBudget(getConfig());
|
|
1477
|
+
const at = resolveBaseDir(cwd, directory);
|
|
1478
|
+
const plans: StaticScoping[] = [];
|
|
1479
|
+
for (const check of dod.checks) {
|
|
1480
|
+
if (check.kind !== "testsPass") continue;
|
|
1481
|
+
const command = resolveRepoCommand(check, "testsPass", undefined);
|
|
1482
|
+
if (!isCommandAllowed(command, DEFAULT_ALLOWLIST)) {
|
|
1483
|
+
plans.push({ unverifiable: true, code: "unsupported-command", reason: `command not allowlisted: ${scrubText(command)}` });
|
|
1484
|
+
continue;
|
|
1485
|
+
}
|
|
1486
|
+
const ms = deadline.remaining();
|
|
1487
|
+
if (ms <= 0) {
|
|
1488
|
+
plans.push(unfinished);
|
|
1489
|
+
continue;
|
|
1490
|
+
}
|
|
1491
|
+
try {
|
|
1492
|
+
plans.push(await withTimeout(
|
|
1493
|
+
planStaticScoping({ command, cwd: at, changedFiles, budget: { maxWorkers: budget.maxWorkers }, fs: fsSeam }),
|
|
1494
|
+
ms,
|
|
1495
|
+
"static scoping",
|
|
1496
|
+
));
|
|
1497
|
+
} catch {
|
|
1498
|
+
plans.push(unfinished);
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
return plans.find(p => "unverifiable" in p) ?? plans[0] ?? unfinished;
|
|
1502
|
+
};
|
|
1503
|
+
|
|
1504
|
+
const finishDeferred: VerificationWiring["finishDeferred"] = async (store, input) => {
|
|
1505
|
+
const producerTier = canonicalTier(input.producerTier);
|
|
1506
|
+
// The live reference promise (no signal: never awaited here). Its settled value at this moment
|
|
1507
|
+
// is the R10 `reference` input; a capture still in flight counts as absent.
|
|
1508
|
+
const reference = store.reference(input.dispatchID);
|
|
1509
|
+
const referenceCaptured = settledReferences.get(reference)?.kind === "captured";
|
|
1510
|
+
const deadline = createDeadline(DEFERRED_FINISH_MS);
|
|
1511
|
+
let risk: RiskAssessment = unattributedRisk();
|
|
1512
|
+
let deferred = false;
|
|
1513
|
+
try {
|
|
1514
|
+
const change = await observeChange(store, input.dispatchID, input.producerSessionID, input.cwd, deadline);
|
|
1515
|
+
// QA-2.4-10: an attributed empty change set is passed by the required gate with no process
|
|
1516
|
+
// (section 1.5-6): nothing to defer. The caller runs that gate, with the same outcome.
|
|
1517
|
+
// QA-G-1: only for a testsPass-only DoD. Any other check (build, lint, run, fileExists,
|
|
1518
|
+
// schemaMatch) or a criterion would be run or graded by that gate synchronously, so such a
|
|
1519
|
+
// DoD stays deferred as a whole, with the attributed empty change set (risk low).
|
|
1520
|
+
if (
|
|
1521
|
+
change.changeBaseline === "available" && change.changedFiles.length === 0 && !deadline.signal.aborted &&
|
|
1522
|
+
noChangeGateSpawnsNothing(input.dod)
|
|
1523
|
+
) {
|
|
1524
|
+
return { deferred: false, reason: "no-change", detail: "the producer changed no file" };
|
|
1525
|
+
}
|
|
1526
|
+
let changedFiles: ChangedPath[] | "unavailable" = "unavailable";
|
|
1527
|
+
let digests: Promise<FileDigests | undefined> | undefined;
|
|
1528
|
+
// Section 1.5-6 / QA-1.6-14: without a change baseline the set is unknown, never [].
|
|
1529
|
+
if (change.changeBaseline === "available" && !deadline.signal.aborted) {
|
|
1530
|
+
const paths: ChangedPath[] = change.changedFiles.map(f => ({
|
|
1531
|
+
path: f.path,
|
|
1532
|
+
status: f.status,
|
|
1533
|
+
...(f.previousPath !== undefined ? { previousPath: f.previousPath } : {}),
|
|
1534
|
+
}));
|
|
1535
|
+
changedFiles = paths;
|
|
1536
|
+
const scopingPlan = await staticScoping(input.dod, input.cwd, paths, deadline);
|
|
1537
|
+
risk = assessRisk({ changedFiles: paths, reference: referenceCaptured, producerTier, scopingPlan, root: change.snapshot?.root });
|
|
1538
|
+
// QA-2.4-8: the drift baseline is taken BEFORE the result is released (fs reads only, under
|
|
1539
|
+
// the same DEFERRED_FINISH_MS bound). An edit that lands right after the return is then
|
|
1540
|
+
// drift, never part of the baseline. Not taken in time: no digests, so drift is
|
|
1541
|
+
// "unchecked" and a later pass is downgraded.
|
|
1542
|
+
const taken = await untilAborted(digestFiles(paths.map(p => p.path)), deadline.signal, () => undefined);
|
|
1543
|
+
if (taken !== undefined) digests = Promise.resolve(taken);
|
|
1544
|
+
}
|
|
1545
|
+
const reg = pending.register({
|
|
1546
|
+
orchestratorSessionID: input.orchestratorSessionID,
|
|
1547
|
+
dispatchID: input.dispatchID,
|
|
1548
|
+
producerSessionID: input.producerSessionID,
|
|
1549
|
+
producerTier,
|
|
1550
|
+
description: input.description,
|
|
1551
|
+
cwd: resolveBaseDir(input.cwd, directory),
|
|
1552
|
+
root: change.snapshot?.root,
|
|
1553
|
+
dispatchedAt: input.dispatchedAt,
|
|
1554
|
+
dod: input.dod,
|
|
1555
|
+
reference,
|
|
1556
|
+
changedFiles,
|
|
1557
|
+
risk,
|
|
1558
|
+
...(digests !== undefined ? { digests } : {}),
|
|
1559
|
+
// QA-3.1-2 / QA-3.1-3: the window ends here (the change set is fixed now); router_verify
|
|
1560
|
+
// adds the caveats to its verdict.
|
|
1561
|
+
...(change.concurrentDispatches !== undefined && change.concurrentDispatches > 0 ? { concurrentDispatches: change.concurrentDispatches } : {}),
|
|
1562
|
+
...(change.contaminatedBy !== undefined ? { contaminatedBy: change.contaminatedBy } : {}),
|
|
1563
|
+
});
|
|
1564
|
+
if (!reg.ok) {
|
|
1565
|
+
// QA-2.4-4: never a delegation without a verdict path: the caller runs the required gate.
|
|
1566
|
+
logger.warn("[verify] deferred delegation not registered; verifying synchronously", { code: reg.code, detail: reg.detail });
|
|
1567
|
+
return { deferred: false, reason: "unregistered", detail: `${reg.code}: ${reg.detail}` };
|
|
1568
|
+
}
|
|
1569
|
+
deferred = true;
|
|
1570
|
+
// 2.4.5 (pending.ts R14): queued, never awaited: the queue's own timer starts the run later.
|
|
1571
|
+
// An unattributed change set is not queued (nothing could run; it stays listed instead).
|
|
1572
|
+
if (background !== undefined && changedFiles !== "unavailable") {
|
|
1573
|
+
try {
|
|
1574
|
+
background.enqueue({ sessionID: input.orchestratorSessionID, handle: reg.handle, files: changedFiles.map(p => p.path) });
|
|
1575
|
+
} catch (err) {
|
|
1576
|
+
// The handle is registered: the delegation stays unverified and listed, as without background.
|
|
1577
|
+
logger.warn("[verify] deferred delegation not queued for background verification", { handle: reg.handle, error: errorText(err) });
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
return { deferred: true, footer: buildDeferredFooter({ handle: reg.handle, risk }), handle: reg.handle, risk };
|
|
1581
|
+
} catch (err) {
|
|
1582
|
+
// QA-2.4-4: as for a refused registration, the required gate runs instead.
|
|
1583
|
+
logger.warn("[verify] deferred finish failed; verifying synchronously", { error: errorText(err) });
|
|
1584
|
+
return { deferred: false, reason: "error", detail: errorText(err) };
|
|
1585
|
+
} finally {
|
|
1586
|
+
deadline.dispose();
|
|
1587
|
+
// A deferred dispatch's record goes once the finish has read it (delta) AND its reference
|
|
1588
|
+
// settled: clearing it earlier aborts an in-flight capture (dispatch.ts evict) and ends its
|
|
1589
|
+
// contamination tracking (section 1.5-14). A dispatch that is not deferred keeps it for the
|
|
1590
|
+
// required gate, which clears it as before.
|
|
1591
|
+
if (deferred) void reference.then(() => store.clear(input.dispatchID));
|
|
1592
|
+
}
|
|
1593
|
+
};
|
|
1594
|
+
|
|
1595
|
+
/**
|
|
1596
|
+
* R11, the downgrade half: proven pre-existing ids that an earlier rejection of the same session
|
|
1597
|
+
* and root introduced turn a non-fail verdict into unverifiable with buildLineageCaveat. It never
|
|
1598
|
+
* creates a pass or a fail. Shared by applyLineage and verifyHandles.
|
|
1599
|
+
*/
|
|
1600
|
+
const lineageDowngrade = (
|
|
1601
|
+
res: GateResult,
|
|
1602
|
+
ctx: Pick<LineageContext, "orchestratorSessionID" | "root" | "dispatchedAt" | "strictUnverifiable">,
|
|
1603
|
+
): GateResult => {
|
|
1604
|
+
const failures = res.verdict.failures;
|
|
1605
|
+
if (failures === undefined || ctx.root === undefined || ctx.orchestratorSessionID === "") return res;
|
|
1606
|
+
const outcome = res.verdict.outcome ?? (res.verdict.pass ? "pass" : "fail");
|
|
1607
|
+
if (outcome === "fail" || failures.preexisting.length === 0) return res;
|
|
1608
|
+
const match = pending.findLineage({
|
|
1609
|
+
orchestratorSessionID: ctx.orchestratorSessionID,
|
|
1610
|
+
root: ctx.root,
|
|
1611
|
+
dispatchedAt: ctx.dispatchedAt,
|
|
1612
|
+
preexisting: failures.preexisting,
|
|
1613
|
+
});
|
|
1614
|
+
if (match === undefined) return res;
|
|
1615
|
+
const caveat = buildLineageCaveat(match);
|
|
1616
|
+
return gateResult(
|
|
1617
|
+
{ ...res.verdict, pass: false, outcome: "unverifiable", caveats: [...(res.verdict.caveats ?? []), caveat] },
|
|
1618
|
+
res.dodSource,
|
|
1619
|
+
ctx.strictUnverifiable ?? false,
|
|
1620
|
+
);
|
|
1621
|
+
};
|
|
1622
|
+
|
|
1623
|
+
const applyLineage: VerificationWiring["applyLineage"] = (res, ctx) => {
|
|
1624
|
+
const failures = res.verdict.failures;
|
|
1625
|
+
if (failures === undefined || ctx.root === undefined || ctx.orchestratorSessionID === "") return res;
|
|
1626
|
+
const outcome = res.verdict.outcome ?? (res.verdict.pass ? "pass" : "fail");
|
|
1627
|
+
if (outcome === "fail") {
|
|
1628
|
+
if (failures.introduced.length > 0) {
|
|
1629
|
+
pending.recordRejection({
|
|
1630
|
+
orchestratorSessionID: ctx.orchestratorSessionID,
|
|
1631
|
+
root: ctx.root,
|
|
1632
|
+
label: `dispatch ${ctx.dispatchID}`,
|
|
1633
|
+
landedAt: ctx.returnedAt,
|
|
1634
|
+
introduced: failures.introduced,
|
|
1635
|
+
});
|
|
1636
|
+
}
|
|
1637
|
+
return res;
|
|
1638
|
+
}
|
|
1639
|
+
return lineageDowngrade(res, ctx);
|
|
1640
|
+
};
|
|
1641
|
+
|
|
1642
|
+
/** 2.4.3a: the current tree for one call, once per cwd (the materialize same-repository guard, P0). */
|
|
1643
|
+
const snapshotFor = async (cwd: string, deadline: Deadline, lowPriority: boolean): Promise<TreeSnapshot | undefined> => {
|
|
1644
|
+
const controller = new AbortController();
|
|
1645
|
+
const onAbort = (): void => controller.abort();
|
|
1646
|
+
deadline.signal.addEventListener("abort", onAbort, { once: true });
|
|
1647
|
+
try {
|
|
1648
|
+
const bound = deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS);
|
|
1649
|
+
if (bound <= 0 || controller.signal.aborted) return undefined;
|
|
1650
|
+
// No digests: the drift check digests the producer's files itself (checkDrift).
|
|
1651
|
+
return await withTimeout(snapshotTree(cwd, controller.signal, { digestPaths: [], lowPriority }), bound, "router_verify fingerprint");
|
|
1652
|
+
} catch {
|
|
1653
|
+
return undefined; // No current tree: materialize skips its same-repository guard, as without a snapshot.
|
|
1654
|
+
} finally {
|
|
1655
|
+
deadline.signal.removeEventListener("abort", onAbort);
|
|
1656
|
+
controller.abort();
|
|
1657
|
+
}
|
|
1658
|
+
};
|
|
1659
|
+
|
|
1660
|
+
/**
|
|
1661
|
+
* 2.4.3a, section 1.5-18: the producer's files now against their digests right after it returned.
|
|
1662
|
+
* "unchecked" whenever either side is missing (no change set, no stored digests, a digest that
|
|
1663
|
+
* could not be taken, or the deadline): never a claim of "no drift" without proof.
|
|
1664
|
+
*/
|
|
1665
|
+
const checkDrift = async (entry: PendingEntry, deadline: Deadline): Promise<DriftCheck> => {
|
|
1666
|
+
if (entry.changedFiles === "unavailable" || entry.digests === undefined) return { kind: "unchecked" };
|
|
1667
|
+
const before = await untilAborted(entry.digests, deadline.signal, () => undefined);
|
|
1668
|
+
if (before === undefined) return { kind: "unchecked" };
|
|
1669
|
+
const after = await untilAborted(digestFiles([...before.keys()]), deadline.signal, () => undefined);
|
|
1670
|
+
if (after === undefined) return { kind: "unchecked" };
|
|
1671
|
+
const paths = driftedPaths(before, after);
|
|
1672
|
+
return paths.length > 0 ? { kind: "drifted", paths } : { kind: "none" };
|
|
1673
|
+
};
|
|
1674
|
+
|
|
1675
|
+
interface ClaimPreparation {
|
|
1676
|
+
readonly prepared: PreparedVerification;
|
|
1677
|
+
readonly drift: DriftCheck;
|
|
1678
|
+
/** R11 root: the registered one, else the current tree's. */
|
|
1679
|
+
readonly root: string | undefined;
|
|
1680
|
+
}
|
|
1681
|
+
|
|
1682
|
+
/** One claimed entry after its gate: a final result, or the raw gate result still to be judged. */
|
|
1683
|
+
type ClaimGate =
|
|
1684
|
+
| { readonly kind: "final"; readonly result: VerificationResult }
|
|
1685
|
+
| { readonly kind: "gate"; readonly res: GateResult; readonly retryable: boolean; readonly strict: boolean };
|
|
1686
|
+
|
|
1687
|
+
/** 2.4.3a P0 from the pending entry: stored change set and reference, current tree, drift. */
|
|
1688
|
+
const prepareClaim = async (
|
|
1689
|
+
entry: PendingEntry,
|
|
1690
|
+
deadline: Deadline,
|
|
1691
|
+
snapshots: Map<string, Promise<TreeSnapshot | undefined>>,
|
|
1692
|
+
lowPriority: boolean,
|
|
1693
|
+
): Promise<ClaimPreparation> => {
|
|
1694
|
+
let snapshot = snapshots.get(entry.cwd);
|
|
1695
|
+
if (snapshot === undefined) {
|
|
1696
|
+
snapshot = snapshotFor(entry.cwd, deadline, lowPriority);
|
|
1697
|
+
snapshots.set(entry.cwd, snapshot);
|
|
1698
|
+
}
|
|
1699
|
+
const [reference, drift, tree] = await Promise.all([
|
|
1700
|
+
// The same bound as the store's reference(id, signal): a capture still pending at the deadline
|
|
1701
|
+
// is "no reference (gate budget)".
|
|
1702
|
+
untilAborted<ReferenceState>(entry.reference, deadline.signal, () => ({ kind: "none", reason: REFERENCE_NONE.gateBudget })),
|
|
1703
|
+
checkDrift(entry, deadline),
|
|
1704
|
+
snapshot,
|
|
1705
|
+
]);
|
|
1706
|
+
const changed = entry.changedFiles;
|
|
1707
|
+
return {
|
|
1708
|
+
prepared: {
|
|
1709
|
+
changedFiles: changed === "unavailable"
|
|
1710
|
+
? []
|
|
1711
|
+
: changed.map(c => ({ path: c.path, status: c.status ?? "", ...(c.previousPath !== undefined ? { previousPath: c.previousPath } : {}) })),
|
|
1712
|
+
// Section 1.5-6: an unattributed change set stays unattributed (never []).
|
|
1713
|
+
changeBaseline: changed === "unavailable" ? "unavailable" : "available",
|
|
1714
|
+
reference,
|
|
1715
|
+
snapshot: tree,
|
|
1716
|
+
},
|
|
1717
|
+
drift,
|
|
1718
|
+
root: entry.root ?? tree?.root,
|
|
1719
|
+
};
|
|
1720
|
+
};
|
|
1721
|
+
|
|
1722
|
+
/**
|
|
1723
|
+
* 2.4.3a: the required gate on one claimed entry (index.ts's sequence: buildGateDeps, accept
|
|
1724
|
+
* under withTimeout(deadline.remaining()), unverifiableGateResult on a reject). A timeout aborts
|
|
1725
|
+
* the shared deadline (every member is out of budget at that instant anyway) and this gate's
|
|
1726
|
+
* graders; any other error leaves the other handles running. Returns either a final result
|
|
1727
|
+
* (nothing was judged) or the raw gate result that judgeVerdict finishes once EVERY gate of the
|
|
1728
|
+
* call has returned (QA-2.4-1).
|
|
1729
|
+
*/
|
|
1730
|
+
const runClaimGate = async (
|
|
1731
|
+
entry: PendingEntry,
|
|
1732
|
+
prep: ClaimPreparation,
|
|
1733
|
+
deadline: OwnedDeadline,
|
|
1734
|
+
cfg: RouterConfig,
|
|
1735
|
+
callSignal: AbortSignal | undefined,
|
|
1736
|
+
lowPriority: boolean,
|
|
1737
|
+
): Promise<ClaimGate> => {
|
|
1738
|
+
const dod = entry.dod;
|
|
1739
|
+
// A claimed entry is never released (release happens on a terminal settle only).
|
|
1740
|
+
if (dod === undefined) return { kind: "final", result: { verdict: unverifiableVerdict(ROUTER_VERIFY_RELEASED_REASON), retryable: false } };
|
|
1741
|
+
const strict = cfg.enforcement?.verify?.strictUnverifiable ?? false;
|
|
1742
|
+
const inFlight = new Set<string>();
|
|
1743
|
+
const completedFailures: string[] = [];
|
|
1744
|
+
const gateDeps = buildGateDeps(entry.orchestratorSessionID, inFlight, prep.prepared, deadline, lowPriority);
|
|
1745
|
+
gateDeps.deterministic.onFailure = reason => completedFailures.push(reason);
|
|
1746
|
+
const artefact = {
|
|
1747
|
+
changedFiles: prep.prepared.changedFiles,
|
|
1748
|
+
changeBaseline: prep.prepared.changeBaseline,
|
|
1749
|
+
// Not stored (R3): a testsPass DoD is deterministic, and no deterministic check reads it.
|
|
1750
|
+
finalReturnText: "",
|
|
1751
|
+
declaredOutputs: dod.deliverable ? [dod.deliverable] : [],
|
|
1752
|
+
producerSessionID: entry.producerSessionID,
|
|
1753
|
+
producerTier: entry.producerTier,
|
|
1754
|
+
};
|
|
1755
|
+
let res: GateResult;
|
|
1756
|
+
let timedOut = false;
|
|
1757
|
+
try {
|
|
1758
|
+
res = await withTimeout(
|
|
1759
|
+
accept({ dod, trivial: false, mode: "modeA", cwd: entry.cwd }, artefact, gateDeps),
|
|
1760
|
+
deadline.remaining(),
|
|
1761
|
+
"verification gate",
|
|
1762
|
+
);
|
|
1763
|
+
} catch (error) {
|
|
1764
|
+
timedOut = error instanceof RouterTimeoutError;
|
|
1765
|
+
if (timedOut) {
|
|
1766
|
+
deadline.abort("verification gate timed out");
|
|
1767
|
+
for (const gsid of inFlight) {
|
|
1768
|
+
try {
|
|
1769
|
+
await client.session.abort({ path: { id: gsid } });
|
|
1770
|
+
} catch (abortError) {
|
|
1771
|
+
logger.debug?.("[verify] router_verify could not abort a grader", { error: errorText(abortError) });
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
res = unverifiableGateResult(
|
|
1776
|
+
timedOut ? `verification gate timed out after ${deadline.budgetMs}ms` : `verification unavailable: ${errorText(error)}`,
|
|
1777
|
+
dod.source,
|
|
1778
|
+
strict,
|
|
1779
|
+
completedFailures,
|
|
1780
|
+
);
|
|
1781
|
+
}
|
|
1782
|
+
// verify.require "never" answers skipped: nothing was judged, so the entry stays unverified.
|
|
1783
|
+
if (res.verdict.skipped === true) return { kind: "final", result: { verdict: res.verdict, retryable: true } };
|
|
1784
|
+
// Decided on the gate's own verdict, before any router caveat (lineage, drift) is added.
|
|
1785
|
+
const retryable = isRetryableVerdict(res.verdict, timedOut || deadline.signal.aborted || callSignal?.aborted === true);
|
|
1786
|
+
return { kind: "gate", res, retryable, strict };
|
|
1787
|
+
};
|
|
1788
|
+
|
|
1789
|
+
/** QA-2.4-1: the proven-introduced ids of a terminal gate fail (what a required gate records). */
|
|
1790
|
+
const introducedOf = (gate: ClaimGate): readonly string[] => {
|
|
1791
|
+
if (gate.kind !== "gate" || gate.retryable) return [];
|
|
1792
|
+
const outcome = gate.res.verdict.outcome ?? (gate.res.verdict.pass ? "pass" : "fail");
|
|
1793
|
+
return outcome === "fail" ? (gate.res.verdict.failures?.introduced ?? []) : [];
|
|
1794
|
+
};
|
|
1795
|
+
|
|
1796
|
+
/**
|
|
1797
|
+
* 2.4.3a: one claimed entry's verdict from its raw gate result: R11 lineage, then the drift rule,
|
|
1798
|
+
* then the next tier. Runs only after every rejection of the call is in the ledger (QA-2.4-1).
|
|
1799
|
+
*/
|
|
1800
|
+
const judgeVerdict = (entry: PendingEntry, prep: ClaimPreparation, gate: ClaimGate, cfg: RouterConfig): VerificationResult => {
|
|
1801
|
+
if (gate.kind === "final") return gate.result;
|
|
1802
|
+
const { strict, retryable } = gate;
|
|
1803
|
+
// QA-3.1-2 / QA-3.1-3: the dispatch's own context, recorded when the producer returned.
|
|
1804
|
+
const res = applyDispatchCaveats(
|
|
1805
|
+
lineageDowngrade(gate.res, { orchestratorSessionID: entry.orchestratorSessionID, root: prep.root, dispatchedAt: entry.dispatchedAt, strictUnverifiable: strict }),
|
|
1806
|
+
entry,
|
|
1807
|
+
);
|
|
1808
|
+
let verdict = res.verdict;
|
|
1809
|
+
if (prep.drift.kind !== "none") {
|
|
1810
|
+
// Section 1.5-18 and the owner's rule: a verdict on a tree that is not (provably) the
|
|
1811
|
+
// producer's never passes; it is unverifiable with the notice. A fail stays a fail.
|
|
1812
|
+
const notice = prep.drift.kind === "drifted" ? DRIFT_NOTICE : DRIFT_UNCHECKED_NOTICE;
|
|
1813
|
+
const outcome = verdict.outcome ?? (verdict.pass ? "pass" : "fail");
|
|
1814
|
+
verdict = gateResult(
|
|
1815
|
+
{
|
|
1816
|
+
...verdict,
|
|
1817
|
+
...(outcome === "pass" ? { pass: false, outcome: "unverifiable" as const } : {}),
|
|
1818
|
+
caveats: [...(verdict.caveats ?? []), notice],
|
|
1819
|
+
},
|
|
1820
|
+
res.dodSource,
|
|
1821
|
+
strict,
|
|
1822
|
+
).verdict;
|
|
1823
|
+
}
|
|
1824
|
+
const judged = gateResult(verdict, res.dodSource, strict);
|
|
1825
|
+
const outcome = judged.verdict.outcome;
|
|
1826
|
+
let nextTier: string | undefined;
|
|
1827
|
+
if (!judged.accepted && outcome === "fail") {
|
|
1828
|
+
// index.ts's rule for the native path: the ladder's next tier after the producer's.
|
|
1829
|
+
const ladder = cfg.enforcement?.escalate?.ladder ?? ["fast", "medium", "heavy"];
|
|
1830
|
+
const li = ladder.findIndex(t => canonicalTier(t) === entry.producerTier);
|
|
1831
|
+
if (li >= 0 && li < ladder.length - 1) nextTier = ladder[li + 1];
|
|
1832
|
+
}
|
|
1833
|
+
const introduced = outcome === "fail" ? judged.verdict.failures?.introduced : undefined;
|
|
1834
|
+
return {
|
|
1835
|
+
verdict: judged.verdict,
|
|
1836
|
+
retryable,
|
|
1837
|
+
...(introduced !== undefined && introduced.length > 0 ? { introduced } : {}),
|
|
1838
|
+
...(prep.drift.kind === "drifted" ? { driftedPaths: prep.drift.paths } : {}),
|
|
1839
|
+
...(nextTier !== undefined ? { nextTier } : {}),
|
|
1840
|
+
};
|
|
1841
|
+
};
|
|
1842
|
+
|
|
1843
|
+
const verifyHandles: VerificationWiring["verifyHandles"] = async (sessionID, target, options = {}) => {
|
|
1844
|
+
let deadline: OwnedDeadline | undefined;
|
|
1845
|
+
const callSignal = options.signal;
|
|
1846
|
+
const onCallAbort = (): void => deadline?.abort(ROUTER_VERIFY_CANCELLED_REASON);
|
|
1847
|
+
try {
|
|
1848
|
+
// 1. Targets: normalized, deduped, capped (R2). `pending` = listOpen, so in-flight runs join.
|
|
1849
|
+
let targets: Array<{ readonly input: string; readonly handle: string | undefined }> = [];
|
|
1850
|
+
if (target.kind === "pending") {
|
|
1851
|
+
// QA-2.4-3: listPending adds the background verdicts not yet replayed (a cached replay, no run).
|
|
1852
|
+
if (sessionID !== "") targets = pending.listPending(sessionID, { verifying: true }).map(e => ({ input: e.handle, handle: e.handle }));
|
|
1853
|
+
if (targets.length === 0) return { items: [], excess: 0, text: ROUTER_VERIFY_NO_PENDING_TEXT };
|
|
1854
|
+
} else {
|
|
1855
|
+
const seen = new Set<string>();
|
|
1856
|
+
for (const raw of target.handles) {
|
|
1857
|
+
const input = typeof raw === "string" ? raw : "(not a string)";
|
|
1858
|
+
const handle = typeof raw === "string" ? normalizeHandle(raw) : undefined;
|
|
1859
|
+
const key = handle ?? `raw:${input}`;
|
|
1860
|
+
if (seen.has(key)) continue;
|
|
1861
|
+
seen.add(key);
|
|
1862
|
+
targets.push({ input, handle });
|
|
1863
|
+
}
|
|
1864
|
+
}
|
|
1865
|
+
const excess = Math.max(0, targets.length - MAX_HANDLES_PER_CALL);
|
|
1866
|
+
targets = targets.slice(0, MAX_HANDLES_PER_CALL);
|
|
1867
|
+
|
|
1868
|
+
// 2. The call's one deadline (section 1.5-13), before any preparation.
|
|
1869
|
+
const cfg = getConfig();
|
|
1870
|
+
const budget = resolveVerifyBudget(cfg);
|
|
1871
|
+
const strict = cfg.enforcement?.verify?.strictUnverifiable ?? false;
|
|
1872
|
+
deadline = createDeadline(budget.gateBudgetMs);
|
|
1873
|
+
const owned = deadline;
|
|
1874
|
+
if (callSignal?.aborted === true) owned.abort(ROUTER_VERIFY_CANCELLED_REASON);
|
|
1875
|
+
else callSignal?.addEventListener("abort", onCallAbort, { once: true });
|
|
1876
|
+
|
|
1877
|
+
// QA-2.4-5: router_verify is foreground work. A background run in flight is preempted, and
|
|
1878
|
+
// its claims settle (retryable) before this call claims, so no handle joins a run that is
|
|
1879
|
+
// being aborted. The wait is bounded by this call's deadline.
|
|
1880
|
+
if (options.background !== true && background !== undefined && targets.length > 0 && sessionID !== "") {
|
|
1881
|
+
await untilAborted(background.preempt(), owned.signal, () => undefined);
|
|
1882
|
+
}
|
|
1883
|
+
|
|
1884
|
+
// 3. Claims (R8: synchronous, so two calls for one handle make one "claimed").
|
|
1885
|
+
type Claimed = Extract<ReturnType<PendingRegistry["markVerifying"]>, { kind: "claimed" }>;
|
|
1886
|
+
const claims: Claimed[] = [];
|
|
1887
|
+
const slots: Array<HandleReport | Promise<HandleReport> | { readonly claim: number }> = [];
|
|
1888
|
+
const cwds = new Map<string, string>();
|
|
1889
|
+
try {
|
|
1890
|
+
for (const t of targets) {
|
|
1891
|
+
if (t.handle === undefined || sessionID === "") {
|
|
1892
|
+
slots.push({ kind: "unknown", input: t.handle ?? t.input });
|
|
1893
|
+
continue;
|
|
1894
|
+
}
|
|
1895
|
+
const c = pending.markVerifying(sessionID, t.handle);
|
|
1896
|
+
if (c.kind === "unknown") slots.push({ kind: "unknown", input: t.handle });
|
|
1897
|
+
else if (c.kind === "expired") slots.push({ kind: "expired", handle: c.handle });
|
|
1898
|
+
else if (c.kind === "settled") {
|
|
1899
|
+
slots.push({ kind: "verdict", handle: c.entry.handle, description: c.entry.description, producerTier: c.entry.producerTier, via: "cached", result: c.result });
|
|
1900
|
+
} else if (c.kind === "joined") {
|
|
1901
|
+
const entry = c.entry;
|
|
1902
|
+
cwds.set(entry.handle, entry.cwd);
|
|
1903
|
+
slots.push(
|
|
1904
|
+
untilAborted<SettledVerification | undefined>(c.run, owned.signal, () => undefined).then((settled): HandleReport =>
|
|
1905
|
+
settled === undefined
|
|
1906
|
+
? { kind: "elsewhere", handle: entry.handle, description: entry.description }
|
|
1907
|
+
: { kind: "verdict", handle: entry.handle, description: entry.description, producerTier: entry.producerTier, via: "joined", result: settled },
|
|
1908
|
+
),
|
|
1909
|
+
);
|
|
1910
|
+
} else {
|
|
1911
|
+
cwds.set(c.entry.handle, c.entry.cwd);
|
|
1912
|
+
slots.push({ claim: claims.length });
|
|
1913
|
+
claims.push(c);
|
|
1914
|
+
}
|
|
1915
|
+
}
|
|
1916
|
+
} catch (error) {
|
|
1917
|
+
// Never leave a claim verifying until the reaper: settle what was claimed, retryable.
|
|
1918
|
+
for (const c of claims) c.settle({ verdict: unverifiableVerdict(`verification unavailable: ${errorText(error)}`), retryable: true });
|
|
1919
|
+
throw error;
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
// 4. Every preparation first, then every gate at once: the testsPass requests share the
|
|
1923
|
+
// deadline and reach the S5 coordinator together (one window, one batch).
|
|
1924
|
+
const snapshots = new Map<string, Promise<TreeSnapshot | undefined>>();
|
|
1925
|
+
// QA-3.1-8: the current-tree snapshot at the configured priority; a background run's always low.
|
|
1926
|
+
const preparations = claims.map(c => prepareClaim(c.entry, owned, snapshots, budget.lowPriority || options.background === true));
|
|
1927
|
+
const allPrepared = Promise.allSettled(preparations);
|
|
1928
|
+
const gates = claims.map(async (c, i): Promise<{ readonly prep: ClaimPreparation | undefined; readonly gate: ClaimGate }> => {
|
|
1929
|
+
let prep: ClaimPreparation | undefined;
|
|
1930
|
+
try {
|
|
1931
|
+
prep = await preparations[i];
|
|
1932
|
+
await allPrepared;
|
|
1933
|
+
return { prep, gate: await runClaimGate(c.entry, prep, owned, cfg, callSignal, options.background === true) };
|
|
1934
|
+
} catch (error) {
|
|
1935
|
+
return { prep, gate: { kind: "final", result: { verdict: unverifiableVerdict(`verification unavailable: ${errorText(error)}`), retryable: true } } };
|
|
1936
|
+
}
|
|
1937
|
+
});
|
|
1938
|
+
// 5. QA-2.4-1: judged in two phases. A verdict of this call must see every rejection of this
|
|
1939
|
+
// call, as it would across two calls or two required gates: (a) every gate returns;
|
|
1940
|
+
// (b) every terminal fail with proven-introduced ids goes into the R11 ledger; (c) lineage,
|
|
1941
|
+
// drift and the next tier are applied to every result; (d) every claim settles.
|
|
1942
|
+
const judged = (async (): Promise<void> => {
|
|
1943
|
+
const results: VerificationResult[] = claims.map(() => ({ verdict: unverifiableVerdict("verification unavailable: no verdict"), retryable: true }));
|
|
1944
|
+
try {
|
|
1945
|
+
const outcomes = await Promise.all(gates);
|
|
1946
|
+
outcomes.forEach(({ prep, gate }, i) => {
|
|
1947
|
+
const introduced = introducedOf(gate);
|
|
1948
|
+
const root = prep?.root;
|
|
1949
|
+
if (introduced.length === 0 || root === undefined) return;
|
|
1950
|
+
const entry = claims[i].entry;
|
|
1951
|
+
pending.recordRejection({ orchestratorSessionID: entry.orchestratorSessionID, root, label: entry.handle, landedAt: entry.createdAt, introduced });
|
|
1952
|
+
});
|
|
1953
|
+
outcomes.forEach(({ prep, gate }, i) => {
|
|
1954
|
+
if (prep !== undefined) results[i] = judgeVerdict(claims[i].entry, prep, gate, cfg);
|
|
1955
|
+
else if (gate.kind === "final") results[i] = gate.result;
|
|
1956
|
+
// QA-2.4-3: a background verdict that did not pass stays listed until it is replayed.
|
|
1957
|
+
if (options.background === true) results[i] = { ...results[i], background: true };
|
|
1958
|
+
});
|
|
1959
|
+
} catch (error) {
|
|
1960
|
+
for (let i = 0; i < results.length; i += 1) {
|
|
1961
|
+
results[i] = { verdict: unverifiableVerdict(`verification unavailable: ${errorText(error)}`), retryable: true };
|
|
1962
|
+
}
|
|
1963
|
+
} finally {
|
|
1964
|
+
// R4: single use, in a finally; false only when the claim was reaped or disposed.
|
|
1965
|
+
claims.forEach((c, i) => {
|
|
1966
|
+
if (!c.settle(results[i])) logger.debug?.("[verify] router_verify settled a claim that was already reaped", { handle: c.entry.handle });
|
|
1967
|
+
});
|
|
1968
|
+
}
|
|
1969
|
+
})();
|
|
1970
|
+
const runs = claims.map(async (c): Promise<HandleReport> => {
|
|
1971
|
+
await judged;
|
|
1972
|
+
const settled = await c.run;
|
|
1973
|
+
return { kind: "verdict", handle: c.entry.handle, description: c.entry.description, producerTier: c.entry.producerTier, via: "run", result: settled };
|
|
262
1974
|
});
|
|
1975
|
+
|
|
1976
|
+
const items = await Promise.all(slots.map(s => ("claim" in s ? runs[s.claim] : s)));
|
|
1977
|
+
// 2.4.5: this caller receives these verdicts, so no late notice repeats them (R14), and a
|
|
1978
|
+
// background verdict among them leaves the pending list (QA-2.4-3). QA-2.4-17: only a
|
|
1979
|
+
// terminal verdict counts; a retryable "not judged" leaves a later background verdict to notice.
|
|
1980
|
+
if (options.background !== true) {
|
|
1981
|
+
const reported = items.flatMap(i => (i.kind === "verdict" && !i.result.retryable ? [i.handle] : []));
|
|
1982
|
+
background?.markReported(reported);
|
|
1983
|
+
pending.markReplayed(sessionID, reported);
|
|
1984
|
+
}
|
|
1985
|
+
return { items, excess, text: formatVerifyReport(items, excess, strict, h => cwds.get(h)) };
|
|
1986
|
+
} catch (error) {
|
|
1987
|
+
logger.warn("[verify] router_verify failed", { error: errorText(error) });
|
|
1988
|
+
return { items: [], excess: 0, text: `[router] router_verify failed; nothing was verified: ${errorText(error)}` };
|
|
1989
|
+
} finally {
|
|
1990
|
+
callSignal?.removeEventListener("abort", onCallAbort);
|
|
1991
|
+
deadline?.dispose();
|
|
1992
|
+
}
|
|
1993
|
+
};
|
|
1994
|
+
|
|
1995
|
+
// 2.4.5 (section 1.5-19, pending.ts R14): only when `background` is true at plugin start. A run is
|
|
1996
|
+
// this instance's own verifyHandles, so it claims, gates, batches and settles exactly as
|
|
1997
|
+
// router_verify does, at low priority.
|
|
1998
|
+
if (pendingBudget.background) {
|
|
1999
|
+
background = createBackgroundQueue({
|
|
2000
|
+
...deps.background,
|
|
2001
|
+
ttlMs: pendingBudget.pendingTtlMs,
|
|
2002
|
+
verify: async (sessionID, handles, signal) =>
|
|
2003
|
+
backgroundOutcomes((await verifyHandles(sessionID, { kind: "handles", handles }, { signal, background: true })).items),
|
|
2004
|
+
onError: error => logger.warn("[verify] background verification run failed", { error: errorText(error) }),
|
|
2005
|
+
// QA-2.4-5: no background run starts while foreground testsPass verification is active.
|
|
2006
|
+
busy: () => foreground.tests > 0,
|
|
2007
|
+
});
|
|
2008
|
+
}
|
|
2009
|
+
|
|
2010
|
+
return {
|
|
2011
|
+
beginVerification,
|
|
2012
|
+
resolveDirectives,
|
|
2013
|
+
async startDispatch(store, id, cwd, dod, text, remember) {
|
|
2014
|
+
// VERIFY_WAIT counts from here, the dispatch's start (see boundedCaptureWait).
|
|
2015
|
+
const startedAt = Date.now();
|
|
2016
|
+
const start: DispatchStart = { directives: resolveDirectives(text), dispatchedAt: pendingNow() };
|
|
2017
|
+
if (remember) {
|
|
2018
|
+
dispatchStarts.delete(id);
|
|
2019
|
+
dispatchStarts.set(id, start);
|
|
2020
|
+
while (dispatchStarts.size > DISPATCH_STARTS_MAX) {
|
|
2021
|
+
const oldest = dispatchStarts.keys().next();
|
|
2022
|
+
if (oldest.done === true) break;
|
|
2023
|
+
dispatchStarts.delete(oldest.value);
|
|
2024
|
+
}
|
|
2025
|
+
}
|
|
2026
|
+
await boundedCaptureWait(store, id, cwd, dod, start.directives.waitMs, startedAt);
|
|
2027
|
+
return start;
|
|
2028
|
+
},
|
|
2029
|
+
takeDispatch(id, text) {
|
|
2030
|
+
const start = dispatchStarts.get(id);
|
|
2031
|
+
if (start !== undefined) {
|
|
2032
|
+
dispatchStarts.delete(id);
|
|
2033
|
+
return start;
|
|
2034
|
+
}
|
|
2035
|
+
return { directives: resolveDirectives(text), dispatchedAt: pendingNow() };
|
|
263
2036
|
},
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
2037
|
+
isDeferred(dod, directives, trivial = false) {
|
|
2038
|
+
if (directives.mode !== "deferred" || !hasTestsPass(dod)) return false;
|
|
2039
|
+
// QA-2.4-10: gate.ts skips exactly this case ("trivial dispatch; verification skipped").
|
|
2040
|
+
if (trivial && dod.source === "inferred") return false;
|
|
267
2041
|
try {
|
|
268
|
-
|
|
2042
|
+
return getConfig().enforcement?.verify?.require !== "never";
|
|
269
2043
|
} catch {
|
|
270
|
-
|
|
271
|
-
}
|
|
272
|
-
|
|
2044
|
+
return false;
|
|
2045
|
+
}
|
|
2046
|
+
},
|
|
2047
|
+
finishDeferred,
|
|
2048
|
+
applyLineage,
|
|
2049
|
+
verifyHandles,
|
|
2050
|
+
pending,
|
|
2051
|
+
background,
|
|
2052
|
+
beginVerificationBounded,
|
|
2053
|
+
startReferenceGc(delayMs = REFERENCE_GC_START_DELAY_MS) {
|
|
2054
|
+
if (!directory) {
|
|
2055
|
+
logger.debug?.("[verify] reference GC skipped: plugin root unknown");
|
|
2056
|
+
return () => undefined;
|
|
273
2057
|
}
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
2058
|
+
const stop = new AbortController();
|
|
2059
|
+
const run = (): void => {
|
|
2060
|
+
if (stop.signal.aborted) return;
|
|
2061
|
+
try {
|
|
2062
|
+
const budget = resolveVerifyBudget(getConfig());
|
|
2063
|
+
// Low priority (QA-1.2-13), and every git call dies with the plugin (dispose).
|
|
2064
|
+
const argv: ArgvSeam = (file, args, opts) => argvSeam(file, args, {
|
|
2065
|
+
...opts,
|
|
2066
|
+
lowPriority: budget.lowPriority,
|
|
2067
|
+
signal: opts?.signal ? AbortSignal.any([opts.signal, stop.signal]) : stop.signal,
|
|
2068
|
+
});
|
|
2069
|
+
gcStaleReferences(directory, { argv, fs: nodeReferenceFs, logger }).then(
|
|
2070
|
+
report => {
|
|
2071
|
+
if (report.removed.length > 0) logger.debug?.("[verify] reference GC removed stale dirs", { removed: report.removed.length });
|
|
2072
|
+
},
|
|
2073
|
+
(err: unknown) => logger.warn("[verify] reference GC failed", { error: errorText(err) }),
|
|
2074
|
+
);
|
|
2075
|
+
} catch (err) {
|
|
2076
|
+
logger.warn("[verify] reference GC failed", { error: errorText(err) });
|
|
2077
|
+
}
|
|
278
2078
|
};
|
|
2079
|
+
const timer = setTimeout(run, Math.max(0, delayMs));
|
|
2080
|
+
timer.unref?.();
|
|
2081
|
+
return () => {
|
|
2082
|
+
clearTimeout(timer);
|
|
2083
|
+
stop.abort();
|
|
2084
|
+
};
|
|
2085
|
+
},
|
|
2086
|
+
async prepareVerification(store, id, childID, cwd, deadline) {
|
|
2087
|
+
const change = await observeChange(store, id, childID, cwd, deadline);
|
|
2088
|
+
const reference = await store.reference(id, deadline?.signal);
|
|
2089
|
+
return { ...change, reference };
|
|
279
2090
|
},
|
|
280
2091
|
graderSessions,
|
|
281
2092
|
disposeChildSession,
|
|
282
2093
|
dispatchGrader,
|
|
283
2094
|
buildGateDeps,
|
|
2095
|
+
sweepVerification: () => {
|
|
2096
|
+
// Native task starts whose after hook never came (the call was cancelled), past the idle TTL.
|
|
2097
|
+
const at = pendingNow();
|
|
2098
|
+
let evicted = 0;
|
|
2099
|
+
for (const [id, start] of [...dispatchStarts]) {
|
|
2100
|
+
if (at - start.dispatchedAt >= DEFAULT_IDLE_TTL_MS) {
|
|
2101
|
+
dispatchStarts.delete(id);
|
|
2102
|
+
evicted += 1;
|
|
2103
|
+
}
|
|
2104
|
+
}
|
|
2105
|
+
// 2.4.5: undelivered late notices past pendingTtlMs; also the queue's idle trigger.
|
|
2106
|
+
return evicted + coordinator.sweep() + (background?.sweep() ?? 0);
|
|
2107
|
+
},
|
|
2108
|
+
disposeVerification: () => {
|
|
2109
|
+
dispatchStarts.clear();
|
|
2110
|
+
// 2.4.5: abort the background run first, so nothing re-queues while the coordinator stops.
|
|
2111
|
+
background?.dispose();
|
|
2112
|
+
return coordinator.dispose();
|
|
2113
|
+
},
|
|
284
2114
|
};
|
|
285
2115
|
}
|