opencode-self-improvement 0.33.9 → 0.33.10

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.
@@ -1,5 +1,5 @@
1
1
  // decay — split from src/portable.ts. Declaration bodies are unchanged.
2
- import { open } from "node:fs/promises";
2
+ import { cmpTs } from "../core/cmp-ts.ts";
3
3
  import { loadAll } from "../store/files/load.ts";
4
4
  import { type Memory } from "../store/model/memory.ts";
5
5
  import { isInjectable } from "../store/model/predicates.ts";
@@ -7,8 +7,7 @@ import { isVisibleTo, readerFromSid } from "../store/model/visibility.ts";
7
7
 
8
8
  // --- decay support --------------------------------------------------------------
9
9
 
10
- // Active open threads with ts older than `days` days, oldest first (both sides
11
- // are UTC-Z ISO strings, so plain lexicographic compare is correct).
10
+ // Legacy rows may omit milliseconds. Compare instants for both the cutoff and order.
12
11
  export async function findStaleOpen(
13
12
  days: number,
14
13
  sid?: string,
@@ -24,8 +23,8 @@ export async function findStaleOpen(
24
23
  isInjectable(m) &&
25
24
  isVisibleTo(m, reader) &&
26
25
  m.status === "open" &&
27
- m.ts < cutoff,
26
+ cmpTs(m.ts, cutoff) < 0,
28
27
  )
29
- .sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0))
28
+ .sort((a, b) => cmpTs(a.ts, b.ts))
30
29
  );
31
30
  }
@@ -13,6 +13,7 @@ import {
13
13
  type StoreCounts,
14
14
  emptyStats,
15
15
  } from "./payload.ts";
16
+ import type { DroppedEvidenceWrites } from "../telemetry/record.ts";
16
17
  import { EVICT_MIN_RIDES } from "./store-summary.ts";
17
18
 
18
19
  function ago(iso: string): string {
@@ -215,6 +216,28 @@ export function captureLines(c: CaptureHealth): string[] {
215
216
  }
216
217
  }
217
218
 
