my-durable 0.0.73 → 0.0.75

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.
@@ -102,7 +102,18 @@ export function writeArchiveManifest(bundleDir: string, m: ArchiveManifest): voi
102
102
  */
103
103
  export function readArchiveManifest(bundleDir: string): ArchiveManifest | undefined {
104
104
  try {
105
- const parsed: unknown = JSON.parse(readFileSync(join(bundleDir, MANIFEST_NAME), "utf8"));
105
+ const manifestPath = join(bundleDir, MANIFEST_NAME);
106
+ // R20 (run-6 h6): a manifest written by store.archive() is a few hundred
107
+ // bytes; a planted one had NO ceiling — restore and the archive LISTING
108
+ // read the whole file into RAM per cheap request (leader probe: a 150 MB
109
+ // plant cost ~770 ms and ~600 MB RSS per refused restore, repeatable).
110
+ // Refuse oversized manifests without reading them.
111
+ if (statSync(manifestPath).size > 1024 * 1024) return undefined;
112
+ const text = readFileSync(manifestPath, "utf8");
113
+ // R20 cold-1 M5: a same-user planter can swap the file between stat and
114
+ // read — the cap is enforced on the BYTES WE ACTUALLY READ, not the stat.
115
+ if (text.length > 1024 * 1024) return undefined;
116
+ const parsed: unknown = JSON.parse(text);
106
117
  if (typeof parsed !== "object" || parsed === null) return undefined;
107
118
  const m = parsed as Record<string, unknown>;
108
119
  if (
@@ -151,21 +162,23 @@ function bundleStats(bundleDir: string): { turns: number; lastMessageAt: number
151
162
  let db: DatabaseSync | undefined;
152
163
  try {
153
164
  db = new DatabaseSync(join(bundleDir, DB_NAME), { readOnly: true });
154
- const rows = db.prepare("SELECT record FROM entries").all() as unknown[];
155
- let turns = 0;
165
+ // R20 cold-1 M5: this used to materialize EVERY entries row into RAM and
166
+ // JSON.parse each one per LISTING request — a planted multi-GB bundle was
167
+ // a repeatable per-request stall (the manifest-cap class). Aggregates run
168
+ // inside SQLite; json_extract tolerates non-JSON rows by yielding NULL.
169
+ const turnsRow = db
170
+ .prepare(
171
+ "SELECT COUNT(*) AS n FROM entries WHERE json_extract(record,'$.kind') IN ('pi.user','pi.assistant')",
172
+ )
173
+ .get() as { n?: number } | undefined;
174
+ const turns = typeof turnsRow?.n === "number" ? turnsRow.n : 0;
156
175
  let lastMessageAt: number | null = null;
157
- for (const row of rows) {
158
- const entry = parseRecord((row as { record?: unknown }).record);
159
- if (!entry) continue;
160
- if (entry.kind === "pi.user" || entry.kind === "pi.assistant") turns += 1;
161
- if (!Array.isArray(entry.model)) continue;
162
- for (const message of entry.model) {
163
- const timestamp = (message as { timestamp?: unknown } | null)?.timestamp;
164
- if (typeof timestamp === "number" && (lastMessageAt === null || timestamp > lastMessageAt)) {
165
- lastMessageAt = timestamp;
166
- }
167
- }
168
- }
176
+ const atRow = db
177
+ .prepare(
178
+ "SELECT MAX(json_extract(json_each.value,'$.timestamp')) AS t FROM entries, json_each(json_extract(record,'$.model')) WHERE json_extract(record,'$.model') IS NOT NULL",
179
+ )
180
+ .get() as { t?: unknown } | undefined;
181
+ if (typeof atRow?.t === "number") lastMessageAt = atRow.t;
169
182
  return { turns, lastMessageAt };
170
183
  } catch {
171
184
  return { turns: -1, lastMessageAt: null };
@@ -192,6 +205,9 @@ function dirBytes(dir: string, depth = 0): number {
192
205
  return 0;
193
206
  }
194
207
  if (depth >= 64) return total;
208
+ // R20 cold-1 M5: breadth cap — a planted million-entry directory allocated
209
+ // a giant dirent array per bundle per listing (depth alone bounded nothing).
210
+ if (entries.length > 100_000) return 0;
195
211
  for (const e of entries) {
196
212
  try {
197
213
  if (e.isDirectory()) total += dirBytes(join(dir, e.name), depth + 1);
@@ -279,13 +295,24 @@ export function findBundle(archiveDir: string, sessionId: string): string | null
279
295
  export function archivedTranscript(bundleDir: string, format: "markdown" | "json"): ArchivedTranscript {
280
296
  let db: DatabaseSync | undefined;
281
297
  const entries: WireEntry[] = [];
298
+ let truncated = 0;
282
299
  try {
283
300
  db = new DatabaseSync(join(bundleDir, DB_NAME), { readOnly: true });
284
- const rows = db.prepare("SELECT record FROM entries ORDER BY conversation_id, commit_seq").all() as unknown[];
301
+ // R20 cold-1 M5: the transcript view read the WHOLE entries table per
302
+ // request — same planted-bundle amplification. A hard entry cap keeps the
303
+ // newest turns (the ORDER BY is commit order; truncating from the front
304
+ // loses the oldest context, which a viewer can still get from the bundle).
305
+ const cap = 5_000;
306
+ const totalRow = db.prepare("SELECT COUNT(*) AS n FROM entries").get() as { n?: number } | undefined;
307
+ const total = typeof totalRow?.n === "number" ? totalRow.n : 0;
308
+ const rows = db
309
+ .prepare("SELECT record FROM entries ORDER BY conversation_id, commit_seq LIMIT ? OFFSET ?")
310
+ .all(Math.min(total, cap), Math.max(0, total - Math.min(total, cap))) as unknown[];
285
311
  for (const row of rows) {
286
312
  const entry = parseRecord((row as { record?: unknown }).record);
287
313
  if (entry) entries.push(entry as unknown as WireEntry);
288
314
  }
315
+ truncated = Math.max(0, total - entries.length);
289
316
  } catch {
290
317
  throw new Error("archive bundle unreadable");
291
318
  } finally {
@@ -296,7 +323,12 @@ export function archivedTranscript(bundleDir: string, format: "markdown" | "json
296
323
  }
297
324
  }
298
325
  const items = toTranscript(entries);
299
- return format === "markdown" ? { format: "markdown", text: toMarkdown(items) } : { format: "json", items };
326
+ // R20 cold-2 minor: the truncation marker used to be a dead array property —
327
+ // surface it in the rendered text the viewer actually reads.
328
+ const notice = truncated > 0 ? `> Showing the newest ${entries.length} entries — ${truncated} older entries truncated.
329
+
330
+ ` : "";
331
+ return format === "markdown" ? { format: "markdown", text: notice + toMarkdown(items) } : { format: "json", items };
300
332
  }
301
333
 
302
334
  /**
@@ -158,6 +158,8 @@ export type FetchLike = (
158
158
  headers: Record<string, string>;
159
159
  body: string;
160
160
  signal?: AbortSignal;
161
+ /** R19 (run-5 h7, leader-confirmed): redirects are refused — see attempt(). */
162
+ redirect?: "error" | "follow" | "manual";
161
163
  },
162
164
  ) => Promise<FetchResponseLike>;
163
165
 
@@ -229,21 +231,115 @@ const nonEmptyString = (value: unknown): string | undefined =>
229
231
  * the check — the flag exists to stop the obvious cases, not to be a firewall.
230
232
  */
231
233
  export function isPrivateHost(hostname: string): boolean {
232
- const host = hostname.trim().toLowerCase().replace(/^\[|\]$/g, "");
234
+ // R19 cold-review: a trailing dot is an FQDN root and resolves identically
235
+ // ("localhost." → ::1), so strip it before every name check.
236
+ const host = hostname.trim().toLowerCase().replace(/^\[|\]$/g, "").replace(/\.+$/, "");
233
237
  if (!host) return true;
234
238
  if (host === "localhost" || host.endsWith(".localhost")) return true;
239
+ // R19 cold-review MAJOR 2: the resolver is inet_aton-shaped, so a lone number
240
+ // is not the only alternate spelling — `0177.0.0.1` (octal) and `0x7f.0.0.1`
241
+ // (hex) both reach 127.0.0.1 through getaddrinfo. Canonicalise first.
235
242
  if (/^\d+$/.test(host)) return true; // decimal-encoded IPv4 (2130706433 → 127.0.0.1)
243
+ const canonical = canonicalIPv4(host);
244
+ if (canonical !== null && isPrivateIPv4(canonical)) return true;
236
245
  if (isPrivateIPv4(host)) return true;
237
246
  if (host.includes(":")) {
238
247
  if (host === "::" || host === "::1") return true;
239
248
  if (/^f[cd][0-9a-f]{2}:/.test(host)) return true; // fc00::/7 unique-local
240
249
  if (/^fe[89ab][0-9a-f]:/.test(host)) return true; // fe80::/10 link-local
241
- if (host.startsWith("::ffff:")) return isPrivateIPv4(host.slice("::ffff:".length));
250
+ if (host.startsWith("::ffff:")) {
251
+ const mapped = host.slice("::ffff:".length);
252
+ if (isPrivateIPv4(mapped)) return true; // dotted-quad mapped form
253
+ // R19 (run-5 h7, leader-confirmed): hex-group mapped spellings
254
+ // ("::ffff:7f00:1" = 127.0.0.1, "::ffff:a9fe:a9fe" = 169.254.169.254)
255
+ // classify as PUBLIC unless decoded here — WHATWG URL keeps the hex
256
+ // groups and the kernel maps the literal's low 32 bits to the IPv4
257
+ // destination. Decode by the LAST two groups (the kernel-mapped half).
258
+ const groups = mapped.split(":").filter(Boolean);
259
+ if (groups.length >= 1 && groups.every((g) => /^[0-9a-f]{1,4}$/i.test(g))) {
260
+ const value = ipv4FromLastGroups(groups);
261
+ if (value !== null && isPrivateIPv4(value)) return true;
262
+ }
263
+ return false;
264
+ }
265
+ // IPv4-compatible ::/96 spellings ("::7f00:1") — deprecated but connectable.
266
+ if (/^::[0-9a-f:]+$/.test(host) && host.includes(":")) {
267
+ const groups = host.slice(2).split(":").filter(Boolean);
268
+ if (groups.length >= 1 && groups.every((g) => /^[0-9a-f]{1,4}$/i.test(g))) {
269
+ const value = ipv4FromLastGroups(groups);
270
+ if (value !== null && isPrivateIPv4(value)) return true;
271
+ }
272
+ }
273
+ // R19 cold-review MAJOR 2: prefixes that CARRY an IPv4 destination.
274
+ // NAT64 64:ff9b::/96 (+ the 64:ff9b:1::/48 local-use block) → low 32 bits
275
+ // 6to4 2002::/16 → bits 16..48
276
+ // Teredo (2001::/32) obfuscates the client address (bitwise NOT) and its
277
+ // server address is attacker-chosen, so classify it as private outright.
278
+ if (/^64:ff9b(:|::)/.test(host)) {
279
+ const groups = host.slice(host.indexOf(":") + 1).split(":").filter(Boolean);
280
+ if (groups.every((g) => /^[0-9a-f]{1,4}$/.test(g))) {
281
+ if (groups.length < 3) return true; // 64:ff9b:1::/48 local-use block
282
+ const value = ipv4FromLastGroups(groups);
283
+ if (value === null || isPrivateIPv4(value)) return true;
284
+ }
285
+ return false;
286
+ }
287
+ if (/^2002:/.test(host)) {
288
+ const groups = host.split(":").filter(Boolean);
289
+ const hi = parseInt(groups[1] ?? "", 16);
290
+ const lo = parseInt(groups[2] ?? "", 16);
291
+ if (Number.isInteger(hi) && Number.isInteger(lo)) {
292
+ const v4 = `${(hi >>> 8) & 255}.${hi & 255}.${(lo >>> 8) & 255}.${lo & 255}`;
293
+ return isPrivateIPv4(v4);
294
+ }
295
+ return false;
296
+ }
297
+ if (/^2001:(?:0{1,4}|):/.test(host)) return true; // Teredo 2001:0000::/32, incl. the "2001::" compression
242
298
  return false;
243
299
  }
244
300
  return false;
245
301
  }
246
302
 
303
+ /**
304
+ * R19 cold-review MAJOR 2: inet_aton-compatible canonicalisation of a dotted
305
+ * IPv4 literal, so octal (`0177.0.0.1`) and hex (`0x7f.0.0.1`) octets cannot
306
+ * slip past the range checks. Returns dotted-quad, or null when the host is not
307
+ * an IPv4 literal at all.
308
+ */
309
+ function canonicalIPv4(host: string): string | null {
310
+ const parts = host.split(".");
311
+ if (parts.length < 1 || parts.length > 4) return null;
312
+ const octets: number[] = [];
313
+ for (const part of parts) {
314
+ if (!part) return null;
315
+ let n: number;
316
+ if (/^0x[0-9a-f]*$/.test(part)) n = part.length > 2 ? parseInt(part.slice(2), 16) : Number.NaN;
317
+ else if (/^0[0-7]+$/.test(part)) n = parseInt(part.slice(1), 8);
318
+ else if (/^\d+$/.test(part)) n = Number(part);
319
+ else return null;
320
+ if (!Number.isInteger(n) || n < 0) return null;
321
+ octets.push(n);
322
+ }
323
+ // inet_aton: the last part fills the remaining bytes (a.b.c.d, a.b.c, a.b, a).
324
+ const last = octets.pop()!;
325
+ const limit = 256 ** (4 - octets.length);
326
+ if (last >= limit) return null;
327
+ if (octets.some((n) => n > 255)) return null;
328
+ const value = octets.reduce((acc, n) => (acc << 8) | n, 0) * limit + last;
329
+ if (!Number.isSafeInteger(value) || value > 0xffffffff) return null;
330
+ return `${(value >>> 24) & 255}.${(value >>> 16) & 255}.${(value >>> 8) & 255}.${value & 255}`;
331
+ }
332
+
333
+ /** R19: decode the low 32 bits of a hex-group IPv6 tail into dotted-quad (null on overflow). */
334
+ function ipv4FromLastGroups(groups: string[]): string | null {
335
+ const last = groups[groups.length - 1]!;
336
+ const prev = groups[groups.length - 2];
337
+ const hi = prev !== undefined ? parseInt(prev, 16) : 0;
338
+ const lo = parseInt(last, 16);
339
+ const value = ((hi & 0xffff) << 16) | (lo & 0xffff);
340
+ return `${(value >>> 24) & 255}.${(value >>> 16) & 255}.${(value >>> 8) & 255}.${value & 255}`;
341
+ }
342
+
247
343
  function isPrivateIPv4(host: string): boolean {
248
344
  const parts = host.split(".");
249
345
  if (parts.length !== 4) return false;
@@ -794,6 +890,12 @@ export class NotifySinks {
794
890
  headers: request.headers,
795
891
  body: request.body,
796
892
  signal: AbortSignal.timeout(this.timeoutMs),
893
+ // R19 (run-5 h7, leader-confirmed): without this, a sink host's 3xx
894
+ // re-aims the daemon's POST at any loopback/LAN/metadata host the
895
+ // create-time private-host guard refuses — the redirect target is
896
+ // never re-validated. Refuse redirects like every other egress fetch
897
+ // in this repo (tunnel, pairing, jev, hub transport).
898
+ redirect: "error",
797
899
  });
798
900
  const ms = Date.now() - startedAt;
799
901
  const status = typeof response?.status === "number" ? response.status : 0;
@@ -206,6 +206,10 @@ const TRANSCRIPT_SESSION_LIMIT = 100;
206
206
  const TRANSCRIPT_AGENT_ENTRY_LIMIT = 4000;
207
207
  const TRANSCRIPT_ENTRY_BUDGET = 50_000;
208
208
  const TRANSCRIPT_HITS_PER_AGENT = 3;
209
+ /** R19 (run-5 h1): per-SESSION hit cap — hits accumulate 3×matching conversations
210
+ * (fork/subagent), so without this the per-agent cap says nothing about a match's
211
+ * total cardinality (leader-probe: 2 conversations → 5 hits, linear in forks). */
212
+ const TRANSCRIPT_HITS_PER_SESSION = 12;
209
213
 
210
214
  /** Scheduler granularity. Schedules are minute-granular, so 30 s is enough and
211
215
  * the timer is unref'd: it never holds the process open. */
@@ -1568,6 +1572,7 @@ export class Store {
1568
1572
  });
1569
1573
  this.catalog.prepare("DELETE FROM conversation_names WHERE sessionId=?").run(row.id);
1570
1574
  this.catalog.prepare("DELETE FROM sessions WHERE id=?").run(row.id);
1575
+ this.salvageFailedSessions.delete(row.id); // R20 h6: clear AFTER the move commits — a failed rename must not re-arm salvage
1571
1576
  this.errors.delete(row.id);
1572
1577
  this.notify();
1573
1578
  return { archived: target };
@@ -1593,6 +1598,11 @@ export class Store {
1593
1598
  }
1594
1599
 
1595
1600
  async restoreArchivedSession(sessionId: string): Promise<SessionSummary> {
1601
+ // R19 (run-5 h4 hardening): normalize ONCE — the live-check used to be
1602
+ // case-sensitive while the pin was case-normalized and the move target
1603
+ // raw, so an uppercase-hex id could bypass the live-session refusal and
1604
+ // strand the bundle. Every check below now sees the same canonical value.
1605
+ sessionId = sessionId.toLowerCase();
1596
1606
  if (this.list().some((r) => r.id === sessionId))
1597
1607
  throw invalid("a live session with this id already exists");
1598
1608
  // R18 (run-4 h1): restore is a session-placement writer, so it enforces
@@ -1604,7 +1614,7 @@ export class Store {
1604
1614
  const bundleDir = findBundle(this.archiveDir, sessionId);
1605
1615
  if (!bundleDir) throw notFound(`no archived session ${sessionId}`);
1606
1616
  const pre = readArchiveManifest(bundleDir);
1607
- if (pre && pre.sessionId !== sessionId.toLowerCase())
1617
+ if (pre && pre.sessionId !== sessionId)
1608
1618
  throw invalid(`archive manifest claims session ${pre.sessionId}, not ${sessionId} — refusing to restore under a foreign id`);
1609
1619
  const candidateCwd = pre?.cwd ?? "";
1610
1620
  if (!candidateCwd.trim())
@@ -1619,14 +1629,18 @@ export class Store {
1619
1629
  await this.assertSessionCwdAllowed(restoredCwd);
1620
1630
  const manifest = await restoreArchive(this.archiveDir, this.options.dataDir, sessionId).catch(() => undefined);
1621
1631
  if (!manifest) throw notFound(`no archived session ${sessionId}`);
1632
+ // R19 (run-5 h4/h11 hardening): the catalog row is built from the
1633
+ // VALIDATED pre-move manifest, not restoreArchive's second, unpinned
1634
+ // re-read — a manifest swapped in during the move can no longer skew
1635
+ // id/dbPath (cwd stays the validated realpath either way).
1622
1636
  const row: SessionRow = {
1623
- id: manifest.sessionId,
1624
- name: manifest.name || "Untitled session",
1637
+ id: sessionId,
1638
+ name: pre?.name || manifest.name || "Untitled session",
1625
1639
  cwd: restoredCwd,
1626
- dbPath: join(this.sessionsDir, manifest.sessionId, "agent.sqlite"),
1627
- createdAt: manifest.createdAt,
1628
- model: manifest.model,
1629
- provider: manifest.provider,
1640
+ dbPath: join(this.sessionsDir, sessionId, "agent.sqlite"),
1641
+ createdAt: pre?.createdAt ?? manifest.createdAt,
1642
+ model: pre?.model ?? manifest.model,
1643
+ provider: pre?.provider ?? manifest.provider,
1630
1644
  };
1631
1645
  this.catalog.exec("BEGIN");
1632
1646
  try {
@@ -1640,6 +1654,8 @@ export class Store {
1640
1654
  throw e;
1641
1655
  }
1642
1656
  this.notify();
1657
+ this.salvageFailedSessions.delete(sessionId); // R20 h6: clear AFTER the bundle actually came back — a REFUSED restore must not re-arm salvage
1658
+ this.errors.delete(sessionId); // R20 cold-1 minor: the fast-fault note may predate the archive — do not surface a stale reason
1643
1659
  // sessionSummary handles a not-yet-opened session (the closed-bundle path).
1644
1660
  return await this.sessionSummary(row);
1645
1661
  }
@@ -1647,6 +1663,12 @@ export class Store {
1647
1663
  async openAgent(row: SessionRow, create = false, thinkingLevel: ThinkingLevel = "medium") {
1648
1664
  const current = this.opened.get(row.id);
1649
1665
  if (current) return current.harness;
1666
+ // R20 (run-6 h6): attempt-once — the memo was only read by the search
1667
+ // path, so every agent-touching request re-ran the FULL salvage (leader
1668
+ // probe: 5.0 s per request on a corrupt session, unbounded). Fail fast
1669
+ // from the recorded fault without touching storage.
1670
+ if (!create && this.salvageFailedSessions.has(row.id))
1671
+ throw new ApiFault("unavailable", this.errors.get(row.id) ?? "session database is unreadable (salvage failed)");
1650
1672
  if (!create) await stat(row.dbPath);
1651
1673
  await mkdir(dirname(row.dbPath), { recursive: true });
1652
1674
  const unlock = lockFile(`${row.dbPath}.lock`);
@@ -1698,6 +1720,10 @@ export class Store {
1698
1720
  this.salvageInFlight.set(row.id, inFlight);
1699
1721
  const outcome = await inFlight;
1700
1722
  if (!outcome.recovered) {
1723
+ // R19 (run-5 h1): attempt-once — a failed salvage is memoized for the
1724
+ // process lifetime so every later open (and every scope=all query's
1725
+ // reopen) fails fast instead of re-copying the corrupt database.
1726
+ this.salvageFailedSessions.add(row.id);
1701
1727
  const note = salvageFailureNote(outcome);
1702
1728
  const previous = this.errors.get(row.id);
1703
1729
  this.errors.set(row.id, note); // rides the session summary and every later fault
@@ -2606,6 +2632,11 @@ export class Store {
2606
2632
  let sessionsScanned = 0;
2607
2633
  let truncated = false;
2608
2634
  for (const row of this.list()) {
2635
+ // R19 (run-5 h1, leader-probed): a session whose salvage already FAILED
2636
+ // never re-opens — the reopen used to re-run the whole-DB copy +
2637
+ // integrity_check on EVERY query (262 MB corrupt db: 5.0 s per query,
2638
+ // memoization-free), and the FE fires scope=all per keystroke.
2639
+ if (this.salvageFailedSessions.has(row.id)) continue;
2609
2640
  if (sessionsScanned >= TRANSCRIPT_SESSION_LIMIT || entriesScanned >= TRANSCRIPT_ENTRY_BUDGET) {
2610
2641
  truncated = true;
2611
2642
  break;
@@ -2655,8 +2686,10 @@ export class Store {
2655
2686
  base.where.push("transcript");
2656
2687
  marked = true;
2657
2688
  }
2658
- for (const hit of hits)
2689
+ for (const hit of hits) {
2690
+ if (base.hits!.length >= TRANSCRIPT_HITS_PER_SESSION) break;
2659
2691
  base.hits!.push({ agent: ref.name, entry: hit.entry, kind: hit.kind, text: hit.text });
2692
+ }
2660
2693
  byId.set(row.id, base);
2661
2694
  }
2662
2695
  } catch {
@@ -2857,6 +2890,19 @@ export class Store {
2857
2890
  /** R10 5.2: per-session salvage single-flight — concurrent openers of one
2858
2891
  * corrupt session share ONE bounded attempt instead of racing scratch files. */
2859
2892
  private salvageInFlight = new Map<string, Promise<import("./salvage.js").SalvageOutcome>>();
2893
+ /** R19 (run-5 h1): sessions whose salvage already failed — searched cheaply skipped, salvage never re-run. */
2894
+ private salvageFailedSessions = new Set<string>();
2895
+
2896
+ /**
2897
+ * R19 (run-5 h1): the salvage memo is per-process so a corrupt session is not
2898
+ * re-copied on every scope=all query. It must NOT outlive the session's
2899
+ * lifecycle: archiving, restoring or deleting a session calls this so a
2900
+ * repaired database becomes searchable again in the same process.
2901
+ */
2902
+ clearSalvageMemo(sessionId?: string): void {
2903
+ if (sessionId === undefined) this.salvageFailedSessions.clear();
2904
+ else this.salvageFailedSessions.delete(sessionId);
2905
+ }
2860
2906
 
2861
2907
  /** R8 schedule budgets (StoreOptions-overridable so tests simulate wedged
2862
2908
  * dispatches in milliseconds instead of minutes). */
@@ -106,7 +106,12 @@ export interface TelegramIo {
106
106
  * read-modify-write (daemon + dpi telegram CLI are two OS processes).
107
107
  * Optional so pure in-memory fakes stay small; absent = unlocked caller.
108
108
  */
109
- withLock?<T>(path: string, fn: () => Promise<T>): Promise<T>;
109
+ /**
110
+ * Run `fn` while holding the advisory lock. `assertOwned` throws when this
111
+ * holder no longer owns the lock file (a peer stale-broke us) — the commit
112
+ * calls it immediately before writing so a stolen lock cannot lead to a write.
113
+ */
114
+ withLock?<T>(path: string, fn: (assertOwned: () => Promise<void>) => Promise<T>): Promise<T>;
110
115
  }
111
116
 
112
117
  export const defaultTelegramIo = (): TelegramIo => ({
@@ -127,38 +132,64 @@ export const defaultTelegramIo = (): TelegramIo => ({
127
132
  }
128
133
  },
129
134
  chmod: (path, mode) => chmod(path, mode),
130
- withLock: async <T>(path: string, fn: () => Promise<T>): Promise<T> => {
135
+ withLock: async <T>(path: string, fn: (assertOwned: () => Promise<void>) => Promise<T>): Promise<T> => {
131
136
  // Advisory lock file next to the registry. Both writers are the same OS
132
137
  // user, so create-exclusive + stale-break (mtime older than 5 s — a
133
138
  // crashed holder never wedges the bridge) is mutual exclusion enough.
139
+ // R19 (run-5 h3, leader-confirmed): the lock used to be ownership-blind —
140
+ // a stale-break stat→unlink raced a successor's fresh lock (forced
141
+ // interleave probe: double-entry), and the finally-unlink removed
142
+ // "whatever file is there". Every unlink now re-reads the holder nonce
143
+ // and removes the file only when it is still exactly the holder we judged.
134
144
  const lockPath = `${path}.lock`;
135
145
  const deadline = Date.now() + 10_000;
146
+ const nonce = `${process.pid}-${randomBytes(8).toString("hex")}`;
147
+ const lockNonce = async (): Promise<string | null> => {
148
+ try {
149
+ return (await readFile(lockPath, "utf8")).trim();
150
+ } catch {
151
+ return null; // vanished between the stat and the read — retry
152
+ }
153
+ };
136
154
  for (;;) {
137
155
  try {
138
156
  const handle = await open(lockPath, "wx", 0o600);
139
- await handle.write(`${process.pid}\n`);
157
+ await handle.write(`${nonce}\n`);
140
158
  await handle.close();
141
159
  break;
142
160
  } catch (error) {
143
161
  if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
144
162
  let age = 0;
163
+ let seen: string | null = null;
145
164
  try {
146
165
  age = Date.now() - (await stat(lockPath)).mtimeMs;
166
+ seen = await lockNonce();
147
167
  } catch {
148
168
  continue; // released between the create attempt and the stat
149
169
  }
170
+ if (seen === null) continue; // gone mid-judge — retry the create
150
171
  if (age > 5_000) {
151
- await unlink(lockPath).catch(() => undefined); // stale holder — break it
172
+ // Stale candidate — break it ONLY if it is still exactly the holder
173
+ // we just judged (a successor's fresh lock must survive our unlink).
174
+ const now = await lockNonce();
175
+ if (now !== null && now === seen) await unlink(lockPath).catch(() => undefined);
152
176
  continue;
153
177
  }
154
178
  if (Date.now() > deadline) throw new Error(`telegram registry lock busy: ${lockPath}`);
155
179
  await new Promise((r) => setTimeout(r, 25));
156
180
  }
157
181
  }
182
+ const assertOwned = async (): Promise<void> => {
183
+ const current = await lockNonce();
184
+ if (current !== nonce)
185
+ throw new Error(`telegram registry lock lost: ${lockPath} (holder changed — refusing to write)`);
186
+ };
158
187
  try {
159
- return await fn();
188
+ return await fn(assertOwned);
160
189
  } finally {
161
- await unlink(lockPath).catch(() => undefined);
190
+ // Release only our own lock — never a successor's.
191
+ const current = await lockNonce();
192
+ if (current !== null && current === nonce) await unlink(lockPath).catch(() => undefined);
162
193
  }
163
194
  },
164
195
  exists: async (path) => {
@@ -708,7 +739,7 @@ export class TelegramBridge {
708
739
  // defaultTelegramIo). Without the lock, a CLI commit landing between the
709
740
  // CAS read and the final write is silently clobbered and a revoked binding
710
741
  // resurrects (leader-probe confirmed on a0893c1-era code).
711
- const commit = async (): Promise<void> => {
742
+ const commit = async (assertOwned?: () => Promise<void>): Promise<void> => {
712
743
  // R17 (run-3 h4): the registry has TWO writers (daemon + dpi telegram
713
744
  // CLI). Write-after-read validation: if the file's bytes changed since we
714
745
  // last saw them, our snapshot is stale — writing it would clobber the
@@ -738,13 +769,59 @@ export class TelegramBridge {
738
769
  if (this.mainIsGood && (await this.io.exists(this.filePath))) {
739
770
  try {
740
771
  const previous = await this.io.readFile(this.filePath);
772
+ // R19 (run-5 h3, leader-confirmed): this re-read happens AFTER the CAS
773
+ // — if the bytes moved since the CAS, a foreign write landed inside
774
+ // our commit window and writing now would clobber it silently (the
775
+ // post-write verify only sees our own payload). Fail loudly BEFORE
776
+ // any write; the foreign bytes stay authoritative on disk.
777
+ if (this.registryText !== null && previous !== this.registryText) {
778
+ this.mainIsGood = false;
779
+ throw new TelegramBridgeError(
780
+ "registry_changed",
781
+ `registry changed between CAS and commit — foreign write preserved — refusing to clobber ${this.filePath}`,
782
+ );
783
+ }
741
784
  await this.io.writeFile(this.backupPath, previous);
742
785
  await this.io.chmod(this.backupPath, 0o600);
743
786
  } catch (error) {
787
+ if (error instanceof TelegramBridgeError) throw error;
744
788
  this.warn(`could not refresh ${this.backupPath}`, error);
745
789
  }
746
790
  }
747
791
  const payload = `${JSON.stringify(draft satisfies TelegramRegistryFile, null, 2)}\n`;
792
+ // R19 (run-5 h3, leader-confirmed HIGH): the .bak refresh above is separated
793
+ // from the write by awaited fs ops, so a NON-locking peer (operator hand-edit,
794
+ // a pre-R18 writer during the upgrade window) could land its bytes after that
795
+ // read and before our write — the post-write verify only ever compares to our
796
+ // OWN payload, so both commits reported success and the revoked binding
797
+ // survived on disk. Re-read immediately before writing: any divergence from
798
+ // the CAS baseline refuses the commit with the foreign bytes intact.
799
+ if (this.registryText !== null) {
800
+ const beforeWrite = await this.io.readFile(this.filePath);
801
+ if (beforeWrite !== this.registryText) {
802
+ this.mainIsGood = false;
803
+ throw new TelegramBridgeError(
804
+ "registry_changed",
805
+ `registry changed just before commit — foreign write preserved — refusing to clobber ${this.filePath}`,
806
+ );
807
+ }
808
+ }
809
+ // R19 cold-review MAJOR 1: a peer that stale-broke our lock and then wrote
810
+ // would otherwise be clobbered by this write while we still reported
811
+ // success. Confirm ownership FIRST — a stolen lock refuses the commit.
812
+ // (A peer that ignores the lock entirely and lands its bytes inside the
813
+ // single writeFile syscall below is a documented residual: without a kernel
814
+ // compare-and-swap no in-process code can observe that interleaving.)
815
+ if (assertOwned) {
816
+ try {
817
+ await assertOwned();
818
+ } catch (error) {
819
+ // Cold-review minor: every other refusal marks the baseline bad; keep the
820
+ // symmetry so the next sync re-reads instead of trusting memory.
821
+ this.mainIsGood = false;
822
+ throw error;
823
+ }
824
+ }
748
825
  await this.io.writeFile(this.filePath, payload);
749
826
  await this.io.chmod(this.filePath, 0o600);
750
827
  // R18 (run-4 h3): the CAS above is separated from the write by several
@@ -757,11 +834,11 @@ export class TelegramBridge {
757
834
  try {
758
835
  const after = await this.io.readFile(this.filePath);
759
836
  if (after !== payload) {
760
- await this.io.writeFile(this.filePath, after);
761
- await this.io.chmod(this.filePath, 0o600);
762
- // Converge memory onto the restored foreign bytes immediately — a
763
- // stale in-memory binding must not authorize the very next update
764
- // through syncForeign's "still our own last write" fast path.
837
+ // R19 (run-5 h3, leader-confirmed): the foreign bytes are ALREADY on
838
+ // disk — the old rollback rewrote them (a second blind write with
839
+ // its own clobber window). Adopt only: converge memory onto what is
840
+ // there so a stale in-memory binding cannot authorize the very next
841
+ // update through syncForeign's "still our own last write" fast path.
765
842
  const foreign = coerceRegistry(JSON.parse(after), this.now());
766
843
  this.adopt({ ...foreign, offset: Math.max(this.offset, foreign.offset) });
767
844
  this.registryText = after;