my-durable 0.0.73 → 0.0.74

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.
@@ -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. */
@@ -1531,6 +1535,7 @@ export class Store {
1531
1535
 
1532
1536
  /** Stop all work, close the harness and move its files to archive/. Nothing is deleted. */
1533
1537
  async archive(row: SessionRow) {
1538
+ this.salvageFailedSessions.delete(row.id); // R19: the bundle left this process's view
1534
1539
  const opened = this.opened.get(row.id);
1535
1540
  if (opened) {
1536
1541
  for (const record of await this.scanAll(opened.harness)) {
@@ -1593,6 +1598,12 @@ 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();
1606
+ this.salvageFailedSessions.delete(sessionId); // R19: the bundle came back — judge it fresh
1596
1607
  if (this.list().some((r) => r.id === sessionId))
1597
1608
  throw invalid("a live session with this id already exists");
1598
1609
  // R18 (run-4 h1): restore is a session-placement writer, so it enforces
@@ -1604,7 +1615,7 @@ export class Store {
1604
1615
  const bundleDir = findBundle(this.archiveDir, sessionId);
1605
1616
  if (!bundleDir) throw notFound(`no archived session ${sessionId}`);
1606
1617
  const pre = readArchiveManifest(bundleDir);
1607
- if (pre && pre.sessionId !== sessionId.toLowerCase())
1618
+ if (pre && pre.sessionId !== sessionId)
1608
1619
  throw invalid(`archive manifest claims session ${pre.sessionId}, not ${sessionId} — refusing to restore under a foreign id`);
1609
1620
  const candidateCwd = pre?.cwd ?? "";
1610
1621
  if (!candidateCwd.trim())
@@ -1619,14 +1630,18 @@ export class Store {
1619
1630
  await this.assertSessionCwdAllowed(restoredCwd);
1620
1631
  const manifest = await restoreArchive(this.archiveDir, this.options.dataDir, sessionId).catch(() => undefined);
1621
1632
  if (!manifest) throw notFound(`no archived session ${sessionId}`);
1633
+ // R19 (run-5 h4/h11 hardening): the catalog row is built from the
1634
+ // VALIDATED pre-move manifest, not restoreArchive's second, unpinned
1635
+ // re-read — a manifest swapped in during the move can no longer skew
1636
+ // id/dbPath (cwd stays the validated realpath either way).
1622
1637
  const row: SessionRow = {
1623
- id: manifest.sessionId,
1624
- name: manifest.name || "Untitled session",
1638
+ id: sessionId,
1639
+ name: pre?.name || manifest.name || "Untitled session",
1625
1640
  cwd: restoredCwd,
1626
- dbPath: join(this.sessionsDir, manifest.sessionId, "agent.sqlite"),
1627
- createdAt: manifest.createdAt,
1628
- model: manifest.model,
1629
- provider: manifest.provider,
1641
+ dbPath: join(this.sessionsDir, sessionId, "agent.sqlite"),
1642
+ createdAt: pre?.createdAt ?? manifest.createdAt,
1643
+ model: pre?.model ?? manifest.model,
1644
+ provider: pre?.provider ?? manifest.provider,
1630
1645
  };
1631
1646
  this.catalog.exec("BEGIN");
1632
1647
  try {
@@ -1698,6 +1713,10 @@ export class Store {
1698
1713
  this.salvageInFlight.set(row.id, inFlight);
1699
1714
  const outcome = await inFlight;
1700
1715
  if (!outcome.recovered) {
1716
+ // R19 (run-5 h1): attempt-once — a failed salvage is memoized for the
1717
+ // process lifetime so every later open (and every scope=all query's
1718
+ // reopen) fails fast instead of re-copying the corrupt database.
1719
+ this.salvageFailedSessions.add(row.id);
1701
1720
  const note = salvageFailureNote(outcome);
1702
1721
  const previous = this.errors.get(row.id);
1703
1722
  this.errors.set(row.id, note); // rides the session summary and every later fault
@@ -2606,6 +2625,11 @@ export class Store {
2606
2625
  let sessionsScanned = 0;
2607
2626
  let truncated = false;
2608
2627
  for (const row of this.list()) {
2628
+ // R19 (run-5 h1, leader-probed): a session whose salvage already FAILED
2629
+ // never re-opens — the reopen used to re-run the whole-DB copy +
2630
+ // integrity_check on EVERY query (262 MB corrupt db: 5.0 s per query,
2631
+ // memoization-free), and the FE fires scope=all per keystroke.
2632
+ if (this.salvageFailedSessions.has(row.id)) continue;
2609
2633
  if (sessionsScanned >= TRANSCRIPT_SESSION_LIMIT || entriesScanned >= TRANSCRIPT_ENTRY_BUDGET) {
2610
2634
  truncated = true;
2611
2635
  break;
@@ -2655,8 +2679,10 @@ export class Store {
2655
2679
  base.where.push("transcript");
2656
2680
  marked = true;
2657
2681
  }
2658
- for (const hit of hits)
2682
+ for (const hit of hits) {
2683
+ if (base.hits!.length >= TRANSCRIPT_HITS_PER_SESSION) break;
2659
2684
  base.hits!.push({ agent: ref.name, entry: hit.entry, kind: hit.kind, text: hit.text });
2685
+ }
2660
2686
  byId.set(row.id, base);
2661
2687
  }
2662
2688
  } catch {
@@ -2857,6 +2883,19 @@ export class Store {
2857
2883
  /** R10 5.2: per-session salvage single-flight — concurrent openers of one
2858
2884
  * corrupt session share ONE bounded attempt instead of racing scratch files. */
2859
2885
  private salvageInFlight = new Map<string, Promise<import("./salvage.js").SalvageOutcome>>();
2886
+ /** R19 (run-5 h1): sessions whose salvage already failed — searched cheaply skipped, salvage never re-run. */
2887
+ private salvageFailedSessions = new Set<string>();
2888
+
2889
+ /**
2890
+ * R19 (run-5 h1): the salvage memo is per-process so a corrupt session is not
2891
+ * re-copied on every scope=all query. It must NOT outlive the session's
2892
+ * lifecycle: archiving, restoring or deleting a session calls this so a
2893
+ * repaired database becomes searchable again in the same process.
2894
+ */
2895
+ clearSalvageMemo(sessionId?: string): void {
2896
+ if (sessionId === undefined) this.salvageFailedSessions.clear();
2897
+ else this.salvageFailedSessions.delete(sessionId);
2898
+ }
2860
2899
 
2861
2900
  /** R8 schedule budgets (StoreOptions-overridable so tests simulate wedged
2862
2901
  * 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;