opencode-model-router 1.14.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +173 -0
- package/README.md +80 -28
- package/package.json +8 -3
- package/server.ts +3 -0
- package/src/compat/child-session.ts +27 -0
- package/src/compat/v2-client.ts +183 -0
- package/src/compat/v2-hooks.ts +376 -0
- package/src/index.ts +427 -85
- package/src/router/config.ts +225 -15
- package/src/router/protocol.ts +12 -2
- package/src/v2.ts +24 -0
- package/src/verify/baseline.ts +143 -25
- package/src/verify/batch.ts +2226 -0
- package/src/verify/checker.ts +1 -1
- package/src/verify/deterministic.ts +1378 -20
- package/src/verify/directives.ts +207 -0
- package/src/verify/dispatch.ts +387 -90
- package/src/verify/dod.ts +8 -1
- package/src/verify/exec.ts +654 -35
- package/src/verify/gate.ts +16 -1
- package/src/verify/paths.ts +9 -1
- 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 +1959 -52
- package/tiers.json +21 -19
|
@@ -0,0 +1,1834 @@
|
|
|
1
|
+
// src/verify/pending.ts
|
|
2
|
+
// ===============================================================================================
|
|
3
|
+
// PENDING VERIFICATION REGISTRY: design (plan Phase 2.4, task 2.4.1; S7, sections 1.5-16..20)
|
|
4
|
+
//
|
|
5
|
+
// STATUS: implemented (task 2.4.1b, R12); tests in test/unit/pending.test.ts. The header below is
|
|
6
|
+
// the contract. Contract types used here come from the 2.1.1 block of
|
|
7
|
+
// src/verify/types.ts (ReferenceState, Verdict) and are never redefined.
|
|
8
|
+
// ===============================================================================================
|
|
9
|
+
//
|
|
10
|
+
// R1. PURPOSE AND NON-GOALS
|
|
11
|
+
//
|
|
12
|
+
// A per-plugin-instance, in-memory registry of DEFERRED delegations (VERIFY:deferred, the
|
|
13
|
+
// default): what a later `router_verify` call (2.4.3), the pending list (2.4.4) and background
|
|
14
|
+
// mode (2.4.5) need to verify one delegation after its producer has returned.
|
|
15
|
+
// - Pure in-memory state with an injected clock and an injected random source. It never spawns
|
|
16
|
+
// a process, never runs git, never touches the filesystem and owns no timer. (The R14
|
|
17
|
+
// background queue in this file owns one timer; it exists only when `background: true`.)
|
|
18
|
+
// - It does not run verifications. It records who may verify what, hands the in-flight run to
|
|
19
|
+
// concurrent callers, and stores the settled result.
|
|
20
|
+
// - It does not parse directives, compute changed files, assess risk or build the scoped run.
|
|
21
|
+
// 2.4.2 does that before `register`, and 2.4.3 runs the 2.1/2.2 pipeline after `markVerifying`.
|
|
22
|
+
// - Required (VERIFY:required) delegations are NOT registered: they are gated synchronously by
|
|
23
|
+
// 2.1 and never produce a handle. A deferred delegation is never labelled accepted or verified
|
|
24
|
+
// by anything in this module (R9).
|
|
25
|
+
//
|
|
26
|
+
// R2. HANDLES
|
|
27
|
+
//
|
|
28
|
+
// - Format: `vrf_` + 24 lowercase hex chars = 12 bytes (96 bits) from `random(12)`, default
|
|
29
|
+
// `crypto.randomBytes`. HANDLE_PATTERN = /^vrf_[0-9a-f]{24}$/. Unguessable, but a handle is NOT
|
|
30
|
+
// a bearer token: every lookup is scoped by the calling session (R6). 96 bits keeps the footer
|
|
31
|
+
// short while making a collision or a guess irrelevant in practice.
|
|
32
|
+
// - Collision: a candidate equal to a live handle or a tombstone is redrawn, at most
|
|
33
|
+
// HANDLE_MAX_DRAWS times; then `register` returns { ok: false, code: "handle-collision" }
|
|
34
|
+
// (never throws: a registration failure must never fail the delegation; the dispatch runs the
|
|
35
|
+
// required gate instead, QA-2.4-4).
|
|
36
|
+
// - Input normalization (`normalizeHandle`, for router_verify arguments): trim, strip ONE pair of
|
|
37
|
+
// surrounding backticks or quotes, lowercase, then HANDLE_PATTERN. Anything else is undefined
|
|
38
|
+
// and reported as UNKNOWN_HANDLE_TEXT. router_verify dedupes normalized handles and accepts at
|
|
39
|
+
// most MAX_HANDLES_PER_CALL (= MAX_ENTRIES_PER_SESSION); the excess is reported, not run.
|
|
40
|
+
//
|
|
41
|
+
// R3. ENTRY
|
|
42
|
+
//
|
|
43
|
+
// Registration (PendingRegistration) is built by 2.4.2 when a deferred producer returns:
|
|
44
|
+
// orchestratorSessionID the session that called `task` / `delegate` (the hook's
|
|
45
|
+
// input.sessionID / the tool context's sessionID). NEVER the producer.
|
|
46
|
+
// dispatchID the dispatch key 2.1's store uses (opaque).
|
|
47
|
+
// producerSessionID the child session; must differ from orchestratorSessionID.
|
|
48
|
+
// producerTier canonical lowercase tier id (1.6 handoff item 8); used for
|
|
49
|
+
// buildForcingNote's next tier on a rejection. "" when untiered.
|
|
50
|
+
// description the orchestrator's `description` arg (or a prompt prefix);
|
|
51
|
+
// stored through sanitizeDescription (R9).
|
|
52
|
+
// cwd absolute check cwd of the delegation.
|
|
53
|
+
// root git top-level realpath (TreeSnapshot.root, 2.1.3a; 1.6 item 7), or
|
|
54
|
+
// undefined when unknown. Used only for lineage (R11).
|
|
55
|
+
// dispatchedAt clock value when the dispatch started (lineage, R11).
|
|
56
|
+
// dod the delegation's DoD (it carries testsPass; else nothing is deferred).
|
|
57
|
+
// reference Promise<ReferenceState> from 2.1's per-dispatch capture. The registry
|
|
58
|
+
// stores `reference.then(s => s, () => ({ kind: "none", reason:
|
|
59
|
+
// REFERENCE_FAILED_REASON }))`, so the stored promise never rejects and
|
|
60
|
+
// an abandoned capture never raises an unhandled rejection.
|
|
61
|
+
// changedFiles ChangedPath[] with status/previousPath, or "unavailable" when
|
|
62
|
+
// attribution failed (never [] for a failure: QA-1.6-14). More than
|
|
63
|
+
// MAX_STORED_CHANGED_FILES paths are stored as "unavailable" with
|
|
64
|
+
// changedFilesDropped = the count: a later verification is then
|
|
65
|
+
// unverifiable (section 1.5-6), never scoped over a truncated set.
|
|
66
|
+
// risk RiskAssessment computed by 2.4.2 (R10) BEFORE registration.
|
|
67
|
+
// digests optional Promise<FileDigests | undefined>: per-path content digests of
|
|
68
|
+
// the producer's files taken right after return (2.4.2, fs reads only,
|
|
69
|
+
// not awaited on the result path). Stored normalized to never reject.
|
|
70
|
+
// router_verify compares them with driftedPaths() for the section
|
|
71
|
+
// 1.5-18 drift notice; undefined -> no drift claim either way.
|
|
72
|
+
// Added by the registry: handle, createdAt = now() at registration (= the producer's return:
|
|
73
|
+
// the TTL and "newest first" run from it), state, verifyingSince, result.
|
|
74
|
+
// Snapshots: `get`/`list*` return frozen snapshot objects (PendingEntry); later transitions do
|
|
75
|
+
// not mutate a snapshot a caller holds.
|
|
76
|
+
// Release on a terminal settle (state "verified"): reference, changedFiles, digests and dod are
|
|
77
|
+
// dropped from the record (reference -> resolved { kind: "none", reason: RELEASED_REASON },
|
|
78
|
+
// changedFiles -> "unavailable"). Only metadata and the settled result stay until the TTL.
|
|
79
|
+
//
|
|
80
|
+
// R4. STATES AND TRANSITIONS
|
|
81
|
+
//
|
|
82
|
+
// from event to effect
|
|
83
|
+
// ------------ ----------------------------------------- ------------ ---------------------
|
|
84
|
+
// (none) register unverified handle issued
|
|
85
|
+
// unverified markVerifying verifying "claimed": new run
|
|
86
|
+
// verifying markVerifying (second caller) verifying "joined": same run
|
|
87
|
+
// verifying claim.settle(result, retryable: false) verified run resolves; release
|
|
88
|
+
// verifying claim.settle(result, retryable: true) unverified run resolves; kept for
|
|
89
|
+
// a later call; result
|
|
90
|
+
// stored as lastResult
|
|
91
|
+
// verifying reaped: verifyingSince + maxVerifyingMs unverified run resolves with
|
|
92
|
+
// <= now (lazy, R7) ABANDONED result
|
|
93
|
+
// verified markVerifying verified "settled": cached result,
|
|
94
|
+
// no new run (no CPU)
|
|
95
|
+
// any but TTL (now - createdAt >= ttlMs), (tombstone) onEvict(entry, cause)
|
|
96
|
+
// verifying forgetSession, dispose; a cap evicts
|
|
97
|
+
// verified entries only (R7, QA-2.4-4)
|
|
98
|
+
//
|
|
99
|
+
// - `retryable` is decided by the caller (2.4.3): true for results that say nothing about the
|
|
100
|
+
// producer's work — slot busy, deadline/abort, timed out, executor error, a joiner cut by its
|
|
101
|
+
// own deadline never settles anything. Everything else (pass, fail, S6 unverifiable,
|
|
102
|
+
// approximate/unusable reference, no reference) is terminal.
|
|
103
|
+
// - A verifying entry is never evicted (joiners await it). After its settle, an entry past its
|
|
104
|
+
// TTL or doomed by forgetSession is evicted at once.
|
|
105
|
+
// - claim.settle is single-use: it returns true once; false afterwards, and false when the
|
|
106
|
+
// claim was reaped (a stale claimer can never overwrite a newer run). The run promise never
|
|
107
|
+
// rejects. 2.4.3 MUST call settle in a `finally` (with a retryable result on an exception);
|
|
108
|
+
// the reaper is only the backstop.
|
|
109
|
+
//
|
|
110
|
+
// R5. OPERATIONS (PendingRegistry)
|
|
111
|
+
//
|
|
112
|
+
// register(reg) -> RegisterResult. Validates (non-empty session ids that differ,
|
|
113
|
+
// else "invalid-input"), applies caps (R7) BEFORE inserting.
|
|
114
|
+
// get(sessionID, handle) -> Lookup: found | expired | unknown (R6). Reaps and TTL-evicts
|
|
115
|
+
// lazily first, so an expired entry is never "found" even when
|
|
116
|
+
// the throttled sweep has not run.
|
|
117
|
+
// listUnverified(sid, limit?) -> state "unverified" only, newest first (createdAt desc, then
|
|
118
|
+
// registration order desc). limit undefined = all (<= cap).
|
|
119
|
+
// Feeds buildPendingListBlock (2.4.4).
|
|
120
|
+
// listOpen(sid) -> "unverified" + "verifying", newest first: the handle set of
|
|
121
|
+
// router_verify `pending: true`, so a second concurrent
|
|
122
|
+
// `pending: true` joins the in-flight runs instead of seeing
|
|
123
|
+
// an empty list.
|
|
124
|
+
// markVerifying(sid, handle) -> ClaimResult: claimed { run, settle } | joined { run } |
|
|
125
|
+
// settled { result } | expired | unknown.
|
|
126
|
+
// sweep(nowMs?) -> TTL eviction + reaping. Wired as `() => pending.sweep()` into
|
|
127
|
+
// the existing createIdleTtlSweeper list in index.ts (2.4.2);
|
|
128
|
+
// no timer of its own. Returns the number evicted.
|
|
129
|
+
// forgetSession(sid) -> evicts the session's entries, tombstones and rejection records
|
|
130
|
+
// (verifying ones are doomed and evicted at settle). For a
|
|
131
|
+
// session-deletion event, if the host delivers one (pre-flight).
|
|
132
|
+
// recordRejection(record) -> lineage ledger (R11).
|
|
133
|
+
// findLineage(query) -> LineageMatch | undefined (R11).
|
|
134
|
+
// stats() -> counts, for tests and the QA memory-bound assertions.
|
|
135
|
+
// dispose() -> evicts everything (cause "disposed"); every in-flight run
|
|
136
|
+
// resolves with the DISPOSED result; later settles return false.
|
|
137
|
+
//
|
|
138
|
+
// R6. SCOPING (plan 2.4.1 "Scoping"; QA focus "handle leakage across sessions")
|
|
139
|
+
//
|
|
140
|
+
// - Storage is keyed by session first: Map<orchestratorSessionID, Map<handle, record>>. A lookup
|
|
141
|
+
// for (sessionID, handle) consults only that session's map, so another session's live handle,
|
|
142
|
+
// a producer session's attempt, a malformed string and a never-issued handle are the same
|
|
143
|
+
// result: { kind: "unknown" } -> UNKNOWN_HANDLE_TEXT. Nothing distinguishes "exists elsewhere".
|
|
144
|
+
// - Tombstones (evicted handles) remember their session: the same session gets "expired"
|
|
145
|
+
// (EXPIRED_HANDLE_TEXT); any other session gets "unknown". Bounded FIFO, TOMBSTONE_MAX.
|
|
146
|
+
// - A producer (subagent) calling router_verify runs under its own session id, which owns none
|
|
147
|
+
// of the handles its orchestrator received; the footer reaches only the orchestrator. So a
|
|
148
|
+
// subagent can neither verify nor list its own delegation (plan "Subagent cannot self-select").
|
|
149
|
+
//
|
|
150
|
+
// R7. TTL, ABANDONMENT, EVICTION, MEMORY BOUNDS
|
|
151
|
+
//
|
|
152
|
+
// - TTL: ttlMs = pendingTtlMs (section 1.4, default 3600000), from createdAt. Checked lazily on
|
|
153
|
+
// every get/list/markVerifying/register and by sweep(). Future stamps (clock skew) are never
|
|
154
|
+
// expired (same rule as sessions.ts sweep).
|
|
155
|
+
// - Abandonment: maxVerifyingMs = gateBudgetMs + VERIFYING_GRACE_MS (caller passes it). A
|
|
156
|
+
// verifying entry older than that is reverted to unverified and its run resolved with the
|
|
157
|
+
// ABANDONED result (retryable). Checked lazily like the TTL. No timer.
|
|
158
|
+
// - Caps: MAX_ENTRIES_PER_SESSION = 32, MAX_ENTRIES_GLOBAL = 128, and a global weight
|
|
159
|
+
// MAX_GLOBAL_WEIGHT = 100000, weight = stored changed paths + (once the reference resolves
|
|
160
|
+
// "captured") reference.untracked.size + reference.tracked.size. The weight of a reference is
|
|
161
|
+
// added in its settle callback (a promise callback, not a timer). A reference that would exceed
|
|
162
|
+
// the weight cap is shed instead: the entry keeps its place and its reference becomes
|
|
163
|
+
// { kind: "none", reason: REFERENCE_SHED_REASON } (QA-2.4-4; stricter later, never a false pass).
|
|
164
|
+
// - Eviction order when a cap would be exceeded (session cap: within the session; global caps:
|
|
165
|
+
// across sessions): (1) every TTL-expired entry, (2) verified entries, oldest first. Unverified
|
|
166
|
+
// and verifying entries are NEVER evicted by a cap (QA-2.4-4): an evicted unverified delegation
|
|
167
|
+
// would leave the pending list silently and read as verified. If the new entry still does not
|
|
168
|
+
// fit, register returns { ok: false, code: "registry-full" }. Every refusal (registry-full,
|
|
169
|
+
// handle-collision, invalid-input) makes the dispatch run the required gate instead (2.4.2
|
|
170
|
+
// finishDeferred): no delegation is ever left without a verdict path, and there is no footer
|
|
171
|
+
// without a handle.
|
|
172
|
+
// - Worst case: 128 entries, 100000 path strings of the registry's own weight (about 20 MB at
|
|
173
|
+
// 200 B per path), 512 tombstones, 16 x sessions rejection records of <= 50 ids each.
|
|
174
|
+
// - Resources: a stored reference is data only (DispatchReference: commit ids and hash maps). The
|
|
175
|
+
// `git stash create` commit is unreferenced and left to git's own pruning, as in 1.5; worktrees
|
|
176
|
+
// exist only inside a VerificationScope and are disposed by its close() (2.1 T2 P9), never by
|
|
177
|
+
// the registry. So eviction disposes nothing: it drops the record, tombstones the handle and
|
|
178
|
+
// calls onEvict(entry, cause) for logging. An in-flight capture keeps running under 2.1's
|
|
179
|
+
// baselineTimeoutMs; the registry only drops its promise.
|
|
180
|
+
//
|
|
181
|
+
// R8. CONCURRENCY
|
|
182
|
+
//
|
|
183
|
+
// Single-threaded JS: every operation is synchronous and atomic with respect to the others.
|
|
184
|
+
// The only asynchronous edges are the stored promises' settle callbacks (weight accounting) and
|
|
185
|
+
// the run promises the registry resolves. markVerifying is the join point of section 1.5-18:
|
|
186
|
+
// two router_verify calls for one handle -> exactly one "claimed", the rest "joined" (one run).
|
|
187
|
+
// A joiner bounds its own wait by its own deadline (2.4.3); if its deadline passes first it
|
|
188
|
+
// reports VERIFYING_ELSEWHERE_TEXT for that handle and settles nothing.
|
|
189
|
+
//
|
|
190
|
+
// R9. TEXT (stable; 2.4.6 tests assert it verbatim). All builders are pure.
|
|
191
|
+
//
|
|
192
|
+
// Directive safety: no builder ever emits a literal `VERIFY:` / `VERIFY_WAIT:` / `CAP:`
|
|
193
|
+
// directive. An orchestrator that quotes a footer or the pending list in a later dispatch must
|
|
194
|
+
// not change that dispatch's mode (directives.ts router-example contract, QA-1.6-4/QA-1.6-5).
|
|
195
|
+
// Label rule: the first token after `[router] ` of the footer's first line is always
|
|
196
|
+
// `unverified`. Risk reasons may contain "verified" as prose (REASONS.unverifiable); tests assert
|
|
197
|
+
// on the label, never on a bare substring.
|
|
198
|
+
//
|
|
199
|
+
// buildDeferredFooter({ handle, risk }) (section 1.5-16), handle registered:
|
|
200
|
+
// [router] unverified · <handle> · risk <level> (<r1>; <r2>; <r3>; +<k> more)
|
|
201
|
+
// [router] Call `router_verify` with this handle before building on this work if the risk matters.
|
|
202
|
+
// There is no footer without a handle (QA-2.4-4): a registration the registry refuses is not
|
|
203
|
+
// deferred, and the dispatch runs the required gate.
|
|
204
|
+
// The risk fragment is formatRisk(level, reasons, FOOTER_MAX_REASONS): `risk <level>`, then
|
|
205
|
+
// ` (<reasons>)` with at most maxReasons reasons, each through sanitizeDescription's character
|
|
206
|
+
// rules (no length cut), "; "-joined, `; +<k> more` only when k > 0. The parenthesis is omitted
|
|
207
|
+
// when there are no reasons or maxReasons is 0 (the pending list uses 0). `·` is U+00B7 with
|
|
208
|
+
// one space on each side.
|
|
209
|
+
// appendRouterFooter(output, footer): output.trimEnd() + "\n\n" + footer, or footer alone when
|
|
210
|
+
// the trimmed output is empty. The same call is used for the native `task` output
|
|
211
|
+
// (tool.execute.after) and the `delegate` tool return (2.4.2).
|
|
212
|
+
//
|
|
213
|
+
// buildPendingListBlock(entries) (section 1.5-20; entries = listUnverified(sid) or, in index.ts,
|
|
214
|
+
// listPending(sid), newest first):
|
|
215
|
+
// undefined when entries is empty (the prompt does not grow for sessions that never defer);
|
|
216
|
+
// otherwise, with n = entries.length and m = min(n, PENDING_LIST_LIMIT = 5):
|
|
217
|
+
// [router] Unverified delegations in this session (newest first):
|
|
218
|
+
// - <handle> · risk <level> · <description> (m lines)
|
|
219
|
+
// - ... and <n - m> more (only when n > m)
|
|
220
|
+
// [router] Before your final answer, call `router_verify` with the handles that matter, or with `pending: true` for all of them.
|
|
221
|
+
// QA-2.4-3: a verified entry (a background verdict that did not pass, not yet replayed) reads
|
|
222
|
+
// `- <handle> · <fail|unverifiable> in background verification · risk <level> · <description>`,
|
|
223
|
+
// and the header is then PENDING_LIST_MIXED_HEADER. router_verify (a handle or `pending:
|
|
224
|
+
// true`) replays it with no run, and it leaves the list (markReplayed).
|
|
225
|
+
//
|
|
226
|
+
// buildLateNoticeBlock(notices) (section 1.5-19, background mode only; R14 owns the queue):
|
|
227
|
+
// undefined when empty; otherwise
|
|
228
|
+
// [router] Background verification found introduced failures: (every notice a fail)
|
|
229
|
+
// [router] Background verification did not pass these delegations: (otherwise)
|
|
230
|
+
// - <handle> · <description> · failing: <id>, <id> (+<k> more) (a fail with ids, capped at 10)
|
|
231
|
+
// - <handle> · <description> · failed: <reason> (a fail that names no id)
|
|
232
|
+
// - <handle> · <description> · unverifiable: <reason> (terminal unverifiable)
|
|
233
|
+
// [router] Nothing was retried; decide whether to re-dispatch.
|
|
234
|
+
// [router] Call `router_verify` with a handle for its full verdict; nothing is run again.
|
|
235
|
+
// <reason> goes through sanitizeDescription (80 code points, directive-safe).
|
|
236
|
+
//
|
|
237
|
+
// sanitizeDescription(text): every C0/C1 control, U+2028/U+2029 and tab -> space; backtick ->
|
|
238
|
+
// `'`; runs of whitespace -> one space; trim; longer than MAX_DESCRIPTION_CHARS -> the first
|
|
239
|
+
// MAX_DESCRIPTION_CHARS - 1 code points + `…`; empty -> "(no description)". Code-point safe
|
|
240
|
+
// (never splits a surrogate pair). Keeps each list item on one line.
|
|
241
|
+
//
|
|
242
|
+
// Phrases for router_verify results (2.4.3): UNKNOWN_HANDLE_TEXT, EXPIRED_HANDLE_TEXT,
|
|
243
|
+
// VERIFYING_ELSEWHERE_TEXT, and the reasons ABANDONED_REASON / DISPOSED_REASON of the synthetic
|
|
244
|
+
// retryable results (Verdict { pass: false, outcome: "unverifiable", method: "deterministic",
|
|
245
|
+
// reasons: [<reason>], caveats: [<reason>] }).
|
|
246
|
+
//
|
|
247
|
+
// R10. RISK INPUTS (2.4.2 computes the risk; handoffs from docs/qa/.../phase-1.6.md)
|
|
248
|
+
//
|
|
249
|
+
// assessRisk({ changedFiles, reference, producerTier, scopingPlan, root }) with:
|
|
250
|
+
// - changedFiles: the tree-snapshot ChangedPath[] with status and previousPath (2.1.3a). When
|
|
251
|
+
// attribution failed, do NOT call assessRisk with []: use unattributedRisk() = { level:
|
|
252
|
+
// "high", reasons: [UNATTRIBUTED_RISK_REASON] } and register changedFiles "unavailable".
|
|
253
|
+
// - reference: true only when the reference promise has ALREADY settled as "captured" at return
|
|
254
|
+
// time (2.4.2 tracks the settled value; it never awaits: 0 ms result latency). A capture still
|
|
255
|
+
// in flight counts as absent: the risk is raised one step, conservatively. The stored promise
|
|
256
|
+
// is still the one router_verify awaits later.
|
|
257
|
+
// - producerTier: canonical lowercase id (only exact "fast" triggers row 11).
|
|
258
|
+
// - scopingPlan: planStaticScoping (1.3, no spawn) for the stored changed files.
|
|
259
|
+
// - root: git top-level realpath (TreeSnapshot.root), never the delegation cwd.
|
|
260
|
+
// The risk is fixed at registration; it is advice (section 1.5-17) and is not recomputed.
|
|
261
|
+
//
|
|
262
|
+
// R11. T11 LINEAGE (a native `task` re-dispatch after a rejection)
|
|
263
|
+
//
|
|
264
|
+
// Problem (2.1 deterministic.ts T11): after a rejection, a native `task` re-dispatch captures a
|
|
265
|
+
// new reference that already contains the failed attempt's changes. A test the first attempt
|
|
266
|
+
// broke then fails at the new reference too, is classified pre-existing, and passes with the
|
|
267
|
+
// "no worse than before" note.
|
|
268
|
+
// Decision: pending.ts keeps a small per-orchestrator-session ledger of proven-introduced ids,
|
|
269
|
+
// and 2.4 downgrades such a pass to UNVERIFIABLE with a caveat naming the earlier delegation.
|
|
270
|
+
// It does NOT link the re-dispatch to the original reference, because the router cannot tell a
|
|
271
|
+
// retry from a new delegation in the native path (no retry marker, and section 1.5-15 closes
|
|
272
|
+
// the directive set): with the old reference a third party's break between the two dispatches
|
|
273
|
+
// would be blamed on the retry (section 1.2, second guarantee), and a failure fixed and broken
|
|
274
|
+
// again in between would be excused (a false pass). The downgrade instead only removes passes
|
|
275
|
+
// for ids that are both pre-existing at the new reference and proven introduced earlier in the
|
|
276
|
+
// same session: it can never create a pass and never creates a fail, which is exactly section
|
|
277
|
+
// 1.2's third guarantee ("cannot tell them apart" -> unverifiable).
|
|
278
|
+
// - recordRejection({ orchestratorSessionID, root, label, landedAt, introduced }) — called by
|
|
279
|
+
// claim.settle automatically for a terminal result with introduced ids and a known root
|
|
280
|
+
// (label = handle, landedAt = entry.createdAt), and by 2.4.2 for a rejected REQUIRED gate in
|
|
281
|
+
// the native path (label "dispatch <dispatchID>", landedAt = the producer's return).
|
|
282
|
+
// introduced is capped at MAX_LEDGER_IDS; MAX_LEDGER_PER_SESSION records per session, oldest
|
|
283
|
+
// dropped; records expire with ttlMs. One record per (label, root): a second one replaces the
|
|
284
|
+
// first (router_verify records a call's rejections before it settles them, QA-2.4-1).
|
|
285
|
+
// - findLineage({ orchestratorSessionID, root, dispatchedAt, preexisting }) -> the newest record
|
|
286
|
+
// of the same session and root with landedAt <= dispatchedAt whose introduced ids intersect
|
|
287
|
+
// `preexisting`: { label, ids } (ids in `preexisting` order). A record never matches its own
|
|
288
|
+
// delegation (its landedAt is after its dispatchedAt).
|
|
289
|
+
// - buildLineageCaveat(match): "<ids> failed after <label> in this session and still fail; that
|
|
290
|
+
// change may still be present in the reference of this delegation, so pre-existing cannot be
|
|
291
|
+
// told apart from not fixed". <ids> as in 2.1 T7 (at most 10, then " (+<k> more)"). "May":
|
|
292
|
+
// the ledger matches by id and root only, and the change may have been reverted (QA-2.4-13).
|
|
293
|
+
// - Precondition (2.4 pre-flight): the merged 2.1 must expose TestsPassJudgement.failures on the
|
|
294
|
+
// gate result that 2.4 code sees. If it does not, 2.4 does not edit 2.1-owned internals: it
|
|
295
|
+
// deletes recordRejection/findLineage/buildLineageCaveat from this file (no dead code) and the
|
|
296
|
+
// 2.4 QA report keeps T11 as a residual.
|
|
297
|
+
//
|
|
298
|
+
// R12. IMPLEMENTATION TASKS (each <= ~20 tool calls; commit + push each green; scoped tests only)
|
|
299
|
+
//
|
|
300
|
+
// 2.4.1b (now, parallel with 2.1.2+ and 2.2) Implement this file per R2-R11 and add
|
|
301
|
+
// test/unit/pending.test.ts: handle format + collision redraw (fake random), R6 scoping
|
|
302
|
+
// matrix (other session / producer session / malformed / never issued -> unknown; own
|
|
303
|
+
// tombstone -> expired), R4 transition table row by row, join (N markVerifying -> one
|
|
304
|
+
// claimed), single-use settle, reaping, TTL at read without sweep, caps and eviction
|
|
305
|
+
// order (verifying never evicted, registry-full), weight added on reference resolution,
|
|
306
|
+
// release on terminal settle, rejected reference promise normalized, forgetSession,
|
|
307
|
+
// dispose resolves joiners, every R9 text verbatim (empty list -> undefined, cap 5,
|
|
308
|
+
// "+k more", no directive tokens, label rule), lineage matrix (other session, other
|
|
309
|
+
// root, landedAt after dispatchedAt, no intersection -> undefined). typecheck.
|
|
310
|
+
// 2.4.2a (after 2.1 + 2.2.3 merge) wiring.ts: parse directives from the orchestrator prompt
|
|
311
|
+
// only; VERIFY_WAIT replaces captureWaitMs in the bounded capture wait; a deferred-finish
|
|
312
|
+
// helper (snapshot -> changedFiles | "unavailable", planStaticScoping, risk per R10,
|
|
313
|
+
// digests, register, footer). Tests in deferred-verification.test.ts (zero spawns).
|
|
314
|
+
// 2.4.2b index.ts native `task` path: mode routing in tool.execute.before/after; required ->
|
|
315
|
+
// 2.1 gate unchanged; deferred -> footer appended; recordRejection on required
|
|
316
|
+
// rejections (R11); sweep wired into createIdleTtlSweeper.
|
|
317
|
+
// 2.4.2c index.ts `delegate` path: same routing, footer on the tool return, no ladder for
|
|
318
|
+
// deferred.
|
|
319
|
+
// 2.4.3a wiring.ts: verifyHandles(sessionID, handles | "pending", deps): normalize, claim/join,
|
|
320
|
+
// one Deadline, one batch through the 2.2 coordinator, drift via driftedPaths, verdict
|
|
321
|
+
// per handle with forcing note + next tier on rejection, lineage caveat, settle in
|
|
322
|
+
// finally; no retry ever dispatched.
|
|
323
|
+
// 2.4.3b index.ts: register `router_verify` next to `delegate` whenever verification is
|
|
324
|
+
// enabled (independent of enableDelegateTool). Tests: router-verify-tool.test.ts.
|
|
325
|
+
// 2.4.4 index.ts system transform: buildPendingListBlock(listUnverified(sid)) appended only
|
|
326
|
+
// when defined. Tests: cap 5, newest first, leaves on verify/TTL, per-session.
|
|
327
|
+
// 2.4.5 (done, R14) background (only when background: true): the queue factory in this file,
|
|
328
|
+
// coalescing, same coordinator/slot/caps, late notices via buildLateNoticeBlock once per
|
|
329
|
+
// handle; the queue is never constructed when false (assert). Tests: the plan's set.
|
|
330
|
+
// 2.4.6 remaining plan tests (latency under fake timers, capture after the wait, subagent
|
|
331
|
+
// cannot self-select, 50 deferred delegations spawn nothing).
|
|
332
|
+
//
|
|
333
|
+
// R13. RESIDUAL RISKS (accepted; QA may challenge)
|
|
334
|
+
//
|
|
335
|
+
// - A producer can end its final text with a fake `[router] …` line. The real footer is always
|
|
336
|
+
// appended last; the 2.3 protocol text says only the last `[router]` footer counts.
|
|
337
|
+
// - Drift digests are taken just after the producer returns (not atomically with it), but before
|
|
338
|
+
// the deferred result is released (QA-2.4-8): only an edit that lands during the deferred
|
|
339
|
+
// finish itself (at most DEFERRED_FINISH_MS) is attributed to the producer.
|
|
340
|
+
// - The registry lives in one plugin instance: a restarted opencode process loses its handles
|
|
341
|
+
// (router_verify then says "unknown handle"); nothing persists across processes by design.
|
|
342
|
+
// - Lineage (R11) is id-based: a renamed test id escapes it (the pass keeps 2.1's n2 note).
|
|
343
|
+
//
|
|
344
|
+
// R14. BACKGROUND QUEUE (task 2.4.5; section 1.5-19; `background: true` only)
|
|
345
|
+
//
|
|
346
|
+
// - Construction: the wiring calls createBackgroundQueue only when `background` is true at plugin
|
|
347
|
+
// start. When it is false (the default) no queue, timer, notice store or run exists, and no
|
|
348
|
+
// code path reaches one (the wiring holds `undefined`).
|
|
349
|
+
// - Input: the wiring's deferred finish enqueues every registered entry whose change set is
|
|
350
|
+
// attributed ({ sessionID, handle, files }). An "unavailable" set is not queued: nothing could
|
|
351
|
+
// be run for it, and settling it would only move it out of the pending list.
|
|
352
|
+
// - Coalescing: a newer request of the same orchestrator session whose files overlap a QUEUED
|
|
353
|
+
// older one drops the older request (its producer's files changed again, so its verdict would
|
|
354
|
+
// be a drift notice at best). The older entry stays unverified and listed; it is never
|
|
355
|
+
// reported as verified. Requests of other sessions are never dropped by it.
|
|
356
|
+
// - Scheduling: one unref'd timer, armed at the earliest due request and never moved later (no
|
|
357
|
+
// debounce: a steady stream cannot starve the queue). A fresh request is due BACKGROUND_SETTLE_MS
|
|
358
|
+
// after it arrives, so delegations returning together share one run. One run per plugin
|
|
359
|
+
// instance at a time. A run takes the oldest due request, then every fresh or due request of
|
|
360
|
+
// the same session (at most MAX_HANDLES_PER_CALL): one verify call, i.e. one router_verify
|
|
361
|
+
// deadline and one S5 window.
|
|
362
|
+
// - The run is `verify` = the wiring's verifyHandles (the required gate's path, slot, caps, batch
|
|
363
|
+
// coordinator, low priority), so it claims and settles entries exactly as router_verify does:
|
|
364
|
+
// a later router_verify replays the stored verdict and runs nothing.
|
|
365
|
+
// - Outcomes: a terminal pass -> nothing; a terminal fail or unverifiable -> one late notice for
|
|
366
|
+
// the orchestrator session (lateNoticeFor); a retryable result -> requeued with backoff
|
|
367
|
+
// retryBaseMs * 2^(attempt-1), at most BACKGROUND_MAX_ATTEMPTS runs, then it just stays
|
|
368
|
+
// unverified (never a hot loop); "reported" (a router_verify call claimed or had settled it)
|
|
369
|
+
// and "gone" (unknown/expired) -> dropped. A handle missing from the outcomes, or a rejected
|
|
370
|
+
// verify, counts as retryable.
|
|
371
|
+
// - Notices: per session, one per handle, returned once by takeNotices (the system transform) and
|
|
372
|
+
// remembered as delivered. A consumed notice never makes its entry disappear (QA-2.4-3): the
|
|
373
|
+
// run settles with `background: true`, and a verdict that did not pass stays in listPending
|
|
374
|
+
// (the pending list) until router_verify replays it (markReplayed) or the TTL expires. markReported(handles) (router_verify's verdict items) drops and
|
|
375
|
+
// suppresses a notice the orchestrator already saw. Bounded: LATE_NOTICES_PER_SESSION,
|
|
376
|
+
// LATE_NOTICES_MAX, REPORTED_MEMO_MAX; sweep drops notices older than ttlMs.
|
|
377
|
+
// - Cancellation: forgetSession (session.deleted) drops the session's requests and notices and
|
|
378
|
+
// aborts its run in flight (the deadline, so the batch's tree is killed); dispose aborts the run,
|
|
379
|
+
// clears the timer and drops everything. A cancelled run's results are ignored.
|
|
380
|
+
// ===============================================================================================
|
|
381
|
+
|
|
382
|
+
import { randomBytes } from "node:crypto";
|
|
383
|
+
|
|
384
|
+
import type { DoD } from "./dod";
|
|
385
|
+
import type { RiskAssessment, RiskLevel } from "./risk";
|
|
386
|
+
import type { ChangedPath } from "./runner";
|
|
387
|
+
import type { ReferenceState, Verdict } from "./types";
|
|
388
|
+
|
|
389
|
+
// ---------------------------------------------------------------------------------------------
|
|
390
|
+
// Constants (R2, R7, R9)
|
|
391
|
+
// ---------------------------------------------------------------------------------------------
|
|
392
|
+
|
|
393
|
+
export const HANDLE_PREFIX = "vrf_";
|
|
394
|
+
/** 12 random bytes -> 24 lowercase hex chars (R2). */
|
|
395
|
+
export const HANDLE_RANDOM_BYTES = 12;
|
|
396
|
+
export const HANDLE_PATTERN = /^vrf_[0-9a-f]{24}$/;
|
|
397
|
+
export const HANDLE_MAX_DRAWS = 4;
|
|
398
|
+
|
|
399
|
+
export const MAX_ENTRIES_PER_SESSION = 32;
|
|
400
|
+
export const MAX_ENTRIES_GLOBAL = 128;
|
|
401
|
+
/** Global weight in path strings: stored changed paths + captured reference untracked/tracked sizes (R7). */
|
|
402
|
+
export const MAX_GLOBAL_WEIGHT = 100_000;
|
|
403
|
+
/** Above this, changedFiles is stored as "unavailable" (never truncated, R3). */
|
|
404
|
+
export const MAX_STORED_CHANGED_FILES = 500;
|
|
405
|
+
export const TOMBSTONE_MAX = 512;
|
|
406
|
+
export const MAX_HANDLES_PER_CALL = MAX_ENTRIES_PER_SESSION;
|
|
407
|
+
/** Added to gateBudgetMs by the caller to form maxVerifyingMs (R7). */
|
|
408
|
+
export const VERIFYING_GRACE_MS = 30_000;
|
|
409
|
+
|
|
410
|
+
export const MAX_LEDGER_PER_SESSION = 16;
|
|
411
|
+
export const MAX_LEDGER_IDS = 50;
|
|
412
|
+
|
|
413
|
+
export const MAX_DESCRIPTION_CHARS = 80;
|
|
414
|
+
export const PENDING_LIST_LIMIT = 5;
|
|
415
|
+
export const FOOTER_MAX_REASONS = 3;
|
|
416
|
+
export const LATE_NOTICE_MAX_IDS = 10;
|
|
417
|
+
|
|
418
|
+
export const UNKNOWN_HANDLE_TEXT = "unknown handle";
|
|
419
|
+
export const EXPIRED_HANDLE_TEXT = "expired handle: older than pendingTtlMs or evicted; it can no longer be verified";
|
|
420
|
+
export const VERIFYING_ELSEWHERE_TEXT =
|
|
421
|
+
"still being verified by another router_verify call; call again for its verdict";
|
|
422
|
+
export const REFERENCE_FAILED_REASON = "reference capture failed";
|
|
423
|
+
export const RELEASED_REASON = "reference released after verification";
|
|
424
|
+
export const ABANDONED_REASON = "verification run abandoned before it settled";
|
|
425
|
+
export const DISPOSED_REASON = "verification registry disposed";
|
|
426
|
+
export const UNATTRIBUTED_RISK_REASON = "changed files could not be attributed";
|
|
427
|
+
/** R7, QA-2.4-4: a captured reference dropped at the weight cap (the entry itself is kept). */
|
|
428
|
+
export const REFERENCE_SHED_REASON = "reference dropped at the pending registry's memory bound";
|
|
429
|
+
/** R14: the late-notice header when a notice is not a plain failure (an unverifiable result). */
|
|
430
|
+
export const LATE_NOTICE_MIXED_HEADER = "[router] Background verification did not pass these delegations:";
|
|
431
|
+
/**
|
|
432
|
+
* QA-2.4-3: the pending-list header when it also holds background verdicts that did not pass and
|
|
433
|
+
* were not replayed yet (each such line says `<outcome> in background verification`).
|
|
434
|
+
*/
|
|
435
|
+
export const PENDING_LIST_MIXED_HEADER = "[router] Unverified delegations, and background verdicts not yet read, in this session (newest first):";
|
|
436
|
+
/** R14: a settled handle replays its cached verdict (forcing note, next tier) with no new run. */
|
|
437
|
+
export const LATE_NOTICE_REPLAY_LINE = "[router] Call `router_verify` with a handle for its full verdict; nothing is run again.";
|
|
438
|
+
|
|
439
|
+
/** R14: a fresh background request waits this long, so delegations returning together share a run. */
|
|
440
|
+
export const BACKGROUND_SETTLE_MS = 1_000;
|
|
441
|
+
/** R14: the first retry of a retryable background result; each later retry doubles it. */
|
|
442
|
+
export const BACKGROUND_RETRY_BASE_MS = 30_000;
|
|
443
|
+
/** R14: background runs per request, retries included; then the entry just stays unverified. */
|
|
444
|
+
export const BACKGROUND_MAX_ATTEMPTS = 3;
|
|
445
|
+
/** R14: queued background requests; the oldest is dropped beyond it (it stays unverified). */
|
|
446
|
+
export const BACKGROUND_QUEUE_MAX = MAX_ENTRIES_GLOBAL;
|
|
447
|
+
/** R14: undelivered late notices per orchestrator session, and in total. */
|
|
448
|
+
export const LATE_NOTICES_PER_SESSION = MAX_ENTRIES_PER_SESSION;
|
|
449
|
+
export const LATE_NOTICES_MAX = MAX_ENTRIES_GLOBAL;
|
|
450
|
+
/** R14: handles whose verdict reached the orchestrator (delivered, or through router_verify). */
|
|
451
|
+
export const REPORTED_MEMO_MAX = TOMBSTONE_MAX;
|
|
452
|
+
|
|
453
|
+
// ---------------------------------------------------------------------------------------------
|
|
454
|
+
// Types
|
|
455
|
+
// ---------------------------------------------------------------------------------------------
|
|
456
|
+
|
|
457
|
+
export type PendingState = "unverified" | "verifying" | "verified";
|
|
458
|
+
|
|
459
|
+
/** Absolute path -> sha256 hex of the file bytes, or ABSENT_DIGEST for a missing path (R3). */
|
|
460
|
+
export type FileDigests = ReadonlyMap<string, string>;
|
|
461
|
+
export const ABSENT_DIGEST = "absent";
|
|
462
|
+
|
|
463
|
+
/** What 2.4.2 hands to `register` when a deferred producer returns (R3). */
|
|
464
|
+
export interface PendingRegistration {
|
|
465
|
+
readonly orchestratorSessionID: string;
|
|
466
|
+
readonly dispatchID: string;
|
|
467
|
+
readonly producerSessionID: string;
|
|
468
|
+
/** Canonical lowercase tier id; "" when the producer is untiered. */
|
|
469
|
+
readonly producerTier: string;
|
|
470
|
+
/** Raw; the registry stores sanitizeDescription(description). */
|
|
471
|
+
readonly description: string;
|
|
472
|
+
readonly cwd: string;
|
|
473
|
+
/** Git top-level realpath (TreeSnapshot.root), or undefined when unknown. */
|
|
474
|
+
readonly root: string | undefined;
|
|
475
|
+
/** Clock value when the dispatch started. */
|
|
476
|
+
readonly dispatchedAt: number;
|
|
477
|
+
readonly dod: DoD;
|
|
478
|
+
readonly reference: Promise<ReferenceState>;
|
|
479
|
+
/** "unavailable" when attribution failed; never [] for a failure (QA-1.6-14). */
|
|
480
|
+
readonly changedFiles: readonly ChangedPath[] | "unavailable";
|
|
481
|
+
readonly risk: RiskAssessment;
|
|
482
|
+
readonly digests?: Promise<FileDigests | undefined>;
|
|
483
|
+
/** QA-3.1-2: other dispatches live in the same git tree during this one's window; absent: none. */
|
|
484
|
+
readonly concurrentDispatches?: number;
|
|
485
|
+
/** QA-3.1-3: the tool whose call discarded the dispatch snapshot (the change set is then unavailable). */
|
|
486
|
+
readonly contaminatedBy?: string;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** What a verification of one handle produced (2.4.3 builds it from the gate result). */
|
|
490
|
+
export interface VerificationResult {
|
|
491
|
+
readonly verdict: Verdict;
|
|
492
|
+
/** true -> the entry returns to "unverified" (R4); false -> "verified" (terminal). */
|
|
493
|
+
readonly retryable: boolean;
|
|
494
|
+
/** Proven-introduced test ids (TestsPassJudgement.failures.introduced); feeds R11. */
|
|
495
|
+
readonly introduced?: readonly string[];
|
|
496
|
+
/** Producer paths modified after it returned (driftedPaths); drives the drift notice. */
|
|
497
|
+
readonly driftedPaths?: readonly string[];
|
|
498
|
+
/** buildForcingNote's suggested next tier on a rejection. */
|
|
499
|
+
readonly nextTier?: string;
|
|
500
|
+
/**
|
|
501
|
+
* R14, QA-2.4-3: settled by a background run. A terminal verdict that did not pass then keeps its
|
|
502
|
+
* entry in the pending list (listPending) until router_verify replays it to the session
|
|
503
|
+
* (markReplayed) or the TTL expires: a consumed late notice never makes it disappear.
|
|
504
|
+
*/
|
|
505
|
+
readonly background?: boolean;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
export interface SettledVerification extends VerificationResult {
|
|
509
|
+
readonly handle: string;
|
|
510
|
+
readonly settledAt: number;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/** A frozen snapshot of one entry (R3). */
|
|
514
|
+
export interface PendingEntry {
|
|
515
|
+
readonly handle: string;
|
|
516
|
+
readonly orchestratorSessionID: string;
|
|
517
|
+
readonly dispatchID: string;
|
|
518
|
+
readonly producerSessionID: string;
|
|
519
|
+
readonly producerTier: string;
|
|
520
|
+
readonly description: string;
|
|
521
|
+
readonly cwd: string;
|
|
522
|
+
readonly root: string | undefined;
|
|
523
|
+
readonly dispatchedAt: number;
|
|
524
|
+
/** undefined once released by a terminal settle. */
|
|
525
|
+
readonly dod: DoD | undefined;
|
|
526
|
+
/** Never rejects. Resolves { kind: "none", reason: RELEASED_REASON } once released. */
|
|
527
|
+
readonly reference: Promise<ReferenceState>;
|
|
528
|
+
readonly changedFiles: readonly ChangedPath[] | "unavailable";
|
|
529
|
+
/** Paths dropped because the set exceeded MAX_STORED_CHANGED_FILES; 0 otherwise. */
|
|
530
|
+
readonly changedFilesDropped: number;
|
|
531
|
+
readonly risk: RiskAssessment;
|
|
532
|
+
/** Never rejects; undefined when not provided or released. */
|
|
533
|
+
readonly digests: Promise<FileDigests | undefined> | undefined;
|
|
534
|
+
/** PendingRegistration.concurrentDispatches, as registered. */
|
|
535
|
+
readonly concurrentDispatches?: number;
|
|
536
|
+
/** PendingRegistration.contaminatedBy, as registered. */
|
|
537
|
+
readonly contaminatedBy?: string;
|
|
538
|
+
readonly createdAt: number;
|
|
539
|
+
readonly state: PendingState;
|
|
540
|
+
/** Set while state is "verifying". */
|
|
541
|
+
readonly verifyingSince: number | undefined;
|
|
542
|
+
/** The last settled result: terminal when "verified", retryable when back to "unverified". */
|
|
543
|
+
readonly result: SettledVerification | undefined;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
export type RegisterResult =
|
|
547
|
+
| { readonly ok: true; readonly handle: string; readonly evicted: readonly string[] }
|
|
548
|
+
| {
|
|
549
|
+
readonly ok: false;
|
|
550
|
+
readonly code: "invalid-input" | "registry-full" | "handle-collision";
|
|
551
|
+
readonly detail: string;
|
|
552
|
+
};
|
|
553
|
+
|
|
554
|
+
export type Lookup =
|
|
555
|
+
| { readonly kind: "found"; readonly entry: PendingEntry }
|
|
556
|
+
/** Evicted (TTL, cap, forgetSession) and issued to THIS session. */
|
|
557
|
+
| { readonly kind: "expired"; readonly handle: string }
|
|
558
|
+
/** Malformed, never issued, or issued to another session (R6). */
|
|
559
|
+
| { readonly kind: "unknown"; readonly handle: string };
|
|
560
|
+
|
|
561
|
+
export type ClaimResult =
|
|
562
|
+
| {
|
|
563
|
+
readonly kind: "claimed";
|
|
564
|
+
readonly entry: PendingEntry;
|
|
565
|
+
/** Resolves when `settle` is called, the claim is reaped, or the registry is disposed. Never rejects. */
|
|
566
|
+
readonly run: Promise<SettledVerification>;
|
|
567
|
+
/** Single use; false when already settled, reaped or disposed (R4). */
|
|
568
|
+
settle(result: VerificationResult): boolean;
|
|
569
|
+
}
|
|
570
|
+
| { readonly kind: "joined"; readonly entry: PendingEntry; readonly run: Promise<SettledVerification> }
|
|
571
|
+
| { readonly kind: "settled"; readonly entry: PendingEntry; readonly result: SettledVerification }
|
|
572
|
+
| { readonly kind: "expired"; readonly handle: string }
|
|
573
|
+
| { readonly kind: "unknown"; readonly handle: string };
|
|
574
|
+
|
|
575
|
+
export type EvictionCause = "ttl" | "session-cap" | "global-cap" | "weight-cap" | "session-gone" | "disposed";
|
|
576
|
+
|
|
577
|
+
/** A proven-introduced rejection, for R11 lineage. */
|
|
578
|
+
export interface RejectionRecord {
|
|
579
|
+
readonly orchestratorSessionID: string;
|
|
580
|
+
readonly root: string;
|
|
581
|
+
/** The handle, or "dispatch <dispatchID>" for a required gate. */
|
|
582
|
+
readonly label: string;
|
|
583
|
+
/** When the rejected producer's changes were in the tree (its return time). */
|
|
584
|
+
readonly landedAt: number;
|
|
585
|
+
readonly introduced: readonly string[];
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
export interface LineageQuery {
|
|
589
|
+
readonly orchestratorSessionID: string;
|
|
590
|
+
readonly root: string;
|
|
591
|
+
readonly dispatchedAt: number;
|
|
592
|
+
/** TestsPassJudgement.failures.preexisting of the delegation being judged. */
|
|
593
|
+
readonly preexisting: readonly string[];
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
export interface LineageMatch {
|
|
597
|
+
readonly label: string;
|
|
598
|
+
/** The intersection, in `preexisting` order. */
|
|
599
|
+
readonly ids: readonly string[];
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
export interface PendingRegistryStats {
|
|
603
|
+
readonly entries: number;
|
|
604
|
+
readonly sessions: number;
|
|
605
|
+
readonly verifying: number;
|
|
606
|
+
readonly weight: number;
|
|
607
|
+
readonly tombstones: number;
|
|
608
|
+
readonly rejections: number;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
export interface PendingRegistryOptions {
|
|
612
|
+
/** pendingTtlMs (section 1.4). */
|
|
613
|
+
readonly ttlMs: number;
|
|
614
|
+
/** gateBudgetMs + VERIFYING_GRACE_MS. */
|
|
615
|
+
readonly maxVerifyingMs: number;
|
|
616
|
+
/** Injected clock; default Date.now. */
|
|
617
|
+
readonly now?: () => number;
|
|
618
|
+
/** Injected random source; default crypto.randomBytes. */
|
|
619
|
+
readonly random?: (bytes: number) => Uint8Array;
|
|
620
|
+
readonly maxPerSession?: number;
|
|
621
|
+
readonly maxGlobal?: number;
|
|
622
|
+
readonly maxWeight?: number;
|
|
623
|
+
/** Logging hook; never throws into the registry (a throwing hook is ignored). */
|
|
624
|
+
readonly onEvict?: (entry: PendingEntry, cause: EvictionCause) => void;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
export interface PendingRegistry {
|
|
628
|
+
register(reg: PendingRegistration): RegisterResult;
|
|
629
|
+
get(sessionID: string, handle: string): Lookup;
|
|
630
|
+
listUnverified(sessionID: string, limit?: number): readonly PendingEntry[];
|
|
631
|
+
listOpen(sessionID: string): readonly PendingEntry[];
|
|
632
|
+
/**
|
|
633
|
+
* QA-2.4-3: what the orchestrator still has to look at, newest first: unverified entries,
|
|
634
|
+
* verifying ones when `verifying` is set (background mode), and verified entries whose background
|
|
635
|
+
* verdict did not pass and was not yet replayed by router_verify (awaitsReplay).
|
|
636
|
+
*/
|
|
637
|
+
listPending(sessionID: string, options?: { readonly verifying?: boolean }): readonly PendingEntry[];
|
|
638
|
+
/** QA-2.4-3: router_verify reported these handles' verdicts to the session: they leave listPending. */
|
|
639
|
+
markReplayed(sessionID: string, handles: readonly string[]): void;
|
|
640
|
+
markVerifying(sessionID: string, handle: string): ClaimResult;
|
|
641
|
+
sweep(nowMs?: number): number;
|
|
642
|
+
forgetSession(sessionID: string): void;
|
|
643
|
+
recordRejection(record: RejectionRecord): void;
|
|
644
|
+
findLineage(query: LineageQuery): LineageMatch | undefined;
|
|
645
|
+
stats(): PendingRegistryStats;
|
|
646
|
+
dispose(): void;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
export interface FooterInput {
|
|
650
|
+
/**
|
|
651
|
+
* The registered handle. A delegation the registry refuses is not deferred at all (QA-2.4-4: the
|
|
652
|
+
* required gate runs instead), so there is no footer without a handle.
|
|
653
|
+
*/
|
|
654
|
+
readonly handle: string;
|
|
655
|
+
readonly risk: RiskAssessment;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
export interface LateNotice {
|
|
659
|
+
readonly handle: string;
|
|
660
|
+
readonly description: string;
|
|
661
|
+
/** Proven-introduced test ids; empty when the run named none. */
|
|
662
|
+
readonly introduced: readonly string[];
|
|
663
|
+
/** R14: "unverifiable" when the run could not judge the work (terminal). Default "fail". */
|
|
664
|
+
readonly outcome?: "fail" | "unverifiable";
|
|
665
|
+
/** R14: the first reason, shown for an unverifiable result and for a fail that names no id. */
|
|
666
|
+
readonly reason?: string;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
// ---------------------------------------------------------------------------------------------
|
|
670
|
+
// Text helpers (R9)
|
|
671
|
+
// ---------------------------------------------------------------------------------------------
|
|
672
|
+
|
|
673
|
+
// Every C0/C1 control (tab included), U+2028 and U+2029.
|
|
674
|
+
const CONTROL_CHARS = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g;
|
|
675
|
+
// A directive key and EVERY colon that follows it on the same line, as directives.ts scans keys
|
|
676
|
+
// (anywhere, any case, horizontal whitespace around the colon). All colons go: dropping only the
|
|
677
|
+
// first would turn `VERIFY::required` into `VERIFY :required`, which parses again (QA-2.4-6).
|
|
678
|
+
const DIRECTIVE_KEY = /\b(VERIFY_WAIT|VERIFY|CAP)(?:[^\S\r\n\u2028\u2029]*:)+/gi;
|
|
679
|
+
|
|
680
|
+
/**
|
|
681
|
+
* R9 directive safety (QA-2.4-6): every `VERIFY:` / `VERIFY_WAIT:` / `CAP:` key (any case) loses
|
|
682
|
+
* its colons, so neither parseVerifyDirectives nor parseCapDirective finds a directive in the
|
|
683
|
+
* result. Line breaks and everything else are kept, so it applies to multi-line router text
|
|
684
|
+
* (router_verify reports, forcing notes, accepted suffixes) that quotes producer-derived text such
|
|
685
|
+
* as failing test ids. Pure.
|
|
686
|
+
*/
|
|
687
|
+
export function neutralizeDirectives(text: string): string {
|
|
688
|
+
return text.replace(DIRECTIVE_KEY, "$1 ");
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* The character rules shared by every dynamic fragment: controls -> space, backtick -> `'`,
|
|
693
|
+
* directive keys lose their colons (R9 directive safety), whitespace runs -> one space, trim.
|
|
694
|
+
*/
|
|
695
|
+
function sanitizeInline(text: string): string {
|
|
696
|
+
return neutralizeDirectives(text.replace(CONTROL_CHARS, " ").replace(/`/g, "'"))
|
|
697
|
+
.replace(/\s+/g, " ")
|
|
698
|
+
.trim();
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
function formatIds(ids: readonly string[], max: number): string {
|
|
702
|
+
const shown = ids.slice(0, max).map(sanitizeInline);
|
|
703
|
+
const rest = ids.length - shown.length;
|
|
704
|
+
return rest > 0 ? `${shown.join(", ")} (+${rest} more)` : shown.join(", ");
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
function syntheticVerdict(reason: string): Verdict {
|
|
708
|
+
return { pass: false, outcome: "unverifiable", method: "deterministic", reasons: [reason], caveats: [reason] };
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// ---------------------------------------------------------------------------------------------
|
|
712
|
+
// Registry (R2-R8, R11)
|
|
713
|
+
// ---------------------------------------------------------------------------------------------
|
|
714
|
+
|
|
715
|
+
interface RunSlot {
|
|
716
|
+
readonly promise: Promise<SettledVerification>;
|
|
717
|
+
readonly resolve: (value: SettledVerification) => void;
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
interface EntryRecord {
|
|
721
|
+
readonly handle: string;
|
|
722
|
+
readonly seq: number;
|
|
723
|
+
readonly orchestratorSessionID: string;
|
|
724
|
+
readonly dispatchID: string;
|
|
725
|
+
readonly producerSessionID: string;
|
|
726
|
+
readonly producerTier: string;
|
|
727
|
+
readonly description: string;
|
|
728
|
+
readonly cwd: string;
|
|
729
|
+
readonly root: string | undefined;
|
|
730
|
+
readonly dispatchedAt: number;
|
|
731
|
+
readonly createdAt: number;
|
|
732
|
+
readonly risk: RiskAssessment;
|
|
733
|
+
readonly changedFilesDropped: number;
|
|
734
|
+
readonly concurrentDispatches: number | undefined;
|
|
735
|
+
readonly contaminatedBy: string | undefined;
|
|
736
|
+
dod: DoD | undefined;
|
|
737
|
+
reference: Promise<ReferenceState>;
|
|
738
|
+
changedFiles: readonly ChangedPath[] | "unavailable";
|
|
739
|
+
digests: Promise<FileDigests | undefined> | undefined;
|
|
740
|
+
state: PendingState;
|
|
741
|
+
verifyingSince: number | undefined;
|
|
742
|
+
result: SettledVerification | undefined;
|
|
743
|
+
run: RunSlot | undefined;
|
|
744
|
+
pathWeight: number;
|
|
745
|
+
refWeight: number;
|
|
746
|
+
released: boolean;
|
|
747
|
+
doomed: boolean;
|
|
748
|
+
live: boolean;
|
|
749
|
+
/** QA-2.4-3: router_verify reported the verdict to the session (markReplayed). */
|
|
750
|
+
replayed: boolean;
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
type LookupMiss = Extract<Lookup, { readonly kind: "expired" | "unknown" }>;
|
|
754
|
+
|
|
755
|
+
interface LedgerRecord {
|
|
756
|
+
readonly record: RejectionRecord;
|
|
757
|
+
readonly recordedAt: number;
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
function defaultRandom(bytes: number): Uint8Array {
|
|
761
|
+
return randomBytes(bytes);
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
function toHex(bytes: Uint8Array): string {
|
|
765
|
+
let out = "";
|
|
766
|
+
for (const b of bytes) out += b.toString(16).padStart(2, "0");
|
|
767
|
+
return out;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
function isNonEmptyString(value: unknown): value is string {
|
|
771
|
+
return typeof value === "string" && value.length > 0;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/**
|
|
775
|
+
* Eviction order (R7, QA-2.4-4): verified entries only, oldest first. An unverified or verifying
|
|
776
|
+
* entry is never evicted by a cap: its delegation would leave the pending list silently and read as
|
|
777
|
+
* verified. A cap that only such entries fill refuses the new registration ("registry-full"), and
|
|
778
|
+
* the dispatch then runs the required gate instead.
|
|
779
|
+
*/
|
|
780
|
+
function evictionCandidates(records: Iterable<EntryRecord>): EntryRecord[] {
|
|
781
|
+
const byAge = (a: EntryRecord, b: EntryRecord): number => a.createdAt - b.createdAt || a.seq - b.seq;
|
|
782
|
+
return [...records].filter((r) => r.state === "verified" && !awaitsReplay(r)).sort(byAge);
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
/**
|
|
786
|
+
* QA-2.4-3: a background verdict that did not pass and that router_verify has not yet replayed to
|
|
787
|
+
* the session. It stays listed (and, like an unverified entry, is never evicted by a cap) until the
|
|
788
|
+
* replay or the TTL: the one-shot late notice may never have reached the orchestrator.
|
|
789
|
+
*/
|
|
790
|
+
function awaitsReplay(rec: EntryRecord): boolean {
|
|
791
|
+
if (rec.state !== "verified" || rec.replayed || rec.result?.background !== true) return false;
|
|
792
|
+
const verdict = rec.result.verdict;
|
|
793
|
+
return (verdict.outcome ?? (verdict.pass ? "pass" : "fail")) !== "pass";
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
/** R2-R8, R11. */
|
|
797
|
+
export function createPendingRegistry(options: PendingRegistryOptions): PendingRegistry {
|
|
798
|
+
const now = options.now ?? Date.now;
|
|
799
|
+
const random = options.random ?? defaultRandom;
|
|
800
|
+
const maxPerSession = options.maxPerSession ?? MAX_ENTRIES_PER_SESSION;
|
|
801
|
+
const maxGlobal = options.maxGlobal ?? MAX_ENTRIES_GLOBAL;
|
|
802
|
+
const maxWeight = options.maxWeight ?? MAX_GLOBAL_WEIGHT;
|
|
803
|
+
const { ttlMs, maxVerifyingMs } = options;
|
|
804
|
+
|
|
805
|
+
const sessions = new Map<string, Map<string, EntryRecord>>();
|
|
806
|
+
const byHandle = new Map<string, EntryRecord>();
|
|
807
|
+
/** handle -> the session it was issued to; insertion order = FIFO. */
|
|
808
|
+
const tombstones = new Map<string, string>();
|
|
809
|
+
const ledger = new Map<string, LedgerRecord[]>();
|
|
810
|
+
const counters = { seq: 0, weight: 0, hookFailures: 0 };
|
|
811
|
+
|
|
812
|
+
function snapshot(rec: EntryRecord): PendingEntry {
|
|
813
|
+
return Object.freeze({
|
|
814
|
+
handle: rec.handle,
|
|
815
|
+
orchestratorSessionID: rec.orchestratorSessionID,
|
|
816
|
+
dispatchID: rec.dispatchID,
|
|
817
|
+
producerSessionID: rec.producerSessionID,
|
|
818
|
+
producerTier: rec.producerTier,
|
|
819
|
+
description: rec.description,
|
|
820
|
+
cwd: rec.cwd,
|
|
821
|
+
root: rec.root,
|
|
822
|
+
dispatchedAt: rec.dispatchedAt,
|
|
823
|
+
dod: rec.dod,
|
|
824
|
+
reference: rec.reference,
|
|
825
|
+
changedFiles: rec.changedFiles,
|
|
826
|
+
changedFilesDropped: rec.changedFilesDropped,
|
|
827
|
+
risk: rec.risk,
|
|
828
|
+
digests: rec.digests,
|
|
829
|
+
...(rec.concurrentDispatches !== undefined ? { concurrentDispatches: rec.concurrentDispatches } : {}),
|
|
830
|
+
...(rec.contaminatedBy !== undefined ? { contaminatedBy: rec.contaminatedBy } : {}),
|
|
831
|
+
createdAt: rec.createdAt,
|
|
832
|
+
state: rec.state,
|
|
833
|
+
verifyingSince: rec.verifyingSince,
|
|
834
|
+
result: rec.result,
|
|
835
|
+
});
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
function addTombstone(handle: string, sessionID: string): void {
|
|
839
|
+
tombstones.delete(handle);
|
|
840
|
+
tombstones.set(handle, sessionID);
|
|
841
|
+
while (tombstones.size > TOMBSTONE_MAX) {
|
|
842
|
+
const oldest = tombstones.keys().next();
|
|
843
|
+
if (oldest.done === true) break;
|
|
844
|
+
tombstones.delete(oldest.value);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
function evict(rec: EntryRecord, cause: EvictionCause): void {
|
|
849
|
+
if (!rec.live) return;
|
|
850
|
+
rec.live = false;
|
|
851
|
+
const session = sessions.get(rec.orchestratorSessionID);
|
|
852
|
+
session?.delete(rec.handle);
|
|
853
|
+
if (session !== undefined && session.size === 0) sessions.delete(rec.orchestratorSessionID);
|
|
854
|
+
byHandle.delete(rec.handle);
|
|
855
|
+
counters.weight -= rec.pathWeight + rec.refWeight;
|
|
856
|
+
addTombstone(rec.handle, rec.orchestratorSessionID);
|
|
857
|
+
const hook = options.onEvict;
|
|
858
|
+
if (hook === undefined) return;
|
|
859
|
+
try {
|
|
860
|
+
hook(snapshot(rec), cause);
|
|
861
|
+
} catch {
|
|
862
|
+
// A logging hook must never break the registry (PendingRegistryOptions.onEvict).
|
|
863
|
+
counters.hookFailures += 1;
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
function release(rec: EntryRecord): void {
|
|
868
|
+
counters.weight -= rec.pathWeight + rec.refWeight;
|
|
869
|
+
rec.pathWeight = 0;
|
|
870
|
+
rec.refWeight = 0;
|
|
871
|
+
rec.released = true;
|
|
872
|
+
rec.dod = undefined;
|
|
873
|
+
rec.digests = undefined;
|
|
874
|
+
rec.changedFiles = "unavailable";
|
|
875
|
+
rec.reference = Promise.resolve<ReferenceState>({ kind: "none", reason: RELEASED_REASON });
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
function isExpired(rec: EntryRecord, at: number): boolean {
|
|
879
|
+
return at - rec.createdAt >= ttlMs;
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
function recordRejection(record: RejectionRecord): void {
|
|
883
|
+
if (!isNonEmptyString(record.orchestratorSessionID) || !isNonEmptyString(record.root)) return;
|
|
884
|
+
if (record.introduced.length === 0) return;
|
|
885
|
+
const stored: RejectionRecord = Object.freeze({
|
|
886
|
+
orchestratorSessionID: record.orchestratorSessionID,
|
|
887
|
+
root: record.root,
|
|
888
|
+
label: record.label,
|
|
889
|
+
landedAt: record.landedAt,
|
|
890
|
+
introduced: Object.freeze(record.introduced.slice(0, MAX_LEDGER_IDS)),
|
|
891
|
+
});
|
|
892
|
+
// QA-2.4-1: router_verify records a call's rejections before it settles them, and settle records
|
|
893
|
+
// again: one record per label and root, the newest kept.
|
|
894
|
+
const list = (ledger.get(record.orchestratorSessionID) ?? []).filter(
|
|
895
|
+
(l) => l.record.label !== record.label || l.record.root !== record.root,
|
|
896
|
+
);
|
|
897
|
+
list.push({ record: stored, recordedAt: now() });
|
|
898
|
+
while (list.length > MAX_LEDGER_PER_SESSION) list.shift();
|
|
899
|
+
ledger.set(record.orchestratorSessionID, list);
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
/** Resolves a run and moves the entry out of "verifying" (settle, reap). */
|
|
903
|
+
function finishRun(rec: EntryRecord, settled: SettledVerification): void {
|
|
904
|
+
const run = rec.run;
|
|
905
|
+
rec.run = undefined;
|
|
906
|
+
rec.verifyingSince = undefined;
|
|
907
|
+
rec.result = settled;
|
|
908
|
+
if (settled.retryable) {
|
|
909
|
+
rec.state = "unverified";
|
|
910
|
+
} else {
|
|
911
|
+
rec.state = "verified";
|
|
912
|
+
release(rec);
|
|
913
|
+
}
|
|
914
|
+
run?.resolve(settled);
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
/** Reaping, TTL eviction and ledger expiry (R7). Returns the number of evicted entries. */
|
|
918
|
+
function maintain(at: number): number {
|
|
919
|
+
let evicted = 0;
|
|
920
|
+
for (const rec of [...byHandle.values()]) {
|
|
921
|
+
if (rec.state === "verifying" && rec.verifyingSince !== undefined && rec.verifyingSince + maxVerifyingMs <= at) {
|
|
922
|
+
finishRun(rec, {
|
|
923
|
+
verdict: syntheticVerdict(ABANDONED_REASON),
|
|
924
|
+
retryable: true,
|
|
925
|
+
handle: rec.handle,
|
|
926
|
+
settledAt: at,
|
|
927
|
+
});
|
|
928
|
+
}
|
|
929
|
+
if (rec.state === "verifying") continue;
|
|
930
|
+
if (rec.doomed) {
|
|
931
|
+
evict(rec, "session-gone");
|
|
932
|
+
evicted += 1;
|
|
933
|
+
} else if (isExpired(rec, at)) {
|
|
934
|
+
evict(rec, "ttl");
|
|
935
|
+
evicted += 1;
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
for (const [sid, list] of ledger) {
|
|
939
|
+
const kept = list.filter((l) => at - l.recordedAt < ttlMs);
|
|
940
|
+
if (kept.length === 0) ledger.delete(sid);
|
|
941
|
+
else if (kept.length !== list.length) ledger.set(sid, kept);
|
|
942
|
+
}
|
|
943
|
+
return evicted;
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
function lookup(sessionID: string, handle: string): EntryRecord | LookupMiss {
|
|
947
|
+
const rec = sessions.get(sessionID)?.get(handle);
|
|
948
|
+
if (rec !== undefined) return rec;
|
|
949
|
+
if (tombstones.get(handle) === sessionID) return { kind: "expired", handle };
|
|
950
|
+
return { kind: "unknown", handle };
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
function isRecord(value: EntryRecord | LookupMiss): value is EntryRecord {
|
|
954
|
+
return !("kind" in value);
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
/**
|
|
958
|
+
* R7, QA-2.4-4: a captured reference that would push the weight over the cap is shed, never an
|
|
959
|
+
* entry: the entry stays unverified and listed, and its reference becomes { kind: "none", reason:
|
|
960
|
+
* REFERENCE_SHED_REASON }, so a later verification cannot excuse pre-existing failures (stricter,
|
|
961
|
+
* never a false pass). Expired entries go first (verified entries hold no weight once released).
|
|
962
|
+
*/
|
|
963
|
+
function admitReferenceWeight(rec: EntryRecord, refWeight: number): void {
|
|
964
|
+
if (counters.weight + refWeight > maxWeight) maintain(now());
|
|
965
|
+
if (!rec.live || rec.released) return;
|
|
966
|
+
if (counters.weight + refWeight <= maxWeight) {
|
|
967
|
+
rec.refWeight = refWeight;
|
|
968
|
+
counters.weight += refWeight;
|
|
969
|
+
return;
|
|
970
|
+
}
|
|
971
|
+
rec.reference = Promise.resolve<ReferenceState>({ kind: "none", reason: REFERENCE_SHED_REASON });
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
function drawHandle(): string | undefined {
|
|
975
|
+
for (let i = 0; i < HANDLE_MAX_DRAWS; i += 1) {
|
|
976
|
+
const candidate = HANDLE_PREFIX + toHex(random(HANDLE_RANDOM_BYTES));
|
|
977
|
+
if (!HANDLE_PATTERN.test(candidate)) continue;
|
|
978
|
+
if (byHandle.has(candidate) || tombstones.has(candidate)) continue;
|
|
979
|
+
return candidate;
|
|
980
|
+
}
|
|
981
|
+
return undefined;
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
function register(reg: PendingRegistration): RegisterResult {
|
|
985
|
+
if (
|
|
986
|
+
!isNonEmptyString(reg.orchestratorSessionID) ||
|
|
987
|
+
!isNonEmptyString(reg.producerSessionID) ||
|
|
988
|
+
reg.orchestratorSessionID === reg.producerSessionID
|
|
989
|
+
) {
|
|
990
|
+
return {
|
|
991
|
+
ok: false,
|
|
992
|
+
code: "invalid-input",
|
|
993
|
+
detail: "orchestrator and producer session ids must be non-empty and differ",
|
|
994
|
+
};
|
|
995
|
+
}
|
|
996
|
+
const at = now();
|
|
997
|
+
maintain(at);
|
|
998
|
+
|
|
999
|
+
const incoming = reg.changedFiles;
|
|
1000
|
+
let changedFiles: readonly ChangedPath[] | "unavailable" = "unavailable";
|
|
1001
|
+
let changedFilesDropped = 0;
|
|
1002
|
+
if (incoming !== "unavailable") {
|
|
1003
|
+
if (incoming.length > MAX_STORED_CHANGED_FILES) changedFilesDropped = incoming.length;
|
|
1004
|
+
else changedFiles = Object.freeze([...incoming]);
|
|
1005
|
+
}
|
|
1006
|
+
const pathWeight = changedFiles === "unavailable" ? 0 : changedFiles.length;
|
|
1007
|
+
|
|
1008
|
+
// Plan the evictions first: a registration that cannot fit evicts nothing.
|
|
1009
|
+
const session = sessions.get(reg.orchestratorSessionID);
|
|
1010
|
+
const victims: Array<{ rec: EntryRecord; cause: EvictionCause }> = [];
|
|
1011
|
+
const chosen = new Set<EntryRecord>();
|
|
1012
|
+
if (session !== undefined) {
|
|
1013
|
+
let count = session.size;
|
|
1014
|
+
for (const rec of evictionCandidates(session.values())) {
|
|
1015
|
+
if (count + 1 <= maxPerSession) break;
|
|
1016
|
+
victims.push({ rec, cause: "session-cap" });
|
|
1017
|
+
chosen.add(rec);
|
|
1018
|
+
count -= 1;
|
|
1019
|
+
}
|
|
1020
|
+
if (count + 1 > maxPerSession) {
|
|
1021
|
+
return { ok: false, code: "registry-full", detail: `session holds ${count} unverified or verifying entries` };
|
|
1022
|
+
}
|
|
1023
|
+
} else if (maxPerSession < 1) {
|
|
1024
|
+
return { ok: false, code: "registry-full", detail: "per-session cap is 0" };
|
|
1025
|
+
}
|
|
1026
|
+
let count = byHandle.size - victims.length;
|
|
1027
|
+
let weight = counters.weight - victims.reduce((sum, v) => sum + v.rec.pathWeight + v.rec.refWeight, 0);
|
|
1028
|
+
for (const rec of evictionCandidates(byHandle.values())) {
|
|
1029
|
+
if (count + 1 <= maxGlobal && weight + pathWeight <= maxWeight) break;
|
|
1030
|
+
if (chosen.has(rec)) continue;
|
|
1031
|
+
victims.push({ rec, cause: count + 1 > maxGlobal ? "global-cap" : "weight-cap" });
|
|
1032
|
+
chosen.add(rec);
|
|
1033
|
+
count -= 1;
|
|
1034
|
+
weight -= rec.pathWeight + rec.refWeight;
|
|
1035
|
+
}
|
|
1036
|
+
if (count + 1 > maxGlobal || weight + pathWeight > maxWeight) {
|
|
1037
|
+
return { ok: false, code: "registry-full", detail: "the pending registry cannot hold another entry" };
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
const handle = drawHandle();
|
|
1041
|
+
if (handle === undefined) {
|
|
1042
|
+
return { ok: false, code: "handle-collision", detail: `no free handle after ${HANDLE_MAX_DRAWS} draws` };
|
|
1043
|
+
}
|
|
1044
|
+
for (const v of victims) evict(v.rec, v.cause);
|
|
1045
|
+
|
|
1046
|
+
const reference = reg.reference.then(
|
|
1047
|
+
(state) => state,
|
|
1048
|
+
(): ReferenceState => ({ kind: "none", reason: REFERENCE_FAILED_REASON }),
|
|
1049
|
+
);
|
|
1050
|
+
const digests = reg.digests?.then(
|
|
1051
|
+
(d) => d,
|
|
1052
|
+
() => undefined,
|
|
1053
|
+
);
|
|
1054
|
+
counters.seq += 1;
|
|
1055
|
+
const rec: EntryRecord = {
|
|
1056
|
+
handle,
|
|
1057
|
+
seq: counters.seq,
|
|
1058
|
+
orchestratorSessionID: reg.orchestratorSessionID,
|
|
1059
|
+
dispatchID: reg.dispatchID,
|
|
1060
|
+
producerSessionID: reg.producerSessionID,
|
|
1061
|
+
producerTier: reg.producerTier,
|
|
1062
|
+
description: sanitizeDescription(reg.description),
|
|
1063
|
+
cwd: reg.cwd,
|
|
1064
|
+
root: reg.root,
|
|
1065
|
+
dispatchedAt: reg.dispatchedAt,
|
|
1066
|
+
createdAt: at,
|
|
1067
|
+
risk: reg.risk,
|
|
1068
|
+
changedFilesDropped,
|
|
1069
|
+
concurrentDispatches: reg.concurrentDispatches,
|
|
1070
|
+
contaminatedBy: reg.contaminatedBy,
|
|
1071
|
+
dod: reg.dod,
|
|
1072
|
+
reference,
|
|
1073
|
+
changedFiles,
|
|
1074
|
+
digests,
|
|
1075
|
+
state: "unverified",
|
|
1076
|
+
verifyingSince: undefined,
|
|
1077
|
+
result: undefined,
|
|
1078
|
+
run: undefined,
|
|
1079
|
+
pathWeight,
|
|
1080
|
+
refWeight: 0,
|
|
1081
|
+
released: false,
|
|
1082
|
+
doomed: false,
|
|
1083
|
+
live: true,
|
|
1084
|
+
replayed: false,
|
|
1085
|
+
};
|
|
1086
|
+
const target = session ?? new Map<string, EntryRecord>();
|
|
1087
|
+
target.set(handle, rec);
|
|
1088
|
+
sessions.set(reg.orchestratorSessionID, target);
|
|
1089
|
+
byHandle.set(handle, rec);
|
|
1090
|
+
counters.weight += pathWeight;
|
|
1091
|
+
|
|
1092
|
+
// R7: the reference's weight is added when it resolves "captured" (a promise callback).
|
|
1093
|
+
void reference.then((state) => {
|
|
1094
|
+
if (!rec.live || rec.released || state.kind !== "captured") return;
|
|
1095
|
+
admitReferenceWeight(rec, state.reference.untracked.size + state.reference.tracked.size);
|
|
1096
|
+
});
|
|
1097
|
+
|
|
1098
|
+
return { ok: true, handle, evicted: victims.map((v) => v.rec.handle) };
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
function markVerifying(sessionID: string, handle: string): ClaimResult {
|
|
1102
|
+
const at = now();
|
|
1103
|
+
maintain(at);
|
|
1104
|
+
const found = lookup(sessionID, handle);
|
|
1105
|
+
if (!isRecord(found)) return found;
|
|
1106
|
+
const rec = found;
|
|
1107
|
+
if (rec.state === "verified" && rec.result !== undefined) {
|
|
1108
|
+
return { kind: "settled", entry: snapshot(rec), result: rec.result };
|
|
1109
|
+
}
|
|
1110
|
+
if (rec.state === "verifying" && rec.run !== undefined) {
|
|
1111
|
+
return { kind: "joined", entry: snapshot(rec), run: rec.run.promise };
|
|
1112
|
+
}
|
|
1113
|
+
let resolveRun: (value: SettledVerification) => void = () => undefined;
|
|
1114
|
+
const promise = new Promise<SettledVerification>((resolve) => {
|
|
1115
|
+
resolveRun = resolve;
|
|
1116
|
+
});
|
|
1117
|
+
const run: RunSlot = { promise, resolve: resolveRun };
|
|
1118
|
+
rec.state = "verifying";
|
|
1119
|
+
rec.verifyingSince = at;
|
|
1120
|
+
rec.run = run;
|
|
1121
|
+
let used = false;
|
|
1122
|
+
const settle = (result: VerificationResult): boolean => {
|
|
1123
|
+
if (used || rec.run !== run || !rec.live) return false;
|
|
1124
|
+
used = true;
|
|
1125
|
+
const settledAt = now();
|
|
1126
|
+
const settled: SettledVerification = Object.freeze({ ...result, handle: rec.handle, settledAt });
|
|
1127
|
+
finishRun(rec, settled);
|
|
1128
|
+
if (!result.retryable && result.introduced !== undefined && result.introduced.length > 0 && rec.root !== undefined) {
|
|
1129
|
+
recordRejection({
|
|
1130
|
+
orchestratorSessionID: rec.orchestratorSessionID,
|
|
1131
|
+
root: rec.root,
|
|
1132
|
+
label: rec.handle,
|
|
1133
|
+
landedAt: rec.createdAt,
|
|
1134
|
+
introduced: result.introduced,
|
|
1135
|
+
});
|
|
1136
|
+
}
|
|
1137
|
+
if (rec.doomed) evict(rec, "session-gone");
|
|
1138
|
+
else if (isExpired(rec, settledAt)) evict(rec, "ttl");
|
|
1139
|
+
return true;
|
|
1140
|
+
};
|
|
1141
|
+
return { kind: "claimed", entry: snapshot(rec), run: promise, settle };
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
function listByState(sessionID: string, states: readonly PendingState[]): EntryRecord[] {
|
|
1145
|
+
maintain(now());
|
|
1146
|
+
const session = sessions.get(sessionID);
|
|
1147
|
+
if (session === undefined) return [];
|
|
1148
|
+
return [...session.values()]
|
|
1149
|
+
.filter((r) => states.includes(r.state))
|
|
1150
|
+
.sort((a, b) => b.createdAt - a.createdAt || b.seq - a.seq);
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
return {
|
|
1154
|
+
register,
|
|
1155
|
+
get(sessionID, handle) {
|
|
1156
|
+
maintain(now());
|
|
1157
|
+
const found = lookup(sessionID, handle);
|
|
1158
|
+
return isRecord(found) ? { kind: "found", entry: snapshot(found) } : found;
|
|
1159
|
+
},
|
|
1160
|
+
listUnverified(sessionID, limit) {
|
|
1161
|
+
const list = listByState(sessionID, ["unverified"]);
|
|
1162
|
+
const bounded = limit === undefined ? list : list.slice(0, Math.max(0, Math.floor(limit)));
|
|
1163
|
+
return bounded.map(snapshot);
|
|
1164
|
+
},
|
|
1165
|
+
listOpen(sessionID) {
|
|
1166
|
+
return listByState(sessionID, ["unverified", "verifying"]).map(snapshot);
|
|
1167
|
+
},
|
|
1168
|
+
listPending(sessionID, options) {
|
|
1169
|
+
const states: PendingState[] = options?.verifying === true ? ["unverified", "verifying", "verified"] : ["unverified", "verified"];
|
|
1170
|
+
return listByState(sessionID, states)
|
|
1171
|
+
.filter((r) => r.state !== "verified" || awaitsReplay(r))
|
|
1172
|
+
.map(snapshot);
|
|
1173
|
+
},
|
|
1174
|
+
markReplayed(sessionID, handles) {
|
|
1175
|
+
const session = sessions.get(sessionID);
|
|
1176
|
+
if (session === undefined) return;
|
|
1177
|
+
for (const handle of handles) {
|
|
1178
|
+
const rec = session.get(handle);
|
|
1179
|
+
if (rec !== undefined) rec.replayed = true;
|
|
1180
|
+
}
|
|
1181
|
+
},
|
|
1182
|
+
markVerifying,
|
|
1183
|
+
sweep(nowMs) {
|
|
1184
|
+
return maintain(nowMs ?? now());
|
|
1185
|
+
},
|
|
1186
|
+
forgetSession(sessionID) {
|
|
1187
|
+
const session = sessions.get(sessionID);
|
|
1188
|
+
for (const rec of session === undefined ? [] : [...session.values()]) {
|
|
1189
|
+
if (rec.state === "verifying") rec.doomed = true;
|
|
1190
|
+
else evict(rec, "session-gone");
|
|
1191
|
+
}
|
|
1192
|
+
for (const [handle, sid] of [...tombstones]) {
|
|
1193
|
+
if (sid === sessionID) tombstones.delete(handle);
|
|
1194
|
+
}
|
|
1195
|
+
ledger.delete(sessionID);
|
|
1196
|
+
},
|
|
1197
|
+
recordRejection,
|
|
1198
|
+
findLineage(query) {
|
|
1199
|
+
maintain(now());
|
|
1200
|
+
const list = ledger.get(query.orchestratorSessionID) ?? [];
|
|
1201
|
+
for (let i = list.length - 1; i >= 0; i -= 1) {
|
|
1202
|
+
const { record } = list[i];
|
|
1203
|
+
if (record.root !== query.root || record.landedAt > query.dispatchedAt) continue;
|
|
1204
|
+
const introduced = new Set(record.introduced);
|
|
1205
|
+
const ids = [...new Set(query.preexisting)].filter((id) => introduced.has(id));
|
|
1206
|
+
if (ids.length > 0) return { label: record.label, ids };
|
|
1207
|
+
}
|
|
1208
|
+
return undefined;
|
|
1209
|
+
},
|
|
1210
|
+
stats() {
|
|
1211
|
+
let verifying = 0;
|
|
1212
|
+
for (const rec of byHandle.values()) if (rec.state === "verifying") verifying += 1;
|
|
1213
|
+
let rejections = 0;
|
|
1214
|
+
for (const list of ledger.values()) rejections += list.length;
|
|
1215
|
+
return {
|
|
1216
|
+
entries: byHandle.size,
|
|
1217
|
+
sessions: sessions.size,
|
|
1218
|
+
verifying,
|
|
1219
|
+
weight: counters.weight,
|
|
1220
|
+
tombstones: tombstones.size,
|
|
1221
|
+
rejections,
|
|
1222
|
+
};
|
|
1223
|
+
},
|
|
1224
|
+
dispose() {
|
|
1225
|
+
const at = now();
|
|
1226
|
+
for (const rec of [...byHandle.values()]) {
|
|
1227
|
+
if (rec.run !== undefined) {
|
|
1228
|
+
finishRun(rec, { verdict: syntheticVerdict(DISPOSED_REASON), retryable: true, handle: rec.handle, settledAt: at });
|
|
1229
|
+
}
|
|
1230
|
+
evict(rec, "disposed");
|
|
1231
|
+
}
|
|
1232
|
+
ledger.clear();
|
|
1233
|
+
},
|
|
1234
|
+
};
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
// ---------------------------------------------------------------------------------------------
|
|
1238
|
+
// Background queue (R14, task 2.4.5; section 1.5-19). Constructed only when `background: true`.
|
|
1239
|
+
// ---------------------------------------------------------------------------------------------
|
|
1240
|
+
|
|
1241
|
+
/** One deferred delegation queued for background verification (the wiring's deferred finish). */
|
|
1242
|
+
export interface BackgroundRequest {
|
|
1243
|
+
readonly sessionID: string;
|
|
1244
|
+
readonly handle: string;
|
|
1245
|
+
/** The entry's stored changed paths (absolute); coalescing compares them. */
|
|
1246
|
+
readonly files: readonly string[];
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
/** What one background run reports per handle. */
|
|
1250
|
+
export type BackgroundOutcome =
|
|
1251
|
+
/** This run claimed and settled the handle (router_verify's "run"). */
|
|
1252
|
+
| { readonly kind: "judged"; readonly handle: string; readonly description: string; readonly result: SettledVerification }
|
|
1253
|
+
/** A router_verify call judged it or is judging it: that caller has the verdict. */
|
|
1254
|
+
| { readonly kind: "reported"; readonly handle: string }
|
|
1255
|
+
/** Unknown or expired: the entry is gone. */
|
|
1256
|
+
| { readonly kind: "gone"; readonly handle: string };
|
|
1257
|
+
|
|
1258
|
+
/** The gate path of one background run: router_verify's verifyHandles for one session. Never rejects in production. */
|
|
1259
|
+
export type BackgroundVerify = (sessionID: string, handles: readonly string[], signal: AbortSignal) => Promise<readonly BackgroundOutcome[]>;
|
|
1260
|
+
|
|
1261
|
+
export interface BackgroundTimers {
|
|
1262
|
+
setTimeout(callback: () => void, ms: number): unknown;
|
|
1263
|
+
clearTimeout(handle: unknown): void;
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
export interface BackgroundQueueOptions {
|
|
1267
|
+
readonly verify: BackgroundVerify;
|
|
1268
|
+
/** pendingTtlMs: an undelivered notice older than this is dropped by sweep. */
|
|
1269
|
+
readonly ttlMs: number;
|
|
1270
|
+
/** Injected clock; default Date.now. */
|
|
1271
|
+
readonly now?: () => number;
|
|
1272
|
+
/** Injected timers; default unref'd setTimeout. */
|
|
1273
|
+
readonly timers?: BackgroundTimers;
|
|
1274
|
+
readonly settleMs?: number;
|
|
1275
|
+
readonly retryBaseMs?: number;
|
|
1276
|
+
readonly maxAttempts?: number;
|
|
1277
|
+
/** Paths compare case-folded (and slash-normalized) on win32; default process.platform. */
|
|
1278
|
+
readonly platform?: NodeJS.Platform;
|
|
1279
|
+
/** Logging hook for a rejected run; never throws into the queue. */
|
|
1280
|
+
readonly onError?: (error: unknown) => void;
|
|
1281
|
+
/**
|
|
1282
|
+
* QA-2.4-5: true while foreground verification (a required gate or router_verify) is running. A
|
|
1283
|
+
* run is then not started: its due requests back off (not counted as an attempt) and retry later.
|
|
1284
|
+
*/
|
|
1285
|
+
readonly busy?: () => boolean;
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
/** QA-2.4-5: the exponent cap of the backoff of requests that were preempted or postponed. */
|
|
1289
|
+
export const BACKGROUND_MAX_BACKOFF_STEPS = 5;
|
|
1290
|
+
|
|
1291
|
+
export interface BackgroundQueueStats {
|
|
1292
|
+
readonly queued: number;
|
|
1293
|
+
readonly running: boolean;
|
|
1294
|
+
readonly timerArmed: boolean;
|
|
1295
|
+
readonly notices: number;
|
|
1296
|
+
readonly superseded: number;
|
|
1297
|
+
readonly runs: number;
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
export interface BackgroundQueue {
|
|
1301
|
+
/** Queues a deferred delegation; a queued older request of the session with overlapping files is dropped. */
|
|
1302
|
+
enqueue(request: BackgroundRequest): void;
|
|
1303
|
+
/** The session's undelivered notices, oldest first; each is returned once (delivered on read). */
|
|
1304
|
+
takeNotices(sessionID: string): readonly LateNotice[];
|
|
1305
|
+
/** A router_verify caller received these handles' verdicts: no late notice for them. */
|
|
1306
|
+
markReported(handles: readonly string[]): void;
|
|
1307
|
+
/** session.deleted: drops the session's requests and notices, and aborts its run in flight. */
|
|
1308
|
+
forgetSession(sessionID: string): void;
|
|
1309
|
+
/** Drops undelivered notices older than ttlMs; returns how many. The idle trigger (R14). */
|
|
1310
|
+
sweep(nowMs?: number): number;
|
|
1311
|
+
stats(): BackgroundQueueStats;
|
|
1312
|
+
/** Resolves once no run is in flight and no request is fresh or due (tests, diagnostics). */
|
|
1313
|
+
whenIdle(): Promise<void>;
|
|
1314
|
+
/**
|
|
1315
|
+
* QA-2.4-5: foreground verification takes precedence. Aborts the run in flight (its deadline, so
|
|
1316
|
+
* its tree dies and the slot is freed); its requests go back to the queue with backoff, not
|
|
1317
|
+
* counted as an attempt, and a verdict it already reached is kept. Resolves once that run has
|
|
1318
|
+
* finished (at once when none is in flight). Never rejects.
|
|
1319
|
+
*/
|
|
1320
|
+
preempt(): Promise<void>;
|
|
1321
|
+
/** Plugin dispose: aborts the run in flight, clears the timer, drops everything. Idempotent. */
|
|
1322
|
+
dispose(): void;
|
|
1323
|
+
}
|
|
1324
|
+
|
|
1325
|
+
const DEFAULT_BACKGROUND_TIMERS: BackgroundTimers = {
|
|
1326
|
+
setTimeout(callback, ms) {
|
|
1327
|
+
const handle = setTimeout(callback, ms);
|
|
1328
|
+
handle.unref?.();
|
|
1329
|
+
return handle;
|
|
1330
|
+
},
|
|
1331
|
+
clearTimeout(handle) {
|
|
1332
|
+
clearTimeout(handle as ReturnType<typeof setTimeout>);
|
|
1333
|
+
},
|
|
1334
|
+
};
|
|
1335
|
+
|
|
1336
|
+
/** R14. */
|
|
1337
|
+
export function createBackgroundQueue(options: BackgroundQueueOptions): BackgroundQueue {
|
|
1338
|
+
const now = options.now ?? Date.now;
|
|
1339
|
+
const timers = options.timers ?? DEFAULT_BACKGROUND_TIMERS;
|
|
1340
|
+
const settleMs = Math.max(0, options.settleMs ?? BACKGROUND_SETTLE_MS);
|
|
1341
|
+
const retryBaseMs = Math.max(0, options.retryBaseMs ?? BACKGROUND_RETRY_BASE_MS);
|
|
1342
|
+
const maxAttempts = Math.max(1, Math.floor(options.maxAttempts ?? BACKGROUND_MAX_ATTEMPTS));
|
|
1343
|
+
const foldCase = (options.platform ?? process.platform) === "win32";
|
|
1344
|
+
const pathKey = (p: string): string => (foldCase ? p.replace(/\\/g, "/").toLowerCase() : p);
|
|
1345
|
+
|
|
1346
|
+
interface QueuedItem {
|
|
1347
|
+
readonly sessionID: string;
|
|
1348
|
+
readonly handle: string;
|
|
1349
|
+
readonly files: ReadonlySet<string>;
|
|
1350
|
+
/** Runs already made for this request that counted (fresh when this and `deferrals` are 0). */
|
|
1351
|
+
readonly attempts: number;
|
|
1352
|
+
/** QA-2.4-5: preemptions and postponements; they back off but never count as attempts. */
|
|
1353
|
+
readonly deferrals: number;
|
|
1354
|
+
readonly notBefore: number;
|
|
1355
|
+
}
|
|
1356
|
+
interface Run {
|
|
1357
|
+
readonly sessionID: string;
|
|
1358
|
+
readonly items: readonly QueuedItem[];
|
|
1359
|
+
readonly controller: AbortController;
|
|
1360
|
+
cancelled: boolean;
|
|
1361
|
+
/** QA-2.4-5: aborted for foreground verification. */
|
|
1362
|
+
preempted: boolean;
|
|
1363
|
+
/** Resolves when the run has finished (finish). */
|
|
1364
|
+
readonly done: Promise<void>;
|
|
1365
|
+
readonly markDone: () => void;
|
|
1366
|
+
}
|
|
1367
|
+
interface StoredNotice {
|
|
1368
|
+
readonly notice: LateNotice;
|
|
1369
|
+
readonly at: number;
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
/** handle -> request; insertion order = FIFO. */
|
|
1373
|
+
const queue = new Map<string, QueuedItem>();
|
|
1374
|
+
/** orchestrator session -> handle -> notice; insertion order = settle order. */
|
|
1375
|
+
const notices = new Map<string, Map<string, StoredNotice>>();
|
|
1376
|
+
const reported = new Set<string>();
|
|
1377
|
+
const idleWaiters: Array<() => void> = [];
|
|
1378
|
+
const counters = { superseded: 0, runs: 0, notices: 0, hookFailures: 0 };
|
|
1379
|
+
let running: Run | undefined;
|
|
1380
|
+
let timer: { readonly handle: unknown; readonly at: number } | undefined;
|
|
1381
|
+
let disposed = false;
|
|
1382
|
+
|
|
1383
|
+
function report(error: unknown): void {
|
|
1384
|
+
try {
|
|
1385
|
+
options.onError?.(error);
|
|
1386
|
+
} catch {
|
|
1387
|
+
// A logging hook must never break the queue (BackgroundQueueOptions.onError).
|
|
1388
|
+
counters.hookFailures += 1;
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
function overlaps(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {
|
|
1393
|
+
for (const f of a) if (b.has(f)) return true;
|
|
1394
|
+
return false;
|
|
1395
|
+
}
|
|
1396
|
+
|
|
1397
|
+
function remember(handle: string): void {
|
|
1398
|
+
reported.delete(handle);
|
|
1399
|
+
reported.add(handle);
|
|
1400
|
+
while (reported.size > REPORTED_MEMO_MAX) {
|
|
1401
|
+
const oldest = reported.values().next();
|
|
1402
|
+
if (oldest.done === true) break;
|
|
1403
|
+
reported.delete(oldest.value);
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
function removeNotice(sessionID: string, handle: string): void {
|
|
1408
|
+
const list = notices.get(sessionID);
|
|
1409
|
+
if (list === undefined || !list.delete(handle)) return;
|
|
1410
|
+
counters.notices -= 1;
|
|
1411
|
+
if (list.size === 0) notices.delete(sessionID);
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
function addNotice(sessionID: string, notice: LateNotice): void {
|
|
1415
|
+
if (reported.has(notice.handle)) return;
|
|
1416
|
+
const list = notices.get(sessionID) ?? new Map<string, StoredNotice>();
|
|
1417
|
+
if (list.has(notice.handle)) return;
|
|
1418
|
+
list.set(notice.handle, { notice, at: now() });
|
|
1419
|
+
notices.set(sessionID, list);
|
|
1420
|
+
counters.notices += 1;
|
|
1421
|
+
if (list.size > LATE_NOTICES_PER_SESSION) removeNotice(sessionID, list.keys().next().value ?? "");
|
|
1422
|
+
while (counters.notices > LATE_NOTICES_MAX) {
|
|
1423
|
+
let victim: { readonly sessionID: string; readonly handle: string; readonly at: number } | undefined;
|
|
1424
|
+
for (const [sid, stored] of notices) {
|
|
1425
|
+
const first = stored.entries().next();
|
|
1426
|
+
if (first.done === true) continue;
|
|
1427
|
+
const [handle, oldest] = first.value;
|
|
1428
|
+
if (victim === undefined || oldest.at < victim.at) victim = { sessionID: sid, handle, at: oldest.at };
|
|
1429
|
+
}
|
|
1430
|
+
if (victim === undefined) break;
|
|
1431
|
+
removeNotice(victim.sessionID, victim.handle);
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1435
|
+
function wakeIdle(): void {
|
|
1436
|
+
for (const resolveIdle of idleWaiters.splice(0)) resolveIdle();
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
/** A request that has never run, been preempted or been postponed. */
|
|
1440
|
+
function isFresh(item: QueuedItem): boolean {
|
|
1441
|
+
return item.attempts === 0 && item.deferrals === 0;
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1444
|
+
/** Backoff: retryBaseMs * 2^(attempts + deferrals - 1), the exponent capped (QA-2.4-5). */
|
|
1445
|
+
function backoffFrom(at: number, attempts: number, deferrals: number): number {
|
|
1446
|
+
const steps = Math.min(Math.max(attempts + deferrals, 1) - 1, BACKGROUND_MAX_BACKOFF_STEPS);
|
|
1447
|
+
return at + retryBaseMs * 2 ** steps;
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
/** Quiet: no run in flight, and every queued request is backing off into the future. */
|
|
1451
|
+
function isQuiet(at: number): boolean {
|
|
1452
|
+
if (running !== undefined) return false;
|
|
1453
|
+
for (const item of queue.values()) if (isFresh(item) || item.notBefore <= at) return false;
|
|
1454
|
+
return true;
|
|
1455
|
+
}
|
|
1456
|
+
|
|
1457
|
+
/** One timer at a time, at the earliest due request; never moved later (no debounce). */
|
|
1458
|
+
function arm(at: number): void {
|
|
1459
|
+
if (disposed) return;
|
|
1460
|
+
if (timer !== undefined) {
|
|
1461
|
+
if (timer.at <= at) return;
|
|
1462
|
+
timers.clearTimeout(timer.handle);
|
|
1463
|
+
}
|
|
1464
|
+
const handle = timers.setTimeout(() => {
|
|
1465
|
+
timer = undefined;
|
|
1466
|
+
runNext();
|
|
1467
|
+
}, Math.max(0, at - now()));
|
|
1468
|
+
timer = { handle, at };
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
function reschedule(): void {
|
|
1472
|
+
if (disposed || running !== undefined) return;
|
|
1473
|
+
let next: number | undefined;
|
|
1474
|
+
for (const item of queue.values()) next = next === undefined ? item.notBefore : Math.min(next, item.notBefore);
|
|
1475
|
+
if (next !== undefined) arm(next);
|
|
1476
|
+
else if (timer !== undefined) {
|
|
1477
|
+
timers.clearTimeout(timer.handle);
|
|
1478
|
+
timer = undefined;
|
|
1479
|
+
}
|
|
1480
|
+
if (isQuiet(now())) wakeIdle();
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
function enforceCap(): void {
|
|
1484
|
+
while (queue.size > BACKGROUND_QUEUE_MAX) {
|
|
1485
|
+
const oldest = queue.keys().next();
|
|
1486
|
+
if (oldest.done === true) break;
|
|
1487
|
+
queue.delete(oldest.value);
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
|
|
1491
|
+
/**
|
|
1492
|
+
* A retryable result: back off, never a hot loop; after maxAttempts it stays unverified.
|
|
1493
|
+
* QA-2.4-5: a run preempted for foreground verification is not `counted`: it backs off without
|
|
1494
|
+
* using an attempt (bounded by the entry's TTL, which ends it as "gone").
|
|
1495
|
+
*/
|
|
1496
|
+
function retry(item: QueuedItem, counted = true): void {
|
|
1497
|
+
const attempts = counted ? item.attempts + 1 : item.attempts;
|
|
1498
|
+
if (counted && attempts >= maxAttempts) return;
|
|
1499
|
+
const deferrals = counted ? item.deferrals : item.deferrals + 1;
|
|
1500
|
+
for (const other of queue.values()) {
|
|
1501
|
+
if (other.sessionID === item.sessionID && overlaps(other.files, item.files)) {
|
|
1502
|
+
counters.superseded += 1;
|
|
1503
|
+
return;
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
queue.set(item.handle, { ...item, attempts, deferrals, notBefore: backoffFrom(now(), attempts, deferrals) });
|
|
1507
|
+
enforceCap();
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
function apply(run: Run, outcomes: readonly BackgroundOutcome[]): void {
|
|
1511
|
+
const byHandle = new Map(outcomes.map(o => [o.handle, o] as const));
|
|
1512
|
+
const counted = !run.preempted;
|
|
1513
|
+
for (const item of run.items) {
|
|
1514
|
+
const outcome = byHandle.get(item.handle);
|
|
1515
|
+
if (outcome === undefined) retry(item, counted);
|
|
1516
|
+
else if (outcome.kind !== "judged") continue;
|
|
1517
|
+
else if (outcome.result.retryable) retry(item, counted);
|
|
1518
|
+
else {
|
|
1519
|
+
const notice = lateNoticeFor(item.handle, outcome.description, outcome.result);
|
|
1520
|
+
if (notice !== undefined) addNotice(run.sessionID, notice);
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
function finish(run: Run, outcomes: readonly BackgroundOutcome[]): void {
|
|
1526
|
+
try {
|
|
1527
|
+
if (!disposed && !run.cancelled) apply(run, outcomes);
|
|
1528
|
+
} finally {
|
|
1529
|
+
if (running === run) running = undefined;
|
|
1530
|
+
reschedule();
|
|
1531
|
+
run.markDone();
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
/** QA-2.4-5: foreground verification is running: the due requests back off, uncounted. */
|
|
1536
|
+
function postponeDue(at: number): void {
|
|
1537
|
+
for (const item of [...queue.values()]) {
|
|
1538
|
+
if (item.notBefore > at) continue;
|
|
1539
|
+
const deferrals = item.deferrals + 1;
|
|
1540
|
+
queue.set(item.handle, { ...item, deferrals, notBefore: backoffFrom(at, item.attempts, deferrals) });
|
|
1541
|
+
}
|
|
1542
|
+
reschedule();
|
|
1543
|
+
}
|
|
1544
|
+
|
|
1545
|
+
function foregroundBusy(): boolean {
|
|
1546
|
+
try {
|
|
1547
|
+
return options.busy?.() === true;
|
|
1548
|
+
} catch (error) {
|
|
1549
|
+
report(error);
|
|
1550
|
+
return false;
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
function runNext(): void {
|
|
1555
|
+
if (disposed || running !== undefined) return;
|
|
1556
|
+
const at = now();
|
|
1557
|
+
let first: QueuedItem | undefined;
|
|
1558
|
+
for (const item of queue.values()) {
|
|
1559
|
+
if (item.notBefore <= at && (first === undefined || item.notBefore < first.notBefore)) first = item;
|
|
1560
|
+
}
|
|
1561
|
+
if (first === undefined) {
|
|
1562
|
+
reschedule();
|
|
1563
|
+
return;
|
|
1564
|
+
}
|
|
1565
|
+
// QA-2.4-5: never start while foreground verification runs; never queue for the slot.
|
|
1566
|
+
if (foregroundBusy()) {
|
|
1567
|
+
postponeDue(at);
|
|
1568
|
+
return;
|
|
1569
|
+
}
|
|
1570
|
+
const lead = first;
|
|
1571
|
+
// One session per run (verifyHandles is session-scoped): its fresh and due requests ride along.
|
|
1572
|
+
const riders = [...queue.values()].filter(i => i !== lead && i.sessionID === lead.sessionID && (isFresh(i) || i.notBefore <= at));
|
|
1573
|
+
const items = [lead, ...riders].slice(0, MAX_HANDLES_PER_CALL);
|
|
1574
|
+
for (const item of items) queue.delete(item.handle);
|
|
1575
|
+
let markDone: () => void = () => undefined;
|
|
1576
|
+
const done = new Promise<void>(resolveDone => {
|
|
1577
|
+
markDone = resolveDone;
|
|
1578
|
+
});
|
|
1579
|
+
const run: Run = { sessionID: lead.sessionID, items, controller: new AbortController(), cancelled: false, preempted: false, done, markDone };
|
|
1580
|
+
running = run;
|
|
1581
|
+
counters.runs += 1;
|
|
1582
|
+
let outcome: Promise<readonly BackgroundOutcome[]>;
|
|
1583
|
+
try {
|
|
1584
|
+
outcome = options.verify(run.sessionID, items.map(i => i.handle), run.controller.signal);
|
|
1585
|
+
} catch (error) {
|
|
1586
|
+
outcome = Promise.reject(error);
|
|
1587
|
+
}
|
|
1588
|
+
outcome
|
|
1589
|
+
.then(
|
|
1590
|
+
outcomes => finish(run, outcomes),
|
|
1591
|
+
(error: unknown) => {
|
|
1592
|
+
report(error);
|
|
1593
|
+
finish(run, []);
|
|
1594
|
+
},
|
|
1595
|
+
)
|
|
1596
|
+
.catch(report);
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
return {
|
|
1600
|
+
enqueue(request) {
|
|
1601
|
+
if (disposed || !isNonEmptyString(request.sessionID) || !isNonEmptyString(request.handle)) return;
|
|
1602
|
+
if (queue.has(request.handle) || running?.items.some(i => i.handle === request.handle) === true) return;
|
|
1603
|
+
const files = new Set(request.files.map(pathKey));
|
|
1604
|
+
// Section 1.5-19: a newer request for an overlapping file set supersedes a queued older one.
|
|
1605
|
+
// The older entry stays unverified (and listed); it is never reported as verified.
|
|
1606
|
+
for (const other of [...queue.values()]) {
|
|
1607
|
+
if (other.sessionID === request.sessionID && overlaps(other.files, files)) {
|
|
1608
|
+
queue.delete(other.handle);
|
|
1609
|
+
counters.superseded += 1;
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
const at = now();
|
|
1613
|
+
queue.set(request.handle, { sessionID: request.sessionID, handle: request.handle, files, attempts: 0, deferrals: 0, notBefore: at + settleMs });
|
|
1614
|
+
enforceCap();
|
|
1615
|
+
if (running === undefined) arm(at + settleMs);
|
|
1616
|
+
},
|
|
1617
|
+
takeNotices(sessionID) {
|
|
1618
|
+
const list = notices.get(sessionID);
|
|
1619
|
+
if (list === undefined) return [];
|
|
1620
|
+
notices.delete(sessionID);
|
|
1621
|
+
counters.notices -= list.size;
|
|
1622
|
+
const out = [...list.values()].map(s => s.notice);
|
|
1623
|
+
for (const n of out) remember(n.handle);
|
|
1624
|
+
return out;
|
|
1625
|
+
},
|
|
1626
|
+
markReported(handles) {
|
|
1627
|
+
for (const handle of handles) {
|
|
1628
|
+
remember(handle);
|
|
1629
|
+
for (const sid of [...notices.keys()]) removeNotice(sid, handle);
|
|
1630
|
+
}
|
|
1631
|
+
},
|
|
1632
|
+
forgetSession(sessionID) {
|
|
1633
|
+
for (const item of [...queue.values()]) if (item.sessionID === sessionID) queue.delete(item.handle);
|
|
1634
|
+
const list = notices.get(sessionID);
|
|
1635
|
+
if (list !== undefined) {
|
|
1636
|
+
counters.notices -= list.size;
|
|
1637
|
+
notices.delete(sessionID);
|
|
1638
|
+
}
|
|
1639
|
+
if (running?.sessionID === sessionID) {
|
|
1640
|
+
running.cancelled = true;
|
|
1641
|
+
running.controller.abort();
|
|
1642
|
+
}
|
|
1643
|
+
reschedule();
|
|
1644
|
+
},
|
|
1645
|
+
sweep(nowMs) {
|
|
1646
|
+
const at = nowMs ?? now();
|
|
1647
|
+
let dropped = 0;
|
|
1648
|
+
for (const [sid, list] of [...notices]) {
|
|
1649
|
+
for (const [handle, stored] of [...list]) {
|
|
1650
|
+
if (at - stored.at < options.ttlMs) continue;
|
|
1651
|
+
removeNotice(sid, handle);
|
|
1652
|
+
dropped += 1;
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
reschedule();
|
|
1656
|
+
return dropped;
|
|
1657
|
+
},
|
|
1658
|
+
stats() {
|
|
1659
|
+
return {
|
|
1660
|
+
queued: queue.size,
|
|
1661
|
+
running: running !== undefined,
|
|
1662
|
+
timerArmed: timer !== undefined,
|
|
1663
|
+
notices: counters.notices,
|
|
1664
|
+
superseded: counters.superseded,
|
|
1665
|
+
runs: counters.runs,
|
|
1666
|
+
};
|
|
1667
|
+
},
|
|
1668
|
+
whenIdle() {
|
|
1669
|
+
if (disposed || isQuiet(now())) return Promise.resolve();
|
|
1670
|
+
return new Promise<void>(resolveIdle => idleWaiters.push(resolveIdle));
|
|
1671
|
+
},
|
|
1672
|
+
preempt() {
|
|
1673
|
+
const run = running;
|
|
1674
|
+
if (run === undefined) return Promise.resolve();
|
|
1675
|
+
if (!run.cancelled && !run.preempted) {
|
|
1676
|
+
run.preempted = true;
|
|
1677
|
+
run.controller.abort();
|
|
1678
|
+
}
|
|
1679
|
+
return run.done;
|
|
1680
|
+
},
|
|
1681
|
+
dispose() {
|
|
1682
|
+
if (disposed) return;
|
|
1683
|
+
disposed = true;
|
|
1684
|
+
if (timer !== undefined) {
|
|
1685
|
+
timers.clearTimeout(timer.handle);
|
|
1686
|
+
timer = undefined;
|
|
1687
|
+
}
|
|
1688
|
+
if (running !== undefined) {
|
|
1689
|
+
running.cancelled = true;
|
|
1690
|
+
running.controller.abort();
|
|
1691
|
+
}
|
|
1692
|
+
queue.clear();
|
|
1693
|
+
notices.clear();
|
|
1694
|
+
counters.notices = 0;
|
|
1695
|
+
wakeIdle();
|
|
1696
|
+
},
|
|
1697
|
+
};
|
|
1698
|
+
}
|
|
1699
|
+
|
|
1700
|
+
// ---------------------------------------------------------------------------------------------
|
|
1701
|
+
// Pure builders (R2, R9, R10, R11)
|
|
1702
|
+
// ---------------------------------------------------------------------------------------------
|
|
1703
|
+
|
|
1704
|
+
/** R2: trimmed, one pair of surrounding backticks/quotes stripped, lowercased, HANDLE_PATTERN. */
|
|
1705
|
+
export function normalizeHandle(text: string): string | undefined {
|
|
1706
|
+
let value = text.trim();
|
|
1707
|
+
const first = value.charAt(0);
|
|
1708
|
+
if (value.length >= 2 && (first === "`" || first === '"' || first === "'") && value.endsWith(first)) {
|
|
1709
|
+
value = value.slice(1, -1);
|
|
1710
|
+
}
|
|
1711
|
+
value = value.toLowerCase();
|
|
1712
|
+
return HANDLE_PATTERN.test(value) ? value : undefined;
|
|
1713
|
+
}
|
|
1714
|
+
|
|
1715
|
+
/** R9. */
|
|
1716
|
+
export function sanitizeDescription(text: string): string {
|
|
1717
|
+
const clean = sanitizeInline(text);
|
|
1718
|
+
if (clean.length === 0) return "(no description)";
|
|
1719
|
+
const points = Array.from(clean);
|
|
1720
|
+
if (points.length <= MAX_DESCRIPTION_CHARS) return clean;
|
|
1721
|
+
return points.slice(0, MAX_DESCRIPTION_CHARS - 1).join("") + "\u2026";
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
/** R10: the risk of a delegation whose changed files could not be attributed. */
|
|
1725
|
+
export function unattributedRisk(): RiskAssessment {
|
|
1726
|
+
return { level: "high", reasons: [UNATTRIBUTED_RISK_REASON] };
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1729
|
+
/** R9, section 1.5-16. */
|
|
1730
|
+
export function buildDeferredFooter(input: FooterInput): string {
|
|
1731
|
+
const risk = formatRisk(input.risk.level, input.risk.reasons, FOOTER_MAX_REASONS);
|
|
1732
|
+
return (
|
|
1733
|
+
`[router] unverified \u00b7 ${input.handle} \u00b7 ${risk}\n` +
|
|
1734
|
+
"[router] Call `router_verify` with this handle before building on this work if the risk matters."
|
|
1735
|
+
);
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
/** R9. */
|
|
1739
|
+
export function appendRouterFooter(output: string, footer: string): string {
|
|
1740
|
+
const trimmed = output.trimEnd();
|
|
1741
|
+
return trimmed.length === 0 ? footer : `${trimmed}\n\n${footer}`;
|
|
1742
|
+
}
|
|
1743
|
+
|
|
1744
|
+
/** R9, section 1.5-20. `entries` = listUnverified(sessionID), newest first. undefined when empty. */
|
|
1745
|
+
export function buildPendingListBlock(entries: readonly PendingEntry[]): string | undefined {
|
|
1746
|
+
if (entries.length === 0) return undefined;
|
|
1747
|
+
const shown = entries.slice(0, PENDING_LIST_LIMIT);
|
|
1748
|
+
// QA-2.4-3: a verified entry here is a background verdict that did not pass (listPending).
|
|
1749
|
+
const judgedOutcome = (e: PendingEntry): string | undefined => {
|
|
1750
|
+
if (e.state !== "verified" || e.result === undefined) return undefined;
|
|
1751
|
+
return e.result.verdict.outcome ?? (e.result.verdict.pass ? "pass" : "fail");
|
|
1752
|
+
};
|
|
1753
|
+
const lines = [entries.some((e) => judgedOutcome(e) !== undefined) ? PENDING_LIST_MIXED_HEADER : "[router] Unverified delegations in this session (newest first):"];
|
|
1754
|
+
for (const e of shown) {
|
|
1755
|
+
const outcome = judgedOutcome(e);
|
|
1756
|
+
const label = outcome === undefined ? "" : ` \u00b7 ${outcome} in background verification`;
|
|
1757
|
+
lines.push(`- ${e.handle}${label} \u00b7 ${formatRisk(e.risk.level, e.risk.reasons, 0)} \u00b7 ${sanitizeDescription(e.description)}`);
|
|
1758
|
+
}
|
|
1759
|
+
if (entries.length > shown.length) lines.push(`- ... and ${entries.length - shown.length} more`);
|
|
1760
|
+
lines.push(
|
|
1761
|
+
"[router] Before your final answer, call `router_verify` with the handles that matter, or with `pending: true` for all of them.",
|
|
1762
|
+
);
|
|
1763
|
+
return lines.join("\n");
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
/** R9, section 1.5-19 (background mode only; R14). undefined when empty. */
|
|
1767
|
+
export function buildLateNoticeBlock(notices: readonly LateNotice[]): string | undefined {
|
|
1768
|
+
if (notices.length === 0) return undefined;
|
|
1769
|
+
const allFailures = notices.every(n => (n.outcome ?? "fail") === "fail");
|
|
1770
|
+
const lines = [allFailures ? "[router] Background verification found introduced failures:" : LATE_NOTICE_MIXED_HEADER];
|
|
1771
|
+
for (const n of notices) {
|
|
1772
|
+
const head = `- ${n.handle} \u00b7 ${sanitizeDescription(n.description)} \u00b7 `;
|
|
1773
|
+
if ((n.outcome ?? "fail") === "unverifiable") lines.push(`${head}unverifiable: ${sanitizeDescription(n.reason ?? "no verdict")}`);
|
|
1774
|
+
else if (n.introduced.length > 0) lines.push(`${head}failing: ${formatIds(n.introduced, LATE_NOTICE_MAX_IDS)}`);
|
|
1775
|
+
else lines.push(`${head}failed: ${sanitizeDescription(n.reason ?? "no reason given")}`);
|
|
1776
|
+
}
|
|
1777
|
+
lines.push("[router] Nothing was retried; decide whether to re-dispatch.");
|
|
1778
|
+
lines.push(LATE_NOTICE_REPLAY_LINE);
|
|
1779
|
+
return lines.join("\n");
|
|
1780
|
+
}
|
|
1781
|
+
|
|
1782
|
+
/**
|
|
1783
|
+
* R14: the late notice of a background run's OWN terminal result; undefined for a pass and for a
|
|
1784
|
+
* retryable result (the entry stays unverified and listed). An unverifiable result gets a notice
|
|
1785
|
+
* too: it leaves the pending list at its settle, and silence would read like a pass. Pure.
|
|
1786
|
+
*/
|
|
1787
|
+
export function lateNoticeFor(handle: string, description: string, result: VerificationResult): LateNotice | undefined {
|
|
1788
|
+
if (result.retryable) return undefined;
|
|
1789
|
+
const verdict = result.verdict;
|
|
1790
|
+
const outcome = verdict.outcome ?? (verdict.pass ? "pass" : "fail");
|
|
1791
|
+
if (outcome === "pass") return undefined;
|
|
1792
|
+
// A drift or lineage downgrade appends its caveat last; a gate's own cause is its first reason.
|
|
1793
|
+
const reason = verdict.reasons.find(r => r.trim() !== "") ?? [...(verdict.caveats ?? [])].reverse().find(r => r.trim() !== "");
|
|
1794
|
+
return {
|
|
1795
|
+
handle,
|
|
1796
|
+
description,
|
|
1797
|
+
introduced: outcome === "fail" ? [...(result.introduced ?? [])] : [],
|
|
1798
|
+
outcome,
|
|
1799
|
+
...(reason !== undefined ? { reason } : {}),
|
|
1800
|
+
};
|
|
1801
|
+
}
|
|
1802
|
+
|
|
1803
|
+
/**
|
|
1804
|
+
* R3, section 1.5-18: paths of `before` whose digest differs in `after` (a path missing from
|
|
1805
|
+
* `after` counts as drifted), sorted. Pure.
|
|
1806
|
+
*/
|
|
1807
|
+
export function driftedPaths(before: FileDigests, after: FileDigests): string[] {
|
|
1808
|
+
const out: string[] = [];
|
|
1809
|
+
for (const [path, digest] of before) {
|
|
1810
|
+
if (after.get(path) !== digest) out.push(path);
|
|
1811
|
+
}
|
|
1812
|
+
return out.sort();
|
|
1813
|
+
}
|
|
1814
|
+
|
|
1815
|
+
/**
|
|
1816
|
+
* R11. The ledger matches by test id and root only, so the earlier change may have been reverted
|
|
1817
|
+
* since: the caveat says it "may still be present", never that it is (QA-2.4-13).
|
|
1818
|
+
*/
|
|
1819
|
+
export function buildLineageCaveat(match: LineageMatch): string {
|
|
1820
|
+
return (
|
|
1821
|
+
`${formatIds(match.ids, LATE_NOTICE_MAX_IDS)} failed after ${sanitizeInline(match.label)} in this session and still fail; ` +
|
|
1822
|
+
"that change may still be present in the reference of this delegation, so pre-existing cannot be told apart from not fixed"
|
|
1823
|
+
);
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
/** R9: the risk fragment shared by the footer and the pending list. */
|
|
1827
|
+
export function formatRisk(level: RiskLevel, reasons: readonly string[], maxReasons: number): string {
|
|
1828
|
+
const max = Math.max(0, Math.floor(maxReasons));
|
|
1829
|
+
const shown = reasons.slice(0, max).map(sanitizeInline);
|
|
1830
|
+
if (shown.length === 0) return `risk ${level}`;
|
|
1831
|
+
const rest = reasons.length - shown.length;
|
|
1832
|
+
const parts = rest > 0 ? [...shown, `+${rest} more`] : shown;
|
|
1833
|
+
return `risk ${level} (${parts.join("; ")})`;
|
|
1834
|
+
}
|