@creatornader/agent-bridge 0.6.3 → 0.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,14 @@ All notable changes to agent-bridge are documented in this file.
4
4
 
5
5
  The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [0.6.4] - 2026-07-27
8
+
9
+ ### Fixed
10
+
11
+ - Preserve the original SQLite failure when SQLite has already ended a failed
12
+ transaction. Local and edge stores no longer replace it with a second
13
+ "cannot rollback" error.
14
+
7
15
  ## [0.6.3] - 2026-07-26
8
16
 
9
17
  ### Fixed
@@ -453,7 +461,8 @@ First tagged release. Marks the point where agent-bridge has shipped its initial
453
461
  - Narrative-leak detection in CI + on commit via `creatornader/textleaks@v0.2.0` (renamed from leakguard).
454
462
 
455
463
  [0.1.0]: https://github.com/creatornader/agent-bridge/releases/tag/v0.1.0
456
- [Unreleased]: https://github.com/creatornader/agent-bridge/compare/v0.6.3...HEAD
464
+ [Unreleased]: https://github.com/creatornader/agent-bridge/compare/v0.6.4...HEAD
465
+ [0.6.4]: https://github.com/creatornader/agent-bridge/compare/v0.6.3...v0.6.4
457
466
  [0.6.3]: https://github.com/creatornader/agent-bridge/compare/v0.6.2...v0.6.3
458
467
  [0.6.2]: https://github.com/creatornader/agent-bridge/compare/v0.6.1...v0.6.2
459
468
  [0.6.1]: https://github.com/creatornader/agent-bridge/compare/v0.6.0...v0.6.1
package/ROADMAP.md CHANGED
@@ -165,6 +165,11 @@ The published npm version is the authority for whether this package line has shi
165
165
  expired crashed-writer lease safely, and keep gateway calls outside the local
166
166
  write boundary.
167
167
 
168
+ ### 0.6.4 package contents
169
+
170
+ - Preserve primary SQLite errors when the engine already ended a failed
171
+ transaction, rather than raising a secondary rollback error.
172
+
168
173
  ### Production validation and adoption
169
174
 
170
175
  Completed through the published and deployed 0.6.1 package:
package/dist/bridge.js CHANGED
@@ -15,10 +15,10 @@ import {
15
15
  inspectEdgeScopeReadOnly,
16
16
  isRetryableSyncError,
17
17
  stableIdempotency
18
- } from "./chunk-U4M67GFU.js";
18
+ } from "./chunk-HIYXPNBE.js";
19
19
  import {
20
20
  SQLiteBridgeStore
21
- } from "./chunk-7PYY3S27.js";
21
+ } from "./chunk-NSQE6YRP.js";
22
22
  import "./chunk-GTK4KOED.js";
23
23
  import {
24
24
  PostgresBridgeStore
@@ -8,7 +8,7 @@ import {
8
8
  } from "./chunk-UKFRCP6X.js";
9
9
  import {
10
10
  createStore
11
- } from "./chunk-TZHXTMPJ.js";
11
+ } from "./chunk-DBQ5PNQW.js";
12
12
  import {
13
13
  BridgeService
14
14
  } from "./chunk-4V2PFJEF.js";
@@ -633,4 +633,4 @@ export {
633
633
  createAgentBridgeServer,
634
634
  startServer
635
635
  };
636
- //# sourceMappingURL=chunk-DHGJN6NA.js.map
636
+ //# sourceMappingURL=chunk-2UBJ6DHC.js.map
@@ -5,10 +5,10 @@ import {
5
5
  import {
6
6
  SQLiteEdgeStore,
7
7
  SyncingBridgeStore
8
- } from "./chunk-U4M67GFU.js";
8
+ } from "./chunk-HIYXPNBE.js";
9
9
  import {
10
10
  SQLiteBridgeStore
11
- } from "./chunk-7PYY3S27.js";
11
+ } from "./chunk-NSQE6YRP.js";
12
12
  import {
13
13
  securePrivatePath
14
14
  } from "./chunk-GTK4KOED.js";
@@ -50,4 +50,4 @@ export {
50
50
  createStore,
51
51
  createClientRuntime
52
52
  };
53
- //# sourceMappingURL=chunk-TZHXTMPJ.js.map
53
+ //# sourceMappingURL=chunk-DBQ5PNQW.js.map
@@ -10,7 +10,7 @@ import {
10
10
  isSupportedLocalSqliteSchemaContract,
11
11
  sqliteSchemaContractHash,
12
12
  verifySqliteHealth
13
- } from "./chunk-7PYY3S27.js";
13
+ } from "./chunk-NSQE6YRP.js";
14
14
  import {
15
15
  preparePrivateFileLocation,
16
16
  preparePrivateSqliteLocation,
@@ -2686,4 +2686,4 @@ export {
2686
2686
  restoreLocalSqlite,
2687
2687
  SQLITE_EDGE_APPLICATION_ID
2688
2688
  };
2689
- //# sourceMappingURL=chunk-7Q5THTJH.js.map
2689
+ //# sourceMappingURL=chunk-H2UAY6AV.js.map
@@ -3,8 +3,9 @@ import {
3
3
  SQLITE_INITIALIZATION_BUSY_TIMEOUT_MS,
4
4
  assertEdgeUpgradeCandidate,
5
5
  installEdgeMarkers,
6
- retrySqliteBusy
7
- } from "./chunk-7PYY3S27.js";
6
+ retrySqliteBusy,
7
+ rollbackSqliteTransaction
8
+ } from "./chunk-NSQE6YRP.js";
8
9
  import {
9
10
  preparePrivateSqliteLocation,
10
11
  securePrivatePath,
@@ -296,7 +297,7 @@ var SQLiteEdgeStore = class {
296
297
  this.db.exec("COMMIT");
297
298
  return update.changes === 1;
298
299
  } catch (error) {
299
- this.db.exec("ROLLBACK");
300
+ rollbackSqliteTransaction(this.db);
300
301
  throw error;
301
302
  }
302
303
  }, Math.max(1, deadline - Date.now()));
@@ -318,7 +319,7 @@ var SQLiteEdgeStore = class {
318
319
  this.db.prepare("UPDATE edge_write_gates SET lease_token=NULL,lease_expires_at=NULL WHERE gate_key='edge' AND lease_token=?").run(token);
319
320
  this.db.exec("COMMIT");
320
321
  } catch (error) {
321
- this.db.exec("ROLLBACK");
322
+ rollbackSqliteTransaction(this.db);
322
323
  throw error;
323
324
  }
324
325
  }, Math.max(1, Math.trunc(this.writeGateWaitMs)));
@@ -339,7 +340,7 @@ var SQLiteEdgeStore = class {
339
340
  if (!exists()) this.db.exec(writeGateSchema);
340
341
  this.db.exec("COMMIT");
341
342
  } catch (error) {
342
- this.db.exec("ROLLBACK");
343
+ rollbackSqliteTransaction(this.db);
343
344
  throw error;
344
345
  }
345
346
  }, timeoutMs);
@@ -439,7 +440,7 @@ var SQLiteEdgeStore = class {
439
440
  installEdgeMarkers(this.db);
440
441
  this.db.exec("COMMIT");
441
442
  } catch (error) {
442
- this.db.exec("ROLLBACK");
443
+ rollbackSqliteTransaction(this.db);
443
444
  throw error;
444
445
  }
445
446
  this.restrictFiles();
@@ -457,7 +458,7 @@ var SQLiteEdgeStore = class {
457
458
  this.db.prepare("UPDATE edge_scopes SET pull_cursor=NULL, cache_contract=1 WHERE scope_key=?").run(this.key);
458
459
  this.db.exec("COMMIT");
459
460
  } catch (error) {
460
- this.db.exec("ROLLBACK");
461
+ rollbackSqliteTransaction(this.db);
461
462
  throw error;
462
463
  }
463
464
  }
@@ -479,7 +480,7 @@ var SQLiteEdgeStore = class {
479
480
  this.assertScopeActiveInTransaction();
480
481
  this.db.exec("COMMIT");
481
482
  } catch (error) {
482
- this.db.exec("ROLLBACK");
483
+ rollbackSqliteTransaction(this.db);
483
484
  throw error;
484
485
  }
485
486
  });
@@ -494,7 +495,7 @@ var SQLiteEdgeStore = class {
494
495
  this.assertDrainLeaseInTransaction(lease, now);
495
496
  this.db.exec("COMMIT");
496
497
  } catch (error) {
497
- this.db.exec("ROLLBACK");
498
+ rollbackSqliteTransaction(this.db);
498
499
  throw error;
499
500
  }
500
501
  });
@@ -529,7 +530,7 @@ var SQLiteEdgeStore = class {
529
530
  this.db.exec("COMMIT");
530
531
  return { scopeKey: this.key, operationId: normalizedOperationId, leaseToken, leaseExpiresAt };
531
532
  } catch (error) {
532
- this.db.exec("ROLLBACK");
533
+ rollbackSqliteTransaction(this.db);
533
534
  throw error;
534
535
  }
535
536
  });
@@ -575,7 +576,7 @@ var SQLiteEdgeStore = class {
575
576
  }
576
577
  this.db.exec("COMMIT");
577
578
  } catch (error) {
578
- this.db.exec("ROLLBACK");
579
+ rollbackSqliteTransaction(this.db);
579
580
  throw error;
580
581
  }
581
582
  });
@@ -603,7 +604,7 @@ var SQLiteEdgeStore = class {
603
604
  this.db.exec("COMMIT");
604
605
  return { ...lease, leaseExpiresAt };
605
606
  } catch (error) {
606
- this.db.exec("ROLLBACK");
607
+ rollbackSqliteTransaction(this.db);
607
608
  throw error;
608
609
  }
609
610
  });
@@ -629,7 +630,7 @@ var SQLiteEdgeStore = class {
629
630
  if (updated.changes !== 1) throw new EdgeMigrationLeaseError();
630
631
  this.db.exec("COMMIT");
631
632
  } catch (error) {
632
- this.db.exec("ROLLBACK");
633
+ rollbackSqliteTransaction(this.db);
633
634
  throw error;
634
635
  }
635
636
  });
@@ -659,7 +660,7 @@ var SQLiteEdgeStore = class {
659
660
  this.db.exec("COMMIT");
660
661
  return { draft, created: true };
661
662
  } catch (error) {
662
- this.db.exec("ROLLBACK");
663
+ rollbackSqliteTransaction(this.db);
663
664
  throw error;
664
665
  }
665
666
  });
@@ -698,7 +699,7 @@ var SQLiteEdgeStore = class {
698
699
  createdAt: String(head.created_at)
699
700
  };
700
701
  } catch (error) {
701
- this.db.exec("ROLLBACK");
702
+ rollbackSqliteTransaction(this.db);
702
703
  throw error;
703
704
  }
704
705
  });
@@ -730,7 +731,7 @@ var SQLiteEdgeStore = class {
730
731
  this.db.prepare("UPDATE edge_scopes SET last_outbound_sync_at=? WHERE scope_key=?").run(now.toISOString(), this.key);
731
732
  this.db.exec("COMMIT");
732
733
  } catch (error) {
733
- this.db.exec("ROLLBACK");
734
+ rollbackSqliteTransaction(this.db);
734
735
  throw error;
735
736
  }
736
737
  });
@@ -781,7 +782,7 @@ var SQLiteEdgeStore = class {
781
782
  this.db.prepare("UPDATE edge_scopes SET last_inbound_sync_at=? WHERE scope_key=?").run(now.toISOString(), this.key);
782
783
  this.db.exec("COMMIT");
783
784
  } catch (error) {
784
- this.db.exec("ROLLBACK");
785
+ rollbackSqliteTransaction(this.db);
785
786
  throw error;
786
787
  }
787
788
  });
