opencode-model-router 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +44 -5
  3. package/package.json +4 -1
  4. package/src/commands/output.ts +4 -1
  5. package/src/compat/child-session.ts +43 -0
  6. package/src/compat/v2-client.ts +107 -7
  7. package/src/compat/v2-hooks.ts +174 -47
  8. package/src/escalate/attempt-recorder.ts +263 -0
  9. package/src/escalate/ladder.ts +484 -10
  10. package/src/escalate/resume.ts +208 -0
  11. package/src/escalate/variants.ts +391 -0
  12. package/src/index.ts +557 -61
  13. package/src/router/build-info.ts +151 -0
  14. package/src/router/config.ts +1691 -67
  15. package/src/router/protocol.ts +47 -0
  16. package/src/router/sessions.ts +441 -9
  17. package/src/routing/advisor/findings.ts +706 -0
  18. package/src/routing/advisor/index.ts +606 -0
  19. package/src/routing/classify/backends/host.ts +163 -0
  20. package/src/routing/classify/backends/openai-compatible.ts +275 -0
  21. package/src/routing/classify/backends/shared.ts +741 -0
  22. package/src/routing/classify/backends/typesafe.ts +315 -0
  23. package/src/routing/classify/fences.ts +96 -0
  24. package/src/routing/classify/index.ts +576 -0
  25. package/src/routing/classify/route-line.ts +298 -0
  26. package/src/routing/classify/rules.ts +607 -0
  27. package/src/routing/classify/scrub.ts +214 -0
  28. package/src/routing/classify/state.ts +148 -0
  29. package/src/routing/classify/text.ts +20 -0
  30. package/src/routing/classify/types.ts +1280 -0
  31. package/src/routing/commands/annotate-plan.ts +652 -0
  32. package/src/routing/commands/stats.ts +131 -0
  33. package/src/routing/commands/v1-roles.ts +64 -0
  34. package/src/routing/engine/index.ts +32 -0
  35. package/src/routing/engine/kernel.ts +597 -0
  36. package/src/routing/engine/ladders.ts +561 -0
  37. package/src/routing/engine/plan.ts +404 -0
  38. package/src/routing/engine/protocol-line.ts +133 -0
  39. package/src/routing/engine/simulate.ts +167 -0
  40. package/src/routing/engine/types.ts +270 -0
  41. package/src/routing/file-lock.ts +53 -0
  42. package/src/routing/outcomes/beta.ts +141 -0
  43. package/src/routing/outcomes/cost.ts +313 -0
  44. package/src/routing/outcomes/index.ts +172 -0
  45. package/src/routing/outcomes/ingest.ts +812 -0
  46. package/src/routing/outcomes/persist.ts +1058 -0
  47. package/src/routing/outcomes/stats.ts +602 -0
  48. package/src/routing/outcomes/store.ts +653 -0
  49. package/src/routing/outcomes/types.ts +954 -0
  50. package/src/routing/wire/dispatch.ts +799 -0
  51. package/src/routing/wire/hint.ts +208 -0
  52. package/src/routing/wire/host-info.ts +256 -0
  53. package/src/routing/wire/runtime.ts +259 -0
  54. package/src/v2.ts +15 -1
  55. package/tiers.json +43 -0