219
+ /**
220
+ * The one report an unwritable evidence log can produce: a count kept in this
221
+ * process, never a line appended to the log that failed. Silence here means
222
+ * this process lost nothing — a store that lost writes in an earlier process
223
+ * reports nothing, because the counter lives and dies with the process that
224
+ * could still tell.
225
+ */
226
+ export function evidenceWriteLines(
227
+ evidence?: DroppedEvidenceWrites | null,
228
+ ): string[] {
229
+ if (!evidence || evidence.dropped === 0) return [];
230
+ return [
231
+ ` evidence writes dropped: ${evidence.dropped} by this process (last ${
232
+ evidence.lastEvent
233
+ }: ${evidence.lastError.slice(0, 160)})`,
234
+ // The health lines above are read back out of the log that is losing
235
+ // writes, so they under-report what ran. Without this the reader weighs a
236
+ // missing line as evidence that the pass never happened.
237
+ " capture kept running; the auto-capture lines above read from that same log and under-count it",
238
+ ];
239
+ }
240
+
218
241
  /**
219
242
  * Plain-text rendering shared by the memory_status tool (and any other chat
220
243
  * client). Sections match the terminal /memory panel one-for-one.
@@ -225,6 +248,12 @@ export function renderMemoryReport(input: {
225
248
  blocked: BlockedRow[];
226
249
  quarantined?: { ts: string; patterns: string[] }[];
227
250
  capture?: CaptureHealth;
251
+ /**
252
+ * Evidence writes this process lost for this store. The only report an
253
+ * unwritable log can produce is one that never touches the log, so it arrives
254
+ * from process memory rather than from the lines above it.
255
+ */
256
+ evidence?: DroppedEvidenceWrites | null;
228
257
  }): string {
229
258
  const { status, store, blocked } = input;
230
259
  const out: string[] = ["MEMORY STATUS", ""];
@@ -347,11 +376,15 @@ export function renderMemoryReport(input: {
347
376
  );
348
377
  }
349
378
  if (sizing.length) out.push(` ${sizing.join(" · ")}`);
350
- if (input.capture) {
379
+ const captureSection = [
380
+ ...(input.capture ? captureLines(input.capture) : []),
381
+ ...evidenceWriteLines(input.evidence),
382
+ ];
383
+ if (captureSection.length) {
351
384
  out.push(
352
385
  "",
353
386
  "AUTO-CAPTURE — is it off, misconfigured, armed, or alive?",
354
- ...captureLines(input.capture),
387
+ ...captureSection,
355
388
  );
356
389
  }
357
390
  out.push(
package/src/store/lock.ts CHANGED
@@ -98,7 +98,6 @@ import { record } from "../telemetry/record.ts";
98
98
  */
99
99
  const lockDatabaseName = (file: string): string =>
100
100
  `.store-lock.${basename(file)}.sqlite`;
101
- const DEFAULT_TIMEOUT_MS = 10_000;
102
101
  // The budget must exceed the worst LEGITIMATE wait, not just an idle section.
103
102
  // A whole-file publish inside a section can spend 2000 ms in `handoverRename`
104
103
  // retrying a rename Windows refuses while a reader holds the destination
@@ -108,24 +107,12 @@ const DEFAULT_TIMEOUT_MS = 10_000;
108
107
  // reported "locked for 5001ms" while the holder was mid-handover-retry, not
109
108
  // wedged. 10 s still fails closed and reports, but stops refusing writes that
110
109
  // were simply behind two honest retries.
111
- // the default policy is fail-closed, the policy moved every
112
- // production writer to. A writer that omits opts must refuse at the deadline,
113
- // not silently reintroduce the unlocked-proceed row loss the LOCK_WRITE
114
- // contract retired. "proceed" survives only as an explicit opt-in.
115
- const DEFAULT_ON_TIMEOUT = "fail";
110
+ const DEFAULT_TIMEOUT_MS = 10_000;
116
111
  const MIN_BACKOFF_MS = 1;
117
112
  const MAX_BACKOFF_MS = 25;
118
- // Leaving a legacy WAL journal is a once-per-process-per-lock setup step, not
119
- // the hot path, so it gets its own bound rather than the caller's budget.
113
+ // Legacy journal conversion has its own ceiling within the acquisition deadline.
120
114
  const JOURNAL_CONVERT_BUDGET_MS = 5_000;
121
115
 
122
- // The one source of the timeout policy: both give-up paths — the FIFO
123
- // hand-off and the SQLite wait — resolve through here, so the fail-closed
124
- // default cannot drift between them.
125
- function timeoutPolicy(opts: LockOptions): "proceed" | "fail" {
126
- return opts.onTimeout === "proceed" ? "proceed" : DEFAULT_ON_TIMEOUT;
127
- }
128
-
129
116
  /**
130
117
  * `timeout`: waited past the budget. `reset`: a release was refused, so the
131
118
  * connection was thrown away. SQLite should never refuse a ROLLBACK, and if it
@@ -169,18 +156,34 @@ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
169
156
  const busyMessage = (file: string, waitedMs: number): string =>
170
157
  `memory store is busy: ${basename(file)} has been locked for ${waitedMs}ms — retry`;
171
158
 
172
- // Resolves when the task stored as this key has finished, handing the turn to
173
- // whoever queued after it.
174
- const turns = new Map<string, Promise<void>>();
175
-
176
- async function timed(prev: Promise<void>, ms: number): Promise<boolean> {
177
- let timer: ReturnType<typeof setTimeout> | undefined;
178
- const gained = await Promise.race([
179
- prev.then(() => true),
180
- new Promise<boolean>((res) => (timer = setTimeout(() => res(false), ms))),
181
- ]);
182
- clearTimeout(timer);
183
- return gained;
159
+ function onLockTimeout<T>(
160
+ file: string,
161
+ fn: () => Promise<T>,
162
+ opts: LockOptions,
163
+ waited: number,
164
+ ): Promise<T> {
165
+ const ms = Math.round(waited);
166
+ opts.onEvent?.("timeout", ms);
167
+ if (opts.onTimeout === "proceed") return fn();
168
+ throw new Error(busyMessage(file, ms));
169
+ }
170
+
171
+ // An entry exists while one owner holds the turn. Waiters can leave the FIFO
172
+ // on timeout without releasing the owner or waking its successor.
173
+ const turns = new Map<string, Set<() => void>>();
174
+
175
+ function waitForTurn(waiters: Set<() => void>, ms: number): Promise<boolean> {
176
+ return new Promise((resolve) => {
177
+ const grant = () => {
178
+ clearTimeout(timer);
179
+ resolve(true);
180
+ };
181
+ const timer = setTimeout(() => {
182
+ waiters.delete(grant);
183
+ resolve(false);
184
+ }, ms);
185
+ waiters.add(grant);
186
+ });
184
187
  }
185
188
 
186
189
  /**
@@ -337,7 +340,10 @@ async function harden(dbPath: string): Promise<void> {
337
340
  await chmod(dbPath, 0o600).catch(() => undefined);
338
341
  }
339
342
 
340
- async function lockDatabase(dbPath: string): Promise<Database> {
343
+ async function lockDatabase(
344
+ dbPath: string,
345
+ deadline: number,
346
+ ): Promise<Database | undefined> {
341
347
  const cached = lockDbs.get(dbPath);
342
348
  if (cached) {
343
349
  // Touch: this directory is in use, so it moves to the protected end of the
@@ -367,7 +373,10 @@ async function lockDatabase(dbPath: string): Promise<Database> {
367
373
  // policy stays ours — async, bounded, and sharing one budget with the FIFO
368
374
  // hand-off above.
369
375
  db.run("PRAGMA busy_timeout = 0");
370
- await ensureLockJournal(db, dbPath);
376
+ if (!(await ensureLockJournal(db, dbPath, deadline))) {
377
+ db.close();
378
+ return undefined;
379
+ }
371
380
  } catch (err) {
372
381
  db.close();
373
382
  throw err;
@@ -402,14 +411,18 @@ const journalMode = (db: Database): string =>
402
411
  * LEAVE WAL is refused rather than run that way: the sidecar churn would come
403
412
  * back per store, silently.
404
413
  */
405
- async function ensureLockJournal(db: Database, dbPath: string): Promise<void> {
414
+ async function ensureLockJournal(
415
+ db: Database,
416
+ dbPath: string,
417
+ deadline: number,
418
+ ): Promise<boolean> {
419
+ const started = performance.now();
420
+ const until = Math.min(deadline, started + JOURNAL_CONVERT_BUDGET_MS);
406
421
  let backoff = MIN_BACKOFF_MS;
407
- let waited = 0;
408
422
  for (;;) {
409
- const step = Date.now();
410
423
  try {
411
424
  const mode = journalMode(db);
412
- if (mode === "delete") return;
425
+ if (mode === "delete") return true;
413
426
  db.run("PRAGMA journal_mode = DELETE");
414
427
  if (journalMode(db) === "delete") {
415
428
  // The conversion checkpoints and removes `-wal`, but `-shm` only goes
@@ -421,7 +434,7 @@ async function ensureLockJournal(db: Database, dbPath: string): Promise<void> {
421
434
  // the issue is the Windows delete this module exists to avoid.
422
435
  await unlink(`${dbPath}-wal`).catch(() => undefined);
423
436
  await unlink(`${dbPath}-shm`).catch(() => undefined);
424
- return;
437
+ return true;
425
438
  }
426
439
  } catch (err) {
427
440
  if (!contention(err)) {
@@ -431,14 +444,10 @@ async function ensureLockJournal(db: Database, dbPath: string): Promise<void> {
431
444
  );
432
445
  }
433
446
  }
434
- await sleep(backoff);
435
- waited += Date.now() - step;
447
+ const remaining = until - performance.now();
448
+ if (remaining <= 0) return false;
449
+ await sleep(Math.min(backoff, remaining));
436
450
  backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);
437
- if (waited >= JOURNAL_CONVERT_BUDGET_MS) {
438
- throw new Error(
439
- `store lock could not leave write-ahead journal mode for ${dbPath} after ${waited}ms — another process is holding the lock database in a state that refuses it`,
440
- );
441
- }
442
451
  }
443
452
  }
444
453
 
@@ -458,24 +467,19 @@ function dropLockDatabase(dbPath: string): void {
458
467
  }
459
468
  }
460
469
 
461
- /**
462
- * Cross-process half: hold the lock while `fn` runs. `now` is a seam for tests
463
- * that must land the deadline inside a specific wait iteration; production
464
- * callers never pass it and the real clock is used.
465
- */
470
+ /** Cross-process acquisition uses the same monotonic deadline as the FIFO. */
466
471
  async function holdLock<T>(
467
472
  dbPath: string,
468
473
  file: string,
469
474
  fn: () => Promise<T>,
470
475
  opts: LockOptions,
471
- budgetMs: number,
472
- now: () => number = Date.now,
476
+ started: number,
477
+ deadline: number,
473
478
  ): Promise<T> {
474
- let db = await lockDatabase(dbPath);
475
- const started = now();
479
+ let db = await lockDatabase(dbPath, deadline);
476
480
  let backoff = MIN_BACKOFF_MS;
477
481
  let reconnected = false;
478
- for (;;) {
482
+ while (db) {
479
483
  try {
480
484
  db.run("BEGIN IMMEDIATE");
481
485
  break;
@@ -486,7 +490,7 @@ async function holdLock<T>(
486
490
  // try again on a fresh connection; a second failure surfaces.
487
491
  reconnected = true;
488
492
  dropLockDatabase(dbPath);
489
- db = await lockDatabase(dbPath);
493
+ db = await lockDatabase(dbPath, deadline);
490
494
  continue;
491
495
  }
492
496
  const info = err as { code?: string; errno?: number };
@@ -494,21 +498,14 @@ async function holdLock<T>(
494
498
  `[code=${info.code ?? "-"} errno=${info.errno ?? "-"}] store lock unavailable for ${basename(file)}: ${(err as Error).message}`,
495
499
  );
496
500
  }
497
- if (now() - started >= budgetMs) {
498
- opts.onEvent?.("timeout", now() - started);
499
- if (timeoutPolicy(opts) === "fail") {
500
- throw new Error(busyMessage(file, now() - started));
501
- }
502
- // Proceeding without the lock is the explicit "proceed" opt-in
503
- // (no longer the default). heldLocks is deliberately NOT touched
504
- // here: a writer that never held the lock must not let a nested call
505
- // believe it did.
506
- return await fn();
507
- }
508
- await sleep(backoff);
501
+ const remaining = deadline - performance.now();
502
+ if (remaining <= 0)
503
+ return onLockTimeout(file, fn, opts, performance.now() - started);
504
+ await sleep(Math.min(backoff, remaining));
509
505
  backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);
510
506
  }
511
507
  }
508
+ if (!db) return onLockTimeout(file, fn, opts, performance.now() - started);
512
509
  await harden(dbPath);
513
510
  acquiredHook?.(file);
514
511
  // Protected from eviction for as long as the section runs: closing a
@@ -527,7 +524,7 @@ async function holdLock<T>(
527
524
  db.run("ROLLBACK");
528
525
  } catch (err) {
529
526
  dropLockDatabase(dbPath);
530
- opts.onEvent?.("reset", now() - started);
527
+ opts.onEvent?.("reset", Math.round(performance.now() - started));
531
528
  void err;
532
529
  }
533
530
  }
@@ -544,16 +541,12 @@ async function acquire<T>(
544
541
  opts: LockOptions,
545
542
  ): Promise<T> {
546
543
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
547
- const started = Date.now();
544
+ const started = performance.now();
548
545
 
549
546
  if (busyInjector?.(file)) {
550
547
  // Reported exactly as a waited-out budget would report it, so a test that
551
548
  // injects a refusal exercises the same policy and message as a real one.
552
- opts.onEvent?.("timeout", 0);
553
- if (timeoutPolicy(opts) === "fail") {
554
- throw new Error(busyMessage(file, 0));
555
- }
556
- return fn();
549
+ return onLockTimeout(file, fn, opts, 0);
557
550
  }
558
551
 
559
552
  if (heldLocks.getStore()?.has(dbPath)) {
@@ -565,40 +558,25 @@ async function acquire<T>(
565
558
  return await fn();
566
559
  }
567
560
 
568
- let releaseTurn!: () => void;
569
- const myTurnEnded = new Promise<void>((res) => (releaseTurn = res));
570
- const queuedBehind = turns.get(dbPath);
571
- turns.set(dbPath, myTurnEnded);
572
-
573
- const finish = () => {
574
- releaseTurn();
575
- if (turns.get(dbPath) === myTurnEnded) turns.delete(dbPath);
576
- };
577
-
578
- if (queuedBehind) {
579
- const gained = await timed(queuedBehind, timeoutMs);
580
- if (!gained) {
581
- // Give up our place in line rather than park everyone behind us on a
582
- // writer that is not going to finish.
583
- finish();
584
- opts.onEvent?.("timeout", Date.now() - started);
585
- if (timeoutPolicy(opts) === "fail") {
586
- throw new Error(busyMessage(file, Date.now() - started));
587
- }
588
- return fn();
589
- }
561
+ let waiters = turns.get(dbPath);
562
+ if (waiters) {
563
+ if (!(await waitForTurn(waiters, timeoutMs)))
564
+ return onLockTimeout(file, fn, opts, performance.now() - started);
565
+ } else {
566
+ waiters = new Set();
567
+ turns.set(dbPath, waiters);
590
568
  }
591
569
 
592
570
  try {
593
- return await holdLock(
594
- dbPath,
595
- file,
596
- fn,
597
- opts,
598
- timeoutMs - (Date.now() - started),
599
- );
571
+ return await holdLock(dbPath, file, fn, opts, started, started + timeoutMs);
600
572
  } finally {
601
- finish();
573
+ const next = waiters.values().next().value;
574
+ if (next) {
575
+ waiters.delete(next);
576
+ next();
577
+ } else {
578
+ turns.delete(dbPath);
579
+ }
602
580
  }
603
581
  }
604
582
 
@@ -6,7 +6,9 @@
6
6
  // What a "use" is, deliberately narrow:
7
7
  // inject — the rows that actually survived into an epoch block (offered to
8
8
  // the model on every request of that epoch);
9
- // pull — rows appended to a grep/glob/read result by the contextual pull;
9
+ // pull — rows appended to a grep/glob/read result by the contextual pull
10
+ // and still whole in the next request for that call
11
+ // (src/inject/pull-receipts.ts);
10
12
  // recall — rows returned by a memory_recall call.
11
13
  //
12
14
  // What it is NOT: evidence is a different file and a different contract. This
@@ -29,6 +31,8 @@ import { withStoreLock, LOCK_WRITE } from "../store/lock.ts";
29
31
  import type { Memory } from "../store/model/memory.ts";
30
32
  import type { ReadSet } from "../consolidate/propose.ts";
31
33
 
34
+ import { type EvidenceContext, record } from "./record.ts";
35
+
32
36
  export type HitSource = "inject" | "pull" | "recall";
33
37
 
34
38
  export { HITS_FILENAME };
@@ -95,7 +99,7 @@ export function resetHitThrottle(): void {
95
99
  nextAttempt.clear();
96
100
  }
97
101
 
98
- async function rotateIfNeeded(): Promise<void> {
102
+ async function rotateIfNeeded(retryRename = true): Promise<void> {
99
103
  let size: number;
100
104
  try {
101
105
  size = (await stat(hitsFile())).size;
@@ -107,7 +111,9 @@ async function rotateIfNeeded(): Promise<void> {
107
111
  // anchor the halving like every other whole-file publish - on
108
112
  // Windows the rename can be refused by a reader's handle, and the retry is
109
113
  // only safe while nothing else moved this file.
110
- const since = await fileIdentity(hitsFile());
114
+ // A request-time pull attempts the atomic handover once. Other writers
115
+ // retain the identity-checked retry window for transient Windows readers.
116
+ const since = retryRename ? await fileIdentity(hitsFile()) : undefined;
111
117
  const lines = (await readFile(hitsFile(), "utf8"))
112
118
  .split("\n")
113
119
  .filter((l) => l.trim());
@@ -136,6 +142,12 @@ export async function recordHits(
136
142
  now = Date.now(),
137
143
  turn?: number,
138
144
  turnKey?: string,
145
+ receipt?: {
146
+ lockWaitMs: number;
147
+ observedAt: number;
148
+ tool?: string;
149
+ evidence?: EvidenceContext;
150
+ },
139
151
  ): Promise<boolean> {
140
152
  if (!rows.length) return false;
141
153
  const ids = rows.map((m) => m.ts);
@@ -143,9 +155,21 @@ export async function recordHits(
143
155
  if (inFlight.has(key)) return false;
144
156
  const eligibleAt = nextAttempt.get(key);
145
157
  if (eligibleAt !== undefined && now < eligibleAt) return false;
158
+ if (receipt && receipt.lockWaitMs <= 0) {
159
+ if (receipt.evidence && receipt.tool) {
160
+ await record(
161
+ "pull_credit_skipped",
162
+ { tool: receipt.tool, rows: rows.length, reason: "budget" },
163
+ false,
164
+ sid,
165
+ receipt.evidence,
166
+ ).catch(() => undefined);
167
+ }
168
+ return false;
169
+ }
146
170
  const line = formatLine({
147
171
  ev: "memory_used",
148
- ts: new Date(now).toISOString(),
172
+ ts: new Date(receipt?.observedAt ?? now).toISOString(),
149
173
  src: source,
150
174
  sid,
151
175
  mem: bracketList(ids),
@@ -162,14 +186,29 @@ export async function recordHits(
162
186
  });
163
187
  inFlight.add(key);
164
188
  let cooldown = RETRY_BACKOFF_MS;
189
+ const evidence = receipt?.evidence;
190
+ const lock = receipt
191
+ ? { ...LOCK_WRITE, timeoutMs: receipt.lockWaitMs }
192
+ : LOCK_WRITE;
193
+ if (receipt && evidence) {
194
+ lock.onEvent = (event, waitedMs) => {
195
+ void record(
196
+ "store_lock",
197
+ { event, waited_ms: waitedMs, op: "write" },
198
+ false,
199
+ sid,
200
+ evidence,
201
+ ).catch(() => undefined);
202
+ };
203
+ }
165
204
  try {
166
205
  await withStoreLock(
167
206
  hitsFile(),
168
207
  async () => {
169
- await rotateIfNeeded();
208
+ await rotateIfNeeded(!receipt);
170
209
  await appendLog(hitsFile(), line);
171
210
  },
172
- LOCK_WRITE,
211
+ lock,
173
212
  );
174
213
  cooldown = THROTTLE_MS;
175
214
  return true;
@@ -177,6 +216,15 @@ export async function recordHits(
177
216
  // Fail-closed lock contention can drop this use observation. Decay and
178
217
  // consolidation therefore see a best-effort ledger, not proof of non-use;
179
218
  // retrieval remains available even when its telemetry cannot be persisted.
219
+ if (evidence && receipt?.tool) {
220
+ await record(
221
+ "pull_credit_skipped",
222
+ { tool: receipt.tool, rows: rows.length, reason: "write_failed" },
223
+ false,
224
+ sid,
225
+ evidence,
226
+ ).catch(() => undefined);
227
+ }
180
228
  return false; // telemetry never breaks retrieval
181
229
  } finally {
182
230
  nextAttempt.set(key, now + cooldown);
@@ -302,3 +302,137 @@ export async function recordWriteBlocked(
302
302
  context,
303
303
  );
304
304
  }
305
+
306
+ // ---- the best-effort evidence policy --------------------------------------
307
+ //
308
+ // The evidence log describes a feature; it is not a dependency of it. A write
309
+ // that fails costs one line and must cost nothing else: not the pass that wrote
310
+ // it, and not the event subscription that hands capture every later turn. The
311
+ // capture path therefore writes only through the wrappers below, which state the
312
+ // decision once instead of at each call site — a per-site `try` is a policy a
313
+ // later receipt can forget.
314
+ //
315
+ // `record` and `recordSync` keep throwing for every other caller. A viewer edit
316
+ // or a gate refusal that cannot write its audit line is a failed operation the
317
+ // operator must see; a capture receipt that cannot write its line is a missing
318
+ // footnote on an operation that succeeded.
319
+ //
320
+ // The counter is the only channel that can report this failure — a line about an
321
+ // unwritable log cannot land either — so it lives in process memory and
322
+ // `memory_status` reads it back. It is keyed by the evidence directory: one
323
+ // store's broken log is not another store's, and a shared server holds several.
324
+ export interface DroppedEvidenceWrites {
325
+ /** Evidence writes this process lost for this store. */
326
+ dropped: number;
327
+ /** Event name of the most recent loss. */
328
+ lastEvent: string;
329
+ /** How the file layer reported the most recent loss. */
330
+ lastError: string;
331
+ }
332
+
333
+ const droppedWrites = new Map<string, DroppedEvidenceWrites>();
334
+
335
+ // Reportable text for a rejection, without becoming the failure it reports.
336
+ // `String` handles a Symbol (`"Symbol(...)"`); what it cannot survive is a
337
+ // rejection whose own `toString` throws, and this runs inside the handler that
338
+ // exists to swallow exactly that class of throw.
339
+ function describeError(err: unknown): string {
340
+ if (err instanceof Error && err.message) return err.message;
341
+ try {
342
+ return String(err);
343
+ } catch {
344
+ return `unprintable ${typeof err}`;
345
+ }
346
+ }
347
+
348
+ // The one rendering every channel of ONE failure shares. The console line and
349
+ // the evidence receipt are the same fact on two channels, so they must not
350
+ // carry different privacy guarantees: neither formats the error itself.
351
+ const MIRRORED_ERROR_MAX = 200;
352
+
353
+ /**
354
+ * A failure as reportable text: message only, credential-scrubbed, capped. Use
355
+ * it for every output that mirrors an error — console, evidence line, counter —
356
+ * and never hand the original object to a surface, because that carries the
357
+ * stack and every unscrubbed field on it.
358
+ */
359
+ export function safeErrorMessage(err: unknown): string {
360
+ return redactSecrets(describeError(err)).slice(0, MIRRORED_ERROR_MAX);
361
+ }
362
+
363
+ function noteDroppedWrite(event: EvidenceEvent, err: unknown): void {
364
+ const key = evidenceDir();
365
+ const prev = droppedWrites.get(key);
366
+ droppedWrites.set(key, {
367
+ dropped: (prev?.dropped ?? 0) + 1,
368
+ lastEvent: event,
369
+ // NOT `(err as Error).message`: a messageless Error or a non-Error
370
+ // rejection would make this field empty, and an empty field reads as
371
+ // "nothing was lost" to every surface that tests it for truth. Scrubbed at
372
+ // the same boundary as every other mirrored error: a path is what an fs
373
+ // failure carries, but a throw from line building carries field values.
374
+ lastError: safeErrorMessage(err),
375
+ });
376
+ // A long-lived server sees many stores. Bound the map the way the ledger's
377
+ // throttle does, and never evict the entry just written — an entry set twice
378
+ // keeps its original position, so the oldest key can be the live one.
379
+ if (droppedWrites.size > 64) {
380
+ for (const k of [...droppedWrites.keys()].slice(0, 32)) {
381
+ if (k !== key) droppedWrites.delete(k);
382
+ }
383
+ }
384
+ }
385
+
386
+ /**
387
+ * This process's lost evidence writes for the current store, or null when this
388
+ * store has lost none. Absent and zero are the same claim here, so only the
389
+ * failure case is worth a line.
390
+ */
391
+ export function droppedEvidenceWrites(): DroppedEvidenceWrites | null {
392
+ return droppedWrites.get(evidenceDir()) ?? null;
393
+ }
394
+
395
+ /** `record` under the best-effort policy: a failed line is counted, not thrown. */
396
+ export async function recordBestEffort(
397
+ ev: EvidenceEvent,
398
+ fields: Record<string, unknown> = {},
399
+ includeContext = true,
400
+ sessionID?: string,
401
+ context?: EvidenceContext,
402
+ ): Promise<void> {
403
+ try {
404
+ await record(ev, fields, includeContext, sessionID, context);
405
+ } catch (err) {
406
+ noteDroppedWrite(ev, err);
407
+ }
408
+ }
409
+
410
+ /** `recordSync` under the best-effort policy. */
411
+ export function recordSyncBestEffort(
412
+ ev: EvidenceEvent,
413
+ fields: Record<string, unknown> = {},
414
+ includeContext = true,
415
+ sessionID?: string,
416
+ context?: EvidenceContext,
417
+ ): void {
418
+ try {
419
+ recordSync(ev, fields, includeContext, sessionID, context);
420
+ } catch (err) {
421
+ noteDroppedWrite(ev, err);
422
+ }
423
+ }
424
+
425
+ /** `recordCaptureLag` under the best-effort policy. */
426
+ export async function recordCaptureLagBestEffort(
427
+ session: string,
428
+ lagMs: number | null,
429
+ outcome: string,
430
+ context?: EvidenceContext,
431
+ model?: string,
432
+ ): Promise<void> {
433
+ try {
434
+ await recordCaptureLag(session, lagMs, outcome, context, model);
435
+ } catch (err) {
436
+ noteDroppedWrite("capture_lag", err);
437
+ }
438
+ }