@@ -796,7 +797,7 @@ var SQLiteEdgeStore = class {
796
797
  this.db.prepare("UPDATE edge_scopes SET last_inbound_sync_at=? WHERE scope_key=?").run(now.toISOString(), this.key);
797
798
  this.db.exec("COMMIT");
798
799
  } catch (error) {
799
- this.db.exec("ROLLBACK");
800
+ rollbackSqliteTransaction(this.db);
800
801
  throw error;
801
802
  }
802
803
  });
@@ -1512,4 +1513,4 @@ export {
1512
1513
  isRetryableSyncError,
1513
1514
  SyncingBridgeStore
1514
1515
  };
1515
- //# sourceMappingURL=chunk-U4M67GFU.js.map
1516
+ //# sourceMappingURL=chunk-HIYXPNBE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sqlite-edge-store.ts","../src/syncing-bridge-store.ts"],"sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport { existsSync, lstatSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { pathToFileURL } from \"node:url\";\nimport type { DatabaseSync as Database, SQLInputValue } from \"node:sqlite\";\nimport {\n cursorScope,\n decodeCursor,\n encodeCursor,\n type BridgeMessage,\n type BridgePrincipal,\n type JsonValue,\n} from \"./bridge-domain.js\";\nimport type { MessagePage, MessageQuery } from \"./bridge-store.js\";\nimport { retrySqliteBusy, rollbackSqliteTransaction, SQLITE_INITIALIZATION_BUSY_TIMEOUT_MS } from \"./sqlite-retry.js\";\nimport { preparePrivateSqliteLocation, securePrivatePath, securePrivateSqliteSidecar, verifyPrivatePathAccess } from \"./private-path.js\";\nimport { assertEdgeUpgradeCandidate, installEdgeMarkers } from \"./sqlite-database-contract.js\";\n\nconst require = createRequire(import.meta.url);\nfunction openDatabase(path: string): Database {\n const { DatabaseSync } = require(\"node:sqlite\") as typeof import(\"node:sqlite\");\n return new DatabaseSync(path);\n}\nfunction openReadOnlyDatabase(path: string): Database {\n const { DatabaseSync } = require(\"node:sqlite\") as typeof import(\"node:sqlite\");\n // immutable=1 prevents SQLite from creating a WAL shared-memory sidecar while\n // evaluating a dry-run. A present WAL is rejected below because immutable reads\n // cannot safely incorporate its uncheckpointed state.\n return new DatabaseSync(`${pathToFileURL(path).toString()}?immutable=1`, { readOnly: true });\n}\nconst MAX_SEQUENCE = 9_223_372_036_854_775_807n;\n\nconst schema = `\nCREATE TABLE IF NOT EXISTS edge_scopes (\n scope_key TEXT PRIMARY KEY,\n endpoint_hash TEXT NOT NULL,\n workspace TEXT NOT NULL,\n agent TEXT NOT NULL,\n pull_cursor TEXT,\n last_sync_at TEXT,\n last_error TEXT,\n last_outbound_sync_at TEXT,\n last_inbound_sync_at TEXT,\n last_attempt_at TEXT,\n cache_contract INTEGER NOT NULL DEFAULT 1\n);\nCREATE TABLE IF NOT EXISTS edge_migration_gates (\n scope_key TEXT PRIMARY KEY REFERENCES edge_scopes(scope_key),\n state TEXT NOT NULL CHECK(state IN ('active', 'draining', 'retired')),\n operation_id TEXT,\n lease_token TEXT,\n lease_expires_at TEXT,\n updated_at TEXT NOT NULL,\n CHECK(\n (state='active' AND operation_id IS NULL AND lease_token IS NULL AND lease_expires_at IS NULL)\n OR (state='draining' AND operation_id IS NOT NULL AND lease_token IS NOT NULL AND lease_expires_at IS NOT NULL)\n OR (state='retired' AND operation_id IS NOT NULL AND lease_token IS NULL AND lease_expires_at IS NULL)\n )\n);\nCREATE INDEX IF NOT EXISTS edge_migration_gates_state\n ON edge_migration_gates(state, lease_expires_at);\nCREATE TABLE IF NOT EXISTS edge_outbox (\n position INTEGER PRIMARY KEY AUTOINCREMENT,\n scope_key TEXT NOT NULL REFERENCES edge_scopes(scope_key),\n message_id TEXT NOT NULL,\n idempotency_key TEXT NOT NULL,\n payload_hash TEXT NOT NULL,\n draft_json TEXT NOT NULL,\n state TEXT NOT NULL CHECK(state IN ('pending', 'blocked')),\n attempts INTEGER NOT NULL DEFAULT 0,\n available_at TEXT NOT NULL,\n lease_token TEXT,\n lease_expires_at TEXT,\n last_error TEXT,\n blocked_at TEXT,\n created_at TEXT NOT NULL,\n UNIQUE(scope_key, message_id),\n UNIQUE(scope_key, idempotency_key)\n);\nCREATE INDEX IF NOT EXISTS edge_outbox_due\n ON edge_outbox(scope_key, state, available_at, position);\nCREATE TRIGGER IF NOT EXISTS edge_outbox_migration_gate_insert\nBEFORE INSERT ON edge_outbox\nWHEN NOT EXISTS (\n SELECT 1 FROM edge_migration_gates\n WHERE scope_key=NEW.scope_key AND state='active'\n)\nBEGIN\n SELECT RAISE(ABORT, 'edge migration gate rejects outbox publication');\nEND;\nCREATE TABLE IF NOT EXISTS edge_inbox (\n scope_key TEXT NOT NULL REFERENCES edge_scopes(scope_key),\n message_id TEXT NOT NULL,\n remote_sequence TEXT NOT NULL,\n sequence_key TEXT NOT NULL,\n workspace TEXT NOT NULL,\n project TEXT,\n source TEXT NOT NULL,\n type TEXT NOT NULL,\n thread_id TEXT,\n created_at TEXT NOT NULL,\n expires_at TEXT,\n message_json TEXT NOT NULL,\n PRIMARY KEY(scope_key, message_id),\n UNIQUE(scope_key, sequence_key)\n);\nCREATE INDEX IF NOT EXISTS edge_inbox_cursor\n ON edge_inbox(scope_key, sequence_key);\nCREATE INDEX IF NOT EXISTS edge_inbox_source\n ON edge_inbox(scope_key, source, sequence_key);\nCREATE INDEX IF NOT EXISTS edge_inbox_thread\n ON edge_inbox(scope_key, thread_id, sequence_key);\nCREATE INDEX IF NOT EXISTS edge_inbox_created\n ON edge_inbox(scope_key, created_at, sequence_key);\n`;\nconst writeGateSchema = \"CREATE TABLE IF NOT EXISTS edge_write_gates (gate_key TEXT PRIMARY KEY, lease_token TEXT, lease_expires_at TEXT)\";\n\ntype Row = Record<string, unknown>;\nexport type PendingMessage = Omit<BridgeMessage, \"sequence\" | \"createdAt\">;\n\nexport interface EdgeScope {\n endpoint: string;\n principal: BridgePrincipal;\n}\n\n/** A side-effect-free inspection used by migration dry-runs and preflight gates. */\nexport interface EdgeReadOnlyInspection {\n exists: boolean;\n gate: EdgeMigrationGate;\n pending: number;\n due: number;\n scheduled: number;\n leased: number;\n blocked: number;\n cached: number;\n}\n\n/**\n * Inspect an edge without creating a database, a schema object, or a WAL sidecar.\n * An absent path has the same empty active state that initialization would create.\n */\nexport function inspectEdgeScopeReadOnly(path: string, scope: EdgeScope, now = new Date()): EdgeReadOnlyInspection {\n if (!existsSync(path)) {\n return { exists: false, gate: { scopeKey: edgeScopeKey(scope), state: \"active\", operationId: undefined, leaseExpiresAt: undefined, updatedAt: new Date(0).toISOString() }, pending: 0, due: 0, scheduled: 0, leased: 0, blocked: 0, cached: 0 };\n }\n verifyPrivatePathAccess(path, \"file\");\n const details = lstatSync(path);\n if (!details.isFile() || details.isSymbolicLink()) throw new EdgeConflictError(\"edge database is not a private regular file\");\n if (existsSync(`${path}-wal`) || existsSync(`${path}-shm`)) {\n throw new EdgeConflictError(\"read-only migration inspection refuses an edge with live WAL state\");\n }\n const db = openReadOnlyDatabase(path);\n try {\n const tables = db.prepare(\"SELECT name FROM sqlite_master WHERE type='table' AND name IN ('edge_scopes','edge_migration_gates','edge_outbox','edge_inbox','edge_write_gates') ORDER BY name\")\n .all() as Row[];\n if (tables.length === 0) {\n const userTables = db.prepare(\"SELECT count(*) AS count FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'\").get() as Row;\n if (Number(userTables.count) !== 0) throw new EdgeConflictError(\"edge database is not an Agent Bridge edge store\");\n return { exists: true, gate: { scopeKey: edgeScopeKey(scope), state: \"active\", operationId: undefined, leaseExpiresAt: undefined, updatedAt: new Date(0).toISOString() }, pending: 0, due: 0, scheduled: 0, leased: 0, blocked: 0, cached: 0 };\n }\n const names = new Set(tables.map((table) => String(table.name)));\n for (const name of [\"edge_scopes\", \"edge_migration_gates\", \"edge_outbox\", \"edge_inbox\"]) {\n if (!names.has(name)) throw new EdgeConflictError(\"edge database schema is incomplete\");\n }\n const key = edgeScopeKey(scope);\n const scopeRow = db.prepare(\"SELECT 1 AS present FROM edge_scopes WHERE scope_key=?\").get(key) as Row | undefined;\n if (!scopeRow) {\n return { exists: true, gate: { scopeKey: key, state: \"active\", operationId: undefined, leaseExpiresAt: undefined, updatedAt: new Date(0).toISOString() }, pending: 0, due: 0, scheduled: 0, leased: 0, blocked: 0, cached: 0 };\n }\n const gateRow = db.prepare(\"SELECT state,operation_id,lease_expires_at,updated_at FROM edge_migration_gates WHERE scope_key=?\").get(key) as Row | undefined;\n if (!gateRow || ![\"active\", \"draining\", \"retired\"].includes(String(gateRow.state))) throw new EdgeConflictError(\"edge migration gate is missing or invalid\");\n const nowText = now.toISOString();\n const counts = db.prepare(`SELECT\n sum(CASE WHEN state='pending' THEN 1 ELSE 0 END) AS pending,\n sum(CASE WHEN state='pending' AND available_at<=? AND (lease_expires_at IS NULL OR lease_expires_at<=?) THEN 1 ELSE 0 END) AS due,\n sum(CASE WHEN state='pending' AND available_at>? AND (lease_expires_at IS NULL OR lease_expires_at<=?) THEN 1 ELSE 0 END) AS scheduled,\n sum(CASE WHEN state='pending' AND lease_expires_at>? THEN 1 ELSE 0 END) AS leased,\n sum(CASE WHEN state='blocked' THEN 1 ELSE 0 END) AS blocked\n FROM edge_outbox WHERE scope_key=?`).get(nowText, nowText, nowText, nowText, nowText, key) as Row;\n const cached = db.prepare(\"SELECT count(*) AS count FROM edge_inbox WHERE scope_key=?\").get(key) as Row;\n return {\n exists: true,\n gate: { scopeKey: key, state: gateRow.state as EdgeMigrationGateState, operationId: gateRow.operation_id ? String(gateRow.operation_id) : undefined, leaseExpiresAt: gateRow.lease_expires_at ? String(gateRow.lease_expires_at) : undefined, updatedAt: gateRow.updated_at ? String(gateRow.updated_at) : new Date(0).toISOString() },\n pending: Number(counts.pending ?? 0), due: Number(counts.due ?? 0), scheduled: Number(counts.scheduled ?? 0), leased: Number(counts.leased ?? 0), blocked: Number(counts.blocked ?? 0), cached: Number(cached.count ?? 0),\n };\n } finally { db.close(); }\n}\n\nexport interface EdgeOutboxRecord {\n position: number;\n draft: PendingMessage;\n payloadHash: string;\n attempts: number;\n leaseToken: string;\n createdAt: string;\n}\n\nexport interface EdgeEnqueueResult {\n draft: PendingMessage;\n created: boolean;\n}\n\nexport interface EdgeStats {\n pending: number;\n due: number;\n scheduled: number;\n leased: number;\n blocked: number;\n cached: number;\n pullCursor?: string;\n lastSyncAt?: string;\n lastError?: string;\n oldestDueAt?: string;\n queueLagMs: number;\n oldestBlockedAt?: string;\n blockedAgeMs: number | null;\n blockedMaxAttempts: number;\n blockedLastError?: string;\n nextRetryAt?: string;\n lastOutboundSyncAt?: string;\n lastInboundSyncAt?: string;\n lastAttemptAt?: string;\n migrationState: EdgeMigrationGateState;\n migrationOperationId?: string;\n migrationLeaseExpiresAt?: string;\n}\n\nexport type EdgeMigrationGateState = \"active\" | \"draining\" | \"retired\";\n\nexport interface EdgeMigrationGate {\n scopeKey: string;\n state: EdgeMigrationGateState;\n operationId?: string;\n leaseExpiresAt?: string;\n updatedAt: string;\n}\n\nexport interface EdgeDrainLease {\n scopeKey: string;\n operationId: string;\n leaseToken: string;\n leaseExpiresAt: string;\n}\n\nexport class EdgeConflictError extends Error {\n readonly code = \"edge_idempotency_conflict\";\n}\n\nexport class EdgeMigrationDrainingError extends Error {\n readonly code = \"client_migration_draining\";\n constructor(readonly gate: EdgeMigrationGate) {\n super(\"edge scope is draining for a client migration\");\n }\n}\n\nexport class EdgeMigrationRetiredError extends Error {\n readonly code = \"client_migration_retired\";\n constructor(readonly gate: EdgeMigrationGate) {\n super(\"edge scope was retired by a client migration\");\n }\n}\n\nexport class EdgeMigrationLeaseError extends Error {\n readonly code = \"client_migration_lease_lost\";\n constructor() {\n super(\"client migration worker no longer holds the edge drain lease\");\n }\n}\n\nfunction canonical(value: JsonValue | undefined): string {\n if (value === undefined) return \"null\";\n if (value === null || typeof value !== \"object\") return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(canonical).join(\",\")}]`;\n return `{${Object.keys(value).filter((key) => value[key] !== undefined).sort()\n .map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(\",\")}}`;\n}\n\nfunction intent(message: PendingMessage | BridgeMessage): JsonValue {\n const deliveryPolicy = message.deliveryPolicy ?? (message.targets.length\n ? { mode: \"leased\", maxAttempts: 5, retryBaseDelayMs: 1_000, retryMaxDelayMs: 60_000, retryJitterRatio: 0.2 }\n : { mode: \"mailbox\" });\n return {\n workspace: message.workspace,\n project: message.project ?? null,\n source: message.source,\n type: message.type,\n content: message.content,\n contentType: message.contentType,\n data: message.data ?? null,\n targets: [...message.targets].sort(),\n threadId: message.threadId ?? null,\n replyToId: message.replyToId ?? null,\n correlationId: message.correlationId ?? null,\n causationId: message.causationId ?? null,\n priority: message.priority,\n expiresAt: message.expiresAt ?? null,\n atribReceiptId: message.atribReceiptId ?? null,\n informedBy: [...(message.informedBy ?? [])].sort(),\n metadata: message.metadata ?? null,\n deliveryPolicy: deliveryPolicy as unknown as JsonValue,\n };\n}\n\nexport function edgeMessageFingerprint(message: PendingMessage | BridgeMessage): string {\n return createHash(\"sha256\").update(canonical(intent(message))).digest(\"hex\");\n}\n\nexport function stableIdempotency(message: PendingMessage): PendingMessage {\n return message.idempotencyKey\n ? message\n : { ...message, idempotencyKey: `agent-bridge:id:${message.id}` };\n}\n\nexport function edgeScopeKey(scope: EdgeScope): string {\n return createHash(\"sha256\")\n .update(`${scope.endpoint.replace(/\\/$/, \"\")}\\0${scope.principal.workspace}\\0${scope.principal.agent}`)\n .digest(\"hex\");\n}\n\nfunction sequenceKey(sequence: string): string {\n if (!/^(0|[1-9][0-9]*)$/.test(sequence) || BigInt(sequence) > MAX_SEQUENCE) {\n throw new EdgeConflictError(\"remote sequence is invalid\");\n }\n return sequence.padStart(19, \"0\");\n}\n\nfunction parseDraft(value: unknown): PendingMessage {\n return JSON.parse(String(value)) as PendingMessage;\n}\n\nfunction parseMessage(value: unknown): BridgeMessage {\n return JSON.parse(String(value)) as BridgeMessage;\n}\n\nfunction safeOperationId(value: string): string {\n if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)) {\n throw new Error(\"client migration operation ID is invalid\");\n }\n return value.toLowerCase();\n}\n\nexport class SQLiteEdgeStore {\n private readonly db: Database;\n private readonly databasePath: string;\n private readonly preexistingFiles: ReadonlySet<string>;\n private readonly key: string;\n private initialized = false;\n private initialization?: Promise<void>;\n\n constructor(\n private readonly path: string,\n private readonly scope: EdgeScope,\n private readonly busyTimeoutMs = 2_000,\n private readonly writeGateLeaseMs = 30_000,\n // Windows first-open ACL work is materially slower with many concurrent clients.\n private readonly writeGateWaitMs = process.platform === \"win32\" ? 60_000 : SQLITE_INITIALIZATION_BUSY_TIMEOUT_MS,\n ) {\n const selected = preparePrivateSqliteLocation(path, true, \"defer\");\n this.databasePath = selected;\n this.preexistingFiles = new Set(selected === \":memory:\" ? [] : [selected, `${selected}-wal`, `${selected}-shm`].filter(existsSync));\n const before = selected === \":memory:\" || !existsSync(selected) ? undefined : lstatSync(selected);\n this.db = openDatabase(selected);\n try {\n this.db.exec(`PRAGMA busy_timeout = ${Math.max(1, Math.trunc(this.busyTimeoutMs))}`);\n this.restrictFiles(false);\n if (before) {\n const after = lstatSync(selected);\n if (after.dev !== before.dev || after.ino !== before.ino) throw new Error(\"SQLite edge database path identity changed while opening\");\n }\n } catch (error) { this.db.close(); throw error; }\n this.key = edgeScopeKey(scope);\n }\n\n private async write<T>(work: () => T | Promise<T>): Promise<T> {\n if (this.databasePath === \":memory:\") return work();\n const token = randomUUID();\n const deadline = Date.now() + Math.max(1, Math.trunc(this.writeGateWaitMs));\n let pause = 2;\n while (true) {\n const now = new Date();\n const claimed = await retrySqliteBusy(() => {\n this.db.exec(\"BEGIN IMMEDIATE\");\n try {\n this.db.prepare(\"INSERT INTO edge_write_gates (gate_key,lease_token,lease_expires_at) VALUES ('edge',NULL,NULL) ON CONFLICT(gate_key) DO NOTHING\").run();\n const update = this.db.prepare(`UPDATE edge_write_gates SET lease_token=?,lease_expires_at=?\n WHERE gate_key='edge' AND (lease_token IS NULL OR lease_expires_at<=?)`).run(\n token, new Date(now.getTime() + Math.max(1, Math.trunc(this.writeGateLeaseMs))).toISOString(), now.toISOString(),\n );\n this.db.exec(\"COMMIT\");\n return update.changes === 1;\n } catch (error) { rollbackSqliteTransaction(this.db); throw error; }\n }, Math.max(1, deadline - Date.now()));\n if (claimed) break;\n if (Date.now() >= deadline) throw new EdgeConflictError(\"edge write coordinator remained busy\");\n await new Promise((resolve) => setTimeout(resolve, pause));\n pause = Math.min(Math.ceil(pause * 1.7), 25);\n }\n let completed = false;\n let result: T;\n try {\n result = await work();\n completed = true;\n }\n finally {\n try {\n await retrySqliteBusy(() => {\n this.db.exec(\"BEGIN IMMEDIATE\");\n try {\n this.db.prepare(\"UPDATE edge_write_gates SET lease_token=NULL,lease_expires_at=NULL WHERE gate_key='edge' AND lease_token=?\").run(token);\n this.db.exec(\"COMMIT\");\n } catch (error) { rollbackSqliteTransaction(this.db); throw error; }\n }, Math.max(1, Math.trunc(this.writeGateWaitMs)));\n } catch (error) {\n if (!completed) throw error;\n }\n }\n return result!;\n }\n\n private async bootstrapWriteGate(timeoutMs: number): Promise<void> {\n await retrySqliteBusy(() => this.db.exec(\"PRAGMA journal_mode = WAL\"), timeoutMs);\n const exists = () => Boolean(this.db.prepare(\"SELECT 1 FROM sqlite_master WHERE type='table' AND name='edge_write_gates'\").get());\n if (exists()) return;\n await retrySqliteBusy(() => {\n if (exists()) return;\n this.db.exec(\"BEGIN IMMEDIATE\");\n try { if (!exists()) this.db.exec(writeGateSchema); this.db.exec(\"COMMIT\"); }\n catch (error) { rollbackSqliteTransaction(this.db); throw error; }\n }, timeoutMs);\n }\n\n private restrictFiles(includeSidecars = true): void {\n if (this.databasePath === \":memory:\") return;\n const paths = includeSidecars\n ? [this.databasePath, `${this.databasePath}-wal`, `${this.databasePath}-shm`]\n : [this.databasePath];\n for (const path of paths) {\n if (!existsSync(path)) continue;\n if (path === this.databasePath && this.preexistingFiles.has(path)) verifyPrivatePathAccess(path, \"file\");\n else if (path === this.databasePath) securePrivatePath(path, \"file\");\n else securePrivateSqliteSidecar(path);\n }\n }\n\n get scopeKey(): string {\n return this.key;\n }\n\n private gateFromRow(row: Row): EdgeMigrationGate {\n const state = String(row.state);\n if (state !== \"active\" && state !== \"draining\" && state !== \"retired\") {\n throw new EdgeConflictError(\"edge migration gate state is invalid\");\n }\n const operationId = row.operation_id === null || row.operation_id === undefined\n ? undefined\n : safeOperationId(String(row.operation_id));\n const leaseExpiresAt = row.lease_expires_at === null || row.lease_expires_at === undefined\n ? undefined\n : String(row.lease_expires_at);\n const updatedAt = String(row.updated_at ?? \"\");\n if (!updatedAt || !Number.isFinite(Date.parse(updatedAt))) {\n throw new EdgeConflictError(\"edge migration gate timestamp is invalid\");\n }\n const leaseToken = row.lease_token === null || row.lease_token === undefined\n ? undefined\n : String(row.lease_token);\n if ((state === \"active\" && (operationId || leaseExpiresAt || leaseToken))\n || (state === \"draining\" && (!operationId || !leaseExpiresAt || !leaseToken))\n || (state === \"retired\" && (!operationId || leaseExpiresAt || leaseToken))) {\n throw new EdgeConflictError(\"edge migration gate state is invalid\");\n }\n return { scopeKey: this.key, state, operationId, leaseExpiresAt, updatedAt };\n }\n\n private gateInTransaction(): EdgeMigrationGate {\n const row = this.db.prepare(`SELECT state,operation_id,lease_token,lease_expires_at,updated_at\n FROM edge_migration_gates WHERE scope_key=?`).get(this.key) as Row | undefined;\n if (!row) throw new EdgeConflictError(\"edge migration gate is missing\");\n return this.gateFromRow(row);\n }\n\n private assertScopeActiveInTransaction(): void {\n const gate = this.gateInTransaction();\n if (gate.state === \"draining\") throw new EdgeMigrationDrainingError(gate);\n if (gate.state === \"retired\") throw new EdgeMigrationRetiredError(gate);\n }\n\n private assertDrainLeaseInTransaction(lease: EdgeDrainLease, now: Date): void {\n const gate = this.gateInTransaction();\n if (gate.state !== \"draining\" || gate.operationId !== lease.operationId\n || gate.leaseExpiresAt !== lease.leaseExpiresAt || Date.parse(gate.leaseExpiresAt) <= now.getTime()) {\n throw new EdgeMigrationLeaseError();\n }\n const row = this.db.prepare(\"SELECT lease_token FROM edge_migration_gates WHERE scope_key=?\")\n .get(this.key) as Row;\n if (row.lease_token !== lease.leaseToken) throw new EdgeMigrationLeaseError();\n }\n\n private assertClaimAuthorityInTransaction(now: Date, lease?: EdgeDrainLease): void {\n if (lease) this.assertDrainLeaseInTransaction(lease, now);\n else this.assertScopeActiveInTransaction();\n }\n\n async initialize(): Promise<void> {\n if (this.initialized) return;\n if (!this.initialization) {\n this.initialization = this.initializeOnce().then(() => {\n this.initialized = true;\n }).catch((error) => {\n this.initialization = undefined;\n throw error;\n });\n }\n return this.initialization;\n }\n\n private async initializeOnce(): Promise<void> {\n assertEdgeUpgradeCandidate(this.db);\n const initializationTimeoutMs = Math.max(this.busyTimeoutMs, SQLITE_INITIALIZATION_BUSY_TIMEOUT_MS);\n await this.bootstrapWriteGate(initializationTimeoutMs);\n this.db.exec(\"PRAGMA synchronous = FULL; PRAGMA foreign_keys = ON\");\n await this.write(async () => {\n await retrySqliteBusy(() => this.db.exec(\"BEGIN IMMEDIATE\"), initializationTimeoutMs);\n try {\n this.db.exec(schema);\n const scopeColumns = this.db.prepare(\"PRAGMA table_info(edge_scopes)\").all() as Row[];\n if (!scopeColumns.some((column) => column.name === \"cache_contract\")) {\n this.db.exec(\"ALTER TABLE edge_scopes ADD COLUMN cache_contract INTEGER NOT NULL DEFAULT 0\");\n }\n for (const name of [\"last_outbound_sync_at\", \"last_inbound_sync_at\", \"last_attempt_at\"]) {\n if (!scopeColumns.some((column) => column.name === name)) {\n this.db.exec(`ALTER TABLE edge_scopes ADD COLUMN ${name} TEXT`);\n }\n }\n const columns = this.db.prepare(\"PRAGMA table_info(edge_inbox)\").all() as Row[];\n if (!columns.some((column) => column.name === \"project\")) {\n this.db.exec(\"ALTER TABLE edge_inbox ADD COLUMN project TEXT\");\n }\n this.db.exec(\"CREATE INDEX IF NOT EXISTS edge_inbox_project ON edge_inbox(scope_key, project, sequence_key)\");\n const outboxColumns = this.db.prepare(\"PRAGMA table_info(edge_outbox)\").all() as Row[];\n if (!outboxColumns.some((column) => column.name === \"blocked_at\")) {\n this.db.exec(\"ALTER TABLE edge_outbox ADD COLUMN blocked_at TEXT\");\n }\n installEdgeMarkers(this.db);\n this.db.exec(\"COMMIT\");\n } catch (error) {\n rollbackSqliteTransaction(this.db);\n throw error;\n }\n this.restrictFiles();\n const endpointHash = createHash(\"sha256\").update(this.scope.endpoint.replace(/\\/$/, \"\")).digest(\"hex\");\n this.db.prepare(`INSERT INTO edge_scopes (scope_key, endpoint_hash, workspace, agent)\n VALUES (?, ?, ?, ?) ON CONFLICT(scope_key) DO NOTHING`)\n .run(this.key, endpointHash, this.scope.principal.workspace, this.scope.principal.agent);\n this.db.prepare(`INSERT INTO edge_migration_gates\n (scope_key,state,operation_id,lease_token,lease_expires_at,updated_at)\n SELECT scope_key,'active',NULL,NULL,NULL,? FROM edge_scopes\n WHERE scope_key=? ON CONFLICT(scope_key) DO NOTHING`)\n .run(new Date().toISOString(), this.key);\n const contract = this.db.prepare(\"SELECT cache_contract FROM edge_scopes WHERE scope_key=?\").get(this.key) as Row;\n if (Number(contract.cache_contract) < 1) {\n this.db.exec(\"BEGIN IMMEDIATE\");\n try {\n this.db.prepare(\"UPDATE edge_scopes SET pull_cursor=NULL, cache_contract=1 WHERE scope_key=?\").run(this.key);\n this.db.exec(\"COMMIT\");\n } catch (error) { rollbackSqliteTransaction(this.db); throw error; }\n }\n });\n }\n\n private async ready(): Promise<void> {\n await this.initialize();\n }\n\n async migrationGate(): Promise<EdgeMigrationGate> {\n await this.ready();\n return this.gateInTransaction();\n }\n\n /** Refuse new normal-client writes before any remote attempt begins. */\n async assertScopeActive(): Promise<void> {\n await this.ready();\n await this.write(() => {\n this.db.exec(\"BEGIN IMMEDIATE\");\n try {\n this.assertScopeActiveInTransaction();\n this.db.exec(\"COMMIT\");\n } catch (error) {\n rollbackSqliteTransaction(this.db);\n throw error;\n }\n });\n }\n\n /** Refuse remote publication unless this worker still owns the durable drain lease. */\n async assertDrainLease(lease: EdgeDrainLease, now = new Date()): Promise<void> {\n await this.ready();\n if (lease.scopeKey !== this.key) throw new EdgeMigrationLeaseError();\n await this.write(() => {\n this.db.exec(\"BEGIN IMMEDIATE\");\n try {\n this.assertDrainLeaseInTransaction(lease, now);\n this.db.exec(\"COMMIT\");\n } catch (error) {\n rollbackSqliteTransaction(this.db);\n throw error;\n }\n });\n }\n\n private async claimDrainLease(\n operationId: string, now: Date, leaseMs: number, mode: \"begin\" | \"resume\",\n ): Promise<EdgeDrainLease> {\n await this.ready();\n const normalizedOperationId = safeOperationId(operationId);\n const duration = Math.max(1, Math.trunc(leaseMs));\n return this.write(() => {\n this.db.exec(\"BEGIN IMMEDIATE\");\n try {\n const gate = this.gateInTransaction();\n if (gate.state === \"retired\") throw new EdgeMigrationRetiredError(gate);\n if (mode === \"begin\" && gate.state !== \"active\") throw new EdgeMigrationDrainingError(gate);\n if (mode === \"resume\") {\n if (gate.state !== \"draining\" || gate.operationId !== normalizedOperationId\n || !gate.leaseExpiresAt || Date.parse(gate.leaseExpiresAt) > now.getTime()) {\n throw new EdgeMigrationDrainingError(gate);\n }\n }\n const leaseToken = randomUUID();\n const leaseExpiresAt = new Date(now.getTime() + duration).toISOString();\n const updated = this.db.prepare(`UPDATE edge_migration_gates\n SET state='draining',operation_id=?,lease_token=?,lease_expires_at=?,updated_at=?\n WHERE scope_key=?`).run(\n normalizedOperationId, leaseToken, leaseExpiresAt, now.toISOString(), this.key,\n );\n if (updated.changes !== 1) throw new EdgeConflictError(\"edge migration gate could not be acquired\");\n this.db.exec(\"COMMIT\");\n return { scopeKey: this.key, operationId: normalizedOperationId, leaseToken, leaseExpiresAt };\n } catch (error) {\n rollbackSqliteTransaction(this.db);\n throw error;\n }\n });\n }\n\n /** Start a new durable drain only from an active edge scope. */\n async beginDrain(operationId: string, now = new Date(), leaseMs = 30_000): Promise<EdgeDrainLease> {\n return this.claimDrainLease(operationId, now, leaseMs, \"begin\");\n }\n\n /** Resume the same persisted drain only after the prior worker lease expires. */\n async resumeDrain(operationId: string, now = new Date(), leaseMs = 30_000): Promise<EdgeDrainLease> {\n return this.claimDrainLease(operationId, now, leaseMs, \"resume\");\n }\n\n /** Backward-compatible dispatcher for callers that have already inspected the gate. */\n async acquireDrainLease(operationId: string, now = new Date(), leaseMs = 30_000): Promise<EdgeDrainLease> {\n const gate = await this.migrationGate();\n if (gate.state === \"active\") return this.beginDrain(operationId, now, leaseMs);\n return this.resumeDrain(operationId, now, leaseMs);\n }\n\n /** Verify the held lease and require an exact zero-work outbox before a cutover continues. */\n async assertDrainComplete(lease: EdgeDrainLease, now = new Date()): Promise<void> {\n await this.ready();\n if (lease.scopeKey !== this.key) throw new EdgeMigrationLeaseError();\n await this.write(() => {\n this.db.exec(\"BEGIN IMMEDIATE\");\n try {\n this.assertDrainLeaseInTransaction(lease, now);\n const counts = this.db.prepare(`SELECT\n sum(CASE WHEN state='pending' THEN 1 ELSE 0 END) AS pending,\n sum(CASE WHEN state='pending' AND available_at<=? AND (lease_expires_at IS NULL OR lease_expires_at<=?) THEN 1 ELSE 0 END) AS due,\n sum(CASE WHEN state='pending' AND available_at>? AND (lease_expires_at IS NULL OR lease_expires_at<=?) THEN 1 ELSE 0 END) AS scheduled,\n sum(CASE WHEN state='pending' AND lease_expires_at>? THEN 1 ELSE 0 END) AS leased,\n sum(CASE WHEN state='blocked' THEN 1 ELSE 0 END) AS blocked\n FROM edge_outbox WHERE scope_key=?`).get(\n now.toISOString(), now.toISOString(), now.toISOString(), now.toISOString(), now.toISOString(), this.key,\n ) as Row;\n if (Number(counts.pending ?? 0) !== 0 || Number(counts.due ?? 0) !== 0\n || Number(counts.scheduled ?? 0) !== 0 || Number(counts.leased ?? 0) !== 0\n || Number(counts.blocked ?? 0) !== 0) {\n throw new EdgeConflictError(\"edge scope cannot complete a drain with retained outbox work\");\n }\n this.db.exec(\"COMMIT\");\n } catch (error) {\n rollbackSqliteTransaction(this.db);\n throw error;\n }\n });\n }\n\n async renewDrainLease(lease: EdgeDrainLease, now = new Date(), leaseMs = 30_000): Promise<EdgeDrainLease> {\n await this.ready();\n if (lease.scopeKey !== this.key) throw new EdgeMigrationLeaseError();\n const duration = Math.max(1, Math.trunc(leaseMs));\n return this.write(() => {\n this.db.exec(\"BEGIN IMMEDIATE\");\n try {\n this.assertDrainLeaseInTransaction(lease, now);\n const leaseExpiresAt = new Date(now.getTime() + duration).toISOString();\n const updated = this.db.prepare(`UPDATE edge_migration_gates\n SET lease_expires_at=?,updated_at=? WHERE scope_key=? AND state='draining'\n AND operation_id=? AND lease_token=? AND lease_expires_at=?`).run(\n leaseExpiresAt, now.toISOString(), this.key, lease.operationId, lease.leaseToken, lease.leaseExpiresAt,\n );\n if (updated.changes !== 1) throw new EdgeMigrationLeaseError();\n this.db.exec(\"COMMIT\");\n return { ...lease, leaseExpiresAt };\n } catch (error) {\n rollbackSqliteTransaction(this.db);\n throw error;\n }\n });\n }\n\n async retireScope(lease: EdgeDrainLease, now = new Date()): Promise<void> {\n await this.ready();\n if (lease.scopeKey !== this.key) throw new EdgeMigrationLeaseError();\n await this.write(() => {\n this.db.exec(\"BEGIN IMMEDIATE\");\n try {\n this.assertDrainLeaseInTransaction(lease, now);\n const stats = this.db.prepare(`SELECT count(*) AS count FROM edge_outbox\n WHERE scope_key=?`).get(this.key) as Row;\n if (Number(stats.count) !== 0) throw new EdgeConflictError(\"edge scope cannot retire with retained outbox work\");\n const updated = this.db.prepare(`UPDATE edge_migration_gates\n SET state='retired',lease_token=NULL,lease_expires_at=NULL,updated_at=?\n WHERE scope_key=? AND state='draining' AND operation_id=? AND lease_token=?`).run(\n now.toISOString(), this.key, lease.operationId, lease.leaseToken,\n );\n if (updated.changes !== 1) throw new EdgeMigrationLeaseError();\n this.db.exec(\"COMMIT\");\n } catch (error) {\n rollbackSqliteTransaction(this.db);\n throw error;\n }\n });\n }\n\n async enqueue(input: PendingMessage, now = new Date()): Promise<EdgeEnqueueResult> {\n await this.ready();\n const draft = stableIdempotency(input);\n const payloadHash = edgeMessageFingerprint(draft);\n const serialized = canonical(draft as unknown as JsonValue);\n const nowText = now.toISOString();\n return this.write(() => {\n this.db.exec(\"BEGIN IMMEDIATE\");\n try {\n this.assertScopeActiveInTransaction();\n const existing = this.db.prepare(`SELECT * FROM edge_outbox\n WHERE scope_key=? AND (message_id=? OR idempotency_key=?) ORDER BY position LIMIT 1`)\n .get(this.key, draft.id, draft.idempotencyKey!) as Row | undefined;\n if (existing) {\n if (String(existing.payload_hash) !== payloadHash) {\n throw new EdgeConflictError(\"message ID or idempotency key is already bound to different content\");\n }\n this.db.exec(\"COMMIT\");\n return { draft: parseDraft(existing.draft_json), created: false };\n }\n this.db.prepare(`INSERT INTO edge_outbox\n (scope_key, message_id, idempotency_key, payload_hash, draft_json, state, available_at, created_at)\n VALUES (?, ?, ?, ?, ?, 'pending', ?, ?)`)\n .run(this.key, draft.id, draft.idempotencyKey!, payloadHash, serialized, nowText, nowText);\n this.db.exec(\"COMMIT\");\n return { draft, created: true };\n } catch (error) {\n rollbackSqliteTransaction(this.db);\n throw error;\n }\n });\n }\n\n async claimNext(now = new Date(), leaseMs = 30_000, migrationLease?: EdgeDrainLease): Promise<EdgeOutboxRecord | undefined> {\n await this.ready();\n const nowText = now.toISOString();\n return this.write(() => {\n this.db.exec(\"BEGIN IMMEDIATE\");\n try {\n this.assertClaimAuthorityInTransaction(now, migrationLease);\n const head = this.db.prepare(`SELECT * FROM edge_outbox\n WHERE scope_key=? AND state='pending' AND available_at<=?\n AND (lease_expires_at IS NULL OR lease_expires_at<=?)\n ORDER BY position LIMIT 1`).get(this.key, nowText, nowText) as Row | undefined;\n if (!head) {\n this.db.exec(\"COMMIT\");\n return undefined;\n }\n const leaseToken = randomUUID();\n const leaseExpiresAt = new Date(now.getTime() + leaseMs).toISOString();\n const updated = this.db.prepare(`UPDATE edge_outbox\n SET lease_token=?, lease_expires_at=? WHERE scope_key=? AND position=?\n AND (lease_expires_at IS NULL OR lease_expires_at<=?)`)\n .run(leaseToken, leaseExpiresAt, this.key, Number(head.position), nowText);\n if (!updated.changes) {\n this.db.exec(\"COMMIT\");\n return undefined;\n }\n this.db.exec(\"COMMIT\");\n return {\n position: Number(head.position),\n draft: parseDraft(head.draft_json),\n payloadHash: String(head.payload_hash),\n attempts: Number(head.attempts),\n leaseToken,\n createdAt: String(head.created_at),\n };\n } catch (error) {\n rollbackSqliteTransaction(this.db);\n throw error;\n }\n });\n }\n\n async retry(record: EdgeOutboxRecord, error: string, availableAt: Date): Promise<void> {\n await this.ready();\n await this.write(() => this.db.prepare(`UPDATE edge_outbox SET attempts=attempts+1, available_at=?,\n lease_token=NULL, lease_expires_at=NULL, last_error=?\n WHERE scope_key=? AND position=? AND lease_token=?`)\n .run(availableAt.toISOString(), error.slice(0, 256), this.key, record.position, record.leaseToken));\n await this.noteError(error);\n }\n\n async block(record: EdgeOutboxRecord, error: string, now = new Date()): Promise<void> {\n await this.ready();\n await this.write(() => this.db.prepare(`UPDATE edge_outbox SET state='blocked', attempts=attempts+1,\n lease_token=NULL, lease_expires_at=NULL, last_error=?, blocked_at=?\n WHERE scope_key=? AND position=? AND lease_token=?`)\n .run(error.slice(0, 256), now.toISOString(), this.key, record.position, record.leaseToken));\n await this.noteError(error);\n }\n\n async commit(\n record: EdgeOutboxRecord,\n message: BridgeMessage,\n now = new Date(),\n ): Promise<void> {\n await this.ready();\n await this.write(() => {\n this.db.exec(\"BEGIN IMMEDIATE\");\n try {\n this.cacheOne(message);\n const deleted = this.db.prepare(`DELETE FROM edge_outbox\n WHERE scope_key=? AND position=? AND lease_token=?`)\n .run(this.key, record.position, record.leaseToken);\n if (deleted.changes !== 1) throw new EdgeConflictError(\"outbox lease was lost before commit\");\n this.db.prepare(`UPDATE edge_scopes SET last_sync_at=?, last_error=NULL WHERE scope_key=?`)\n .run(now.toISOString(), this.key);\n this.db.prepare(\"UPDATE edge_scopes SET last_outbound_sync_at=? WHERE scope_key=?\")\n .run(now.toISOString(), this.key);\n this.db.exec(\"COMMIT\");\n } catch (error) {\n rollbackSqliteTransaction(this.db);\n throw error;\n }\n });\n }\n\n private cacheOne(message: BridgeMessage): void {\n const serialized = canonical(message as unknown as JsonValue);\n const key = sequenceKey(message.sequence);\n const byId = this.db.prepare(`SELECT remote_sequence, message_json FROM edge_inbox\n WHERE scope_key=? AND message_id=?`).get(this.key, message.id) as Row | undefined;\n const bySequence = this.db.prepare(`SELECT message_id, message_json FROM edge_inbox\n WHERE scope_key=? AND sequence_key=?`).get(this.key, key) as Row | undefined;\n if (byId || bySequence) {\n if (\n !byId ||\n String(byId.remote_sequence) !== message.sequence ||\n String(byId.message_json) !== serialized ||\n (bySequence && String(bySequence.message_id) !== message.id)\n ) {\n throw new EdgeConflictError(\"cached message conflicts with immutable remote history\");\n }\n return;\n }\n this.db.prepare(`INSERT INTO edge_inbox\n (scope_key, message_id, remote_sequence, sequence_key, workspace, project, source, type,\n thread_id, created_at, expires_at, message_json)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)\n .run(this.key, message.id, message.sequence, key, message.workspace, message.project ?? null, message.source,\n message.type, message.threadId ?? null, message.createdAt, message.expiresAt ?? null, serialized);\n }\n\n async cachePage(messages: BridgeMessage[], cursor: string | undefined, now = new Date()): Promise<void> {\n await this.ready();\n const scope = cursorScope(this.scope.principal, { mailbox: \"all\", includeExpired: true });\n await this.write(() => {\n this.db.exec(\"BEGIN IMMEDIATE\");\n try {\n for (const message of messages) this.cacheOne(message);\n const current = this.db.prepare(\"SELECT pull_cursor FROM edge_scopes WHERE scope_key=?\")\n .get(this.key) as Row;\n const currentCursor = current.pull_cursor ? String(current.pull_cursor) : undefined;\n const nextCursor = !cursor\n ? currentCursor\n : !currentCursor || sequenceKey(decodeCursor(cursor, scope)!) >= sequenceKey(decodeCursor(currentCursor, scope)!)\n ? cursor\n : currentCursor;\n this.db.prepare(`UPDATE edge_scopes SET pull_cursor=?, last_sync_at=?, last_error=NULL\n WHERE scope_key=?`).run(nextCursor ?? null, now.toISOString(), this.key);\n this.db.prepare(\"UPDATE edge_scopes SET last_inbound_sync_at=? WHERE scope_key=?\")\n .run(now.toISOString(), this.key);\n this.db.exec(\"COMMIT\");\n } catch (error) {\n rollbackSqliteTransaction(this.db);\n throw error;\n }\n });\n }\n\n async cacheLatest(messages: BridgeMessage[], now = new Date()): Promise<void> {\n await this.ready();\n await this.write(() => {\n this.db.exec(\"BEGIN IMMEDIATE\");\n try {\n for (const message of messages) this.cacheOne(message);\n this.db.prepare(`UPDATE edge_scopes SET last_sync_at=?, last_error=NULL WHERE scope_key=?`)\n .run(now.toISOString(), this.key);\n this.db.prepare(\"UPDATE edge_scopes SET last_inbound_sync_at=? WHERE scope_key=?\")\n .run(now.toISOString(), this.key);\n this.db.exec(\"COMMIT\");\n } catch (error) {\n rollbackSqliteTransaction(this.db);\n throw error;\n }\n });\n }\n\n async list(query: MessageQuery = {}): Promise<MessagePage> {\n await this.ready();\n const scope = cursorScope(this.scope.principal, query);\n const inputSequence = query.latest ? undefined : decodeCursor(query.cursor, scope) ?? \"0\";\n const cachedHighWater = query.latest ? undefined : this.db.prepare(`SELECT remote_sequence\n FROM edge_inbox WHERE scope_key=? ORDER BY sequence_key DESC LIMIT 1`)\n .get(this.key) as Row | undefined;\n const syncState = query.latest ? undefined : this.db.prepare(\n \"SELECT pull_cursor FROM edge_scopes WHERE scope_key=?\",\n ).get(this.key) as Row | undefined;\n const syncScope = cursorScope(this.scope.principal, {\n mailbox: \"all\",\n includeExpired: true,\n });\n const syncSequence = syncState?.pull_cursor\n ? decodeCursor(String(syncState.pull_cursor), syncScope) ?? \"0\"\n : \"0\";\n const highWaterSequence = query.latest ? undefined : [\n inputSequence ?? \"0\",\n syncSequence,\n cachedHighWater?.remote_sequence ? String(cachedHighWater.remote_sequence) : \"0\",\n ].reduce((highest, candidate) => (\n sequenceKey(candidate) > sequenceKey(highest) ? candidate : highest\n ), \"0\");\n // Receipts are remote authority and are deliberately not mirrored. During\n // an outage callers may still inspect the cached candidate set, but the\n // wrapping store must label acknowledgement state as unknown.\n const clauses = [\"scope_key=?\"];\n const args: SQLInputValue[] = [this.key];\n if (!query.latest) {\n clauses.push(\"sequence_key>?\");\n args.push(sequenceKey(inputSequence ?? \"0\"));\n }\n if (!query.includeExpired) {\n clauses.push(\"(expires_at IS NULL OR expires_at>?)\");\n args.push(new Date().toISOString());\n }\n if (query.types?.length) {\n clauses.push(`type IN (${query.types.map(() => \"?\").join(\",\")})`);\n args.push(...query.types);\n }\n if (query.source) {\n clauses.push(\"source=?\");\n args.push(query.source);\n }\n const mailbox = query.mailbox ?? \"inbox\";\n if (mailbox === \"sent\") { clauses.push(\"source=?\"); args.push(this.scope.principal.agent); }\n else if (mailbox !== \"all\") {\n clauses.push(\"(json_array_length(json_extract(message_json, '$.targets'))=0 OR EXISTS (SELECT 1 FROM json_each(json_extract(message_json, '$.targets')) WHERE value=?))\");\n args.push(this.scope.principal.agent);\n } else {\n clauses.push(\"(source=? OR json_array_length(json_extract(message_json, '$.targets'))=0 OR EXISTS (SELECT 1 FROM json_each(json_extract(message_json, '$.targets')) WHERE value=?))\");\n args.push(this.scope.principal.agent, this.scope.principal.agent);\n }\n if (query.project) {\n clauses.push(\"project=?\");\n args.push(query.project);\n }\n if (query.since) {\n clauses.push(\"created_at>=?\");\n args.push(query.since);\n }\n if (query.threadId) {\n clauses.push(\"thread_id=?\");\n args.push(query.threadId);\n }\n const limit = Math.min(Math.max(Math.trunc(query.limit ?? 50), 1), 200);\n const rows = this.db.prepare(`SELECT message_json FROM edge_inbox\n WHERE ${clauses.join(\" AND \")} ORDER BY sequence_key ${query.latest ? \"DESC\" : \"ASC\"} LIMIT ?`)\n .all(...args, limit) as Row[];\n const messages = rows.map((row) => parseMessage(row.message_json));\n const cursorMessage = query.latest ? messages[0] : messages[messages.length - 1];\n if (query.latest || messages.length === limit) {\n return { messages, cursor: cursorMessage ? encodeCursor(cursorMessage.sequence, scope) : query.cursor };\n }\n return {\n messages,\n cursor: highWaterSequence && highWaterSequence !== \"0\"\n ? encodeCursor(highWaterSequence, scope)\n : query.cursor,\n };\n }\n\n async pullCursor(): Promise<string | undefined> {\n await this.ready();\n const row = this.db.prepare(\"SELECT pull_cursor FROM edge_scopes WHERE scope_key=?\")\n .get(this.key) as Row;\n return row.pull_cursor ? String(row.pull_cursor) : undefined;\n }\n\n async noteError(error: string): Promise<void> {\n await this.ready();\n await this.write(() => this.db.prepare(\"UPDATE edge_scopes SET last_error=? WHERE scope_key=?\")\n .run(error.slice(0, 256), this.key));\n }\n\n async noteAttempt(now = new Date()): Promise<void> {\n await this.ready();\n await this.write(() => this.db.prepare(\"UPDATE edge_scopes SET last_attempt_at=? WHERE scope_key=?\")\n .run(now.toISOString(), this.key));\n }\n\n async stats(now = new Date()): Promise<EdgeStats> {\n await this.ready();\n const nowText = now.toISOString();\n const counts = this.db.prepare(`SELECT\n sum(CASE WHEN state='pending' THEN 1 ELSE 0 END) AS pending,\n sum(CASE WHEN state='pending' AND available_at<=? AND (lease_expires_at IS NULL OR lease_expires_at<=?) THEN 1 ELSE 0 END) AS due,\n sum(CASE WHEN state='pending' AND available_at>? AND (lease_expires_at IS NULL OR lease_expires_at<=?) THEN 1 ELSE 0 END) AS scheduled,\n sum(CASE WHEN state='pending' AND lease_expires_at>? THEN 1 ELSE 0 END) AS leased,\n sum(CASE WHEN state='blocked' THEN 1 ELSE 0 END) AS blocked,\n min(CASE WHEN state='pending' AND available_at<=? AND (lease_expires_at IS NULL OR lease_expires_at<=?) THEN available_at END) AS oldest_due,\n min(CASE WHEN state='pending' AND available_at>? AND (lease_expires_at IS NULL OR lease_expires_at<=?) THEN available_at END) AS next_retry,\n min(CASE WHEN state='blocked' THEN blocked_at END) AS oldest_blocked,\n sum(CASE WHEN state='blocked' AND blocked_at IS NULL THEN 1 ELSE 0 END) AS blocked_age_unknown,\n max(CASE WHEN state='blocked' THEN attempts ELSE 0 END) AS blocked_max_attempts\n FROM edge_outbox WHERE scope_key=?`).get(nowText, nowText, nowText, nowText, nowText, nowText, nowText, nowText, nowText, this.key) as Row;\n const blocked = this.db.prepare(\"SELECT last_error FROM edge_outbox WHERE scope_key=? AND state='blocked' ORDER BY coalesce(blocked_at,created_at) LIMIT 1\").get(this.key) as Row | undefined;\n const cache = this.db.prepare(\"SELECT count(*) AS count FROM edge_inbox WHERE scope_key=?\")\n .get(this.key) as Row;\n const state = this.db.prepare(`SELECT pull_cursor, last_sync_at, last_error,\n last_outbound_sync_at,last_inbound_sync_at,last_attempt_at\n FROM edge_scopes WHERE scope_key=?`).get(this.key) as Row;\n const migrationGate = this.gateInTransaction();\n const oldestDueAt = counts.oldest_due ? String(counts.oldest_due) : undefined;\n const oldestBlockedAt = Number(counts.blocked_age_unknown ?? 0) > 0\n ? undefined\n : counts.oldest_blocked ? String(counts.oldest_blocked) : undefined;\n return {\n pending: Number(counts.pending ?? 0),\n due: Number(counts.due ?? 0),\n scheduled: Number(counts.scheduled ?? 0),\n leased: Number(counts.leased ?? 0),\n blocked: Number(counts.blocked ?? 0),\n cached: Number(cache.count ?? 0),\n pullCursor: state.pull_cursor ? String(state.pull_cursor) : undefined,\n lastSyncAt: state.last_sync_at ? String(state.last_sync_at) : undefined,\n lastError: state.last_error ? String(state.last_error) : undefined,\n oldestDueAt,\n queueLagMs: oldestDueAt ? Math.max(0, now.getTime() - Date.parse(oldestDueAt)) : 0,\n oldestBlockedAt,\n blockedAgeMs: oldestBlockedAt ? Math.max(0, now.getTime() - Date.parse(oldestBlockedAt)) : null,\n blockedMaxAttempts: Number(counts.blocked_max_attempts ?? 0),\n blockedLastError: blocked?.last_error ? String(blocked.last_error) : undefined,\n nextRetryAt: counts.next_retry ? String(counts.next_retry) : undefined,\n lastOutboundSyncAt: state.last_outbound_sync_at ? String(state.last_outbound_sync_at) : undefined,\n lastInboundSyncAt: state.last_inbound_sync_at ? String(state.last_inbound_sync_at) : undefined,\n lastAttemptAt: state.last_attempt_at ? String(state.last_attempt_at) : undefined,\n migrationState: migrationGate.state,\n migrationOperationId: migrationGate.operationId,\n migrationLeaseExpiresAt: migrationGate.leaseExpiresAt,\n };\n }\n\n async close(): Promise<void> {\n this.db.close();\n }\n}\n","import type {\n BridgeDelivery,\n BridgeMessage,\n BridgePrincipal,\n DeliveryState,\n} from \"./bridge-domain.js\";\nimport type {\n BridgeDiagnostics,\n BridgeStore,\n ClaimOptions,\n InsertMessageResult,\n MessagePage,\n MessageQuery,\n} from \"./bridge-store.js\";\nimport {\n EdgeMigrationDrainingError,\n EdgeMigrationLeaseError,\n EdgeMigrationRetiredError,\n edgeMessageFingerprint,\n type EdgeDrainLease,\n type EdgeMigrationGateState,\n type PendingMessage,\n SQLiteEdgeStore,\n} from \"./sqlite-edge-store.js\";\n\nexport interface SyncInsertResult extends InsertMessageResult {\n disposition: \"committed\" | \"queued\";\n authoritative: boolean;\n}\n\nexport interface CachedMessagePage extends MessagePage {\n source: \"remote\" | \"cache\";\n stale: boolean;\n degraded: boolean;\n acknowledgements: \"authoritative\" | \"unknown\";\n lastSyncedAt?: string;\n}\n\nexport interface SyncReport {\n online: boolean;\n pushed: number;\n deduplicated: number;\n pulled: number;\n pending: number;\n blocked: number;\n cached: number;\n cursor?: string;\n lastSyncedAt?: string;\n lastError?: string;\n failureRetryable?: boolean;\n migrationState?: EdgeMigrationGateState;\n migrationOperationId?: string;\n migrationLeaseExpiresAt?: string;\n}\n\nexport interface SyncDiagnostics extends BridgeDiagnostics {\n remoteReachable: boolean | null;\n outboxPending: number;\n outboxBlocked: number;\n cachedMessages: number;\n lastSyncAt?: string;\n lastSyncError?: string;\n outboxDue: number;\n outboxScheduled: number;\n outboxLeased: number;\n outboxOldestDueAt?: string;\n outboxQueueLagMs: number;\n outboxOldestBlockedAt?: string;\n outboxBlockedAgeMs: number | null;\n outboxBlockedMaxAttempts: number;\n outboxBlockedLastError?: string;\n outboxNextRetryAt?: string;\n lastOutboundSyncAt?: string;\n lastInboundSyncAt?: string;\n lastSyncAttemptAt?: string;\n syncLoopState: \"disabled\" | \"idle\" | \"running\" | \"backoff\" | \"paused\" | \"stopped\" | \"failed\";\n syncLoopError?: string;\n remoteError?: string;\n migrationState: EdgeMigrationGateState;\n migrationOperationId?: string;\n migrationLeaseExpiresAt?: string;\n}\n\nexport interface SyncingBridgeStoreOptions {\n now?: () => Date;\n random?: () => number;\n baseDelayMs?: number;\n maxDelayMs?: number;\n leaseMs?: number;\n autoSync?: boolean;\n idleDelayMs?: number;\n edgeDrainLease?: EdgeDrainLease;\n /** A maintenance caller may retain the edge while closing the sync wrapper. */\n closeEdge?: boolean;\n}\n\ntype FlushResult =\n | { state: \"empty\" }\n | { state: \"committed\"; result: InsertMessageResult; messageId: string }\n | { state: \"retry\"; error: Error; retryable: boolean }\n | { state: \"blocked\"; error: Error; messageId: string }\n | { state: \"paused\"; error: EdgeMigrationDrainingError | EdgeMigrationRetiredError | EdgeMigrationLeaseError }\n | { state: \"fatal\"; error: Error };\n\nfunction statusOf(error: unknown): number | undefined {\n if (!error || typeof error !== \"object\" || !(\"status\" in error)) return undefined;\n const status = Number((error as { status?: unknown }).status);\n return Number.isFinite(status) ? status : undefined;\n}\n\nfunction codeOf(error: unknown): string {\n if (error && typeof error === \"object\" && \"code\" in error) {\n const code = (error as { code?: unknown }).code;\n if (typeof code === \"string\" && code) return code.slice(0, 128);\n }\n return error instanceof Error ? error.name.slice(0, 128) : \"sync_error\";\n}\n\nexport function isRetryableSyncError(error: unknown): boolean {\n const status = statusOf(error);\n const code = codeOf(error);\n if ([\"network_error\", \"request_timeout\"].includes(code)) return true;\n if ([\"invalid_input\", \"idempotency_conflict\", \"edge_idempotency_conflict\", \"principal_mismatch\", \"protocol_mismatch\", \"store_closed\", \"client_migration_draining\", \"client_migration_retired\", \"client_migration_lease_lost\"].includes(code)) return false;\n return status === 0 || status === 408 || status === 425 ||\n status === 429 || (status !== undefined && status >= 500);\n}\n\nfunction provisional(draft: PendingMessage, createdAt: string): BridgeMessage {\n return { ...draft, sequence: \"0\", createdAt };\n}\n\nexport class SyncingBridgeStore implements BridgeStore {\n private readonly now: () => Date;\n private readonly random: () => number;\n private readonly baseDelayMs: number;\n private readonly maxDelayMs: number;\n private readonly leaseMs: number;\n private readonly autoSync: boolean;\n private readonly idleDelayMs: number;\n private edgeDrainLease?: EdgeDrainLease;\n private readonly closeEdge: boolean;\n private remoteReady: Promise<void> | undefined;\n private stopped = false;\n private wakeTimer: ReturnType<typeof setTimeout> | undefined;\n private wake: (() => void) | undefined;\n private background: Promise<void> | undefined;\n private readonly closeController = new AbortController();\n private backgroundError: unknown;\n private wakeRequested = false;\n private remoteReachable: boolean | null = null;\n private loopState: SyncDiagnostics[\"syncLoopState\"];\n\n constructor(\n private readonly edge: SQLiteEdgeStore,\n private readonly remote: BridgeStore,\n private readonly principal: BridgePrincipal,\n options: SyncingBridgeStoreOptions = {},\n ) {\n this.now = options.now ?? (() => new Date());\n this.random = options.random ?? Math.random;\n this.baseDelayMs = options.baseDelayMs ?? 1_000;\n this.maxDelayMs = options.maxDelayMs ?? 5 * 60_000;\n this.leaseMs = options.leaseMs ?? 30_000;\n this.autoSync = options.autoSync ?? true;\n this.idleDelayMs = Math.max(this.baseDelayMs + 1, options.idleDelayMs ?? 30_000);\n this.edgeDrainLease = options.edgeDrainLease;\n this.closeEdge = options.closeEdge ?? true;\n this.loopState = this.autoSync ? \"idle\" : \"disabled\";\n }\n\n async initialize(): Promise<void> {\n // Remote readiness is intentionally deferred so clients can start offline.\n await this.edge.initialize();\n if (this.autoSync) this.startTransportLoop();\n }\n\n /** Replace a renewed maintenance lease without creating another edge wrapper. */\n setDrainLease(lease: EdgeDrainLease | undefined): void {\n this.edgeDrainLease = lease;\n }\n\n private startTransportLoop(): void {\n if (this.background) return;\n this.background = this.transportLoop().catch((error) => {\n this.backgroundError = error;\n this.loopState = \"failed\";\n });\n }\n\n private async wait(delayMs: number): Promise<void> {\n if (this.stopped) return;\n if (this.wakeRequested) {\n this.wakeRequested = false;\n return;\n }\n await new Promise<void>((resolve) => {\n this.wake = resolve;\n this.wakeTimer = setTimeout(resolve, delayMs);\n this.wakeTimer.unref?.();\n });\n this.wake = undefined;\n this.wakeTimer = undefined;\n }\n\n private wakeTransport(): void {\n if (this.wake) {\n if (this.wakeTimer) clearTimeout(this.wakeTimer);\n this.wake();\n }\n else this.wakeRequested = true;\n }\n\n private fatal(error: unknown): Error {\n if (this.backgroundError instanceof Error) return this.backgroundError;\n const cause = error instanceof Error ? error : new Error(String(error));\n const fatal = Object.assign(new Error(`fatal local edge failure: ${cause.message}`), {\n code: \"local_edge_commit_failed\",\n cause,\n });\n this.backgroundError = fatal;\n return fatal;\n }\n\n private assertHealthy(): void {\n if (this.backgroundError) throw this.backgroundError;\n }\n\n private async transportLoop(): Promise<void> {\n let failures = 0;\n await this.wait(this.delay(0));\n while (!this.stopped) {\n this.loopState = \"running\";\n const report = await this.sync({ maxPush: 100, maxPages: 1, signal: this.closeController.signal });\n if (this.stopped) break;\n if (report.migrationState !== \"active\" && !this.edgeDrainLease) {\n this.loopState = \"paused\";\n await this.wait(this.idleDelayMs);\n continue;\n }\n if (report.failureRetryable === false) {\n this.backgroundError = Object.assign(\n new Error(`gateway synchronization failed permanently: ${report.lastError ?? \"sync_error\"}`),\n { code: report.lastError ?? \"sync_error\" },\n );\n this.loopState = \"failed\";\n return;\n }\n failures = report.online ? 0 : Math.min(failures + 1, 20);\n this.loopState = report.online ? \"idle\" : \"backoff\";\n await this.wait(report.pending > 0 ? this.delay(Math.max(0, failures - 1)) : this.idleDelayMs);\n }\n }\n\n async verifyRemote(): Promise<void> {\n await this.ensureRemote();\n }\n\n private async ensureRemote(signal?: AbortSignal): Promise<void> {\n if (!this.remoteReady) {\n this.remoteReady = this.remote.initialize({ signal }).catch((error) => {\n this.remoteReady = undefined;\n throw error;\n });\n }\n try {\n await this.remoteReady;\n this.remoteReachable = true;\n } catch (error) {\n this.remoteReachable = false;\n throw error;\n }\n }\n\n private assertPrincipal(principal: BridgePrincipal, includeInstance = true): void {\n if (\n principal.workspace !== this.principal.workspace ||\n principal.agent !== this.principal.agent ||\n (includeInstance && principal.instance !== this.principal.instance)\n ) {\n const error = new Error(\"principal does not match the synchronized edge scope\");\n Object.assign(error, { status: 403, code: \"principal_mismatch\" });\n throw error;\n }\n }\n\n private delay(attempts: number): number {\n const exponential = Math.min(this.maxDelayMs, this.baseDelayMs * 2 ** Math.min(attempts, 20));\n const jitter = 0.8 + this.random() * 0.4;\n return Math.max(1, Math.round(exponential * jitter));\n }\n\n private cancelled(signal?: AbortSignal): boolean {\n return this.stopped || Boolean(signal?.aborted);\n }\n\n private async flushOne(signal?: AbortSignal): Promise<FlushResult> {\n await this.edge.noteAttempt(this.now());\n try {\n if (this.edgeDrainLease) await this.edge.assertDrainLease(this.edgeDrainLease, this.now());\n else await this.edge.assertScopeActive();\n } catch (error) {\n if (error instanceof EdgeMigrationDrainingError\n || error instanceof EdgeMigrationRetiredError\n || error instanceof EdgeMigrationLeaseError) return { state: \"paused\", error };\n throw error;\n }\n try {\n await this.ensureRemote(signal);\n } catch (error) {\n await this.edge.noteError(codeOf(error));\n return {\n state: \"retry\",\n error: error instanceof Error ? error : new Error(String(error)),\n retryable: isRetryableSyncError(error),\n };\n }\n let record;\n try {\n record = await this.edge.claimNext(this.now(), this.leaseMs, this.edgeDrainLease);\n } catch (error) {\n if (error instanceof EdgeMigrationDrainingError\n || error instanceof EdgeMigrationRetiredError\n || error instanceof EdgeMigrationLeaseError) return { state: \"paused\", error };\n throw error;\n }\n if (!record) return { state: \"empty\" };\n try {\n const result = await this.remote.insertMessage(record.draft, { signal });\n this.remoteReachable = true;\n if (result.message.id !== record.draft.id) {\n const error = new Error(\"idempotency key resolved to a different message ID\");\n Object.assign(error, { status: 409, code: \"idempotency_conflict\" });\n await this.edge.block(record, codeOf(error), this.now());\n return { state: \"blocked\", error, messageId: record.draft.id };\n }\n if (edgeMessageFingerprint(result.message) !== record.payloadHash) {\n const error = new Error(\"idempotency key resolved to different message content\");\n Object.assign(error, { status: 409, code: \"idempotency_conflict\" });\n await this.edge.block(record, codeOf(error), this.now());\n return { state: \"blocked\", error, messageId: record.draft.id };\n }\n try {\n await this.edge.commit(record, result.message, this.now());\n } catch (error) {\n return { state: \"fatal\", error: this.fatal(error) };\n }\n return { state: \"committed\", result, messageId: record.draft.id };\n } catch (error) {\n const caught = error instanceof Error ? error : new Error(String(error));\n this.remoteReachable = isRetryableSyncError(error) ? false : true;\n if (this.cancelled(signal)) {\n await this.edge.retry(record, \"request_cancelled\", this.now());\n return { state: \"retry\", error: caught, retryable: true };\n }\n if (isRetryableSyncError(error)) {\n await this.edge.retry(\n record,\n codeOf(error),\n new Date(this.now().getTime() + this.delay(record.attempts)),\n );\n return { state: \"retry\", error: caught, retryable: true };\n }\n await this.edge.block(record, codeOf(error), this.now());\n return { state: \"blocked\", error: caught, messageId: record.draft.id };\n }\n }\n\n async insertMessage(message: PendingMessage): Promise<SyncInsertResult> {\n this.assertHealthy();\n this.assertPrincipal({ workspace: message.workspace, agent: message.source }, false);\n // A drain lease authorizes only claimNext for work that existed before the\n // gate closed. It never authorizes new publication or an early remote call.\n await this.edge.assertScopeActive();\n let remoteError: unknown;\n try {\n await this.ensureRemote();\n } catch (error) {\n if (!isRetryableSyncError(error)) throw error;\n remoteError = error;\n }\n const queued = await this.edge.enqueue(message, this.now());\n const draft = queued.draft;\n if (remoteError) {\n await this.edge.noteError(codeOf(remoteError));\n this.wakeTransport();\n return {\n message: provisional(draft, this.now().toISOString()),\n created: queued.created,\n disposition: \"queued\",\n authoritative: false,\n };\n }\n const flushed = await this.flushOne();\n if (flushed.state === \"fatal\") throw flushed.error;\n if (flushed.state === \"blocked\" && flushed.messageId === draft.id) throw flushed.error;\n if (flushed.state === \"retry\" && !flushed.retryable) throw flushed.error;\n if (flushed.state === \"committed\" && flushed.messageId === draft.id) {\n return { ...flushed.result, disposition: \"committed\", authoritative: true };\n }\n this.wakeTransport();\n return {\n message: provisional(draft, this.now().toISOString()),\n created: queued.created,\n disposition: \"queued\",\n authoritative: false,\n };\n }\n\n async enqueueMessage(message: PendingMessage): Promise<SyncInsertResult & { disposition: \"queued\"; authoritative: false }> {\n this.assertHealthy();\n this.assertPrincipal({ workspace: message.workspace, agent: message.source }, false);\n await this.edge.assertScopeActive();\n const queued = await this.edge.enqueue(message, this.now());\n return {\n message: provisional(queued.draft, this.now().toISOString()),\n created: queued.created,\n disposition: \"queued\",\n authoritative: false,\n };\n }\n\n private async pull(maxPages: number, signal?: AbortSignal): Promise<{\n online: boolean;\n pulled: number;\n error?: Error;\n retryable?: boolean;\n }> {\n let pulled = 0;\n for (let pageNumber = 0; pageNumber < maxPages; pageNumber += 1) {\n if (this.cancelled(signal)) break;\n const before = await this.edge.pullCursor();\n let page: MessagePage;\n try {\n await this.ensureRemote(signal);\n page = await this.remote.listMessages(this.principal, {\n cursor: before,\n limit: 200,\n includeExpired: true,\n mailbox: \"all\",\n }, { signal });\n this.remoteReachable = true;\n } catch (error) {\n this.remoteReachable = isRetryableSyncError(error) ? false : true;\n await this.edge.noteError(codeOf(error));\n return {\n online: false,\n pulled,\n error: error instanceof Error ? error : new Error(String(error)),\n retryable: isRetryableSyncError(error),\n };\n }\n try {\n await this.edge.cachePage(page.messages, page.cursor, this.now());\n } catch (error) {\n throw this.fatal(error);\n }\n pulled += page.messages.length;\n if (page.messages.length < 200 || !page.cursor || page.cursor === before) break;\n }\n return { online: true, pulled };\n }\n\n async sync(options: { maxPush?: number; maxPages?: number; signal?: AbortSignal } = {}): Promise<SyncReport> {\n this.assertHealthy();\n await this.edge.initialize();\n await this.edge.noteAttempt(this.now());\n const maxPush = Math.min(Math.max(Math.trunc(options.maxPush ?? 100), 0), 1_000);\n const maxPages = Math.min(Math.max(Math.trunc(options.maxPages ?? 20), 0), 100);\n let pushed = 0;\n let deduplicated = 0;\n let online = true;\n let lastError: string | undefined;\n let failureRetryable: boolean | undefined;\n\n if (options.signal?.aborted) {\n const stats = await this.edge.stats(this.now());\n return {\n online: false, pushed: 0, deduplicated: 0, pulled: 0,\n pending: stats.pending, blocked: stats.blocked, cached: stats.cached,\n cursor: stats.pullCursor, lastSyncedAt: stats.lastSyncAt,\n lastError: \"request_cancelled\", failureRetryable: true,\n };\n }\n\n for (let index = 0; index < maxPush; index += 1) {\n if (this.cancelled(options.signal)) break;\n const result = await this.flushOne(options.signal);\n if (result.state === \"empty\") break;\n if (result.state === \"committed\") {\n pushed += 1;\n if (!result.result.created) deduplicated += 1;\n continue;\n }\n if (result.state === \"fatal\") throw result.error;\n if (result.state === \"paused\") {\n lastError = codeOf(result.error);\n break;\n }\n lastError = codeOf(result.error);\n failureRetryable = result.state === \"retry\" ? result.retryable : undefined;\n if (result.state === \"retry\") online = false;\n if (result.state === \"retry\") break;\n }\n\n let pulled = 0;\n if (maxPages > 0 && !this.cancelled(options.signal) && !lastError?.startsWith(\"client_migration_\")) {\n const pull = await this.pull(maxPages, options.signal);\n online = online && pull.online;\n pulled = pull.pulled;\n if (pull.error) {\n lastError = codeOf(pull.error);\n failureRetryable = pull.retryable;\n }\n }\n\n const stats = await this.edge.stats(this.now());\n return {\n online,\n pushed,\n deduplicated,\n pulled,\n pending: stats.pending,\n blocked: stats.blocked,\n cached: stats.cached,\n cursor: stats.pullCursor,\n lastSyncedAt: stats.lastSyncAt,\n lastError: lastError ?? stats.lastError,\n failureRetryable,\n migrationState: stats.migrationState,\n migrationOperationId: stats.migrationOperationId,\n migrationLeaseExpiresAt: stats.migrationLeaseExpiresAt,\n };\n }\n\n async listMessages(principal: BridgePrincipal, query: MessageQuery = {}): Promise<CachedMessagePage> {\n this.assertHealthy();\n this.assertPrincipal(principal);\n await this.sync({ maxPush: 20, maxPages: 0 });\n let remotePage: MessagePage;\n try {\n await this.ensureRemote();\n remotePage = await this.remote.listMessages(principal, query);\n } catch (error) {\n const retryable = isRetryableSyncError(error);\n this.remoteReachable = retryable ? false : true;\n if (!retryable) throw error;\n await this.edge.noteError(codeOf(error));\n let cached: MessagePage;\n let stats: Awaited<ReturnType<SQLiteEdgeStore[\"stats\"]>>;\n try {\n cached = await this.edge.list(query);\n stats = await this.edge.stats(this.now());\n } catch (cacheError) {\n throw this.fatal(cacheError);\n }\n return { ...cached, source: \"cache\", stale: true, degraded: true,\n acknowledgements: (query.receiptState && query.receiptState !== \"any\") || \"unacknowledgedBy\" in query ? \"unknown\" : \"authoritative\",\n lastSyncedAt: stats.lastSyncAt };\n }\n try {\n this.remoteReachable = true;\n await this.edge.cacheLatest(remotePage.messages, this.now());\n const stats = await this.edge.stats(this.now());\n return { ...remotePage, source: \"remote\", stale: false, degraded: false,\n acknowledgements: \"authoritative\", lastSyncedAt: stats.lastSyncAt };\n } catch (error) {\n throw this.fatal(error);\n }\n }\n\n async recordReceipt(\n principal: BridgePrincipal,\n messageIds: string[],\n readAt?: Date,\n ): Promise<number> {\n this.assertPrincipal(principal, false);\n await this.ensureRemote();\n return this.remote.recordReceipt(principal, messageIds, readAt);\n }\n\n async claimDelivery(principal: BridgePrincipal, options: ClaimOptions): Promise<BridgeDelivery | null> {\n this.assertPrincipal(principal);\n await this.ensureRemote();\n return this.remote.claimDelivery(principal, options);\n }\n\n async renewDelivery(\n principal: BridgePrincipal,\n deliveryId: string,\n leaseToken: string,\n leaseMs: number,\n ): Promise<BridgeDelivery | null> {\n this.assertPrincipal(principal);\n await this.ensureRemote();\n return this.remote.renewDelivery(principal, deliveryId, leaseToken, leaseMs);\n }\n\n async settleDelivery(\n principal: BridgePrincipal,\n deliveryId: string,\n leaseToken: string,\n state: Extract<DeliveryState, \"acked\" | \"retrying\" | \"dead\">,\n error?: string,\n _retryPolicy?: import(\"./bridge-domain.js\").RetryPolicy,\n ): Promise<BridgeDelivery | null> {\n this.assertPrincipal(principal);\n await this.ensureRemote();\n return this.remote.settleDelivery(principal, deliveryId, leaseToken, state, error);\n }\n\n async listDeliveries(principal: BridgePrincipal, query: import(\"./bridge-store.js\").DeliveryQuery = {}) { this.assertPrincipal(principal); await this.ensureRemote(); if(!this.remote.listDeliveries) throw new Error(\"delivery listing is not supported\"); return this.remote.listDeliveries(principal,query); }\n async listDeliveryEvents(principal: BridgePrincipal,id:string,query:{cursor?:string;limit?:number}={}) { this.assertPrincipal(principal);await this.ensureRemote();if(!this.remote.listDeliveryEvents)throw new Error(\"delivery event listing is not supported\");return this.remote.listDeliveryEvents(principal,id,query); }\n async cancelDelivery(principal:BridgePrincipal,id:string){this.assertPrincipal(principal);await this.ensureRemote();if(!this.remote.cancelDelivery)throw new Error(\"delivery cancellation is not supported\");return this.remote.cancelDelivery(principal,id);}\n async requeueDelivery(principal:BridgePrincipal,id:string){this.assertPrincipal(principal);await this.ensureRemote();if(!this.remote.requeueDelivery)throw new Error(\"delivery requeue is not supported\");return this.remote.requeueDelivery(principal,id);}\n\n async diagnostics(principal: BridgePrincipal, options: { mode?: \"snapshot\" | \"probe\" } = {}): Promise<SyncDiagnostics> {\n this.assertPrincipal(principal);\n const edge = await this.edge.stats(this.now());\n let remote: BridgeDiagnostics | undefined;\n let remoteError: string | undefined;\n if (options.mode === \"probe\") {\n try {\n if (this.remote.diagnostics) remote = await this.remote.diagnostics(principal);\n else await this.ensureRemote();\n this.remoteReachable = true;\n } catch (error) {\n const retryable = isRetryableSyncError(error);\n this.remoteReachable = retryable ? false : true;\n remoteError = codeOf(error);\n }\n }\n return {\n schemaVersion: remote?.schemaVersion ?? \"postgres-v2\",\n deliverySupported: remote?.deliverySupported ?? true,\n pending: remote?.pending ?? null,\n claimed: remote?.claimed ?? null,\n retrying: remote?.retrying ?? null,\n dead: remote?.dead ?? null,\n cancelled: remote?.cancelled ?? null,\n oldestAvailableAt: remote?.oldestAvailableAt,\n due: remote?.due ?? null,\n scheduled: remote?.scheduled ?? null,\n expiredLeases: remote?.expiredLeases ?? null,\n oldestDueAt: remote?.oldestDueAt,\n queueLagMs: remote?.queueLagMs ?? null,\n principal: { workspace: principal.workspace, agent: principal.agent },\n remoteReachable: options.mode === \"probe\" ? this.remoteReachable : null,\n outboxPending: edge.pending,\n outboxBlocked: edge.blocked,\n cachedMessages: edge.cached,\n lastSyncAt: edge.lastSyncAt,\n lastSyncError: edge.lastError,\n outboxDue: edge.due,\n outboxScheduled: edge.scheduled,\n outboxLeased: edge.leased,\n outboxOldestDueAt: edge.oldestDueAt,\n outboxQueueLagMs: edge.queueLagMs,\n outboxOldestBlockedAt: edge.oldestBlockedAt,\n outboxBlockedAgeMs: edge.blockedAgeMs,\n outboxBlockedMaxAttempts: edge.blockedMaxAttempts,\n outboxBlockedLastError: edge.blockedLastError,\n outboxNextRetryAt: edge.nextRetryAt,\n lastOutboundSyncAt: edge.lastOutboundSyncAt,\n lastInboundSyncAt: edge.lastInboundSyncAt,\n lastSyncAttemptAt: edge.lastAttemptAt,\n syncLoopState: this.backgroundError ? \"failed\" : this.loopState,\n syncLoopError: this.backgroundError ? codeOf(this.backgroundError) : undefined,\n remoteError,\n migrationState: edge.migrationState,\n migrationOperationId: edge.migrationOperationId,\n migrationLeaseExpiresAt: edge.migrationLeaseExpiresAt,\n };\n }\n\n async heartbeat(principal: BridgePrincipal, leaseMs: number, runtimeType?: string, capabilities: string[] = []) {\n this.assertPrincipal(principal);\n await this.ensureRemote();\n if (!this.remote.heartbeat) throw new Error(\"presence is not supported by the remote provider\");\n return this.remote.heartbeat(principal, leaseMs, runtimeType, capabilities);\n }\n\n async listPresence(principal: BridgePrincipal) {\n this.assertPrincipal(principal);\n await this.ensureRemote();\n if (!this.remote.listPresence) throw new Error(\"presence is not supported by the remote provider\");\n return this.remote.listPresence(principal);\n }\n\n async close(): Promise<void> {\n this.stopped = true;\n this.loopState = \"stopped\";\n this.closeController.abort(new Error(\"synchronization stopped\"));\n if (this.wakeTimer) clearTimeout(this.wakeTimer);\n this.wake?.();\n const results = await Promise.allSettled([\n this.remote.close?.() ?? Promise.resolve(),\n this.background ?? Promise.resolve(),\n ]);\n const failures = results\n .filter((result): result is PromiseRejectedResult => result.status === \"rejected\")\n .map((result) => result.reason);\n if (this.backgroundError) failures.push(this.backgroundError);\n if (this.closeEdge) {\n try { await this.edge.close(); } catch (error) { failures.push(error); }\n }\n if (failures.length === 1) throw failures[0];\n if (failures.length > 1) throw Object.assign(new Error(\"failed to close synchronized bridge store\"), { errors: failures });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,kBAAkB;AACvC,SAAS,YAAY,iBAAiB;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