@@ -0,0 +1,1058 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Persistence (M3): atomic outcomes.json, rotating decisions.jsonl, coalescing flusher (D15, A3).
3
+ //
4
+ // Design: docs/qa/cost-aware-routing/phase-1.3.md "Design (1.3.1)" §5.
5
+ // The only module of src/routing/outcomes/ that touches disk, and only through the injected PersistFs.
6
+ // The clock, the sleep function and the timers are injected too. It never opens, lists for processing,
7
+ // renames or deletes a `*.scorecard.log` file (it filters readdir by its own names).
8
+ // Runnable under Node type stripping (type-only imports use `import type`).
9
+ // ---------------------------------------------------------------------------
10
+
11
+ import { appendFile, mkdir, open, readFile, readdir, rename, stat, unlink } from "node:fs/promises";
12
+ import { isAbsolute, join, normalize, resolve } from "node:path";
13
+ import type {
14
+ DecisionRow,
15
+ DecisionTrace,
16
+ FlusherDeps,
17
+ ForeignCheck,
18
+ FlusherOptions,
19
+ FlushScheduler,
20
+ LoadResult,
21
+ LoadStatus,
22
+ LogRow,
23
+ OutcomeFlusher,
24
+ OutcomeLogger,
25
+ OutcomeKey,
26
+ OutcomeSnapshot,
27
+ OutcomeStore,
28
+ OutcomesFile,
29
+ PersistDeps,
30
+ PersistFs,
31
+ PersistStat,
32
+ Persister,
33
+ PersisterOptions,
34
+ ReadRowsResult,
35
+ RefusalRow,
36
+ RouteChoice,
37
+ VerdictRow,
38
+ WriteResult,
39
+ } from "./types";
40
+ import {
41
+ DECISIONS_FILE,
42
+ DECISIONS_MAX_BYTES,
43
+ DECISIONS_MAX_GENERATIONS,
44
+ DECISIONS_ROTATED_RE,
45
+ DEFAULT_OUTCOMES_DIRNAME,
46
+ FLUSH_BATCH_ROWS,
47
+ FLUSH_MIN_INTERVAL_MS,
48
+ LADDER_STEP_KINDS,
49
+ LOG_ROW_VERSION,
50
+ MAX_QUEUED_ROWS,
51
+ MAX_CORRUPT_COPIES,
52
+ OUTCOMES_CORRUPT_PREFIX,
53
+ OUTCOMES_CORRUPT_RE,
54
+ OUTCOMES_FILE,
55
+ OUTCOMES_SCHEMA_ID,
56
+ OUTCOMES_SCHEMA_VERSION,
57
+ OUTCOMES_TMP_PREFIX,
58
+ RENAME_RETRY_DELAYS_MS,
59
+ STALE_TMP_MS,
60
+ parseKey,
61
+ safeNow,
62
+ } from "./types";
63
+ import { parseSnapshot } from "./store";
64
+ import { withLock } from "../file-lock";
65
+
66
+ // ---------------------------------------------------------------------------
67
+ // Small helpers
68
+ // ---------------------------------------------------------------------------
69
+
70
+ type Rec = Record<string, unknown>;
71
+
72
+ function isRec(x: unknown): x is Rec {
73
+ return typeof x === "object" && x !== null && !Array.isArray(x);
74
+ }
75
+
76
+ function isFiniteNum(x: unknown): x is number {
77
+ return typeof x === "number" && Number.isFinite(x);
78
+ }
79
+
80
+ function errorCode(error: unknown): string | undefined {
81
+ if (typeof error === "object" && error !== null && "code" in error) {
82
+ const code = (error as { code?: unknown }).code;
83
+ if (typeof code === "string") return code;
84
+ }
85
+ return undefined;
86
+ }
87
+
88
+ function describeError(error: unknown): string {
89
+ return error instanceof Error ? error.message : String(error);
90
+ }
91
+
92
+ function failure(error: unknown): WriteResult {
93
+ const code = errorCode(error);
94
+ return { ok: false, error: describeError(error), ...(code !== undefined ? { code } : {}) };
95
+ }
96
+
97
+ function emptySnapshot(): OutcomeSnapshot {
98
+ return { version: OUTCOMES_SCHEMA_VERSION, entries: {} };
99
+ }
100
+
101
+ // ---------------------------------------------------------------------------
102
+ // Directory resolution
103
+ // ---------------------------------------------------------------------------
104
+
105
+ /**
106
+ * `routing.outcomes.path` is a **directory** holding both files. Unset or blank → the scorecard
107
+ * directory (`<tmpdir>/opencode-model-router-trajectory`). A leading `~` resolves against `homedir`, an
108
+ * absolute path is normalised, and a relative path resolves against the default directory (never the
109
+ * process cwd).
110
+ */
111
+ export function resolveOutcomesDir(
112
+ configured: string | null | undefined,
113
+ env: { readonly tmpdir: string; readonly homedir: string },
114
+ ): string {
115
+ const fallback = join(env.tmpdir, DEFAULT_OUTCOMES_DIRNAME);
116
+ const raw = typeof configured === "string" ? configured.trim() : "";
117
+ if (raw === "") return fallback;
118
+ if (raw === "~") return normalize(env.homedir);
119
+ if (raw.startsWith("~/") || raw.startsWith("~\\")) return join(env.homedir, raw.slice(2));
120
+ if (isAbsolute(raw)) return normalize(raw);
121
+ return join(fallback, raw);
122
+ }
123
+
124
+ // ---------------------------------------------------------------------------
125
+ // Node implementations of the injected dependencies
126
+ // ---------------------------------------------------------------------------
127
+
128
+ export function nodePersistFs(): PersistFs {
129
+ return {
130
+ async createExclusive(path, data) {
131
+ let handle;
132
+ try { handle = await open(path, "wx"); } catch (error) {
133
+ if (errorCode(error) === "EEXIST") return false;
134
+ throw error;
135
+ }
136
+ try { await handle.writeFile(data, "utf8"); } finally { await handle.close(); }
137
+ return true;
138
+ },
139
+ async mkdirp(dir: string): Promise<void> {
140
+ await mkdir(dir, { recursive: true });
141
+ },
142
+ async readText(path: string): Promise<string | null> {
143
+ try {
144
+ return await readFile(path, "utf8");
145
+ } catch (error) {
146
+ if (errorCode(error) === "ENOENT") return null;
147
+ throw error;
148
+ }
149
+ },
150
+ async writeDurable(path: string, data: string): Promise<void> {
151
+ const handle = await open(path, "w");
152
+ try {
153
+ await handle.writeFile(data, "utf8");
154
+ await handle.sync();
155
+ } finally {
156
+ await handle.close();
157
+ }
158
+ },
159
+ async appendText(path: string, data: string): Promise<void> {
160
+ await appendFile(path, data, "utf8");
161
+ },
162
+ async rename(from: string, to: string): Promise<void> {
163
+ await rename(from, to);
164
+ },
165
+ async unlink(path: string): Promise<void> {
166
+ try {
167
+ await unlink(path);
168
+ } catch (error) {
169
+ if (errorCode(error) !== "ENOENT") throw error;
170
+ }
171
+ },
172
+ async stat(path: string): Promise<(PersistStat & { readonly mode: number }) | null> {
173
+ try {
174
+ const s = await stat(path);
175
+ return { size: s.size, mtimeMs: s.mtimeMs, mode: s.mode };
176
+ } catch (error) {
177
+ if (errorCode(error) === "ENOENT") return null;
178
+ throw error;
179
+ }
180
+ },
181
+ async readdir(dir: string): Promise<string[]> {
182
+ try {
183
+ return await readdir(dir);
184
+ } catch (error) {
185
+ if (errorCode(error) === "ENOENT") return [];
186
+ throw error;
187
+ }
188
+ },
189
+ };
190
+ }
191
+
192
+ /** `setTimeout` with `.unref()`: a pending flush never keeps the process alive. */
193
+ export function nodeScheduler(): FlushScheduler {
194
+ return {
195
+ setTimer(fn: () => void, ms: number): unknown {
196
+ const handle = setTimeout(fn, ms);
197
+ handle.unref();
198
+ return handle;
199
+ },
200
+ clearTimer(handle: unknown): void {
201
+ clearTimeout(handle as ReturnType<typeof setTimeout>);
202
+ },
203
+ };
204
+ }
205
+
206
+ export function nodePersistDeps(logger: OutcomeLogger): PersistDeps {
207
+ return {
208
+ fs: nodePersistFs(),
209
+ now: Date.now,
210
+ sleep: (ms: number) => new Promise<void>((done) => setTimeout(done, ms)),
211
+ logger,
212
+ pid: process.pid,
213
+ };
214
+ }
215
+
216
+ // ---------------------------------------------------------------------------
217
+ // Windows-safe rename
218
+ // ---------------------------------------------------------------------------
219
+
220
+ const RETRYABLE_CODES: ReadonlySet<string> = new Set(["EPERM", "EBUSY", "EACCES"]);
221
+
222
+ async function withRetry<T>(
223
+ operation: () => Promise<T>,
224
+ sleep: (ms: number) => Promise<void>,
225
+ delays: readonly number[],
226
+ ): Promise<T> {
227
+ for (let attempt = 0; ; attempt++) {
228
+ try {
229
+ return await operation();
230
+ } catch (error) {
231
+ const code = errorCode(error);
232
+ if (code === undefined || !RETRYABLE_CODES.has(code) || attempt >= delays.length) throw error;
233
+ await sleep(delays[attempt] as number);
234
+ }
235
+ }
236
+ }
237
+
238
+ /**
239
+ * `rename` that survives Windows sharing violations: `EPERM`/`EBUSY`/`EACCES` (the target or source is
240
+ * held open by an antivirus, an indexer, a reader or another instance) are retried after each delay of
241
+ * `delays`; any other code, or exhausted retries, is thrown. Always off the hot path.
242
+ */
243
+ export async function renameWithRetry(
244
+ fs: Pick<PersistFs, "rename">,
245
+ from: string,
246
+ to: string,
247
+ sleep: (ms: number) => Promise<void>,
248
+ delays: readonly number[] = RENAME_RETRY_DELAYS_MS,
249
+ ): Promise<void> {
250
+ await withRetry(() => fs.rename(from, to), sleep, delays);
251
+ }
252
+
253
+ // ---------------------------------------------------------------------------
254
+ // Decision-log rows
255
+ // ---------------------------------------------------------------------------
256
+
257
+ const LOGGED_MODES: readonly string[] = ["shadow", "advise", "enforce"];
258
+ const COST_UNITS: readonly string[] = ["usd", "ratio"];
259
+ const VERDICT_VALUES: readonly string[] = ["pass", "fail", "unverifiable"];
260
+
261
+ function isOutcomeKey(x: unknown): x is OutcomeKey {
262
+ return typeof x === "string" && parseKey(x) !== null;
263
+ }
264
+
265
+ function oneOf(list: readonly string[], x: unknown): x is string {
266
+ return typeof x === "string" && list.includes(x);
267
+ }
268
+
269
+ function readChoice(x: unknown): RouteChoice | null {
270
+ if (!isRec(x)) return null;
271
+ const { key, agent, origin, model, variant } = x;
272
+ if (!isOutcomeKey(key) || typeof agent !== "string" || typeof model !== "string" || typeof variant !== "string") return null;
273
+ if (origin !== "router" && origin !== "host") return null;
274
+ return { key, agent, origin, model, variant };
275
+ }
276
+
277
+ /** A trace is optional and cosmetic: a malformed one is dropped, never a reason to lose the row. */
278
+ function readTrace(x: unknown): DecisionTrace | undefined {
279
+ if (!isRec(x) || !isRec(x.routeLines)) return undefined;
280
+ const { count, conflict, edgeOnly } = x.routeLines;
281
+ if (!isFiniteNum(count) || typeof conflict !== "boolean" || typeof edgeOnly !== "boolean") return undefined;
282
+ let backend: DecisionTrace["backend"] = null;
283
+ if (x.backend !== null && x.backend !== undefined) {
284
+ const b = x.backend;
285
+ if (!isRec(b) || typeof b.id !== "string" || typeof b.status !== "string" || !isFiniteNum(b.latencyMs)) return undefined;
286
+ backend = {
287
+ id: b.id,
288
+ status: b.status,
289
+ latencyMs: b.latencyMs,
290
+ ...(typeof b.label === "string" ? { label: b.label } : {}),
291
+ ...(b.rejected === true ? { rejected: true as const } : {}),
292
+ ...(b.disagrees === true ? { disagrees: true as const } : {}),
293
+ };
294
+ }
295
+ const argmin = readChoice(x.argmin);
296
+ return {
297
+ routeLines: { count, conflict, edgeOnly },
298
+ backend,
299
+ ...(x.backendSkipped === "credentials" ? { backendSkipped: "credentials" as const } : {}),
300
+ ...(argmin === null ? {} : { argmin }),
301
+ };
302
+ }
303
+ function readLadderStep(x: unknown): (typeof LADDER_STEP_KINDS)[number] | null {
304
+ return LADDER_STEP_KINDS.find((kind) => kind === x) ?? null;
305
+ }
306
+
307
+ /**
308
+ * Validate one JSONL line. A valid row comes back as a clean copy (unknown extra fields are ignored,
309
+ * forward-compatible within v1; non-finite `costs` entries are dropped); anything else is `null`.
310
+ */
311
+ export function parseLogLine(line: string): LogRow | null {
312
+ let json: unknown;
313
+ try {
314
+ json = JSON.parse(line);
315
+ } catch {
316
+ return null;
317
+ }
318
+ if (!isRec(json) || json.v !== LOG_ROW_VERSION) return null;
319
+ const { kind, ts, sessionID } = json;
320
+ if (typeof ts !== "string" || !Number.isFinite(Date.parse(ts)) || typeof sessionID !== "string") return null;
321
+ const step = readLadderStep(json.step);
322
+ if (step === null) return null;
323
+
324
+ if (kind === "verdict" || kind === "refusal") {
325
+ const { decisionID, childSessionID, attemptID, key } = json;
326
+ if (decisionID !== null && typeof decisionID !== "string") return null;
327
+ if (typeof childSessionID !== "string" || typeof attemptID !== "string" || !isOutcomeKey(key)) return null;
328
+ if (kind === "refusal") {
329
+ const row: RefusalRow = {
330
+ v: LOG_ROW_VERSION, kind, ts, sessionID, decisionID, childSessionID, attemptID, key, step,
331
+ ...(json.overrides === "pass" ? { overrides: "pass" as const } : {}),
332
+ };
333
+ return row;
334
+ }
335
+ const verdict = json.verdict;
336
+ if (!oneOf(VERDICT_VALUES, verdict)) return null;
337
+ const row: VerdictRow = {
338
+ v: LOG_ROW_VERSION,
339
+ kind,
340
+ ts,
341
+ sessionID,
342
+ decisionID,
343
+ childSessionID,
344
+ attemptID,
345
+ key,
346
+ verdict: verdict as VerdictRow["verdict"],
347
+ step,
348
+ };
349
+ return row;
350
+ }
351
+
352
+ if (kind !== "decision") return null;
353
+ const { decisionID, mode, childSessionID, facts, switched, pinned, unit, costs, confidence, reason, resume } = json;
354
+ if (typeof decisionID !== "string" || !oneOf(LOGGED_MODES, mode) || !oneOf(COST_UNITS, unit)) return null;
355
+ if (childSessionID !== null && typeof childSessionID !== "string") return null;
356
+ if (typeof switched !== "boolean" || typeof pinned !== "boolean" || typeof resume !== "boolean") return null;
357
+ if (!isFiniteNum(confidence) || typeof reason !== "string") return null;
358
+
359
+ if (!isRec(facts)) return null;
360
+ const { class: cls, risk, scope, needs, confidence: factsConfidence, source } = facts;
361
+ if (typeof cls !== "string" || typeof risk !== "string" || typeof scope !== "string" || typeof source !== "string") return null;
362
+ if (!Array.isArray(needs) || !needs.every((n): n is string => typeof n === "string")) return null;
363
+ if (!isFiniteNum(factsConfidence)) return null;
364
+
365
+ const chosen = readChoice(json.chosen);
366
+ if (chosen === null) return null;
367
+ const best = json.best === null ? null : readChoice(json.best);
368
+ if (json.best !== null && best === null) return null;
369
+
370
+ if (!isRec(costs)) return null;
371
+ const cleanCosts: Record<string, number> = Object.fromEntries(
372
+ Object.entries(costs).filter((entry): entry is [string, number] => isFiniteNum(entry[1])),
373
+ );
374
+
375
+ const trace = readTrace(json.trace);
376
+ const isDetection = (value: unknown): value is "none" | "grader" | "deterministic" =>
377
+ value === "none" || value === "grader" || value === "deterministic";
378
+ const detection = isRec(json.detection) && isDetection(json.detection.effective)
379
+ ? { effective: json.detection.effective, ...(isDetection(json.detection.claimed) ? { claimed: json.detection.claimed } : {}) }
380
+ : undefined;
381
+ const capability = isRec(json.capability)
382
+ && (json.capability.pick === null || isFiniteNum(json.capability.pick))
383
+ && (json.capability.dispatched === null || isFiniteNum(json.capability.dispatched))
384
+ ? { pick: json.capability.pick, dispatched: json.capability.dispatched }
385
+ : undefined;
386
+ const row: DecisionRow = {
387
+ v: LOG_ROW_VERSION,
388
+ kind,
389
+ ts,
390
+ sessionID,
391
+ decisionID,
392
+ mode: mode as DecisionRow["mode"],
393
+ childSessionID,
394
+ facts: { class: cls, risk, scope, needs: [...needs], confidence: factsConfidence, source },
395
+ chosen,
396
+ best,
397
+ switched,
398
+ pinned,
399
+ unit: unit as DecisionRow["unit"],
400
+ costs: cleanCosts,
401
+ confidence,
402
+ reason,
403
+ step,
404
+ resume,
405
+ ...(trace === undefined ? {} : { trace }),
406
+ ...(detection === undefined ? {} : { detection }),
407
+ ...(capability === undefined ? {} : { capability }),
408
+ };
409
+ return row;
410
+ }
411
+
412
+ /** `20261006T120000123Z` for the rotated generation names (`DECISIONS_ROTATED_RE`). */
413
+ export function compactStamp(ms: number): string {
414
+ return new Date(ms).toISOString().replace(/[-:.]/g, "");
415
+ }
416
+
417
+ function stampToMs(stamp: string): number | null {
418
+ const m = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(\d{3})Z$/.exec(stamp);
419
+ if (m === null) return null;
420
+ const [, y, mo, d, h, mi, s, ms] = m.map(Number) as [number, number, number, number, number, number, number, number];
421
+ return Date.UTC(y, mo - 1, d, h, mi, s, ms);
422
+ }
423
+
424
+ function rotatedNames(names: readonly string[]): string[] {
425
+ return names.filter((name) => DECISIONS_ROTATED_RE.test(name)).sort();
426
+ }
427
+
428
+ // ---------------------------------------------------------------------------
429
+ // Persister
430
+ // ---------------------------------------------------------------------------
431
+
432
+ export function createPersister(dir: string, deps: PersistDeps, options: PersisterOptions = {}): Persister {
433
+ const { fs, sleep, logger, pid } = deps;
434
+ const now = (): number => safeNow(deps.now);
435
+ const outcomesPath = join(dir, OUTCOMES_FILE);
436
+ const decisionsPath = join(dir, DECISIONS_FILE);
437
+ const maxBytes = options.maxBytes ?? DECISIONS_MAX_BYTES;
438
+ const maxGenerations = Math.max(0, Math.floor(options.maxGenerations ?? DECISIONS_MAX_GENERATIONS));
439
+ const delays = options.renameRetryDelaysMs ?? RENAME_RETRY_DELAYS_MS;
440
+
441
+ let seq = 0;
442
+ /** Set when the file on disk must not be overwritten (newer schema, or unreadable). */
443
+ let readOnlyReason: string | null = null;
444
+ /** mtime of outcomes.json at the last load/save; `undefined` until the first load (no foreign-writer check). */
445
+ let lastKnownMtime: number | null | undefined;
446
+ let warnedForeignWriter = false;
447
+ let warnedMerge = false;
448
+ /** Size of decisions.jsonl right after this persister's last append (a file that ends with a newline); `null` = not appended yet. */
449
+ let knownEnd: number | null = null;
450
+ /** What this persister last loaded or wrote: the base for `disk − baseline` when another process writes (QA-1.3-4). */
451
+ let baseline: OutcomeSnapshot | undefined;
452
+
453
+ async function statOrNull(path: string): Promise<PersistStat | null> {
454
+ try {
455
+ return await fs.stat(path);
456
+ } catch (error) {
457
+ logger.info?.("[router] outcome store stat failed", { path, error: describeError(error) });
458
+ return null;
459
+ }
460
+ }
461
+
462
+ async function cleanStaleTemps(): Promise<void> {
463
+ try {
464
+ const t = now();
465
+ for (const name of await fs.readdir(dir)) {
466
+ if (!name.startsWith(OUTCOMES_TMP_PREFIX)) continue;
467
+ const path = join(dir, name);
468
+ try {
469
+ const st = await fs.stat(path);
470
+ if (st !== null && t - st.mtimeMs > STALE_TMP_MS) await fs.unlink(path);
471
+ } catch (error) {
472
+ logger.info?.("[router] stale outcome temp file not removed", { path, error: describeError(error) });
473
+ }
474
+ }
475
+ } catch (error) {
476
+ logger.info?.("[router] outcome temp cleanup skipped", { dir, error: describeError(error) });
477
+ }
478
+ }
479
+
480
+ function loadResult(
481
+ status: LoadStatus,
482
+ message: string | null,
483
+ snapshot: OutcomeSnapshot = emptySnapshot(),
484
+ dropped = 0,
485
+ savedAt: string | null = null,
486
+ ): LoadResult {
487
+ return { status, snapshot, dropped, savedAt, message };
488
+ }
489
+
490
+ async function loadInner(quarantine: boolean): Promise<LoadResult> {
491
+ readOnlyReason = null;
492
+ const absPath = resolve(outcomesPath);
493
+ let result: LoadResult;
494
+ let text: string | null;
495
+ try {
496
+ text = await withRetry(() => fs.readText(outcomesPath), sleep, delays);
497
+ } catch (error) {
498
+ // Something exists but cannot be read: never overwrite it blindly.
499
+ readOnlyReason = `outcome store at ${absPath} is unreadable`;
500
+ const reason = describeError(error);
501
+ logger.warn("[router] outcome store unreadable; persistence disabled for this process", { path: outcomesPath, reason });
502
+ return loadResult("corrupt", `${absPath}: cannot read (${reason})`);
503
+ }
504
+
505
+ if (text === null) {
506
+ result = loadResult("missing", null);
507
+ } else {
508
+ let json: unknown;
509
+ let parseError: string | null = null;
510
+ try {
511
+ json = JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text); // a UTF-8 BOM is tolerated
512
+ } catch (error) {
513
+ parseError = `invalid JSON: ${describeError(error)}`;
514
+ }
515
+ const parsed = parseError === null ? parseSnapshot(json) : null;
516
+
517
+ if (parsed !== null && parsed.ok) {
518
+ const savedAt = isRec(json) && typeof json.savedAt === "string" ? json.savedAt : null;
519
+ let message: string | null = null;
520
+ if (parsed.dropped > 0) {
521
+ message = `${absPath}: ${parsed.dropped} invalid ${parsed.dropped === 1 ? "entry" : "entries"} dropped`;
522
+ logger.warn("[router] outcome store had invalid entries; they were dropped", { path: outcomesPath, dropped: parsed.dropped });
523
+ }
524
+ result = loadResult("ok", message, parsed.snapshot, parsed.dropped, savedAt);
525
+ } else if (parsed !== null && parsed.reason === "unsupported-version") {
526
+ readOnlyReason = parsed.message.startsWith("unsupported outcome store version")
527
+ ? "unsupported outcome store version on disk"
528
+ : "unrecognized outcome store on disk";
529
+ logger.warn("[router] outcome store is not a version-1 file of this plugin; leaving it untouched", {
530
+ path: outcomesPath,
531
+ reason: parsed.message,
532
+ });
533
+ result = loadResult("unsupported-version", `${absPath}: ${parsed.message}`);
534
+ } else {
535
+ const reason = parseError ?? (parsed !== null && !parsed.ok ? parsed.message : "unknown error");
536
+ if (quarantine) await quarantineCorrupt();
537
+ logger.warn("[router] outcome store corrupted; starting fresh", { path: outcomesPath, reason });
538
+ result = loadResult("corrupt", `${absPath}: ${reason}`);
539
+ }
540
+ }
541
+
542
+ baseline = result.snapshot;
543
+ lastKnownMtime = (await statOrNull(outcomesPath))?.mtimeMs ?? null;
544
+ if (quarantine) await cleanStaleTemps();
545
+ return result;
546
+ }
547
+
548
+ /** Move the unparseable/malformed store aside under a unique name and keep only the newest few copies. */
549
+ async function quarantineCorrupt(): Promise<void> {
550
+ try {
551
+ let ms = now();
552
+ const newest = (await fs.readdir(dir)).filter((name) => OUTCOMES_CORRUPT_RE.test(name)).sort().at(-1);
553
+ const newestMs = newest === undefined ? null : stampToMs((OUTCOMES_CORRUPT_RE.exec(newest) ?? [])[1] ?? "");
554
+ if (newestMs !== null && ms <= newestMs) ms = newestMs + 1; // strictly newer than every kept copy, so pruning drops the oldest
555
+ let moved = false;
556
+ for (let attempt = 0; attempt < 20 && !moved; attempt++) {
557
+ const target = join(dir, `${OUTCOMES_CORRUPT_PREFIX}${compactStamp(ms)}-${pid}.json`);
558
+ if ((await statOrNull(target)) === null) {
559
+ await renameWithRetry(fs, outcomesPath, target, sleep, delays);
560
+ moved = true;
561
+ } else {
562
+ ms += 1;
563
+ }
564
+ }
565
+ if (!moved) throw new Error("no free quarantine file name");
566
+ const copies = (await fs.readdir(dir)).filter((name) => OUTCOMES_CORRUPT_RE.test(name)).sort();
567
+ for (const name of copies.slice(0, Math.max(0, copies.length - MAX_CORRUPT_COPIES))) {
568
+ try {
569
+ await fs.unlink(join(dir, name));
570
+ } catch (error) {
571
+ logger.info?.("[router] old quarantined outcome store not removed", { name, error: describeError(error) });
572
+ }
573
+ }
574
+ } catch (error) {
575
+ logger.warn("[router] could not quarantine the corrupt outcome store; the next save overwrites it", {
576
+ path: outcomesPath,
577
+ error: describeError(error),
578
+ });
579
+ }
580
+ }
581
+
582
+ async function checkForeignWriter(): Promise<void> {
583
+ if (lastKnownMtime === undefined || warnedForeignWriter) return;
584
+ const current = (await statOrNull(outcomesPath))?.mtimeMs ?? null;
585
+ if (current !== lastKnownMtime) {
586
+ warnedForeignWriter = true;
587
+ logger.warn("[router] another process wrote outcomes.json; the last writer wins", { path: outcomesPath });
588
+ }
589
+ }
590
+
591
+ async function rotate(): Promise<void> {
592
+ try {
593
+ let ms = now();
594
+ const newest = rotatedNames(await fs.readdir(dir)).at(-1);
595
+ const match = newest === undefined ? null : DECISIONS_ROTATED_RE.exec(newest);
596
+ const newestMs = match === null ? null : stampToMs(match[1] as string);
597
+ if (newestMs !== null && ms <= newestMs) ms = newestMs + 1; // names stay unique and chronological
598
+ const target = join(dir, `decisions.${compactStamp(ms)}-${pid}.jsonl`);
599
+ try {
600
+ // Another process may have rotated while we listed generations. Do not rotate its small new file.
601
+ const current = await fs.stat(decisionsPath);
602
+ if (current === null || current.size < maxBytes) return;
603
+ await renameWithRetry(fs, decisionsPath, target, sleep, delays);
604
+ } catch (error) {
605
+ if (errorCode(error) !== "ENOENT") throw error; // ENOENT: another process rotated first
606
+ }
607
+ const generations = rotatedNames(await fs.readdir(dir));
608
+ for (const name of generations.slice(0, Math.max(0, generations.length - maxGenerations))) {
609
+ try {
610
+ await fs.unlink(join(dir, name));
611
+ } catch (error) {
612
+ logger.warn("[router] could not prune a rotated decision log", { name, error: describeError(error) });
613
+ }
614
+ }
615
+ } catch (error) {
616
+ logger.warn("[router] decision log rotation failed; appending to the live file", { error: describeError(error) });
617
+ }
618
+ }
619
+
620
+ return {
621
+ dir,
622
+ outcomesPath,
623
+ decisionsPath,
624
+
625
+ async withSnapshotLock(run): Promise<boolean> {
626
+ const result = await withLock(fs, dir, `${outcomesPath}.lock`, now, logger, run);
627
+ return result.status === "ran";
628
+ },
629
+
630
+ async load(opts?: { readonly quarantine?: boolean }): Promise<LoadResult> {
631
+ try {
632
+ return await loadInner(opts?.quarantine ?? true);
633
+ } catch (error) {
634
+ const reason = describeError(error);
635
+ readOnlyReason = `outcome store at ${resolve(outcomesPath)} failed to load`;
636
+ logger.warn("[router] outcome store failed to load; persistence disabled for this process", { path: outcomesPath, reason });
637
+ return loadResult("corrupt", `${resolve(outcomesPath)}: ${reason}`);
638
+ }
639
+ },
640
+
641
+ async saveSnapshot(snapshot: OutcomeSnapshot): Promise<WriteResult> {
642
+ if (readOnlyReason !== null) return { ok: false, error: readOnlyReason, readOnly: true };
643
+ const tmp = join(dir, `${OUTCOMES_TMP_PREFIX}${pid}-${++seq}`);
644
+ try {
645
+ await fs.mkdirp(dir);
646
+ await checkForeignWriter();
647
+ const file: OutcomesFile = {
648
+ schema: OUTCOMES_SCHEMA_ID,
649
+ version: OUTCOMES_SCHEMA_VERSION,
650
+ savedAt: new Date(now()).toISOString(),
651
+ entries: snapshot.entries,
652
+ };
653
+ await fs.writeDurable(tmp, JSON.stringify(file, null, 2) + "\n");
654
+ await renameWithRetry(fs, tmp, outcomesPath, sleep, delays);
655
+ baseline = snapshot;
656
+ lastKnownMtime = (await statOrNull(outcomesPath))?.mtimeMs ?? null;
657
+ return { ok: true };
658
+ } catch (error) {
659
+ try {
660
+ await fs.unlink(tmp);
661
+ } catch (cleanupError) {
662
+ logger.info?.("[router] outcome temp file not removed", { tmp, error: describeError(cleanupError) });
663
+ }
664
+ // Exhausted Windows rename retries may mean a read-only target, not a transient sharing violation.
665
+ // Node stat exposes its mode; injected filesystems without that evidence remain retryable.
666
+ if (errorCode(error) === "EPERM") {
667
+ const target = await statOrNull(outcomesPath);
668
+ if (target !== null && "mode" in target && typeof target.mode === "number" && (target.mode & 0o222) === 0) {
669
+ readOnlyReason = `outcome store at ${resolve(outcomesPath)} is read-only (EPERM)`;
670
+ return { ok: false, code: "EPERM", error: readOnlyReason, readOnly: true };
671
+ }
672
+ }
673
+ return failure(error);
674
+ }
675
+ },
676
+
677
+ async appendRows(rows: readonly LogRow[]): Promise<WriteResult> {
678
+ if (rows.length === 0) return { ok: true };
679
+ try {
680
+ await fs.mkdirp(dir);
681
+ const body = rows.map((row) => JSON.stringify(row)).join("\n") + "\n";
682
+ let size = (await statOrNull(decisionsPath))?.size ?? 0;
683
+ if (size > 0 && size + Buffer.byteLength(body, "utf8") + 1 > maxBytes) {
684
+ await rotate();
685
+ size = (await statOrNull(decisionsPath))?.size ?? 0;
686
+ }
687
+ // QA-1.3-9: a crash can leave a torn last line without its newline; a batch that follows one starts on a fresh
688
+ // line, so the next row is not glued to the fragment (readRows skips the torn line). QA-2.4-R2-10: only then. A file
689
+ // that ends with a newline (every batch of this process does) takes the batch as it is, with no blank line between
690
+ // batches. The end of the file is only looked at when it is not where this process' last append left it: its first
691
+ // batch, or another process wrote since.
692
+ let lead = "";
693
+ if (size > 0 && size !== knownEnd) {
694
+ try {
695
+ const existing = await fs.readText(decisionsPath);
696
+ if (existing !== null && !existing.endsWith("\n")) lead = "\n";
697
+ } catch (readError) {
698
+ lead = "\n"; // cannot tell: a blank line is harmless, a glued row is not
699
+ logger.info?.("[router] decisions log end not checked", { error: describeError(readError) });
700
+ }
701
+ }
702
+ await fs.appendText(decisionsPath, lead + body);
703
+ knownEnd = size + Buffer.byteLength(lead + body, "utf8");
704
+ return { ok: true };
705
+ } catch (error) {
706
+ return failure(error);
707
+ }
708
+ },
709
+
710
+ async readForeignWrites(force = false): Promise<ForeignCheck> {
711
+ try {
712
+ if (readOnlyReason !== null || lastKnownMtime === undefined) return { status: "unchanged" };
713
+ // Strict stat/read: a failure here is "we do not know what is on disk", never "nothing changed".
714
+ const st = await fs.stat(outcomesPath);
715
+ const current = st?.mtimeMs ?? null;
716
+ if (!force && current === lastKnownMtime) return { status: "unchanged" };
717
+ if (current === null) {
718
+ lastKnownMtime = null; // removed: the next save recreates it (its entries are then a new lineage, QA-1.3-16)
719
+ return { status: "unchanged" };
720
+ }
721
+ const text = await withRetry(() => fs.readText(outcomesPath), sleep, delays);
722
+ if (text === null) {
723
+ lastKnownMtime = null; // vanished between the stat and the read
724
+ return { status: "unchanged" };
725
+ }
726
+ let json: unknown;
727
+ let unparseable: string | null = null;
728
+ try {
729
+ json = JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
730
+ } catch (error) {
731
+ unparseable = `invalid JSON: ${describeError(error)}`;
732
+ }
733
+ const parsed = unparseable === null ? parseSnapshot(json) : null;
734
+ if (parsed !== null && parsed.ok) {
735
+ // Filesystems can give two distinct writes the same mtime. Under the lock compare content too.
736
+ if (current === lastKnownMtime && JSON.stringify(parsed.snapshot) === JSON.stringify(baseline)) {
737
+ return { status: "unchanged" };
738
+ }
739
+ // Only a successfully parsed file counts as "seen" (QA-1.3-18): the mtime is recorded here, not before.
740
+ const previous = baseline ?? emptySnapshot();
741
+ baseline = parsed.snapshot;
742
+ lastKnownMtime = current;
743
+ if (warnedMerge) {
744
+ logger.info?.("[router] merged another process's outcome changes", { path: outcomesPath });
745
+ } else {
746
+ warnedMerge = true;
747
+ logger.warn("[router] another process writes this outcome directory; its changes are merged into this process's before each save", {
748
+ path: outcomesPath,
749
+ });
750
+ }
751
+ return { status: "merge", disk: parsed.snapshot, baseline: previous };
752
+ }
753
+ if (parsed !== null && parsed.reason === "unsupported-version") {
754
+ readOnlyReason = parsed.message.startsWith("unsupported outcome store version")
755
+ ? "unsupported outcome store version on disk"
756
+ : "unrecognized outcome store on disk";
757
+ lastKnownMtime = current;
758
+ logger.warn("[router] another process replaced outcomes.json with a file this plugin does not own; not overwriting it", {
759
+ path: outcomesPath,
760
+ reason: parsed.message,
761
+ });
762
+ return { status: "unchanged" }; // the save that follows is refused as read-only
763
+ }
764
+ // Garbage or a malformed version-1 file: move it aside *before* the save replaces it.
765
+ logger.warn("[router] another process left an unreadable outcomes.json; it is moved aside and replaced", {
766
+ path: outcomesPath,
767
+ reason: unparseable ?? (parsed !== null && !parsed.ok ? parsed.message : "unknown"),
768
+ });
769
+ await quarantineCorrupt();
770
+ lastKnownMtime = (await statOrNull(outcomesPath))?.mtimeMs ?? null;
771
+ return { status: "unchanged" };
772
+ } catch (error) {
773
+ const reason = describeError(error);
774
+ logger.warn("[router] could not read outcomes.json to check for another writer; the snapshot save is skipped this round", {
775
+ path: outcomesPath,
776
+ error: reason,
777
+ });
778
+ return { status: "skip", reason: `cannot read ${resolve(outcomesPath)}: ${reason}` };
779
+ }
780
+ },
781
+ async readRows(): Promise<ReadRowsResult> {
782
+ const rows: LogRow[] = [];
783
+ const files: string[] = [];
784
+ let skipped = 0;
785
+ let generations = 0;
786
+ let names: string[] = [];
787
+ try {
788
+ names = await fs.readdir(dir);
789
+ } catch (error) {
790
+ logger.warn("[router] decision log directory unreadable", { dir, error: describeError(error) });
791
+ return { rows, skipped, files, oldestTs: null, generations: 0 };
792
+ }
793
+ for (const name of [...rotatedNames(names), DECISIONS_FILE]) {
794
+ const path = join(dir, name);
795
+ let text: string | null;
796
+ try {
797
+ text = await withRetry(() => fs.readText(path), sleep, delays);
798
+ } catch (error) {
799
+ logger.warn("[router] decision log unreadable; skipped", { path, error: describeError(error) });
800
+ continue;
801
+ }
802
+ if (text === null) continue;
803
+ files.push(path);
804
+ if (name !== DECISIONS_FILE) generations += 1;
805
+ for (const line of (text.charCodeAt(0) === 0xfeff ? text.slice(1) : text).split(/\r?\n/)) {
806
+ if (line.trim() === "") continue;
807
+ const row = parseLogLine(line);
808
+ if (row === null) skipped += 1;
809
+ else rows.push(row);
810
+ }
811
+ }
812
+ let oldestTs: string | null = null;
813
+ let oldestMs = Number.POSITIVE_INFINITY;
814
+ for (const row of rows) {
815
+ const t = Date.parse(row.ts);
816
+ if (t < oldestMs) {
817
+ oldestMs = t;
818
+ oldestTs = row.ts;
819
+ }
820
+ }
821
+ return { rows, skipped, files, oldestTs, generations };
822
+ },
823
+ };
824
+ }
825
+
826
+ // ---------------------------------------------------------------------------
827
+ // Flusher: coalescing, throttled, never on the hot path
828
+ // ---------------------------------------------------------------------------
829
+
830
+ export function createFlusher(
831
+ store: Pick<OutcomeStore, "revision" | "snapshot"> & Partial<Pick<OutcomeStore, "mergeForeign">>,
832
+ persister: Pick<Persister, "saveSnapshot" | "appendRows"> & Partial<Pick<Persister, "readForeignWrites" | "withSnapshotLock">>,
833
+ deps: FlusherDeps,
834
+ options: FlusherOptions = {},
835
+ ): OutcomeFlusher {
836
+ const { scheduler, logger } = deps;
837
+ const now = (): number => safeNow(deps.now);
838
+ const minIntervalMs = options.minIntervalMs ?? FLUSH_MIN_INTERVAL_MS;
839
+ const batchRows = Math.max(1, Math.floor(options.batchRows ?? FLUSH_BATCH_ROWS));
840
+ const maxQueuedRows = Math.max(1, Math.floor(options.maxQueuedRows ?? MAX_QUEUED_ROWS));
841
+
842
+ let queue: LogRow[] = [];
843
+ let writtenRevision = store.revision;
844
+ let inFlight: Promise<void> | null = null;
845
+ let timer: { handle: unknown } | null = null;
846
+ let lastFlushEnd = Number.NEGATIVE_INFINITY;
847
+ let disposed = false;
848
+ let disposing: Promise<void> | null = null;
849
+ let droppedRows = 0;
850
+ const failing = new Set<"snapshot" | "decision log" | "flush">();
851
+ /** The snapshot cannot be written (read-only store): it is no longer pending work (QA-1.3-2). */
852
+ let snapshotBlocked = false;
853
+ /** `requestFlush` callers, released when the next flush attempt finishes, whether it succeeded or not. */
854
+ let waiters: Array<() => void> = [];
855
+
856
+ const hasWork = (): boolean => (!snapshotBlocked && store.revision !== writtenRevision) || queue.length > 0;
857
+
858
+ function releaseWaiters(list: Array<() => void>): void {
859
+ for (const release of list) release();
860
+ }
861
+
862
+ function trimQueue(): void {
863
+ const over = queue.length - maxQueuedRows;
864
+ if (over > 0) {
865
+ queue.splice(0, over);
866
+ droppedRows += over;
867
+ }
868
+ }
869
+
870
+ function noteFailure(what: "snapshot" | "decision log" | "flush", error: string): void {
871
+ if (failing.has(what)) return;
872
+ failing.add(what);
873
+ logger.warn(`[router] outcome ${what} write failed; will retry`, { error });
874
+ }
875
+
876
+ function noteRecovery(what: "snapshot" | "decision log" | "flush"): void {
877
+ if (failing.delete(what)) logger.info?.("[router] outcome persistence recovered", { what });
878
+ }
879
+
880
+ /**
881
+ * Delay before the next flush may start: the rest of the throttle window, clamped to [0, minIntervalMs]. A
882
+ * clock that went backwards (QA-1.3-3) resets the window instead of stretching it by the jump.
883
+ */
884
+ function flushDelay(): number {
885
+ const t = now();
886
+ if (t < lastFlushEnd) lastFlushEnd = t;
887
+ return Math.min(minIntervalMs, Math.max(0, lastFlushEnd + minIntervalMs - t));
888
+ }
889
+
890
+ function schedule(ms: number): void {
891
+ const slot: { handle: unknown } = { handle: undefined };
892
+ timer = slot;
893
+ try {
894
+ slot.handle = scheduler.setTimer(() => {
895
+ if (timer === slot) timer = null;
896
+ void startFlush();
897
+ }, ms);
898
+ } catch (error) {
899
+ if (timer === slot) timer = null;
900
+ logger.warn("[router] outcome flush could not be scheduled", { error: describeError(error) });
901
+ }
902
+ }
903
+
904
+ function cancelTimer(): void {
905
+ const slot = timer;
906
+ timer = null;
907
+ if (slot === null) return;
908
+ try {
909
+ scheduler.clearTimer(slot.handle);
910
+ } catch (error) {
911
+ logger.warn("[router] outcome flush timer could not be cleared", { error: describeError(error) });
912
+ }
913
+ }
914
+
915
+ /**
916
+ * Merge what another process wrote into memory before ours is saved. Returns false when the file could not be
917
+ * checked: the snapshot is then NOT written this round (it stays pending and is retried), because writing
918
+ * blind could overwrite what we failed to read (QA-1.3-18).
919
+ */
920
+ async function absorbForeignWrites(): Promise<boolean> {
921
+ if (persister.readForeignWrites === undefined || store.mergeForeign === undefined) return true;
922
+ try {
923
+ const check = await persister.readForeignWrites(true);
924
+ if (check.status === "merge") store.mergeForeign(check.disk, check.baseline);
925
+ if (check.status === "skip") {
926
+ noteFailure("snapshot", check.reason);
927
+ return false;
928
+ }
929
+ return true;
930
+ } catch (error) {
931
+ noteFailure("snapshot", `cannot check for another writer: ${describeError(error)}`);
932
+ return false;
933
+ }
934
+ }
935
+
936
+ async function doFlush(): Promise<void> {
937
+ if (deps.ready !== undefined) await deps.ready;
938
+ if (!snapshotBlocked && store.revision !== writtenRevision) {
939
+ const transaction = async (): Promise<void> => {
940
+ // QA-1.3-4: write `disk + (memory − baseline)`, never plain memory over another process's work
941
+ const checked = await absorbForeignWrites();
942
+ const revision = store.revision;
943
+ const result = checked ? await persister.saveSnapshot(store.snapshot()) : null;
944
+ if (result === null) {
945
+ // Skipped, already reported; the snapshot stays pending.
946
+ } else if (result.ok) {
947
+ writtenRevision = revision;
948
+ noteRecovery("snapshot");
949
+ } else if (result.readOnly === true) {
950
+ snapshotBlocked = true;
951
+ failing.delete("snapshot"); // disabled, not recovered
952
+ logger.warn("[router] outcome snapshots are not written: the store on disk is read-only for this plugin", { error: result.error });
953
+ } else {
954
+ noteFailure("snapshot", result.error);
955
+ }
956
+ };
957
+ try {
958
+ const acquired = persister.withSnapshotLock === undefined
959
+ ? (await transaction(), true)
960
+ : await persister.withSnapshotLock(transaction);
961
+ if (!acquired) {
962
+ noteFailure("snapshot", "outcomes.json.lock is busy; snapshot remains pending");
963
+ }
964
+ } catch (error) {
965
+ noteFailure("snapshot", describeError(error));
966
+ }
967
+ }
968
+ while (queue.length > 0) {
969
+ const batch = queue.splice(0, batchRows);
970
+ const result = await persister.appendRows(batch);
971
+ if (!result.ok) {
972
+ queue = batch.concat(queue);
973
+ trimQueue();
974
+ noteFailure("decision log", result.error);
975
+ break;
976
+ }
977
+ }
978
+ if (droppedRows > 0) {
979
+ logger.warn("[router] outcome decision rows were dropped (queue limit)", { dropped: droppedRows });
980
+ droppedRows = 0;
981
+ }
982
+ if (queue.length === 0) noteRecovery("decision log");
983
+ noteRecovery("flush");
984
+ }
985
+
986
+ function startFlush(): Promise<void> {
987
+ const attempt = waiters; // every request made before this attempt started is covered by it
988
+ waiters = [];
989
+ const run: Promise<void> = doFlush()
990
+ .catch((error: unknown) => {
991
+ noteFailure("flush", describeError(error));
992
+ })
993
+ .finally(() => {
994
+ if (inFlight === run) inFlight = null;
995
+ const t = now();
996
+ lastFlushEnd = t;
997
+ if (!disposed && hasWork() && timer === null) schedule(minIntervalMs);
998
+ releaseWaiters(attempt);
999
+ // Nothing left scheduled: later requesters would wait for an attempt that will never run.
1000
+ if (timer === null) {
1001
+ const rest = waiters;
1002
+ waiters = [];
1003
+ releaseWaiters(rest);
1004
+ }
1005
+ });
1006
+ inFlight = run;
1007
+ return run;
1008
+ }
1009
+
1010
+ /** Arm a flush if there is work and none is armed or running. Creates no promise (safe in a hook). */
1011
+ function kick(): void {
1012
+ if (disposed || !hasWork()) return;
1013
+ if (inFlight !== null || timer !== null) return; // the running flush's follow-up / the armed timer covers it
1014
+ schedule(flushDelay());
1015
+ }
1016
+
1017
+ function requestFlush(): Promise<void> {
1018
+ if (disposed || !hasWork()) return Promise.resolve();
1019
+ kick();
1020
+ if (timer === null && inFlight === null) return Promise.resolve(); // could not be scheduled
1021
+ return new Promise<void>((done) => {
1022
+ waiters.push(done);
1023
+ });
1024
+ }
1025
+
1026
+ async function flushNow(): Promise<void> {
1027
+ while (inFlight !== null) await inFlight;
1028
+ cancelTimer();
1029
+ await startFlush();
1030
+ }
1031
+
1032
+ function dispose(): Promise<void> {
1033
+ disposing ??= (async () => {
1034
+ await flushNow();
1035
+ cancelTimer();
1036
+ disposed = true;
1037
+ const rest = waiters;
1038
+ waiters = [];
1039
+ releaseWaiters(rest);
1040
+ })();
1041
+ return disposing;
1042
+ }
1043
+
1044
+ return {
1045
+ get pendingRows(): number {
1046
+ return queue.length;
1047
+ },
1048
+ enqueue(row: LogRow): void {
1049
+ if (disposed) return;
1050
+ queue.push(row);
1051
+ trimQueue();
1052
+ kick();
1053
+ },
1054
+ requestFlush,
1055
+ flushNow,
1056
+ dispose,
1057
+ };
1058
+ }