@codemem/core 0.49.0-beta.2 → 0.49.0-beta.3
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/dist/better-sqlite-coordinator-store.d.ts +21 -2
- package/dist/better-sqlite-coordinator-store.d.ts.map +1 -1
- package/dist/coordinator-account-change-authority.d.ts +56 -0
- package/dist/coordinator-account-change-authority.d.ts.map +1 -0
- package/dist/coordinator-account-change-decision.d.ts +141 -0
- package/dist/coordinator-account-change-decision.d.ts.map +1 -0
- package/dist/coordinator-account-change-http-test-fixtures.d.ts +3 -1
- package/dist/coordinator-account-change-http-test-fixtures.d.ts.map +1 -1
- package/dist/coordinator-account-change-original-sql-test-fixtures.d.ts +61 -0
- package/dist/coordinator-account-change-original-sql-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-account-change.d.ts +7 -1
- package/dist/coordinator-account-change.d.ts.map +1 -1
- package/dist/coordinator-account-connection-schema.d.ts +31 -0
- package/dist/coordinator-account-connection-schema.d.ts.map +1 -1
- package/dist/coordinator-account-connection-session.d.ts +9 -0
- package/dist/coordinator-account-connection-session.d.ts.map +1 -1
- package/dist/coordinator-account-historical-revoke-original-sql-test-fixtures.d.ts +7 -0
- package/dist/coordinator-account-historical-revoke-original-sql-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-account-historical-revoke.d.ts +8 -2
- package/dist/coordinator-account-historical-revoke.d.ts.map +1 -1
- package/dist/coordinator-account-link-status.d.ts.map +1 -1
- package/dist/coordinator-account-schema-sqlite-test-fixtures.d.ts +58 -0
- package/dist/coordinator-account-schema-sqlite-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-account-schema-test-fixtures.d.ts +20 -0
- package/dist/coordinator-account-schema-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-auth-browser-owner-purpose-test-harness.d.ts.map +1 -1
- package/dist/coordinator-auth-browser-transaction-test-fixtures.d.ts.map +1 -1
- package/dist/coordinator-auth-browser-transaction.d.ts.map +1 -1
- package/dist/coordinator-auth-controller-consistency-test-fixtures.d.ts +5 -1
- package/dist/coordinator-auth-controller-consistency-test-fixtures.d.ts.map +1 -1
- package/dist/coordinator-auth-controller-history.d.ts +0 -1
- package/dist/coordinator-auth-controller-history.d.ts.map +1 -1
- package/dist/coordinator-auth-controller-original-sql-test-fixtures.d.ts +41 -0
- package/dist/coordinator-auth-controller-original-sql-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-auth-controller-owner.d.ts +0 -6
- package/dist/coordinator-auth-controller-owner.d.ts.map +1 -1
- package/dist/coordinator-auth-controller-race-test-fixtures.d.ts +38 -0
- package/dist/coordinator-auth-controller-race-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-auth-controller-read-set.d.ts +47 -0
- package/dist/coordinator-auth-controller-read-set.d.ts.map +1 -0
- package/dist/coordinator-auth-controller-stages-original-sql-test-fixtures.d.ts +8 -0
- package/dist/coordinator-auth-controller-stages-original-sql-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-auth-controller.d.ts +1 -21
- package/dist/coordinator-auth-controller.d.ts.map +1 -1
- package/dist/coordinator-auth-device-claim-eligibility.d.ts +39 -1
- package/dist/coordinator-auth-device-claim-eligibility.d.ts.map +1 -1
- package/dist/coordinator-auth-historical-store-test-fixture.d.ts +2 -0
- package/dist/coordinator-auth-historical-store-test-fixture.d.ts.map +1 -1
- package/dist/coordinator-auth-legacy-assignment.d.ts +4 -2
- package/dist/coordinator-auth-legacy-assignment.d.ts.map +1 -1
- package/dist/coordinator-auth-link-authority-upgrade.d.ts +5 -0
- package/dist/coordinator-auth-link-authority-upgrade.d.ts.map +1 -1
- package/dist/coordinator-auth-link-maintenance-fixtures.d.ts +2 -2
- package/dist/coordinator-auth-link-maintenance-fixtures.d.ts.map +1 -1
- package/dist/coordinator-auth-link-provenance.d.ts.map +1 -1
- package/dist/coordinator-auth-link-revocation-test-harness.d.ts.map +1 -1
- package/dist/coordinator-auth-link-test-fixtures.d.ts +26 -4
- package/dist/coordinator-auth-link-test-fixtures.d.ts.map +1 -1
- package/dist/coordinator-auth-link.d.ts +4 -0
- package/dist/coordinator-auth-link.d.ts.map +1 -1
- package/dist/coordinator-auth-read-set.d.ts +99 -0
- package/dist/coordinator-auth-read-set.d.ts.map +1 -0
- package/dist/coordinator-auth-schema-stage.d.ts +36 -0
- package/dist/coordinator-auth-schema-stage.d.ts.map +1 -0
- package/dist/coordinator-auth-schema.d.ts.map +1 -1
- package/dist/coordinator-auth-session.d.ts.map +1 -1
- package/dist/coordinator-auth-store-test-fixtures.d.ts +12 -0
- package/dist/coordinator-auth-store-test-fixtures.d.ts.map +1 -1
- package/dist/coordinator-controller-revocation-test-harness.d.ts.map +1 -1
- package/dist/coordinator-d1-schema-inventory.d.ts +10 -0
- package/dist/coordinator-d1-schema-inventory.d.ts.map +1 -0
- package/dist/coordinator-device-claim-binding-reuse.d.ts +2 -0
- package/dist/coordinator-device-claim-binding-reuse.d.ts.map +1 -1
- package/dist/coordinator-device-claim-binding-sql.d.ts +8 -0
- package/dist/coordinator-device-claim-binding-sql.d.ts.map +1 -1
- package/dist/coordinator-device-ownership-evidence-original-sql-test-fixtures.d.ts +88 -0
- package/dist/coordinator-device-ownership-evidence-original-sql-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-device-ownership-evidence-queries.d.ts +4 -14
- package/dist/coordinator-device-ownership-evidence-queries.d.ts.map +1 -1
- package/dist/coordinator-device-ownership-evidence-test-fixtures.d.ts +10 -0
- package/dist/coordinator-device-ownership-evidence-test-fixtures.d.ts.map +1 -1
- package/dist/coordinator-device-ownership-evidence.d.ts +11 -3
- package/dist/coordinator-device-ownership-evidence.d.ts.map +1 -1
- package/dist/coordinator-device-rebind-browser.d.ts +1 -1
- package/dist/coordinator-device-rebind-ceremony.d.ts +2 -1
- package/dist/coordinator-device-rebind-ceremony.d.ts.map +1 -1
- package/dist/coordinator-device-rebind-commit.d.ts.map +1 -1
- package/dist/coordinator-device-rebind-test-fixtures.d.ts.map +1 -1
- package/dist/coordinator-device-self-bind-authority.d.ts +11 -2
- package/dist/coordinator-device-self-bind-authority.d.ts.map +1 -1
- package/dist/coordinator-device-self-bind-decision.d.ts +84 -0
- package/dist/coordinator-device-self-bind-decision.d.ts.map +1 -0
- package/dist/coordinator-device-self-bind-original-sql-test-fixtures.d.ts +17 -0
- package/dist/coordinator-device-self-bind-original-sql-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-device-self-bind-test-fixtures.d.ts +12 -1
- package/dist/coordinator-device-self-bind-test-fixtures.d.ts.map +1 -1
- package/dist/coordinator-history-sql-equivalence-test-fixtures.d.ts +6 -2
- package/dist/coordinator-history-sql-equivalence-test-fixtures.d.ts.map +1 -1
- package/dist/coordinator-legacy-completion-owner-proof-original-sql-test-fixtures.d.ts +77 -0
- package/dist/coordinator-legacy-completion-owner-proof-original-sql-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-legacy-completion-owner-proof-test-fixtures.d.ts +46 -0
- package/dist/coordinator-legacy-completion-owner-proof-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-legacy-completion-owner-proof.d.ts +19 -2
- package/dist/coordinator-legacy-completion-owner-proof.d.ts.map +1 -1
- package/dist/coordinator-legacy-owner-compatibility.d.ts +23 -0
- package/dist/coordinator-legacy-owner-compatibility.d.ts.map +1 -1
- package/dist/coordinator-legacy-owner-resolution-commit-original-sql-test-fixtures.d.ts +63 -0
- package/dist/coordinator-legacy-owner-resolution-commit-original-sql-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-legacy-owner-resolution-commit-test-fixtures.d.ts +3 -1
- package/dist/coordinator-legacy-owner-resolution-commit-test-fixtures.d.ts.map +1 -1
- package/dist/coordinator-legacy-owner-resolution-commit.d.ts.map +1 -1
- package/dist/coordinator-owner-enrollment-commit.d.ts.map +1 -1
- package/dist/coordinator-owner-enrollment-historical-test-fixture.d.ts +2 -0
- package/dist/coordinator-owner-enrollment-historical-test-fixture.d.ts.map +1 -1
- package/dist/coordinator-owner-enrollment-start-test-fixtures.d.ts.map +1 -1
- package/dist/coordinator-owner-negative-consistency.d.ts +11 -17
- package/dist/coordinator-owner-negative-consistency.d.ts.map +1 -1
- package/dist/coordinator-owner-negative-original-sql-test-fixtures.d.ts +44 -0
- package/dist/coordinator-owner-negative-original-sql-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-owner-negative-race-test-fixtures.d.ts +26 -0
- package/dist/coordinator-owner-negative-race-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-owner-negative-read-set.d.ts +43 -0
- package/dist/coordinator-owner-negative-read-set.d.ts.map +1 -0
- package/dist/coordinator-owner-negative-reads.d.ts +32 -0
- package/dist/coordinator-owner-negative-reads.d.ts.map +1 -0
- package/dist/coordinator-owner-producer-original-sql-test-fixtures.d.ts +26 -0
- package/dist/coordinator-owner-producer-original-sql-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-owner-resolution-review-test-fixtures.d.ts +1 -0
- package/dist/coordinator-owner-resolution-review-test-fixtures.d.ts.map +1 -1
- package/dist/coordinator-owner-resolution-review.d.ts +1 -0
- package/dist/coordinator-owner-resolution-review.d.ts.map +1 -1
- package/dist/coordinator-producer-negative-owner-test-fixtures.d.ts +8 -2
- package/dist/coordinator-producer-negative-owner-test-fixtures.d.ts.map +1 -1
- package/dist/coordinator-recipient-negative-race-test-fixtures.d.ts +54 -0
- package/dist/coordinator-recipient-negative-race-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-recipient-owner-consistency.d.ts +4 -5
- package/dist/coordinator-recipient-owner-consistency.d.ts.map +1 -1
- package/dist/coordinator-recipient-owner-original-sql-test-fixtures.d.ts +30 -0
- package/dist/coordinator-recipient-owner-original-sql-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-resolved-account-owner-status-query.d.ts +4 -1
- package/dist/coordinator-resolved-account-owner-status-query.d.ts.map +1 -1
- package/dist/coordinator-resolved-account-owner-status-test-fixtures.d.ts +1 -0
- package/dist/coordinator-resolved-account-owner-status-test-fixtures.d.ts.map +1 -1
- package/dist/coordinator-resolved-account-owner-status.d.ts +2 -0
- package/dist/coordinator-resolved-account-owner-status.d.ts.map +1 -1
- package/dist/{coordinator-runtime-kbPwxxKq.js → coordinator-runtime-BXJQAKFD.js} +3 -3
- package/dist/{coordinator-runtime-kbPwxxKq.js.map → coordinator-runtime-BXJQAKFD.js.map} +1 -1
- package/dist/coordinator-sql-compare.d.ts +22 -0
- package/dist/coordinator-sql-compare.d.ts.map +1 -0
- package/dist/d1-coordinator-store.d.ts +16 -1
- package/dist/d1-coordinator-store.d.ts.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8907 -8434
- package/dist/index.js.map +1 -1
- package/dist/internal/cloudflare-coordinator.js +1070 -1065
- package/dist/internal/cloudflare-coordinator.js.map +1 -1
- package/dist/internal/relay-runtime.js +2 -2
- package/dist/linked-legacy-setup-test-fixtures.d.ts +2 -0
- package/dist/linked-legacy-setup-test-fixtures.d.ts.map +1 -1
- package/dist/{owner-enrollment-start-BtoRKf3z.js → owner-enrollment-start-BFyBKWvZ.js} +2626 -2425
- package/dist/owner-enrollment-start-BFyBKWvZ.js.map +1 -0
- package/dist/owner-enrollment-start.d.ts.map +1 -1
- package/dist/relay-admission-table-keys-test-fixtures.d.ts +2 -1
- package/dist/relay-admission-table-keys-test-fixtures.d.ts.map +1 -1
- package/dist/{relay-peer-client-0XpekgnZ.js → relay-peer-client-DrTb2oZt.js} +2631 -2617
- package/dist/relay-peer-client-DrTb2oZt.js.map +1 -0
- package/dist/{sync-auth-constants-DvALG0T0.js → sync-auth-constants-BVzVfSmn.js} +4019 -3416
- package/dist/sync-auth-constants-BVzVfSmn.js.map +1 -0
- package/dist/{sync-reachability-pass-BpDt2z4y.js → sync-reachability-pass-CUe5bK61.js} +12 -12
- package/dist/{sync-reachability-pass-BpDt2z4y.js.map → sync-reachability-pass-CUe5bK61.js.map} +1 -1
- package/dist/sync-reachability-pass-D9cA54fj.js +2 -0
- package/package.json +3 -3
- package/dist/owner-enrollment-start-BtoRKf3z.js.map +0 -1
- package/dist/relay-peer-client-0XpekgnZ.js.map +0 -1
- package/dist/sync-auth-constants-DvALG0T0.js.map +0 -1
- package/dist/sync-reachability-pass-Bi4GBi-x.js +0 -2
package/dist/{sync-reachability-pass-BpDt2z4y.js.map → sync-reachability-pass-CUe5bK61.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sync-reachability-pass-BpDt2z4y.js","names":[],"sources":["../src/secret-scanner.ts","../src/repository-mapping-aliases.ts","../src/policy-team-device-eligibility.ts","../src/sync-bootstrap-constants.ts","../src/maintenance-jobs.ts","../src/session-export-identity.ts","../src/session-export-identity-mutation.ts","../src/ref-populate.ts","../src/vector-metadata-rows.ts","../src/vector-metadata-snapshot.ts","../src/vector-writes.ts","../src/vectors.ts","../src/repository-discovery-cache.ts","../src/scope-stamping.ts","../src/memory-retirement-snapshot-guard.ts","../src/recipient-policy-reconciliation.ts","../src/tags.ts","../src/sync-replication.ts","../src/vector-backfill-queue.ts","../src/vector-cutover-validation.ts","../src/vector-migration.ts","../src/mise-install-path.ts","../src/release-discovery.ts","../src/sync-bootstrap.ts","../src/sync-discovery.ts","../src/sync-channel-progress.ts","../src/sync-failure-classification.ts","../src/sync-pass.ts","../src/peer-http-client.ts","../src/sync-scope-protocol.ts","../src/sync-channel-pass.ts","../src/sync-reachability-pass.ts"],"sourcesContent":["/**\n * Write-time secret scanner for the codemem store.\n *\n * Detects common secrets in memory write payloads (titles, bodies, narratives,\n * structured fields, and free-form metadata) and replaces them with\n * `[REDACTED:<kind>]` markers before persistence. There is no override flag:\n * codemem has no legitimate use case for storing live secrets, so any escape\n * hatch becomes the bypass that makes scanning theater.\n *\n * Scope of this foundation: the local-write chokepoint inside `MemoryStore.remember`.\n * Other writers into `memory_items` (sync-replication apply, sync-bootstrap\n * snapshot apply, AI/maintenance backfills of narrative/facts/concepts/tags)\n * are NOT scanned by this module yet — they are addressed by dependent bd\n * issues (codemem-hflk for sync-receive, codemem-tzrn for compaction/AI output,\n * codemem-vb2s for retroactive sweep over already-stored content). Workspace-level\n * rule overrides (codemem-ben8) and the test-fixture allowlist (codemem-jasn)\n * plug in via `ScannerOptions` without changing this module's shape.\n */\n\nexport interface SecretRule {\n\t/** Stable identifier surfaced in the redaction marker and detection log. */\n\tkind: string;\n\t/** Regex used to find candidate matches. Must be a global regex. */\n\tpattern: RegExp;\n\t/**\n\t * Optional minimum Shannon entropy (bits/char) the matched substring must\n\t * meet to be redacted. Filters out low-entropy false positives like\n\t * common words that happen to look like a secret.\n\t */\n\tminEntropy?: number;\n\t/**\n\t * If set, only the indicated capture group (1-based) is replaced. Useful\n\t * for context-aware rules where the match includes a known prefix that\n\t * should be preserved.\n\t */\n\tredactGroup?: number;\n}\n\nexport interface ScanDetection {\n\tkind: string;\n\tcount: number;\n}\n\nexport interface ScanResult {\n\tredacted: string;\n\tdetections: ScanDetection[];\n}\n\nexport interface ScannerOptions {\n\t/** Additional rules merged with `DEFAULT_RULES`. */\n\trules?: SecretRule[];\n\t/**\n\t * Strings or regexes that bypass redaction even when matched. NOTE: string\n\t * entries match by exact equality against the matched substring; regex\n\t * entries are tested with `RegExp.test()` (partial match by default; use\n\t * anchors for exact match).\n\t */\n\tallowlist?: Array<string | RegExp>;\n}\n\n/** Field names whose string values should be treated as secret-bearing. */\nconst SECRET_BEARING_KEY =\n\t/^(?:secret|token|password|passwd|pwd|auth|bearer|credential|api[_-]?key|access[_-]?key|client[_-]?secret|private[_-]?key|access[_-]?token|refresh[_-]?token|id[_-]?token|bearer[_-]?token|api[_-]?token)$/i;\n\n/**\n * Built-in default rules. Conservative: prefer well-known prefixes and\n * structural patterns over raw entropy to keep the false-positive rate low.\n *\n * Rule precedence is order-dependent. More-specific rules MUST come before\n * more-general ones — see the OpenAI rule, which uses a negative lookahead to\n * avoid swallowing Anthropic keys regardless of order.\n */\nexport const DEFAULT_RULES: SecretRule[] = [\n\t// AWS — both halves of an access key pair\n\t{ kind: \"aws_access_key_id\", pattern: /\\b(?:AKIA|ASIA)[0-9A-Z]{16}\\b/g },\n\t// AWS secret access key — 40 base64-ish chars; require entropy to filter FPs\n\t{\n\t\tkind: \"aws_secret_access_key\",\n\t\tpattern: /(?<![A-Za-z0-9/+=])[A-Za-z0-9/+=]{40}(?![A-Za-z0-9/+=])/g,\n\t\tminEntropy: 4.5,\n\t},\n\n\t// GitHub token family\n\t{ kind: \"github_pat_classic\", pattern: /\\bghp_[A-Za-z0-9]{36}\\b/g },\n\t{ kind: \"github_pat_finegrained\", pattern: /\\bgithub_pat_[A-Za-z0-9_]{82}\\b/g },\n\t{ kind: \"github_oauth\", pattern: /\\bgho_[A-Za-z0-9]{36}\\b/g },\n\t{ kind: \"github_user_token\", pattern: /\\bghu_[A-Za-z0-9]{36}\\b/g },\n\t{ kind: \"github_server_token\", pattern: /\\bghs_[A-Za-z0-9]{36}\\b/g },\n\t{ kind: \"github_refresh_token\", pattern: /\\bghr_[A-Za-z0-9]{36}\\b/g },\n\n\t// JWT — three base64url segments separated by dots, header begins with eyJ\n\t{ kind: \"jwt\", pattern: /\\beyJ[A-Za-z0-9_-]{10,}\\.eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\b/g },\n\n\t// Common provider keys\n\t{ kind: \"google_api_key\", pattern: /\\bAIza[0-9A-Za-z_-]{35}\\b/g },\n\t{ kind: \"slack_token\", pattern: /\\bxox[abprs]-[A-Za-z0-9-]{10,}\\b/g },\n\t{ kind: \"stripe_live_key\", pattern: /\\bsk_live_[0-9a-zA-Z]{24,}\\b/g },\n\t{ kind: \"stripe_test_key\", pattern: /\\bsk_test_[0-9a-zA-Z]{24,}\\b/g },\n\t{ kind: \"anthropic_api_key\", pattern: /\\bsk-ant-(?:api|admin)\\d{2}-[A-Za-z0-9_-]{80,}\\b/g },\n\t// OpenAI keys: negative lookahead for `ant-` so Anthropic keys do not match here\n\t// even if rule order changes. Entropy floor avoids false-positive on internal\n\t// `sk-` prefixed identifiers that happen to be long enough.\n\t{\n\t\tkind: \"openai_api_key\",\n\t\tpattern: /\\bsk-(?!ant-)(?:proj-|svcacct-)?[A-Za-z0-9_-]{32,}\\b/g,\n\t\tminEntropy: 3.5,\n\t},\n\n\t// PEM-encoded private keys (RSA/EC/DSA/OpenSSH/PGP). Note: PGP MESSAGE\n\t// blocks, SSH2 ENCRYPTED PRIVATE KEY, and PuTTY user-key files are NOT\n\t// matched by this rule and remain a known gap (deferred backlog).\n\t{\n\t\tkind: \"pem_private_key\",\n\t\tpattern:\n\t\t\t/-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----[\\s\\S]+?-----END (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----/g,\n\t},\n\n\t// Context-aware generic secret: secret/token/password = \"<value>\"\n\t// Only the captured value (group 1) is redacted; the prefix is preserved.\n\t{\n\t\tkind: \"generic_assigned_secret\",\n\t\tpattern:\n\t\t\t/\\b(?:secret|token|password|passwd|pwd|auth|bearer|credential|api[_-]?key|access[_-]?key|client[_-]?secret|access[_-]?token|refresh[_-]?token|id[_-]?token|bearer[_-]?token|api[_-]?token)\\s*[:=]\\s*[\"']?([A-Za-z0-9+/=_.-]{20,})[\"']?/gi,\n\t\tminEntropy: 3.5,\n\t\tredactGroup: 1,\n\t},\n];\n\n/** Shannon entropy in bits per character. */\nfunction shannonEntropy(text: string): number {\n\tif (text.length === 0) return 0;\n\tconst freq = new Map<string, number>();\n\tfor (const ch of text) freq.set(ch, (freq.get(ch) ?? 0) + 1);\n\tlet h = 0;\n\tfor (const count of freq.values()) {\n\t\tconst p = count / text.length;\n\t\th -= p * Math.log2(p);\n\t}\n\treturn h;\n}\n\nfunction ensureGlobal(re: RegExp): RegExp {\n\tif (re.flags.includes(\"g\")) return re;\n\treturn new RegExp(re.source, `${re.flags}g`);\n}\n\nfunction isAllowlisted(match: string, allowlist: Array<string | RegExp>): boolean {\n\tfor (const entry of allowlist) {\n\t\tif (typeof entry === \"string\") {\n\t\t\tif (entry === match) return true;\n\t\t} else {\n\t\t\t// `RegExp.test()` advances `lastIndex` on regexes with `g` or `y`\n\t\t\t// flags, which would make repeated allowlist checks return\n\t\t\t// alternating results. Reset before testing so the decision is\n\t\t\t// stable across calls regardless of caller-supplied flags.\n\t\t\tif (entry.global || entry.sticky) entry.lastIndex = 0;\n\t\t\tif (entry.test(match)) return true;\n\t\t}\n\t}\n\treturn false;\n}\n\n/**\n * Detect whether `value` is a \"plain\" object (`{}` literal or `Object.create(null)`),\n * vs a class instance / built-in like Date, Map, Set, RegExp, Buffer, typed array.\n * Plain objects are walked recursively; non-plain objects are returned as-is so\n * we don't silently corrupt them by reconstructing as `{}`.\n */\nfunction isPlainObject(value: object): boolean {\n\tconst proto = Object.getPrototypeOf(value);\n\treturn proto === null || proto === Object.prototype;\n}\n\nexport class SecretScanner {\n\tprivate readonly rules: SecretRule[];\n\tprivate readonly allowlist: Array<string | RegExp>;\n\n\tconstructor(opts: ScannerOptions = {}) {\n\t\tthis.rules = [...DEFAULT_RULES, ...(opts.rules ?? [])];\n\t\tthis.allowlist = opts.allowlist ?? [];\n\t}\n\n\t/** Scan a single string. Returns the redacted form and per-kind detection counts. */\n\tscan(text: string): ScanResult {\n\t\tif (!text || typeof text !== \"string\") return { redacted: text, detections: [] };\n\t\tlet redacted = text;\n\t\tconst counts = new Map<string, number>();\n\t\tfor (const rule of this.rules) {\n\t\t\tconst re = ensureGlobal(rule.pattern);\n\t\t\tredacted = redacted.replace(re, (...args) => {\n\t\t\t\t// args = [match, ...groups, offset, fullString, groupsObj?]\n\t\t\t\tconst match = args[0] as string;\n\t\t\t\tconst target =\n\t\t\t\t\trule.redactGroup != null ? ((args[rule.redactGroup] as string | undefined) ?? \"\") : match;\n\t\t\t\tif (!target) return match;\n\t\t\t\tif (isAllowlisted(target, this.allowlist)) return match;\n\t\t\t\tif (rule.minEntropy != null && shannonEntropy(target) < rule.minEntropy) return match;\n\t\t\t\tcounts.set(rule.kind, (counts.get(rule.kind) ?? 0) + 1);\n\t\t\t\tconst marker = `[REDACTED:${rule.kind}]`;\n\t\t\t\tif (rule.redactGroup != null) {\n\t\t\t\t\treturn match.replace(target, marker);\n\t\t\t\t}\n\t\t\t\treturn marker;\n\t\t\t});\n\t\t}\n\t\tconst detections = Array.from(counts.entries()).map(([kind, count]) => ({ kind, count }));\n\t\treturn { redacted, detections };\n\t}\n\n\t/**\n\t * Recursively walk a value, scanning every string. String values whose\n\t * containing key name matches a secret-bearing field are redacted whole if\n\t * non-trivial. Non-plain objects (Date, Map, Set, RegExp, Buffer, typed\n\t * arrays, class instances) are returned as-is to avoid silent corruption.\n\t * Cycles are detected via a `seen` set so misbehaving callers cannot\n\t * stack-overflow the scanner.\n\t */\n\tredactValue(value: unknown, parentKey?: string): { value: unknown; detections: ScanDetection[] } {\n\t\treturn this.redactValueInternal(value, parentKey, new WeakSet());\n\t}\n\n\tprivate redactValueInternal(\n\t\tvalue: unknown,\n\t\tparentKey: string | undefined,\n\t\tseen: WeakSet<object>,\n\t): { value: unknown; detections: ScanDetection[] } {\n\t\tif (typeof value === \"string\") {\n\t\t\tif (parentKey && SECRET_BEARING_KEY.test(parentKey) && this.looksLikeSecretValue(value)) {\n\t\t\t\tif (isAllowlisted(value, this.allowlist)) {\n\t\t\t\t\treturn { value, detections: [] };\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tvalue: \"[REDACTED:context_secret]\",\n\t\t\t\t\tdetections: [{ kind: \"context_secret\", count: 1 }],\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst result = this.scan(value);\n\t\t\treturn { value: result.redacted, detections: result.detections };\n\t\t}\n\t\tif (Array.isArray(value)) {\n\t\t\tif (seen.has(value)) return { value, detections: [] };\n\t\t\tseen.add(value);\n\t\t\tconst out: unknown[] = [];\n\t\t\tconst merged = new Map<string, number>();\n\t\t\tfor (const item of value) {\n\t\t\t\tconst r = this.redactValueInternal(item, parentKey, seen);\n\t\t\t\tout.push(r.value);\n\t\t\t\tfor (const d of r.detections) merged.set(d.kind, (merged.get(d.kind) ?? 0) + d.count);\n\t\t\t}\n\t\t\treturn { value: out, detections: aggregateMap(merged) };\n\t\t}\n\t\tif (value !== null && typeof value === \"object\") {\n\t\t\tif (seen.has(value)) return { value, detections: [] };\n\t\t\tif (!isPlainObject(value)) {\n\t\t\t\t// Non-plain objects (Date, Map, Set, RegExp, Buffer, typed arrays,\n\t\t\t\t// class instances) are returned unchanged. Walking them would\n\t\t\t\t// silently strip prototype methods and corrupt state.\n\t\t\t\treturn { value, detections: [] };\n\t\t\t}\n\t\t\tseen.add(value);\n\t\t\tconst obj = value as Record<string, unknown>;\n\t\t\tconst out: Record<string, unknown> = {};\n\t\t\tconst merged = new Map<string, number>();\n\t\t\tfor (const [k, v] of Object.entries(obj)) {\n\t\t\t\tconst r = this.redactValueInternal(v, k, seen);\n\t\t\t\tout[k] = r.value;\n\t\t\t\tfor (const d of r.detections) merged.set(d.kind, (merged.get(d.kind) ?? 0) + d.count);\n\t\t\t}\n\t\t\treturn { value: out, detections: aggregateMap(merged) };\n\t\t}\n\t\treturn { value, detections: [] };\n\t}\n\n\tprivate looksLikeSecretValue(text: string): boolean {\n\t\t// Threshold of 8 chars filters obvious placeholders (\"n/a\", \"true\", short\n\t\t// human values) while still catching anything long enough to plausibly\n\t\t// be a secret. URL values get a free pass since auth callback URLs are\n\t\t// commonly stored under \"auth\"-named keys.\n\t\tif (text.length < 8) return false;\n\t\tif (/^(?:https?|ftp|file):\\/\\//i.test(text)) return false;\n\t\tif (/^(?:\\[REDACTED:|<.*>|\\{\\{.*\\}\\}|null|undefined)$/i.test(text.trim())) return false;\n\t\treturn true;\n\t}\n}\n\nfunction aggregateMap(map: Map<string, number>): ScanDetection[] {\n\treturn Array.from(map.entries()).map(([kind, count]) => ({ kind, count }));\n}\n\n/**\n * Build `ScannerOptions` from a parsed codemem config object's\n * `secret_scanner` block. Workspace-scoped rule overrides and an allowlist\n * for known-safe matches are accepted under a single config key so a team\n * can tighten or loosen the default policy without forking codemem.\n *\n * Expected shape (all keys optional):\n * ```jsonc\n * {\n * \"secret_scanner\": {\n * \"rules\": [\n * { \"kind\": \"internal_token\", \"pattern\": \"\\\\bACME-[A-Z0-9]{10}\\\\b\", \"flags\": \"g\", \"minEntropy\": 3.0 }\n * ],\n * \"allowlist\": [\n * \"AKIAFAKEFIXTURE0001\", // string entries match by exact equality\n * \"/^test-fixture-.*$/i\" // strings of the form /pattern/flags become regexes\n * ]\n * }\n * }\n * ```\n *\n * Malformed entries are silently dropped — config errors should never block\n * a workspace from opening.\n */\nexport function loadScannerOptionsFromConfig(\n\tconfig: Record<string, unknown> | null | undefined,\n): ScannerOptions {\n\tconst empty: ScannerOptions = {};\n\tif (!config || typeof config !== \"object\") return empty;\n\tconst block = (config as { secret_scanner?: unknown }).secret_scanner;\n\tif (!block || typeof block !== \"object\" || Array.isArray(block)) return empty;\n\tconst out: ScannerOptions = {};\n\n\tconst rawRules = (block as { rules?: unknown }).rules;\n\tif (Array.isArray(rawRules)) {\n\t\tconst rules: SecretRule[] = [];\n\t\tfor (const entry of rawRules) {\n\t\t\tif (!entry || typeof entry !== \"object\" || Array.isArray(entry)) continue;\n\t\t\tconst e = entry as Record<string, unknown>;\n\t\t\tif (typeof e.kind !== \"string\" || typeof e.pattern !== \"string\") continue;\n\t\t\tconst flagsRaw = typeof e.flags === \"string\" ? e.flags : \"g\";\n\t\t\tconst flags = flagsRaw.includes(\"g\") ? flagsRaw : `${flagsRaw}g`;\n\t\t\tlet pattern: RegExp;\n\t\t\ttry {\n\t\t\t\tpattern = new RegExp(e.pattern, flags);\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst rule: SecretRule = { kind: e.kind, pattern };\n\t\t\tif (typeof e.minEntropy === \"number\" && Number.isFinite(e.minEntropy)) {\n\t\t\t\trule.minEntropy = e.minEntropy;\n\t\t\t}\n\t\t\tif (\n\t\t\t\ttypeof e.redactGroup === \"number\" &&\n\t\t\t\tNumber.isInteger(e.redactGroup) &&\n\t\t\t\te.redactGroup > 0\n\t\t\t) {\n\t\t\t\trule.redactGroup = e.redactGroup;\n\t\t\t}\n\t\t\trules.push(rule);\n\t\t}\n\t\tif (rules.length > 0) out.rules = rules;\n\t}\n\n\tconst rawAllowlist = (block as { allowlist?: unknown }).allowlist;\n\tif (Array.isArray(rawAllowlist)) {\n\t\tconst allowlist: Array<string | RegExp> = [];\n\t\tfor (const entry of rawAllowlist) {\n\t\t\tif (typeof entry !== \"string\" || entry.length === 0) continue;\n\t\t\t// Strings of the form /pattern/flags are parsed as regex; everything\n\t\t\t// else is treated as a literal.\n\t\t\tconst re = parseRegexLiteral(entry);\n\t\t\tallowlist.push(re ?? entry);\n\t\t}\n\t\tif (allowlist.length > 0) out.allowlist = allowlist;\n\t}\n\n\treturn out;\n}\n\nfunction parseRegexLiteral(value: string): RegExp | null {\n\tif (value.length < 2 || value[0] !== \"/\") return null;\n\tconst lastSlash = value.lastIndexOf(\"/\");\n\tif (lastSlash <= 0) return null;\n\tconst pattern = value.slice(1, lastSlash);\n\tconst flags = value.slice(lastSlash + 1);\n\tif (!/^[gimsuy]*$/.test(flags)) return null;\n\t// Allowlist regexes are tested via RegExp.test which is stateful when `g`\n\t// or `y` is set. Strip those flags up front so a configured /^foo/g\n\t// behaves the same as /^foo/ — the runtime guard in isAllowlisted is\n\t// belt-and-suspenders, this is the suspenders.\n\tconst safeFlags = flags.replace(/[gy]/g, \"\");\n\ttry {\n\t\treturn new RegExp(pattern, safeFlags);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Merge multiple detection lists into a single per-kind summary. */\nexport function mergeDetections(...lists: ScanDetection[][]): ScanDetection[] {\n\tconst merged = new Map<string, number>();\n\tfor (const list of lists) {\n\t\tfor (const d of list) merged.set(d.kind, (merged.get(d.kind) ?? 0) + d.count);\n\t}\n\treturn aggregateMap(merged);\n}\n\n/**\n * Shape of a parsed inbound memory payload (sync-replication or sync-bootstrap).\n * Any field that is `undefined` is left untouched. The struct is mutated in\n * place by `redactMemoryFields` so callers can redact-then-insert without\n * cloning.\n */\nexport interface MemoryFieldRedactionTarget {\n\ttitle?: string | null;\n\tsubtitle?: string | null;\n\tbody_text?: string | null;\n\ttags_text?: string | null;\n\tnarrative?: string | null;\n\tfacts?: unknown;\n\tconcepts?: unknown;\n\tfiles_read?: unknown;\n\tfiles_modified?: unknown;\n\tmetadata_json?: unknown;\n\t/**\n\t * Peer-controlled identity strings persisted alongside content. They show\n\t * up in the viewer and exports verbatim, so a malicious peer could smuggle\n\t * a secret in a display name. Scanned for the same well-known patterns as\n\t * everything else; not subject to context_secret heuristics since they\n\t * legitimately contain free-form text.\n\t */\n\tactor_display_name?: string | null;\n\torigin_source?: string | null;\n}\n\n/**\n * Redact secrets from a parsed inbound memory payload before persistence.\n * Used by sync-receive (sync-replication.ts) and bootstrap-snapshot apply\n * (sync-bootstrap.ts) so peer-shipped content goes through the same scanner\n * as locally-authored writes. Mutates the target in place; returns the merged\n * detection summary across all scanned fields.\n */\nexport function redactMemoryFields<T extends MemoryFieldRedactionTarget>(\n\ttarget: T,\n\tscanner: SecretScanner,\n): { target: T; detections: ScanDetection[] } {\n\tconst lists: ScanDetection[][] = [];\n\n\tconst scanStringField = (key: keyof MemoryFieldRedactionTarget): void => {\n\t\tconst value = (target as MemoryFieldRedactionTarget)[key];\n\t\tif (typeof value === \"string\" && value.length > 0) {\n\t\t\tconst result = scanner.scan(value);\n\t\t\t(target as MemoryFieldRedactionTarget)[key] = result.redacted;\n\t\t\tlists.push(result.detections);\n\t\t}\n\t};\n\tscanStringField(\"title\");\n\tscanStringField(\"subtitle\");\n\tscanStringField(\"body_text\");\n\tscanStringField(\"narrative\");\n\tscanStringField(\"actor_display_name\");\n\tscanStringField(\"origin_source\");\n\n\t// tags_text is a whitespace-joined string here. Local writes scan each tag\n\t// individually before joining (store.ts), so to keep behavior consistent\n\t// when peer payloads arrive pre-joined we split, scan-per-tag, and rejoin.\n\tconst rawTagsText = (target as MemoryFieldRedactionTarget).tags_text;\n\tif (typeof rawTagsText === \"string\" && rawTagsText.length > 0) {\n\t\tconst parts = rawTagsText.split(/\\s+/).filter(Boolean);\n\t\tconst scannedParts: string[] = [];\n\t\tfor (const part of parts) {\n\t\t\tconst result = scanner.scan(part);\n\t\t\tscannedParts.push(result.redacted);\n\t\t\tlists.push(result.detections);\n\t\t}\n\t\t(target as MemoryFieldRedactionTarget).tags_text = scannedParts.join(\" \");\n\t}\n\n\tfor (const key of [\"facts\", \"concepts\", \"files_read\", \"files_modified\"] as const) {\n\t\tconst value = (target as MemoryFieldRedactionTarget)[key];\n\t\tif (Array.isArray(value)) {\n\t\t\tconst next: unknown[] = [];\n\t\t\tfor (const item of value) {\n\t\t\t\tif (typeof item === \"string\") {\n\t\t\t\t\tconst result = scanner.scan(item);\n\t\t\t\t\tnext.push(result.redacted);\n\t\t\t\t\tlists.push(result.detections);\n\t\t\t\t} else {\n\t\t\t\t\tnext.push(item);\n\t\t\t\t}\n\t\t\t}\n\t\t\t(target as MemoryFieldRedactionTarget)[key] = next;\n\t\t}\n\t}\n\n\tif (target.metadata_json && typeof target.metadata_json === \"object\") {\n\t\tconst result = scanner.redactValue(target.metadata_json);\n\t\ttarget.metadata_json = result.value;\n\t\tlists.push(result.detections);\n\t}\n\n\treturn { target, detections: mergeDetections(...lists) };\n}\n","import { isAbsolute } from \"node:path\";\nimport type { Database } from \"./db.js\";\nimport { repositoryIdentityFromMetadata, resolveGitRepositoryIdentity } from \"./project.js\";\nimport { cleanProjectIdentity } from \"./project-identity.js\";\nimport {\n\tLOCAL_DEFAULT_SCOPE_ID,\n\tresolveProjectScope,\n\ttype ScopeMapping,\n} from \"./scope-resolution.js\";\n\nconst GIT_IDENTITY_CACHE_TTL_MS = 5_000;\nconst GIT_IDENTITY_CACHE_MAX_ENTRIES = 256;\nconst gitIdentityCache = new Map<string, { expiresAt: number; identity: string }>();\nconst syntheticRepositoryAliases = new WeakSet<object>();\nconst recordedWorkspacesByIdentityMap = new WeakMap<object, ReadonlySet<string>>();\n\nexport function normalizeRepositoryWorkspaceIdentity(\n\tvalue: string | null | undefined,\n): string | null {\n\tconst cleaned = value?.trim();\n\tif (!cleaned) return null;\n\treturn cleaned.replaceAll(\"\\\\\", \"/\").replace(/\\/+$/u, \"\") || cleaned;\n}\n\nconst normalizeIdentity = normalizeRepositoryWorkspaceIdentity;\n\nexport function hasRecordedRepositoryWorkspace(\n\trepositoryIdentities: ReadonlyMap<string, string>,\n\tworkspace: string | null | undefined,\n): boolean {\n\tconst normalized = normalizeIdentity(workspace);\n\treturn Boolean(\n\t\tnormalized && recordedWorkspacesByIdentityMap.get(repositoryIdentities)?.has(normalized),\n\t);\n}\n\nfunction cachedGitRepositoryIdentity(cwd: string): string | null {\n\tconst normalizedCwd = normalizeIdentity(cwd);\n\tif (!normalizedCwd) return null;\n\tconst now = Date.now();\n\tconst cached = gitIdentityCache.get(normalizedCwd);\n\tif (cached && cached.expiresAt > now) return cached.identity;\n\tif (cached) gitIdentityCache.delete(normalizedCwd);\n\tconst identity = normalizeIdentity(resolveGitRepositoryIdentity(cwd)?.identity);\n\tif (!identity) return null;\n\tif (gitIdentityCache.size >= GIT_IDENTITY_CACHE_MAX_ENTRIES) {\n\t\tconst oldestKey = gitIdentityCache.keys().next().value;\n\t\tif (oldestKey) gitIdentityCache.delete(oldestKey);\n\t}\n\tgitIdentityCache.set(normalizedCwd, {\n\t\texpiresAt: now + GIT_IDENTITY_CACHE_TTL_MS,\n\t\tidentity,\n\t});\n\treturn identity;\n}\n\nfunction gitRepositoryIdentity(cwd: string, bypassCache: boolean): string | null {\n\tif (!bypassCache) return cachedGitRepositoryIdentity(cwd);\n\tconst normalizedCwd = normalizeIdentity(cwd);\n\tif (!normalizedCwd) return null;\n\tgitIdentityCache.delete(normalizedCwd);\n\treturn normalizeIdentity(resolveGitRepositoryIdentity(cwd)?.identity);\n}\n\nfunction recordedRepositoryIdentity(row: {\n\tgit_remote?: string | null;\n\tmetadata_json?: string | null;\n\trepository_identity?: string | null;\n}): string | null {\n\treturn normalizeIdentity(\n\t\tcleanProjectIdentity(row.repository_identity) ??\n\t\t\tcleanProjectIdentity(repositoryIdentityFromMetadata(row.metadata_json)) ??\n\t\t\tcleanProjectIdentity(row.git_remote),\n\t);\n}\n\nfunction recordedRepositoryEvidence(row: {\n\tcwd: string;\n\tgit_remote?: string | null;\n\tmetadata_json?: string | null;\n\trepository_identity?: string | null;\n}): { cwd: string; fromMetadata: boolean; repositoryIdentity: string } | null {\n\tconst cwd = normalizeIdentity(row.cwd);\n\tif (!cwd) return null;\n\tconst metadataIdentity = normalizeIdentity(\n\t\tcleanProjectIdentity(row.repository_identity) ??\n\t\t\tcleanProjectIdentity(repositoryIdentityFromMetadata(row.metadata_json)),\n\t);\n\tconst repositoryIdentity =\n\t\tmetadataIdentity ?? normalizeIdentity(cleanProjectIdentity(row.git_remote));\n\tif (!repositoryIdentity) return null;\n\treturn { cwd, fromMetadata: metadataIdentity != null, repositoryIdentity };\n}\n\nfunction addRecordedRepositoryIdentity(\n\tidentities: Map<string, Set<string>>,\n\tcwd: string,\n\trepositoryIdentity: string,\n): void {\n\tconst recorded = identities.get(cwd) ?? new Set<string>();\n\trecorded.add(repositoryIdentity);\n\tidentities.set(cwd, recorded);\n}\n\nfunction recordedRepositoryIdentities(\n\trows: Array<{\n\t\tcwd: string;\n\t\tgit_remote?: string | null;\n\t\tmetadata_json?: string | null;\n\t\trepository_identity?: string | null;\n\t}>,\n): {\n\tbyWorkspace: Map<string, Set<string>>;\n\tknown: Set<string>;\n} {\n\tconst metadataByWorkspace = new Map<string, Set<string>>();\n\tconst remoteByWorkspace = new Map<string, Set<string>>();\n\tconst known = new Set<string>();\n\tfor (const row of rows) {\n\t\tconst evidence = recordedRepositoryEvidence(row);\n\t\tif (!evidence) continue;\n\t\taddRecordedRepositoryIdentity(\n\t\t\tevidence.fromMetadata ? metadataByWorkspace : remoteByWorkspace,\n\t\t\tevidence.cwd,\n\t\t\tevidence.repositoryIdentity,\n\t\t);\n\t}\n\tconst byWorkspace = new Map<string, Set<string>>();\n\tfor (const cwd of new Set([...metadataByWorkspace.keys(), ...remoteByWorkspace.keys()])) {\n\t\tconst recorded = new Set([\n\t\t\t...(metadataByWorkspace.get(cwd) ?? []),\n\t\t\t...(remoteByWorkspace.get(cwd) ?? []),\n\t\t]);\n\t\tif (recorded.size === 0) continue;\n\t\tbyWorkspace.set(cwd, recorded);\n\t\tfor (const repositoryIdentity of recorded) known.add(repositoryIdentity);\n\t}\n\treturn { byWorkspace, known };\n}\n\nexport function recordedRepositoryIdentitySetsByWorkspace(db: Database): Map<string, Set<string>> {\n\tconst rows = db\n\t\t.prepare(\n\t\t\t`SELECT DISTINCT cwd, git_remote, metadata_json\n\t\t\t FROM sessions\n\t\t\t WHERE cwd IS NOT NULL AND TRIM(cwd) <> ''\n\t\t\t AND ((json_valid(metadata_json)\n\t\t\t AND json_type(metadata_json, '$.codemem_repository_identity') = 'text')\n\t\t\t OR (git_remote IS NOT NULL AND TRIM(git_remote) <> ''))`,\n\t\t)\n\t\t.all() as Array<{ cwd: string; git_remote: string | null; metadata_json: string | null }>;\n\treturn recordedRepositoryIdentities(rows).byWorkspace;\n}\n\nexport function recordedRepositoryIdentityEvidence(db: Database): {\n\tbyWorkspace: Map<string, string>;\n\tknown: Set<string>;\n\trecordedWorkspaces: Set<string>;\n} {\n\tconst byWorkspaceSets = recordedRepositoryIdentitySetsByWorkspace(db);\n\tconst byWorkspace = new Map<string, string>();\n\tconst recordedWorkspaces = new Set(byWorkspaceSets.keys());\n\tconst known = new Set<string>();\n\trecordedWorkspacesByIdentityMap.set(byWorkspace, recordedWorkspaces);\n\tfor (const [cwd, identities] of byWorkspaceSets) {\n\t\tfor (const identity of identities) known.add(identity);\n\t\tif (identities.size !== 1) continue;\n\t\tconst [repositoryIdentity] = identities;\n\t\tif (repositoryIdentity) byWorkspace.set(cwd, repositoryIdentity);\n\t}\n\treturn {\n\t\tbyWorkspace,\n\t\tknown,\n\t\trecordedWorkspaces,\n\t};\n}\n\nexport function repositoryIdentityMapFromEvidence(\n\trows: Array<{ cwd: string; recordedIdentities: string[]; filesystemIdentity: string | null }>,\n\tknown: ReadonlySet<string>,\n): Map<string, string> {\n\tconst identities = new Map<string, string>();\n\tconst recordedWorkspaces = new Set<string>();\n\trecordedWorkspacesByIdentityMap.set(identities, recordedWorkspaces);\n\tfor (const row of rows) {\n\t\tif (row.recordedIdentities.length > 0) {\n\t\t\trecordedWorkspaces.add(row.cwd);\n\t\t\tif (row.recordedIdentities.length === 1) {\n\t\t\t\tconst identity = row.recordedIdentities[0];\n\t\t\t\tif (identity) identities.set(row.cwd, identity);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (row.filesystemIdentity && known.has(row.filesystemIdentity)) {\n\t\t\tidentities.set(row.cwd, row.filesystemIdentity);\n\t\t}\n\t}\n\treturn identities;\n}\n\nexport function discoverKnownRepositoryIdentity(\n\tcwd: string,\n\tknownRepositoryIdentities: ReadonlySet<string>,\n): string | null {\n\tif (!isAbsolute(cwd)) return null;\n\tconst repositoryIdentity = cachedGitRepositoryIdentity(cwd);\n\treturn repositoryIdentity && knownRepositoryIdentities.has(repositoryIdentity)\n\t\t? repositoryIdentity\n\t\t: null;\n}\n\n/** Recorded evidence shared only for the lifetime of one inventory request. */\nexport interface RepositoryIdentitySnapshot {\n\treadonly recordedByWorkspace: ReadonlyMap<string, ReadonlySet<string>>;\n\treadonly workspaces: readonly { readonly cwd: string }[];\n}\n\nexport function readRepositoryIdentitySnapshot(db: Database): RepositoryIdentitySnapshot {\n\tconst recordedByWorkspace = recordedRepositoryIdentitySetsByWorkspace(db);\n\tconst workspaces = db\n\t\t.prepare(\n\t\t\t`SELECT DISTINCT cwd\n\t\t\t FROM sessions\n\t\t\t WHERE cwd IS NOT NULL AND TRIM(cwd) <> ''\n\t\t\t ORDER BY cwd`,\n\t\t)\n\t\t.all() as Array<{ cwd: string }>;\n\treturn { recordedByWorkspace, workspaces };\n}\n\nexport function repositoryIdentitiesByWorkspace(\n\tdb: Database,\n\toptions: {\n\t\tknownRepositoryIdentities?: Iterable<string | null | undefined>;\n\t\trepositoryIdentitySnapshot?: RepositoryIdentitySnapshot;\n\t} = {},\n): Map<string, string> {\n\tconst snapshot = options.repositoryIdentitySnapshot ?? readRepositoryIdentitySnapshot(db);\n\t// Each consumer may mutate its map or supply different identities for discovery.\n\tconst identities = new Map<string, string>();\n\tconst recordedWorkspaces = new Set<string>();\n\trecordedWorkspacesByIdentityMap.set(identities, recordedWorkspaces);\n\taddUnambiguousRecordedEvidence(identities, recordedWorkspaces, snapshot.recordedByWorkspace);\n\tconst known = new Set<string>();\n\tfor (const recorded of snapshot.recordedByWorkspace.values()) {\n\t\tfor (const identity of recorded) known.add(identity);\n\t}\n\tfor (const identity of options.knownRepositoryIdentities ?? []) {\n\t\tconst normalized = normalizeIdentity(cleanProjectIdentity(identity));\n\t\tif (normalized) known.add(normalized);\n\t}\n\tfor (const row of snapshot.workspaces) {\n\t\tconst cwd = normalizeIdentity(row.cwd);\n\t\tif (!cwd || identities.has(cwd) || recordedWorkspaces.has(cwd)) continue;\n\t\tconst repositoryIdentity = discoverKnownRepositoryIdentity(row.cwd, known);\n\t\tif (repositoryIdentity) identities.set(cwd, repositoryIdentity);\n\t}\n\treturn identities;\n}\n\nexport function canonicalRepositoryProjectIdentity(\n\trepositoryIdentities: ReadonlyMap<string, string>,\n\tvalue: string,\n): string {\n\tconst identity = normalizeIdentity(value);\n\tif (!identity) return value;\n\treturn repositoryIdentities.get(identity) ?? identity;\n}\n\nexport function repositoryIdentityForWorkspace(\n\trepositoryIdentities: ReadonlyMap<string, string>,\n\tinput: {\n\t\tcwd?: string | null;\n\t\tgitRemote: string | null;\n\t\tmetadataJson?: string | null;\n\t\trepositoryIdentity?: string | null;\n\t},\n): string | null {\n\tconst recorded =\n\t\tnormalizeIdentity(cleanProjectIdentity(input.repositoryIdentity)) ??\n\t\tnormalizeIdentity(cleanProjectIdentity(repositoryIdentityFromMetadata(input.metadataJson)));\n\tif (recorded) return recorded;\n\tconst gitRemote = normalizeIdentity(cleanProjectIdentity(input.gitRemote));\n\tif (gitRemote) return gitRemote;\n\tconst cwd = normalizeIdentity(input.cwd);\n\treturn cwd ? (repositoryIdentities.get(cwd) ?? null) : null;\n}\n\nexport function recordedRepositoryIdentitiesByWorkspace(\n\tdb: Database,\n\tworkspaceIdentities: Iterable<string | null | undefined>,\n\toptions: { freshWorkspaces?: Iterable<string | null | undefined> } = {},\n): Map<string, string> {\n\treturn recordedRepositoryIdentityEvidenceByWorkspace(db, workspaceIdentities, options)\n\t\t.byWorkspace;\n}\n\nfunction collectRecordedRepositoryEvidence(\n\trows: Array<{ cwd: string; git_remote: string | null; metadata_json: string | null }>,\n\trequested: ReadonlySet<string>,\n): { known: Set<string>; recordedByWorkspace: Map<string, Set<string>> } {\n\tconst recorded = recordedRepositoryIdentities(rows);\n\treturn {\n\t\tknown: recorded.known,\n\t\trecordedByWorkspace: new Map(\n\t\t\t[...recorded.byWorkspace].filter(([workspace]) => requested.has(workspace)),\n\t\t),\n\t};\n}\n\nfunction addUnambiguousRecordedEvidence(\n\tidentities: Map<string, string>,\n\trecordedWorkspaces: Set<string>,\n\trecordedByWorkspace: ReadonlyMap<string, ReadonlySet<string>>,\n): void {\n\tfor (const [workspaceIdentity, recorded] of recordedByWorkspace) {\n\t\trecordedWorkspaces.add(workspaceIdentity);\n\t\tif (recorded.size !== 1) continue;\n\t\tconst [repositoryIdentity] = recorded;\n\t\tif (repositoryIdentity) identities.set(workspaceIdentity, repositoryIdentity);\n\t}\n}\n\nfunction addDiscoveredRepositoryEvidence(\n\tidentities: Map<string, string>,\n\trecordedWorkspaces: ReadonlySet<string>,\n\tworkspaceIdentities: string[],\n\tknownRepositoryIdentities: ReadonlySet<string>,\n\tfreshWorkspaces: ReadonlySet<string>,\n): void {\n\tfor (const workspaceIdentity of workspaceIdentities) {\n\t\tif (recordedWorkspaces.has(workspaceIdentity) || !isAbsolute(workspaceIdentity)) continue;\n\t\tconst discovered = gitRepositoryIdentity(\n\t\t\tworkspaceIdentity,\n\t\t\tfreshWorkspaces.has(workspaceIdentity),\n\t\t);\n\t\tif (discovered && knownRepositoryIdentities.has(discovered)) {\n\t\t\tidentities.set(workspaceIdentity, discovered);\n\t\t}\n\t}\n}\n\nexport function recordedRepositoryIdentityEvidenceByWorkspace(\n\tdb: Database,\n\tworkspaceIdentities: Iterable<string | null | undefined>,\n\toptions: { freshWorkspaces?: Iterable<string | null | undefined> } = {},\n): {\n\tbyWorkspace: Map<string, string>;\n\trecordedWorkspaces: Set<string>;\n} {\n\tconst identities = new Map<string, string>();\n\tconst recordedWorkspaces = new Set<string>();\n\trecordedWorkspacesByIdentityMap.set(identities, recordedWorkspaces);\n\tconst normalizedWorkspaces = [\n\t\t...new Set(\n\t\t\t[...workspaceIdentities]\n\t\t\t\t.map((identity) => normalizeIdentity(identity))\n\t\t\t\t.filter((identity): identity is string => identity != null),\n\t\t),\n\t];\n\tconst freshWorkspaces = new Set(\n\t\t[...(options.freshWorkspaces ?? [])]\n\t\t\t.map((identity) => normalizeIdentity(identity))\n\t\t\t.filter((identity): identity is string => identity != null),\n\t);\n\tconst requested = new Set(normalizedWorkspaces);\n\tconst rows = db\n\t\t.prepare(\n\t\t\t`SELECT cwd, git_remote, metadata_json FROM sessions\n\t\t\t WHERE cwd IS NOT NULL AND TRIM(cwd) <> '' ORDER BY id DESC`,\n\t\t)\n\t\t.all() as Array<{ cwd: string; git_remote: string | null; metadata_json: string | null }>;\n\tconst evidence = collectRecordedRepositoryEvidence(rows, requested);\n\taddUnambiguousRecordedEvidence(identities, recordedWorkspaces, evidence.recordedByWorkspace);\n\taddDiscoveredRepositoryEvidence(\n\t\tidentities,\n\t\trecordedWorkspaces,\n\t\tnormalizedWorkspaces,\n\t\tevidence.known,\n\t\tfreshWorkspaces,\n\t);\n\treturn { byWorkspace: identities, recordedWorkspaces };\n}\n\nexport function recordedWorkspacesForRepositoryIdentity(\n\tdb: Database,\n\trepositoryIdentity: string,\n): Map<string, string> {\n\tconst normalizedRepositoryIdentity = normalizeIdentity(repositoryIdentity);\n\tif (!normalizedRepositoryIdentity) return new Map();\n\tconst rows = db\n\t\t.prepare(\n\t\t\t`SELECT DISTINCT cwd, git_remote, metadata_json\n\t\t\t FROM sessions\n\t\t\t WHERE cwd IS NOT NULL AND TRIM(cwd) <> ''\n\t\t\t AND (RTRIM(REPLACE(TRIM(git_remote), char(92), '/'), '/') = ?\n\t\t\t OR (json_valid(metadata_json)\n\t\t\t AND json_type(metadata_json, '$.codemem_repository_identity') = 'text'\n\t\t\t AND RTRIM(REPLACE(TRIM(json_extract(metadata_json, '$.codemem_repository_identity')), char(92), '/'), '/') = ?))\n\t\t\t ORDER BY cwd`,\n\t\t)\n\t\t.all(normalizedRepositoryIdentity, normalizedRepositoryIdentity) as Array<{\n\t\tcwd: string;\n\t\tgit_remote: string | null;\n\t\tmetadata_json: string | null;\n\t}>;\n\tconst matchingRows = rows.filter(\n\t\t(row) => recordedRepositoryIdentity(row) === normalizedRepositoryIdentity,\n\t);\n\tconst evidence = recordedRepositoryIdentityEvidenceByWorkspace(\n\t\tdb,\n\t\tmatchingRows.map((row) => row.cwd),\n\t);\n\treturn new Map(\n\t\t[...evidence.byWorkspace].filter(([, identity]) => identity === normalizedRepositoryIdentity),\n\t);\n}\n\nfunction compareMappingPrecedence(left: ScopeMapping, right: ScopeMapping): number {\n\tconst leftUpdatedAt = Date.parse(left.updated_at ?? \"\") || 0;\n\tconst rightUpdatedAt = Date.parse(right.updated_at ?? \"\") || 0;\n\treturn (\n\t\t(right.priority ?? 0) - (left.priority ?? 0) ||\n\t\trightUpdatedAt - leftUpdatedAt ||\n\t\t(right.id ?? 0) - (left.id ?? 0)\n\t);\n}\n\nfunction mappedRepositoryIdentity(\n\tidentity: string,\n\trepositoryIdentities: ReadonlyMap<string, string>,\n\tknownRepositoryIdentities: Set<string>,\n\tdiscoverFilesystem: boolean,\n): string | null {\n\tconst recorded = repositoryIdentities.get(identity);\n\tif (recorded) return recorded;\n\tif (recordedWorkspacesByIdentityMap.get(repositoryIdentities)?.has(identity)) return null;\n\tif (!discoverFilesystem || !isAbsolute(identity)) return null;\n\tconst discovered = cachedGitRepositoryIdentity(identity);\n\treturn discovered && knownRepositoryIdentities.has(discovered) ? discovered : null;\n}\n\nfunction mappingsGroupedByRepository<T extends ScopeMapping>(\n\tmappings: T[],\n\trepositoryIdentities: ReadonlyMap<string, string>,\n\tdiscoverFilesystem: boolean,\n): Map<string, T[]> {\n\tconst grouped = new Map<string, T[]>();\n\tconst knownRepositoryIdentities = new Set(repositoryIdentities.values());\n\tfor (const mapping of mappings) {\n\t\tconst identity = normalizeIdentity(mapping.workspace_identity);\n\t\tif (!identity) continue;\n\t\tconst repositoryIdentity = mappedRepositoryIdentity(\n\t\t\tidentity,\n\t\t\trepositoryIdentities,\n\t\t\tknownRepositoryIdentities,\n\t\t\tdiscoverFilesystem,\n\t\t);\n\t\tif (!repositoryIdentity || repositoryIdentity === identity) continue;\n\t\tconst repositoryMappings = grouped.get(repositoryIdentity) ?? [];\n\t\trepositoryMappings.push(mapping);\n\t\tgrouped.set(repositoryIdentity, repositoryMappings);\n\t}\n\treturn grouped;\n}\n\nexport function withRepositoryMappingAliasesFromIdentities<T extends ScopeMapping>(\n\tmappings: T[],\n\trepositoryIdentities: ReadonlyMap<string, string>,\n\toptions: { discoverFilesystem?: boolean } = {},\n): T[] {\n\tif (mappings.length === 0) return mappings;\n\tconst explicitIdentities = new Set(\n\t\tmappings\n\t\t\t.map((mapping) => normalizeIdentity(mapping.workspace_identity))\n\t\t\t.filter((identity): identity is string => identity != null),\n\t);\n\tconst mappingsByRepository = mappingsGroupedByRepository(\n\t\tmappings,\n\t\trepositoryIdentities,\n\t\toptions.discoverFilesystem === true,\n\t);\n\tconst aliases = new Map<string, T>();\n\tfor (const [repositoryIdentity, repositoryMappings] of mappingsByRepository) {\n\t\tif (explicitIdentities.has(repositoryIdentity)) continue;\n\t\tconst scopeIds = new Set(repositoryMappings.map((mapping) => mapping.scope_id));\n\t\tif (scopeIds.size !== 1) continue;\n\t\tconst mapping = repositoryMappings.toSorted(compareMappingPrecedence)[0];\n\t\tif (mapping) {\n\t\t\tconst alias = { ...mapping, workspace_identity: repositoryIdentity };\n\t\t\tsyntheticRepositoryAliases.add(alias);\n\t\t\taliases.set(repositoryIdentity, alias);\n\t\t}\n\t}\n\treturn [...mappings, ...aliases.values()];\n}\n\nfunction repositoryWorkspacesForMappings(\n\tmappings: ScopeMapping[],\n\trepositoryIdentities: ReadonlyMap<string, string>,\n\trepositoryIdentity: string,\n): Set<string> {\n\tconst workspaces = new Set(\n\t\t[...repositoryIdentities]\n\t\t\t.filter(([, identity]) => identity === repositoryIdentity)\n\t\t\t.map(([workspace]) => workspace),\n\t);\n\tconst knownRepositoryIdentities = new Set(repositoryIdentities.values());\n\tknownRepositoryIdentities.add(repositoryIdentity);\n\tfor (const mapping of mappings) {\n\t\tconst identity = normalizeIdentity(mapping.workspace_identity);\n\t\tif (!identity || identity === repositoryIdentity) continue;\n\t\tif (\n\t\t\tmappedRepositoryIdentity(identity, repositoryIdentities, knownRepositoryIdentities, true) ===\n\t\t\trepositoryIdentity\n\t\t) {\n\t\t\tworkspaces.add(identity);\n\t\t}\n\t}\n\treturn workspaces;\n}\n\nfunction repositoryScopeResolutions(\n\tmappings: ScopeMapping[],\n\trepositoryIdentity: string,\n\tworkspaces: ReadonlySet<string>,\n): { explicitLocalWinner: boolean; scopeIds: Set<string>; mappedScopeIds: Set<string> } {\n\tconst scopeIds = new Set<string>();\n\tconst mappedScopeIds = new Set<string>();\n\tlet explicitLocalWinner = false;\n\tconst candidateWorkspaces = workspaces.size > 0 ? workspaces : [null];\n\tfor (const cwd of candidateWorkspaces) {\n\t\tconst resolution = resolveProjectScope({ repositoryIdentity, cwd, mappings });\n\t\tscopeIds.add(resolution.scopeId);\n\t\tif (resolution.mapping) mappedScopeIds.add(resolution.scopeId);\n\t\tif (resolution.scopeId === LOCAL_DEFAULT_SCOPE_ID && resolution.mapping) {\n\t\t\texplicitLocalWinner = true;\n\t\t}\n\t}\n\treturn { explicitLocalWinner, scopeIds, mappedScopeIds };\n}\n\nexport function mappedScopeIdsForRepository(\n\tmappings: ScopeMapping[],\n\trepositoryIdentities: ReadonlyMap<string, string>,\n\trepositoryIdentity: string,\n): Set<string> {\n\tconst normalized = normalizeIdentity(repositoryIdentity);\n\tif (!normalized) return new Set();\n\tconst effectiveMappings = mappings.filter((mapping) => !syntheticRepositoryAliases.has(mapping));\n\tconst workspaces = repositoryWorkspacesForMappings(\n\t\teffectiveMappings,\n\t\trepositoryIdentities,\n\t\tnormalized,\n\t);\n\treturn repositoryScopeResolutions(effectiveMappings, normalized, workspaces).mappedScopeIds;\n}\n\nexport function hasConflictingRepositoryMappings(\n\tmappings: ScopeMapping[],\n\trepositoryIdentities: ReadonlyMap<string, string>,\n\trepositoryIdentity: string,\n): boolean {\n\tconst normalizedRepositoryIdentity = normalizeIdentity(repositoryIdentity);\n\tif (!normalizedRepositoryIdentity) return false;\n\tconst effectiveMappings = mappings.filter((mapping) => !syntheticRepositoryAliases.has(mapping));\n\tconst repositoryWorkspaces = repositoryWorkspacesForMappings(\n\t\teffectiveMappings,\n\t\trepositoryIdentities,\n\t\tnormalizedRepositoryIdentity,\n\t);\n\tconst { explicitLocalWinner, scopeIds } = repositoryScopeResolutions(\n\t\teffectiveMappings,\n\t\tnormalizedRepositoryIdentity,\n\t\trepositoryWorkspaces,\n\t);\n\tif (scopeIds.size <= 1) return false;\n\tif (explicitLocalWinner) return true;\n\tconst sharedScopes = new Set(\n\t\t[...scopeIds].filter((scopeId) => scopeId !== LOCAL_DEFAULT_SCOPE_ID),\n\t);\n\tif (sharedScopes.size !== 1 || !scopeIds.has(LOCAL_DEFAULT_SCOPE_ID)) return true;\n\tconst mappingsWithAliases = withRepositoryMappingAliasesFromIdentities(\n\t\teffectiveMappings,\n\t\trepositoryIdentities,\n\t\t{ discoverFilesystem: true },\n\t);\n\tconst fallback = resolveProjectScope({\n\t\trepositoryIdentity: normalizedRepositoryIdentity,\n\t\tmappings: mappingsWithAliases,\n\t\tallowRepositoryCwdFallback: false,\n\t});\n\treturn !fallback.mapping || !sharedScopes.has(fallback.scopeId);\n}\n\n/**\n * Treat an existing checkout-path mapping as a repository mapping after that\n * checkout gains trusted repository identity. This preserves pre-upgrade Space\n * assignments while making sibling worktrees inherit the same decision.\n */\nexport function withRepositoryMappingAliases<T extends ScopeMapping>(\n\tdb: Database,\n\tmappings: T[],\n\toptions: { repositoryIdentitySnapshot?: RepositoryIdentitySnapshot } = {},\n): T[] {\n\tif (mappings.length === 0) return mappings;\n\tconst repositoryIdentities = repositoryIdentitiesByWorkspace(db, options);\n\treturn withRepositoryMappingAliasesFromIdentities(mappings, repositoryIdentities, {\n\t\tdiscoverFilesystem: true,\n\t});\n}\n","import { isStrictRecipientPolicyId } from \"./recipient-policy-identifiers.js\";\n\nexport const POLICY_TEAM_DEVICE_ELIGIBILITY_MODES = [\n\t\"person_all_devices\",\n\t\"reviewed_allowlist\",\n] as const;\n\nexport type PolicyTeamDeviceEligibilityMode = (typeof POLICY_TEAM_DEVICE_ELIGIBILITY_MODES)[number];\n\nexport const POLICY_TEAM_DEVICE_DECISIONS = [\"included\", \"excluded\", \"unresolved\"] as const;\n\nexport type PolicyTeamDeviceDecision = (typeof POLICY_TEAM_DEVICE_DECISIONS)[number];\n\nexport type PolicyTeamDeviceEligibilityBlockCode =\n\t| \"team_device_eligibility_mode_invalid\"\n\t| \"team_device_decision_invalid\"\n\t| \"team_membership_invalid\"\n\t| \"team_membership_mode_invalid\"\n\t| \"team_member_identity_missing\"\n\t| \"team_member_identity_not_active\"\n\t| \"team_member_identity_merged\"\n\t| \"identity_device_invalid\";\n\nexport interface PolicyTeamDeviceEligibilityIdentity {\n\tidentityId: string;\n\tstatus: string;\n\tmergedIntoIdentityId: string | null;\n}\n\nexport interface PolicyTeamDeviceEligibilityMembership {\n\tidentityId: string;\n\tstatus: string;\n}\n\nexport interface PolicyTeamDeviceEligibilityDevice {\n\tidentityId: string;\n\tdeviceId: string;\n\tstatus: string;\n\tassignmentVersion: number;\n}\n\nexport interface PolicyTeamDeviceEligibilityDecision {\n\tdeviceId: string;\n\tdecision: string;\n\tassignmentVersion: number;\n}\n\nexport interface DerivePolicyTeamDeviceEligibilityInput {\n\tteamId: string;\n\tmode: string;\n\tmemberships: PolicyTeamDeviceEligibilityMembership[];\n\tidentities: PolicyTeamDeviceEligibilityIdentity[];\n\tdevices: PolicyTeamDeviceEligibilityDevice[];\n\tdecisions: PolicyTeamDeviceEligibilityDecision[];\n}\n\nexport interface PolicyTeamDeviceEligibilityBlock {\n\tcode: PolicyTeamDeviceEligibilityBlockCode;\n\treferenceId: string;\n}\n\nexport interface EligiblePolicyTeamDeviceEligibilityResult {\n\tstatus: \"eligible\";\n\tactiveMemberIdentityIds: string[];\n\teligibleDeviceIds: string[];\n\tblocked: [];\n}\n\nexport interface BlockedPolicyTeamDeviceEligibilityResult {\n\tstatus: \"blocked\";\n\tblocked: [PolicyTeamDeviceEligibilityBlock, ...PolicyTeamDeviceEligibilityBlock[]];\n}\n\nexport type PolicyTeamDeviceEligibilityResult =\n\t| EligiblePolicyTeamDeviceEligibilityResult\n\t| BlockedPolicyTeamDeviceEligibilityResult;\n\nconst MODES = new Set<string>(POLICY_TEAM_DEVICE_ELIGIBILITY_MODES);\nconst DECISIONS = new Set<string>(POLICY_TEAM_DEVICE_DECISIONS);\nconst DEVICE_STATUSES = new Set([\"active\", \"revoked\"]);\nconst INACTIVE_MEMBERSHIP_STATUSES = new Set([\"pending\", \"revoked\"]);\n// Surface authority-shape and principal-integrity failures before mutable\n// decision/device facts so callers expose the most security-relevant cause.\nconst BLOCK_PRECEDENCE: Record<PolicyTeamDeviceEligibilityBlockCode, number> = {\n\tteam_device_eligibility_mode_invalid: 0,\n\tteam_membership_invalid: 1,\n\tteam_membership_mode_invalid: 2,\n\tteam_member_identity_missing: 3,\n\tteam_member_identity_merged: 4,\n\tteam_member_identity_not_active: 5,\n\tteam_device_decision_invalid: 6,\n\tidentity_device_invalid: 7,\n};\n\nfunction compareText(left: string, right: string): number {\n\treturn left < right ? -1 : left > right ? 1 : 0;\n}\n\nexport function isPolicyTeamMembershipActiveForMode(mode: string, status: string): boolean {\n\treturn (\n\t\t(mode === \"person_all_devices\" && status === \"active\") ||\n\t\t(mode === \"reviewed_allowlist\" && status === \"reviewed_active\")\n\t);\n}\n\nfunction sortedBlocks(\n\tblocked: Iterable<PolicyTeamDeviceEligibilityBlock>,\n): PolicyTeamDeviceEligibilityBlock[] {\n\treturn [...blocked].toSorted(\n\t\t(left, right) =>\n\t\t\tBLOCK_PRECEDENCE[left.code] - BLOCK_PRECEDENCE[right.code] ||\n\t\t\tcompareText(left.referenceId, right.referenceId),\n\t);\n}\n\nfunction blockedResult(\n\tblocked: Iterable<PolicyTeamDeviceEligibilityBlock>,\n): BlockedPolicyTeamDeviceEligibilityResult {\n\tconst [first, ...rest] = sortedBlocks(blocked);\n\tif (!first) throw new Error(\"policy_team_device_eligibility_block_missing\");\n\treturn { status: \"blocked\", blocked: [first, ...rest] };\n}\n\nfunction collectDeviceDecisions(\n\tinput: Pick<DerivePolicyTeamDeviceEligibilityInput, \"teamId\" | \"mode\" | \"decisions\">,\n\taddBlock: (code: PolicyTeamDeviceEligibilityBlockCode, referenceId: string) => void,\n): Map<string, PolicyTeamDeviceEligibilityDecision> {\n\tconst decisions = new Map<string, PolicyTeamDeviceEligibilityDecision>();\n\tfor (const decision of input.decisions) {\n\t\tif (\n\t\t\t!isStrictRecipientPolicyId(decision.deviceId) ||\n\t\t\t!DECISIONS.has(decision.decision) ||\n\t\t\t!Number.isSafeInteger(decision.assignmentVersion) ||\n\t\t\tdecision.assignmentVersion < 0 ||\n\t\t\tdecisions.has(decision.deviceId) ||\n\t\t\t(input.mode === \"person_all_devices\" && decision.decision !== \"excluded\")\n\t\t) {\n\t\t\taddBlock(\"team_device_decision_invalid\", `${input.teamId}:${decision.deviceId}`);\n\t\t\tcontinue;\n\t\t}\n\t\tdecisions.set(decision.deviceId, decision);\n\t}\n\treturn decisions;\n}\n\nexport function derivePolicyTeamDeviceEligibility(\n\tinput: DerivePolicyTeamDeviceEligibilityInput,\n): PolicyTeamDeviceEligibilityResult {\n\tconst blocked = new Map<string, PolicyTeamDeviceEligibilityBlock>();\n\tconst addBlock = (code: PolicyTeamDeviceEligibilityBlockCode, referenceId: string): void => {\n\t\tblocked.set(`${code}\\u0000${referenceId}`, { code, referenceId });\n\t};\n\tif (!MODES.has(input.mode)) {\n\t\treturn blockedResult([\n\t\t\t{ code: \"team_device_eligibility_mode_invalid\", referenceId: input.teamId },\n\t\t]);\n\t}\n\tconst mode = input.mode as PolicyTeamDeviceEligibilityMode;\n\tconst activeMembers = new Set<string>();\n\tfor (const membership of input.memberships) {\n\t\tif (!isStrictRecipientPolicyId(membership.identityId)) {\n\t\t\taddBlock(\"team_membership_invalid\", `${input.teamId}:${membership.identityId}`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (isPolicyTeamMembershipActiveForMode(mode, membership.status)) {\n\t\t\tactiveMembers.add(membership.identityId);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!INACTIVE_MEMBERSHIP_STATUSES.has(membership.status)) {\n\t\t\taddBlock(\"team_membership_mode_invalid\", `${input.teamId}:${membership.identityId}`);\n\t\t}\n\t}\n\tconst identities = new Map(input.identities.map((identity) => [identity.identityId, identity]));\n\tfor (const identityId of activeMembers) {\n\t\tconst identity = identities.get(identityId);\n\t\tif (!identity) {\n\t\t\taddBlock(\"team_member_identity_missing\", identityId);\n\t\t\tcontinue;\n\t\t}\n\t\tif (identity.status === \"merged\" || identity.mergedIntoIdentityId) {\n\t\t\taddBlock(\"team_member_identity_merged\", identityId);\n\t\t\tcontinue;\n\t\t}\n\t\tif (identity.status !== \"active\") {\n\t\t\taddBlock(\"team_member_identity_not_active\", identityId);\n\t\t}\n\t}\n\tconst decisions = collectDeviceDecisions(input, addBlock);\n\tconst eligibleDeviceIds = new Set<string>();\n\tfor (const device of input.devices) {\n\t\tif (!activeMembers.has(device.identityId)) continue;\n\t\tif (!DEVICE_STATUSES.has(device.status)) {\n\t\t\taddBlock(\"identity_device_invalid\", device.deviceId);\n\t\t\tcontinue;\n\t\t}\n\t\tif (device.status !== \"active\") continue;\n\t\tif (\n\t\t\t!isStrictRecipientPolicyId(device.identityId) ||\n\t\t\t!isStrictRecipientPolicyId(device.deviceId) ||\n\t\t\t!Number.isSafeInteger(device.assignmentVersion) ||\n\t\t\tdevice.assignmentVersion < 0\n\t\t) {\n\t\t\taddBlock(\"identity_device_invalid\", device.deviceId);\n\t\t\tcontinue;\n\t\t}\n\t\tconst decision = decisions.get(device.deviceId);\n\t\t// A Team exclusion persists for this device ID when assignment metadata changes.\n\t\tif (mode === \"person_all_devices\" && decision?.decision === \"excluded\") continue;\n\t\tif (\n\t\t\tmode === \"person_all_devices\" ||\n\t\t\t(decision?.decision === \"included\" && decision.assignmentVersion === device.assignmentVersion)\n\t\t) {\n\t\t\teligibleDeviceIds.add(device.deviceId);\n\t\t}\n\t}\n\tif (blocked.size > 0) return blockedResult(blocked.values());\n\treturn {\n\t\tstatus: \"eligible\",\n\t\tactiveMemberIdentityIds: [...activeMembers].toSorted(compareText),\n\t\teligibleDeviceIds: [...eligibleDeviceIds].toSorted(compareText),\n\t\tblocked: [],\n\t};\n}\n","/**\n * Synthetic placeholder cwd used for sessions created during sync bootstrap.\n * Keep this in a dependency-free module so policy code can use it without\n * pulling the Node-only bootstrap runtime into Cloudflare Worker bundles.\n */\nexport const SYNC_BOOTSTRAP_CWD_PREFIX = \"__sync_bootstrap__\";\n","import type { Database } from \"./db.js\";\n\nexport type MaintenanceJobStatus = \"pending\" | \"running\" | \"completed\" | \"failed\" | \"cancelled\";\n\nexport interface MaintenanceJobRecord {\n\tkind: string;\n\ttitle: string;\n\tstatus: MaintenanceJobStatus;\n\tmessage: string | null;\n\tprogress_current: number;\n\tprogress_total: number | null;\n\tprogress_unit: string;\n\tmetadata_json: string | null;\n\tstarted_at: string | null;\n\tupdated_at: string;\n\tfinished_at: string | null;\n\terror: string | null;\n}\n\nexport interface MaintenanceJobSnapshot {\n\tkind: string;\n\ttitle: string;\n\tstatus: MaintenanceJobStatus;\n\tmessage: string | null;\n\tprogress: {\n\t\tcurrent: number;\n\t\ttotal: number | null;\n\t\tunit: string;\n\t};\n\tmetadata: Record<string, unknown> | null;\n\tstarted_at: string | null;\n\tupdated_at: string;\n\tfinished_at: string | null;\n\terror: string | null;\n}\n\nexport interface StartMaintenanceJobInput {\n\tkind: string;\n\ttitle: string;\n\tmessage?: string | null;\n\tprogressTotal?: number | null;\n\tprogressUnit?: string;\n\tmetadata?: Record<string, unknown> | null;\n\tstatus?: \"pending\" | \"running\";\n}\n\nexport interface UpdateMaintenanceJobInput {\n\tmessage?: string | null;\n\tprogressCurrent?: number;\n\tprogressTotal?: number | null;\n\tprogressUnit?: string;\n\tmetadata?: Record<string, unknown> | null;\n\tstatus?: MaintenanceJobStatus;\n}\n\nfunction ensureTable(db: Database): void {\n\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS maintenance_jobs (\n\t\t\tkind TEXT PRIMARY KEY,\n\t\t\ttitle TEXT NOT NULL,\n\t\t\tstatus TEXT NOT NULL,\n\t\t\tmessage TEXT,\n\t\t\tprogress_current INTEGER NOT NULL DEFAULT 0,\n\t\t\tprogress_total INTEGER,\n\t\t\tprogress_unit TEXT NOT NULL DEFAULT 'items',\n\t\t\tmetadata_json TEXT,\n\t\t\tstarted_at TEXT,\n\t\t\tupdated_at TEXT NOT NULL,\n\t\t\tfinished_at TEXT,\n\t\t\terror TEXT\n\t\t);\n\t\tCREATE INDEX IF NOT EXISTS idx_maintenance_jobs_status_updated\n\t\t\tON maintenance_jobs(status, updated_at);\n\t`);\n}\n\nfunction parseMetadata(value: string | null): Record<string, unknown> | null {\n\tif (!value) return null;\n\ttry {\n\t\tconst parsed = JSON.parse(value) as unknown;\n\t\tif (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n\t\t\treturn parsed as Record<string, unknown>;\n\t\t}\n\t} catch {\n\t\treturn null;\n\t}\n\treturn null;\n}\n\nfunction isTerminalStatus(status: MaintenanceJobStatus): boolean {\n\treturn status === \"completed\" || status === \"failed\" || status === \"cancelled\";\n}\n\nfunction resolveMessage(\n\tinput: UpdateMaintenanceJobInput,\n\texisting: MaintenanceJobSnapshot,\n): string | null {\n\tif (Object.hasOwn(input, \"message\")) {\n\t\treturn input.message ?? null;\n\t}\n\treturn existing.message;\n}\n\nfunction resolveMetadataJson(\n\tinput: UpdateMaintenanceJobInput,\n\texisting: MaintenanceJobSnapshot,\n): string | null {\n\tif (Object.hasOwn(input, \"metadata\")) {\n\t\treturn input.metadata ? JSON.stringify(input.metadata) : null;\n\t}\n\treturn existing.metadata ? JSON.stringify(existing.metadata) : null;\n}\n\nfunction toSnapshot(row: MaintenanceJobRecord | undefined): MaintenanceJobSnapshot | null {\n\tif (!row) return null;\n\tconst progressCurrent =\n\t\trow.status === \"completed\" && row.progress_total != null\n\t\t\t? row.progress_total\n\t\t\t: row.progress_current;\n\treturn {\n\t\tkind: row.kind,\n\t\ttitle: row.title,\n\t\tstatus: row.status,\n\t\tmessage: row.message,\n\t\tprogress: {\n\t\t\tcurrent: progressCurrent,\n\t\t\ttotal: row.progress_total,\n\t\t\tunit: row.progress_unit,\n\t\t},\n\t\tmetadata: parseMetadata(row.metadata_json),\n\t\tstarted_at: row.started_at,\n\t\tupdated_at: row.updated_at,\n\t\tfinished_at: row.finished_at,\n\t\terror: row.error,\n\t};\n}\n\nexport function getMaintenanceJob(db: Database, kind: string): MaintenanceJobSnapshot | null {\n\tensureTable(db);\n\tconst row = db.prepare(\"SELECT * FROM maintenance_jobs WHERE kind = ?\").get(kind) as\n\t\t| MaintenanceJobRecord\n\t\t| undefined;\n\treturn toSnapshot(row);\n}\n\nexport function listMaintenanceJobs(db: Database): MaintenanceJobSnapshot[] {\n\tensureTable(db);\n\tconst rows = db\n\t\t.prepare(\"SELECT * FROM maintenance_jobs ORDER BY updated_at DESC, kind ASC\")\n\t\t.all() as MaintenanceJobRecord[];\n\treturn rows\n\t\t.map((row) => toSnapshot(row))\n\t\t.filter((row): row is MaintenanceJobSnapshot => row != null);\n}\n\nexport function startMaintenanceJob(\n\tdb: Database,\n\tinput: StartMaintenanceJobInput,\n): MaintenanceJobSnapshot {\n\tensureTable(db);\n\tconst now = new Date().toISOString();\n\tconst status = input.status ?? \"running\";\n\tconst metadataJson = input.metadata ? JSON.stringify(input.metadata) : null;\n\tdb.prepare(\n\t\t`INSERT INTO maintenance_jobs(\n\t\t\tkind, title, status, message, progress_current, progress_total,\n\t\t\tprogress_unit, metadata_json, started_at, updated_at, finished_at, error\n\t\t) VALUES (?, ?, ?, ?, 0, ?, ?, ?, ?, ?, NULL, NULL)\n\t\tON CONFLICT(kind) DO UPDATE SET\n\t\t\ttitle = excluded.title,\n\t\t\tstatus = excluded.status,\n\t\t\tmessage = excluded.message,\n\t\t\tprogress_current = 0,\n\t\t\tprogress_total = excluded.progress_total,\n\t\t\tprogress_unit = excluded.progress_unit,\n\t\t\tmetadata_json = excluded.metadata_json,\n\t\t\tstarted_at = excluded.started_at,\n\t\t\tupdated_at = excluded.updated_at,\n\t\t\tfinished_at = NULL,\n\t\t\terror = NULL`,\n\t).run(\n\t\tinput.kind,\n\t\tinput.title,\n\t\tstatus,\n\t\tinput.message ?? null,\n\t\tinput.progressTotal ?? null,\n\t\tinput.progressUnit ?? \"items\",\n\t\tmetadataJson,\n\t\tnow,\n\t\tnow,\n\t);\n\tconst job = getMaintenanceJob(db, input.kind);\n\tif (!job) {\n\t\tthrow new Error(`Failed to start maintenance job: ${input.kind}`);\n\t}\n\treturn job;\n}\n\nexport function updateMaintenanceJob(\n\tdb: Database,\n\tkind: string,\n\tinput: UpdateMaintenanceJobInput,\n): MaintenanceJobSnapshot | null {\n\tensureTable(db);\n\tconst existing = getMaintenanceJob(db, kind);\n\tif (!existing) return null;\n\tconst now = new Date().toISOString();\n\tconst nextStatus = input.status ?? existing.status;\n\tconst transitioningToTerminal =\n\t\t!isTerminalStatus(existing.status) && isTerminalStatus(nextStatus);\n\tconst transitioningToRunning = isTerminalStatus(existing.status) && !isTerminalStatus(nextStatus);\n\tconst finishedAt = transitioningToTerminal\n\t\t? now\n\t\t: transitioningToRunning\n\t\t\t? null\n\t\t\t: existing.finished_at;\n\tconst error =\n\t\tnextStatus === \"failed\"\n\t\t\t? existing.error\n\t\t\t: nextStatus === \"completed\" || nextStatus === \"cancelled\" || transitioningToRunning\n\t\t\t\t? null\n\t\t\t\t: existing.error;\n\tdb.prepare(\n\t\t`UPDATE maintenance_jobs\n\t\t SET status = ?,\n\t\t message = ?,\n\t\t progress_current = ?,\n\t\t progress_total = ?,\n\t\t progress_unit = ?,\n\t\t metadata_json = ?,\n\t\t updated_at = ?,\n\t\t finished_at = ?,\n\t\t error = ?\n\t\t WHERE kind = ?`,\n\t).run(\n\t\tnextStatus,\n\t\tresolveMessage(input, existing),\n\t\tinput.progressCurrent ?? existing.progress.current,\n\t\tinput.progressTotal === undefined ? existing.progress.total : input.progressTotal,\n\t\tinput.progressUnit ?? existing.progress.unit,\n\t\tresolveMetadataJson(input, existing),\n\t\tnow,\n\t\tfinishedAt,\n\t\terror,\n\t\tkind,\n\t);\n\treturn getMaintenanceJob(db, kind);\n}\n\nexport function completeMaintenanceJob(\n\tdb: Database,\n\tkind: string,\n\tinput: Omit<UpdateMaintenanceJobInput, \"status\"> = {},\n): MaintenanceJobSnapshot | null {\n\treturn updateMaintenanceJob(db, kind, { ...input, status: \"completed\" });\n}\n\nexport function failMaintenanceJob(\n\tdb: Database,\n\tkind: string,\n\terror: string,\n\tinput: Omit<UpdateMaintenanceJobInput, \"status\"> = {},\n): MaintenanceJobSnapshot | null {\n\tensureTable(db);\n\tconst existing = getMaintenanceJob(db, kind);\n\tif (!existing) return null;\n\tconst now = new Date().toISOString();\n\tdb.prepare(\n\t\t`UPDATE maintenance_jobs\n\t\t SET status = 'failed',\n\t\t message = ?,\n\t\t progress_current = ?,\n\t\t\t progress_total = ?,\n\t\t\t progress_unit = ?,\n\t\t\t metadata_json = ?,\n\t\t\t updated_at = ?,\n\t\t\t finished_at = ?,\n\t\t\t error = ?\n\t\t WHERE kind = ?`,\n\t).run(\n\t\tresolveMessage(input, existing),\n\t\tinput.progressCurrent ?? existing.progress.current,\n\t\tinput.progressTotal === undefined ? existing.progress.total : input.progressTotal,\n\t\tinput.progressUnit ?? existing.progress.unit,\n\t\tresolveMetadataJson(input, existing),\n\t\tnow,\n\t\tnow,\n\t\terror,\n\t\tkind,\n\t);\n\treturn getMaintenanceJob(db, kind);\n}\n\nexport function ensureMaintenanceJobsSchema(db: Database): void {\n\tensureTable(db);\n}\n\n/**\n * A backfill write that loses the lock to another writer is not a job\n * failure: runners should skip the tick and retry instead of parking the job\n * as failed until the next process restart.\n */\nexport function isTransientSqliteBusy(error: unknown): boolean {\n\tconst code =\n\t\ttypeof error === \"object\" && error != null\n\t\t\t? String((error as { code?: unknown }).code ?? \"\")\n\t\t\t: \"\";\n\t// Extended codes such as SQLITE_BUSY_SNAPSHOT and SQLITE_LOCKED_SHAREDCACHE are the same condition.\n\tif (code.startsWith(\"SQLITE_BUSY\") || code.startsWith(\"SQLITE_LOCKED\")) return true;\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn /database (?:table )?is (?:locked|busy)/i.test(message);\n}\n","import { createHash } from \"node:crypto\";\nimport type { Database } from \"./db.js\";\n\nfunction nonblankString(value: unknown): string | null {\n\tif (typeof value !== \"string\") return null;\n\treturn value.trim() ? value : null;\n}\n\nfunction hashIdentity(value: string | readonly [string, string]): string {\n\treturn createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\");\n}\n\nexport function isCanonicalSessionKey(value: string | null): value is string {\n\treturn value != null && /^export-session:v1:[a-f0-9]{64}(?::remap:[a-f0-9]{64})?$/.test(value);\n}\n\nfunction firstNonblankMemoryKey(db: Database, sessionId: number): string | null {\n\t// Use all history, independent of mutable labels or the caller's readable subset.\n\tconst candidates = db\n\t\t.prepare(`SELECT import_key FROM memory_items\n\t\t\tWHERE session_id = ? AND import_key IS NOT NULL\n\t\t\tORDER BY id ASC`)\n\t\t.iterate(sessionId) as IterableIterator<Record<string, unknown>>;\n\tfor (const candidate of candidates) {\n\t\tconst key = nonblankString(candidate.import_key);\n\t\tif (key) return key;\n\t}\n\treturn null;\n}\n\n/** Resolve export bookkeeping identity without changing source rows or enrollment state. */\nexport function exportedSessionKey(db: Database, row: Record<string, unknown>): string {\n\tconst sourceKey = nonblankString(row.import_key);\n\tif (isCanonicalSessionKey(sourceKey)) return sourceKey;\n\tif (sourceKey) return `export-session:v1:${hashIdentity([\"import_key\", sourceKey])}`;\n\n\tconst memoryKey = firstNonblankMemoryKey(db, Number(row.id));\n\tif (!memoryKey)\n\t\tthrow new Error(\"session_identity_unavailable: session has no immutable source key\");\n\treturn `export-session:v1:${hashIdentity([\"memory_key\", memoryKey])}`;\n}\n\n/** Apply a project namespace to a validated canonical key, replacing any prior remap. */\nexport function remappedSessionKey(marker: string, remapProject: string): string {\n\tconst baseKey = marker.replace(/:remap:[a-f0-9]{64}$/, \"\");\n\treturn `${baseKey}:remap:${hashIdentity(remapProject)}`;\n}\n","import type { Statement } from \"better-sqlite3\";\nimport type { Database } from \"./db.js\";\nimport { exportedSessionKey } from \"./session-export-identity.js\";\n\nfunction hasHistoricalMemoryAnchor(statement: Statement, sessionId: number): boolean {\n\tconst candidates = statement.iterate(sessionId) as IterableIterator<Record<string, unknown>>;\n\tfor (const candidate of candidates) {\n\t\tif (typeof candidate.import_key === \"string\" && candidate.import_key.trim()) return true;\n\t}\n\treturn false;\n}\n\n/** Preserve bookkeeping identity before changing memory anchors, never grant access. */\nexport function snapshotSessionExportKeysForMemoryIds(\n\tdb: Database,\n\tmemoryIds: readonly number[],\n): void {\n\tif (!db.inTransaction) throw new Error(\"session_export_identity_transaction_required\");\n\t// One JSON parameter carries numeric IDs without SQLite's variable limit.\n\t// Resolve only the supplied memory primary keys, then deduplicate actual sessions\n\t// before any per-session anchor reads while the caller holds its transaction.\n\tconst sessions = db\n\t\t.prepare(`SELECT DISTINCT s.id, s.import_key FROM memory_items m\n\t\t\tJOIN sessions s ON s.id = m.session_id\n\t\t\tWHERE m.id IN (SELECT value FROM json_each(?))`)\n\t\t.all(JSON.stringify(memoryIds)) as { id: number; import_key: string | null }[];\n\tconst findAnchor = db.prepare(`SELECT import_key FROM memory_items\n\t\tWHERE session_id = ? AND import_key IS NOT NULL ORDER BY id ASC`);\n\t// Match the original key (including NULL or whitespace), never replace a new key.\n\tconst saveKey = db.prepare(\"UPDATE sessions SET import_key = ? WHERE id = ? AND import_key IS ?\");\n\tfor (const session of sessions) {\n\t\tif (session.import_key?.trim()) continue;\n\t\t// No prior helper identity exists without an anchor; cleanup must still proceed.\n\t\tif (!hasHistoricalMemoryAnchor(findAnchor, session.id)) continue;\n\t\tsaveKey.run(exportedSessionKey(db, session), session.id, session.import_key);\n\t}\n}\n","/**\n * Shared helpers for populating the `memory_file_refs` and\n * `memory_concept_refs` junction tables from the denormalized JSON arrays\n * stored on `memory_items` rows.\n *\n * Used at write time in `MemoryStore.remember()`, during replication apply,\n * and by the ref-backfill maintenance job.\n */\n\nimport type { Database as SqliteDatabase } from \"better-sqlite3\";\n\n/**\n * Normalize a concept string for storage/lookup: trim whitespace and\n * lowercase. Shared across write, backfill, and query paths so the\n * normalization rule lives in exactly one place.\n */\nexport function normalizeConcept(concept: string): string {\n\treturn concept.trim().toLowerCase();\n}\n\n/**\n * Delete all existing ref rows for a memory. Used before re-populating on\n * updates where the files/concepts may have changed.\n */\nexport function clearMemoryRefs(db: SqliteDatabase, memoryId: number): void {\n\tdb.prepare(\"DELETE FROM memory_file_refs WHERE memory_id = ?\").run(memoryId);\n\tdb.prepare(\"DELETE FROM memory_concept_refs WHERE memory_id = ?\").run(memoryId);\n}\n\n/**\n * Populate `memory_file_refs` and `memory_concept_refs` junction-table rows\n * for a single memory item. Uses `INSERT OR IGNORE` so calling this on an\n * already-populated memory is a safe no-op.\n *\n * Callers are responsible for running this inside a transaction when\n * atomicity with the parent insert/update is required.\n */\nexport function populateMemoryRefs(\n\tdb: SqliteDatabase,\n\tmemoryId: number,\n\tfilesRead: string[] | null,\n\tfilesModified: string[] | null,\n\tconcepts: string[] | null,\n): void {\n\tconst insertFileRef = db.prepare(\n\t\t\"INSERT OR IGNORE INTO memory_file_refs (memory_id, file_path, relation) VALUES (?, ?, ?)\",\n\t);\n\tif (filesRead) {\n\t\tfor (const path of filesRead) {\n\t\t\tif (typeof path !== \"string\" || !path) continue;\n\t\t\tinsertFileRef.run(memoryId, path, \"read\");\n\t\t}\n\t}\n\tif (filesModified) {\n\t\tfor (const path of filesModified) {\n\t\t\tif (typeof path !== \"string\" || !path) continue;\n\t\t\tinsertFileRef.run(memoryId, path, \"modified\");\n\t\t}\n\t}\n\tconst insertConceptRef = db.prepare(\n\t\t\"INSERT OR IGNORE INTO memory_concept_refs (memory_id, concept) VALUES (?, ?)\",\n\t);\n\tif (concepts) {\n\t\tfor (const concept of concepts) {\n\t\t\tif (typeof concept !== \"string\") continue;\n\t\t\tconst normalized = normalizeConcept(concept);\n\t\t\tif (normalized) insertConceptRef.run(memoryId, normalized);\n\t\t}\n\t}\n}\n","import type { Database } from \"./db.js\";\nimport { resolveVectorLayout } from \"./vector-layout.js\";\n\nexport type VectorMetadataFilter = { memoryIds?: readonly number[]; model?: string };\n\nexport type VectorMetadataRow = {\n\trowid: bigint;\n\tmemory_id: bigint | null;\n\tmodel: string | null;\n\tcontent_hash: string | null;\n};\n\n/**\n * Whether vector metadata can be read from the indexed `validated_vector_rows`\n * table instead of scanning vec0.\n *\n * In the v1 layout that table holds exactly one row per vec0 row, with the\n * same rowid, memory_id, model, chunk_index, and content_hash:\n * - The upgrade copies legacy vectors and runs the census that fills the table\n * from the copy in one transaction (`upgradeWithinTransaction`).\n * - Every later census (`startAudit`) deletes and refills the table from vec0\n * in one transaction.\n * - The only vec0 insert path (`insertRow`) writes both tables, and the\n * `memory_vectors` view rejects inserts and updates.\n * - Deletes through the view remove both rows and abort if the indexed row is\n * missing. `removeRow` deletes both rows directly.\n * - Audits change only `audit_state` and `reason`, which callers never read.\n *\n * Legacy layouts can invalidate the index and write vec0 without it, so they\n * keep reading vec0. A layout that fails validation also keeps the vec0 read,\n * which is what every caller did before.\n *\n * As a cheap check against writes outside these paths (for example a manual\n * delete from memory_vectors_v1), the row counts must also match vec0's rowid\n * table. Both counts read b-tree pages only.\n */\nexport function hasIndexedVectorMetadata(db: Database): boolean {\n\tlet layout: ReturnType<typeof resolveVectorLayout>;\n\ttry {\n\t\tlayout = resolveVectorLayout(db);\n\t} catch {\n\t\treturn false;\n\t}\n\tif (layout.kind !== \"v1\") return false;\n\tconst count = (table: string) =>\n\t\tNumber(db.prepare(`SELECT COUNT(*) FROM ${table}`).pluck().get());\n\treturn count(\"validated_vector_rows\") === count(layout.rowidsName);\n}\n\n/**\n * Walk the distinct models with one index seek each. The only index on\n * `validated_vector_rows` that contains memory_id leads with model, so a\n * memory-only filter must be expanded into (model, memory_id) lookups.\n */\nfunction indexedModels(db: Database): Array<string | null> {\n\tconst models = db\n\t\t.prepare(\n\t\t\t`WITH RECURSIVE models(model) AS (\n\t\t\t\tSELECT (SELECT MIN(model) FROM validated_vector_rows)\n\t\t\t\tUNION ALL\n\t\t\t\tSELECT (SELECT MIN(model) FROM validated_vector_rows WHERE model > models.model)\n\t\t\t\tFROM models WHERE models.model IS NOT NULL\n\t\t\t)\n\t\t\tSELECT model FROM models WHERE model IS NOT NULL`,\n\t\t)\n\t\t.pluck()\n\t\t.all() as string[];\n\tconst hasNullModel = db\n\t\t.prepare(\"SELECT 1 FROM validated_vector_rows WHERE model IS NULL LIMIT 1\")\n\t\t.get();\n\treturn hasNullModel ? [null, ...models] : models;\n}\n\nfunction* readIndexedRows(\n\tdb: Database,\n\t{ memoryIds, model }: VectorMetadataFilter,\n\tmarker: string,\n): Generator<VectorMetadataRow> {\n\tconst columns = \"rowid, memory_id, model, content_hash\";\n\tif (memoryIds === undefined) {\n\t\tconst where = model === undefined ? \"\" : \"WHERE model = ?\";\n\t\tconst params = model === undefined ? [] : [model];\n\t\tconst select = db\n\t\t\t.prepare(`SELECT ${columns} FROM validated_vector_rows ${where} /* ${marker} indexed */`)\n\t\t\t.safeIntegers();\n\t\tyield* select.iterate(...params) as Iterable<VectorMetadataRow>;\n\t\treturn;\n\t}\n\tconst ids = JSON.stringify(memoryIds);\n\t// Resolve the model list before iterating: the connection cannot run another\n\t// statement while an iterator is open.\n\tconst models = model === undefined ? indexedModels(db) : [model];\n\tconst select = db\n\t\t.prepare(\n\t\t\t`SELECT ${columns} FROM validated_vector_rows\n\t\t\t WHERE model IS ? AND memory_id IN (SELECT value FROM json_each(?)) /* ${marker} indexed */`,\n\t\t)\n\t\t.safeIntegers();\n\tfor (const value of models) yield* select.iterate(value, ids) as Iterable<VectorMetadataRow>;\n}\n\nfunction* readVec0Rows(\n\tdb: Database,\n\t{ memoryIds, model }: VectorMetadataFilter,\n\tmarker: string,\n): Generator<VectorMetadataRow> {\n\t// Restrict copied rows to this batch; vec0 may still scan memory IDs.\n\t// A JSON ID list uses one binding even when callers exceed SQLite's bind limit.\n\tconst conditions =\n\t\tmemoryIds === undefined ? [] : [\"memory_id IN (SELECT value FROM json_each(?))\"];\n\tconst params: Array<string> = memoryIds === undefined ? [] : [JSON.stringify(memoryIds)];\n\tif (model !== undefined) {\n\t\tconditions.push(\"model = ?\");\n\t\tparams.push(model);\n\t}\n\tconst where = conditions.length === 0 ? \"\" : `WHERE ${conditions.join(\" AND \")}`;\n\tconst select = db\n\t\t.prepare(\n\t\t\t`SELECT rowid, memory_id, model, content_hash FROM memory_vectors\n\t\t ${where} /* ${marker} */`,\n\t\t)\n\t\t.safeIntegers();\n\tyield* select.iterate(...params) as Iterable<VectorMetadataRow>;\n}\n\n/**\n * Stream rowid, memory_id, model, and content_hash for vector rows matching\n * the filter, as bigint IDs. Uses the indexed table when the layout keeps it\n * complete and vec0 otherwise. `marker` names the caller in the SQL comment.\n */\nexport function readVectorMetadataRows(\n\tdb: Database,\n\tfilter: VectorMetadataFilter,\n\tmarker: string,\n): Iterable<VectorMetadataRow> {\n\tif (filter.memoryIds?.length === 0) return [];\n\tif (hasIndexedVectorMetadata(db)) return readIndexedRows(db, filter, marker);\n\treturn readVec0Rows(db, filter, marker);\n}\n","import SqliteDatabase from \"better-sqlite3\";\nimport type { Database } from \"./db.js\";\nimport { readVectorMetadataRows, type VectorMetadataFilter } from \"./vector-metadata-rows.js\";\n\ntype VectorMetadataSnapshotOptions = VectorMetadataFilter;\n\nfunction copyVectorMetadata(\n\tdb: Database,\n\tmetadata: Database,\n\toptions: VectorMetadataSnapshotOptions,\n): void {\n\tif (options.memoryIds?.length === 0) return;\n\tconst insert = metadata.prepare(\n\t\t\"INSERT INTO vector_metadata(rowid, memory_id, model, content_hash) VALUES (?, ?, ?, ?)\",\n\t);\n\tmetadata.transaction(() => {\n\t\tfor (const row of readVectorMetadataRows(db, options, \"vector-metadata-snapshot\")) {\n\t\t\tif (\n\t\t\t\t!Number.isSafeInteger(Number(row.rowid)) ||\n\t\t\t\t(row.memory_id !== null && !Number.isSafeInteger(Number(row.memory_id)))\n\t\t\t) {\n\t\t\t\tthrow new RangeError(\"Vector metadata IDs exceed the exact numeric range\");\n\t\t\t}\n\t\t\tinsert.run(row.rowid, row.memory_id, row.model, row.content_hash);\n\t\t}\n\t})();\n}\n\n/**\n * Stream vector metadata once into an indexed, disposable SQLite database.\n * v1 layouts read the indexed mirror table; legacy layouts scan vec0.\n *\n * A separate temporary database avoids changing the source connection's\n * temp_store (which would destroy callers' TEMP tables). Its pager can spill\n * to disk, unlike a TEMP table on our temp_store=MEMORY source connection.\n * Every invocation owns its connection, including nested operations.\n *\n * Callers own its lifetime and must close it in finally. Retaining an idle\n * catalog across cleanup yields holds no source transaction or statement open.\n * A write recheck must build it inside the source's immediate transaction.\n */\nexport function createVectorMetadataSnapshot(\n\tdb: Database,\n\toptions: VectorMetadataSnapshotOptions = {},\n): Database {\n\tconst metadata = new SqliteDatabase(\"\");\n\ttry {\n\t\tmetadata.pragma(\"temp_store = FILE\");\n\t\tmetadata.pragma(\"cache_size = -1024\");\n\t\tmetadata.exec(`CREATE TABLE vector_metadata (\n\t\t\trowid INTEGER PRIMARY KEY,\n\t\t\tmemory_id INTEGER,\n\t\t\tmodel TEXT,\n\t\t\tcontent_hash TEXT\n\t\t)`);\n\t\tcopyVectorMetadata(db, metadata, options);\n\t\tmetadata.exec(\n\t\t\t\"CREATE INDEX vector_metadata_memory_model_hash ON vector_metadata(memory_id, model, content_hash)\",\n\t\t);\n\t\treturn metadata;\n\t} catch (error) {\n\t\tmetadata.close();\n\t\tthrow error;\n\t}\n}\n\nexport function withVectorMetadataSnapshot<T>(\n\tdb: Database,\n\tvisit: (metadata: Database) => T,\n\toptions: VectorMetadataSnapshotOptions = {},\n): T {\n\tconst metadata = createVectorMetadataSnapshot(db, options);\n\ttry {\n\t\treturn visit(metadata);\n\t} finally {\n\t\tmetadata.close();\n\t}\n}\n","/** Supported vector mutations. Callers own the synchronous writer transaction. */\nimport { type Database, tableExists } from \"./db.js\";\nimport { type VectorRowInput, vectorBytes } from \"./semantic/semantic-ranking.js\";\nimport { startAudit } from \"./semantic/validated-vector-index-audit.js\";\nimport {\n\tinsertRow,\n\tremoveRow,\n\trequireModel,\n\trequireVectorMetadata,\n} from \"./semantic/validated-vector-index-mutations.js\";\nimport {\n\tfinishMutation,\n\ttype IndexedRow,\n\tinvalidateValidatedIndex,\n\treadState,\n} from \"./semantic/validated-vector-index-state.js\";\nimport {\n\ttype IndexStatement,\n\tprepareCountStatements,\n\ttype RemoveStatements,\n} from \"./semantic/validated-vector-index-statements.js\";\nimport { resolveVectorLayout, type VectorLayout } from \"./vector-layout.js\";\nimport { readVectorMetadataRows } from \"./vector-metadata-rows.js\";\n\nexport interface VectorWriteBatch {\n\tinsert?: { model: string; rows: readonly VectorRowInput[]; expectedCount: number };\n\tdeleteRowIds?: readonly number[];\n\tdeleteMemoryIds?: readonly number[];\n\tsignal?: AbortSignal;\n}\n\ninterface WriteStatements {\n\tdb: Database;\n\tlayout?: VectorLayout;\n\tdeleteVector?: IndexStatement;\n\tselectVector?: IndexStatement;\n\tinsertVector?: IndexStatement;\n\tselectMemoryRows?: IndexStatement;\n\tmetadata?: ReturnType<typeof prepareMetadata>;\n}\n\n/** Statement lifetime is one maintenance operation, not one row or connection.\n * Preparing the operation is harmless outside a transaction; every batch requires one.\n */\nexport function prepareVectorWrites(db: Database) {\n\tconst statements: WriteStatements = { db };\n\treturn (batch: VectorWriteBatch) => writeVectorBatch(statements, batch);\n}\n\n/** Explicit model transition: rotate the generation and census old rows as pending.\n * The lifecycle driver audits those rows later; declaring a model never validates them.\n */\nexport function ensureVectorWriteModel(db: Database, model: string): boolean {\n\tif (!db.inTransaction) throw new Error(\"vector_write_transaction_required\");\n\trequireModel(model);\n\tif (!tableExists(db, \"validated_vector_state\")) return false;\n\tconst state = readState(db);\n\tconst knownModels: unknown = JSON.parse(state.known_models);\n\tif (!Array.isArray(knownModels) || !knownModels.every((entry) => typeof entry === \"string\"))\n\t\tthrow new Error(\"invalid_generation_models\");\n\tif (state.audit_started && knownModels.includes(model)) return false;\n\tstartAudit(db, { knownModels: [...new Set([...knownModels, model])] });\n\treturn true;\n}\n\nfunction writeVectorBatch(statements: WriteStatements, batch: VectorWriteBatch) {\n\tconst { db } = statements;\n\tif (!db.inTransaction) throw new Error(\"vector_write_transaction_required\");\n\tconst prepared = prepareInsertBatch(batch.insert);\n\tconst empty = { deleted: 0, deletedRowIds: [] as number[], inserted: 0 };\n\tif (!prepared.length && !batch.deleteRowIds?.length && !batch.deleteMemoryIds?.length)\n\t\treturn empty;\n\tconst layout = resolveVectorLayout(db);\n\tif (layout.kind === \"absent\") {\n\t\tif (prepared.length) throw new Error(\"vector_table_required\");\n\t\treturn empty;\n\t}\n\tresetLayoutStatements(statements, layout);\n\tconst state = prepareCatalogMutation(statements, batch, prepared);\n\tconst rowIds = collectDeleteRowIds(statements, batch);\n\tconst result = deleteRows(statements, rowIds, {\n\t\trebuild: state !== null && !state.audit_started,\n\t\tsignal: batch.signal,\n\t});\n\tinsertRows(statements, prepared, { indexed: state !== null && !result.rebuild });\n\tif (layout.kind === \"legacy\") finishLegacyMutation(db, state, result, prepared.length);\n\treturn {\n\t\tdeleted: result.deletedRowIds.length,\n\t\tdeletedRowIds: result.deletedRowIds,\n\t\tinserted: prepared.length,\n\t};\n}\n\nfunction finishLegacyMutation(\n\tdb: Database,\n\tstate: ReturnType<typeof readState> | null,\n\tresult: ReturnType<typeof deleteRows>,\n\tinserted: number,\n): void {\n\tif (!state) return;\n\tif (!result.deletedRowIds.length && !inserted && !(state.audit_started && result.rebuild)) return;\n\tif (result.rebuild) invalidateValidatedIndex(db);\n\telse finishMutation(db);\n}\n\nfunction resetLayoutStatements(statements: WriteStatements, layout: VectorLayout): void {\n\tif (statements.layout?.kind === layout.kind) return;\n\tstatements.layout = layout;\n\tstatements.deleteVector = undefined;\n\tstatements.selectVector = undefined;\n\tstatements.insertVector = undefined;\n\tstatements.selectMemoryRows = undefined;\n\tstatements.metadata = undefined;\n}\n\nfunction prepareCatalogMutation(\n\tstatements: WriteStatements,\n\tbatch: VectorWriteBatch,\n\trows: ReturnType<typeof prepareInsertBatch>,\n) {\n\tconst { db } = statements;\n\tif (!tableExists(db, \"validated_vector_state\")) {\n\t\tif (statements.layout?.kind === \"v1\") throw new Error(\"validated_index_not_initialized\");\n\t\treturn null;\n\t}\n\tconst state = readState(db);\n\tif (batch.insert) requireDeclaredModel(state.known_models, batch.insert.model);\n\tif (statements.layout?.kind === \"v1\" && rows.length && !state.audit_started)\n\t\tthrow new Error(\"start_audit_census_required\");\n\tstatements.metadata ??= prepareMetadata(db, prepareDeleteVector(statements), statements.layout);\n\tfor (const row of rows) {\n\t\tif (!statements.metadata.sourceExists.get(row.memoryId))\n\t\t\tthrow new Error(\"vector_source_memory_missing\");\n\t}\n\treturn state;\n}\n\nfunction collectDeleteRowIds(statements: WriteStatements, batch: VectorWriteBatch): Set<number> {\n\tconst ids = new Set(batch.deleteRowIds ?? []);\n\tif (!batch.deleteMemoryIds?.length) return ids;\n\tif (statements.layout?.kind === \"v1\") {\n\t\t// v1 keeps validated_vector_rows identical to vec0 (see hasIndexedVectorMetadata),\n\t\t// so (model, memory_id) index seeks replace a vec0 metadata scan. The\n\t\t// reader falls back to vec0 if the row counts disagree.\n\t\tconst rows = readVectorMetadataRows(\n\t\t\tstatements.db,\n\t\t\t{ memoryIds: batch.deleteMemoryIds },\n\t\t\t\"vector-delete-memory-rows\",\n\t\t);\n\t\tfor (const row of rows) ids.add(Number(row.rowid));\n\t\treturn ids;\n\t}\n\tstatements.selectMemoryRows ??= statements.db.prepare(`SELECT rowid FROM memory_vectors\n\t\tWHERE memory_id IN (SELECT value FROM json_each(?))`);\n\tfor (const row of statements.selectMemoryRows.all(JSON.stringify(batch.deleteMemoryIds)) as {\n\t\trowid: number;\n\t}[])\n\t\tids.add(row.rowid);\n\treturn ids;\n}\n\nfunction deleteRows(\n\tstatements: WriteStatements,\n\trowIds: Set<number>,\n\toptions: { rebuild: boolean; signal?: AbortSignal },\n) {\n\tlet rebuild = options.rebuild;\n\tconst deletedRowIds: number[] = [];\n\tfor (const rowid of rowIds) {\n\t\tif (options.signal?.aborted) break;\n\t\tconst result = deleteRow(statements, rowid, { rebuild });\n\t\trebuild = result.rebuild;\n\t\tif (result.deleted) deletedRowIds.push(rowid);\n\t}\n\treturn { rebuild, deletedRowIds };\n}\n\nfunction deleteRow(statements: WriteStatements, rowid: number, options: { rebuild: boolean }) {\n\tif (!Number.isSafeInteger(rowid)) throw new RangeError(\"unsafe_vector_rowid\");\n\tconst deleteVector = prepareDeleteVector(statements);\n\tif (statements.layout?.kind === \"v1\") {\n\t\tstatements.selectVector ??= statements.db.prepare(\n\t\t\t\"SELECT rowid FROM memory_vectors WHERE rowid = ?\",\n\t\t);\n\t\tconst exists = Boolean(statements.selectVector.get(BigInt(rowid)));\n\t\tif (exists) deleteVector.run(BigInt(rowid));\n\t\treturn { deleted: exists, rebuild: false };\n\t}\n\tconst metadata = statements.metadata;\n\tif (!metadata) return { deleted: deleteVector.run(BigInt(rowid)).changes > 0, rebuild: false };\n\tconst row = metadata.selectRow.get(rowid) as IndexedRow | undefined;\n\tconst physical = metadata.selectPhysical.get(BigInt(rowid)) as IndexedRow | undefined;\n\tconst rebuild = options.rebuild || !sameIndexedMetadata(row, physical);\n\tif (row && physical && !rebuild) {\n\t\tremoveRow(metadata.remove, row);\n\t\treturn { deleted: true, rebuild };\n\t}\n\treturn { deleted: deleteVector.run(BigInt(rowid)).changes > 0, rebuild };\n}\n\nfunction insertRows(\n\tstatements: WriteStatements,\n\trows: ReturnType<typeof prepareInsertBatch>,\n\toptions: { indexed: boolean },\n) {\n\tfor (const row of rows) {\n\t\tif (options.indexed && statements.metadata) {\n\t\t\tinsertRow(statements.metadata.insert, row, row.model, row.bytes);\n\t\t\tcontinue;\n\t\t}\n\t\tstatements.insertVector ??= statements.db.prepare(`INSERT INTO memory_vectors\n\t\t\t(embedding,memory_id,chunk_index,content_hash,model) VALUES(?,?,?,?,?)`);\n\t\tstatements.insertVector.run(\n\t\t\trow.bytes,\n\t\t\tBigInt(row.memoryId),\n\t\t\tBigInt(row.chunkIndex),\n\t\t\trow.contentHash,\n\t\t\trow.model,\n\t\t);\n\t}\n\tif (statements.layout?.kind === \"v1\" && rows.length) finishMutation(statements.db);\n}\n\nfunction prepareDeleteVector(statements: WriteStatements): IndexStatement {\n\tstatements.deleteVector ??= statements.db.prepare(\"DELETE FROM memory_vectors WHERE rowid = ?\");\n\treturn statements.deleteVector;\n}\n\nfunction sameIndexedMetadata(\n\tindexed: IndexedRow | undefined,\n\tphysical: IndexedRow | undefined,\n): boolean {\n\tif (!indexed || !physical) return indexed === physical;\n\treturn (\n\t\tindexed.memory_id === physical.memory_id &&\n\t\tindexed.model === physical.model &&\n\t\tindexed.chunk_index === physical.chunk_index &&\n\t\tindexed.content_hash === physical.content_hash\n\t);\n}\n\nfunction prepareInsertBatch(batch: VectorWriteBatch[\"insert\"]) {\n\tif (!batch) return [];\n\trequireModel(batch.model);\n\tif (!Number.isSafeInteger(batch.expectedCount) || batch.expectedCount !== batch.rows.length)\n\t\tthrow new TypeError(\"vector_count_mismatch\");\n\treturn batch.rows.map((row) => {\n\t\trequireVectorMetadata(row);\n\t\treturn { ...row, model: batch.model, bytes: vectorBytes(row.vector) };\n\t});\n}\n\nfunction requireDeclaredModel(knownModels: string, model: string): void {\n\tconst models: unknown = JSON.parse(knownModels);\n\tif (!Array.isArray(models) || !models.includes(model))\n\t\tthrow new TypeError(\"vector_model_not_declared_in_generation\");\n}\n\nfunction prepareMetadata(\n\tdb: Database,\n\tdeleteVector: IndexStatement,\n\tlayout: WriteStatements[\"layout\"],\n) {\n\tconst counts = prepareCountStatements(db);\n\tconst remove: RemoveStatements = {\n\t\tcounts,\n\t\tdeleteVector,\n\t\tdeleteIndexedRow: db.prepare(\"DELETE FROM validated_vector_rows WHERE rowid=?\"),\n\t\tdecrementAuditCounts:\n\t\t\tdb.prepare(`UPDATE validated_vector_state SET pending_count=pending_count-?,\n\t\t\tinvalid_count=invalid_count-? WHERE id=1`),\n\t};\n\treturn {\n\t\tremove,\n\t\tinsert: {\n\t\t\tcounts,\n\t\t\tinsertVector: preparePhysicalInsert(db, layout),\n\t\t\tinsertIndexedRow: db.prepare(`INSERT INTO validated_vector_rows\n\t\t\t\t(rowid,memory_id,model,chunk_index,content_hash,audit_state) VALUES(?,?,?,?,?,'valid')`),\n\t\t},\n\t\tselectRow: db.prepare(\"SELECT * FROM validated_vector_rows WHERE rowid=?\"),\n\t\tselectPhysical: db.prepare(\n\t\t\t\"SELECT memory_id,model,chunk_index,content_hash FROM memory_vectors WHERE rowid=?\",\n\t\t),\n\t\tsourceExists: db.prepare(\"SELECT 1 FROM memory_items WHERE id=?\"),\n\t};\n}\n\nfunction preparePhysicalInsert(db: Database, layout: WriteStatements[\"layout\"]): IndexStatement {\n\tif (layout?.kind === \"v1\")\n\t\treturn db.prepare(`INSERT INTO memory_vectors_v1\n\t\t(embedding,memory_id,chunk_index,content_hash,model) VALUES(?,?,?,?,?)`);\n\treturn db.prepare(`INSERT INTO memory_vectors\n\t\t(embedding,memory_id,chunk_index,content_hash,model) VALUES(?,?,?,?,?)`);\n}\n","/**\n * Vector store operations for semantic search.\n *\n * Ports codemem/store/vectors.py — backfill and on-insert vector writes\n * against the sqlite-vec `memory_vectors` virtual table.\n *\n * All functions accept a raw better-sqlite3 Database so they work outside\n * the MemoryStore class. Embedding is async; callers await then write\n * synchronously (matches the runtime-topology decision: main thread owns DB).\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport type { Statement } from \"better-sqlite3\";\nimport type { Database } from \"./db.js\";\nimport { isEmbeddingDisabled } from \"./db.js\";\nimport {\n\tassertEmbeddingClientIdentity,\n\tchunkText,\n\tDEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL,\n\ttype EmbeddingClient,\n\tembedTexts,\n\tgetEmbeddingClient,\n\tgetEmbeddingRuntimeStatus,\n\thashText,\n\tresolveEmbeddingClientVectorIdentityLabel,\n\tresolveEmbeddingModel,\n\tserializeFloat32,\n\ttryResolveEmbeddingRevision,\n\ttryResolveEmbeddingVectorIdentityLabel,\n} from \"./embeddings.js\";\nimport type { OwnershipFilterContext } from \"./filters.js\";\nimport {\n\tcompleteMaintenanceJob,\n\tgetMaintenanceJob,\n\tstartMaintenanceJob,\n} from \"./maintenance-jobs.js\";\nimport { projectColumnClause } from \"./project.js\";\nimport { snapshot } from \"./semantic/validated-vector-index-state.js\";\nimport {\n\tbuildAuthorizedSemanticMemoryIdsQuery,\n\tpendingVectorFreshness,\n\tresolveSemanticSearchModelFromCatalog,\n\tsemanticResult,\n} from \"./semantic-query.js\";\nimport type { ReplicationVectorWork } from \"./sync-replication.js\";\nimport type { MemoryFilters } from \"./types.js\";\nimport { resolveVectorLayout, vectorStoreExists } from \"./vector-layout.js\";\nimport {\n\tcreateVectorMetadataSnapshot,\n\twithVectorMetadataSnapshot,\n} from \"./vector-metadata-snapshot.js\";\nimport { ensureVectorWriteModel, prepareVectorWrites } from \"./vector-writes.js\";\n\nconst VECTOR_MODEL_MIGRATION_JOB = \"vector_model_migration\";\n// Keep resolved-client identity separate from migration progress: direct or\n// partial backfills must not claim that a model cutover completed.\nconst VECTOR_MODEL_IDENTITY_JOB = \"vector_model_identity\";\nconst LEGACY_DEFAULT_EMBEDDING_MODEL = \"Xenova/bge-small-en-v1.5\";\nconst BACKFILL_MEMORY_PAGE_SIZE = 50;\nconst BACKFILL_INFERENCE_BATCH_SIZE = 32;\nconst BACKFILL_CANDIDATE_TABLE_PREFIX = \"codemem_backfill_vector_candidates\";\n\ntype MemoryTextRow = {\n\tid: number;\n\ttitle: string | null;\n\tbody_text: string | null;\n\tcreated_at?: string;\n};\ntype PendingChunk = { text: string; chunkIndex: number; contentHash: string };\ntype PendingMemory = {\n\tmemoryId: number;\n\tsource: VectorSourceRow;\n\tchunks: PendingChunk[];\n\tvectors: Float32Array[];\n};\n\ntype VectorSourceRow = MemoryTextRow & {\n\timport_key: string | null;\n\tsession_id: number;\n\tcreated_at: string;\n\torigin_device_id: string | null;\n\trev: number | null;\n\tupdated_at: string;\n\tactive: number | null;\n\tdeleted_at: string | null;\n};\n\ntype BackfillMemoryRow = VectorSourceRow & { snapshot_seq: number };\n\nconst VECTOR_SOURCE_COLUMNS = `id, title, body_text, import_key, session_id, created_at,\n\torigin_device_id, rev, updated_at, active, deleted_at`;\nconst QUALIFIED_VECTOR_SOURCE_COLUMNS = VECTOR_SOURCE_COLUMNS.split(\",\")\n\t.map((column) => `memory_items.${column.trim()}`)\n\t.join(\", \");\n\nfunction readVectorSource(db: Database, memoryId: number): VectorSourceRow | undefined {\n\tif (!Number.isInteger(memoryId)) return undefined;\n\treturn db\n\t\t.prepare(`SELECT ${VECTOR_SOURCE_COLUMNS} FROM memory_items WHERE id = ?`)\n\t\t.get(memoryId) as VectorSourceRow | undefined;\n}\n\nfunction currentVectorSourceHashes(\n\tsaved: VectorSourceRow,\n\tcurrent: VectorSourceRow | undefined,\n): string[] {\n\t// Text equality alone cannot distinguish reuse of a deleted memory's numeric ID.\n\tif (\n\t\t!current ||\n\t\tcurrent.import_key !== saved.import_key ||\n\t\tcurrent.session_id !== saved.session_id ||\n\t\tcurrent.created_at !== saved.created_at ||\n\t\tcurrent.origin_device_id !== saved.origin_device_id ||\n\t\tcurrent.rev !== saved.rev ||\n\t\tcurrent.updated_at !== saved.updated_at ||\n\t\tcurrent.active !== saved.active ||\n\t\tcurrent.deleted_at !== saved.deleted_at\n\t) {\n\t\treturn [];\n\t}\n\t// Redaction can change text without advancing the revision or update timestamp.\n\treturn chunkHashes(memoryText(current.title, current.body_text));\n}\n\nfunction pendingBackfillMemory(source: VectorSourceRow, chunks: PendingChunk[]): PendingMemory {\n\treturn { memoryId: source.id, source, chunks, vectors: [] };\n}\n\nfunction assertVectorMemoryId(memoryId: number): void {\n\tif (!Number.isFinite(memoryId))\n\t\tthrow new TypeError(`Expected finite integer, received ${String(memoryId)}`);\n\tif (!Number.isInteger(memoryId))\n\t\tthrow new TypeError(`Expected integer, received ${String(memoryId)}`);\n}\n\nfunction createBackfillCandidateSnapshot(\n\tdb: Database,\n\tjoinClause: string,\n\twhere: string,\n\tparams: unknown[],\n\trowLimit: number,\n): string {\n\t// randomUUID is hex plus hyphens; stripping hyphens keeps this interpolated identifier safe.\n\tconst tableName = `${BACKFILL_CANDIDATE_TABLE_PREFIX}_${randomUUID().replaceAll(\"-\", \"\")}`;\n\tdb.exec(`\n\t\tCREATE TEMP TABLE ${tableName} (\n\t\t\tseq INTEGER PRIMARY KEY,\n\t\t\tmemory_id INTEGER NOT NULL\n\t\t)\n\t`);\n\tconst hasFiniteLimit = Number.isFinite(rowLimit);\n\tconst limitClause = hasFiniteLimit ? \"LIMIT ?\" : \"\";\n\tconst snapshotParams = hasFiniteLimit ? [...params, rowLimit] : params;\n\ttry {\n\t\tdb.prepare(\n\t\t\t`INSERT INTO ${tableName}(memory_id)\n\t\t\t SELECT memory_items.id\n\t\t\t FROM memory_items ${joinClause}\n\t\t\t WHERE ${where}\n\t\t\t ORDER BY memory_items.created_at ASC, memory_items.id ASC\n\t\t\t ${limitClause}`,\n\t\t).run(...snapshotParams);\n\t} catch (error) {\n\t\tdb.exec(`DROP TABLE IF EXISTS ${tableName}`);\n\t\tthrow error;\n\t}\n\treturn tableName;\n}\n\nfunction deleteBackfillCandidateSnapshot(db: Database, tableName: string): void {\n\tdb.exec(`DROP TABLE IF EXISTS ${tableName}`);\n}\n\n// Deliberately omits `enforceScopeVisibility` so semantic callers can never\n// disable the local read boundary — scopeVisibleFilterContext() always forces\n// it on below. Field list otherwise mirrors OwnershipFilterContext.\nexport type SemanticSearchScopeContext = Omit<OwnershipFilterContext, \"enforceScopeVisibility\">;\n\nfunction clampSemanticLimit(limit: number): number {\n\tif (limit === Number.POSITIVE_INFINITY) return 200;\n\tif (!Number.isFinite(limit)) return 1;\n\treturn Math.min(Math.max(1, Math.trunc(limit)), 200);\n}\n\nfunction listVectorModels(db: Database): Array<string | null> {\n\tif (!vectorStoreExists(db)) {\n\t\treturn [];\n\t}\n\ttry {\n\t\tconst rows = db.prepare(\"SELECT DISTINCT model FROM memory_vectors\").all() as Array<{\n\t\t\tmodel: string | null;\n\t\t}>;\n\t\t// Keep NULL and unknown labels: they must still prevent an unverified\n\t\t// mixed corpus from looking like an exclusively current-model corpus.\n\t\treturn rows.map((row) => row.model);\n\t} catch {\n\t\treturn [];\n\t}\n}\n\nfunction hasVectorRows(db: Database): boolean {\n\tif (!vectorStoreExists(db)) return false;\n\ttry {\n\t\treturn db.prepare(\"SELECT 1 FROM memory_vectors LIMIT 1\").get() != null;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction tryResolveConfiguredVectorIdentityLabel(db: Database): string | null {\n\tfor (const jobKind of [VECTOR_MODEL_IDENTITY_JOB, VECTOR_MODEL_MIGRATION_JOB]) {\n\t\tconst metadata = (getMaintenanceJob(db, jobKind)?.metadata ?? {}) as Record<string, unknown>;\n\t\tconst targetModel = tryResolveEmbeddingVectorIdentityLabel({\n\t\t\ttargetModel: metadata.target_model,\n\t\t\trequestedModel: metadata.requested_model,\n\t\t\trequestedRevision: metadata.requested_revision,\n\t\t});\n\t\tif (targetModel) return targetModel;\n\t}\n\treturn null;\n}\n\nfunction persistVectorIdentity(db: Database, client: EmbeddingClient, targetModel: string): void {\n\tif (!client.identity) {\n\t\tthrow new TypeError(\"Embedding runtime identity is required to persist vector metadata\");\n\t}\n\tconst metadata = {\n\t\ttarget_model: targetModel,\n\t\trequested_model: client.model,\n\t\trequested_revision: client.identity.requestedRevision ?? client.identity.revision,\n\t};\n\tconst existing = getMaintenanceJob(db, VECTOR_MODEL_IDENTITY_JOB);\n\tif (\n\t\texisting?.status === \"completed\" &&\n\t\texisting.metadata?.target_model === metadata.target_model &&\n\t\texisting.metadata.requested_model === metadata.requested_model &&\n\t\texisting.metadata.requested_revision === metadata.requested_revision\n\t) {\n\t\treturn;\n\t}\n\tstartMaintenanceJob(db, {\n\t\tkind: VECTOR_MODEL_IDENTITY_JOB,\n\t\ttitle: \"Embedding vector identity\",\n\t\tmessage: \"Recorded the canonical embedding identity used by vector writes\",\n\t\tprogressTotal: 1,\n\t\tmetadata,\n\t});\n\tcompleteMaintenanceJob(db, VECTOR_MODEL_IDENTITY_JOB, {\n\t\tprogressCurrent: 1,\n\t\tprogressTotal: 1,\n\t\tmetadata,\n\t});\n}\n\nexport function resolveSemanticSearchModel(db: Database, currentModel?: string): string | null {\n\tif (currentModel === undefined) {\n\t\tcurrentModel = tryResolveConfiguredVectorIdentityLabel(db) ?? undefined;\n\t\tif (currentModel === undefined) return null;\n\t}\n\treturn resolveSemanticSearchModelFromCatalog(\n\t\tcurrentModel,\n\t\tgetMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB),\n\t\tlistVectorModels(db),\n\t);\n}\n\n/**\n * Resolve every vector-model label that should be read together for the current\n * identity. During the compatible legacy-default rebuild this returns both the\n * legacy label and the revision-aware target so consumers see memories written\n * under either identity. Returns a single-element list otherwise, or `[]` when\n * no semantic corpus is currently serviceable.\n */\nexport function resolveSemanticSearchModels(db: Database, resolvedModel?: string): string[] {\n\tconst currentModel = resolvedModel ?? tryResolveConfiguredVectorIdentityLabel(db);\n\tif (currentModel == null) return [];\n\t// Primary selection and compatible expansion share this call's catalog,\n\t// never a cross-search snapshot that could survive a model cutover.\n\tconst job = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\tconst models = listVectorModels(db);\n\tconst primaryModel = resolveSemanticSearchModelFromCatalog(currentModel, job, models);\n\treturn expandSemanticSearchModels(db, primaryModel, currentModel, models);\n}\n\nfunction expandSemanticSearchModels(\n\tdb: Database,\n\tprimaryModel: string | null,\n\tcurrentModel: string,\n\tmodels?: readonly (string | null)[],\n): string[] {\n\tif (!primaryModel) return [];\n\tif (\n\t\tprimaryModel === LEGACY_DEFAULT_EMBEDDING_MODEL &&\n\t\tcurrentModel === DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL &&\n\t\t(models ?? listVectorModels(db)).includes(currentModel)\n\t) {\n\t\treturn [primaryModel, currentModel];\n\t}\n\treturn [primaryModel];\n}\n\nfunction chunkHashes(text: string): string[] {\n\treturn chunkText(text).map((chunk) => hashText(chunk));\n}\n\nfunction memoryText(title: string | null, bodyText: string | null): string {\n\treturn `${title ?? \"\"}\\n${bodyText ?? \"\"}`.trim();\n}\n\nexport function memoryHasCompleteVectorCoverage(\n\tdb: Database,\n\tmemory: MemoryTextRow,\n\tmodel: string,\n): boolean {\n\tconst expectedHashes = chunkHashes(memoryText(memory.title, memory.body_text));\n\tif (expectedHashes.length === 0) return true;\n\tconst existingRows = db\n\t\t.prepare(\"SELECT content_hash FROM memory_vectors WHERE memory_id = ? AND model = ?\")\n\t\t.all(memory.id, model) as Array<{ content_hash: string | null }>;\n\treturn expectedHashesExist(expectedHashes, existingRows);\n}\n\nexport function findMemoryIdsWithCompleteActiveVectorCoverage(\n\tdb: Database,\n\tmemoryIds: number[],\n\tmodel: string,\n): number[] {\n\tconst ids = uniqueMemoryIds(memoryIds);\n\tif (ids.length === 0) return [];\n\tconst placeholders = ids.map(() => \"?\").join(\", \");\n\tconst memories = db\n\t\t.prepare(\n\t\t\t`SELECT id, title, body_text FROM memory_items\n\t\t\t WHERE active = 1 AND id IN (${placeholders})`,\n\t\t)\n\t\t.all(...ids) as MemoryTextRow[];\n\tif (memories.length === 0) return ids;\n\t// The coverage query reads only these memories' rows for this model, so the\n\t// snapshot copies only those instead of the whole vector catalog.\n\tconst incompleteIds = withVectorMetadataSnapshot(\n\t\tdb,\n\t\t(metadata) => {\n\t\t\tconst selectHash = prepareSnapshotHashQuery(metadata);\n\t\t\treturn new Set(\n\t\t\t\tmemories\n\t\t\t\t\t.filter((memory) => !memoryHasSnapshotCoverage(selectHash, memory, model))\n\t\t\t\t\t.map((memory) => memory.id),\n\t\t\t);\n\t\t},\n\t\t{ memoryIds: memories.map((memory) => memory.id), model },\n\t);\n\t// Missing or inactive memories have no active coverage work and must not\n\t// remain queued forever. Their deletion work is tracked separately.\n\treturn ids.filter((memoryId) => !incompleteIds.has(memoryId));\n}\n\nfunction expectedHashesExist(\n\texpectedHashes: string[],\n\texistingRows: Array<{ content_hash: string | null }>,\n): boolean {\n\tconst existingHashes = new Set(\n\t\texistingRows.map((row) => row.content_hash).filter((hash): hash is string => hash != null),\n\t);\n\treturn expectedHashSetContains(expectedHashes, existingHashes);\n}\n\nfunction expectedHashSetContains(expectedHashes: string[], existingHashes: Set<string>): boolean {\n\treturn expectedHashes.every((hash) => existingHashes.has(hash));\n}\n\ntype SnapshotQuery = Statement<unknown[]>;\n\nfunction prepareSnapshotHashQuery(metadata: Database): SnapshotQuery {\n\treturn metadata.prepare(\n\t\t`SELECT 1 FROM vector_metadata\n\t\t WHERE memory_id = ? AND model = ? AND content_hash = ? LIMIT 1`,\n\t);\n}\n\nfunction memoryHasSnapshotCoverage(\n\tselectHash: SnapshotQuery,\n\tmemory: MemoryTextRow,\n\tmodel: string,\n): boolean {\n\tconst expectedHashes = chunkHashes(memoryText(memory.title, memory.body_text));\n\treturn snapshotHasExpectedHashes(selectHash, memory.id, model, expectedHashes);\n}\n\nfunction snapshotHasExpectedHashes(\n\tselectHash: SnapshotQuery,\n\tmemoryId: number,\n\tmodel: string,\n\texpectedHashes: string[],\n): boolean {\n\treturn expectedHashes.every((hash) => selectHash.get(memoryId, model, hash) != null);\n}\n\nexport function countIncompleteActiveMemoryVectorCoverage(\n\tdb: Database,\n\tmodel: string,\n\toptions: { metadata?: Database } = {},\n): number {\n\tlet incomplete = 0;\n\tvisitIncompleteActiveMemoryIds(db, model, () => incomplete++, options);\n\treturn incomplete;\n}\n\n/** Internal repair candidates, using the same current-hash coverage check as cutover. */\nexport function findIncompleteActiveMemoryIds(\n\tdb: Database,\n\tmodel: string,\n\toptions: { metadata?: Database } = {},\n): number[] {\n\tconst ids: number[] = [];\n\tvisitIncompleteActiveMemoryIds(db, model, (id) => ids.push(id), options);\n\treturn ids;\n}\n\nfunction visitIncompleteActiveMemoryIds(\n\tdb: Database,\n\tmodel: string,\n\tvisit: (id: number) => void,\n\toptions: { metadata?: Database },\n): void {\n\tconst batchSize = 250;\n\tlet afterId = 0;\n\tlet metadata: Database | null = options.metadata ?? null;\n\tlet selectHash: SnapshotQuery | null = null;\n\t// Keep cursor pages on the rowid range; the active/created index requires a sort per page.\n\tconst selectMemories = db.prepare(\n\t\t`SELECT id, title, body_text FROM memory_items NOT INDEXED\n\t\t WHERE active = 1\n\t\t AND TRIM(COALESCE(title, '') || COALESCE(body_text, '')) != ''\n\t\t AND id > ?\n\t\t ORDER BY id ASC\n\t\t LIMIT ? /* vector-coverage-validation */`,\n\t);\n\ttry {\n\t\twhile (true) {\n\t\t\tconst memories = selectMemories.all(afterId, batchSize) as MemoryTextRow[];\n\t\t\tif (memories.length === 0) break;\n\t\t\tif (memories.some((memory) => !Number.isSafeInteger(memory.id))) {\n\t\t\t\tthrow new RangeError(\"Vector coverage requires safe integer memory IDs\");\n\t\t\t}\n\t\t\tmetadata ??= createVectorMetadataSnapshot(db);\n\t\t\tselectHash ??= prepareSnapshotHashQuery(metadata);\n\t\t\tfor (const memory of memories) {\n\t\t\t\tif (!memoryHasSnapshotCoverage(selectHash, memory, model)) visit(memory.id);\n\t\t\t}\n\t\t\tafterId = memories.at(-1)?.id ?? afterId;\n\t\t}\n\t} finally {\n\t\tif (!options.metadata) metadata?.close();\n\t}\n}\n\n/** Recheck a delete batch under its writer transaction, using one metadata scan. */\nexport function findMemoryIdsWithCurrentTargetCoverage(\n\tdb: Database,\n\tmemoryIds: readonly number[],\n\tmodel: string,\n): Set<number> {\n\t// Unlike queue IDs, persisted metadata may reference zero or negative IDs.\n\t// Reject inexact IDs rather than checking coverage for a rounded memory ID.\n\tconst ids = [...new Set(memoryIds.filter(Number.isSafeInteger))];\n\tconst covered = new Set(ids);\n\tif (ids.length === 0) return covered;\n\tconst memories = db\n\t\t.prepare(\n\t\t\t`SELECT id, title, body_text FROM memory_items\n\t\t WHERE active = 1 AND id IN (SELECT value FROM json_each(?))`,\n\t\t)\n\t\t.all(JSON.stringify(ids)) as MemoryTextRow[];\n\t// Missing/inactive memories need no target coverage before removing fallback rows.\n\tif (memories.length === 0) return covered;\n\treturn withVectorMetadataSnapshot(\n\t\tdb,\n\t\t(metadata) => {\n\t\t\tconst selectHash = prepareSnapshotHashQuery(metadata);\n\t\t\tfor (const memory of memories) {\n\t\t\t\tif (!memoryHasSnapshotCoverage(selectHash, memory, model)) covered.delete(memory.id);\n\t\t\t}\n\t\t\treturn covered;\n\t\t},\n\t\t{ memoryIds: memories.map((memory) => memory.id), model },\n\t);\n}\n\n/**\n * Prune from the same catalog later used for cutover coverage and exact equality.\n * Only our successful deletes alter it: an external deletion must fail equality.\n */\ntype CatalogVectorRow = {\n\trowid: number;\n\tmemory_id: number | null;\n\tmodel: string;\n\tcontent_hash: string | null;\n};\n\ntype CatalogPruneOptions = { signal?: AbortSignal; pruneScope?: \"all\" | \"active-only\" };\n\nfunction catalogPruneCandidates(\n\tdb: Database,\n\trows: CatalogVectorRow[],\n\toptions: CatalogPruneOptions,\n): CatalogVectorRow[] {\n\tconst expectedByMemory = new Map<number | null, Set<string> | null>();\n\tconst selectMemory = db.prepare(\"SELECT title, body_text, active FROM memory_items WHERE id = ?\");\n\treturn rows.filter((row) => {\n\t\tif (!expectedByMemory.has(row.memory_id)) {\n\t\t\tconst memory = selectMemory.get(row.memory_id) as\n\t\t\t\t| (MemoryTextRow & { active: number })\n\t\t\t\t| undefined;\n\t\t\tconst expected =\n\t\t\t\tmemory?.active === 1\n\t\t\t\t\t? new Set(chunkHashes(memoryText(memory.title, memory.body_text)))\n\t\t\t\t\t: null;\n\t\t\texpectedByMemory.set(row.memory_id, expected);\n\t\t}\n\t\tconst expected = expectedByMemory.get(row.memory_id);\n\t\tif (options.pruneScope === \"active-only\" && expected == null) return false;\n\t\treturn !expected?.has(row.content_hash ?? \"\");\n\t});\n}\n\nfunction deleteCatalogPruneCandidates(\n\tdb: Database,\n\trows: CatalogVectorRow[],\n\tmodel: string,\n\toptions: CatalogPruneOptions,\n): number[] {\n\tconst { signal } = options;\n\tconst selectCurrent = db.prepare(\n\t\t\"SELECT rowid, memory_id, model, content_hash FROM memory_vectors WHERE rowid = ?\",\n\t);\n\tconst write = prepareVectorWrites(db);\n\treturn db\n\t\t.transaction(() => {\n\t\t\t// Re-read bodies and metadata after acquiring the writer lock. A candidate\n\t\t\t// may now be a current chunk, or its memory may have lost target coverage.\n\t\t\tconst currentRows = rows.filter((row) => {\n\t\t\t\tif (signal?.aborted) return false;\n\t\t\t\tconst current = selectCurrent.get(row.rowid) as CatalogVectorRow | undefined;\n\t\t\t\treturn sameCatalogVectorRow(row, current);\n\t\t\t});\n\t\t\tif (signal?.aborted) return [];\n\t\t\tconst obsolete = catalogPruneCandidates(db, currentRows, options);\n\t\t\tconst coverage = findMemoryIdsWithCurrentTargetCoverage(\n\t\t\t\tdb,\n\t\t\t\tobsolete.flatMap((row) => (row.memory_id === null ? [] : [row.memory_id])),\n\t\t\t\tmodel,\n\t\t\t);\n\t\t\tconst ids: number[] = [];\n\t\t\tfor (const row of obsolete) {\n\t\t\t\tif (signal?.aborted) break;\n\t\t\t\tconst covered = row.memory_id === null || coverage.has(row.memory_id);\n\t\t\t\tif (covered) ids.push(row.rowid);\n\t\t\t}\n\t\t\treturn write({ deleteRowIds: ids, signal }).deletedRowIds;\n\t\t})\n\t\t.immediate();\n}\n\nfunction sameCatalogVectorRow(\n\tsaved: CatalogVectorRow,\n\tcurrent: CatalogVectorRow | undefined,\n): boolean {\n\treturn (\n\t\tcurrent !== undefined &&\n\t\tcurrent.memory_id === saved.memory_id &&\n\t\tcurrent.model === saved.model &&\n\t\tcurrent.content_hash === saved.content_hash\n\t);\n}\n\nexport function pruneObsoleteTargetVectorsFromCatalog(\n\tdb: Database,\n\tmodel: string,\n\tmetadata: Database,\n\toptions: CatalogPruneOptions = {},\n): number {\n\tconst selectPage = metadata.prepare(\n\t\t\"SELECT rowid, memory_id, model, content_hash FROM vector_metadata WHERE model = ? AND (? IS NULL OR rowid > ?) ORDER BY rowid LIMIT 250\",\n\t);\n\tconst forgetRow = metadata.prepare(\"DELETE FROM vector_metadata WHERE rowid = ?\");\n\tlet cursor: number | null = null;\n\tlet deleted = 0;\n\twhile (!options.signal?.aborted) {\n\t\tconst rows = selectPage.all(model, cursor, cursor) as CatalogVectorRow[];\n\t\tif (rows.length === 0) break;\n\t\tconst obsolete = catalogPruneCandidates(db, rows, options);\n\t\tconst deletedIds =\n\t\t\tobsolete.length === 0 ? [] : deleteCatalogPruneCandidates(db, obsolete, model, options);\n\t\tmetadata.transaction(() => {\n\t\t\tfor (const rowid of deletedIds) forgetRow.run(rowid);\n\t\t})();\n\t\tdeleted += deletedIds.length;\n\t\tcursor = rows.at(-1)?.rowid ?? cursor;\n\t}\n\treturn deleted;\n}\n\nfunction hasMemoryVectorRowidsShadowTable(db: Database): boolean {\n\tconst layout = resolveVectorLayout(db);\n\tif (layout.kind === \"absent\") return false;\n\tconst tables = db.prepare(\"PRAGMA table_list\").all() as Array<{ name: string }>;\n\treturn tables.some((table) => table.name === layout.rowidsName);\n}\n\nfunction vectorRowidsTable(db: Database): \"memory_vectors_rowids\" | \"memory_vectors_v1_rowids\" {\n\tconst layout = resolveVectorLayout(db);\n\tif (layout.kind === \"absent\") throw new Error(\"vector_table_required\");\n\treturn layout.rowidsName;\n}\n\ntype TargetVectorRow = {\n\trowid: number;\n\tmemory_id: number;\n\tcontent_hash: string | null;\n};\n\ntype TargetVectorCoverageState = {\n\texpectedHashes: string[];\n\texpected: Set<string>;\n\texisting: Set<string>;\n};\n\nfunction collectTargetVectorRows(\n\tdb: Database,\n\tmodel: string,\n\tbatchSize: number,\n\tsignal?: AbortSignal,\n): boolean {\n\tconst selectRowIds = db.prepare(\n\t\t`SELECT rowid FROM ${vectorRowidsTable(db)} WHERE rowid > ? ORDER BY rowid ASC LIMIT ? /* vector-target-prune-rowids */`,\n\t);\n\tconst selectMetadata = db.prepare(\n\t\t\"SELECT memory_id, content_hash, model FROM memory_vectors WHERE rowid = ?\",\n\t);\n\tconst insertScanRow = db.prepare(\n\t\t\"INSERT INTO temp.vector_prune_scan(rowid, memory_id, content_hash) VALUES (?, ?, ?) /* vector-target-prune-spill */\",\n\t);\n\tconst insertScanPage = db.transaction((rows: TargetVectorRow[]) => {\n\t\tfor (const row of rows) insertScanRow.run(row.rowid, row.memory_id, row.content_hash);\n\t});\n\tlet afterRowId = 0;\n\twhile (!signal?.aborted) {\n\t\tconst rowIds = selectRowIds.all(afterRowId, batchSize) as Array<{ rowid: number }>;\n\t\tif (signal?.aborted) return false;\n\t\tif (rowIds.length === 0) return true;\n\t\tconst targetRows: TargetVectorRow[] = [];\n\t\tfor (const { rowid } of rowIds) {\n\t\t\tif (signal?.aborted) return false;\n\t\t\tconst metadata = selectMetadata.get(rowid) as\n\t\t\t\t| { memory_id: number; content_hash: string | null; model: string }\n\t\t\t\t| undefined;\n\t\t\tif (!metadata || metadata.model !== model) continue;\n\t\t\ttargetRows.push({\n\t\t\t\trowid,\n\t\t\t\tmemory_id: metadata.memory_id,\n\t\t\t\tcontent_hash: metadata.content_hash,\n\t\t\t});\n\t\t}\n\t\tif (signal?.aborted) return false;\n\t\tinsertScanPage.deferred(targetRows);\n\t\tafterRowId = rowIds.at(-1)?.rowid ?? afterRowId;\n\t\tif (rowIds.length < batchSize) return true;\n\t}\n\treturn false;\n}\n\nfunction visitTargetVectorRowsForMemories(\n\tdb: Database,\n\tmemoryIds: number[],\n\tbatchSize: number,\n\tvisit: (rows: TargetVectorRow[]) => void,\n\tsignal?: AbortSignal,\n): boolean {\n\tif (memoryIds.length === 0) return true;\n\tconst placeholders = memoryIds.map(() => \"?\").join(\", \");\n\tconst selectRows = db.prepare(\n\t\t`SELECT rowid, memory_id, content_hash FROM temp.vector_prune_scan\n\t\t WHERE memory_id IN (${placeholders}) AND rowid > ?\n\t\t ORDER BY rowid ASC LIMIT ? /* vector-target-prune-spill-page */`,\n\t);\n\tlet afterRowId = 0;\n\twhile (!signal?.aborted) {\n\t\tconst rows = selectRows.all(...memoryIds, afterRowId, batchSize) as TargetVectorRow[];\n\t\tif (signal?.aborted) return false;\n\t\tif (rows.length === 0) return true;\n\t\tvisit(rows);\n\t\tafterRowId = rows.at(-1)?.rowid ?? afterRowId;\n\t\tif (rows.length < batchSize) return true;\n\t}\n\treturn false;\n}\n\nfunction deleteVectorRows(db: Database, rowIds: number[]): number {\n\tconst write = prepareVectorWrites(db);\n\treturn db.transaction(() => write({ deleteRowIds: rowIds }).deleted).immediate();\n}\n\nfunction createTargetVectorCoverageStates(\n\tmemories: MemoryTextRow[],\n): Map<number, TargetVectorCoverageState> {\n\treturn new Map(\n\t\tmemories.map((memory): [number, TargetVectorCoverageState] => {\n\t\t\tconst expectedHashes = chunkHashes(memoryText(memory.title, memory.body_text));\n\t\t\treturn [\n\t\t\t\tmemory.id,\n\t\t\t\t{ expectedHashes, expected: new Set(expectedHashes), existing: new Set<string>() },\n\t\t\t];\n\t\t}),\n\t);\n}\n\nfunction summarizeTargetVectorCoverage(states: Map<number, TargetVectorCoverageState>): {\n\tcoveredMemoryIds: number[];\n\tincomplete: number;\n} {\n\tconst coveredMemoryIds: number[] = [];\n\tlet incomplete = 0;\n\tfor (const [memoryId, state] of states) {\n\t\tif (!expectedHashSetContains(state.expectedHashes, state.existing)) incomplete++;\n\t\telse coveredMemoryIds.push(memoryId);\n\t}\n\treturn { coveredMemoryIds, incomplete };\n}\n\nfunction pruneCoveredTargetVectorRows(\n\tdb: Database,\n\tstates: Map<number, TargetVectorCoverageState>,\n\tmemoryIds: number[],\n\tbatchSize: number,\n\tsignal?: AbortSignal,\n): { completed: boolean; deleted: number } {\n\tlet deleted = 0;\n\tconst completed = visitTargetVectorRowsForMemories(\n\t\tdb,\n\t\tmemoryIds,\n\t\tbatchSize,\n\t\t(rows) => {\n\t\t\tconst obsolete = rows\n\t\t\t\t.filter((row) => {\n\t\t\t\t\tconst expected = states.get(row.memory_id)?.expected;\n\t\t\t\t\treturn row.content_hash == null || !expected?.has(row.content_hash);\n\t\t\t\t})\n\t\t\t\t.map((row) => row.rowid);\n\t\t\tif (obsolete.length > 0) deleted += deleteVectorRows(db, obsolete);\n\t\t},\n\t\tsignal,\n\t);\n\treturn { completed, deleted };\n}\n\nfunction pruneActiveMemoryPage(\n\tdb: Database,\n\tmemories: MemoryTextRow[],\n\tbatchSize: number,\n\tsignal?: AbortSignal,\n): { completed: boolean; deleted: number; incomplete: number } {\n\tconst states = createTargetVectorCoverageStates(memories);\n\tconst memoryIds = memories.map((memory) => memory.id);\n\tconst covered = visitTargetVectorRowsForMemories(\n\t\tdb,\n\t\tmemoryIds,\n\t\tbatchSize,\n\t\t(rows) => {\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst state = states.get(row.memory_id);\n\t\t\t\tif (row.content_hash != null && state?.expected.has(row.content_hash)) {\n\t\t\t\t\tstate.existing.add(row.content_hash);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tsignal,\n\t);\n\tif (!covered) return { completed: false, deleted: 0, incomplete: 0 };\n\tconst coverage = summarizeTargetVectorCoverage(states);\n\tconst pruned = pruneCoveredTargetVectorRows(\n\t\tdb,\n\t\tstates,\n\t\tcoverage.coveredMemoryIds,\n\t\tbatchSize,\n\t\tsignal,\n\t);\n\tif (!pruned.completed) {\n\t\treturn { completed: false, deleted: pruned.deleted, incomplete: coverage.incomplete };\n\t}\n\tconst placeholders = memoryIds.map(() => \"?\").join(\", \");\n\tdb.prepare(`DELETE FROM temp.vector_prune_scan WHERE memory_id IN (${placeholders})`).run(\n\t\t...memoryIds,\n\t);\n\treturn { completed: true, deleted: pruned.deleted, incomplete: coverage.incomplete };\n}\n\nfunction pruneRemainingTargetVectorRows(\n\tdb: Database,\n\tbatchSize: number,\n\tsignal?: AbortSignal,\n): { completed: boolean; deleted: number } {\n\tconst selectRows = db.prepare(\n\t\t`SELECT rowid, memory_id, content_hash FROM temp.vector_prune_scan\n\t\t WHERE rowid > ? ORDER BY rowid ASC LIMIT ? /* vector-target-prune-spill-remainder */`,\n\t);\n\tlet afterRowId = 0;\n\tlet deleted = 0;\n\twhile (!signal?.aborted) {\n\t\tconst rows = selectRows.all(afterRowId, batchSize) as TargetVectorRow[];\n\t\tif (signal?.aborted) return { completed: false, deleted };\n\t\tif (rows.length === 0) return { completed: true, deleted };\n\t\tdeleted += deleteVectorRows(\n\t\t\tdb,\n\t\t\trows.map((row) => row.rowid),\n\t\t);\n\t\tafterRowId = rows.at(-1)?.rowid ?? afterRowId;\n\t\tif (rows.length < batchSize) return { completed: true, deleted };\n\t}\n\treturn { completed: false, deleted };\n}\n\nfunction pruneTargetVectorRowsFromShadowTable(\n\tdb: Database,\n\tmodel: string,\n\toptions: { signal?: AbortSignal },\n): { deleted: number; incompleteActiveCoverage: number | null } {\n\tconst batchSize = 250;\n\t// The connection defaults to temp_store=MEMORY, which would keep the spill\n\t// resident in SQLite's heap and leave peak memory O(total vectors). Force it\n\t// to disk for the prune so the bound is genuinely one page. temp_store cannot\n\t// change while temp tables exist, so this must bracket the CREATE/DROP.\n\tconst previousTempStore = readTempStore(db);\n\tdb.pragma(\"temp_store = FILE\");\n\ttry {\n\t\treturn pruneTargetVectorRowsWithSpill(db, model, batchSize, options.signal);\n\t} finally {\n\t\tdb.pragma(`temp_store = ${previousTempStore}`);\n\t}\n}\n\nfunction readTempStore(db: Database): number {\n\tconst value = db.pragma(\"temp_store\", { simple: true });\n\treturn typeof value === \"number\" ? value : 0;\n}\n\nfunction pruneTargetVectorRowsWithSpill(\n\tdb: Database,\n\tmodel: string,\n\tbatchSize: number,\n\tsignal: AbortSignal | undefined,\n): { deleted: number; incompleteActiveCoverage: number | null } {\n\tconst options = { signal };\n\tdb.exec(`CREATE TEMP TABLE IF NOT EXISTS vector_prune_scan (\n\t\trowid INTEGER PRIMARY KEY,\n\t\tmemory_id INTEGER NOT NULL,\n\t\tcontent_hash TEXT\n\t)`);\n\ttry {\n\t\tdb.exec(\n\t\t\t\"CREATE INDEX IF NOT EXISTS temp.vector_prune_scan_memory_id_idx ON vector_prune_scan(memory_id)\",\n\t\t);\n\t\tdb.exec(\"DELETE FROM temp.vector_prune_scan\");\n\t\tif (!collectTargetVectorRows(db, model, batchSize, options.signal)) {\n\t\t\treturn { deleted: 0, incompleteActiveCoverage: null };\n\t\t}\n\t\tconst selectMemories = db.prepare(\n\t\t\t`SELECT id, title, body_text FROM memory_items\n\t\t\t WHERE active = 1 AND id > ?\n\t\t\t ORDER BY id ASC LIMIT ?`,\n\t\t);\n\t\tlet afterMemoryId = 0;\n\t\tlet deleted = 0;\n\t\tlet incompleteActiveCoverage = 0;\n\t\twhile (!options.signal?.aborted) {\n\t\t\tconst memories = selectMemories.all(afterMemoryId, batchSize) as MemoryTextRow[];\n\t\t\tif (memories.length === 0) break;\n\t\t\tconst result = pruneActiveMemoryPage(db, memories, batchSize, options.signal);\n\t\t\tdeleted += result.deleted;\n\t\t\tif (!result.completed) return { deleted, incompleteActiveCoverage: null };\n\t\t\tincompleteActiveCoverage += result.incomplete;\n\t\t\tafterMemoryId = memories.at(-1)?.id ?? afterMemoryId;\n\t\t}\n\t\tif (options.signal?.aborted) return { deleted, incompleteActiveCoverage: null };\n\t\tconst remaining = pruneRemainingTargetVectorRows(db, batchSize, options.signal);\n\t\tdeleted += remaining.deleted;\n\t\treturn {\n\t\t\tdeleted,\n\t\t\tincompleteActiveCoverage: remaining.completed ? incompleteActiveCoverage : null,\n\t\t};\n\t} finally {\n\t\tdb.exec(\"DROP TABLE IF EXISTS temp.vector_prune_scan\");\n\t}\n}\n\nfunction pruneTargetVectorRowsWithLegacyScan(\n\tdb: Database,\n\tmodel: string,\n\toptions: { signal?: AbortSignal },\n): number {\n\tconst batchSize = 250;\n\tlet afterRowId = 0;\n\tlet deleted = 0;\n\tconst selectBatch = db.prepare(\n\t\t`SELECT mv.rowid AS rowid, mv.memory_id AS memory_id, mv.content_hash AS content_hash,\n\t\t mi.title AS title, mi.body_text AS body_text, mi.active AS active\n\t\t FROM memory_vectors mv\n\t\t LEFT JOIN memory_items mi ON mi.id = mv.memory_id\n\t\t WHERE mv.model = ? AND mv.rowid > ?\n\t\t ORDER BY mv.rowid ASC\n\t\t LIMIT ?`,\n\t);\n\tconst write = prepareVectorWrites(db);\n\twhile (!options.signal?.aborted) {\n\t\tconst rows = selectBatch.all(model, afterRowId, batchSize) as Array<\n\t\t\tTargetVectorRow & { title: string | null; body_text: string | null; active: number | null }\n\t\t>;\n\t\tif (rows.length === 0) break;\n\t\tconst obsoleteRowIds: number[] = [];\n\t\tconst expectedByMemory = new Map<number, Set<string>>();\n\t\tconst coverageByMemory = new Map<number, boolean>();\n\t\tfor (const row of rows) {\n\t\t\tif (row.active == null || row.active === 0) {\n\t\t\t\tobsoleteRowIds.push(row.rowid);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlet covered = coverageByMemory.get(row.memory_id);\n\t\t\tif (covered === undefined) {\n\t\t\t\tcovered = memoryHasCompleteVectorCoverage(\n\t\t\t\t\tdb,\n\t\t\t\t\t{ id: row.memory_id, title: row.title, body_text: row.body_text },\n\t\t\t\t\tmodel,\n\t\t\t\t);\n\t\t\t\tcoverageByMemory.set(row.memory_id, covered);\n\t\t\t}\n\t\t\tif (!covered) continue;\n\t\t\tconst expected =\n\t\t\t\texpectedByMemory.get(row.memory_id) ??\n\t\t\t\tnew Set(chunkHashes(memoryText(row.title, row.body_text)));\n\t\t\texpectedByMemory.set(row.memory_id, expected);\n\t\t\tif (row.content_hash == null || !expected.has(row.content_hash)) {\n\t\t\t\tobsoleteRowIds.push(row.rowid);\n\t\t\t}\n\t\t}\n\t\tdeleted += db.transaction(() => write({ deleteRowIds: obsoleteRowIds }).deleted).immediate();\n\t\tafterRowId = rows.at(-1)?.rowid ?? afterRowId;\n\t}\n\treturn deleted;\n}\n\n/**\n * Delete target-model vector rows whose content_hash is not part of their\n * memory's current chunk set. Coverage is a subset check, so a memory can be\n * \"covered\" while still retaining obsolete target rows — e.g. an interrupted\n * migration, or a title/body edit (like `codemem db scan-secrets` redaction)\n * without vector maintenance. Because semanticSearch ranks by MIN(distance)\n * across a memory's rows, those stale rows would keep pre-edit or redacted\n * content influencing recall after cutover. Incomplete memories are left\n * untouched so their current rows can still be repaired safely. Returns the\n * number of rows removed.\n */\nexport function pruneObsoleteTargetModelVectors(\n\tdb: Database,\n\tmodel: string,\n\toptions: { signal?: AbortSignal } = {},\n): number {\n\treturn pruneObsoleteTargetModelVectorsWithCoverage(db, model, options).deleted;\n}\n\nexport function pruneObsoleteTargetModelVectorsWithCoverage(\n\tdb: Database,\n\tmodel: string,\n\toptions: { signal?: AbortSignal } = {},\n): { deleted: number; incompleteActiveCoverage: number | null } {\n\tif (!hasMemoryVectorRowidsShadowTable(db)) {\n\t\treturn {\n\t\t\tdeleted: pruneTargetVectorRowsWithLegacyScan(db, model, options),\n\t\t\tincompleteActiveCoverage: null,\n\t\t};\n\t}\n\treturn pruneTargetVectorRowsFromShadowTable(db, model, options);\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface BackfillVectorsResult {\n\tchecked: number;\n\tembedded: number;\n\tinserted: number;\n\tskipped: number;\n}\n\nexport interface BackfillVectorsOptions {\n\tlimit?: number | null;\n\tsince?: string | null;\n\tproject?: string | null;\n\tactiveOnly?: boolean;\n\tdryRun?: boolean;\n\tmemoryIds?: number[] | null;\n\t/**\n\t * When provided, backfill stops between inference batches. The in-flight\n\t * batch finishes, and any memory with only partial output remains unwritten.\n\t * Used by the viewer serve shutdown sequence to bound SIGTERM latency.\n\t */\n\tsignal?: AbortSignal;\n\t/** Use an already-resolved client so vectors and their persisted label cannot diverge. */\n\tclient?: EmbeddingClient;\n}\n\nexport interface ReplicationVectorMaintenanceResult {\n\tdeleted: number;\n\tinserted: number;\n\terrors: string[];\n}\n\nexport type SemanticIndexState = \"healthy\" | \"pending\" | \"failed\" | \"degraded\" | \"disabled\";\n\nexport interface SemanticIndexDiagnostics {\n\tstate: SemanticIndexState;\n\tsummary: string;\n\tmode: \"semantic\" | \"keyword_only\";\n\tcurrent_model: string;\n\tsemantic_search_model: string | null;\n\tembeddable_memory_count: number;\n\tindexed_memory_count: number;\n\tpending_memory_count: number;\n\tmaintenance_job: {\n\t\tstatus: \"pending\" | \"running\" | \"failed\" | \"completed\" | \"cancelled\";\n\t\tmessage: string | null;\n\t\terror: string | null;\n\t\tprogress_current: number;\n\t\tprogress_total: number | null;\n\t} | null;\n}\n\nexport interface SemanticIndexDiagnosticsOptions {\n\t/**\n\t * Default true — runs a single indexed COUNT(DISTINCT) join. The slow\n\t * alternative does a vec0 probe per memory row, which blocks the event\n\t * loop; only set to false from non-request-path tooling that needs\n\t * per-chunk coverage precision.\n\t */\n\tfastCounts?: boolean;\n}\n\nfunction traceSemanticDiag<T>(label: string, fn: () => T): T {\n\tif (process.env.CODEMEM_TRACE_SEMANTIC_DIAGNOSTICS !== \"1\") return fn();\n\tconst startedAt = Date.now();\n\tconsole.warn(`[codemem semantic] ${label} start`);\n\ttry {\n\t\treturn fn();\n\t} finally {\n\t\tconsole.warn(`[codemem semantic] ${label} ${Date.now() - startedAt}ms`);\n\t}\n}\n\nfunction countEmbeddableActiveMemories(db: Database): number {\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT COUNT(*) AS c\n\t\t\t FROM memory_items\n\t\t\t WHERE active = 1\n\t\t\t AND TRIM(COALESCE(title, '') || COALESCE(body_text, '')) != ''`,\n\t\t)\n\t\t.get() as { c?: number } | undefined;\n\treturn Number(row?.c ?? 0);\n}\n\n/**\n * `memory_vectors` is a sqlite-vec virtual table. Querying it requires the\n * `vec0` module to be loaded into the active connection — a different\n * concern from the table merely existing in the schema. On platforms where\n * sqlite-vec failed to load (e.g. Linux ARM64 without the matching\n * platform package), the table can persist from a previous run while the\n * module is gone, so a JOIN crashes with `SQLITE_ERROR: no such module:\n * vec0`. Diagnostic counters must treat that case as \"0 indexed\", same as\n * the explicit `CODEMEM_EMBEDDING_DISABLED` path, instead of throwing.\n */\nfunction isVecModuleMissingError(error: unknown): boolean {\n\tif (!(error instanceof Error)) return false;\n\tconst message = error.message ?? \"\";\n\treturn /no such module:\\s*vec0/i.test(message);\n}\n\nfunction countIndexedActiveMemories(db: Database, models: string[]): number {\n\tif (isEmbeddingDisabled() || !vectorStoreExists(db)) return 0;\n\tlet rows: MemoryTextRow[];\n\ttry {\n\t\trows = db\n\t\t\t.prepare(\n\t\t\t\t`SELECT id, title, body_text\n\t\t\t\t FROM memory_items\n\t\t\t\t WHERE active = 1\n\t\t\t\t AND TRIM(COALESCE(title, '') || COALESCE(body_text, '')) != ''\n\t\t\t\t ORDER BY id ASC`,\n\t\t\t)\n\t\t\t.all() as MemoryTextRow[];\n\t} catch (error) {\n\t\tif (isVecModuleMissingError(error)) return 0;\n\t\tthrow error;\n\t}\n\ttry {\n\t\treturn withVectorMetadataSnapshot(db, (metadata) => {\n\t\t\tconst selectHash = prepareSnapshotHashQuery(metadata);\n\t\t\treturn rows.filter((row) =>\n\t\t\t\tmodels.some((model) => memoryHasSnapshotCoverage(selectHash, row, model)),\n\t\t\t).length;\n\t\t});\n\t} catch (error) {\n\t\tif (isVecModuleMissingError(error)) return 0;\n\t\tthrow error;\n\t}\n}\n\nfunction countIndexedActiveMemoriesFast(db: Database, models: string[]): number {\n\tif (isEmbeddingDisabled() || !vectorStoreExists(db)) return 0;\n\ttry {\n\t\tconst placeholders = models.map(() => \"?\").join(\", \");\n\t\tconst row = db\n\t\t\t.prepare(\n\t\t\t\t`SELECT COUNT(DISTINCT mi.id) AS c\n\t\t\t\t FROM memory_items mi\n\t\t\t\t JOIN memory_vectors mv ON mv.memory_id = mi.id\n\t\t\t\t WHERE mi.active = 1\n\t\t\t\t AND mv.model IN (${placeholders})\n\t\t\t\t AND TRIM(COALESCE(mi.title, '') || COALESCE(mi.body_text, '')) != ''`,\n\t\t\t)\n\t\t\t.get(...models) as { c?: number } | undefined;\n\t\treturn Number(row?.c ?? 0);\n\t} catch (error) {\n\t\tif (isVecModuleMissingError(error)) return 0;\n\t\tthrow error;\n\t}\n}\n\nfunction resolvePendingMemoryCount(\n\tfallbackPendingCount: number,\n\tjob: ReturnType<typeof getMaintenanceJob>,\n): number {\n\tif (!(job?.status === \"pending\" || job?.status === \"running\" || job?.status === \"failed\")) {\n\t\treturn fallbackPendingCount;\n\t}\n\tconst metadata = job?.metadata ?? {};\n\tconst total = Number(metadata.embeddable_total ?? job?.progress.total ?? Number.NaN);\n\tconst processed = Number(metadata.processed_embeddable ?? job?.progress.current ?? Number.NaN);\n\tif (Number.isFinite(total) && Number.isFinite(processed)) {\n\t\treturn Math.max(total - processed, 0);\n\t}\n\treturn fallbackPendingCount;\n}\n\nfunction summarizeSemanticIndexState(\n\tstate: SemanticIndexState,\n\tcounts: { embeddable: number; indexed: number; pending: number },\n\tjob: ReturnType<typeof getMaintenanceJob>,\n\truntimeUnavailable: boolean,\n): string {\n\tif (state === \"failed\") {\n\t\treturn job?.error ?? job?.message ?? \"Semantic-index catch-up failed\";\n\t}\n\tif (state === \"disabled\") {\n\t\treturn \"Semantic search is off because embeddings are disabled; keyword search remains available\";\n\t}\n\tif (state === \"degraded\") {\n\t\tif (runtimeUnavailable) {\n\t\t\treturn \"The embedding runtime is unavailable; sync data is available in keyword-only mode\";\n\t\t}\n\t\treturn \"Semantic-index coverage is unavailable; sync data is effectively running in keyword-only mode\";\n\t}\n\tif (state === \"pending\") {\n\t\tconst jobActive = job?.status === \"pending\" || job?.status === \"running\";\n\t\tconst jobMessage = jobActive ? job?.message : null;\n\t\treturn jobMessage ?? `${counts.pending} memory(s) still need semantic indexing`;\n\t}\n\tif (counts.embeddable === 0) {\n\t\treturn \"No embeddable memories need semantic indexing\";\n\t}\n\treturn `Semantic index is current for ${counts.indexed} embeddable mem${counts.indexed === 1 ? \"ory\" : \"ories\"}`;\n}\n\nfunction resolveSemanticIndexState(options: {\n\tembeddingsDisabled: boolean;\n\tembeddingRevisionMissing: boolean;\n\tidentityLabelUnresolved: boolean;\n\tjobStatus: NonNullable<ReturnType<typeof getMaintenanceJob>>[\"status\"] | undefined;\n\tactiveCatchUp: boolean;\n\tdegraded: boolean;\n\tpendingMemoryCount: number;\n}): SemanticIndexState {\n\t// Disabled embeddings also stop the catch-up runner, so a queued job would\n\t// otherwise read as pending forever.\n\tif (options.embeddingsDisabled) return \"disabled\";\n\tif (options.embeddingRevisionMissing) return \"degraded\";\n\tif (options.jobStatus === \"failed\") return \"failed\";\n\tif (options.identityLabelUnresolved) return \"pending\";\n\tif (options.activeCatchUp) return \"pending\";\n\tif (options.degraded) return \"degraded\";\n\tif (options.pendingMemoryCount > 0) return \"pending\";\n\treturn \"healthy\";\n}\n\nfunction resolveSemanticRuntime(db: Database): {\n\tembeddingModel: string;\n\tembeddingRevision: string | null;\n\tcurrentModel: string;\n\tsemanticSearchModel: string | null;\n\tembeddingsDisabled: boolean;\n\truntimeUnavailable: boolean;\n\tembeddingRevisionMissing: boolean;\n\tidentityLabelUnresolved: boolean;\n} {\n\tconst embeddingModel = traceSemanticDiag(\"resolveEmbeddingModel\", () => resolveEmbeddingModel());\n\tconst embeddingRevision = traceSemanticDiag(\"tryResolveEmbeddingRevision\", () =>\n\t\ttryResolveEmbeddingRevision(embeddingModel),\n\t);\n\tconst resolvedCurrentModel = traceSemanticDiag(\"tryResolveConfiguredVectorIdentityLabel\", () =>\n\t\ttryResolveConfiguredVectorIdentityLabel(db),\n\t);\n\tconst embeddingRevisionMissing = embeddingRevision == null;\n\tconst identityLabelUnresolved = !embeddingRevisionMissing && resolvedCurrentModel == null;\n\tconst currentModel =\n\t\tresolvedCurrentModel ??\n\t\t(embeddingRevision == null\n\t\t\t? `${embeddingModel} (missing CODEMEM_EMBEDDING_REVISION)`\n\t\t\t: `${embeddingModel}@${embeddingRevision} (revision unresolved)`);\n\tconst semanticSearchModel =\n\t\tembeddingRevisionMissing || identityLabelUnresolved\n\t\t\t? null\n\t\t\t: traceSemanticDiag(\"resolveSemanticSearchModel\", () =>\n\t\t\t\t\tresolveSemanticSearchModel(db, currentModel),\n\t\t\t\t);\n\tconst embeddingsDisabled = traceSemanticDiag(\"isEmbeddingDisabled\", () => isEmbeddingDisabled());\n\tconst runtimeUnavailable = getEmbeddingRuntimeStatus().state === \"unavailable\";\n\treturn {\n\t\tembeddingModel,\n\t\tembeddingRevision,\n\t\tcurrentModel,\n\t\tsemanticSearchModel,\n\t\tembeddingsDisabled,\n\t\truntimeUnavailable,\n\t\tembeddingRevisionMissing,\n\t\tidentityLabelUnresolved,\n\t};\n}\n\nfunction collectSemanticIndexCounts(\n\tdb: Database,\n\tcoverageModels: string[],\n\tfastCounts: boolean,\n): { embeddableMemoryCount: number; indexedMemoryCount: number } {\n\tconst embeddableMemoryCount = traceSemanticDiag(\"countEmbeddableActiveMemories\", () =>\n\t\tcountEmbeddableActiveMemories(db),\n\t);\n\tconst indexedMemoryCount = traceSemanticDiag(\n\t\tfastCounts ? \"countIndexedActiveMemoriesFast\" : \"countIndexedActiveMemories\",\n\t\t() =>\n\t\t\tfastCounts\n\t\t\t\t? countIndexedActiveMemoriesFast(db, coverageModels)\n\t\t\t\t: countIndexedActiveMemories(db, coverageModels),\n\t);\n\treturn { embeddableMemoryCount, indexedMemoryCount };\n}\n\ntype SemanticRuntime = ReturnType<typeof resolveSemanticRuntime>;\n\nfunction collectSemanticCoverage(\n\tdb: Database,\n\truntime: SemanticRuntime,\n\tfastCounts: boolean,\n): { embeddableMemoryCount: number; indexedMemoryCount: number } {\n\tif (runtime.embeddingRevisionMissing || runtime.identityLabelUnresolved) {\n\t\tconst embeddableMemoryCount = traceSemanticDiag(\"countEmbeddableActiveMemories\", () =>\n\t\t\tcountEmbeddableActiveMemories(db),\n\t\t);\n\t\treturn { embeddableMemoryCount, indexedMemoryCount: 0 };\n\t}\n\t// Count coverage under the same model labels search reads, so a corpus\n\t// served from compatible legacy vectors is not reported as unindexed.\n\tconst searchModels = expandSemanticSearchModels(\n\t\tdb,\n\t\truntime.semanticSearchModel,\n\t\truntime.currentModel,\n\t);\n\treturn collectSemanticIndexCounts(\n\t\tdb,\n\t\tsearchModels.length > 0 ? searchModels : [runtime.currentModel],\n\t\tfastCounts,\n\t);\n}\n\nfunction describeSemanticIndex(\n\tstate: SemanticIndexState,\n\truntime: SemanticRuntime,\n\tcounts: { embeddable: number; indexed: number; pending: number },\n\tjob: ReturnType<typeof getMaintenanceJob>,\n): string {\n\tif (state !== \"disabled\" && runtime.embeddingRevisionMissing) {\n\t\treturn `Semantic search is unavailable because ${runtime.embeddingModel} has no CODEMEM_EMBEDDING_REVISION; keyword search remains available`;\n\t}\n\tif (state !== \"disabled\" && runtime.identityLabelUnresolved) {\n\t\treturn `Semantic indexing is pending until ${runtime.embeddingModel}@${runtime.embeddingRevision} resolves to a canonical commit`;\n\t}\n\treturn summarizeSemanticIndexState(state, counts, job, runtime.runtimeUnavailable);\n}\n\nexport function getSemanticIndexDiagnostics(\n\tdb: Database,\n\toptions: SemanticIndexDiagnosticsOptions = {},\n): SemanticIndexDiagnostics {\n\tconst runtime = resolveSemanticRuntime(db);\n\tconst {\n\t\tcurrentModel,\n\t\tsemanticSearchModel,\n\t\tembeddingsDisabled,\n\t\truntimeUnavailable,\n\t\tembeddingRevisionMissing,\n\t\tidentityLabelUnresolved,\n\t} = runtime;\n\tconst { embeddableMemoryCount, indexedMemoryCount } = collectSemanticCoverage(\n\t\tdb,\n\t\truntime,\n\t\toptions.fastCounts !== false,\n\t);\n\tconst fallbackPendingCount = Math.max(embeddableMemoryCount - indexedMemoryCount, 0);\n\tconst job = traceSemanticDiag(\"getMaintenanceJob\", () =>\n\t\tgetMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB),\n\t);\n\tconst pendingMemoryCount = resolvePendingMemoryCount(fallbackPendingCount, job);\n\tconst degraded =\n\t\tembeddingRevisionMissing ||\n\t\t(embeddableMemoryCount > 0 &&\n\t\t\t(embeddingsDisabled || runtimeUnavailable || semanticSearchModel == null));\n\tconst state = resolveSemanticIndexState({\n\t\tembeddingsDisabled,\n\t\tembeddingRevisionMissing,\n\t\tidentityLabelUnresolved,\n\t\tjobStatus: job?.status,\n\t\tactiveCatchUp: job?.status === \"pending\" || job?.status === \"running\",\n\t\tdegraded,\n\t\tpendingMemoryCount,\n\t});\n\tconst summary = describeSemanticIndex(\n\t\tstate,\n\t\truntime,\n\t\t{ embeddable: embeddableMemoryCount, indexed: indexedMemoryCount, pending: pendingMemoryCount },\n\t\tjob,\n\t);\n\n\treturn {\n\t\tstate,\n\t\tsummary,\n\t\tmode:\n\t\t\tembeddingsDisabled || runtimeUnavailable || !semanticSearchModel\n\t\t\t\t? \"keyword_only\"\n\t\t\t\t: \"semantic\",\n\t\tcurrent_model: currentModel,\n\t\tsemantic_search_model: semanticSearchModel,\n\t\tembeddable_memory_count: embeddableMemoryCount,\n\t\tindexed_memory_count: indexedMemoryCount,\n\t\tpending_memory_count: pendingMemoryCount,\n\t\tmaintenance_job: job\n\t\t\t? {\n\t\t\t\t\tstatus: job.status,\n\t\t\t\t\tmessage: job.message,\n\t\t\t\t\terror: job.error,\n\t\t\t\t\tprogress_current: job.progress.current,\n\t\t\t\t\tprogress_total: job.progress.total,\n\t\t\t\t}\n\t\t\t: null,\n\t};\n}\n\nfunction uniqueMemoryIds(memoryIds: number[]): number[] {\n\treturn [...new Set(memoryIds.filter((memoryId) => Number.isInteger(memoryId) && memoryId > 0))];\n}\n\nfunction deleteVectorsForMemoryIds(db: Database, memoryIds: number[]): number {\n\tif (!vectorStoreExists(db) || memoryIds.length === 0) return 0;\n\tconst write = prepareVectorWrites(db);\n\treturn db.transaction(() => write({ deleteMemoryIds: memoryIds }).deleted).immediate();\n}\n\nfunction prepareSnapshotPruneQueries(metadata: Database, rowIds: number[]) {\n\treturn {\n\t\tselectHash: prepareSnapshotHashQuery(metadata),\n\t\tselectRows: metadata.prepare(\n\t\t\t\"SELECT rowid, model, content_hash FROM vector_metadata WHERE memory_id = ? AND model IN (?, ?)\",\n\t\t),\n\t\trowIds,\n\t};\n}\n\nfunction pruneSnapshotMemoryRows(\n\t{ selectHash, selectRows, rowIds }: ReturnType<typeof prepareSnapshotPruneQueries>,\n\tmemory: MemoryTextRow,\n\tmodel: string,\n): void {\n\tconst expectedHashes = chunkHashes(memoryText(memory.title, memory.body_text));\n\tif (!snapshotHasExpectedHashes(selectHash, memory.id, model, expectedHashes)) return;\n\tconst expected = new Set(expectedHashes);\n\tconst compatibleLegacyModel =\n\t\tmodel === DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL ? LEGACY_DEFAULT_EMBEDDING_MODEL : null;\n\tfor (const row of selectRows.iterate(memory.id, model, compatibleLegacyModel) as Iterable<{\n\t\trowid: number;\n\t\tmodel: string;\n\t\tcontent_hash: string | null;\n\t}>) {\n\t\tif (row.model === model && row.content_hash != null && expected.has(row.content_hash)) continue;\n\t\trowIds.push(row.rowid);\n\t}\n}\n\n/**\n * Prune stale target rows only after the memory's current target hashes are\n * complete. For the revision-aware default identity, also remove that memory's\n * compatible legacy rows so covered memories no longer rank on pre-edit content.\n */\nexport function pruneStaleCurrentModelVectors(\n\tdb: Database,\n\tmemoryIds: number[],\n\tmodel: string,\n): number {\n\tconst ids = uniqueMemoryIds(memoryIds);\n\tif (ids.length === 0) return 0;\n\tconst batchSize = 250;\n\tconst write = prepareVectorWrites(db);\n\tlet deleted = 0;\n\n\tfor (let offset = 0; offset < ids.length; offset += batchSize) {\n\t\tconst batchIds = ids.slice(offset, offset + batchSize);\n\t\tconst placeholders = batchIds.map(() => \"?\").join(\", \");\n\t\tconst pruneCoveredMemories = db.transaction(() =>\n\t\t\twithVectorMetadataSnapshot(\n\t\t\t\tdb,\n\t\t\t\t(metadata) => {\n\t\t\t\t\tconst rowIds: number[] = [];\n\t\t\t\t\tconst queries = prepareSnapshotPruneQueries(metadata, rowIds);\n\t\t\t\t\tconst rows = db\n\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t`SELECT id, title, body_text FROM memory_items\n\t\t\t\t\t WHERE id IN (${placeholders}) ORDER BY id ASC`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.all(...batchIds) as MemoryTextRow[];\n\t\t\t\t\tfor (const row of rows) {\n\t\t\t\t\t\tpruneSnapshotMemoryRows(queries, row, model);\n\t\t\t\t\t}\n\t\t\t\t\treturn write({ deleteRowIds: rowIds }).deleted;\n\t\t\t\t},\n\t\t\t\t{ memoryIds: batchIds },\n\t\t\t),\n\t\t);\n\t\tdeleted += pruneCoveredMemories.immediate();\n\t}\n\n\treturn deleted;\n}\n\n/**\n * Fallback-only sync maintenance path used when durable incremental queueing\n * fails after inbound replication has already been applied. New sync code\n * should prefer queueVectorBackfillForIncrementalSync so work survives restart.\n */\nexport async function bestEffortMaintainVectorsForSyncFallback(\n\tdb: Database,\n\twork: ReplicationVectorWork,\n): Promise<ReplicationVectorMaintenanceResult> {\n\tconst result: ReplicationVectorMaintenanceResult = { deleted: 0, inserted: 0, errors: [] };\n\tconst deleteMemoryIds = uniqueMemoryIds(work.deleteMemoryIds);\n\tconst upsertMemoryIds = uniqueMemoryIds(work.upsertMemoryIds);\n\n\tif (!vectorStoreExists(db)) {\n\t\treturn result;\n\t}\n\n\ttry {\n\t\tresult.deleted += deleteVectorsForMemoryIds(db, deleteMemoryIds);\n\t} catch (error) {\n\t\tresult.errors.push(\n\t\t\t`delete vectors failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t);\n\t}\n\n\tif (upsertMemoryIds.length === 0) return result;\n\n\ttry {\n\t\tconst client = await getEmbeddingClient();\n\t\tconst backfill = await backfillVectors(db, {\n\t\t\tmemoryIds: upsertMemoryIds,\n\t\t\tclient: client ?? undefined,\n\t\t});\n\t\tresult.inserted = backfill.inserted;\n\t\tif (backfill.checked > 0 && client) {\n\t\t\tresult.deleted += pruneStaleCurrentModelVectors(\n\t\t\t\tdb,\n\t\t\t\tupsertMemoryIds,\n\t\t\t\tresolveEmbeddingClientVectorIdentityLabel(client),\n\t\t\t);\n\t\t}\n\t} catch (error) {\n\t\tresult.errors.push(\n\t\t\t`backfill vectors failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t);\n\t}\n\n\treturn result;\n}\n\n// ---------------------------------------------------------------------------\n// storeVectors — called inline when a memory is created/remembered\n// ---------------------------------------------------------------------------\n\n/**\n * Embed and store vectors for a single memory item.\n * No-op when embeddings are disabled or the client is unavailable.\n */\nexport async function storeVectors(\n\tdb: Database,\n\tmemoryId: number,\n\ttitle: string,\n\tbodyText: string,\n\toptions: { signal?: AbortSignal } = {},\n): Promise<void> {\n\tif (options.signal?.aborted) return;\n\t// Capture before client initialization yields, so ID reuse during that wait is visible.\n\tconst source = readVectorSource(db, memoryId);\n\tconst client = await getEmbeddingClient();\n\tif (options.signal?.aborted) return;\n\tif (!client) return;\n\tassertEmbeddingClientIdentity(client);\n\tassertVectorMemoryId(memoryId);\n\tif (!source) return;\n\n\tconst text = `${title}\\n${bodyText}`.trim();\n\tconst chunks = chunkText(text);\n\tif (chunks.length === 0) return;\n\n\tconst embeddings = await embedTexts(chunks, client);\n\t// Inference cannot be canceled here; a closed owner must never commit its late result.\n\tif (options.signal?.aborted) return;\n\tif (embeddings.length !== chunks.length) throw new TypeError(\"vector_count_mismatch\");\n\n\tconst model = resolveEmbeddingClientVectorIdentityLabel(client);\n\tconst persistVectors = db.transaction(\n\t\t(entries: Array<{ vector: Float32Array; chunkIndex: number; contentHash: string }>) => {\n\t\t\tif (options.signal?.aborted) return;\n\t\t\tconst hashes = currentVectorSourceHashes(source, readVectorSource(db, memoryId));\n\t\t\tconst currentEntries = entries.filter(\n\t\t\t\t(entry) => hashes[entry.chunkIndex] === entry.contentHash,\n\t\t\t);\n\t\t\tif (currentEntries.length === 0) return;\n\t\t\tensureVectorWriteModel(db, model);\n\t\t\tprepareVectorWrites(db)({\n\t\t\t\tinsert: {\n\t\t\t\t\tmodel,\n\t\t\t\t\trows: currentEntries.map((entry) => ({ ...entry, memoryId })),\n\t\t\t\t\texpectedCount: currentEntries.length,\n\t\t\t\t},\n\t\t\t});\n\t\t\tpersistVectorIdentity(db, client, model);\n\t\t},\n\t);\n\tconst entries: Array<{ vector: Float32Array; chunkIndex: number; contentHash: string }> = [];\n\n\tfor (let i = 0; i < chunks.length; i++) {\n\t\tconst vector = embeddings[i];\n\t\tconst chunk = chunks[i];\n\t\tif (!vector || vector.length === 0) throw new TypeError(\"invalid_vector_shape\");\n\t\tif (!chunk) throw new TypeError(\"invalid_vector_chunk\");\n\t\tentries.push({ vector, chunkIndex: i, contentHash: hashText(chunk) });\n\t}\n\tif (entries.length === 0) return;\n\tpersistVectors.immediate(entries);\n}\n\n// ---------------------------------------------------------------------------\n// backfillVectors — CLI batch backfill\n// ---------------------------------------------------------------------------\n\nfunction insertCompletedBackfillMemories(\n\tdb: Database,\n\tcompleted: Set<PendingMemory>,\n\tmodel: string,\n): number {\n\tif (completed.size === 0) return 0;\n\tconst memoryIds = Array.from(completed, (memory) => memory.memoryId);\n\t// All memories completed by this inference batch intentionally commit or\n\t// roll back together; a write failure must not leave a partially inserted batch.\n\treturn db\n\t\t.transaction(() =>\n\t\t\twithVectorMetadataSnapshot(\n\t\t\t\tdb,\n\t\t\t\t(metadata) => {\n\t\t\t\t\tconst entries = collectCompletedBackfillRows(db, metadata, completed, model);\n\t\t\t\t\tif (!entries.length) return 0;\n\t\t\t\t\tensureVectorWriteModel(db, model);\n\t\t\t\t\treturn prepareVectorWrites(db)({\n\t\t\t\t\t\tinsert: { model, rows: entries, expectedCount: entries.length },\n\t\t\t\t\t}).inserted;\n\t\t\t\t},\n\t\t\t\t{ memoryIds },\n\t\t\t),\n\t\t)\n\t\t.immediate();\n}\n\nfunction collectCompletedBackfillRows(\n\tdb: Database,\n\tmetadata: Database,\n\tcompleted: Set<PendingMemory>,\n\tmodel: string,\n) {\n\tconst selectHash = prepareSnapshotHashQuery(metadata);\n\tconst selectSource = db.prepare(`SELECT ${VECTOR_SOURCE_COLUMNS} FROM memory_items WHERE id = ?`);\n\tconst entries: Array<{\n\t\tmemoryId: number;\n\t\tvector: Float32Array;\n\t\tchunkIndex: number;\n\t\tcontentHash: string;\n\t}> = [];\n\tfor (const memory of completed) {\n\t\tconst current = selectSource.get(memory.memoryId) as VectorSourceRow | undefined;\n\t\tconst hashes = currentVectorSourceHashes(memory.source, current);\n\t\tfor (const [index, chunk] of memory.chunks.entries()) {\n\t\t\tif (hashes[chunk.chunkIndex] !== chunk.contentHash) continue;\n\t\t\tif (selectHash.get(memory.memoryId, model, chunk.contentHash)) continue;\n\t\t\tentries.push({\n\t\t\t\tvector: memory.vectors[index] as Float32Array,\n\t\t\t\tmemoryId: memory.memoryId,\n\t\t\t\tchunkIndex: chunk.chunkIndex,\n\t\t\t\tcontentHash: chunk.contentHash,\n\t\t\t});\n\t\t}\n\t}\n\treturn entries;\n}\n\nfunction snapshotHashesByMemory(\n\tselectRows: SnapshotQuery,\n\tmemoryIds: number[],\n\tmodel: string,\n): Map<number, Set<string>> {\n\tconst hashesByMemory = new Map<number, Set<string>>();\n\tfor (const row of selectRows.iterate(model, JSON.stringify(memoryIds)) as Iterable<{\n\t\tmemory_id: number;\n\t\tcontent_hash: string | null;\n\t}>) {\n\t\tif (row.content_hash == null) continue;\n\t\tconst hashes = hashesByMemory.get(row.memory_id) ?? new Set<string>();\n\t\thashes.add(row.content_hash);\n\t\thashesByMemory.set(row.memory_id, hashes);\n\t}\n\treturn hashesByMemory;\n}\n\nfunction validateBackfillEmbeddings(\n\tembeddings: Float32Array[],\n\texpectedCount: number,\n\tdimensions: number,\n): void {\n\tif (embeddings.length !== expectedCount) {\n\t\tthrow new TypeError(\n\t\t\t`Embedding client returned ${embeddings.length} vectors for ${expectedCount} texts`,\n\t\t);\n\t}\n\tfor (const vector of embeddings) {\n\t\tif (vector.length !== dimensions) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`Embedding client returned vector dimension ${vector.length}, expected ${dimensions}`,\n\t\t\t);\n\t\t}\n\t\tfor (const value of vector) {\n\t\t\tif (!Number.isFinite(value)) {\n\t\t\t\tthrow new TypeError(\"Embedding client returned a non-finite vector value\");\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction collectCompletedBackfillMemories(\n\tbatch: Array<{ memory: PendingMemory; chunk: PendingChunk }>,\n\tembeddings: Float32Array[],\n): Set<PendingMemory> {\n\tconst completed = new Set<PendingMemory>();\n\tfor (const [index, { memory }] of batch.entries()) {\n\t\tconst vector = embeddings[index];\n\t\tif (!vector) throw new TypeError(\"Embedding client omitted a validated vector\");\n\t\tmemory.vectors.push(vector);\n\t\tif (memory.vectors.length === memory.chunks.length) completed.add(memory);\n\t}\n\treturn completed;\n}\n\n/**\n * Backfill vectors for memories that don't have them yet.\n * Matches Python's `backfill_vectors()` in store/vectors.py.\n */\nexport async function backfillVectors(\n\tdb: Database,\n\topts: BackfillVectorsOptions = {},\n): Promise<BackfillVectorsResult> {\n\tif (opts.client) assertEmbeddingClientIdentity(opts.client);\n\tconst client = opts.client ?? (await getEmbeddingClient());\n\tif (!client) return { checked: 0, embedded: 0, inserted: 0, skipped: 0 };\n\n\tconst { limit, since, project, activeOnly = true, dryRun = false, memoryIds, signal } = opts;\n\n\tconst params: unknown[] = [];\n\tconst whereClauses: string[] = [];\n\n\tif (activeOnly) whereClauses.push(\"memory_items.active = 1\");\n\tif (since) {\n\t\twhereClauses.push(\"memory_items.created_at >= ?\");\n\t\tparams.push(since);\n\t}\n\tif (project) {\n\t\tconst pc = projectColumnClause(\"COALESCE(sessions.project, memory_items.project)\", project);\n\t\tif (pc.clause) {\n\t\t\twhereClauses.push(pc.clause);\n\t\t\tparams.push(...pc.params);\n\t\t}\n\t}\n\tif (memoryIds && memoryIds.length > 0) {\n\t\tconst placeholders = memoryIds.map(() => \"?\").join(\",\");\n\t\twhereClauses.push(`memory_items.id IN (${placeholders})`);\n\t\tparams.push(...memoryIds);\n\t}\n\n\tconst where = whereClauses.length > 0 ? whereClauses.join(\" AND \") : \"1=1\";\n\tconst joinSessions = project != null;\n\tconst joinClause = joinSessions ? \"JOIN sessions ON sessions.id = memory_items.session_id\" : \"\";\n\tconst model = resolveEmbeddingClientVectorIdentityLabel(client);\n\tlet checked = 0;\n\tlet embedded = 0;\n\tlet inserted = 0;\n\tlet skipped = 0;\n\tconst rowLimit = limit != null && limit > 0 ? limit : Infinity;\n\tconst candidateTable = createBackfillCandidateSnapshot(db, joinClause, where, params, rowLimit);\n\tlet metadata: Database | null = null;\n\tlet selectPageHashes: SnapshotQuery | null = null;\n\n\ttry {\n\t\tconst selectPage = db.prepare(\n\t\t\t`SELECT candidates.seq AS snapshot_seq,\n\t\t\t ${QUALIFIED_VECTOR_SOURCE_COLUMNS}\n\t\t\t FROM ${candidateTable} AS candidates\n\t\t\t JOIN memory_items ON memory_items.id = candidates.memory_id\n\t\t\t WHERE candidates.seq > ?\n\t\t\t ORDER BY candidates.seq ASC\n\t\t\t LIMIT ?`,\n\t\t);\n\t\tlet cursorSeq = 0;\n\t\twhile (!signal?.aborted) {\n\t\t\tconst rows = selectPage.all(cursorSeq, BACKFILL_MEMORY_PAGE_SIZE) as BackfillMemoryRow[];\n\t\t\tif (rows.length === 0) break;\n\t\t\tconst lastRow = rows.at(-1) as BackfillMemoryRow;\n\t\t\t// This cursor lives only for this invocation. An aborted caller starts a fresh pass.\n\t\t\tcursorSeq = lastRow.snapshot_seq;\n\n\t\t\t// Reuse only during uninterrupted synchronous reads. Inference closes\n\t\t\t// this snapshot before yielding; the next page then reads current state.\n\t\t\tmetadata ??= createVectorMetadataSnapshot(db);\n\t\t\tselectPageHashes ??= metadata.prepare(\n\t\t\t\t`SELECT memory_id, content_hash FROM vector_metadata\n\t\t\t\t WHERE model = ? AND memory_id IN (SELECT value FROM json_each(?))`,\n\t\t\t);\n\t\t\tconst existingHashesByMemory = snapshotHashesByMemory(\n\t\t\t\tselectPageHashes,\n\t\t\t\trows.map((row) => row.id),\n\t\t\t\tmodel,\n\t\t\t);\n\n\t\t\tlet batch: Array<{ memory: PendingMemory; chunk: PendingChunk }> = [];\n\t\t\tconst flushBatch = async (): Promise<void> => {\n\t\t\t\tif (batch.length === 0) return;\n\t\t\t\tconst currentBatch = batch;\n\t\t\t\tbatch = [];\n\t\t\t\tmetadata?.close();\n\t\t\t\tmetadata = null;\n\t\t\t\tselectPageHashes = null;\n\t\t\t\tconst embeddings = await embedTexts(\n\t\t\t\t\tcurrentBatch.map(({ chunk }) => chunk.text),\n\t\t\t\t\tclient,\n\t\t\t\t);\n\t\t\t\tvalidateBackfillEmbeddings(embeddings, currentBatch.length, client.dimensions);\n\t\t\t\tembedded += embeddings.length;\n\t\t\t\tconst completed = collectCompletedBackfillMemories(currentBatch, embeddings);\n\t\t\t\t// Page hashes are planning hints only. Recheck the completed batch\n\t\t\t\t// after inference inside the immediate write boundary: vec0 has no\n\t\t\t\t// uniqueness constraint. Do not add our inserts to that snapshot;\n\t\t\t\t// distinct chunk_index rows may legitimately share the same hash.\n\t\t\t\tif (!dryRun) inserted += insertCompletedBackfillMemories(db, completed, model);\n\t\t\t\tfor (const memory of completed) {\n\t\t\t\t\tif (dryRun) inserted += memory.chunks.length;\n\t\t\t\t\tmemory.vectors.length = 0;\n\t\t\t\t\tmemory.chunks.length = 0;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tfor (const row of rows) {\n\t\t\t\tif (signal?.aborted) return { checked, embedded, inserted, skipped };\n\t\t\t\tchecked++;\n\t\t\t\tconst chunks = chunkText(memoryText(row.title, row.body_text));\n\t\t\t\tconst existingHashes = existingHashesByMemory.get(row.id) ?? new Set<string>();\n\t\t\t\tconst pendingChunks: PendingChunk[] = [];\n\t\t\t\tfor (const [chunkIndex, text] of chunks.entries()) {\n\t\t\t\t\tconst contentHash = hashText(text);\n\t\t\t\t\tif (existingHashes.has(contentHash)) {\n\t\t\t\t\t\tskipped++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tpendingChunks.push({ text, chunkIndex, contentHash });\n\t\t\t\t}\n\t\t\t\tif (pendingChunks.length === 0) continue;\n\t\t\t\tconst memory = pendingBackfillMemory(row, pendingChunks);\n\t\t\t\tfor (const chunk of pendingChunks) {\n\t\t\t\t\tbatch.push({ memory, chunk });\n\t\t\t\t\tif (batch.length < BACKFILL_INFERENCE_BATCH_SIZE) continue;\n\t\t\t\t\tawait flushBatch();\n\t\t\t\t\tif (!signal?.aborted) continue;\n\t\t\t\t\t// `embedded` includes valid inference discarded for an incomplete memory;\n\t\t\t\t\t// `inserted` counts only memories completed by this batch (also for dry-run).\n\t\t\t\t\treturn { checked, embedded, inserted, skipped };\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (batch.length > 0) await flushBatch();\n\t\t\tif (signal?.aborted) return { checked, embedded, inserted, skipped };\n\t\t}\n\t} finally {\n\t\tmetadata?.close();\n\t\tdeleteBackfillCandidateSnapshot(db, candidateTable);\n\t}\n\n\tif (!dryRun && (inserted > 0 || skipped > 0)) {\n\t\tpersistVectorIdentity(db, client, model);\n\t}\n\treturn { checked, embedded, inserted, skipped };\n}\n\n// ---------------------------------------------------------------------------\n// semanticSearch — vector KNN query\n// ---------------------------------------------------------------------------\n\nexport interface SemanticSearchResult {\n\tid: number;\n\tkind: string;\n\ttitle: string;\n\tbody_text: string;\n\tconfidence: number;\n\ttags_text: string;\n\tmetadata_json: string | null;\n\tcreated_at: string;\n\tupdated_at: string;\n\tsession_id: number;\n\tscore: number;\n\tdistance: number;\n\t/** Structured narrative from observation (carried through from memory_items.*). */\n\tnarrative: string | null;\n\t/** JSON-encoded string array of extracted facts. */\n\tfacts: string | null;\n}\n\nexport { semanticResult };\n\n/**\n * Search for memories by vector similarity using exact sqlite-vec distance.\n * Returns an empty array when embeddings are disabled or unavailable.\n *\n * Matches Python's `_semantic_search()` in store/search.py.\n */\nexport async function semanticSearch(\n\tdb: Database,\n\tquery: string,\n\tlimit: number,\n\tfilters: MemoryFilters | null,\n\tcontext: SemanticSearchScopeContext,\n\tsummarySessionId?: number | null,\n): Promise<SemanticSearchResult[]> {\n\tif (query.trim().length < 3) return [];\n\tif (!hasVectorRows(db)) return [];\n\tconst client = await getEmbeddingClient();\n\tif (!client) return [];\n\tconst searchModels = resolveSemanticSearchModels(\n\t\tdb,\n\t\tresolveEmbeddingClientVectorIdentityLabel(client),\n\t);\n\tif (searchModels.length === 0) return [];\n\tif (!context?.deviceId?.trim()) {\n\t\tthrow new Error(\"semantic_search_scope_context_required\");\n\t}\n\n\tconst embeddings = await embedTexts([query], client);\n\tif (embeddings.length === 0) return [];\n\n\tconst firstEmbedding = embeddings[0];\n\tif (!firstEmbedding) return [];\n\tconst queryEmbedding = serializeFloat32(firstEmbedding);\n\treturn rankSemanticEmbedding(\n\t\tdb,\n\t\tqueryEmbedding,\n\t\tsearchModels,\n\t\tlimit,\n\t\tfilters,\n\t\tcontext,\n\t\tsummarySessionId,\n\t);\n}\n\n/** Internal exact ranking stage shared with the read-only semantic worker. */\nexport function rankSemanticEmbedding(\n\tdb: Database,\n\tqueryEmbedding: Buffer,\n\tsearchModels: string[],\n\tlimit: number,\n\tfilters: MemoryFilters | null,\n\tcontext: SemanticSearchScopeContext,\n\tsummarySessionId?: number | null,\n): SemanticSearchResult[] {\n\tif (searchModels.length === 0) return [];\n\treturn snapshot(db, () =>\n\t\trankSemanticEmbeddingSnapshot(\n\t\t\tdb,\n\t\t\tqueryEmbedding,\n\t\t\tsearchModels,\n\t\t\tlimit,\n\t\t\tfilters,\n\t\t\tcontext,\n\t\t\tsummarySessionId,\n\t\t),\n\t);\n}\n\nfunction rankSemanticEmbeddingSnapshot(\n\tdb: Database,\n\tqueryEmbedding: Buffer,\n\tsearchModels: string[],\n\tlimit: number,\n\tfilters: MemoryFilters | null,\n\tcontext: SemanticSearchScopeContext,\n\tsummarySessionId?: number | null,\n): SemanticSearchResult[] {\n\tconst effectiveLimit = clampSemanticLimit(limit);\n\tconst authorizedIds = buildAuthorizedSemanticMemoryIdsQuery(filters, context, summarySessionId);\n\tconst freshness = pendingVectorFreshness(\n\t\tdb,\n\t\tfilters,\n\t\tcontext,\n\t\tsummarySessionId,\n\t\t\"memory_vectors.\",\n\t);\n\tconst modelPlaceholders = searchModels.map(() => \"?\").join(\", \");\n\n\t// Scope predicates must apply before vector ranking. sqlite-vec's MATCH/k\n\t// query ranks inside the virtual table before joined memory_items filters can\n\t// reliably constrain the candidate set, so use an exact distance scan over the\n\t// already-authorized memory rows instead of widening post-KNN candidates.\n\t// Materialize IDs so vec0 metadata probes do not reopen wide memory rows;\n\t// materialize the limited ranking before fetching the final result payloads.\n\tconst sql = `\n\t\tWITH authorized_ids AS MATERIALIZED (${authorizedIds.sql}),\n\t\tscoped_vectors AS MATERIALIZED (\n\t\t\tSELECT\n\t\t\t\tmemory_vectors.memory_id,\n\t\t\t\tMIN(vec_distance_l2(memory_vectors.embedding, ?)) AS distance\n\t\t\tFROM memory_vectors\n\t\t\tJOIN authorized_ids ON authorized_ids.id = memory_vectors.memory_id\n\t\t\tWHERE memory_vectors.model IN (${modelPlaceholders})\n\t\t\t${freshness.sql}\n\t\t\tGROUP BY memory_vectors.memory_id\n\t\t\tORDER BY distance ASC\n\t\t\tLIMIT ?\n\t\t)\n\t\tSELECT memory_items.*, scoped_vectors.distance\n\t\tFROM scoped_vectors\n\t\tJOIN memory_items ON memory_items.id = scoped_vectors.memory_id\n\t\tORDER BY scoped_vectors.distance ASC\n\t`;\n\n\tconst statement = db.prepare(sql);\n\tconst rows = statement.all(\n\t\t...authorizedIds.params,\n\t\tqueryEmbedding,\n\t\t...searchModels,\n\t\t...freshness.params,\n\t\teffectiveLimit,\n\t) as Array<Record<string, unknown>>;\n\n\treturn rows.map(semanticResult).slice(0, effectiveLimit);\n}\n","import { lstatSync, statSync } from \"node:fs\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport type { Database } from \"./db.js\";\nimport { resolveGitRepositoryIdentity } from \"./project.js\";\nimport { cleanProjectIdentity } from \"./project-identity.js\";\nimport {\n\tloadRepositoryDiscoveryEvidence,\n\ttype RepositoryWorkspaceEvidence,\n\treplaceRepositoryDiscoveryEvidence,\n\trepositoryDiscoveryRevision,\n} from \"./repository-discovery-index.js\";\nimport {\n\tnormalizeRepositoryWorkspaceIdentity,\n\trecordedRepositoryIdentitySetsByWorkspace,\n\trepositoryIdentityMapFromEvidence,\n} from \"./repository-mapping-aliases.js\";\n\nconst POSITIVE_DISCOVERY_TTL_MS = 5_000;\nconst MAX_IDENTITY_MAP_VARIANTS = 8;\n\ninterface DiscoverySnapshot {\n\trevision: number;\n\trows: Array<RepositoryWorkspaceEvidence & { recordedIdentities: string[] }>;\n\tworkspaces: Set<string>;\n\tknownRecorded: Set<string>;\n\tanchors: Map<string, string>;\n\texpiresAt: number;\n\tidentityMaps: Map<string, { identities: Map<string, string>; known: Set<string> }>;\n}\n\nconst snapshots = new WeakMap<Database, DiscoverySnapshot>();\n\nexport const __repositoryDiscoveryCacheTestHooks = {\n\tvariantCount: (db: Database): number => snapshots.get(db)?.identityMaps.size ?? 0,\n};\n\nfunction statFingerprint(path: string): string | null {\n\ttry {\n\t\tconst stat = statSync(path, { bigint: true });\n\t\treturn `${stat.dev}:${stat.ino}:${stat.mtimeNs}`;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction gitMarkerState(path: string): \"missing\" | \"present\" | \"uncertain\" {\n\ttry {\n\t\tlstatSync(join(path, \".git\"));\n\t\treturn \"present\";\n\t} catch (error) {\n\t\treturn (error as NodeJS.ErrnoException).code === \"ENOENT\" ? \"missing\" : \"uncertain\";\n\t}\n}\n\nfunction anchorFingerprint(path: string): string | null {\n\tconst fingerprint = statFingerprint(path);\n\tif (!fingerprint) return null;\n\tlet current = path;\n\twhile (true) {\n\t\tif (gitMarkerState(current) !== \"missing\") return null;\n\t\tconst parent = dirname(current);\n\t\tif (parent === current) return fingerprint;\n\t\tcurrent = parent;\n\t}\n}\n\nfunction anchored(path: string | null): { path: string; mtimeNs: string } | null {\n\tif (!path) return null;\n\tconst mtimeNs = anchorFingerprint(path);\n\treturn mtimeNs ? { path, mtimeNs } : null;\n}\n\nfunction missingGitAnchor(cwd: string): { path: string; mtimeNs: string } | null {\n\tif (!isAbsolute(cwd)) return null;\n\tlet path = resolve(cwd);\n\tlet anchorPath: string | null = null;\n\twhile (true) {\n\t\tif (statFingerprint(path) && !anchorPath) anchorPath = path;\n\t\tif (gitMarkerState(path) !== \"missing\") return null;\n\t\tconst parent = dirname(path);\n\t\tif (parent === path) return anchored(anchorPath);\n\t\tpath = parent;\n\t}\n}\n\nfunction inspectWorkspace(\n\tcwd: string,\n\trecordedIdentities: string[],\n\tcheckedAtMs: number,\n): RepositoryWorkspaceEvidence | null {\n\tif (recordedIdentities.length > 0 || !isAbsolute(cwd)) {\n\t\treturn {\n\t\t\tcwd,\n\t\t\trecordedIdentitiesJson: JSON.stringify(recordedIdentities),\n\t\t\tfilesystemIdentity: null,\n\t\t\tfilesystemAnchor: null,\n\t\t\tanchorMtimeNs: null,\n\t\t\tcheckedAtMs,\n\t\t};\n\t}\n\tconst filesystemIdentity = normalizeRepositoryWorkspaceIdentity(\n\t\tresolveGitRepositoryIdentity(cwd)?.identity,\n\t);\n\tconst anchor = filesystemIdentity ? null : missingGitAnchor(cwd);\n\tif (!filesystemIdentity && !anchor) return null;\n\treturn {\n\t\tcwd,\n\t\trecordedIdentitiesJson: \"[]\",\n\t\tfilesystemIdentity,\n\t\tfilesystemAnchor: anchor?.path ?? null,\n\t\tanchorMtimeNs: anchor?.mtimeNs ?? null,\n\t\tcheckedAtMs,\n\t};\n}\n\nfunction buildSnapshot(db: Database, revision: number): RepositoryWorkspaceEvidence[] | null {\n\tconst recorded = recordedRepositoryIdentitySetsByWorkspace(db);\n\tconst workspaces = db\n\t\t.prepare(\"SELECT DISTINCT cwd FROM sessions WHERE cwd IS NOT NULL AND TRIM(cwd) <> ''\")\n\t\t.pluck()\n\t\t.all() as string[];\n\tconst byCwd = new Map<string, RepositoryWorkspaceEvidence>();\n\tconst now = Date.now();\n\tfor (const workspace of workspaces) {\n\t\tconst cwd = normalizeRepositoryWorkspaceIdentity(workspace);\n\t\tif (!cwd || byCwd.has(cwd)) continue;\n\t\tconst row = inspectWorkspace(cwd, [...(recorded.get(cwd) ?? [])], now);\n\t\tif (!row) return null;\n\t\tbyCwd.set(cwd, row);\n\t}\n\tconst rows = [...byCwd.values()];\n\treturn replaceRepositoryDiscoveryEvidence(db, revision, rows) ? rows : null;\n}\n\nfunction parseRecordedIdentities(row: RepositoryWorkspaceEvidence): string[] | null {\n\tif (!row.cwd || row.cwd !== normalizeRepositoryWorkspaceIdentity(row.cwd)) return null;\n\ttry {\n\t\tconst identities: unknown = JSON.parse(row.recordedIdentitiesJson);\n\t\tif (!Array.isArray(identities) || identities.some((identity) => typeof identity !== \"string\")) {\n\t\t\treturn null;\n\t\t}\n\t\treturn identities;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction recordAnchor(\n\trow: RepositoryWorkspaceEvidence,\n\trecordedIdentities: string[],\n\tanchors: Map<string, string>,\n): boolean {\n\tif (!row.filesystemAnchor || !row.anchorMtimeNs) {\n\t\treturn Boolean(row.filesystemIdentity || recordedIdentities.length > 0 || !isAbsolute(row.cwd));\n\t}\n\tconst previous = anchors.get(row.filesystemAnchor);\n\tif (previous && previous !== row.anchorMtimeNs) return false;\n\tanchors.set(row.filesystemAnchor, row.anchorMtimeNs);\n\treturn true;\n}\n\nfunction parseSnapshot(\n\trevision: number,\n\trows: RepositoryWorkspaceEvidence[],\n): DiscoverySnapshot | null {\n\tconst knownRecorded = new Set<string>();\n\tconst anchors = new Map<string, string>();\n\tlet expiresAt = Number.POSITIVE_INFINITY;\n\tconst parsed = [] as DiscoverySnapshot[\"rows\"];\n\tfor (const row of rows) {\n\t\tconst recordedIdentities = parseRecordedIdentities(row);\n\t\tif (!recordedIdentities) return null;\n\t\tfor (const identity of recordedIdentities) knownRecorded.add(identity);\n\t\tif (row.filesystemIdentity)\n\t\t\texpiresAt = Math.min(expiresAt, row.checkedAtMs + POSITIVE_DISCOVERY_TTL_MS);\n\t\tif (!recordAnchor(row, recordedIdentities, anchors)) return null;\n\t\tparsed.push({ ...row, recordedIdentities });\n\t}\n\treturn {\n\t\trevision,\n\t\trows: parsed,\n\t\tworkspaces: new Set(parsed.map((row) => row.cwd)),\n\t\tknownRecorded,\n\t\tanchors,\n\t\texpiresAt,\n\t\tidentityMaps: new Map(),\n\t};\n}\n\nfunction stillFresh(snapshot: DiscoverySnapshot): boolean {\n\tif (Date.now() >= snapshot.expiresAt) return false;\n\tfor (const [path, mtimeNs] of snapshot.anchors) {\n\t\tif (anchorFingerprint(path) !== mtimeNs) return false;\n\t}\n\treturn true;\n}\n\nfunction currentSnapshot(db: Database, revision: number): DiscoverySnapshot | null {\n\tconst cached = snapshots.get(db);\n\tif (cached?.revision === revision && stillFresh(cached)) return cached;\n\tconst saved = cached?.revision === revision ? null : loadRepositoryDiscoveryEvidence(db);\n\tconst restored = saved ? parseSnapshot(revision, saved) : null;\n\tif (restored && stillFresh(restored)) {\n\t\tsnapshots.set(db, restored);\n\t\treturn restored;\n\t}\n\tlet rows: RepositoryWorkspaceEvidence[] | null;\n\ttry {\n\t\trows = buildSnapshot(db, revision);\n\t} catch {\n\t\treturn null;\n\t}\n\tif (!rows) return null;\n\tconst rebuilt = parseSnapshot(revision, rows);\n\tif (!rebuilt || !stillFresh(rebuilt)) return null;\n\tsnapshots.set(db, rebuilt);\n\treturn rebuilt;\n}\n\nfunction identityMapForSeeds(\n\tsnapshot: DiscoverySnapshot,\n\tseeds: ReadonlySet<string>,\n): { identities: Map<string, string>; known: Set<string> } {\n\tconst key = JSON.stringify([...seeds].toSorted());\n\tconst existing = snapshot.identityMaps.get(key);\n\tif (existing) {\n\t\tsnapshot.identityMaps.delete(key);\n\t\tsnapshot.identityMaps.set(key, existing);\n\t\treturn existing;\n\t}\n\tconst known = new Set(snapshot.knownRecorded);\n\tfor (const seed of seeds) known.add(seed);\n\tconst variant = { identities: repositoryIdentityMapFromEvidence(snapshot.rows, known), known };\n\tif (snapshot.identityMaps.size >= MAX_IDENTITY_MAP_VARIANTS) {\n\t\tconst oldestKey = snapshot.identityMaps.keys().next().value;\n\t\tif (oldestKey !== undefined) snapshot.identityMaps.delete(oldestKey);\n\t}\n\tsnapshot.identityMaps.set(key, variant);\n\treturn variant;\n}\n\nexport function repositoryIdentitiesFromIndexedEvidence(\n\tdb: Database,\n\tknownRepositoryIdentities: Array<string | null | undefined>,\n): { identities: Map<string, string>; known: Set<string>; workspaces: ReadonlySet<string> } | null {\n\tconst revision = repositoryDiscoveryRevision(db);\n\tif (revision == null) return null;\n\tconst snapshot = currentSnapshot(db, revision);\n\tif (!snapshot) return null;\n\tconst seeds = new Set<string>();\n\tfor (const identity of knownRepositoryIdentities) {\n\t\tconst normalized = normalizeRepositoryWorkspaceIdentity(cleanProjectIdentity(identity));\n\t\tif (normalized) seeds.add(normalized);\n\t}\n\tconst { identities, known } = identityMapForSeeds(snapshot, seeds);\n\tif (repositoryDiscoveryRevision(db) !== revision) return null;\n\treturn { identities, known, workspaces: snapshot.workspaces };\n}\n","import { isAbsolute } from \"node:path\";\nimport type { Database } from \"./db.js\";\nimport { resolveGitRepositoryIdentity } from \"./project.js\";\nimport { repositoryIdentitiesFromIndexedEvidence } from \"./repository-discovery-cache.js\";\nimport {\n\tdiscoverKnownRepositoryIdentity,\n\thasConflictingRepositoryMappings,\n\thasRecordedRepositoryWorkspace,\n\tnormalizeRepositoryWorkspaceIdentity,\n\trecordedRepositoryIdentityEvidenceByWorkspace,\n\trepositoryIdentitiesByWorkspace,\n\trepositoryIdentityForWorkspace,\n\twithRepositoryMappingAliasesFromIdentities,\n} from \"./repository-mapping-aliases.js\";\nimport {\n\tLOCAL_DEFAULT_SCOPE_ID,\n\tresolveProjectScope,\n\ttype ScopeMapping,\n} from \"./scope-resolution.js\";\n\ninterface SessionScopeRow {\n\tcwd: string | null;\n\tproject: string | null;\n\tgit_remote: string | null;\n\tgit_branch: string | null;\n\tmetadata_json: string | null;\n}\n\ntype IndexedRepositoryEvidence = NonNullable<\n\tReturnType<typeof repositoryIdentitiesFromIndexedEvidence>\n>;\n\nfunction refreshMappedWorkspace(\n\tindexed: IndexedRepositoryEvidence,\n\tworkspace: string | null | undefined,\n\tcurrentCwd: string | null,\n): void {\n\tconst mapped = normalizeRepositoryWorkspaceIdentity(workspace);\n\tif (!mapped || mapped === currentCwd || indexed.workspaces.has(mapped)) return;\n\tindexed.identities.delete(mapped);\n\tconst identity = discoverKnownRepositoryIdentity(mapped, indexed.known);\n\tif (identity) indexed.identities.set(mapped, identity);\n}\n\nfunction refreshIndexedWorkspaces(\n\tindexed: IndexedRepositoryEvidence,\n\trow: SessionScopeRow | null,\n\tmappedWorkspaces: Array<string | null | undefined>,\n): Set<string> {\n\tconst cwd = normalizeRepositoryWorkspaceIdentity(row?.cwd);\n\tconst recordedWorkspaces = new Set<string>();\n\tif (cwd && hasRecordedRepositoryWorkspace(indexed.identities, cwd)) {\n\t\trecordedWorkspaces.add(cwd);\n\t} else if (cwd) {\n\t\tindexed.identities.delete(cwd);\n\t\tif (isAbsolute(cwd)) {\n\t\t\tconst identity = normalizeRepositoryWorkspaceIdentity(\n\t\t\t\tresolveGitRepositoryIdentity(row?.cwd ?? cwd)?.identity,\n\t\t\t);\n\t\t\tif (identity && indexed.known.has(identity)) indexed.identities.set(cwd, identity);\n\t\t}\n\t}\n\tfor (const workspace of mappedWorkspaces) {\n\t\trefreshMappedWorkspace(indexed, workspace, cwd);\n\t}\n\treturn recordedWorkspaces;\n}\n\ninterface MemoryScopeRow extends SessionScopeRow {\n\tid: number;\n\tsession_id: number;\n\tworkspace_id: string | null;\n\tscope_id: string | null;\n}\n\nexport interface ResolveSessionScopeOptions {\n\tsessionId: number;\n\tworkspaceId?: string | null;\n\texplicitScopeId?: string | null;\n\tlocalDefaultScopeId?: string;\n\t/** Admission checks must not rebuild persisted repository evidence. */\n\treadOnly?: boolean;\n}\n\ninterface RepositoryScopeContext {\n\tallowRepositoryCwdFallback: boolean;\n\tmappings: ScopeMapping[];\n\trepositoryIdentity: string | null;\n}\n\nfunction clean(value: string | null | undefined): string | null {\n\tconst trimmed = value?.trim();\n\treturn trimmed ? trimmed : null;\n}\n\nfunction loadProjectScopeMappings(db: Database): ScopeMapping[] {\n\treturn db\n\t\t.prepare(\n\t\t\t`SELECT id, workspace_identity, project_pattern, scope_id, priority, source, updated_at\n\t\t\t FROM project_scope_mappings\n\t\t\t WHERE scope_id IS NOT NULL AND TRIM(scope_id) != ''\n\t\t\t ORDER BY priority DESC, id ASC`,\n\t\t)\n\t\t.all() as ScopeMapping[];\n}\n\nfunction hasRepositoryConflict(\n\tmappings: ScopeMapping[],\n\trepositoryIdentities: ReadonlyMap<string, string>,\n\trepositoryIdentity: string | null,\n): boolean {\n\treturn Boolean(\n\t\trepositoryIdentity &&\n\t\t\thasConflictingRepositoryMappings(mappings, repositoryIdentities, repositoryIdentity),\n\t);\n}\n\nfunction emptyRepositoryScopeContext(\n\trow: SessionScopeRow | null,\n\tmappings: ScopeMapping[],\n): RepositoryScopeContext {\n\treturn {\n\t\tallowRepositoryCwdFallback: true,\n\t\tmappings,\n\t\trepositoryIdentity: repositoryIdentityForWorkspace(new Map(), {\n\t\t\tcwd: row?.cwd,\n\t\t\tgitRemote: row?.git_remote ?? null,\n\t\t\tmetadataJson: row?.metadata_json,\n\t\t}),\n\t};\n}\n\nfunction addDiscoveredRepositoryWorkspaces(\n\tdb: Database,\n\trepositoryIdentities: Map<string, string>,\n\trepositoryIdentity: string,\n\tmappedWorkspaces: Array<string | null | undefined>,\n): void {\n\tconst discoveredWorkspaces = repositoryIdentitiesByWorkspace(db, {\n\t\tknownRepositoryIdentities: [repositoryIdentity, ...mappedWorkspaces],\n\t});\n\tfor (const [workspace, identity] of discoveredWorkspaces) {\n\t\tif (identity === repositoryIdentity) repositoryIdentities.set(workspace, identity);\n\t}\n}\n\nfunction scopeRepositoryEvidence(\n\tdb: Database,\n\trow: SessionScopeRow | null,\n\tmappedWorkspaces: Array<string | null | undefined>,\n\tmappingIdentitySeeds: Array<string | null | undefined>,\n\toptions: { readOnly?: boolean } = {},\n) {\n\tconst legacy = () => ({\n\t\tevidence: recordedRepositoryIdentityEvidenceByWorkspace(db, [row?.cwd, ...mappedWorkspaces], {\n\t\t\tfreshWorkspaces: [row?.cwd],\n\t\t}),\n\t\tindexed: false,\n\t});\n\t// Authorization must not rebuild the persisted discovery cache before it permits a write.\n\tif (options.readOnly) return legacy();\n\tconst indexed = repositoryIdentitiesFromIndexedEvidence(db, mappingIdentitySeeds);\n\tif (!indexed) return legacy();\n\tconst recordedWorkspaces = refreshIndexedWorkspaces(indexed, row, mappedWorkspaces);\n\treturn {\n\t\tevidence: { byWorkspace: indexed.identities, recordedWorkspaces },\n\t\tindexed: true,\n\t};\n}\n\nfunction discoverCurrentWorkspace(\n\tcwd: string | null,\n\trepositoryIdentities: Map<string, string>,\n\trecordedWorkspaces: ReadonlySet<string>,\n\tmappingIdentitySeeds: Array<string | null | undefined>,\n): void {\n\tif (!cwd || recordedWorkspaces.has(cwd)) return;\n\tconst known = new Set(\n\t\t[\n\t\t\t...repositoryIdentities.values(),\n\t\t\t...mappingIdentitySeeds.map((identity) => normalizeRepositoryWorkspaceIdentity(identity)),\n\t\t].filter((identity): identity is string => identity != null),\n\t);\n\tconst identity = discoverKnownRepositoryIdentity(cwd, known);\n\tif (identity) repositoryIdentities.set(cwd, identity);\n}\n\nfunction mappingIdentitySeeds(mappings: ScopeMapping[]) {\n\treturn mappings.flatMap((mapping) => [mapping.workspace_identity, mapping.project_pattern]);\n}\n\nfunction repositoryScopeContext(\n\tdb: Database,\n\trow: SessionScopeRow | null,\n\tmappings: ScopeMapping[],\n\toptions: { readOnly?: boolean } = {},\n): RepositoryScopeContext {\n\tif (mappings.length === 0) return emptyRepositoryScopeContext(row, mappings);\n\tconst mappedWorkspaces = mappings.map((mapping) => mapping.workspace_identity);\n\tconst identitySeeds = mappingIdentitySeeds(mappings);\n\tconst { evidence, indexed } = scopeRepositoryEvidence(\n\t\tdb,\n\t\trow,\n\t\tmappedWorkspaces,\n\t\tidentitySeeds,\n\t\toptions,\n\t);\n\tconst repositoryIdentities = evidence.byWorkspace;\n\tconst cwd = normalizeRepositoryWorkspaceIdentity(row?.cwd);\n\tconst ambiguousCwd = Boolean(\n\t\tcwd && evidence.recordedWorkspaces.has(cwd) && !repositoryIdentities.has(cwd),\n\t);\n\tif (!indexed)\n\t\tdiscoverCurrentWorkspace(cwd, repositoryIdentities, evidence.recordedWorkspaces, identitySeeds);\n\tconst repositoryIdentity = repositoryIdentityForWorkspace(repositoryIdentities, {\n\t\tcwd: row?.cwd,\n\t\tgitRemote: row?.git_remote ?? null,\n\t\tmetadataJson: row?.metadata_json,\n\t});\n\tif (repositoryIdentity && !indexed) {\n\t\taddDiscoveredRepositoryWorkspaces(db, repositoryIdentities, repositoryIdentity, identitySeeds);\n\t}\n\tconst repositoryConflict = hasRepositoryConflict(\n\t\tmappings,\n\t\trepositoryIdentities,\n\t\trepositoryIdentity,\n\t);\n\tconst unresolvedAmbiguousCwd = ambiguousCwd && !repositoryIdentity;\n\tlet effectiveMappings = mappings;\n\tif (repositoryConflict || unresolvedAmbiguousCwd) {\n\t\teffectiveMappings = [];\n\t} else if (!ambiguousCwd) {\n\t\teffectiveMappings = withRepositoryMappingAliasesFromIdentities(mappings, repositoryIdentities, {\n\t\t\tdiscoverFilesystem: true,\n\t\t});\n\t}\n\treturn {\n\t\tallowRepositoryCwdFallback: !ambiguousCwd && !repositoryConflict,\n\t\tmappings: effectiveMappings,\n\t\trepositoryIdentity,\n\t};\n}\n\nfunction loadSessionScopeRow(db: Database, sessionId: number): SessionScopeRow | null {\n\tconst row = db\n\t\t.prepare(\n\t\t\t\"SELECT cwd, project, git_remote, git_branch, metadata_json FROM sessions WHERE id = ? LIMIT 1\",\n\t\t)\n\t\t.get(sessionId) as SessionScopeRow | undefined;\n\treturn row ?? null;\n}\n\nexport function resolveSessionScopeId(db: Database, options: ResolveSessionScopeOptions): string {\n\tconst explicitScopeId = clean(options.explicitScopeId);\n\tif (explicitScopeId) return explicitScopeId;\n\tconst session = loadSessionScopeRow(db, options.sessionId);\n\tconst context = repositoryScopeContext(db, session, loadProjectScopeMappings(db), {\n\t\treadOnly: options.readOnly,\n\t});\n\tconst result = resolveProjectScope({\n\t\tallowRepositoryCwdFallback: context.allowRepositoryCwdFallback,\n\t\tgitRemote: session?.git_remote ?? null,\n\t\tgitBranch: session?.git_branch ?? null,\n\t\trepositoryIdentity: context.repositoryIdentity,\n\t\tcwd: session?.cwd ?? null,\n\t\tproject: session?.project ?? null,\n\t\tworkspaceId: options.workspaceId ?? null,\n\t\tlocalDefaultScopeId: options.localDefaultScopeId ?? LOCAL_DEFAULT_SCOPE_ID,\n\t\tmappings: context.mappings,\n\t});\n\treturn result.scopeId;\n}\n\nfunction loadMemoryScopeRow(db: Database, memoryId: number): MemoryScopeRow | null {\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT\n\t\t\t\tmi.id,\n\t\t\t\tmi.session_id,\n\t\t\t\tmi.workspace_id,\n\t\t\t\tmi.scope_id,\n\t\t\t\ts.cwd,\n\t\t\t\ts.project,\n\t\t\t\ts.git_remote,\n\t\t\t\ts.git_branch,\n\t\t\t\ts.metadata_json\n\t\t\t FROM memory_items mi\n\t\t\t LEFT JOIN sessions s ON s.id = mi.session_id\n\t\t\t WHERE mi.id = ?\n\t\t\t LIMIT 1`,\n\t\t)\n\t\t.get(memoryId) as MemoryScopeRow | undefined;\n\treturn row ?? null;\n}\n\n/** Resolve the eventual stamp without writing schema, caches, keys, or memory rows. */\nexport function resolveMemoryScopeId(\n\tdb: Database,\n\tmemoryId: number,\n\toptions: { mappings?: ScopeMapping[] } = {},\n): string | null {\n\tconst row = loadMemoryScopeRow(db, memoryId);\n\tif (!row) return null;\n\tconst existingScopeId = clean(row.scope_id);\n\tif (existingScopeId) return existingScopeId;\n\tconst context = repositoryScopeContext(\n\t\tdb,\n\t\trow,\n\t\toptions.mappings ?? loadProjectScopeMappings(db),\n\t\t{ readOnly: true },\n\t);\n\tconst result = resolveProjectScope({\n\t\tallowRepositoryCwdFallback: context.allowRepositoryCwdFallback,\n\t\tgitRemote: row.git_remote,\n\t\tgitBranch: row.git_branch,\n\t\trepositoryIdentity: context.repositoryIdentity,\n\t\tcwd: row.cwd,\n\t\tproject: row.project,\n\t\tworkspaceId: row.workspace_id,\n\t\tlocalDefaultScopeId: LOCAL_DEFAULT_SCOPE_ID,\n\t\tmappings: context.mappings,\n\t});\n\treturn result.scopeId;\n}\n\nexport function ensureMemoryScopeId(db: Database, memoryId: number): string | null {\n\tconst scopeId = resolveMemoryScopeId(db, memoryId);\n\tif (!scopeId) return null;\n\tconst row = loadMemoryScopeRow(db, memoryId);\n\tif (clean(row?.scope_id)) return scopeId;\n\tdb.prepare(\n\t\t`UPDATE memory_items\n\t\t SET scope_id = ?\n\t\t WHERE id = ?\n\t\t AND (scope_id IS NULL OR TRIM(scope_id) = '')`,\n\t).run(scopeId, memoryId);\n\treturn scopeId;\n}\n","import type { Database } from \"./db.js\";\nimport { hasMemoryScopeRetirement, isMemoryScopeRetired } from \"./memory-scope-retirement.js\";\n\n/** Snapshot payloads have no op envelope: history requires their own explicit scope. */\nexport function retirementAllowsSnapshot(\n\tdb: Database,\n\tentityId: string,\n\tpayload: Record<string, unknown>,\n\tenvelopeScope: string | null,\n): boolean {\n\tconst canonicalId = entityId.trim();\n\tif (!hasMemoryScopeRetirement(db, canonicalId)) return true;\n\tif (entityId !== canonicalId) return false;\n\tconst scope = typeof payload.scope_id === \"string\" ? payload.scope_id.trim() : \"\";\n\tif (!scope || scope !== envelopeScope || isMemoryScopeRetired(db, entityId, scope)) return false;\n\tconst metadata = payload.metadata_json;\n\tif (!metadata || typeof metadata !== \"object\" || Array.isArray(metadata)) return true;\n\tconst metadataScope = (metadata as Record<string, unknown>).scope_id;\n\treturn (\n\t\tmetadataScope == null || (typeof metadataScope === \"string\" && metadataScope.trim() === scope)\n\t);\n}\n","import type { Database } from \"./db.js\";\nimport { derivePolicyTeamDeviceEligibility } from \"./policy-team-device-eligibility.js\";\nimport { denyOverlayRow } from \"./recipient-policy-deny-overlay.js\";\n\nimport {\n\tisStrictRecipientPolicyId,\n\tisStrictRecipientPolicyProjectIdentity,\n\tlegacyRecipientPolicyDigest,\n} from \"./recipient-policy-identifiers.js\";\nimport {\n\tcanonicalRepositoryProjectIdentity,\n\trepositoryIdentitiesByWorkspace,\n} from \"./repository-mapping-aliases.js\";\n\nexport { getAnyRecipientPolicyDenyOverlayForScopeDevice } from \"./recipient-policy-deny-overlay.js\";\n\n// Preserve the established module-level import path while sharing one grammar.\nexport { isStrictRecipientPolicyId };\n\nexport type RecipientPolicyAuthorityState = \"legacy\" | \"eligible\" | \"active\" | \"rolled_back\";\n\nexport type RecipientPolicyDerivationBlockCode =\n\t| \"canonical_project_identity_invalid\"\n\t| \"project_recipient_invalid\"\n\t| \"identity_missing\"\n\t| \"identity_not_active\"\n\t| \"identity_merged\"\n\t| \"team_missing\"\n\t| \"team_not_active\"\n\t| \"team_membership_invalid\"\n\t| \"team_membership_mode_invalid\"\n\t| \"team_device_eligibility_mode_invalid\"\n\t| \"team_device_decision_invalid\"\n\t| \"team_member_identity_missing\"\n\t| \"team_member_identity_not_active\"\n\t| \"team_member_identity_merged\"\n\t| \"identity_device_invalid\"\n\t| \"device_identity_conflict\";\n\n// Keep first-block reporting stable and security-oriented rather than lexical.\nconst DERIVATION_BLOCK_PRECEDENCE: Record<RecipientPolicyDerivationBlockCode, number> = {\n\tcanonical_project_identity_invalid: 0,\n\tproject_recipient_invalid: 1,\n\tidentity_missing: 2,\n\tidentity_merged: 3,\n\tidentity_not_active: 4,\n\tteam_missing: 5,\n\tteam_not_active: 6,\n\tteam_device_eligibility_mode_invalid: 7,\n\tteam_membership_invalid: 8,\n\tteam_membership_mode_invalid: 9,\n\tteam_member_identity_missing: 10,\n\tteam_member_identity_merged: 11,\n\tteam_member_identity_not_active: 12,\n\tteam_device_decision_invalid: 13,\n\tdevice_identity_conflict: 14,\n\tidentity_device_invalid: 15,\n};\n\nexport interface RecipientPolicyDerivationIdentity {\n\tidentityId: string;\n\tstatus: string;\n\tmergedIntoIdentityId?: string | null;\n}\n\nexport interface RecipientPolicyDerivationTeam {\n\tteamId: string;\n\tstatus: string;\n\tdeviceEligibilityMode?: string;\n}\n\nexport interface RecipientPolicyDerivationTeamMembership {\n\tteamId: string;\n\tidentityId: string;\n\tstatus: string;\n}\n\nexport interface RecipientPolicyDerivationIdentityDevice {\n\tidentityId: string;\n\tdeviceId: string;\n\tstatus: string;\n\tassignmentVersion?: number;\n}\n\nexport interface RecipientPolicyDerivationTeamDeviceDecision {\n\tteamId: string;\n\tdeviceId: string;\n\tdecision: string;\n\tassignmentVersion: number;\n}\n\nexport interface RecipientPolicyDerivationProjectRecipient {\n\tcanonicalProjectIdentity: string;\n\trecipientKind: string;\n\trecipientId: string;\n\tstatus: string;\n}\n\nexport interface RecipientPolicyEffectiveDeviceSource {\n\tkind: \"direct_identity\" | \"team_membership\";\n\tteamId?: string;\n}\n\nexport interface StrictRecipientPolicyEffectiveDevice {\n\tcanonicalProjectIdentity: string;\n\tidentityId: string;\n\tdeviceId: string;\n\tsources: RecipientPolicyEffectiveDeviceSource[];\n}\n\nexport interface RecipientPolicyDerivationBlock {\n\tcode: RecipientPolicyDerivationBlockCode;\n\treferenceId: string;\n}\n\nexport interface DeriveRecipientPolicyEffectiveDevicesInput {\n\tcanonicalProjectIdentity: string;\n\tprojectRecipients: RecipientPolicyDerivationProjectRecipient[];\n\tidentities: RecipientPolicyDerivationIdentity[];\n\tteams: RecipientPolicyDerivationTeam[];\n\tteamMemberships: RecipientPolicyDerivationTeamMembership[];\n\tteamDeviceDecisions?: RecipientPolicyDerivationTeamDeviceDecision[];\n\tidentityDevices: RecipientPolicyDerivationIdentityDevice[];\n}\n\nexport interface StrictRecipientPolicyEffectiveDeviceDerivation {\n\tcanonicalProjectIdentity: string;\n\tstatus: \"eligible\" | \"blocked\";\n\tdevices: StrictRecipientPolicyEffectiveDevice[];\n\tblocked: RecipientPolicyDerivationBlock[];\n\tdesiredDevicesDigest: string;\n}\n\nexport interface RecipientPolicyAuthorityStateRecord {\n\tcanonicalProjectIdentity: string;\n\tauthorityState: RecipientPolicyAuthorityState;\n\tgeneration: number;\n\tdesiredDevicesDigest: string | null;\n\tcurrentDevicesDigest: string | null;\n\tstableParityEvidenceDigest: string | null;\n\tstableParityPassedAt: string | null;\n\tfreshSnapshotFingerprint: string | null;\n\tfreshSnapshotObservedAt: string | null;\n\tsafeErrorCode: string | null;\n\tstateChangedAt: string;\n\tlastErrorAt: string | null;\n\tattemptCount: number;\n\tlastAttemptAt: string | null;\n\tlastCompletedAt: string | null;\n\tleaseOwner: string | null;\n\tleaseAcquiredAt: string | null;\n\tleaseExpiresAt: string | null;\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\nexport interface UpsertRecipientPolicyAuthorityObservationInput {\n\tcanonicalProjectIdentity: string;\n\tgeneration: number;\n\tdesiredDevicesDigest: string;\n\tcurrentDevicesDigest: string | null;\n\tfreshSnapshotFingerprint: string | null;\n\tfreshSnapshotObservedAt: string | null;\n\tnow: string;\n}\n\nexport interface RecordRecipientPolicyAuthorityExecutionInput {\n\tcanonicalProjectIdentity: string;\n\tgeneration: number;\n\tattemptCount: number;\n\tlastAttemptAt: string | null;\n\tlastCompletedAt: string | null;\n\tsafeErrorCode: string | null;\n\tlastErrorAt: string | null;\n\tleaseOwner: string | null;\n\tleaseAcquiredAt: string | null;\n\tleaseExpiresAt: string | null;\n\tupdatedAt: string;\n}\n\nexport interface EnsureRecipientPolicyReconciliationStepInput {\n\tcanonicalProjectIdentity: string;\n\tgeneration: number;\n\tstepKey: string;\n\tpayloadDigest: string;\n\tnow: string;\n}\n\nexport interface RecordRecipientPolicyReconciliationStepStateInput {\n\tcanonicalProjectIdentity: string;\n\tgeneration: number;\n\tstepKey: string;\n\teffectId: string;\n\tstatus: \"pending\" | \"running\" | \"waiting\" | \"completed\" | \"failed\";\n\tattemptCount: number;\n\tstartedAt: string | null;\n\tcompletedAt: string | null;\n\tlastAttemptAt: string | null;\n\tsafeErrorCode: string | null;\n\terrorAt: string | null;\n\tleaseOwner: string | null;\n\tleaseAcquiredAt: string | null;\n\tleaseExpiresAt: string | null;\n\tupdatedAt: string;\n}\n\nexport interface RecipientPolicyReconciliationStepRecord {\n\tcanonicalProjectIdentity: string;\n\tgeneration: number;\n\tstepKey: string;\n\teffectId: string;\n\tpayloadDigest: string;\n\tstatus: string;\n\tattemptCount: number;\n\tstartedAt: string | null;\n\tcompletedAt: string | null;\n\tlastAttemptAt: string | null;\n\tsafeErrorCode: string | null;\n\terrorAt: string | null;\n\tleaseOwner: string | null;\n\tleaseAcquiredAt: string | null;\n\tleaseExpiresAt: string | null;\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\nexport interface PendingRecipientPolicyRevocationRefreshStep {\n\tgeneration: number;\n\tstepKey: string;\n}\n\nexport interface PendingRecipientPolicyRefreshStep {\n\tgeneration: number;\n\tstepKey: string;\n}\n\nexport interface PruneRecipientPolicyReconciliationStepsInput {\n\tcanonicalProjectIdentity: string;\n\tretainCompletedPerKind?: number;\n}\n\nexport interface PruneSupersededRecipientPolicyCapabilityStepsInput {\n\tcanonicalProjectIdentity: string;\n\tactiveGeneration: number;\n\tactivePassKey: string;\n}\n\nexport interface RecipientPolicyDenyOverlayRecord {\n\tcanonicalProjectIdentity: string;\n\tscopeId: string;\n\tdeviceId: string;\n\tgeneration: number;\n\treasonCode: string;\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\nconst KNOWN_DEVICE_STATUSES = new Set([\"active\", \"revoked\"]);\nconst DEFAULT_COMPLETED_STEP_RETENTION_PER_KIND = 256;\nconst MAX_PENDING_REVOCATION_REFRESH_STEPS = 64;\nconst MAX_RECONCILIATION_STEP_KEY_UTF16_UNITS = 1_024;\nconst RECONCILIATION_STEP_KEY_CONTROL_OR_FORMAT_CHARACTER = /[\\p{Cc}\\p{Cf}]/u;\nconst PRUNABLE_COMPLETED_STEP_PATTERNS = [\"capability:*\", \"refresh:*\"] as const;\nexport const PENDING_RECIPIENT_POLICY_REVOCATION_REFRESH_STEPS_SQL = `SELECT generation, step_key FROM recipient_policy_reconciliation_steps\n\t WHERE canonical_project_identity = ?\n\t AND step_key GLOB 'refresh-after-revocations-v2:*'\n\t AND status IN ('pending', 'running', 'failed')\n\t ORDER BY generation, step_key\n\t LIMIT ?`;\nconst KNOWN_RECIPIENT_STATUSES = new Set([\"active\", \"revoked\"]);\n\nfunction compareText(left: string, right: string): number {\n\treturn left < right ? -1 : left > right ? 1 : 0;\n}\n\nfunction isStrictRecipientPolicyReconciliationStepKey(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue === value.trim() &&\n\t\tvalue.length <= MAX_RECONCILIATION_STEP_KEY_UTF16_UNITS &&\n\t\t!RECONCILIATION_STEP_KEY_CONTROL_OR_FORMAT_CHARACTER.test(value)\n\t);\n}\n\nconst digest = legacyRecipientPolicyDigest;\n\nfunction sourceKey(source: RecipientPolicyEffectiveDeviceSource): string {\n\treturn source.kind === \"direct_identity\" ? source.kind : `${source.kind}\\u0000${source.teamId}`;\n}\n\nfunction block(\n\tblocked: Map<string, RecipientPolicyDerivationBlock>,\n\tcode: RecipientPolicyDerivationBlockCode,\n\treferenceId: string,\n): void {\n\tblocked.set(`${code}\\u0000${referenceId}`, { code, referenceId });\n}\n\nfunction activeIdentityCode(\n\tidentity: RecipientPolicyDerivationIdentity | undefined,\n\tmissing: RecipientPolicyDerivationBlockCode,\n\tinactive: RecipientPolicyDerivationBlockCode,\n\tmerged: RecipientPolicyDerivationBlockCode,\n): RecipientPolicyDerivationBlockCode | null {\n\tif (!identity) return missing;\n\tif (identity.status === \"merged\" || identity.mergedIntoIdentityId) return merged;\n\tif (identity.status !== \"active\") return inactive;\n\treturn null;\n}\n\nfunction addEffectiveDevice(\n\teffective: Map<string, StrictRecipientPolicyEffectiveDevice>,\n\tdeviceOwners: Map<string, string>,\n\tprojectId: string,\n\tidentityId: string,\n\tdeviceId: string,\n\tsource: RecipientPolicyEffectiveDeviceSource,\n\tblocked: Map<string, RecipientPolicyDerivationBlock>,\n): void {\n\tconst owner = deviceOwners.get(deviceId);\n\tif (owner && owner !== identityId) {\n\t\tblock(blocked, \"device_identity_conflict\", deviceId);\n\t\treturn;\n\t}\n\tdeviceOwners.set(deviceId, identityId);\n\tconst current = effective.get(deviceId);\n\tconst sources = new Map((current?.sources ?? []).map((item) => [sourceKey(item), item]));\n\tsources.set(sourceKey(source), source);\n\teffective.set(deviceId, {\n\t\tcanonicalProjectIdentity: projectId,\n\t\tidentityId,\n\t\tdeviceId,\n\t\tsources: [...sources.values()].toSorted((left, right) =>\n\t\t\tcompareText(sourceKey(left), sourceKey(right)),\n\t\t),\n\t});\n}\n\nexport function recipientPolicyDevicesDigest(\n\tdevices: readonly StrictRecipientPolicyEffectiveDevice[],\n): string {\n\treturn digest(\n\t\t\"recipient-policy-devices-v1\",\n\t\tdevices\n\t\t\t.toSorted(\n\t\t\t\t(left, right) =>\n\t\t\t\t\tcompareText(left.canonicalProjectIdentity, right.canonicalProjectIdentity) ||\n\t\t\t\t\tcompareText(left.deviceId, right.deviceId) ||\n\t\t\t\t\tcompareText(left.identityId, right.identityId),\n\t\t\t)\n\t\t\t.map((device) => ({\n\t\t\t\tcanonicalProjectIdentity: device.canonicalProjectIdentity,\n\t\t\t\tidentityId: device.identityId,\n\t\t\t\tdeviceId: device.deviceId,\n\t\t\t\tsources: device.sources.toSorted((left, right) =>\n\t\t\t\t\tcompareText(sourceKey(left), sourceKey(right)),\n\t\t\t\t),\n\t\t\t})),\n\t);\n}\n\nexport function deriveRecipientPolicyEffectiveDevices(\n\tinput: DeriveRecipientPolicyEffectiveDevicesInput,\n): StrictRecipientPolicyEffectiveDeviceDerivation {\n\tconst blocked = new Map<string, RecipientPolicyDerivationBlock>();\n\tif (!isStrictRecipientPolicyProjectIdentity(input.canonicalProjectIdentity)) {\n\t\tblock(blocked, \"canonical_project_identity_invalid\", input.canonicalProjectIdentity);\n\t}\n\tconst identities = new Map(input.identities.map((identity) => [identity.identityId, identity]));\n\tconst eligibilityIdentities = input.identities.map((identity) => ({\n\t\tidentityId: identity.identityId,\n\t\tstatus: identity.status,\n\t\tmergedIntoIdentityId: identity.mergedIntoIdentityId ?? null,\n\t}));\n\tconst teams = new Map(input.teams.map((team) => [team.teamId, team]));\n\tconst membershipsByTeam = new Map<string, RecipientPolicyDerivationTeamMembership[]>();\n\tfor (const membership of input.teamMemberships) {\n\t\tconst current = membershipsByTeam.get(membership.teamId) ?? [];\n\t\tcurrent.push(membership);\n\t\tmembershipsByTeam.set(membership.teamId, current);\n\t}\n\tconst decisionsByTeam = new Map<string, RecipientPolicyDerivationTeamDeviceDecision[]>();\n\tfor (const decision of input.teamDeviceDecisions ?? []) {\n\t\tconst current = decisionsByTeam.get(decision.teamId) ?? [];\n\t\tcurrent.push(decision);\n\t\tdecisionsByTeam.set(decision.teamId, current);\n\t}\n\tconst devicesByIdentity = new Map<string, RecipientPolicyDerivationIdentityDevice[]>();\n\tfor (const device of input.identityDevices) {\n\t\tconst current = devicesByIdentity.get(device.identityId) ?? [];\n\t\tcurrent.push(device);\n\t\tdevicesByIdentity.set(device.identityId, current);\n\t}\n\tconst legacyEligibilityDevices = input.identityDevices.map((device) => ({\n\t\t...device,\n\t\tassignmentVersion: device.assignmentVersion ?? 0,\n\t}));\n\tconst reviewedEligibilityDevices = input.identityDevices.map((device) => ({\n\t\t...device,\n\t\t// Reviewed access requires present assignment evidence. NaN deliberately\n\t\t// fails the shared safe-integer validation instead of treating omission as v0.\n\t\tassignmentVersion: device.assignmentVersion ?? Number.NaN,\n\t}));\n\tconst effective = new Map<string, StrictRecipientPolicyEffectiveDevice>();\n\tconst deviceOwners = new Map<string, string>();\n\tconst expandIdentity = (\n\t\tidentityId: string,\n\t\tsource: RecipientPolicyEffectiveDeviceSource,\n\t\tcodes: readonly [\n\t\t\tRecipientPolicyDerivationBlockCode,\n\t\t\tRecipientPolicyDerivationBlockCode,\n\t\t\tRecipientPolicyDerivationBlockCode,\n\t\t],\n\t\tallowedDeviceIds?: ReadonlySet<string>,\n\t): void => {\n\t\tconst identityCode = activeIdentityCode(identities.get(identityId), ...codes);\n\t\tif (identityCode) {\n\t\t\tblock(blocked, identityCode, identityId);\n\t\t\treturn;\n\t\t}\n\t\tfor (const device of devicesByIdentity.get(identityId) ?? []) {\n\t\t\tif (!KNOWN_DEVICE_STATUSES.has(device.status)) {\n\t\t\t\tblock(blocked, \"identity_device_invalid\", device.deviceId);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (device.status !== \"active\") continue;\n\t\t\tif (allowedDeviceIds && !allowedDeviceIds.has(device.deviceId)) continue;\n\t\t\tif (\n\t\t\t\t!isStrictRecipientPolicyId(device.identityId) ||\n\t\t\t\t!isStrictRecipientPolicyId(device.deviceId)\n\t\t\t) {\n\t\t\t\tblock(blocked, \"identity_device_invalid\", device.deviceId);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\taddEffectiveDevice(\n\t\t\t\teffective,\n\t\t\t\tdeviceOwners,\n\t\t\t\tinput.canonicalProjectIdentity,\n\t\t\t\tidentityId,\n\t\t\t\tdevice.deviceId,\n\t\t\t\tsource,\n\t\t\t\tblocked,\n\t\t\t);\n\t\t}\n\t};\n\tconst projectRecipients = input.projectRecipients.filter(\n\t\t(recipient) => recipient.canonicalProjectIdentity === input.canonicalProjectIdentity,\n\t);\n\tfor (const recipient of projectRecipients) {\n\t\tif (!KNOWN_RECIPIENT_STATUSES.has(recipient.status)) {\n\t\t\tblock(blocked, \"project_recipient_invalid\", recipient.recipientId);\n\t\t\tcontinue;\n\t\t}\n\t\tif (recipient.status !== \"active\") continue;\n\t\tif (!isStrictRecipientPolicyId(recipient.recipientId)) {\n\t\t\tblock(blocked, \"project_recipient_invalid\", recipient.recipientId);\n\t\t\tcontinue;\n\t\t}\n\t\tif (recipient.recipientKind === \"identity\") {\n\t\t\texpandIdentity(recipient.recipientId, { kind: \"direct_identity\" }, [\n\t\t\t\t\"identity_missing\",\n\t\t\t\t\"identity_not_active\",\n\t\t\t\t\"identity_merged\",\n\t\t\t]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (recipient.recipientKind !== \"team\") {\n\t\t\tblock(blocked, \"project_recipient_invalid\", recipient.recipientId);\n\t\t\tcontinue;\n\t\t}\n\t\tconst team = teams.get(recipient.recipientId);\n\t\tif (!team) {\n\t\t\tblock(blocked, \"team_missing\", recipient.recipientId);\n\t\t\tcontinue;\n\t\t}\n\t\tif (team.status !== \"active\") {\n\t\t\tblock(blocked, \"team_not_active\", recipient.recipientId);\n\t\t\tcontinue;\n\t\t}\n\t\tconst memberships = membershipsByTeam.get(team.teamId) ?? [];\n\t\tfor (const membership of memberships) {\n\t\t\tif (\n\t\t\t\t!isStrictRecipientPolicyId(membership.teamId) ||\n\t\t\t\t!isStrictRecipientPolicyId(membership.identityId)\n\t\t\t) {\n\t\t\t\tblock(blocked, \"team_membership_invalid\", `${membership.teamId}:${membership.identityId}`);\n\t\t\t}\n\t\t}\n\t\tconst eligibility = derivePolicyTeamDeviceEligibility({\n\t\t\tteamId: team.teamId,\n\t\t\tmode: team.deviceEligibilityMode ?? \"person_all_devices\",\n\t\t\tmemberships,\n\t\t\tidentities: eligibilityIdentities,\n\t\t\tdevices:\n\t\t\t\tteam.deviceEligibilityMode === \"reviewed_allowlist\"\n\t\t\t\t\t? reviewedEligibilityDevices\n\t\t\t\t\t: legacyEligibilityDevices,\n\t\t\tdecisions: decisionsByTeam.get(team.teamId) ?? [],\n\t\t});\n\t\tfor (const item of eligibility.blocked) block(blocked, item.code, item.referenceId);\n\t\tif (eligibility.status === \"blocked\") continue;\n\t\tconst eligibleDeviceIds = new Set(eligibility.eligibleDeviceIds);\n\t\tfor (const identityId of eligibility.activeMemberIdentityIds) {\n\t\t\texpandIdentity(\n\t\t\t\tidentityId,\n\t\t\t\t{ kind: \"team_membership\", teamId: team.teamId },\n\t\t\t\t[\n\t\t\t\t\t\"team_member_identity_missing\",\n\t\t\t\t\t\"team_member_identity_not_active\",\n\t\t\t\t\t\"team_member_identity_merged\",\n\t\t\t\t],\n\t\t\t\teligibleDeviceIds,\n\t\t\t);\n\t\t}\n\t}\n\tconst blockedItems = [...blocked.values()].toSorted(\n\t\t(left, right) =>\n\t\t\tDERIVATION_BLOCK_PRECEDENCE[left.code] - DERIVATION_BLOCK_PRECEDENCE[right.code] ||\n\t\t\tcompareText(left.referenceId, right.referenceId),\n\t);\n\tconst devices = [...effective.values()].toSorted(\n\t\t(left, right) =>\n\t\t\tcompareText(left.deviceId, right.deviceId) || compareText(left.identityId, right.identityId),\n\t);\n\tconst grantCandidates = blockedItems.length === 0 ? devices : [];\n\treturn {\n\t\tcanonicalProjectIdentity: input.canonicalProjectIdentity,\n\t\tstatus: blockedItems.length === 0 ? \"eligible\" : \"blocked\",\n\t\tdevices: grantCandidates,\n\t\tblocked: blockedItems,\n\t\tdesiredDevicesDigest: recipientPolicyDevicesDigest(grantCandidates),\n\t};\n}\n\ninterface StoredProjectRecipientRow {\n\tcanonical_project_identity: string;\n\trecipient_kind: string;\n\trecipient_id: string;\n\tstatus: string;\n\tupdated_at: string;\n}\n\nfunction canonicalProjectRecipientRows(\n\tdb: Database,\n\tcanonicalProjectIdentity: string,\n): StoredProjectRecipientRow[] {\n\tconst repositoryIdentities = repositoryIdentitiesByWorkspace(db);\n\tconst canonicalIdentity = canonicalRepositoryProjectIdentity(\n\t\trepositoryIdentities,\n\t\tcanonicalProjectIdentity,\n\t);\n\tconst aliases = [\n\t\t...new Set([\n\t\t\tcanonicalIdentity,\n\t\t\tcanonicalProjectIdentity,\n\t\t\t...[...repositoryIdentities]\n\t\t\t\t.filter(([, identity]) => identity === canonicalIdentity)\n\t\t\t\t.map(([workspace]) => workspace),\n\t\t]),\n\t];\n\tconst rows = db\n\t\t.prepare(\n\t\t\t`SELECT canonical_project_identity, recipient_kind, recipient_id, status, updated_at\n\t\t\t FROM project_recipients\n\t\t\t WHERE canonical_project_identity IN (SELECT value FROM json_each(?))\n\t\t\t ORDER BY recipient_kind, recipient_id`,\n\t\t)\n\t\t.all(JSON.stringify(aliases)) as StoredProjectRecipientRow[];\n\tconst rowsByRecipient = new Map<string, StoredProjectRecipientRow>();\n\tfor (const row of rows) {\n\t\tconst rowCanonicalIdentity = canonicalRepositoryProjectIdentity(\n\t\t\trepositoryIdentities,\n\t\t\trow.canonical_project_identity,\n\t\t);\n\t\tif (rowCanonicalIdentity !== canonicalIdentity) continue;\n\t\tconst key = `${row.recipient_kind}\\u0000${row.recipient_id}`;\n\t\tconst current = rowsByRecipient.get(key);\n\t\tif (!current) {\n\t\t\trowsByRecipient.set(key, row);\n\t\t\tcontinue;\n\t\t}\n\t\tconst currentIsCanonical = current.canonical_project_identity === canonicalIdentity;\n\t\tconst rowIsCanonical = row.canonical_project_identity === canonicalIdentity;\n\t\tif (currentIsCanonical && !rowIsCanonical) continue;\n\t\tif (rowIsCanonical || row.updated_at > current.updated_at) rowsByRecipient.set(key, row);\n\t}\n\treturn [...rowsByRecipient.values()].map((row) => ({\n\t\t...row,\n\t\tcanonical_project_identity: canonicalIdentity,\n\t}));\n}\n\nexport function deriveRecipientPolicyEffectiveDevicesFromDatabase(\n\tdb: Database,\n\tcanonicalProjectIdentity: string,\n): StrictRecipientPolicyEffectiveDeviceDerivation {\n\tconst repositoryIdentities = repositoryIdentitiesByWorkspace(db);\n\tconst canonicalIdentity = canonicalRepositoryProjectIdentity(\n\t\trepositoryIdentities,\n\t\tcanonicalProjectIdentity,\n\t);\n\tconst projectRecipients = canonicalProjectRecipientRows(db, canonicalIdentity);\n\tconst identities = db\n\t\t.prepare(\"SELECT actor_id, status, merged_into_actor_id FROM actors ORDER BY actor_id\")\n\t\t.all() as Array<{ actor_id: string; status: string; merged_into_actor_id: string | null }>;\n\tconst teams = db\n\t\t.prepare(\"SELECT team_id, status, device_eligibility_mode FROM policy_teams ORDER BY team_id\")\n\t\t.all() as Array<{\n\t\tteam_id: string;\n\t\tstatus: string;\n\t\tdevice_eligibility_mode: string;\n\t}>;\n\tconst teamMemberships = db\n\t\t.prepare(\n\t\t\t\"SELECT team_id, identity_id, status FROM policy_team_memberships ORDER BY team_id, identity_id\",\n\t\t)\n\t\t.all() as Array<{ team_id: string; identity_id: string; status: string }>;\n\tconst identityDevices = db\n\t\t.prepare(\n\t\t\t\"SELECT identity_id, device_id, status, assignment_version FROM identity_devices ORDER BY identity_id, device_id\",\n\t\t)\n\t\t.all() as Array<{\n\t\tidentity_id: string;\n\t\tdevice_id: string;\n\t\tstatus: string;\n\t\tassignment_version: number;\n\t}>;\n\tconst teamDeviceDecisions = db\n\t\t.prepare(\n\t\t\t\"SELECT team_id, device_id, decision, assignment_version FROM policy_team_device_decisions ORDER BY team_id, device_id\",\n\t\t)\n\t\t.all() as Array<{\n\t\tteam_id: string;\n\t\tdevice_id: string;\n\t\tdecision: string;\n\t\tassignment_version: number;\n\t}>;\n\treturn deriveRecipientPolicyEffectiveDevices({\n\t\tcanonicalProjectIdentity: canonicalIdentity,\n\t\tprojectRecipients: projectRecipients.map((row) => ({\n\t\t\tcanonicalProjectIdentity: row.canonical_project_identity,\n\t\t\trecipientKind: row.recipient_kind,\n\t\t\trecipientId: row.recipient_id,\n\t\t\tstatus: row.status,\n\t\t})),\n\t\tidentities: identities.map((row) => ({\n\t\t\tidentityId: row.actor_id,\n\t\t\tstatus: row.status,\n\t\t\tmergedIntoIdentityId: row.merged_into_actor_id,\n\t\t})),\n\t\tteams: teams.map((row) => ({\n\t\t\tteamId: row.team_id,\n\t\t\tstatus: row.status,\n\t\t\tdeviceEligibilityMode: row.device_eligibility_mode,\n\t\t})),\n\t\tteamMemberships: teamMemberships.map((row) => ({\n\t\t\tteamId: row.team_id,\n\t\t\tidentityId: row.identity_id,\n\t\t\tstatus: row.status,\n\t\t})),\n\t\tteamDeviceDecisions: teamDeviceDecisions.map((row) => ({\n\t\t\tteamId: row.team_id,\n\t\t\tdeviceId: row.device_id,\n\t\t\tdecision: row.decision,\n\t\t\tassignmentVersion: row.assignment_version,\n\t\t})),\n\t\tidentityDevices: identityDevices.map((row) => ({\n\t\t\tidentityId: row.identity_id,\n\t\t\tdeviceId: row.device_id,\n\t\t\tstatus: row.status,\n\t\t\tassignmentVersion: row.assignment_version,\n\t\t})),\n\t});\n}\n\nfunction authorityRow(row: Record<string, unknown>): RecipientPolicyAuthorityStateRecord {\n\treturn {\n\t\tcanonicalProjectIdentity: String(row.canonical_project_identity),\n\t\tauthorityState: row.authority_state as RecipientPolicyAuthorityState,\n\t\tgeneration: Number(row.generation),\n\t\tdesiredDevicesDigest: row.desired_devices_digest as string | null,\n\t\tcurrentDevicesDigest: row.current_devices_digest as string | null,\n\t\tstableParityEvidenceDigest: row.stable_parity_evidence_digest as string | null,\n\t\tstableParityPassedAt: row.stable_parity_passed_at as string | null,\n\t\tfreshSnapshotFingerprint: row.fresh_snapshot_fingerprint as string | null,\n\t\tfreshSnapshotObservedAt: row.fresh_snapshot_observed_at as string | null,\n\t\tsafeErrorCode: row.safe_error_code as string | null,\n\t\tstateChangedAt: String(row.state_changed_at),\n\t\tlastErrorAt: row.last_error_at as string | null,\n\t\tattemptCount: Number(row.attempt_count),\n\t\tlastAttemptAt: row.last_attempt_at as string | null,\n\t\tlastCompletedAt: row.last_completed_at as string | null,\n\t\tleaseOwner: row.lease_owner as string | null,\n\t\tleaseAcquiredAt: row.lease_acquired_at as string | null,\n\t\tleaseExpiresAt: row.lease_expires_at as string | null,\n\t\tcreatedAt: String(row.created_at),\n\t\tupdatedAt: String(row.updated_at),\n\t};\n}\n\nexport function getRecipientPolicyAuthorityState(\n\tdb: Database,\n\tcanonicalProjectIdentity: string,\n): RecipientPolicyAuthorityStateRecord | null {\n\tconst row = db\n\t\t.prepare(\"SELECT * FROM recipient_policy_authority_states WHERE canonical_project_identity = ?\")\n\t\t.get(canonicalProjectIdentity) as Record<string, unknown> | undefined;\n\treturn row ? authorityRow(row) : null;\n}\n\nexport function upsertRecipientPolicyAuthorityObservation(\n\tdb: Database,\n\tinput: UpsertRecipientPolicyAuthorityObservationInput,\n): RecipientPolicyAuthorityStateRecord {\n\tif (\n\t\t!isStrictRecipientPolicyProjectIdentity(input.canonicalProjectIdentity) ||\n\t\t!Number.isSafeInteger(input.generation) ||\n\t\tinput.generation < 0\n\t) {\n\t\tthrow new Error(\"recipient_policy_authority_observation_invalid\");\n\t}\n\tconst existing = getRecipientPolicyAuthorityState(db, input.canonicalProjectIdentity);\n\tif (existing && input.generation < existing.generation) {\n\t\tthrow new Error(\"recipient_policy_generation_stale\");\n\t}\n\tif (\n\t\texisting &&\n\t\tinput.generation === existing.generation &&\n\t\texisting.desiredDevicesDigest !== input.desiredDevicesDigest\n\t) {\n\t\tthrow new Error(\"recipient_policy_generation_conflict\");\n\t}\n\tdb.prepare(\n\t\t`INSERT INTO recipient_policy_authority_states(\n\t\t canonical_project_identity, authority_state, generation, desired_devices_digest,\n\t\t current_devices_digest, fresh_snapshot_fingerprint, fresh_snapshot_observed_at,\n\t\t state_changed_at, created_at, updated_at\n\t\t ) VALUES (?, 'legacy', ?, ?, ?, ?, ?, ?, ?, ?)\n\t\t ON CONFLICT(canonical_project_identity) DO UPDATE SET\n\t\t generation = excluded.generation,\n\t\t desired_devices_digest = excluded.desired_devices_digest,\n\t\t current_devices_digest = excluded.current_devices_digest,\n\t\t fresh_snapshot_fingerprint = excluded.fresh_snapshot_fingerprint,\n\t\t fresh_snapshot_observed_at = excluded.fresh_snapshot_observed_at,\n\t\t stable_parity_evidence_digest = CASE\n\t\t WHEN recipient_policy_authority_states.generation = excluded.generation\n\t\t THEN recipient_policy_authority_states.stable_parity_evidence_digest ELSE NULL END,\n\t\t stable_parity_passed_at = CASE\n\t\t WHEN recipient_policy_authority_states.generation = excluded.generation\n\t\t THEN recipient_policy_authority_states.stable_parity_passed_at ELSE NULL END,\n\t\t updated_at = excluded.updated_at`,\n\t).run(\n\t\tinput.canonicalProjectIdentity,\n\t\tinput.generation,\n\t\tinput.desiredDevicesDigest,\n\t\tinput.currentDevicesDigest,\n\t\tinput.freshSnapshotFingerprint,\n\t\tinput.freshSnapshotObservedAt,\n\t\tinput.now,\n\t\tinput.now,\n\t\tinput.now,\n\t);\n\tconst state = getRecipientPolicyAuthorityState(db, input.canonicalProjectIdentity);\n\tif (!state) throw new Error(\"recipient_policy_authority_state_missing\");\n\treturn state;\n}\n\nexport function recordRecipientPolicyStableParityPass(\n\tdb: Database,\n\tinput: {\n\t\tcanonicalProjectIdentity: string;\n\t\tgeneration: number;\n\t\tevidenceDigest: string;\n\t\tsnapshotFingerprint: string;\n\t\tpassedAt: string;\n\t},\n): RecipientPolicyAuthorityStateRecord {\n\tconst state = getRecipientPolicyAuthorityState(db, input.canonicalProjectIdentity);\n\tif (\n\t\t!state ||\n\t\tstate.generation !== input.generation ||\n\t\tstate.desiredDevicesDigest === null ||\n\t\tstate.desiredDevicesDigest !== state.currentDevicesDigest ||\n\t\tstate.freshSnapshotFingerprint !== input.snapshotFingerprint\n\t) {\n\t\tthrow new Error(\"recipient_policy_parity_evidence_invalid\");\n\t}\n\tif (\n\t\tstate.stableParityEvidenceDigest &&\n\t\t(state.stableParityEvidenceDigest !== input.evidenceDigest ||\n\t\t\tstate.stableParityPassedAt !== input.passedAt)\n\t) {\n\t\tthrow new Error(\"recipient_policy_parity_evidence_conflict\");\n\t}\n\tdb.prepare(\n\t\t`UPDATE recipient_policy_authority_states\n\t\t SET stable_parity_evidence_digest = ?, stable_parity_passed_at = ?, updated_at = ?\n\t\t WHERE canonical_project_identity = ?`,\n\t).run(input.evidenceDigest, input.passedAt, input.passedAt, input.canonicalProjectIdentity);\n\tconst updated = getRecipientPolicyAuthorityState(db, input.canonicalProjectIdentity);\n\tif (!updated) throw new Error(\"recipient_policy_authority_state_missing\");\n\treturn updated;\n}\n\nexport function recordRecipientPolicyAuthorityExecution(\n\tdb: Database,\n\tinput: RecordRecipientPolicyAuthorityExecutionInput,\n): RecipientPolicyAuthorityStateRecord {\n\tconst state = getRecipientPolicyAuthorityState(db, input.canonicalProjectIdentity);\n\tif (!state || state.generation !== input.generation) {\n\t\tthrow new Error(\"recipient_policy_authority_generation_missing\");\n\t}\n\tif (!Number.isSafeInteger(input.attemptCount) || input.attemptCount < state.attemptCount) {\n\t\tthrow new Error(\"recipient_policy_reconciliation_attempt_stale\");\n\t}\n\tdb.prepare(\n\t\t`UPDATE recipient_policy_authority_states SET\n\t\t attempt_count = ?, last_attempt_at = ?, last_completed_at = ?, safe_error_code = ?,\n\t\t last_error_at = ?, lease_owner = ?, lease_acquired_at = ?, lease_expires_at = ?,\n\t\t updated_at = ?\n\t\t WHERE canonical_project_identity = ? AND generation = ?`,\n\t).run(\n\t\tinput.attemptCount,\n\t\tinput.lastAttemptAt,\n\t\tinput.lastCompletedAt,\n\t\tinput.safeErrorCode,\n\t\tinput.lastErrorAt,\n\t\tinput.leaseOwner,\n\t\tinput.leaseAcquiredAt,\n\t\tinput.leaseExpiresAt,\n\t\tinput.updatedAt,\n\t\tinput.canonicalProjectIdentity,\n\t\tinput.generation,\n\t);\n\tconst updated = getRecipientPolicyAuthorityState(db, input.canonicalProjectIdentity);\n\tif (!updated) throw new Error(\"recipient_policy_authority_state_missing\");\n\treturn updated;\n}\n\nexport function deterministicRecipientPolicyReconciliationEffectId(input: {\n\tcanonicalProjectIdentity: string;\n\tgeneration: number;\n\tstepKey: string;\n\tpayloadDigest: string;\n}): string {\n\treturn digest(\"recipient-policy-reconciliation-effect-v1\", {\n\t\tcanonicalProjectIdentity: input.canonicalProjectIdentity,\n\t\tgeneration: input.generation,\n\t\tstepKey: input.stepKey,\n\t\tpayloadDigest: input.payloadDigest,\n\t});\n}\n\nfunction stepRow(row: Record<string, unknown>): RecipientPolicyReconciliationStepRecord {\n\treturn {\n\t\tcanonicalProjectIdentity: String(row.canonical_project_identity),\n\t\tgeneration: Number(row.generation),\n\t\tstepKey: String(row.step_key),\n\t\teffectId: String(row.effect_id),\n\t\tpayloadDigest: String(row.payload_digest),\n\t\tstatus: String(row.status),\n\t\tattemptCount: Number(row.attempt_count),\n\t\tstartedAt: row.started_at as string | null,\n\t\tcompletedAt: row.completed_at as string | null,\n\t\tlastAttemptAt: row.last_attempt_at as string | null,\n\t\tsafeErrorCode: row.safe_error_code as string | null,\n\t\terrorAt: row.error_at as string | null,\n\t\tleaseOwner: row.lease_owner as string | null,\n\t\tleaseAcquiredAt: row.lease_acquired_at as string | null,\n\t\tleaseExpiresAt: row.lease_expires_at as string | null,\n\t\tcreatedAt: String(row.created_at),\n\t\tupdatedAt: String(row.updated_at),\n\t};\n}\n\nexport function listPendingRecipientPolicyRevocationRefreshSteps(\n\tdb: Database,\n\tcanonicalProjectIdentity: string,\n\tlimit = MAX_PENDING_REVOCATION_REFRESH_STEPS,\n): PendingRecipientPolicyRevocationRefreshStep[] {\n\tif (\n\t\t!isStrictRecipientPolicyProjectIdentity(canonicalProjectIdentity) ||\n\t\t!Number.isSafeInteger(limit) ||\n\t\tlimit < 1 ||\n\t\tlimit > MAX_PENDING_REVOCATION_REFRESH_STEPS\n\t) {\n\t\tthrow new Error(\"recipient_policy_reconciliation_step_invalid\");\n\t}\n\tconst rows = db\n\t\t.prepare(PENDING_RECIPIENT_POLICY_REVOCATION_REFRESH_STEPS_SQL)\n\t\t.all(canonicalProjectIdentity, limit) as Array<{ generation: number; step_key: string }>;\n\treturn rows.map((row) => ({ generation: row.generation, stepKey: row.step_key }));\n}\n\nexport function listPendingRecipientPolicyRefreshSteps(\n\tdb: Database,\n\tcanonicalProjectIdentity: string,\n\tlimit = MAX_PENDING_REVOCATION_REFRESH_STEPS,\n): PendingRecipientPolicyRefreshStep[] {\n\tif (\n\t\t!isStrictRecipientPolicyProjectIdentity(canonicalProjectIdentity) ||\n\t\t!Number.isSafeInteger(limit) ||\n\t\tlimit < 1 ||\n\t\tlimit > MAX_PENDING_REVOCATION_REFRESH_STEPS\n\t) {\n\t\tthrow new Error(\"recipient_policy_reconciliation_step_invalid\");\n\t}\n\tconst rows = db\n\t\t.prepare(\n\t\t\t`SELECT generation, step_key FROM recipient_policy_reconciliation_steps\n\t\t\t WHERE canonical_project_identity = ?\n\t\t\t AND step_key GLOB 'refresh:*'\n\t\t\t AND status IN ('pending', 'running', 'failed')\n\t\t\t ORDER BY generation, step_key\n\t\t\t LIMIT ?`,\n\t\t)\n\t\t.all(canonicalProjectIdentity, limit) as Array<{ generation: number; step_key: string }>;\n\treturn rows.map((row) => ({ generation: row.generation, stepKey: row.step_key }));\n}\n\nexport function pruneRecipientPolicyReconciliationSteps(\n\tdb: Database,\n\tinput: PruneRecipientPolicyReconciliationStepsInput,\n): number {\n\tconst retainCompletedPerKind =\n\t\tinput.retainCompletedPerKind ?? DEFAULT_COMPLETED_STEP_RETENTION_PER_KIND;\n\tif (\n\t\t!isStrictRecipientPolicyProjectIdentity(input.canonicalProjectIdentity) ||\n\t\t!Number.isSafeInteger(retainCompletedPerKind) ||\n\t\tretainCompletedPerKind < 0\n\t) {\n\t\tthrow new Error(\"recipient_policy_reconciliation_step_invalid\");\n\t}\n\tconst remove = db.prepare(\n\t\t`DELETE FROM recipient_policy_reconciliation_steps\n\t\t WHERE canonical_project_identity = ? AND status = 'completed' AND step_key GLOB ?\n\t\t AND rowid NOT IN (\n\t\t\t SELECT rowid FROM recipient_policy_reconciliation_steps\n\t\t\t WHERE canonical_project_identity = ? AND status = 'completed' AND step_key GLOB ?\n\t\t\t ORDER BY updated_at DESC, generation DESC, step_key DESC\n\t\t\t LIMIT ?\n\t\t )`,\n\t);\n\treturn db\n\t\t.transaction(() => {\n\t\t\tlet deleted = 0;\n\t\t\tfor (const pattern of PRUNABLE_COMPLETED_STEP_PATTERNS) {\n\t\t\t\tdeleted += remove.run(\n\t\t\t\t\tinput.canonicalProjectIdentity,\n\t\t\t\t\tpattern,\n\t\t\t\t\tinput.canonicalProjectIdentity,\n\t\t\t\t\tpattern,\n\t\t\t\t\tretainCompletedPerKind,\n\t\t\t\t).changes;\n\t\t\t}\n\t\t\treturn deleted;\n\t\t})\n\t\t.immediate();\n}\n\nexport function pruneSupersededRecipientPolicyCapabilitySteps(\n\tdb: Database,\n\tinput: PruneSupersededRecipientPolicyCapabilityStepsInput,\n): number {\n\tif (\n\t\t!isStrictRecipientPolicyProjectIdentity(input.canonicalProjectIdentity) ||\n\t\t!Number.isSafeInteger(input.activeGeneration) ||\n\t\tinput.activeGeneration < 0 ||\n\t\t!isStrictRecipientPolicyId(input.activePassKey)\n\t) {\n\t\tthrow new Error(\"recipient_policy_reconciliation_step_invalid\");\n\t}\n\tconst activeStepPrefix = `capability:${input.activePassKey}:`;\n\treturn db\n\t\t.prepare(\n\t\t\t`DELETE FROM recipient_policy_reconciliation_steps\n\t\t\t WHERE canonical_project_identity = ?\n\t\t\t AND status IN ('pending', 'running', 'failed')\n\t\t\t AND step_key GLOB 'capability:*'\n\t\t\t AND (generation <> ? OR substr(step_key, 1, length(?)) <> ?)`,\n\t\t)\n\t\t.run(input.canonicalProjectIdentity, input.activeGeneration, activeStepPrefix, activeStepPrefix)\n\t\t.changes;\n}\n\nexport function ensureRecipientPolicyReconciliationStep(\n\tdb: Database,\n\tinput: EnsureRecipientPolicyReconciliationStepInput,\n): RecipientPolicyReconciliationStepRecord {\n\tif (\n\t\t!isStrictRecipientPolicyProjectIdentity(input.canonicalProjectIdentity) ||\n\t\t!isStrictRecipientPolicyReconciliationStepKey(input.stepKey) ||\n\t\t!Number.isSafeInteger(input.generation) ||\n\t\tinput.generation < 0\n\t) {\n\t\tthrow new Error(\"recipient_policy_reconciliation_step_invalid\");\n\t}\n\tconst effectId = deterministicRecipientPolicyReconciliationEffectId(input);\n\tconst existing = db\n\t\t.prepare(\n\t\t\t`SELECT * FROM recipient_policy_reconciliation_steps\n\t\t\t WHERE canonical_project_identity = ? AND generation = ? AND step_key = ?`,\n\t\t)\n\t\t.get(input.canonicalProjectIdentity, input.generation, input.stepKey) as\n\t\t| Record<string, unknown>\n\t\t| undefined;\n\tif (existing) {\n\t\tconst uncertainMigratedEffect =\n\t\t\texisting.effect_id !== effectId && [\"running\", \"failed\"].includes(String(existing.status));\n\t\tif (\n\t\t\texisting.payload_digest !== input.payloadDigest ||\n\t\t\t(existing.effect_id !== effectId && !uncertainMigratedEffect)\n\t\t) {\n\t\t\tthrow new Error(\"recipient_policy_reconciliation_step_conflict\");\n\t\t}\n\t\treturn stepRow(existing);\n\t}\n\tdb.prepare(\n\t\t`INSERT INTO recipient_policy_reconciliation_steps(\n\t\t canonical_project_identity, generation, step_key, effect_id, payload_digest,\n\t\t status, created_at, updated_at\n\t\t ) VALUES (?, ?, ?, ?, ?, 'pending', ?, ?)`,\n\t).run(\n\t\tinput.canonicalProjectIdentity,\n\t\tinput.generation,\n\t\tinput.stepKey,\n\t\teffectId,\n\t\tinput.payloadDigest,\n\t\tinput.now,\n\t\tinput.now,\n\t);\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT * FROM recipient_policy_reconciliation_steps\n\t\t\t WHERE canonical_project_identity = ? AND generation = ? AND step_key = ?`,\n\t\t)\n\t\t.get(input.canonicalProjectIdentity, input.generation, input.stepKey) as Record<\n\t\tstring,\n\t\tunknown\n\t>;\n\treturn stepRow(row);\n}\n\nexport function recordRecipientPolicyReconciliationStepState(\n\tdb: Database,\n\tinput: RecordRecipientPolicyReconciliationStepStateInput,\n): RecipientPolicyReconciliationStepRecord {\n\tconst existing = db\n\t\t.prepare(\n\t\t\t`SELECT * FROM recipient_policy_reconciliation_steps\n\t\t\t WHERE canonical_project_identity = ? AND generation = ? AND step_key = ?`,\n\t\t)\n\t\t.get(input.canonicalProjectIdentity, input.generation, input.stepKey) as\n\t\t| Record<string, unknown>\n\t\t| undefined;\n\tif (!existing || existing.effect_id !== input.effectId) {\n\t\tthrow new Error(\"recipient_policy_reconciliation_step_missing\");\n\t}\n\tif (\n\t\t!Number.isSafeInteger(input.attemptCount) ||\n\t\tinput.attemptCount < Number(existing.attempt_count)\n\t) {\n\t\tthrow new Error(\"recipient_policy_reconciliation_attempt_stale\");\n\t}\n\tdb.prepare(\n\t\t`UPDATE recipient_policy_reconciliation_steps SET\n\t\t status = ?, attempt_count = ?, started_at = ?, completed_at = ?, last_attempt_at = ?,\n\t\t safe_error_code = ?, error_at = ?, lease_owner = ?, lease_acquired_at = ?,\n\t\t lease_expires_at = ?, updated_at = ?\n\t\t WHERE canonical_project_identity = ? AND generation = ? AND step_key = ? AND effect_id = ?`,\n\t).run(\n\t\tinput.status,\n\t\tinput.attemptCount,\n\t\tinput.startedAt,\n\t\tinput.completedAt,\n\t\tinput.lastAttemptAt,\n\t\tinput.safeErrorCode,\n\t\tinput.errorAt,\n\t\tinput.leaseOwner,\n\t\tinput.leaseAcquiredAt,\n\t\tinput.leaseExpiresAt,\n\t\tinput.updatedAt,\n\t\tinput.canonicalProjectIdentity,\n\t\tinput.generation,\n\t\tinput.stepKey,\n\t\tinput.effectId,\n\t);\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT * FROM recipient_policy_reconciliation_steps\n\t\t\t WHERE canonical_project_identity = ? AND generation = ? AND step_key = ?`,\n\t\t)\n\t\t.get(input.canonicalProjectIdentity, input.generation, input.stepKey) as Record<\n\t\tstring,\n\t\tunknown\n\t>;\n\treturn stepRow(row);\n}\n\nexport function putRecipientPolicyDenyOverlay(\n\tdb: Database,\n\tinput: {\n\t\tcanonicalProjectIdentity: string;\n\t\tscopeId: string;\n\t\tdeviceId: string;\n\t\tgeneration: number;\n\t\treasonCode: string;\n\t\tnow: string;\n\t},\n): RecipientPolicyDenyOverlayRecord {\n\tif (\n\t\t!isStrictRecipientPolicyProjectIdentity(input.canonicalProjectIdentity) ||\n\t\t![input.scopeId, input.deviceId, input.reasonCode].every(isStrictRecipientPolicyId) ||\n\t\t!Number.isSafeInteger(input.generation) ||\n\t\tinput.generation < 0\n\t) {\n\t\tthrow new Error(\"recipient_policy_deny_overlay_invalid\");\n\t}\n\tconst existing = db\n\t\t.prepare(\n\t\t\t`SELECT * FROM recipient_policy_deny_overlays\n\t\t\t WHERE canonical_project_identity = ? AND scope_id = ? AND device_id = ?`,\n\t\t)\n\t\t.get(input.canonicalProjectIdentity, input.scopeId, input.deviceId) as\n\t\t| Record<string, unknown>\n\t\t| undefined;\n\tif (existing && input.generation < Number(existing.generation)) {\n\t\tthrow new Error(\"recipient_policy_deny_overlay_stale\");\n\t}\n\tdb.prepare(\n\t\t`INSERT INTO recipient_policy_deny_overlays(\n\t\t canonical_project_identity, scope_id, device_id, generation, reason_code, created_at, updated_at\n\t\t ) VALUES (?, ?, ?, ?, ?, ?, ?)\n\t\t ON CONFLICT(canonical_project_identity, scope_id, device_id) DO UPDATE SET\n\t\t generation = excluded.generation,\n\t\t reason_code = excluded.reason_code,\n\t\t updated_at = excluded.updated_at`,\n\t).run(\n\t\tinput.canonicalProjectIdentity,\n\t\tinput.scopeId,\n\t\tinput.deviceId,\n\t\tinput.generation,\n\t\tinput.reasonCode,\n\t\tinput.now,\n\t\tinput.now,\n\t);\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT * FROM recipient_policy_deny_overlays\n\t\t\t WHERE canonical_project_identity = ? AND scope_id = ? AND device_id = ?`,\n\t\t)\n\t\t.get(input.canonicalProjectIdentity, input.scopeId, input.deviceId) as Record<string, unknown>;\n\treturn denyOverlayRow(row);\n}\n\nexport function listRecipientPolicyDenyOverlays(\n\tdb: Database,\n\tcanonicalProjectIdentity: string,\n): RecipientPolicyDenyOverlayRecord[] {\n\treturn (\n\t\tdb\n\t\t\t.prepare(\n\t\t\t\t`SELECT * FROM recipient_policy_deny_overlays\n\t\t\t\t WHERE canonical_project_identity = ? ORDER BY scope_id, device_id`,\n\t\t\t)\n\t\t\t.all(canonicalProjectIdentity) as Array<Record<string, unknown>>\n\t).map(denyOverlayRow);\n}\n\nexport function clearRecipientPolicyDenyOverlay(\n\tdb: Database,\n\tinput: {\n\t\tcanonicalProjectIdentity: string;\n\t\tscopeId: string;\n\t\tdeviceId: string;\n\t\tverifiedGeneration: number;\n\t},\n): boolean {\n\tconst result = db\n\t\t.prepare(\n\t\t\t`DELETE FROM recipient_policy_deny_overlays\n\t\t\t WHERE canonical_project_identity = ? AND scope_id = ? AND device_id = ?\n\t\t\t AND generation <= ?`,\n\t\t)\n\t\t.run(input.canonicalProjectIdentity, input.scopeId, input.deviceId, input.verifiedGeneration);\n\treturn result.changes > 0;\n}\n","/**\n * Tag derivation — port of Python's codemem/store/tags.py.\n *\n * Derives searchable tags from memory kind, title, concepts, and file paths.\n * Used at ingest time to populate memory_items.tags_text inline (matching\n * Python's store_observation → derive_tags flow).\n */\n\nconst STOPWORDS = new Set([\n\t\"the\",\n\t\"and\",\n\t\"for\",\n\t\"with\",\n\t\"this\",\n\t\"that\",\n\t\"from\",\n\t\"are\",\n\t\"was\",\n\t\"were\",\n\t\"has\",\n\t\"have\",\n\t\"had\",\n\t\"not\",\n\t\"but\",\n\t\"can\",\n\t\"will\",\n\t\"all\",\n\t\"been\",\n\t\"each\",\n\t\"which\",\n\t\"their\",\n\t\"said\",\n\t\"its\",\n\t\"into\",\n\t\"than\",\n\t\"other\",\n\t\"some\",\n\t\"could\",\n\t\"them\",\n\t\"about\",\n\t\"then\",\n\t\"made\",\n\t\"after\",\n\t\"many\",\n\t\"also\",\n\t\"did\",\n\t\"just\",\n\t\"should\",\n\t\"over\",\n\t\"such\",\n\t\"there\",\n\t\"would\",\n\t\"more\",\n\t\"now\",\n\t\"very\",\n\t\"when\",\n\t\"what\",\n\t\"your\",\n\t\"how\",\n\t\"out\",\n\t\"our\",\n\t\"his\",\n\t\"her\",\n\t\"she\",\n\t\"him\",\n\t\"most\",\n]);\n\n/**\n * Normalize a raw value into a tag-safe lowercase slug.\n * Returns empty string if the value is empty, a stopword, or too short.\n */\nexport function normalizeTag(value: string, stopwords?: Set<string>): string {\n\tlet lowered = (value || \"\").trim().toLowerCase();\n\tif (!lowered) return \"\";\n\tlowered = lowered\n\t\t.replace(/[^a-z0-9_]+/g, \"-\")\n\t\t.replace(/-+/g, \"-\")\n\t\t.replace(/^-|-$/g, \"\");\n\tif (!lowered) return \"\";\n\tconst words = stopwords ?? STOPWORDS;\n\tif (words.has(lowered)) return \"\";\n\tif (lowered.length > 40) lowered = lowered.slice(0, 40).replace(/-$/, \"\");\n\treturn lowered;\n}\n\n/**\n * Extract tags from a file path (basename, parent dir, top-level dir).\n */\nexport function fileTags(pathValue: string, stopwords?: Set<string>): string[] {\n\tconst raw = (pathValue || \"\").trim();\n\tif (!raw) return [];\n\tconst parts = raw.split(/[\\\\/]+/).filter((p): p is string => !!p && p !== \".\" && p !== \"..\");\n\tif (!parts.length) return [];\n\n\tconst tags: string[] = [];\n\tconst last = parts.at(-1);\n\tif (last) {\n\t\tconst basename = normalizeTag(last, stopwords);\n\t\tif (basename) tags.push(basename);\n\t}\n\tif (parts.length >= 2) {\n\t\tconst secondLast = parts.at(-2);\n\t\tif (secondLast) {\n\t\t\tconst parent = normalizeTag(secondLast, stopwords);\n\t\t\tif (parent) tags.push(parent);\n\t\t}\n\t}\n\tif (parts.length >= 3) {\n\t\tconst first = parts.at(0);\n\t\tif (first) {\n\t\t\tconst top = normalizeTag(first, stopwords);\n\t\t\tif (top) tags.push(top);\n\t\t}\n\t}\n\treturn tags;\n}\n\n/**\n * Derive tags from memory metadata, matching Python's derive_tags().\n *\n * Sources (in priority order):\n * 1. Memory kind\n * 2. Concepts (from observer XML output)\n * 3. File paths (read + modified)\n * 4. Title tokens (fallback when nothing else produced tags)\n */\nexport function deriveTags(opts: {\n\tkind: string;\n\ttitle?: string;\n\tconcepts?: string[];\n\tfilesRead?: string[];\n\tfilesModified?: string[];\n\tstopwords?: Set<string>;\n}): string[] {\n\tconst words = opts.stopwords ?? STOPWORDS;\n\tconst tags: string[] = [];\n\n\tconst kindTag = normalizeTag(opts.kind, words);\n\tif (kindTag) tags.push(kindTag);\n\n\tfor (const concept of opts.concepts ?? []) {\n\t\tconst normalized = normalizeTag(concept, words);\n\t\tif (normalized) tags.push(normalized);\n\t}\n\n\tfor (const pathValue of [...(opts.filesRead ?? []), ...(opts.filesModified ?? [])]) {\n\t\ttags.push(...fileTags(pathValue, words));\n\t}\n\n\t// Fallback: extract tokens from title if no other tags were found\n\tif (!tags.length && opts.title) {\n\t\tfor (const match of opts.title.toLowerCase().matchAll(/[a-z0-9_]+/g)) {\n\t\t\tconst normalized = normalizeTag(match[0], words);\n\t\t\tif (normalized) tags.push(normalized);\n\t\t}\n\t}\n\n\t// Dedupe while preserving order, cap at 20\n\tconst deduped: string[] = [];\n\tconst seen = new Set<string>();\n\tfor (const tag of tags) {\n\t\tif (seen.has(tag)) continue;\n\t\tseen.add(tag);\n\t\tdeduped.push(tag);\n\t\tif (deduped.length >= 20) break;\n\t}\n\treturn deduped;\n}\n","/**\n * Sync replication: cursor tracking, op chunking, and payload extraction.\n *\n * Uses Drizzle ORM for all SQL queries so that column mismatches are\n * compile-time errors instead of silent data-loss bugs at runtime.\n *\n * Keeps replication functions decoupled from MemoryStore by accepting\n * a raw Database handle. Ported from codemem/sync/replication.py.\n */\n\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { and, desc, eq, gt, isNotNull, isNull, like, or, sql } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport type { Database } from \"./db.js\";\nimport { fromJson, fromJsonStrict, toJson, toJsonNullable } from \"./db.js\";\nimport {\n\thasMatchingLocalCreation,\n\thasRecordedLocalCreation,\n\trecordForeignMemoryRevision,\n} from \"./memory-creation-provenance.js\";\nimport { type LocalCreationContext, localCreationSourceIds } from \"./memory-local-capture.js\";\nimport { retirementAllowsSnapshot } from \"./memory-retirement-snapshot-guard.js\";\nimport {\n\tassertMemoryScopeNotRetired,\n\thasMemoryScopeRetirement,\n\tisMemoryScopeRetired,\n} from \"./memory-scope-retirement.js\";\nimport { memorySourceNamespace } from \"./memory-source-identity.js\";\nimport { readCodememConfigFile } from \"./observer-config.js\";\nimport { projectBasename } from \"./project.js\";\nimport { getAnyRecipientPolicyDenyOverlayForScopeDevice } from \"./recipient-policy-reconciliation.js\";\nimport { clearMemoryRefs, populateMemoryRefs } from \"./ref-populate.js\";\nimport * as schema from \"./schema.js\";\nimport { getCachedScopeAuthorization } from \"./scope-membership-cache.js\";\nimport { LEGACY_SHARED_REVIEW_SCOPE_ID } from \"./scope-resolution.js\";\nimport { ensureMemoryScopeId } from \"./scope-stamping.js\";\nimport { redactMemoryFields, SecretScanner } from \"./secret-scanner.js\";\nimport { snapshotSessionExportKeysForMemoryIds } from \"./session-export-identity-mutation.js\";\nimport { loadRuntimeSigningPublicKey } from \"./sync-identity.js\";\nimport {\n\tensureSyncTransferActivitySchema,\n\trecordSyncTransferObservation,\n\trecordSyncTransferReceipts,\n\ttype SyncTransferObservationSource,\n} from \"./sync-transfer-activity.js\";\nimport { deriveTags } from \"./tags.js\";\nimport type {\n\tReplicationOp,\n\tReplicationOpsAgePrunePlan,\n\tReplicationOpsPruneResult,\n\tSyncDirtyLocalState,\n\tSyncMemorySnapshotItem,\n} from \"./types.js\";\n\nexport const DEFAULT_SYNC_SCOPE_ID = \"local-default\";\nexport const ACCESS_CLEANUP_OP_TYPE = \"access_cleanup\";\nexport const REASSIGN_SCOPE_OP_TYPE = \"reassign_scope\";\nexport const SCOPED_NULL_BASELINE_BOOTSTRAP_CURSOR_MARKER =\n\t\"__codemem_scoped_null_baseline_bootstrap__\";\n\nexport interface SyncResetBoundary {\n\tscope_id?: string | null;\n\tgeneration: number;\n\tsnapshot_id: string;\n\tbaseline_cursor: string | null;\n\tretained_floor_cursor: string | null;\n}\n\nexport interface SyncResetRequired extends SyncResetBoundary {\n\treset_required: true;\n\treason:\n\t\t| \"stale_cursor\"\n\t\t| \"generation_mismatch\"\n\t\t| \"boundary_mismatch\"\n\t\t| \"missing_scope\"\n\t\t| \"scope_inactive\"\n\t\t| \"stale_epoch\"\n\t\t| \"unsupported_scope\";\n}\n\n/**\n * Serialized bytes of ops or snapshot items one pull page may carry. A relayed\n * exchange on the Durable Object host carries at most 2 MiB, and real memory\n * items average about 5 KB, so a 500-op or 2000-item page by count alone\n * would not fit. This matches the push batch limit. A page always carries at\n * least one entry, so a single larger entry still makes progress.\n */\nexport const SYNC_PAGE_MAX_BYTES = 1_048_576;\n\n/** Returns how many leading entries fit in `maxBytes` of JSON, at least one. */\nfunction entriesWithinBytes(entries: readonly unknown[], maxBytes: number): number {\n\tlet total = 0;\n\tfor (const [index, entry] of entries.entries()) {\n\t\ttotal += Buffer.byteLength(JSON.stringify(entry)) + 1;\n\t\tif (index > 0 && total > maxBytes) return index;\n\t}\n\treturn entries.length;\n}\n\ninterface LoadReplicationOpsForPeerBaseOptions {\n\tsince: string | null;\n\tlimit?: number;\n\t/** Serialized size cap for the returned ops. Defaults to SYNC_PAGE_MAX_BYTES. */\n\tmaxBytes?: number;\n\tgeneration?: number | null;\n\tsnapshotId?: string | null;\n\tbaselineCursor?: string | null;\n}\n\nexport type LoadReplicationOpsForPeerOptions =\n\t| (LoadReplicationOpsForPeerBaseOptions & {\n\t\t\tdeviceId?: string;\n\t\t\tscopeId?: null;\n\t })\n\t| (LoadReplicationOpsForPeerBaseOptions & {\n\t\t\tdeviceId: string;\n\t\t\tscopeId: string;\n\t });\n\nexport type LoadReplicationOpsForPeerResult =\n\t| {\n\t\t\treset_required: false;\n\t\t\tboundary: SyncResetBoundary;\n\t\t\tops: ReplicationOp[];\n\t\t\tnextCursor: string | null;\n\t }\n\t| {\n\t\t\treset_required: true;\n\t\t\treset: SyncResetRequired;\n\t };\n\nexport interface LoadMemorySnapshotPageForPeerOptions {\n\t/** Direct-source reset lane; the HTTP caller must require its own local device ID. */\n\tsourceDeviceId?: string;\n\tlimit?: number;\n\t/** Serialized size cap for the returned items. Defaults to SYNC_PAGE_MAX_BYTES. */\n\tmaxBytes?: number;\n\tpageToken?: string | null;\n\tpeerDeviceId?: string | null;\n\tscopeId?: string | null;\n\tgeneration?: number | null;\n\tsnapshotId?: string | null;\n\tbaselineCursor?: string | null;\n}\n\nexport interface LoadMemorySnapshotPageForPeerResult {\n\tboundary: SyncResetBoundary;\n\titems: SyncMemorySnapshotItem[];\n\tnextPageToken: string | null;\n\thasMore: boolean;\n}\n\ntype MemoryItemRow = typeof schema.memoryItems.$inferSelect;\n\ninterface MemoryPayload {\n\tsession_id: number | null;\n\tkind: string | null;\n\ttitle: string | null;\n\tsubtitle: string | null;\n\tbody_text: string | null;\n\tconfidence: number | null;\n\ttags_text: string | null;\n\tactive: number | null;\n\tcreated_at: string | null;\n\tupdated_at: string | null;\n\tmetadata_json: Record<string, unknown>;\n\tactor_id: string | null;\n\tactor_display_name: string | null;\n\tvisibility: string | null;\n\tworkspace_id: string | null;\n\tworkspace_kind: string | null;\n\torigin_device_id: string | null;\n\torigin_source: string | null;\n\ttrust_state: string | null;\n\tnarrative: string | null;\n\tfacts: unknown;\n\tconcepts: unknown;\n\tfiles_read: unknown;\n\tfiles_modified: unknown;\n\tuser_prompt_id: number | null;\n\tprompt_number: number | null;\n\tdeleted_at: string | null;\n\tscope_id: string | null;\n\t// Wire payloads use this as \"sender explicitly included deleted_at\" so we can\n\t// distinguish a tombstone clear (`deleted_at: null`) from an omitted field.\n\t// Row-derived payloads set it from current storage truth instead.\n\thas_deleted_at: boolean;\n\trev: number;\n\timport_key: string | null;\n\tproject?: string | null;\n}\n\ninterface AccessCleanupPayload {\n\tcleanup_scope_id: string | null;\n\treason: string | null;\n\ttarget_peer_device_id: string | null;\n}\n\nexport interface ReassignScopePayload {\n\toperation_id: string;\n\tmemory_id: string;\n\told_scope_id: string;\n\tnew_scope_id: string;\n\trevision: number;\n\tside: \"old\" | \"new\";\n}\n\nfunction requiredPayloadText(value: unknown): string | null {\n\treturn typeof value === \"string\" && value.trim() ? value.trim() : null;\n}\n\nexport function parseReassignScopePayload(op: ReplicationOp): ReassignScopePayload {\n\tif (op.op_type !== REASSIGN_SCOPE_OP_TYPE) throw new Error(\"reassign_payload_invalid\");\n\tconst payload = parsePayload(op.payload_json);\n\tconst operationId = requiredPayloadText(payload?.operation_id);\n\tconst memoryId = requiredPayloadText(payload?.memory_id);\n\tconst oldScopeId = requiredPayloadText(payload?.old_scope_id);\n\tconst newScopeId = requiredPayloadText(payload?.new_scope_id);\n\tconst side = payload?.side;\n\tconst revision = payload?.revision;\n\tif (\n\t\t!operationId ||\n\t\t!memoryId ||\n\t\tmemoryId !== op.entity_id ||\n\t\t!oldScopeId ||\n\t\t!newScopeId ||\n\t\toldScopeId === newScopeId ||\n\t\t(side !== \"old\" && side !== \"new\") ||\n\t\t!Number.isSafeInteger(revision) ||\n\t\tNumber(revision) <= 0 ||\n\t\tNumber(revision) !== op.clock_rev ||\n\t\tcleanText(op.scope_id) !== (side === \"old\" ? oldScopeId : newScopeId) ||\n\t\t(side === \"new\" && cleanText(payload?.scope_id) !== newScopeId)\n\t) {\n\t\tthrow new Error(\"reassign_payload_invalid\");\n\t}\n\treturn {\n\t\toperation_id: operationId,\n\t\tmemory_id: memoryId,\n\t\told_scope_id: oldScopeId,\n\t\tnew_scope_id: newScopeId,\n\t\trevision: Number(revision),\n\t\tside,\n\t};\n}\n\nfunction parseAccessCleanupPayload(op: ReplicationOp): AccessCleanupPayload {\n\tconst payload = parsePayload(op.payload_json);\n\treturn {\n\t\tcleanup_scope_id: cleanText(payload?.cleanup_scope_id ?? payload?.scope_id),\n\t\treason: cleanText(payload?.reason),\n\t\ttarget_peer_device_id: cleanText(payload?.target_peer_device_id),\n\t};\n}\n\nfunction accessCleanupTargetsPeer(op: ReplicationOp, peerDeviceId: string | null): boolean {\n\tconst cleanup = parseAccessCleanupPayload(op);\n\tif (!cleanup.cleanup_scope_id) return false;\n\treturn (\n\t\tcleanup.target_peer_device_id === null ||\n\t\tcleanup.target_peer_device_id === cleanText(peerDeviceId)\n\t);\n}\n\nfunction resolveReplicatedTextUpdate(\n\tnextValue: string | null | undefined,\n\tcurrentValue: string | null,\n): string {\n\tif (nextValue == null) return currentValue ?? \"\";\n\treturn nextValue;\n}\n\nfunction asNumberOrNull(value: unknown): number | null {\n\tif (value == null) return null;\n\tif (typeof value === \"number\" && Number.isFinite(value)) return value;\n\tif (typeof value === \"string\" && value.trim().length > 0) {\n\t\tconst parsed = Number(value);\n\t\tif (Number.isFinite(parsed)) return parsed;\n\t}\n\treturn null;\n}\n\nfunction asStringOrNull(value: unknown): string | null {\n\tif (value == null) return null;\n\treturn String(value);\n}\n\n/** Coerce an unknown payload field to `string[] | null` for ref population. */\nfunction asStringArrayOrNull(value: unknown): string[] | null {\n\tif (!Array.isArray(value)) return null;\n\tconst strings = value.filter((v): v is string => typeof v === \"string\");\n\treturn strings.length > 0 ? strings : null;\n}\n\nfunction parseMemoryPayload(op: ReplicationOp, errors: string[]): MemoryPayload | null {\n\tif (!op.payload_json) return null;\n\tlet raw: Record<string, unknown>;\n\ttry {\n\t\traw = fromJsonStrict(op.payload_json);\n\t} catch (err) {\n\t\terrors.push(\n\t\t\t`op ${op.op_id}: skipped — payload_json is not a valid object: ${err instanceof Error ? err.message : String(err)}`,\n\t\t);\n\t\treturn null;\n\t}\n\tconst metadataRaw = raw.metadata_json;\n\tconst metadata_json =\n\t\tmetadataRaw && typeof metadataRaw === \"object\" && !Array.isArray(metadataRaw)\n\t\t\t? { ...(metadataRaw as Record<string, unknown>) }\n\t\t\t: {};\n\treturn {\n\t\tsession_id: asNumberOrNull(raw.session_id),\n\t\tkind: asStringOrNull(raw.kind),\n\t\ttitle: asStringOrNull(raw.title),\n\t\tsubtitle: asStringOrNull(raw.subtitle),\n\t\tbody_text: asStringOrNull(raw.body_text),\n\t\tconfidence: asNumberOrNull(raw.confidence),\n\t\ttags_text: asStringOrNull(raw.tags_text),\n\t\tactive: asNumberOrNull(raw.active),\n\t\tcreated_at: asStringOrNull(raw.created_at),\n\t\tupdated_at: asStringOrNull(raw.updated_at),\n\t\tmetadata_json,\n\t\tactor_id: asStringOrNull(raw.actor_id),\n\t\tactor_display_name: asStringOrNull(raw.actor_display_name),\n\t\tvisibility: asStringOrNull(raw.visibility),\n\t\tworkspace_id: asStringOrNull(raw.workspace_id),\n\t\tworkspace_kind: asStringOrNull(raw.workspace_kind),\n\t\torigin_device_id: asStringOrNull(raw.origin_device_id),\n\t\torigin_source: asStringOrNull(raw.origin_source),\n\t\ttrust_state: asStringOrNull(raw.trust_state),\n\t\tnarrative: asStringOrNull(raw.narrative),\n\t\tfacts: raw.facts ?? null,\n\t\tconcepts: raw.concepts ?? null,\n\t\tfiles_read: raw.files_read ?? null,\n\t\tfiles_modified: raw.files_modified ?? null,\n\t\tuser_prompt_id: asNumberOrNull(raw.user_prompt_id),\n\t\tprompt_number: asNumberOrNull(raw.prompt_number),\n\t\tdeleted_at: asStringOrNull(raw.deleted_at),\n\t\tscope_id: asStringOrNull(raw.scope_id),\n\t\thas_deleted_at: Object.hasOwn(raw, \"deleted_at\"),\n\t\trev: asNumberOrNull(raw.rev) ?? 0,\n\t\timport_key: asStringOrNull(raw.import_key),\n\t\tproject: asStringOrNull(raw.project),\n\t};\n}\n\n/**\n * Resolve tags_text for a replicated memory: use incoming tags if non-empty,\n * otherwise derive tags from available metadata (kind, title, concepts, files).\n */\nfunction resolveReplicatedTags(payload: MemoryPayload): string {\n\tconst incoming = (payload.tags_text ?? \"\").trim();\n\tif (incoming) return incoming;\n\tconst concepts = Array.isArray(payload.concepts) ? payload.concepts.map(String) : [];\n\tconst filesRead = Array.isArray(payload.files_read) ? payload.files_read.map(String) : [];\n\tconst filesModified = Array.isArray(payload.files_modified)\n\t\t? payload.files_modified.map(String)\n\t\t: [];\n\tconst tags = deriveTags({\n\t\tkind: payload.kind ?? \"\",\n\t\ttitle: payload.title ?? undefined,\n\t\tconcepts,\n\t\tfilesRead,\n\t\tfilesModified,\n\t});\n\treturn tags.join(\" \");\n}\n\nfunction normalizeCursor(value: string | null | undefined): string | null {\n\tconst trimmed = String(value ?? \"\").trim();\n\treturn trimmed.length > 0 ? trimmed : null;\n}\n\nfunction normalizeSyncStateScopeId(scopeId: string | null | undefined): string {\n\tconst trimmed = String(scopeId ?? \"\").trim();\n\treturn trimmed.length > 0 ? trimmed : DEFAULT_SYNC_SCOPE_ID;\n}\n\nfunction shouldReturnScopeId(scopeId: string | null | undefined): boolean {\n\treturn scopeId !== undefined;\n}\n\nfunction resetBoundaryFromRow(\n\trow: {\n\t\tgeneration: number | null;\n\t\tsnapshot_id: string | null;\n\t\tbaseline_cursor: string | null;\n\t\tretained_floor_cursor: string | null;\n\t},\n\tscopeId: string,\n\tincludeScopeId: boolean,\n): SyncResetBoundary {\n\tconst boundary: SyncResetBoundary = {\n\t\tgeneration: Number(row.generation ?? 1),\n\t\tsnapshot_id: String(row.snapshot_id),\n\t\tbaseline_cursor: normalizeCursor(row.baseline_cursor),\n\t\tretained_floor_cursor: normalizeCursor(row.retained_floor_cursor),\n\t};\n\tif (includeScopeId) boundary.scope_id = scopeId;\n\treturn boundary;\n}\n\nfunction parseSnapshotPageToken(\n\ttoken: string | null | undefined,\n): { importKey: string; id: number } | null {\n\tconst raw = normalizeCursor(token);\n\tif (!raw) return null;\n\tconst idx = raw.lastIndexOf(\"|\");\n\tif (idx <= 0) return null;\n\tconst importKey = raw.slice(0, idx);\n\tconst id = Number(raw.slice(idx + 1));\n\tif (!importKey || !Number.isFinite(id)) return null;\n\treturn { importKey, id };\n}\n\nfunction makeSnapshotPageToken(importKey: string, id: number): string {\n\treturn `${importKey}|${id}`;\n}\n\nfunction ensureSyncResetStateTable(db: Database): void {\n\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS sync_reset_state (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\tgeneration INTEGER NOT NULL,\n\t\t\tsnapshot_id TEXT NOT NULL,\n\t\t\tbaseline_cursor TEXT,\n\t\t\tretained_floor_cursor TEXT,\n\t\t\tupdated_at TEXT NOT NULL\n\t\t)\n\t`);\n\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS sync_reset_state_v2 (\n\t\t\tscope_id TEXT PRIMARY KEY NOT NULL,\n\t\t\tgeneration INTEGER NOT NULL,\n\t\t\tsnapshot_id TEXT NOT NULL,\n\t\t\tbaseline_cursor TEXT,\n\t\t\tretained_floor_cursor TEXT,\n\t\t\tupdated_at TEXT NOT NULL\n\t\t)\n\t`);\n}\n\nfunction seedDefaultSyncResetStateFromLegacy(db: Database): void {\n\tdb.exec(`\n\t\tINSERT OR IGNORE INTO sync_reset_state_v2\n\t\t\t(scope_id, generation, snapshot_id, baseline_cursor, retained_floor_cursor, updated_at)\n\t\tSELECT '${DEFAULT_SYNC_SCOPE_ID}', generation, snapshot_id, baseline_cursor, retained_floor_cursor, updated_at\n\t\tFROM sync_reset_state\n\t\tWHERE id = 1\n\t`);\n}\n\nfunction mirrorDefaultSyncResetStateToLegacy(\n\tdb: Database,\n\tboundary: SyncResetBoundary,\n\tupdatedAt: string,\n): void {\n\tconst d = drizzle(db, { schema });\n\td.insert(schema.syncResetState)\n\t\t.values({\n\t\t\tid: 1,\n\t\t\tgeneration: boundary.generation,\n\t\t\tsnapshot_id: boundary.snapshot_id,\n\t\t\tbaseline_cursor: boundary.baseline_cursor,\n\t\t\tretained_floor_cursor: boundary.retained_floor_cursor,\n\t\t\tupdated_at: updatedAt,\n\t\t})\n\t\t.onConflictDoUpdate({\n\t\t\ttarget: schema.syncResetState.id,\n\t\t\tset: {\n\t\t\t\tgeneration: boundary.generation,\n\t\t\t\tsnapshot_id: boundary.snapshot_id,\n\t\t\t\tbaseline_cursor: boundary.baseline_cursor,\n\t\t\t\tretained_floor_cursor: boundary.retained_floor_cursor,\n\t\t\t\tupdated_at: updatedAt,\n\t\t\t},\n\t\t})\n\t\t.run();\n}\n\nexport function getSyncResetState(db: Database, scopeId?: string | null): SyncResetBoundary {\n\tensureSyncResetStateTable(db);\n\tconst effectiveScopeId = normalizeSyncStateScopeId(scopeId);\n\tconst includeScopeId = shouldReturnScopeId(scopeId);\n\tif (effectiveScopeId === DEFAULT_SYNC_SCOPE_ID) {\n\t\tseedDefaultSyncResetStateFromLegacy(db);\n\t}\n\tconst d = drizzle(db, { schema });\n\tconst existing = d\n\t\t.select()\n\t\t.from(schema.syncResetStateV2)\n\t\t.where(eq(schema.syncResetStateV2.scope_id, effectiveScopeId))\n\t\t.get();\n\tif (existing) {\n\t\treturn resetBoundaryFromRow(existing, effectiveScopeId, includeScopeId);\n\t}\n\n\tconst now = new Date().toISOString();\n\tconst created = {\n\t\tscope_id: effectiveScopeId,\n\t\tgeneration: 1,\n\t\tsnapshot_id: randomUUID(),\n\t\tbaseline_cursor: null,\n\t\tretained_floor_cursor: null,\n\t\tupdated_at: now,\n\t};\n\td.insert(schema.syncResetStateV2).values(created).run();\n\tconst boundary = resetBoundaryFromRow(created, effectiveScopeId, includeScopeId);\n\tif (effectiveScopeId === DEFAULT_SYNC_SCOPE_ID) {\n\t\tmirrorDefaultSyncResetStateToLegacy(db, boundary, now);\n\t}\n\treturn boundary;\n}\n\nexport function setSyncResetState(\n\tdb: Database,\n\tupdates: Partial<SyncResetBoundary> & { generation?: number },\n\tscopeId?: string | null,\n): SyncResetBoundary {\n\tconst requestedScopeId = scopeId !== undefined ? scopeId : updates.scope_id;\n\tconst effectiveScopeId = normalizeSyncStateScopeId(requestedScopeId);\n\tconst includeScopeId = scopeId !== undefined || updates.scope_id !== undefined;\n\tconst current = getSyncResetState(db, includeScopeId ? effectiveScopeId : undefined);\n\tconst now = new Date().toISOString();\n\tconst next: SyncResetBoundary = {\n\t\tgeneration: updates.generation ?? current.generation,\n\t\tsnapshot_id: updates.snapshot_id ?? current.snapshot_id,\n\t\tbaseline_cursor:\n\t\t\tupdates.baseline_cursor === undefined\n\t\t\t\t? current.baseline_cursor\n\t\t\t\t: normalizeCursor(updates.baseline_cursor),\n\t\tretained_floor_cursor:\n\t\t\tupdates.retained_floor_cursor === undefined\n\t\t\t\t? current.retained_floor_cursor\n\t\t\t\t: normalizeCursor(updates.retained_floor_cursor),\n\t};\n\tif (includeScopeId) next.scope_id = effectiveScopeId;\n\tconst d = drizzle(db, { schema });\n\td.insert(schema.syncResetStateV2)\n\t\t.values({\n\t\t\tscope_id: effectiveScopeId,\n\t\t\tgeneration: next.generation,\n\t\t\tsnapshot_id: next.snapshot_id,\n\t\t\tbaseline_cursor: next.baseline_cursor,\n\t\t\tretained_floor_cursor: next.retained_floor_cursor,\n\t\t\tupdated_at: now,\n\t\t})\n\t\t.onConflictDoUpdate({\n\t\t\ttarget: schema.syncResetStateV2.scope_id,\n\t\t\tset: {\n\t\t\t\tgeneration: next.generation,\n\t\t\t\tsnapshot_id: next.snapshot_id,\n\t\t\t\tbaseline_cursor: next.baseline_cursor,\n\t\t\t\tretained_floor_cursor: next.retained_floor_cursor,\n\t\t\t\tupdated_at: now,\n\t\t\t},\n\t\t})\n\t\t.run();\n\tif (effectiveScopeId === DEFAULT_SYNC_SCOPE_ID) {\n\t\tmirrorDefaultSyncResetStateToLegacy(db, next, now);\n\t}\n\treturn next;\n}\n\nfunction resetRequired(\n\tboundary: SyncResetBoundary,\n\treason: SyncResetRequired[\"reason\"],\n): LoadReplicationOpsForPeerResult {\n\treturn {\n\t\treset_required: true,\n\t\treset: {\n\t\t\treset_required: true,\n\t\t\treason,\n\t\t\t...boundary,\n\t\t},\n\t};\n}\n\nfunction foreignRevisionMetadata(\n\tdb: Database,\n\top: ReplicationOp,\n\tmetadata: Record<string, unknown> | string | null,\n): Record<string, unknown> {\n\trecordForeignMemoryRevision(db, op.entity_id, \"replication\");\n\tconst object = typeof metadata === \"string\" || metadata === null ? fromJson(metadata) : metadata;\n\treturn {\n\t\t...object,\n\t\tclock_device_id: op.clock_device_id,\n\t};\n}\n\nexport function clockDeviceIdFromMetadataJson(raw: string | null): string {\n\tconst metadata = fromJson(raw);\n\treturn typeof metadata.clock_device_id === \"string\" ? metadata.clock_device_id : \"\";\n}\n\n// Op chunking\n\n/**\n * Split replication ops into batches that fit within a byte-size limit.\n *\n * Each batch is serialized as `{\"ops\": [...]}` and must not exceed maxBytes\n * when UTF-8 encoded. Throws if a single op exceeds the limit.\n */\nexport function chunkOpsBySize(ops: ReplicationOp[], maxBytes: number): ReplicationOp[][] {\n\tconst encoder = new TextEncoder();\n\t// Overhead: {\"ops\":[]} = 9 bytes, comma between elements = 1 byte\n\tconst WRAPPER_OVERHEAD = 9;\n\tconst COMMA_OVERHEAD = 1;\n\n\tconst batches: ReplicationOp[][] = [];\n\tlet current: ReplicationOp[] = [];\n\tlet currentBytes = WRAPPER_OVERHEAD;\n\n\tfor (const op of ops) {\n\t\tconst opBytes = encoder.encode(JSON.stringify(op)).byteLength;\n\t\tconst addedBytes = current.length === 0 ? opBytes : opBytes + COMMA_OVERHEAD;\n\n\t\tif (currentBytes + addedBytes <= maxBytes) {\n\t\t\tcurrent.push(op);\n\t\t\tcurrentBytes += addedBytes;\n\t\t\tcontinue;\n\t\t}\n\t\tif (current.length === 0) {\n\t\t\tthrow new Error(\"single op exceeds size limit\");\n\t\t}\n\t\tbatches.push(current);\n\t\tcurrent = [op];\n\t\tcurrentBytes = WRAPPER_OVERHEAD + opBytes;\n\t\tif (currentBytes > maxBytes) {\n\t\t\tthrow new Error(\"single op exceeds size limit\");\n\t\t}\n\t}\n\tif (current.length > 0) {\n\t\tbatches.push(current);\n\t}\n\treturn batches;\n}\n\n// Cursor read/write\n\nfunction ensureReplicationCursorTables(db: Database): void {\n\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS replication_cursors (\n\t\t\tpeer_device_id TEXT PRIMARY KEY,\n\t\t\tlast_applied_cursor TEXT,\n\t\t\tlast_acked_cursor TEXT,\n\t\t\tupdated_at TEXT NOT NULL\n\t\t)\n\t`);\n\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS replication_cursors_v2 (\n\t\t\tpeer_device_id TEXT NOT NULL,\n\t\t\tscope_id TEXT NOT NULL,\n\t\t\tlast_applied_cursor TEXT,\n\t\t\tlast_acked_cursor TEXT,\n\t\t\tupdated_at TEXT NOT NULL,\n\t\t\tPRIMARY KEY (peer_device_id, scope_id)\n\t\t);\n\t\tCREATE INDEX IF NOT EXISTS idx_replication_cursors_v2_scope\n\t\t\tON replication_cursors_v2(scope_id)\n\t`);\n}\n\nfunction seedDefaultReplicationCursorFromLegacy(db: Database): void {\n\tdb.exec(`\n\t\tINSERT OR IGNORE INTO replication_cursors_v2\n\t\t\t(peer_device_id, scope_id, last_applied_cursor, last_acked_cursor, updated_at)\n\t\tSELECT peer_device_id, '${DEFAULT_SYNC_SCOPE_ID}', last_applied_cursor, last_acked_cursor, updated_at\n\t\tFROM replication_cursors\n\t`);\n}\n\nfunction mirrorDefaultReplicationCursorToLegacy(\n\tdb: Database,\n\tpeerDeviceId: string,\n\toptions: { lastApplied?: string | null; lastAcked?: string | null },\n\tupdatedAt: string,\n): void {\n\tconst lastApplied = options.lastApplied ?? null;\n\tconst lastAcked = options.lastAcked ?? null;\n\tconst d = drizzle(db, { schema });\n\td.insert(schema.replicationCursors)\n\t\t.values({\n\t\t\tpeer_device_id: peerDeviceId,\n\t\t\tlast_applied_cursor: lastApplied,\n\t\t\tlast_acked_cursor: lastAcked,\n\t\t\tupdated_at: updatedAt,\n\t\t})\n\t\t.onConflictDoUpdate({\n\t\t\ttarget: schema.replicationCursors.peer_device_id,\n\t\t\tset: {\n\t\t\t\tlast_applied_cursor: sql`COALESCE(excluded.last_applied_cursor, ${schema.replicationCursors.last_applied_cursor})`,\n\t\t\t\tlast_acked_cursor: sql`COALESCE(excluded.last_acked_cursor, ${schema.replicationCursors.last_acked_cursor})`,\n\t\t\t\tupdated_at: sql`excluded.updated_at`,\n\t\t\t},\n\t\t})\n\t\t.run();\n}\n\n/**\n * Read the replication cursor for a peer device.\n *\n * Returns `[lastApplied, lastAcked]` — both null when no cursor exists.\n */\nexport function getReplicationCursor(\n\tdb: Database,\n\tpeerDeviceId: string,\n\tscopeId?: string | null,\n): [lastApplied: string | null, lastAcked: string | null] {\n\tensureReplicationCursorTables(db);\n\tconst effectiveScopeId = normalizeSyncStateScopeId(scopeId);\n\tif (effectiveScopeId === DEFAULT_SYNC_SCOPE_ID) {\n\t\tseedDefaultReplicationCursorFromLegacy(db);\n\t}\n\tconst d = drizzle(db, { schema });\n\tconst row = d\n\t\t.select({\n\t\t\tlast_applied_cursor: schema.replicationCursorsV2.last_applied_cursor,\n\t\t\tlast_acked_cursor: schema.replicationCursorsV2.last_acked_cursor,\n\t\t})\n\t\t.from(schema.replicationCursorsV2)\n\t\t.where(\n\t\t\tand(\n\t\t\t\teq(schema.replicationCursorsV2.peer_device_id, peerDeviceId),\n\t\t\t\teq(schema.replicationCursorsV2.scope_id, effectiveScopeId),\n\t\t\t),\n\t\t)\n\t\t.get();\n\n\tif (!row) return [null, null];\n\treturn [row.last_applied_cursor, row.last_acked_cursor];\n}\n\n/**\n * Insert or update the replication cursor for a peer device.\n *\n * Uses COALESCE on update so callers can set only one of the two cursors\n * without clobbering the other.\n */\nexport function setReplicationCursor(\n\tdb: Database,\n\tpeerDeviceId: string,\n\toptions: { lastApplied?: string | null; lastAcked?: string | null } = {},\n\tscopeId?: string | null,\n): void {\n\tensureReplicationCursorTables(db);\n\tconst now = new Date().toISOString();\n\tconst effectiveScopeId = normalizeSyncStateScopeId(scopeId);\n\tif (effectiveScopeId === DEFAULT_SYNC_SCOPE_ID) {\n\t\tseedDefaultReplicationCursorFromLegacy(db);\n\t}\n\tconst lastApplied = options.lastApplied ?? null;\n\tconst lastAcked = options.lastAcked ?? null;\n\n\tconst d = drizzle(db, { schema });\n\t// Atomic UPSERT — avoids TOCTOU race with concurrent sync workers.\n\t// Drizzle's onConflictDoUpdate doesn't support COALESCE(excluded.col, col)\n\t// natively, so we use raw SQL for the SET expressions.\n\td.insert(schema.replicationCursorsV2)\n\t\t.values({\n\t\t\tpeer_device_id: peerDeviceId,\n\t\t\tscope_id: effectiveScopeId,\n\t\t\tlast_applied_cursor: lastApplied,\n\t\t\tlast_acked_cursor: lastAcked,\n\t\t\tupdated_at: now,\n\t\t})\n\t\t.onConflictDoUpdate({\n\t\t\ttarget: [schema.replicationCursorsV2.peer_device_id, schema.replicationCursorsV2.scope_id],\n\t\t\tset: {\n\t\t\t\tlast_applied_cursor: sql`COALESCE(excluded.last_applied_cursor, ${schema.replicationCursorsV2.last_applied_cursor})`,\n\t\t\t\tlast_acked_cursor: sql`COALESCE(excluded.last_acked_cursor, ${schema.replicationCursorsV2.last_acked_cursor})`,\n\t\t\t\tupdated_at: sql`excluded.updated_at`,\n\t\t\t},\n\t\t})\n\t\t.run();\n\tif (effectiveScopeId === DEFAULT_SYNC_SCOPE_ID) {\n\t\tmirrorDefaultReplicationCursorToLegacy(db, peerDeviceId, options, now);\n\t}\n}\n\nexport function clearReplicationCursorLastApplied(\n\tdb: Database,\n\tpeerDeviceId: string,\n\tscopeId?: string | null,\n): void {\n\tensureReplicationCursorTables(db);\n\tconst now = new Date().toISOString();\n\tconst effectiveScopeId = normalizeSyncStateScopeId(scopeId);\n\tdrizzle(db, { schema })\n\t\t.update(schema.replicationCursorsV2)\n\t\t.set({\n\t\t\tlast_applied_cursor: null,\n\t\t\tlast_acked_cursor: null,\n\t\t\tupdated_at: now,\n\t\t})\n\t\t.where(\n\t\t\tand(\n\t\t\t\teq(schema.replicationCursorsV2.peer_device_id, peerDeviceId),\n\t\t\t\teq(schema.replicationCursorsV2.scope_id, effectiveScopeId),\n\t\t\t),\n\t\t)\n\t\t.run();\n}\n\n// Payload extraction\n\n/**\n * Extract replication ops from a parsed JSON payload.\n *\n * Returns an empty array if the payload is not an object or lacks an `ops` array.\n */\n/** Required fields for a valid replication op. */\nconst REQUIRED_OP_FIELDS = [\n\t\"op_id\",\n\t\"entity_type\",\n\t\"entity_id\",\n\t\"op_type\",\n\t\"clock_rev\",\n\t\"clock_updated_at\",\n\t\"clock_device_id\",\n\t\"device_id\",\n\t\"created_at\",\n] as const;\n\n/**\n * Extract and validate replication ops from a parsed JSON payload.\n *\n * Returns an empty array if the payload is not an object or lacks an `ops` array.\n * Silently filters out ops missing required fields to prevent garbage data\n * from entering the replication pipeline.\n */\nexport function extractReplicationOps(payload: unknown): ReplicationOp[] {\n\tif (typeof payload !== \"object\" || payload === null) return [];\n\tconst obj = payload as Record<string, unknown>;\n\tconst ops = obj.ops;\n\tif (!Array.isArray(ops)) return [];\n\n\treturn ops.filter((op): op is ReplicationOp => {\n\t\tif (typeof op !== \"object\" || op === null) return false;\n\t\tconst record = op as Record<string, unknown>;\n\t\treturn REQUIRED_OP_FIELDS.every(\n\t\t\t(field) => record[field] !== undefined && record[field] !== null,\n\t\t);\n\t});\n}\n\n// Clock comparison\n\n/**\n * Build a clock tuple from individual fields.\n *\n * Clock tuples enable lexicographic comparison for last-writer-wins\n * conflict resolution: higher rev wins, tiebreak on updated_at, then device_id.\n */\nexport function clockTuple(\n\trev: number,\n\tupdatedAt: string,\n\tdeviceId: string,\n): [number, string, string] {\n\treturn [rev, updatedAt, deviceId];\n}\n\n/**\n * Return true if `candidate` clock is strictly newer than `existing`.\n *\n * Comparison order: rev (higher wins) → updated_at → device_id.\n * Mirrors Python's `_is_newer_clock` which relies on tuple ordering.\n */\nexport function isNewerClock(\n\tcandidate: [number, string, string],\n\texisting: [number, string, string],\n): boolean {\n\tif (candidate[0] !== existing[0]) return candidate[0] > existing[0];\n\tif (candidate[1] !== existing[1]) return candidate[1] > existing[1];\n\treturn candidate[2] > existing[2];\n}\n\n// Record a replication op\n\n/**\n * Generate and INSERT a single replication op for a memory item.\n *\n * Reads the memory item's clock fields (rev, updated_at, metadata_json)\n * from the DB, builds the op row, and inserts into `replication_ops`.\n * Returns the generated op_id (UUID).\n *\n * Uses Drizzle's typed select so all memory_items columns are captured\n * automatically — no hand-maintained column list to go out of sync.\n */\nexport function recordReplicationOp(\n\tdb: Database,\n\topts: {\n\t\tmemoryId: number;\n\t\topType: \"upsert\" | \"delete\";\n\t\tdeviceId: string;\n\t\tpayload?: Record<string, unknown>;\n\t\tscopeId?: string | null;\n\t\tclockRev?: number;\n\t\tclockUpdatedAt?: string;\n\t\tclockDeviceId?: string;\n\t\tcreatedAt?: string;\n\t\topId?: string;\n\t},\n): string {\n\tconst d = drizzle(db, { schema });\n\tconst opId = opts.opId ?? randomUUID();\n\tconst now = opts.createdAt ?? new Date().toISOString();\n\n\t// Read the full memory row — typed via Drizzle schema\n\tconst row = d\n\t\t.select()\n\t\t.from(schema.memoryItems)\n\t\t.where(eq(schema.memoryItems.id, opts.memoryId))\n\t\t.get();\n\n\tconst rev = opts.clockRev ?? Number(row?.rev ?? 0);\n\tconst updatedAt = opts.clockUpdatedAt ?? row?.updated_at ?? now;\n\tconst entityId = row?.import_key ?? String(opts.memoryId);\n\tconst metadata = fromJson(row?.metadata_json);\n\t// Backfill missing memory scope before emitting an op so storage, op row,\n\t// and payload all carry the same authoritative local scope.\n\tconst scopeId =\n\t\topts.scopeId !== undefined ? opts.scopeId : row ? ensureMemoryScopeId(db, opts.memoryId) : null;\n\tconst clockDeviceId =\n\t\ttypeof opts.clockDeviceId === \"string\" && opts.clockDeviceId.trim().length > 0\n\t\t\t? opts.clockDeviceId.trim()\n\t\t\t: typeof metadata.clock_device_id === \"string\" && metadata.clock_device_id.trim().length > 0\n\t\t\t\t? metadata.clock_device_id\n\t\t\t\t: opts.deviceId;\n\n\t// Resolve session project so peers can reconstruct the project association.\n\tconst sessionProject = row?.session_id\n\t\t? (d\n\t\t\t\t.select({ project: schema.sessions.project })\n\t\t\t\t.from(schema.sessions)\n\t\t\t\t.where(eq(schema.sessions.id, row.session_id))\n\t\t\t\t.get()?.project ?? null)\n\t\t: null;\n\n\t// Build payload from the memory row so peers can reconstruct the full item.\n\t// Explicit payload override wins except for authoritative scope_id on upserts.\n\tlet payloadJson: string | null;\n\tif (opts.payload) {\n\t\tpayloadJson = toJson(\n\t\t\trow && opts.opType === \"upsert\" ? { ...opts.payload, scope_id: scopeId } : opts.payload,\n\t\t);\n\t} else if (row && opts.opType === \"upsert\") {\n\t\t// Parse JSON-string columns so they round-trip as objects, not double-encoded strings\n\t\tconst parseSqliteJson = (val: string | null | undefined): unknown => {\n\t\t\tif (typeof val !== \"string\") return val ?? null;\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(val);\n\t\t\t} catch {\n\t\t\t\treturn val;\n\t\t\t}\n\t\t};\n\n\t\tpayloadJson = toJson({\n\t\t\tproject: sessionProject,\n\t\t\tsession_id: row.session_id,\n\t\t\tkind: row.kind,\n\t\t\ttitle: row.title,\n\t\t\tsubtitle: row.subtitle,\n\t\t\tbody_text: row.body_text,\n\t\t\tconfidence: row.confidence,\n\t\t\ttags_text: row.tags_text,\n\t\t\tactive: row.active,\n\t\t\tcreated_at: row.created_at,\n\t\t\tupdated_at: row.updated_at,\n\t\t\tmetadata_json: parseSqliteJson(row.metadata_json),\n\t\t\tactor_id: row.actor_id,\n\t\t\tactor_display_name: row.actor_display_name,\n\t\t\tvisibility: row.visibility,\n\t\t\tworkspace_id: row.workspace_id,\n\t\t\tworkspace_kind: row.workspace_kind,\n\t\t\torigin_device_id: row.origin_device_id,\n\t\t\torigin_source: row.origin_source,\n\t\t\ttrust_state: row.trust_state,\n\t\t\tfacts: parseSqliteJson(row.facts),\n\t\t\tnarrative: row.narrative,\n\t\t\tconcepts: parseSqliteJson(row.concepts),\n\t\t\tfiles_read: parseSqliteJson(row.files_read),\n\t\t\tfiles_modified: parseSqliteJson(row.files_modified),\n\t\t\tuser_prompt_id: row.user_prompt_id,\n\t\t\tprompt_number: row.prompt_number,\n\t\t\tdeleted_at: row.deleted_at,\n\t\t\tscope_id: scopeId,\n\t\t});\n\t} else {\n\t\tpayloadJson = null;\n\t}\n\n\td.insert(schema.replicationOps)\n\t\t.values({\n\t\t\top_id: opId,\n\t\t\tentity_type: \"memory_item\",\n\t\t\tentity_id: entityId,\n\t\t\top_type: opts.opType,\n\t\t\tpayload_json: payloadJson,\n\t\t\tclock_rev: rev,\n\t\t\tclock_updated_at: updatedAt,\n\t\t\tclock_device_id: clockDeviceId,\n\t\t\tdevice_id: opts.deviceId,\n\t\t\tcreated_at: now,\n\t\t\tscope_id: scopeId,\n\t\t})\n\t\t.run();\n\n\treturn opId;\n}\n\nfunction deterministicReassignOpId(\n\toperationId: string,\n\tmemoryId: string,\n\toldScopeId: string,\n\tnewScopeId: string,\n\tside: \"old\" | \"new\",\n): string {\n\treturn `reassign_${createHash(\"sha256\")\n\t\t.update(JSON.stringify([operationId, memoryId, oldScopeId, newScopeId, side]))\n\t\t.digest(\"hex\")}`;\n}\n\nfunction reassignmentEntityId(existing: MemoryItemRow): string {\n\treturn existing.import_key ?? String(existing.id);\n}\n\nfunction writeUnretiredReassignment(\n\tdb: Database,\n\tentityId: string,\n\tscopeId: string,\n\twrite: () => void,\n): void {\n\tdb.transaction(() => {\n\t\tassertMemoryScopeNotRetired(db, entityId, scopeId);\n\t\twrite();\n\t}).immediate();\n}\n\nexport function recordScopeReassignment(\n\tdb: Database,\n\topts: {\n\t\toperationId: string;\n\t\tmemoryId: number;\n\t\toldScopeId: string;\n\t\tnewScopeId: string;\n\t\tdeviceId: string;\n\t\tcreatedAt?: string;\n\t},\n): { revision: number; oldOpId: string; newOpId: string } {\n\tconst operationId = requiredPayloadText(opts.operationId);\n\tconst oldScopeId = requiredPayloadText(opts.oldScopeId);\n\tconst newScopeId = requiredPayloadText(opts.newScopeId);\n\tconst deviceId = requiredPayloadText(opts.deviceId);\n\tif (\n\t\t!operationId ||\n\t\t!oldScopeId ||\n\t\t!newScopeId ||\n\t\toldScopeId === newScopeId ||\n\t\t!deviceId ||\n\t\t!Number.isSafeInteger(opts.memoryId) ||\n\t\topts.memoryId <= 0\n\t) {\n\t\tthrow new Error(\"reassign_input_invalid\");\n\t}\n\tconst d = drizzle(db, { schema });\n\tconst existing = d\n\t\t.select()\n\t\t.from(schema.memoryItems)\n\t\t.where(eq(schema.memoryItems.id, opts.memoryId))\n\t\t.get();\n\tif (!existing) throw new Error(\"reassign_memory_not_found\");\n\tconst memoryId = reassignmentEntityId(existing);\n\tconst oldOpId = deterministicReassignOpId(operationId, memoryId, oldScopeId, newScopeId, \"old\");\n\tconst newOpId = deterministicReassignOpId(operationId, memoryId, oldScopeId, newScopeId, \"new\");\n\tconst existingOps = db\n\t\t.prepare(\"SELECT op_id, clock_rev FROM replication_ops WHERE op_id IN (?, ?)\")\n\t\t.all(oldOpId, newOpId) as Array<{ op_id: string; clock_rev: number }>;\n\tif (existingOps.length > 0) {\n\t\tif (\n\t\t\texistingOps.length !== 2 ||\n\t\t\texistingOps.some((op) => op.clock_rev !== existingOps[0]?.clock_rev)\n\t\t) {\n\t\t\tthrow new Error(\"reassign_replay_conflict\");\n\t\t}\n\t\treturn { revision: Number(existingOps[0]?.clock_rev ?? 0), oldOpId, newOpId };\n\t}\n\tif ((cleanText(existing.scope_id) ?? DEFAULT_SYNC_SCOPE_ID) !== oldScopeId) {\n\t\tthrow new Error(\"reassign_old_scope_mismatch\");\n\t}\n\tconst revision = Number(existing.rev ?? 0) + 1;\n\tconst createdAt = opts.createdAt ?? new Date().toISOString();\n\tconst metadata = fromJson(existing.metadata_json);\n\tObject.assign(metadata, { clock_device_id: deviceId, scope_id: newScopeId });\n\tmetadata.last_scope_reassignment = {\n\t\toperation_id: operationId,\n\t\told_scope_id: oldScopeId,\n\t\tnew_scope_id: newScopeId,\n\t\trevision,\n\t};\n\tconst write = db.transaction(() => {\n\t\td.update(schema.memoryItems)\n\t\t\t.set({\n\t\t\t\tscope_id: newScopeId,\n\t\t\t\trev: revision,\n\t\t\t\tupdated_at: createdAt,\n\t\t\t\tmetadata_json: toJson(metadata),\n\t\t\t})\n\t\t\t.where(eq(schema.memoryItems.id, opts.memoryId))\n\t\t\t.run();\n\t\tconst updated = d\n\t\t\t.select()\n\t\t\t.from(schema.memoryItems)\n\t\t\t.where(eq(schema.memoryItems.id, opts.memoryId))\n\t\t\t.get();\n\t\tif (!updated) throw new Error(\"reassign_memory_not_found\");\n\t\tconst sessionProject = updated.session_id\n\t\t\t? cleanText(\n\t\t\t\t\tdb.prepare(\"SELECT project FROM sessions WHERE id = ?\").pluck().get(updated.session_id),\n\t\t\t\t)\n\t\t\t: null;\n\t\tconst common = {\n\t\t\toperation_id: operationId,\n\t\t\tmemory_id: memoryId,\n\t\t\told_scope_id: oldScopeId,\n\t\t\tnew_scope_id: newScopeId,\n\t\t\trevision,\n\t\t};\n\t\tconst insert = db.prepare(`INSERT INTO replication_ops(\n\t\t\top_id, entity_type, entity_id, op_type, payload_json, clock_rev,\n\t\t\tclock_updated_at, clock_device_id, device_id, created_at, scope_id\n\t\t) VALUES (?, 'memory_item', ?, ?, ?, ?, ?, ?, ?, ?, ?)`);\n\t\tinsert.run(\n\t\t\toldOpId,\n\t\t\tmemoryId,\n\t\t\tREASSIGN_SCOPE_OP_TYPE,\n\t\t\ttoJson({ ...common, side: \"old\" }),\n\t\t\trevision,\n\t\t\tcreatedAt,\n\t\t\tdeviceId,\n\t\t\tdeviceId,\n\t\t\tcreatedAt,\n\t\t\toldScopeId,\n\t\t);\n\t\tinsert.run(\n\t\t\tnewOpId,\n\t\t\tmemoryId,\n\t\t\tREASSIGN_SCOPE_OP_TYPE,\n\t\t\ttoJson({\n\t\t\t\t...buildPayloadFromMemoryRow(updated),\n\t\t\t\tproject: cleanText(updated.project) ?? sessionProject,\n\t\t\t\t...common,\n\t\t\t\tside: \"new\",\n\t\t\t\tscope_id: newScopeId,\n\t\t\t}),\n\t\t\trevision,\n\t\t\tcreatedAt,\n\t\t\tdeviceId,\n\t\t\tdeviceId,\n\t\t\tcreatedAt,\n\t\t\tnewScopeId,\n\t\t);\n\t});\n\twriteUnretiredReassignment(db, memoryId, newScopeId, write);\n\treturn { revision, oldOpId, newOpId };\n}\n\nexport function recordAccessCleanupOp(\n\tdb: Database,\n\topts: {\n\t\timportKey: string;\n\t\tdeviceId: string;\n\t\tcleanupScopeId: string;\n\t\tclockRev: number;\n\t\tclockUpdatedAt: string;\n\t\tclockDeviceId?: string;\n\t\tcreatedAt?: string;\n\t\ttargetPeerDeviceId?: string | null;\n\t\treason?: string | null;\n\t\topId?: string;\n\t},\n): string {\n\tconst d = drizzle(db, { schema });\n\tconst opId = opts.opId ?? randomUUID();\n\tconst now = opts.createdAt ?? new Date().toISOString();\n\tconst payload = {\n\t\tcleanup_scope_id: opts.cleanupScopeId,\n\t\treason: cleanText(opts.reason) ?? \"scope_access_cleanup\",\n\t\t...(cleanText(opts.targetPeerDeviceId)\n\t\t\t? { target_peer_device_id: cleanText(opts.targetPeerDeviceId) }\n\t\t\t: {}),\n\t};\n\td.insert(schema.replicationOps)\n\t\t.values({\n\t\t\top_id: opId,\n\t\t\tentity_type: \"memory_item\",\n\t\t\tentity_id: opts.importKey,\n\t\t\top_type: ACCESS_CLEANUP_OP_TYPE,\n\t\t\tpayload_json: toJson(payload),\n\t\t\tclock_rev: opts.clockRev,\n\t\t\tclock_updated_at: opts.clockUpdatedAt,\n\t\t\tclock_device_id: opts.clockDeviceId ?? opts.deviceId,\n\t\t\tdevice_id: opts.deviceId,\n\t\t\tcreated_at: now,\n\t\t\tscope_id: DEFAULT_SYNC_SCOPE_ID,\n\t\t})\n\t\t.run();\n\treturn opId;\n}\n\n// Load replication ops with cursor pagination\n\n/** Parse a `created_at|op_id` cursor into its two components. */\nfunction parseCursor(cursor: string): [createdAt: string, opId: string] | null {\n\tconst idx = cursor.indexOf(\"|\");\n\tif (idx < 0) return null;\n\treturn [cursor.slice(0, idx), cursor.slice(idx + 1)];\n}\n\n/** Build a `created_at|op_id` cursor string. */\nfunction computeCursor(createdAt: string, opId: string): string {\n\treturn `${createdAt}|${opId}`;\n}\n\n/**\n * Load replication ops created after `cursor`, ordered by (created_at, op_id).\n *\n * Returns `[ops, nextCursor]` where nextCursor is the cursor for the last\n * returned row (or null if no rows matched). The cursor format is\n * `created_at|op_id`.\n */\nexport function loadReplicationOpsSince(\n\tdb: Database,\n\tcursor: string | null,\n\tlimit = 100,\n\tdeviceId?: string,\n\tscopeId?: string | null,\n): [ReplicationOp[], string | null] {\n\tconst d = drizzle(db, { schema });\n\tconst t = schema.replicationOps;\n\tconst conditions = [];\n\tconst scopeFilterRequested = scopeId !== undefined;\n\tconst effectiveScopeId = normalizeSyncStateScopeId(scopeId);\n\n\tif (cursor) {\n\t\tconst parsed = parseCursor(cursor);\n\t\tif (parsed) {\n\t\t\tconst [createdAt, opId] = parsed;\n\t\t\tconditions.push(\n\t\t\t\tor(gt(t.created_at, createdAt), and(eq(t.created_at, createdAt), gt(t.op_id, opId))),\n\t\t\t);\n\t\t}\n\t}\n\n\tif (deviceId) {\n\t\tconditions.push(\n\t\t\tor(and(eq(t.device_id, deviceId), eq(t.clock_device_id, deviceId)), eq(t.device_id, \"local\")),\n\t\t);\n\t}\n\n\tif (scopeFilterRequested) {\n\t\tconditions.push(\n\t\t\teffectiveScopeId === DEFAULT_SYNC_SCOPE_ID\n\t\t\t\t? or(isNull(t.scope_id), eq(t.scope_id, DEFAULT_SYNC_SCOPE_ID))\n\t\t\t\t: eq(t.scope_id, effectiveScopeId),\n\t\t);\n\t}\n\n\tconst whereClause = conditions.length > 0 ? and(...conditions) : undefined;\n\n\tconst rows = d\n\t\t.select()\n\t\t.from(t)\n\t\t.where(whereClause)\n\t\t.orderBy(t.created_at, t.op_id)\n\t\t.limit(limit)\n\t\t.all();\n\n\tconst ops: ReplicationOp[] = rows.map((r) => ({\n\t\top_id: r.op_id,\n\t\tentity_type: r.entity_type,\n\t\tentity_id: r.entity_id,\n\t\top_type: r.op_type,\n\t\tpayload_json: r.payload_json,\n\t\tclock_rev: r.clock_rev,\n\t\tclock_updated_at: r.clock_updated_at,\n\t\tclock_device_id: r.clock_device_id,\n\t\tdevice_id: r.device_id,\n\t\tcreated_at: r.created_at,\n\t\tscope_id: r.scope_id,\n\t}));\n\n\tlet nextCursor: string | null = null;\n\tif (rows.length > 0) {\n\t\tconst last = rows.at(-1);\n\t\tif (last) {\n\t\t\tnextCursor = computeCursor(last.created_at, last.op_id);\n\t\t}\n\t}\n\n\treturn [ops, nextCursor];\n}\n\n/**\n * Trims a pull page to the byte cap. The next page starts after the last op\n * returned, so ops filtered out after it are scanned and filtered again.\n */\nfunction opsPageWithinBytes(\n\tops: ReplicationOp[],\n\tnextCursor: string | null,\n\tmaxBytes = SYNC_PAGE_MAX_BYTES,\n): { ops: ReplicationOp[]; nextCursor: string | null } {\n\tconst kept = entriesWithinBytes(ops, maxBytes);\n\tconst last = ops[kept - 1];\n\tif (kept === ops.length || !last) return { ops, nextCursor };\n\treturn { ops: ops.slice(0, kept), nextCursor: computeCursor(last.created_at, last.op_id) };\n}\n\nexport function loadReplicationOpsForPeer(\n\tdb: Database,\n\toptions: LoadReplicationOpsForPeerOptions,\n): LoadReplicationOpsForPeerResult {\n\tconst scopeFilterRequested = options.scopeId !== undefined;\n\tconst effectiveScopeId = normalizeSyncStateScopeId(options.scopeId);\n\tconst boundary = getSyncResetState(db, scopeFilterRequested ? options.scopeId : undefined);\n\tconst since = normalizeCursor(options.since);\n\tconst requestedGeneration = options.generation ?? null;\n\tconst requestedSnapshotId = normalizeCursor(options.snapshotId);\n\tconst requestedBaselineCursor = normalizeCursor(options.baselineCursor);\n\tconst hasAnyBoundaryField =\n\t\trequestedGeneration != null || requestedSnapshotId != null || requestedBaselineCursor != null;\n\n\tif (requestedGeneration != null && requestedGeneration !== boundary.generation) {\n\t\treturn resetRequired(boundary, \"generation_mismatch\");\n\t}\n\n\tconst hasCompleteBoundary =\n\t\trequestedGeneration != null &&\n\t\trequestedSnapshotId != null &&\n\t\trequestedBaselineCursor === boundary.baseline_cursor;\n\n\tif (!hasAnyBoundaryField || !hasCompleteBoundary) {\n\t\treturn resetRequired(boundary, \"boundary_mismatch\");\n\t}\n\n\tif (\n\t\trequestedSnapshotId !== boundary.snapshot_id ||\n\t\trequestedBaselineCursor !== boundary.baseline_cursor\n\t) {\n\t\treturn resetRequired(boundary, \"boundary_mismatch\");\n\t}\n\n\tif (\n\t\tsince != null &&\n\t\tboundary.retained_floor_cursor != null &&\n\t\tsince < boundary.retained_floor_cursor\n\t) {\n\t\treturn resetRequired(boundary, \"stale_cursor\");\n\t}\n\n\tconst [ops, nextCursor] = loadReplicationOpsSince(\n\t\tdb,\n\t\tsince,\n\t\toptions.limit,\n\t\t// `/v1/ops` is an author stream, not a Space relay. Even when a\n\t\t// scoped request filters by `scope_id`, this keeps returned ops authored\n\t\t// by the serving device (plus legacy `local` rows) so receivers can keep\n\t\t// rejecting batches whose device_id / clock_device_id do not match the\n\t\t// authenticated peer.\n\t\toptions.deviceId,\n\t\teffectiveScopeId,\n\t);\n\tconst peerBoundaryOps = ops.filter((op) => {\n\t\tif (op.entity_type !== \"memory_item\") return true;\n\t\tif (retirementBlocksMemoryOp(db, op)) return false;\n\t\tif (op.op_type === ACCESS_CLEANUP_OP_TYPE || op.op_type === REASSIGN_SCOPE_OP_TYPE) {\n\t\t\treturn true;\n\t\t}\n\t\tconst scopeId = cleanText(op.scope_id);\n\t\treturn Boolean(scopeId && scopeId !== DEFAULT_SYNC_SCOPE_ID);\n\t});\n\tconst page = opsPageWithinBytes(peerBoundaryOps, nextCursor, options.maxBytes);\n\treturn { reset_required: false, boundary, ...page };\n}\n\nfunction snapshotClockDeviceId(payload: MemoryPayload, row: MemoryItemRow): string {\n\tconst metadata = payload.metadata_json;\n\tif (typeof metadata?.clock_device_id === \"string\" && metadata.clock_device_id.trim())\n\t\treturn metadata.clock_device_id.trim();\n\treturn String(row.origin_device_id ?? \"local\");\n}\n\nfunction unretiredSnapshotPayload(\n\tdb: Database,\n\trow: MemoryItemRow,\n\tsourceDeviceId?: string,\n): MemoryPayload | null {\n\tif (sourceDeviceId && memorySourceNamespace(row.import_key ?? \"\") !== sourceDeviceId) return null;\n\tconst payload = buildPayloadFromMemoryRow(row);\n\tif (\n\t\t!retirementAllowsSnapshot(\n\t\t\tdb,\n\t\t\tString(row.import_key ?? \"\"),\n\t\t\tpayload as unknown as Record<string, unknown>,\n\t\t\tcleanText(row.scope_id),\n\t\t)\n\t)\n\t\treturn null;\n\treturn payload;\n}\n\ntype SnapshotRow = { memory: MemoryItemRow; sessionProject: string | null };\n\n/** The snapshot item for one memory row, or null when the peer may not receive it. */\nfunction snapshotItemForPeer(\n\tdb: Database,\n\trow: SnapshotRow,\n\timportKey: string,\n\toptions: LoadMemorySnapshotPageForPeerOptions,\n): SyncMemorySnapshotItem | null {\n\tconst payload = unretiredSnapshotPayload(db, row.memory, options.sourceDeviceId);\n\tif (!payload) return null;\n\tconst record = payload as unknown as Record<string, unknown>;\n\tconst scope = { scope_id: row.memory.scope_id };\n\tconst peerDeviceId = options.peerDeviceId ?? null;\n\tif (\n\t\t(replicationOpRequiresPersonalScopeAuthorization(scope, record) ||\n\t\t\t!syncVisibilityAllowed(record)) &&\n\t\t!peerCanSyncPrivateOpByPersonalScopeGrant(db, scope, record, peerDeviceId)\n\t)\n\t\treturn null;\n\tif (!syncProjectAllowed(db, row.sessionProject, peerDeviceId)) return null;\n\t// Include session project in the payload so targets can associate\n\t// replicated memories with the correct project.\n\tconst payloadWithProject = { ...payload, project: row.sessionProject ?? null };\n\treturn {\n\t\tentity_id: importKey,\n\t\top_type: row.memory.deleted_at || row.memory.active === 0 ? \"delete\" : \"upsert\",\n\t\tpayload_json: toJson(payloadWithProject),\n\t\tclock_rev: Number(row.memory.rev ?? 0),\n\t\tclock_updated_at: String(\n\t\t\trow.memory.updated_at ?? row.memory.created_at ?? new Date().toISOString(),\n\t\t),\n\t\tclock_device_id: snapshotClockDeviceId(payload, row.memory),\n\t};\n}\n\nexport function loadMemorySnapshotPageForPeer(\n\tdb: Database,\n\toptions: LoadMemorySnapshotPageForPeerOptions,\n): LoadMemorySnapshotPageForPeerResult {\n\tconst scopeFilterRequested = options.scopeId !== undefined;\n\tconst effectiveScopeId = normalizeSyncStateScopeId(options.scopeId);\n\tconst boundary = getSyncResetState(db, scopeFilterRequested ? options.scopeId : undefined);\n\tif (scopeFilterRequested) {\n\t\tconst scope = db\n\t\t\t.prepare(\"SELECT authority_type FROM replication_scopes WHERE scope_id = ? LIMIT 1\")\n\t\t\t.get(effectiveScopeId) as { authority_type?: string | null } | undefined;\n\t\tif (scope?.authority_type === \"local\") {\n\t\t\treturn { boundary, items: [], nextPageToken: null, hasMore: false };\n\t\t}\n\t}\n\tif (options.generation !== boundary.generation) {\n\t\tthrow new Error(\"generation_mismatch\");\n\t}\n\tif (normalizeCursor(options.snapshotId) !== boundary.snapshot_id) {\n\t\tthrow new Error(\"boundary_mismatch\");\n\t}\n\tif (normalizeCursor(options.baselineCursor) !== boundary.baseline_cursor) {\n\t\tthrow new Error(\"boundary_mismatch\");\n\t}\n\tconst peerDeviceId = cleanText(options.peerDeviceId);\n\tif (\n\t\tscopeFilterRequested &&\n\t\tpeerDeviceId &&\n\t\tgetAnyRecipientPolicyDenyOverlayForScopeDevice(db, {\n\t\t\tscopeId: effectiveScopeId,\n\t\t\tdeviceId: peerDeviceId,\n\t\t})\n\t) {\n\t\treturn { boundary, items: [], nextPageToken: null, hasMore: false };\n\t}\n\n\t// Cap raised to 5000 to support elevated bootstrap page sizes (default 2000).\n\tconst limit = Math.max(1, Math.min(options.limit ?? 200, 5000));\n\tconst pageToken = parseSnapshotPageToken(options.pageToken);\n\tconst d = drizzle(db, { schema });\n\t// Scan batch must be >= limit so high page sizes don't degrade into\n\t// multiple keyset-pagination round-trips per page.\n\tconst scanBatchSize = Math.max(limit, Math.min(limit * 3, 10000));\n\tconst rowsAfterToken = (token: { importKey: string; id: number } | null, batchLimit: number) =>\n\t\td\n\t\t\t.select({\n\t\t\t\tmemory: schema.memoryItems,\n\t\t\t\tsessionProject: schema.sessions.project,\n\t\t\t})\n\t\t\t.from(schema.memoryItems)\n\t\t\t.innerJoin(schema.sessions, eq(schema.sessions.id, schema.memoryItems.session_id))\n\t\t\t.where(\n\t\t\t\tand(\n\t\t\t\t\tisNotNull(schema.memoryItems.import_key),\n\t\t\t\t\teffectiveScopeId === DEFAULT_SYNC_SCOPE_ID\n\t\t\t\t\t\t? sql`0 = 1`\n\t\t\t\t\t\t: eq(schema.memoryItems.scope_id, effectiveScopeId),\n\t\t\t\t\ttoken\n\t\t\t\t\t\t? or(\n\t\t\t\t\t\t\t\tgt(schema.memoryItems.import_key, token.importKey),\n\t\t\t\t\t\t\t\tand(\n\t\t\t\t\t\t\t\t\teq(schema.memoryItems.import_key, token.importKey),\n\t\t\t\t\t\t\t\t\tgt(schema.memoryItems.id, token.id),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: undefined,\n\t\t\t\t),\n\t\t\t)\n\t\t\t.orderBy(schema.memoryItems.import_key, schema.memoryItems.id)\n\t\t\t.limit(batchLimit)\n\t\t\t.all();\n\n\tconst items: SyncMemorySnapshotItem[] = [];\n\tconst maxBytes = options.maxBytes ?? SYNC_PAGE_MAX_BYTES;\n\tlet pageBytes = 0;\n\tlet nextScanToken = pageToken;\n\tlet lastScannedToken: string | null = null;\n\tlet hasMore = false;\n\tlet full = false;\n\n\twhile (items.length < limit && !full) {\n\t\tconst rows = rowsAfterToken(nextScanToken, scanBatchSize);\n\t\tif (rows.length === 0) break;\n\n\t\tfor (let index = 0; index < rows.length; index += 1) {\n\t\t\tconst row = rows[index];\n\t\t\tif (!row) continue;\n\t\t\tconst importKey = String(row.memory.import_key ?? \"\").trim();\n\t\t\tif (!importKey) continue;\n\t\t\t// An earlier row is always on the page when this is used, so it is never null then.\n\t\t\tconst tokenBeforeRow: string | null = lastScannedToken;\n\t\t\tlastScannedToken = makeSnapshotPageToken(importKey, Number(row.memory.id));\n\t\t\tnextScanToken = { importKey, id: Number(row.memory.id) };\n\t\t\tconst item = snapshotItemForPeer(db, row, importKey, options);\n\t\t\tif (!item) continue;\n\t\t\tconst itemBytes = Buffer.byteLength(JSON.stringify(item)) + 1;\n\t\t\tif (items.length > 0 && pageBytes + itemBytes > maxBytes) {\n\t\t\t\t// This row goes on the next page, so the token stops before it.\n\t\t\t\tlastScannedToken = tokenBeforeRow;\n\t\t\t\thasMore = true;\n\t\t\t\tfull = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\titems.push(item);\n\t\t\tpageBytes += itemBytes;\n\n\t\t\tif (items.length >= limit) {\n\t\t\t\thasMore = index < rows.length - 1 || rowsAfterToken(nextScanToken, 1).length > 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (full || items.length >= limit || rows.length < scanBatchSize) break;\n\t}\n\treturn {\n\t\tboundary,\n\t\titems,\n\t\tnextPageToken: hasMore ? lastScannedToken : null,\n\t\thasMore: hasMore && lastScannedToken != null,\n\t};\n}\n\nexport function hasUnsyncedSharedMemoryChanges(db: Database, limit = 25): SyncDirtyLocalState {\n\t// Single SQL query replacing the old O(N×M) JS loop that loaded every\n\t// memory item then queried replication_ops per-row. This uses NOT EXISTS\n\t// to find shared memories whose current rev lacks a matching replication op,\n\t// which is exactly the \"dirty\" condition the old loop was checking.\n\t//\n\t// Visibility matching follows syncVisibilityAllowed semantics:\n\t// - explicit 'shared', 'shared:default', 'shared:legacy' → sync-eligible\n\t// - NULL/empty visibility with non-private content → sync-eligible (legacy default)\n\t// - explicit 'private' or 'personal:*' → not sync-eligible\n\tconst stmt = db.prepare(`\n\t\tSELECT count(*) as n FROM (\n\t\t\tSELECT 1 FROM memory_items m\n\t\t\tWHERE m.import_key IS NOT NULL\n\t\t\t AND COALESCE(m.visibility, '') NOT LIKE 'private%'\n\t\t\t AND COALESCE(m.visibility, '') NOT LIKE 'personal%'\n\t\t\t AND NOT EXISTS (\n\t\t\t\tSELECT 1 FROM replication_ops r\n\t\t\t\tWHERE r.entity_type = 'memory_item'\n\t\t\t\t AND r.entity_id = m.import_key\n\t\t\t\t AND r.op_type = CASE WHEN m.deleted_at IS NOT NULL OR m.active = 0 THEN 'delete' ELSE 'upsert' END\n\t\t\t\t AND r.clock_rev = COALESCE(m.rev, 0)\n\t\t\t )\n\t\t\tLIMIT ?\n\t\t)\n\t`);\n\tconst row = stmt.get(limit) as { n: number } | undefined;\n\tconst count = Number(row?.n ?? 0);\n\treturn { dirty: count > 0, count };\n}\n\nexport function pruneReplicationOps(\n\tdb: Database,\n\toptions?: {\n\t\tmaxAgeDays?: number;\n\t\tmaxSizeBytes?: number;\n\t\tmaxDeleteOps?: number;\n\t\tmaxRuntimeMs?: number;\n\t\tscopeId?: string | null;\n\t},\n): ReplicationOpsPruneResult {\n\tconst maxAgeDays = Math.max(1, Math.floor(options?.maxAgeDays ?? 30));\n\tconst maxSizeBytes = Math.max(1, Math.floor(options?.maxSizeBytes ?? 512 * 1024 * 1024));\n\tconst maxDeleteOps = Math.max(1, Math.floor(options?.maxDeleteOps ?? Number.MAX_SAFE_INTEGER));\n\tconst maxRuntimeMs = Math.max(1, Math.floor(options?.maxRuntimeMs ?? Number.MAX_SAFE_INTEGER));\n\tconst scopeId = normalizeSyncStateScopeId(options?.scopeId);\n\tconst d = drizzle(db, { schema });\n\tconst cutoff = new Date(Date.now() - maxAgeDays * 24 * 60 * 60 * 1000).toISOString();\n\tconst startedAt = Date.now();\n\tlet deleted = 0;\n\tlet lastDeletedCursor: string | null = null;\n\tconst deleteThroughCursor = (createdAt: string, opId: string): number => {\n\t\tconst floorCursor = computeCursor(createdAt, opId);\n\t\treturn db\n\t\t\t.transaction(() => {\n\t\t\t\tconst result =\n\t\t\t\t\tscopeId === DEFAULT_SYNC_SCOPE_ID\n\t\t\t\t\t\t? (db\n\t\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\t\t`DELETE FROM replication_ops\n\t\t\t\t\t\t\t\t\t WHERE (scope_id IS NULL OR scope_id = ?)\n\t\t\t\t\t\t\t\t\t AND (created_at < ? OR (created_at = ? AND op_id <= ?))`,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t.run(scopeId, createdAt, createdAt, opId) as { changes?: number })\n\t\t\t\t\t\t: (db\n\t\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\t\t`DELETE FROM replication_ops\n\t\t\t\t\t\t\t\t\t WHERE scope_id = ?\n\t\t\t\t\t\t\t\t\t AND (created_at < ? OR (created_at = ? AND op_id <= ?))`,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t.run(scopeId, createdAt, createdAt, opId) as { changes?: number });\n\t\t\t\tconst changes = result.changes ?? 0;\n\t\t\t\tif (changes > 0) {\n\t\t\t\t\tsetSyncResetState(db, { retained_floor_cursor: floorCursor }, scopeId);\n\t\t\t\t}\n\t\t\t\treturn changes;\n\t\t\t})\n\t\t\t.immediate();\n\t};\n\tconst estimatedBytesBefore = estimateReplicationOpsScopeBytes(db, scopeId);\n\tif (estimatedBytesBefore == null) {\n\t\tthrow new Error(\"replication_ops_size_unavailable\");\n\t}\n\tlet stoppedByBudget = false;\n\tconst budgetExceeded = () => deleted >= maxDeleteOps || Date.now() - startedAt >= maxRuntimeMs;\n\n\twhile (true) {\n\t\tif (budgetExceeded()) {\n\t\t\tstoppedByBudget = true;\n\t\t\tbreak;\n\t\t}\n\t\tconst remainingDeleteBudget = Math.max(1, maxDeleteOps - deleted);\n\t\tconst ageBatchSize = Math.max(1, Math.min(remainingDeleteBudget, 10_000));\n\t\tconst ageCandidates = d\n\t\t\t.select({\n\t\t\t\top_id: schema.replicationOps.op_id,\n\t\t\t\tcreated_at: schema.replicationOps.created_at,\n\t\t\t})\n\t\t\t.from(schema.replicationOps)\n\t\t\t.where(\n\t\t\t\tand(\n\t\t\t\t\tsql`${schema.replicationOps.created_at} < ${cutoff}`,\n\t\t\t\t\tscopeId === DEFAULT_SYNC_SCOPE_ID\n\t\t\t\t\t\t? or(\n\t\t\t\t\t\t\t\tisNull(schema.replicationOps.scope_id),\n\t\t\t\t\t\t\t\teq(schema.replicationOps.scope_id, scopeId),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: eq(schema.replicationOps.scope_id, scopeId),\n\t\t\t\t),\n\t\t\t)\n\t\t\t.orderBy(schema.replicationOps.created_at, schema.replicationOps.op_id)\n\t\t\t.limit(ageBatchSize)\n\t\t\t.all();\n\t\tif (ageCandidates.length === 0) break;\n\t\tconst boundary = ageCandidates[ageCandidates.length - 1];\n\t\tif (!boundary) break;\n\t\tlastDeletedCursor = computeCursor(String(boundary.created_at), String(boundary.op_id));\n\t\tdeleted += deleteThroughCursor(String(boundary.created_at), String(boundary.op_id));\n\t\tif (budgetExceeded()) {\n\t\t\tstoppedByBudget = true;\n\t\t\tbreak;\n\t\t}\n\t\tif (ageCandidates.length < ageBatchSize) break;\n\t}\n\n\tlet estimatedSizeBytes = estimatedBytesBefore;\n\twhile (estimatedSizeBytes > maxSizeBytes) {\n\t\tif (budgetExceeded()) {\n\t\t\tstoppedByBudget = true;\n\t\t\tbreak;\n\t\t}\n\t\tconst remainingDeleteBudget = Math.max(1, maxDeleteOps - deleted);\n\t\tconst sizeBatchSize = Math.max(1, Math.min(remainingDeleteBudget, 10_000));\n\t\tconst oldestChunk = d\n\t\t\t.select({\n\t\t\t\top_id: schema.replicationOps.op_id,\n\t\t\t\tcreated_at: schema.replicationOps.created_at,\n\t\t\t})\n\t\t\t.from(schema.replicationOps)\n\t\t\t.where(\n\t\t\t\tscopeId === DEFAULT_SYNC_SCOPE_ID\n\t\t\t\t\t? or(isNull(schema.replicationOps.scope_id), eq(schema.replicationOps.scope_id, scopeId))\n\t\t\t\t\t: eq(schema.replicationOps.scope_id, scopeId),\n\t\t\t)\n\t\t\t.orderBy(schema.replicationOps.created_at, schema.replicationOps.op_id)\n\t\t\t.limit(sizeBatchSize)\n\t\t\t.all();\n\t\tconst boundary = oldestChunk[oldestChunk.length - 1];\n\t\tif (!boundary) break;\n\t\tlastDeletedCursor = computeCursor(String(boundary.created_at), String(boundary.op_id));\n\t\tdeleted += deleteThroughCursor(String(boundary.created_at), String(boundary.op_id));\n\t\tconst nextEstimatedSize = estimateReplicationOpsScopeBytes(db, scopeId);\n\t\tif (nextEstimatedSize == null) {\n\t\t\tthrow new Error(\"replication_ops_size_unavailable\");\n\t\t}\n\t\testimatedSizeBytes = nextEstimatedSize;\n\t}\n\n\tconst currentBoundary = getSyncResetState(db, scopeId);\n\tconst retainedFloorCursor =\n\t\tdeleted > 0 ? lastDeletedCursor : currentBoundary.retained_floor_cursor;\n\treturn {\n\t\tdeleted,\n\t\tretained_floor_cursor: retainedFloorCursor,\n\t\testimated_bytes_before: estimatedBytesBefore,\n\t\testimated_bytes_after: estimatedSizeBytes,\n\t\tstopped_by_budget: stoppedByBudget,\n\t};\n}\n\nexport interface ReplicationOpsPruneLoopResult {\n\ttotalDeleted: number;\n\tpasses: number;\n\tlastFloor: string | null;\n\tafterBytes: number;\n\tstoppedByBudget: boolean;\n}\n\nexport function pruneReplicationOpsUntilCaughtUp(\n\tdb: Database,\n\toptions: {\n\t\tmaxAgeDays: number;\n\t\tmaxSizeBytes: number;\n\t\tmaxDeleteOps: number;\n\t\tmaxRuntimeMs: number;\n\t\tscopeId?: string | null;\n\t\tmaxPasses?: number;\n\t\tsignal?: AbortSignal;\n\t\tonPass?: (pass: {\n\t\t\tpassNumber: number;\n\t\t\tdeleted: number;\n\t\t\tafterBytes: number;\n\t\t\tstoppedByBudget: boolean;\n\t\t}) => void;\n\t},\n): ReplicationOpsPruneLoopResult {\n\tconst maxPasses = Math.max(1, Math.floor(options.maxPasses ?? 25));\n\tlet totalDeleted = 0;\n\tlet passes = 0;\n\tlet lastFloor: string | null = null;\n\tlet afterBytes = estimateReplicationOpsStorageBytes(db) ?? 0;\n\tlet stoppedByBudget = false;\n\n\twhile (true) {\n\t\tif (options.signal?.aborted || passes >= maxPasses) {\n\t\t\tstoppedByBudget = true;\n\t\t\tbreak;\n\t\t}\n\t\tconst result = pruneReplicationOps(db, options);\n\t\tpasses += 1;\n\t\ttotalDeleted += result.deleted;\n\t\tlastFloor = result.retained_floor_cursor;\n\t\tafterBytes = result.estimated_bytes_after ?? estimateReplicationOpsStorageBytes(db) ?? 0;\n\t\tstoppedByBudget = result.stopped_by_budget ?? false;\n\t\toptions.onPass?.({\n\t\t\tpassNumber: passes,\n\t\t\tdeleted: result.deleted,\n\t\t\tafterBytes,\n\t\t\tstoppedByBudget,\n\t\t});\n\t\tif (result.deleted === 0 || !result.stopped_by_budget) break;\n\t}\n\n\treturn {\n\t\ttotalDeleted,\n\t\tpasses,\n\t\tlastFloor,\n\t\tafterBytes,\n\t\tstoppedByBudget,\n\t};\n}\n\nexport function bulkPruneReplicationOpsByAgeCutoff(\n\tdb: Database,\n\tmaxAgeDays: number,\n\tmaxDeleteOps = Number.MAX_SAFE_INTEGER,\n\tscopeIdInput?: string | null,\n): ReplicationOpsPruneResult {\n\tconst d = drizzle(db, { schema });\n\tconst scopeId = normalizeSyncStateScopeId(scopeIdInput);\n\tconst cutoff = new Date(\n\t\tDate.now() - Math.max(1, Math.floor(maxAgeDays)) * 24 * 60 * 60 * 1000,\n\t).toISOString();\n\tconst estimatedBytesBefore = estimateReplicationOpsScopeBytes(db, scopeId);\n\tif (estimatedBytesBefore == null) {\n\t\tthrow new Error(\"replication_ops_size_unavailable\");\n\t}\n\tconst oldestEligible = d\n\t\t.select({ op_id: schema.replicationOps.op_id, created_at: schema.replicationOps.created_at })\n\t\t.from(schema.replicationOps)\n\t\t.where(\n\t\t\tand(\n\t\t\t\tsql`${schema.replicationOps.created_at} < ${cutoff}`,\n\t\t\t\tscopeId === DEFAULT_SYNC_SCOPE_ID\n\t\t\t\t\t? or(isNull(schema.replicationOps.scope_id), eq(schema.replicationOps.scope_id, scopeId))\n\t\t\t\t\t: eq(schema.replicationOps.scope_id, scopeId),\n\t\t\t),\n\t\t)\n\t\t.orderBy(schema.replicationOps.created_at, schema.replicationOps.op_id)\n\t\t.limit(Math.max(1, maxDeleteOps))\n\t\t.all();\n\tconst boundary = oldestEligible[oldestEligible.length - 1];\n\tif (!boundary) {\n\t\tconst currentBoundary = getSyncResetState(db, scopeId);\n\t\treturn {\n\t\t\tdeleted: 0,\n\t\t\tretained_floor_cursor: currentBoundary.retained_floor_cursor,\n\t\t\testimated_bytes_before: estimatedBytesBefore,\n\t\t\testimated_bytes_after: estimatedBytesBefore,\n\t\t\tstopped_by_budget: false,\n\t\t};\n\t}\n\tconst retainedFloorCursor = computeCursor(String(boundary.created_at), String(boundary.op_id));\n\tconst deleted = db\n\t\t.transaction(() => {\n\t\t\tconst result =\n\t\t\t\tscopeId === DEFAULT_SYNC_SCOPE_ID\n\t\t\t\t\t? (db\n\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\t`DELETE FROM replication_ops\n\t\t\t\t\t\t\t\t WHERE (scope_id IS NULL OR scope_id = ?)\n\t\t\t\t\t\t\t\t AND (created_at < ? OR (created_at = ? AND op_id <= ?))`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.run(scopeId, boundary.created_at, boundary.created_at, boundary.op_id) as {\n\t\t\t\t\t\t\tchanges?: number;\n\t\t\t\t\t\t})\n\t\t\t\t\t: (db\n\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\t`DELETE FROM replication_ops\n\t\t\t\t\t\t\t\t WHERE scope_id = ?\n\t\t\t\t\t\t\t\t AND (created_at < ? OR (created_at = ? AND op_id <= ?))`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.run(scopeId, boundary.created_at, boundary.created_at, boundary.op_id) as {\n\t\t\t\t\t\t\tchanges?: number;\n\t\t\t\t\t\t});\n\t\t\tconst changes = result.changes ?? 0;\n\t\t\tif (changes > 0) {\n\t\t\t\tsetSyncResetState(db, { retained_floor_cursor: retainedFloorCursor }, scopeId);\n\t\t\t}\n\t\t\treturn changes;\n\t\t})\n\t\t.immediate();\n\tconst estimatedBytesAfter = estimateReplicationOpsScopeBytes(db, scopeId);\n\tif (estimatedBytesAfter == null) {\n\t\tthrow new Error(\"replication_ops_size_unavailable\");\n\t}\n\treturn {\n\t\tdeleted,\n\t\tretained_floor_cursor: retainedFloorCursor,\n\t\testimated_bytes_before: estimatedBytesBefore,\n\t\testimated_bytes_after: estimatedBytesAfter,\n\t\tstopped_by_budget: false,\n\t};\n}\n\nexport function planReplicationOpsAgePrune(\n\tdb: Database,\n\tmaxAgeDays: number,\n\tbatchOps: number,\n): ReplicationOpsAgePrunePlan {\n\tconst d = drizzle(db, { schema });\n\tconst cutoff = new Date(\n\t\tDate.now() - Math.max(1, Math.floor(maxAgeDays)) * 24 * 60 * 60 * 1000,\n\t).toISOString();\n\tconst countRow = d\n\t\t.select({ total: sql<number>`COUNT(*)` })\n\t\t.from(schema.replicationOps)\n\t\t.where(sql`${schema.replicationOps.created_at} < ${cutoff}`)\n\t\t.get();\n\tconst totalCountRow = d\n\t\t.select({ total: sql<number>`COUNT(*)` })\n\t\t.from(schema.replicationOps)\n\t\t.get();\n\tconst boundary = d\n\t\t.select({ op_id: schema.replicationOps.op_id, created_at: schema.replicationOps.created_at })\n\t\t.from(schema.replicationOps)\n\t\t.where(sql`${schema.replicationOps.created_at} < ${cutoff}`)\n\t\t.orderBy(desc(schema.replicationOps.created_at), desc(schema.replicationOps.op_id))\n\t\t.limit(1)\n\t\t.get();\n\tconst candidateOps = Number(countRow?.total ?? 0);\n\tconst totalOps = Number(totalCountRow?.total ?? 0);\n\tconst estimatedTotalBytes = estimateReplicationOpsStorageBytes(db) ?? 0;\n\tconst estimatedCandidateBytes =\n\t\ttotalOps > 0 ? Math.round((estimatedTotalBytes * candidateOps) / totalOps) : 0;\n\treturn {\n\t\tcandidate_ops: candidateOps,\n\t\testimated_candidate_bytes: Math.max(0, estimatedCandidateBytes),\n\t\tcutoff_cursor: boundary\n\t\t\t? computeCursor(String(boundary.created_at), String(boundary.op_id))\n\t\t\t: null,\n\t\testimated_batches: candidateOps > 0 ? Math.ceil(candidateOps / Math.max(1, batchOps)) : 0,\n\t};\n}\n\nfunction estimateReplicationOpsStorageBytes(db: Database): number | null {\n\ttry {\n\t\tconst row = db\n\t\t\t.prepare(\n\t\t\t\t`SELECT COALESCE(SUM(pgsize), 0) AS total_bytes\n\t\t\t\t FROM dbstat\n\t\t\t\t WHERE name = 'replication_ops'\n\t\t\t\t OR name LIKE 'idx_replication_ops_%'\n\t\t\t\t OR name LIKE 'sqlite_autoindex_replication_ops_%'`,\n\t\t\t)\n\t\t\t.get() as { total_bytes?: number | string | null } | undefined;\n\t\tconst total = Number(row?.total_bytes ?? 0);\n\t\treturn Number.isFinite(total) && total >= 0 ? total : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function estimateReplicationOpsScopeBytes(db: Database, scopeId: string): number | null {\n\tconst estimateSql = `SELECT COALESCE(SUM(\n\t\tLENGTH(COALESCE(op_id, '')) +\n\t\tLENGTH(COALESCE(entity_type, '')) +\n\t\tLENGTH(COALESCE(entity_id, '')) +\n\t\tLENGTH(COALESCE(op_type, '')) +\n\t\tLENGTH(COALESCE(payload_json, '')) +\n\t\tLENGTH(COALESCE(clock_updated_at, '')) +\n\t\tLENGTH(COALESCE(clock_device_id, '')) +\n\t\tLENGTH(COALESCE(device_id, '')) +\n\t\tLENGTH(COALESCE(created_at, '')) +\n\t\tLENGTH(COALESCE(scope_id, '')) +\n\t\t96\n\t), 0) AS total_bytes\n\tFROM replication_ops\n\tWHERE ${scopeId === DEFAULT_SYNC_SCOPE_ID ? \"scope_id IS NULL OR scope_id = ?\" : \"scope_id = ?\"}`;\n\ttry {\n\t\tconst row = db.prepare(estimateSql).get(scopeId) as\n\t\t\t| { total_bytes?: number | string | null }\n\t\t\t| undefined;\n\t\tconst total = Number(row?.total_bytes ?? 0);\n\t\treturn Number.isFinite(total) && total >= 0 ? total : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction cleanList(values: unknown): string[] {\n\tif (!Array.isArray(values)) return [];\n\tconst out: string[] = [];\n\tfor (const raw of values) {\n\t\tconst value = String(raw ?? \"\").trim();\n\t\tif (value) out.push(value);\n\t}\n\treturn out;\n}\n\nfunction parseStringList(value: unknown): string[] {\n\tif (Array.isArray(value)) return cleanList(value);\n\tif (typeof value === \"string\") {\n\t\treturn value\n\t\t\t.split(\",\")\n\t\t\t.map((part) => part.trim())\n\t\t\t.filter(Boolean);\n\t}\n\treturn [];\n}\n\nfunction parseJsonList(valuesJson: string | null | undefined): string[] {\n\tif (!valuesJson) return [];\n\ttry {\n\t\treturn cleanList(JSON.parse(valuesJson));\n\t} catch {\n\t\treturn [];\n\t}\n}\n\nfunction effectiveSyncProjectFilters(\n\tdb: Database,\n\tpeerDeviceId: string | null,\n): { include: string[]; exclude: string[] } {\n\tconst d = drizzle(db, { schema });\n\tconst config = readCodememConfigFile();\n\tconst includeOverride = process.env.CODEMEM_SYNC_PROJECTS_INCLUDE;\n\tconst excludeOverride = process.env.CODEMEM_SYNC_PROJECTS_EXCLUDE;\n\tconst globalInclude =\n\t\tincludeOverride !== undefined\n\t\t\t? parseStringList(includeOverride)\n\t\t\t: parseStringList(config.sync_projects_include);\n\tconst globalExclude =\n\t\texcludeOverride !== undefined\n\t\t\t? parseStringList(excludeOverride)\n\t\t\t: parseStringList(config.sync_projects_exclude);\n\tif (!peerDeviceId) return { include: globalInclude, exclude: globalExclude };\n\n\tconst row = d\n\t\t.select({\n\t\t\tprojects_include_json: schema.syncPeers.projects_include_json,\n\t\t\tprojects_exclude_json: schema.syncPeers.projects_exclude_json,\n\t\t})\n\t\t.from(schema.syncPeers)\n\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t.limit(1)\n\t\t.get();\n\tif (!row) return { include: globalInclude, exclude: globalExclude };\n\n\tconst hasOverride = row.projects_include_json != null || row.projects_exclude_json != null;\n\tif (!hasOverride) {\n\t\treturn { include: globalInclude, exclude: globalExclude };\n\t}\n\n\treturn {\n\t\tinclude: parseJsonList(row.projects_include_json),\n\t\texclude: parseJsonList(row.projects_exclude_json),\n\t};\n}\n\nexport function syncProjectAllowed(\n\tdb: Database,\n\tproject: string | null,\n\tpeerDeviceId: string | null,\n): boolean {\n\tconst { include, exclude } = effectiveSyncProjectFilters(db, peerDeviceId);\n\treturn syncProjectAllowedByFilters(project, { include, exclude });\n}\n\nexport function syncProjectAllowedByFilters(\n\tprojectValue: string | null,\n\tfilters: { include: string[]; exclude: string[] },\n): boolean {\n\tconst value = String(projectValue ?? \"\").trim();\n\tconst valueBase = projectBasename(value);\n\tfor (const blocked of filters.exclude) {\n\t\tif (blocked === value || blocked === valueBase) return false;\n\t}\n\tif (filters.include.length === 0) return true;\n\tfor (const allowed of filters.include) {\n\t\tif (allowed === value || allowed === valueBase) return true;\n\t}\n\treturn false;\n}\n\nexport function syncVisibilityAllowed(payload: Record<string, unknown> | null): boolean {\n\tif (!payload) return false;\n\tlet visibility = String(payload.visibility ?? \"\")\n\t\t.trim()\n\t\t.toLowerCase();\n\tconst metadata =\n\t\tpayload.metadata_json &&\n\t\ttypeof payload.metadata_json === \"object\" &&\n\t\t!Array.isArray(payload.metadata_json)\n\t\t\t? (payload.metadata_json as Record<string, unknown>)\n\t\t\t: {};\n\tconst metadataVisibility = String(metadata.visibility ?? \"\")\n\t\t.trim()\n\t\t.toLowerCase();\n\tif (!visibility && metadataVisibility) {\n\t\tvisibility = metadataVisibility;\n\t}\n\n\tif (!visibility) {\n\t\tlet workspaceKind = String(payload.workspace_kind ?? \"\")\n\t\t\t.trim()\n\t\t\t.toLowerCase();\n\t\tlet workspaceId = String(payload.workspace_id ?? \"\")\n\t\t\t.trim()\n\t\t\t.toLowerCase();\n\t\tif (!workspaceKind)\n\t\t\tworkspaceKind = String(metadata.workspace_kind ?? \"\")\n\t\t\t\t.trim()\n\t\t\t\t.toLowerCase();\n\t\tif (!workspaceId)\n\t\t\tworkspaceId = String(metadata.workspace_id ?? \"\")\n\t\t\t\t.trim()\n\t\t\t\t.toLowerCase();\n\t\tif (workspaceKind === \"shared\" || workspaceId.startsWith(\"shared:\")) {\n\t\t\tvisibility = \"shared\";\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn visibility === \"shared\";\n}\n\nfunction cleanText(value: unknown): string | null {\n\tconst trimmed = typeof value === \"string\" ? value.trim() : \"\";\n\treturn trimmed.length > 0 ? trimmed : null;\n}\n\nexport interface PersonalScopeGrantStatus {\n\tscope_id: string | null;\n\tauthorized: boolean;\n\tstate: string;\n}\n\nexport function personalScopeGrantStatusForPeer(\n\tdb: Database,\n\tinput: { peerDeviceId: string | null; actorId: string | null },\n): PersonalScopeGrantStatus {\n\tconst peerDeviceId = cleanText(input.peerDeviceId);\n\tconst actorId = cleanText(input.actorId);\n\tif (!peerDeviceId || !actorId) {\n\t\treturn { scope_id: null, authorized: false, state: \"missing_peer_or_actor\" };\n\t}\n\tconst scopeId = `personal:${actorId}`;\n\tconst auth = getCachedScopeAuthorization(db, { deviceId: peerDeviceId, scopeId });\n\treturn { scope_id: scopeId, authorized: auth.authorized, state: auth.state };\n}\n\nfunction personalScopeAuthorizationRequirement(\n\top: Pick<ReplicationOp, \"scope_id\">,\n\tpayload: Record<string, unknown> | null,\n): { required: boolean; scopeId: string | null } {\n\tconst metadata =\n\t\tpayload?.metadata_json &&\n\t\ttypeof payload.metadata_json === \"object\" &&\n\t\t!Array.isArray(payload.metadata_json)\n\t\t\t? (payload.metadata_json as Record<string, unknown>)\n\t\t\t: {};\n\tconst opScopeId = cleanText(op.scope_id);\n\tconst payloadScopeId = cleanText(payload?.scope_id);\n\tconst visibility = cleanText(payload?.visibility ?? metadata.visibility)?.toLowerCase() ?? null;\n\tconst workspaceId = cleanText(payload?.workspace_id ?? metadata.workspace_id);\n\tconst workspaceKind =\n\t\tcleanText(payload?.workspace_kind ?? metadata.workspace_kind)?.toLowerCase() ?? null;\n\tconst actorId = cleanText(payload?.actor_id ?? metadata.actor_id);\n\tconst personalWorkspaceId = workspaceId?.startsWith(\"personal:\") ? workspaceId : null;\n\tconst hasPersonalSignal =\n\t\tvisibility === \"private\" ||\n\t\tvisibility === \"personal\" ||\n\t\tworkspaceKind === \"personal\" ||\n\t\tBoolean(personalWorkspaceId);\n\tconst actorScopeId = actorId && hasPersonalSignal ? `personal:${actorId}` : null;\n\tconst candidates = [opScopeId, payloadScopeId, personalWorkspaceId, actorScopeId].filter(\n\t\t(candidate): candidate is string => Boolean(candidate?.startsWith(\"personal:\")),\n\t);\n\tconst scopeId = candidates[0] ?? null;\n\tif (!scopeId) return { required: hasPersonalSignal, scopeId: null };\n\tif (candidates.some((candidate) => candidate !== scopeId)) {\n\t\treturn { required: true, scopeId: null };\n\t}\n\treturn { required: true, scopeId };\n}\n\nexport function replicationOpRequiresPersonalScopeAuthorization(\n\top: Pick<ReplicationOp, \"scope_id\">,\n\tpayload: Record<string, unknown> | null,\n): boolean {\n\treturn personalScopeAuthorizationRequirement(op, payload).required;\n}\n\nexport function peerCanSyncPrivateOpByPersonalScopeGrant(\n\tdb: Database,\n\top: Pick<ReplicationOp, \"scope_id\">,\n\tpayload: Record<string, unknown> | null,\n\tpeerDeviceId: string | null,\n): boolean {\n\tconst { scopeId } = personalScopeAuthorizationRequirement(op, payload);\n\tif (!scopeId) return false;\n\tconst actorId = scopeId.slice(\"personal:\".length);\n\treturn personalScopeGrantStatusForPeer(db, { peerDeviceId, actorId }).authorized;\n}\n\nfunction parsePayload(payloadJson: string | null): Record<string, unknown> | null {\n\tif (!payloadJson?.trim()) return null;\n\ttry {\n\t\tconst parsed = JSON.parse(payloadJson) as unknown;\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n\t\treturn parsed as Record<string, unknown>;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport interface FilterReplicationSkipped {\n\treason: \"scope_filter\" | \"visibility_filter\" | \"project_filter\";\n\top_id: string;\n\tcreated_at: string;\n\tentity_type: string;\n\tentity_id: string;\n\tskipped_count: number;\n\tproject?: string | null;\n\tscope_id?: string | null;\n\tvisibility?: string | null;\n}\n\nexport interface FilterReplicationOpsForSyncOptions {\n\tlocalDeviceId?: string | null;\n\tapplyScopeFilter?: boolean;\n\tsupportsReassignScope?: boolean;\n}\n\ninterface ExistingMemoryFilterContext {\n\tpayload: Record<string, unknown>;\n\tproject: string | null;\n\tscopeId: string | null;\n}\n\nfunction addSkipped(\n\tstate: { count: number; first: FilterReplicationSkipped | null },\n\top: ReplicationOp,\n\tskipped: Pick<FilterReplicationSkipped, \"reason\"> &\n\t\tPartial<Omit<FilterReplicationSkipped, \"reason\" | \"skipped_count\">>,\n): void {\n\tstate.count += 1;\n\tif (!state.first) {\n\t\tstate.first = {\n\t\t\t...skipped,\n\t\t\top_id: op.op_id,\n\t\t\tcreated_at: op.created_at,\n\t\t\tentity_type: op.entity_type,\n\t\t\tentity_id: op.entity_id,\n\t\t\tskipped_count: 0,\n\t\t};\n\t}\n}\n\nfunction metadataRecord(payload: Record<string, unknown> | null): Record<string, unknown> {\n\tconst metadata = payload?.metadata_json;\n\tif (!metadata || typeof metadata !== \"object\" || Array.isArray(metadata)) return {};\n\treturn metadata as Record<string, unknown>;\n}\n\nfunction payloadScopeId(payload: Record<string, unknown> | null): string | null {\n\tconst metadata = metadataRecord(payload);\n\treturn cleanText(payload?.scope_id ?? metadata.scope_id);\n}\n\nfunction payloadContradictsOutboundScope(\n\top: Pick<ReplicationOp, \"scope_id\">,\n\tpayload: Record<string, unknown> | null,\n): boolean {\n\tconst opScopeId = cleanText(op.scope_id);\n\tconst explicitPayloadScopeId = payloadScopeId(payload);\n\tif (explicitPayloadScopeId && explicitPayloadScopeId !== opScopeId) return true;\n\tif (!opScopeId) return explicitPayloadScopeId != null;\n\n\tconst personalRequirement = personalScopeAuthorizationRequirement(op, payload);\n\treturn Boolean(\n\t\tpersonalRequirement.required &&\n\t\t\tpersonalRequirement.scopeId &&\n\t\t\tpersonalRequirement.scopeId !== opScopeId,\n\t);\n}\n\nfunction existingMemoryFilterContext(\n\tdb: Database,\n\timportKey: string,\n): ExistingMemoryFilterContext | null {\n\tconst key = cleanText(importKey);\n\tif (!key) return null;\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT\n\t\t\t\tm.actor_id,\n\t\t\t\tm.metadata_json,\n\t\t\t\tm.scope_id,\n\t\t\t\tm.visibility,\n\t\t\t\tm.workspace_id,\n\t\t\t\tm.workspace_kind,\n\t\t\t\ts.project\n\t\t\t FROM memory_items m\n\t\t\t LEFT JOIN sessions s ON s.id = m.session_id\n\t\t\t WHERE m.import_key = ?\n\t\t\t LIMIT 1`,\n\t\t)\n\t\t.get(key) as\n\t\t| {\n\t\t\t\tactor_id: string | null;\n\t\t\t\tmetadata_json: string | null;\n\t\t\t\tproject: string | null;\n\t\t\t\tscope_id: string | null;\n\t\t\t\tvisibility: string | null;\n\t\t\t\tworkspace_id: string | null;\n\t\t\t\tworkspace_kind: string | null;\n\t\t }\n\t\t| undefined;\n\tif (!row) return null;\n\treturn {\n\t\tpayload: {\n\t\t\tactor_id: row.actor_id,\n\t\t\tmetadata_json: fromJson(row.metadata_json),\n\t\t\tvisibility: row.visibility,\n\t\t\tworkspace_id: row.workspace_id,\n\t\t\tworkspace_kind: row.workspace_kind,\n\t\t},\n\t\tproject: cleanText(row.project),\n\t\tscopeId: cleanText(row.scope_id),\n\t};\n}\n\nfunction outboundScopeAllowed(\n\tdb: Database,\n\top: ReplicationOp,\n\tpayload: Record<string, unknown> | null,\n\tpeerDeviceId: string | null,\n\tlocalDeviceId: string | null,\n): boolean {\n\tif (payloadContradictsOutboundScope(op, payload)) return false;\n\tconst scopeId = cleanText(op.scope_id);\n\tif (!scopeId) return true;\n\tif (scopeId === DEFAULT_SYNC_SCOPE_ID) return false;\n\tconst peerId = cleanText(peerDeviceId);\n\tif (!peerId) return false;\n\tconst peerAuth = getCachedScopeAuthorization(db, { deviceId: peerId, scopeId });\n\tif (!peerAuth.authorized || peerAuth.scope?.authority_type === \"local\") return false;\n\tconst localId = cleanText(localDeviceId);\n\tif (!localId) return true;\n\tconst localAuth = getCachedScopeAuthorization(db, { deviceId: localId, scopeId });\n\treturn localAuth.authorized && localAuth.scope?.authority_type !== \"local\";\n}\n\nfunction legacyDefaultReassignAllowed(\n\tdb: Database,\n\top: ReplicationOp,\n\tpeerDeviceId: string | null,\n): boolean {\n\tconst existing = existingMemoryFilterContext(db, op.entity_id);\n\tif (!existing) return false;\n\tif (\n\t\t(replicationOpRequiresPersonalScopeAuthorization(op, existing.payload) ||\n\t\t\t!syncVisibilityAllowed(existing.payload)) &&\n\t\t!peerCanSyncPrivateOpByPersonalScopeGrant(db, op, existing.payload, peerDeviceId)\n\t) {\n\t\treturn false;\n\t}\n\treturn syncProjectAllowed(db, existing.project, peerDeviceId);\n}\n\n/**\n * Filter replication ops for peer sync scopes.\n *\n * Returns ops that pass project/visibility rules, a cursor for the last\n * processed op (including skipped ops), and skipped metadata when filtering\n * removed one or more ops.\n */\nfunction existingDeleteRejection(\n\tdb: Database,\n\top: ReplicationOp,\n\tpeerDeviceId: string | null,\n\toptions: { applyScopeFilter: boolean },\n): Parameters<typeof addSkipped>[2] | null {\n\tconst existing = existingMemoryFilterContext(db, op.entity_id);\n\tif (!existing) return null;\n\tif (options.applyScopeFilter && existing.scopeId && existing.scopeId !== cleanText(op.scope_id)) {\n\t\treturn { reason: \"scope_filter\", scope_id: cleanText(op.scope_id) };\n\t}\n\tif (\n\t\t(replicationOpRequiresPersonalScopeAuthorization(op, existing.payload) ||\n\t\t\t!syncVisibilityAllowed(existing.payload)) &&\n\t\t!peerCanSyncPrivateOpByPersonalScopeGrant(db, op, existing.payload, peerDeviceId)\n\t) {\n\t\treturn {\n\t\t\treason: \"visibility_filter\",\n\t\t\tvisibility:\n\t\t\t\ttypeof existing.payload.visibility === \"string\"\n\t\t\t\t\t? String(existing.payload.visibility)\n\t\t\t\t\t: null,\n\t\t};\n\t}\n\tif (!syncProjectAllowed(db, existing.project, peerDeviceId))\n\t\treturn { reason: \"project_filter\", project: existing.project };\n\treturn null;\n}\n\nexport function filterReplicationOpsForSyncWithStatus(\n\tdb: Database,\n\tops: ReplicationOp[],\n\tpeerDeviceId: string | null,\n\toptions: FilterReplicationOpsForSyncOptions = {},\n): [ReplicationOp[], string | null, FilterReplicationSkipped | null] {\n\tconst allowed: ReplicationOp[] = [];\n\tlet nextCursor: string | null = null;\n\tconst skipped = { count: 0, first: null as FilterReplicationSkipped | null };\n\tconst applyScopeFilter = options.applyScopeFilter !== false;\n\tfor (const op of ops) {\n\t\tif (retirementBlocksMemoryOp(db, op)) {\n\t\t\taddSkipped(skipped, op, { reason: \"scope_filter\", scope_id: cleanText(op.scope_id) });\n\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\tcontinue;\n\t\t}\n\t\tif (op.entity_type === \"memory_item\") {\n\t\t\tconst payload = parsePayload(op.payload_json);\n\t\t\tif (op.op_type === REASSIGN_SCOPE_OP_TYPE && options.supportsReassignScope !== true) {\n\t\t\t\taddSkipped(skipped, op, {\n\t\t\t\t\treason: \"scope_filter\",\n\t\t\t\t\tscope_id: cleanText(op.scope_id),\n\t\t\t\t});\n\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (op.op_type === ACCESS_CLEANUP_OP_TYPE) {\n\t\t\t\tif (!accessCleanupTargetsPeer(op, peerDeviceId)) {\n\t\t\t\t\taddSkipped(skipped, op, {\n\t\t\t\t\t\treason: \"scope_filter\",\n\t\t\t\t\t\tscope_id: cleanText(payload?.cleanup_scope_id ?? op.scope_id),\n\t\t\t\t\t});\n\t\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tallowed.push(op);\n\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (op.op_type === REASSIGN_SCOPE_OP_TYPE) {\n\t\t\t\ttry {\n\t\t\t\t\tconst reassignment = parseReassignScopePayload(op);\n\t\t\t\t\tconst scopeAllowed =\n\t\t\t\t\t\t!applyScopeFilter ||\n\t\t\t\t\t\t(reassignment.side === \"old\" && reassignment.old_scope_id === DEFAULT_SYNC_SCOPE_ID\n\t\t\t\t\t\t\t? legacyDefaultReassignAllowed(db, op, peerDeviceId)\n\t\t\t\t\t\t\t: outboundScopeAllowed(db, op, payload, peerDeviceId, options.localDeviceId ?? null));\n\t\t\t\t\tif (!scopeAllowed) {\n\t\t\t\t\t\taddSkipped(skipped, op, {\n\t\t\t\t\t\t\treason: \"scope_filter\",\n\t\t\t\t\t\t\tscope_id: cleanText(op.scope_id),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (reassignment.side === \"old\") {\n\t\t\t\t\t\tallowed.push(op);\n\t\t\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\taddSkipped(skipped, op, {\n\t\t\t\t\t\treason: \"scope_filter\",\n\t\t\t\t\t\tscope_id: cleanText(op.scope_id),\n\t\t\t\t\t});\n\t\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst regularScopeId = cleanText(op.scope_id);\n\t\t\tif (!regularScopeId || regularScopeId === DEFAULT_SYNC_SCOPE_ID) {\n\t\t\t\taddSkipped(skipped, op, { reason: \"scope_filter\", scope_id: regularScopeId });\n\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tapplyScopeFilter &&\n\t\t\t\t!outboundScopeAllowed(db, op, payload, peerDeviceId, options.localDeviceId ?? null)\n\t\t\t) {\n\t\t\t\taddSkipped(skipped, op, { reason: \"scope_filter\", scope_id: cleanText(op.scope_id) });\n\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (op.op_type === \"delete\" && payload == null) {\n\t\t\t\tconst rejection = existingDeleteRejection(db, op, peerDeviceId, { applyScopeFilter });\n\t\t\t\tif (rejection) {\n\t\t\t\t\taddSkipped(skipped, op, rejection);\n\t\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\treplicationOpRequiresPersonalScopeAuthorization(op, payload) &&\n\t\t\t\t\t!peerCanSyncPrivateOpByPersonalScopeGrant(db, op, payload, peerDeviceId)\n\t\t\t\t) {\n\t\t\t\t\taddSkipped(skipped, op, { reason: \"visibility_filter\" });\n\t\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tallowed.push(op);\n\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\t(replicationOpRequiresPersonalScopeAuthorization(op, payload) ||\n\t\t\t\t\t!syncVisibilityAllowed(payload)) &&\n\t\t\t\t!peerCanSyncPrivateOpByPersonalScopeGrant(db, op, payload, peerDeviceId)\n\t\t\t) {\n\t\t\t\taddSkipped(skipped, op, {\n\t\t\t\t\treason: \"visibility_filter\",\n\t\t\t\t\tvisibility: typeof payload?.visibility === \"string\" ? String(payload.visibility) : null,\n\t\t\t\t});\n\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst project =\n\t\t\t\ttypeof payload?.project === \"string\" && payload.project.trim()\n\t\t\t\t\t? payload.project.trim()\n\t\t\t\t\t: null;\n\t\t\tif (!syncProjectAllowed(db, project, peerDeviceId)) {\n\t\t\t\taddSkipped(skipped, op, { reason: \"project_filter\", project });\n\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tallowed.push(op);\n\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t}\n\n\tif (skipped.first) {\n\t\tskipped.first.skipped_count = skipped.count;\n\t}\n\n\treturn [allowed, nextCursor, skipped.first];\n}\n\nexport function filterReplicationOpsForSync(\n\tdb: Database,\n\tops: ReplicationOp[],\n\tpeerDeviceId: string | null,\n\toptions: FilterReplicationOpsForSyncOptions = {},\n): [ReplicationOp[], string | null] {\n\tconst [allowed, nextCursor] = filterReplicationOpsForSyncWithStatus(\n\t\tdb,\n\t\tops,\n\t\tpeerDeviceId,\n\t\toptions,\n\t);\n\treturn [allowed, nextCursor];\n}\n\n// Apply inbound replication ops\n\nfunction skipOwnOrRetiredMemoryOp(db: Database, op: ReplicationOp, localDeviceId: string): boolean {\n\tif (op.device_id === localDeviceId) return true;\n\treturn retirementBlocksMemoryOp(db, op);\n}\n\nfunction retirementPayloadContradictsScope(\n\top: ReplicationOp,\n\tscopeId: string,\n\tpayload: Record<string, unknown> | null,\n): boolean {\n\tconst scopes = [payload?.scope_id, metadataRecord(payload).scope_id];\n\tif (op.op_type === ACCESS_CLEANUP_OP_TYPE) {\n\t\tconst cleanupScope = cleanText(payload?.cleanup_scope_id ?? payload?.scope_id);\n\t\tif (!cleanupScope) return true;\n\t\tif (scopeId !== DEFAULT_SYNC_SCOPE_ID && scopeId !== cleanupScope) return true;\n\t\treturn scopes.some((value) => value != null && cleanText(value) !== cleanupScope);\n\t}\n\treturn scopes.some((value) => value != null && cleanText(value) !== scopeId);\n}\n\n/** History makes missing/contradictory scope unsafe even without optional membership validation. */\nfunction retirementBlocksMemoryOp(db: Database, op: ReplicationOp): boolean {\n\tif (op.entity_type !== \"memory_item\" || !hasMemoryScopeRetirement(db, op.entity_id)) return false;\n\tconst scopeId = cleanText(op.scope_id);\n\tif (!scopeId || isMemoryScopeRetired(db, op.entity_id, scopeId)) return true;\n\tconst payload = parsePayload(op.payload_json);\n\tif (op.payload_json != null && !payload) return true;\n\tif (retirementPayloadContradictsScope(op, scopeId, payload)) return true;\n\tif (op.op_type === ACCESS_CLEANUP_OP_TYPE) {\n\t\treturn isMemoryScopeRetired(db, op.entity_id, parseAccessCleanupPayload(op).cleanup_scope_id);\n\t}\n\tif (op.op_type !== REASSIGN_SCOPE_OP_TYPE) return false;\n\ttry {\n\t\tconst reassignment = parseReassignScopePayload(op);\n\t\treturn isMemoryScopeRetired(db, op.entity_id, reassignment.new_scope_id);\n\t} catch {\n\t\treturn true;\n\t}\n}\n\nexport interface ApplyResult {\n\tapplied: number;\n\tskipped: number;\n\trejected: number;\n\tconflicts: number;\n\terrors: string[];\n\trejections: InboundScopeRejection[];\n\tvectorWork: ReplicationVectorWork;\n}\n\nexport interface ReplicationVectorWork {\n\tupsertMemoryIds: number[];\n\tdeleteMemoryIds: number[];\n}\n\nexport type StalePeerReceivedRowReason =\n\t| \"authorization_unknown\"\n\t| \"missing_import_key\"\n\t| \"missing_origin_device\"\n\t| \"missing_scope\"\n\t| \"unverified_local_creation\";\n\nexport interface StalePeerReceivedRowDiagnostic {\n\tmemory_id: number;\n\timport_key: string | null;\n\torigin_device_id: string | null;\n\tscope_id: string | null;\n\treason: StalePeerReceivedRowReason;\n}\n\nexport interface ReconcileStalePeerReceivedRowsResult {\n\tchecked: number;\n\tdeleted: number;\n\tdeleted_memory_ids: number[];\n\tretained: number;\n\tambiguous: StalePeerReceivedRowDiagnostic[];\n}\n\nexport interface ReconcileStalePeerReceivedRowsOptions extends LocalCreationContext {\n\tlocalDeviceId: string;\n\tkeysDir?: string;\n\tmaxRows?: number | null;\n\tpeerDeviceId?: string | null;\n}\n\nexport type DiagnoseStalePeerReceivedRowsResult = Omit<\n\tReconcileStalePeerReceivedRowsResult,\n\t\"deleted\" | \"deleted_memory_ids\"\n> & {\n\twould_delete: number;\n\twould_delete_memory_ids: number[];\n};\n\ntype StalePeerCandidateAuthState = ReturnType<typeof getCachedScopeAuthorization>[\"state\"];\n\nfunction stalePeerCandidateIsDeletable(state: StalePeerCandidateAuthState): boolean {\n\treturn state === \"revoked\" || state === \"scope_inactive\" || state === \"stale_epoch\";\n}\n\nfunction stalePeerCandidateDiagnostic(input: {\n\timportKey: string | null;\n\tmemoryId: number;\n\toriginDeviceId: string | null;\n\treason: StalePeerReceivedRowReason;\n\tscopeId: string | null;\n}): StalePeerReceivedRowDiagnostic {\n\treturn {\n\t\tmemory_id: input.memoryId,\n\t\timport_key: input.importKey,\n\t\torigin_device_id: input.originDeviceId,\n\t\tscope_id: input.scopeId,\n\t\treason: input.reason,\n\t};\n}\n\nexport function reconcileStalePeerReceivedRows(\n\tdb: Database,\n\toptions: ReconcileStalePeerReceivedRowsOptions,\n): ReconcileStalePeerReceivedRowsResult {\n\treturn reconcileStalePeerReceivedRowsInternal(db, options, true);\n}\n\nexport function diagnoseStalePeerReceivedRows(\n\tdb: Database,\n\toptions: ReconcileStalePeerReceivedRowsOptions,\n): DiagnoseStalePeerReceivedRowsResult {\n\tconst result = reconcileStalePeerReceivedRowsInternal(db, options, false);\n\treturn {\n\t\tchecked: result.checked,\n\t\twould_delete: result.deleted,\n\t\twould_delete_memory_ids: result.deleted_memory_ids,\n\t\tretained: result.retained,\n\t\tambiguous: result.ambiguous,\n\t};\n}\n\nfunction clearRefsBeforeMemoryDeletion(db: Database, memoryId: number): void {\n\tsnapshotSessionExportKeysForMemoryIds(db, [memoryId]);\n\tclearMemoryRefs(db, memoryId);\n}\n\ninterface StalePeerReceivedRow {\n\tid: number;\n\timport_key: string | null;\n\torigin_device_id: string | null;\n\tscope_id: string | null;\n}\n\nfunction stalePeerReceivedRows(\n\tdb: Database,\n\tpeerDeviceId: string | null,\n\tmaxRows: number,\n): StalePeerReceivedRow[] {\n\treturn db\n\t\t.prepare(`SELECT id, import_key, origin_device_id, scope_id\n\t\tFROM memory_items WHERE active = 1 AND (? IS NULL OR origin_device_id = ?)\n\t\tORDER BY id LIMIT ?`)\n\t\t.all(peerDeviceId, peerDeviceId, maxRows) as StalePeerReceivedRow[];\n}\n\nfunction legacyLocalRetentionScope(db: Database, scopeId: string | null): boolean {\n\tconst scope = cleanText(scopeId);\n\tif (!scope || scope === DEFAULT_SYNC_SCOPE_ID || scope === LEGACY_SHARED_REVIEW_SCOPE_ID)\n\t\treturn true;\n\treturn (\n\t\tdb\n\t\t\t.prepare(`SELECT 1 FROM replication_scopes WHERE scope_id = ?\n\t\tAND authority_type IN ('local', 'manual', 'invite')`)\n\t\t\t.get(scope) !== undefined\n\t);\n}\n\nfunction retainOrDiagnoseLocalRow(\n\tdb: Database,\n\trow: StalePeerReceivedRow,\n\tlocalDeviceId: string,\n\tcreationSources: readonly string[],\n\tresult: ReconcileStalePeerReceivedRowsResult,\n): boolean {\n\tconst importKey = cleanText(row.import_key);\n\tconst origin = cleanText(row.origin_device_id);\n\tconst recorded = importKey !== null && hasRecordedLocalCreation(db, importKey);\n\tif (importKey && hasMatchingLocalCreation(db, importKey, creationSources)) {\n\t\tresult.retained += 1;\n\t\treturn true;\n\t}\n\t// Legacy labels retain old rows, but cannot override an unmatched creation record.\n\tif (!recorded && origin === localDeviceId && legacyLocalRetentionScope(db, row.scope_id)) {\n\t\tresult.retained += 1;\n\t\treturn true;\n\t}\n\tif (!recorded && origin !== localDeviceId && origin !== \"local\") return false;\n\t// Preserve uncertain originals; this diagnostic grants no read or write permission.\n\tresult.ambiguous.push(\n\t\tstalePeerCandidateDiagnostic({\n\t\t\tmemoryId: Number(row.id),\n\t\t\timportKey,\n\t\t\toriginDeviceId: origin,\n\t\t\tscopeId: cleanText(row.scope_id),\n\t\t\treason: \"unverified_local_creation\",\n\t\t}),\n\t);\n\treturn true;\n}\n\nfunction reconcileStalePeerReceivedRowsInternal(\n\tdb: Database,\n\toptions: ReconcileStalePeerReceivedRowsOptions,\n\tdeleteRows: boolean,\n): ReconcileStalePeerReceivedRowsResult {\n\tconst localDeviceId = cleanText(options.localDeviceId);\n\tif (!localDeviceId) throw new Error(\"localDeviceId must be a non-empty string\");\n\tconst peerDeviceId = cleanText(options.peerDeviceId);\n\tconst maxRows =\n\t\ttypeof options.maxRows === \"number\" && Number.isFinite(options.maxRows)\n\t\t\t? Math.max(0, Math.trunc(options.maxRows))\n\t\t\t: -1;\n\tconst rows = stalePeerReceivedRows(db, peerDeviceId, maxRows);\n\tconst result: ReconcileStalePeerReceivedRowsResult = {\n\t\tchecked: rows.length,\n\t\tdeleted: 0,\n\t\tdeleted_memory_ids: [],\n\t\tretained: 0,\n\t\tambiguous: [],\n\t};\n\tconst deleteMemory = deleteRows ? db.prepare(\"DELETE FROM memory_items WHERE id = ?\") : null;\n\tconst deleteCandidate = (\n\t\tmemoryId: number,\n\t\tcursor?: { originDeviceId: string; scopeId: string },\n\t): void => {\n\t\tif (deleteRows) {\n\t\t\tclearRefsBeforeMemoryDeletion(db, memoryId);\n\t\t\tdeleteMemory?.run(memoryId);\n\t\t\tif (cursor && cursor.scopeId !== DEFAULT_SYNC_SCOPE_ID) {\n\t\t\t\tclearReplicationCursorLastApplied(db, cursor.originDeviceId, cursor.scopeId);\n\t\t\t}\n\t\t}\n\t\tresult.deleted += 1;\n\t\tresult.deleted_memory_ids.push(memoryId);\n\t};\n\tconst creationSources = cleanupCreationSourceIds(db, localDeviceId, options);\n\tdb.transaction(() => {\n\t\t// Authorization decisions must not survive this synchronous cleanup transaction.\n\t\tconst authorizationByScope = new Map<string, CachedScopeAuthorizationResult>();\n\t\tfor (const row of rows) {\n\t\t\tconst memoryId = Number(row.id);\n\t\t\tconst importKey = cleanText(row.import_key);\n\t\t\tconst originDeviceId = cleanText(row.origin_device_id);\n\t\t\tconst scopeId = cleanText(row.scope_id);\n\t\t\tif (retainOrDiagnoseLocalRow(db, row, localDeviceId, creationSources, result)) continue;\n\t\t\tif (!originDeviceId) {\n\t\t\t\tresult.ambiguous.push(\n\t\t\t\t\tstalePeerCandidateDiagnostic({\n\t\t\t\t\t\timportKey,\n\t\t\t\t\t\tmemoryId,\n\t\t\t\t\t\toriginDeviceId,\n\t\t\t\t\t\treason: \"missing_origin_device\",\n\t\t\t\t\t\tscopeId,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!scopeId || scopeId === DEFAULT_SYNC_SCOPE_ID) {\n\t\t\t\tdeleteCandidate(memoryId);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!importKey) {\n\t\t\t\tresult.ambiguous.push(\n\t\t\t\t\tstalePeerCandidateDiagnostic({\n\t\t\t\t\t\timportKey,\n\t\t\t\t\t\tmemoryId,\n\t\t\t\t\t\toriginDeviceId,\n\t\t\t\t\t\treason: \"missing_import_key\",\n\t\t\t\t\t\tscopeId,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlet auth = authorizationByScope.get(scopeId);\n\t\t\tif (!auth) {\n\t\t\t\tauth = getCachedScopeAuthorization(db, { deviceId: localDeviceId, scopeId });\n\t\t\t\tauthorizationByScope.set(scopeId, auth);\n\t\t\t}\n\t\t\tif (auth.authorized) {\n\t\t\t\tresult.retained += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!auth.scope) {\n\t\t\t\tresult.ambiguous.push(\n\t\t\t\t\tstalePeerCandidateDiagnostic({\n\t\t\t\t\t\timportKey,\n\t\t\t\t\t\tmemoryId,\n\t\t\t\t\t\toriginDeviceId,\n\t\t\t\t\t\treason: \"authorization_unknown\",\n\t\t\t\t\t\tscopeId,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!auth.membership) {\n\t\t\t\tdeleteCandidate(memoryId, { originDeviceId, scopeId });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!stalePeerCandidateIsDeletable(auth.state)) {\n\t\t\t\tresult.ambiguous.push(\n\t\t\t\t\tstalePeerCandidateDiagnostic({\n\t\t\t\t\t\timportKey,\n\t\t\t\t\t\tmemoryId,\n\t\t\t\t\t\toriginDeviceId,\n\t\t\t\t\t\treason: \"authorization_unknown\",\n\t\t\t\t\t\tscopeId,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tdeleteCandidate(memoryId, { originDeviceId, scopeId });\n\t\t}\n\t})();\n\treturn result;\n}\n\nexport type InboundScopeRejectionReason =\n\t| \"missing_scope\"\n\t| \"sender_not_member\"\n\t| \"receiver_not_member\"\n\t| \"stale_epoch\"\n\t| \"scope_mismatch\";\n\nexport interface InboundScopeRejection {\n\top_id: string;\n\tentity_type: string;\n\tentity_id: string;\n\tscope_id: string | null;\n\tpeer_device_id: string | null;\n\treason: InboundScopeRejectionReason;\n}\n\nexport interface InboundScopeValidationOptions {\n\tpeerDeviceId?: string | null;\n\tenabled?: boolean;\n}\n\nexport interface ApplyReplicationOpsOptions extends LocalCreationContext {\n\t/** Authenticated transport peer, for durable applied-mutation accounting. */\n\tactivityPeerDeviceId?: string;\n\t/** Keep incoming requests from resolving failures owned by local cursor retries. */\n\tactivitySource?: SyncTransferObservationSource;\n\tactivityOptions?: { preserveError?: boolean };\n\tinboundScopeValidation?: InboundScopeValidationOptions | null;\n\tkeysDir?: string;\n}\n\nfunction cleanupCreationSourceIds(\n\tdb: Database,\n\tdeviceId: string,\n\toptions: LocalCreationContext & { keysDir?: string },\n): string[] {\n\treturn localCreationSourceIds(db, deviceId, {\n\t\t...options,\n\t\tloadExpectedPublicKey:\n\t\t\toptions.loadExpectedPublicKey ??\n\t\t\t(() =>\n\t\t\t\tloadRuntimeSigningPublicKey(db, {\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tkeysDir: options.keysDir ?? process.env.CODEMEM_KEYS_DIR?.trim(),\n\t\t\t\t}) ?? undefined),\n\t});\n}\n\ntype CachedScopeAuthorizationResult = ReturnType<typeof getCachedScopeAuthorization>;\n\nfunction inboundScopeRejection(\n\top: ReplicationOp,\n\treason: InboundScopeRejectionReason,\n\tpeerDeviceId: string | null,\n\tscopeId: string | null,\n): InboundScopeRejection {\n\treturn {\n\t\top_id: op.op_id,\n\t\tentity_type: op.entity_type,\n\t\tentity_id: op.entity_id,\n\t\tscope_id: scopeId,\n\t\tpeer_device_id: peerDeviceId,\n\t\treason,\n\t};\n}\n\nfunction normalizeInboundScopeId(value: unknown): string | null {\n\treturn cleanText(value);\n}\n\nfunction metadataObject(payload: Record<string, unknown> | null): Record<string, unknown> {\n\tconst metadata = payload?.metadata_json;\n\tif (!metadata || typeof metadata !== \"object\" || Array.isArray(metadata)) return {};\n\treturn metadata as Record<string, unknown>;\n}\n\nfunction payloadContradictsInboundScope(\n\topScopeId: string,\n\tpayload: Record<string, unknown> | null,\n): boolean {\n\tconst metadata = metadataObject(payload);\n\tconst payloadScopeId = cleanText(payload?.scope_id ?? metadata.scope_id);\n\tif (payloadScopeId && payloadScopeId !== opScopeId) return true;\n\n\tconst workspaceId = cleanText(payload?.workspace_id ?? metadata.workspace_id);\n\tif (workspaceId?.startsWith(\"personal:\") && workspaceId !== opScopeId) return true;\n\n\tconst workspaceKind = cleanText(\n\t\tpayload?.workspace_kind ?? metadata.workspace_kind,\n\t)?.toLowerCase();\n\tconst actorId = cleanText(payload?.actor_id ?? metadata.actor_id);\n\tif (workspaceKind === \"personal\" && actorId && `personal:${actorId}` !== opScopeId) {\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nfunction authorizationFailureReason(\n\tauth: CachedScopeAuthorizationResult,\n\tnotMemberReason: \"sender_not_member\" | \"receiver_not_member\",\n): InboundScopeRejectionReason | null {\n\tif (auth.scope?.authority_type === \"local\") return \"missing_scope\";\n\tif (auth.authorized) return null;\n\tif (\n\t\t!auth.scope ||\n\t\tauth.state === \"revoked\" ||\n\t\tauth.state === \"stale_epoch\" ||\n\t\tauth.state === \"scope_unknown\" ||\n\t\tauth.state === \"scope_inactive\"\n\t) {\n\t\treturn \"stale_epoch\";\n\t}\n\treturn notMemberReason;\n}\n\ntype LocalDefaultOldSideReassignmentValidation =\n\t| { ok: true; reassignment: ReassignScopePayload }\n\t| { ok: false; reason: \"scope_mismatch\" | \"sender_not_member\" };\n\nfunction validateLocalDefaultOldSideReassignment(\n\tdb: Database,\n\top: ReplicationOp,\n\tsenderDeviceId: string | null,\n): LocalDefaultOldSideReassignmentValidation {\n\tlet reassignment: ReassignScopePayload;\n\ttry {\n\t\treassignment = parseReassignScopePayload(op);\n\t} catch {\n\t\treturn { ok: false, reason: \"scope_mismatch\" };\n\t}\n\tif (reassignment.side !== \"old\" || reassignment.old_scope_id !== DEFAULT_SYNC_SCOPE_ID) {\n\t\treturn { ok: false, reason: \"scope_mismatch\" };\n\t}\n\tif (\n\t\t!senderDeviceId ||\n\t\tcleanText(op.device_id) !== senderDeviceId ||\n\t\tcleanText(op.clock_device_id) !== senderDeviceId\n\t) {\n\t\treturn { ok: false, reason: \"sender_not_member\" };\n\t}\n\tconst existing = db\n\t\t.prepare(\"SELECT origin_device_id FROM memory_items WHERE import_key = ?\")\n\t\t.get(op.entity_id) as { origin_device_id: string | null } | undefined;\n\tif (existing && cleanText(existing.origin_device_id) !== senderDeviceId) {\n\t\treturn { ok: false, reason: \"sender_not_member\" };\n\t}\n\treturn { ok: true, reassignment };\n}\n\nfunction validateInboundScopeOp(\n\tdb: Database,\n\top: ReplicationOp,\n\tlocalDeviceId: string,\n\toptions: InboundScopeValidationOptions,\n): InboundScopeRejection | null {\n\tconst peerDeviceId = cleanText(options.peerDeviceId) ?? cleanText(op.device_id);\n\tif (op.op_type === ACCESS_CLEANUP_OP_TYPE) {\n\t\tconst senderDeviceId = peerDeviceId ?? cleanText(op.clock_device_id);\n\t\tif (\n\t\t\t!senderDeviceId ||\n\t\t\tcleanText(op.device_id) !== senderDeviceId ||\n\t\t\tcleanText(op.clock_device_id) !== senderDeviceId\n\t\t) {\n\t\t\treturn inboundScopeRejection(op, \"sender_not_member\", peerDeviceId, null);\n\t\t}\n\t\treturn null;\n\t}\n\tconst senderDeviceId = peerDeviceId ?? cleanText(op.clock_device_id);\n\tconst receiverDeviceId = cleanText(localDeviceId);\n\tconst opScopeId = normalizeInboundScopeId(op.scope_id);\n\n\tif (!opScopeId) return inboundScopeRejection(op, \"missing_scope\", peerDeviceId, null);\n\tconst payload = parsePayload(op.payload_json);\n\tif (payloadContradictsInboundScope(opScopeId, payload)) {\n\t\treturn inboundScopeRejection(op, \"scope_mismatch\", peerDeviceId, opScopeId);\n\t}\n\n\tif (\n\t\t!senderDeviceId ||\n\t\tcleanText(op.device_id) !== senderDeviceId ||\n\t\tcleanText(op.clock_device_id) !== senderDeviceId\n\t) {\n\t\treturn inboundScopeRejection(op, \"sender_not_member\", peerDeviceId, opScopeId);\n\t}\n\tlet authorizationScopeId = opScopeId;\n\tlet requireReceiverMembership = true;\n\tlet allowLocalAuthorityRetraction = false;\n\tif (opScopeId === DEFAULT_SYNC_SCOPE_ID) {\n\t\tconst validation = validateLocalDefaultOldSideReassignment(db, op, senderDeviceId);\n\t\tif (!validation.ok) {\n\t\t\treturn inboundScopeRejection(op, validation.reason, peerDeviceId, opScopeId);\n\t\t}\n\t\tauthorizationScopeId = validation.reassignment.new_scope_id;\n\t\tallowLocalAuthorityRetraction = true;\n\t\t// This side only retracts sender-origin data previously delivered through\n\t\t// local-default. Prior recipients intentionally are not members of the new\n\t\t// boundary, and the apply path cannot create a new-scope row for them.\n\t\trequireReceiverMembership = false;\n\t}\n\n\tconst senderAuth = getCachedScopeAuthorization(db, {\n\t\tdeviceId: senderDeviceId,\n\t\tscopeId: authorizationScopeId,\n\t});\n\t// A validated old-side op only retracts a sender-owned local-default row;\n\t// it cannot create data in the destination scope. Permit that removal when\n\t// the receiver cannot know the sender's new device-local scope.\n\tconst senderFailure =\n\t\tallowLocalAuthorityRetraction &&\n\t\t(senderAuth.authorized || (senderAuth.state === \"not_authorized\" && !senderAuth.scope))\n\t\t\t? null\n\t\t\t: authorizationFailureReason(senderAuth, \"sender_not_member\");\n\tif (senderFailure) return inboundScopeRejection(op, senderFailure, peerDeviceId, opScopeId);\n\n\tif (requireReceiverMembership) {\n\t\tif (!receiverDeviceId) {\n\t\t\treturn inboundScopeRejection(op, \"receiver_not_member\", peerDeviceId, opScopeId);\n\t\t}\n\t\tconst receiverAuth = getCachedScopeAuthorization(db, {\n\t\t\tdeviceId: receiverDeviceId,\n\t\t\tscopeId: authorizationScopeId,\n\t\t});\n\t\tconst receiverFailure = authorizationFailureReason(receiverAuth, \"receiver_not_member\");\n\t\tif (receiverFailure) return inboundScopeRejection(op, receiverFailure, peerDeviceId, opScopeId);\n\t}\n\n\treturn null;\n}\n\nfunction validateInboundScopeBatch(\n\tdb: Database,\n\tops: ReplicationOp[],\n\tlocalDeviceId: string,\n\toptions: InboundScopeValidationOptions,\n): InboundScopeRejection[] {\n\tconst rejections: InboundScopeRejection[] = [];\n\tconst expectedPeerDeviceId = cleanText(options.peerDeviceId);\n\tfor (const op of ops) {\n\t\tif (!expectedPeerDeviceId && op.device_id === localDeviceId) continue;\n\t\tconst rejection = validateInboundScopeOp(db, op, localDeviceId, options);\n\t\tif (rejection) rejections.push(rejection);\n\t}\n\treturn rejections;\n}\n\nfunction validateInboundLocalOnlyBatch(\n\tdb: Database,\n\tops: ReplicationOp[],\n\toptions: InboundScopeValidationOptions,\n): InboundScopeRejection[] {\n\tconst peerDeviceId = cleanText(options.peerDeviceId);\n\tconst rejections: InboundScopeRejection[] = [];\n\tfor (const op of ops) {\n\t\tif (op.entity_type !== \"memory_item\" || op.op_type === ACCESS_CLEANUP_OP_TYPE) continue;\n\t\tconst scopeId = normalizeInboundScopeId(op.scope_id);\n\t\tif (!scopeId) {\n\t\t\trejections.push(inboundScopeRejection(op, \"missing_scope\", peerDeviceId, null));\n\t\t\tcontinue;\n\t\t}\n\t\tif (scopeId !== DEFAULT_SYNC_SCOPE_ID) {\n\t\t\tconst scope = db\n\t\t\t\t.prepare(\"SELECT authority_type FROM replication_scopes WHERE scope_id = ? LIMIT 1\")\n\t\t\t\t.get(scopeId) as { authority_type?: string | null } | undefined;\n\t\t\tif (scope?.authority_type === \"local\" || (!scope && options.enabled === false)) {\n\t\t\t\trejections.push(inboundScopeRejection(op, \"missing_scope\", peerDeviceId, scopeId));\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (op.op_type === REASSIGN_SCOPE_OP_TYPE) {\n\t\t\tconst validation = validateLocalDefaultOldSideReassignment(\n\t\t\t\tdb,\n\t\t\t\top,\n\t\t\t\tpeerDeviceId ?? cleanText(op.clock_device_id),\n\t\t\t);\n\t\t\tif (validation.ok) continue;\n\t\t\tif (validation.reason === \"sender_not_member\") {\n\t\t\t\trejections.push(inboundScopeRejection(op, validation.reason, peerDeviceId, scopeId));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\trejections.push(inboundScopeRejection(op, \"scope_mismatch\", peerDeviceId, scopeId));\n\t}\n\treturn rejections;\n}\n\nfunction ensureSyncScopeRejectionLogTable(db: Database): void {\n\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS sync_scope_rejections (\n\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\tpeer_device_id TEXT,\n\t\t\top_id TEXT NOT NULL,\n\t\t\tentity_type TEXT NOT NULL,\n\t\t\tentity_id TEXT NOT NULL,\n\t\t\tscope_id TEXT,\n\t\t\treason TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL\n\t\t);\n\t\tCREATE INDEX IF NOT EXISTS idx_sync_scope_rejections_peer_created\n\t\t\tON sync_scope_rejections(peer_device_id, created_at);\n\t\tCREATE INDEX IF NOT EXISTS idx_sync_scope_rejections_scope_created\n\t\t\tON sync_scope_rejections(scope_id, created_at);\n\t`);\n}\n\nfunction recordInboundScopeRejections(db: Database, rejections: InboundScopeRejection[]): void {\n\tif (rejections.length === 0) return;\n\tensureSyncScopeRejectionLogTable(db);\n\tconst now = new Date().toISOString();\n\tconst insert = db.prepare(\n\t\t`INSERT INTO sync_scope_rejections(\n\t\t\tpeer_device_id, op_id, entity_type, entity_id, scope_id, reason, created_at\n\t\t ) VALUES (?, ?, ?, ?, ?, ?, ?)`,\n\t);\n\tdb.transaction(() => {\n\t\tfor (const rejection of rejections) {\n\t\t\tinsert.run(\n\t\t\t\trejection.peer_device_id,\n\t\t\t\trejection.op_id,\n\t\t\t\trejection.entity_type,\n\t\t\t\trejection.entity_id,\n\t\t\t\trejection.scope_id,\n\t\t\t\trejection.reason,\n\t\t\t\tnow,\n\t\t\t);\n\t\t}\n\t})();\n}\n\nfunction emptyApplyResult(): ApplyResult {\n\treturn {\n\t\tapplied: 0,\n\t\tskipped: 0,\n\t\trejected: 0,\n\t\tconflicts: 0,\n\t\terrors: [],\n\t\trejections: [],\n\t\tvectorWork: { upsertMemoryIds: [], deleteMemoryIds: [] },\n\t};\n}\n\nexport function rejectInboundScopeFailures(\n\tdb: Database,\n\tops: ReplicationOp[],\n\tlocalDeviceId: string,\n\toptions: InboundScopeValidationOptions,\n): ApplyResult | null {\n\tconst localOnlyRejections = validateInboundLocalOnlyBatch(db, ops, options);\n\tconst rejections =\n\t\tlocalOnlyRejections.length > 0\n\t\t\t? localOnlyRejections\n\t\t\t: options.enabled === false\n\t\t\t\t? []\n\t\t\t\t: validateInboundScopeBatch(db, ops, localDeviceId, options);\n\tif (rejections.length === 0) return null;\n\tconst result = emptyApplyResult();\n\tresult.rejected = rejections.length;\n\tresult.rejections = rejections;\n\tresult.errors.push(\n\t\t...rejections.map((rejection) => `op ${rejection.op_id}: rejected — ${rejection.reason}`),\n\t);\n\ttry {\n\t\trecordInboundScopeRejections(db, rejections);\n\t} catch (err) {\n\t\tresult.errors.push(\n\t\t\t`scope rejection log failed: ${err instanceof Error ? err.message : String(err)}`,\n\t\t);\n\t}\n\treturn result;\n}\n\n/** Aggregate counts of recorded inbound-scope rejections per peer device. */\nexport interface InboundScopeRejectionPeerSummary {\n\tpeer_device_id: string | null;\n\ttotal: number;\n\tby_reason: Partial<Record<InboundScopeRejectionReason, number>>;\n\tlast_at: string | null;\n}\n\nexport interface InboundScopeRejectionSummaryOptions {\n\t/** ISO timestamp; rejections older than this are ignored. */\n\tsinceIso?: string;\n\t/** Optional: only summarize rejections recorded for this peer. */\n\tpeerDeviceId?: string | null;\n}\n\n/**\n * Read-only summary of recorded inbound-scope rejections grouped by peer.\n * Pure aggregate over the rejection log — never reads payloads (the log\n * does not store any). Used by the sync API to render reason-code\n * breakdowns without exposing op contents.\n */\nexport function summarizeInboundScopeRejections(\n\tdb: Database,\n\toptions: InboundScopeRejectionSummaryOptions = {},\n): InboundScopeRejectionPeerSummary[] {\n\tif (!syncScopeRejectionsTableExists(db)) return [];\n\tconst params: unknown[] = [];\n\tconst filters: string[] = [];\n\tif (options.sinceIso) {\n\t\tfilters.push(`created_at >= ?`);\n\t\tparams.push(options.sinceIso);\n\t}\n\tif (options.peerDeviceId !== undefined) {\n\t\tconst id = cleanText(options.peerDeviceId);\n\t\tif (id === null) {\n\t\t\tfilters.push(`peer_device_id IS NULL`);\n\t\t} else {\n\t\t\tfilters.push(`peer_device_id = ?`);\n\t\t\tparams.push(id);\n\t\t}\n\t}\n\tconst where = filters.length ? `WHERE ${filters.join(\" AND \")}` : \"\";\n\tconst rows = db\n\t\t.prepare(\n\t\t\t`SELECT peer_device_id, reason, COUNT(*) AS count, MAX(created_at) AS last_at\n\t\t\t FROM sync_scope_rejections\n\t\t\t ${where}\n\t\t\t GROUP BY peer_device_id, reason`,\n\t\t)\n\t\t.all(...params) as Array<{\n\t\tpeer_device_id: string | null;\n\t\treason: string;\n\t\tcount: number;\n\t\tlast_at: string | null;\n\t}>;\n\n\tconst summaries = new Map<string, InboundScopeRejectionPeerSummary>();\n\tfor (const row of rows) {\n\t\tconst key = row.peer_device_id ?? \"\";\n\t\tlet entry = summaries.get(key);\n\t\tif (!entry) {\n\t\t\tentry = {\n\t\t\t\tpeer_device_id: row.peer_device_id ?? null,\n\t\t\t\ttotal: 0,\n\t\t\t\tby_reason: {},\n\t\t\t\tlast_at: null,\n\t\t\t};\n\t\t\tsummaries.set(key, entry);\n\t\t}\n\t\tconst reason = row.reason as InboundScopeRejectionReason;\n\t\tconst count = Number(row.count ?? 0);\n\t\tentry.by_reason[reason] = (entry.by_reason[reason] ?? 0) + count;\n\t\tentry.total += count;\n\t\tif (row.last_at && (!entry.last_at || row.last_at > entry.last_at)) {\n\t\t\tentry.last_at = row.last_at;\n\t\t}\n\t}\n\treturn Array.from(summaries.values());\n}\n\nexport interface InboundScopeRejectionRecord extends InboundScopeRejection {\n\tid: number;\n\tcreated_at: string;\n}\n\nexport interface ListInboundScopeRejectionsOptions {\n\tpeerDeviceId?: string | null;\n\tsinceIso?: string;\n\tlimit?: number;\n}\n\n/**\n * List recently recorded inbound-scope rejections (newest first). Each row\n * is metadata only — op id, entity ref, scope id, reason, timestamp — and\n * never includes op payloads (the log does not store them).\n */\nexport function listInboundScopeRejections(\n\tdb: Database,\n\toptions: ListInboundScopeRejectionsOptions = {},\n): InboundScopeRejectionRecord[] {\n\tif (!syncScopeRejectionsTableExists(db)) return [];\n\tconst params: unknown[] = [];\n\tconst filters: string[] = [];\n\tif (options.sinceIso) {\n\t\tfilters.push(`created_at >= ?`);\n\t\tparams.push(options.sinceIso);\n\t}\n\tif (options.peerDeviceId !== undefined) {\n\t\tconst id = cleanText(options.peerDeviceId);\n\t\tif (id === null) {\n\t\t\tfilters.push(`peer_device_id IS NULL`);\n\t\t} else {\n\t\t\tfilters.push(`peer_device_id = ?`);\n\t\t\tparams.push(id);\n\t\t}\n\t}\n\tconst where = filters.length ? `WHERE ${filters.join(\" AND \")}` : \"\";\n\tconst limit = Math.max(1, Math.min(options.limit ?? 100, 500));\n\tconst rows = db\n\t\t.prepare(\n\t\t\t`SELECT id, peer_device_id, op_id, entity_type, entity_id, scope_id, reason, created_at\n\t\t\t FROM sync_scope_rejections\n\t\t\t ${where}\n\t\t\t ORDER BY created_at DESC, id DESC\n\t\t\t LIMIT ?`,\n\t\t)\n\t\t.all(...params, limit) as Array<{\n\t\tid: number;\n\t\tpeer_device_id: string | null;\n\t\top_id: string;\n\t\tentity_type: string;\n\t\tentity_id: string;\n\t\tscope_id: string | null;\n\t\treason: string;\n\t\tcreated_at: string;\n\t}>;\n\treturn rows.map((row) => ({\n\t\tid: Number(row.id),\n\t\tpeer_device_id: row.peer_device_id ?? null,\n\t\top_id: row.op_id,\n\t\tentity_type: row.entity_type,\n\t\tentity_id: row.entity_id,\n\t\tscope_id: row.scope_id ?? null,\n\t\treason: row.reason as InboundScopeRejectionReason,\n\t\tcreated_at: row.created_at,\n\t}));\n}\n\nfunction syncScopeRejectionsTableExists(db: Database): boolean {\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sync_scope_rejections' LIMIT 1`,\n\t\t)\n\t\t.get();\n\treturn Boolean(row);\n}\n\nconst LEGACY_IMPORT_KEY_OLD_RE = /^legacy:memory_item:(.+)$/;\n\n/**\n * Rewrite legacy import keys into globally unique, device-scoped keys.\n *\n * Older databases may contain keys like `legacy:memory_item:<id>`, which can\n * collide across peers. This rewrites them to\n * `legacy:<device_id>:memory_item:<id>`.\n */\nexport function migrateLegacyImportKeys(db: Database, limit = 2000): number {\n\tconst d = drizzle(db, { schema });\n\tconst deviceRow = d\n\t\t.select({ device_id: schema.syncDevice.device_id })\n\t\t.from(schema.syncDevice)\n\t\t.limit(1)\n\t\t.get();\n\tconst localDeviceId = String(deviceRow?.device_id ?? \"\").trim();\n\tif (!localDeviceId) return 0;\n\n\tconst rows = d\n\t\t.select({\n\t\t\tid: schema.memoryItems.id,\n\t\t\timport_key: schema.memoryItems.import_key,\n\t\t\tmetadata_json: schema.memoryItems.metadata_json,\n\t\t})\n\t\t.from(schema.memoryItems)\n\t\t.where(\n\t\t\tor(\n\t\t\t\tisNull(schema.memoryItems.import_key),\n\t\t\t\tsql`TRIM(${schema.memoryItems.import_key}) = ''`,\n\t\t\t\tlike(schema.memoryItems.import_key, \"legacy:memory_item:%\"),\n\t\t\t),\n\t\t)\n\t\t.orderBy(schema.memoryItems.id)\n\t\t.limit(limit)\n\t\t.all();\n\n\tif (rows.length === 0) return 0;\n\n\tlet updated = 0;\n\tfor (const row of rows) {\n\t\tconst memoryId = Number(row.id);\n\t\tconst current = String(row.import_key ?? \"\").trim();\n\t\tconst metadata = fromJson(row.metadata_json);\n\t\tconst clockDeviceId =\n\t\t\ttypeof metadata.clock_device_id === \"string\" ? metadata.clock_device_id.trim() : \"\";\n\n\t\tlet canonical = \"\";\n\t\tif (!current) {\n\t\t\tcanonical = `legacy:${localDeviceId}:memory_item:${memoryId}`;\n\t\t} else {\n\t\t\tconst match = current.match(LEGACY_IMPORT_KEY_OLD_RE);\n\t\t\tif (!match) continue;\n\t\t\tconst suffix = match[1] ?? \"\";\n\t\t\tconst origin = clockDeviceId && clockDeviceId !== \"local\" ? clockDeviceId : localDeviceId;\n\t\t\tcanonical = origin ? `legacy:${origin}:memory_item:${suffix}` : \"\";\n\t\t}\n\n\t\tif (!canonical || canonical === current) continue;\n\n\t\tconst existing = d\n\t\t\t.select({ id: schema.memoryItems.id })\n\t\t\t.from(schema.memoryItems)\n\t\t\t.where(eq(schema.memoryItems.import_key, canonical))\n\t\t\t.limit(1)\n\t\t\t.get();\n\t\tif (existing && Number(existing.id) !== memoryId) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tassignMemoryImportKey(db, memoryId, canonical);\n\t\tupdated++;\n\t}\n\n\treturn updated;\n}\n\nfunction assignMemoryImportKey(db: Database, memoryId: number, importKey: string): void {\n\tdb.transaction(() => {\n\t\tsnapshotSessionExportKeysForMemoryIds(db, [memoryId]);\n\t\tdb.prepare(\"UPDATE memory_items SET import_key = ? WHERE id = ?\").run(importKey, memoryId);\n\t}).immediate();\n}\n\n/**\n * Generate replication ops for rows that predate replication.\n *\n * Prioritizes delete/tombstone ops first, then active upserts, and only\n * generates ops when a matching op for the same entity/rev/op_type is missing.\n */\nexport function backfillReplicationOps(db: Database, limit = 200): number {\n\tif (limit <= 0) return 0;\n\n\tmigrateLegacyImportKeys(db, 2000);\n\n\tconst d = drizzle(db, { schema });\n\tconst deviceRow = d\n\t\t.select({ device_id: schema.syncDevice.device_id })\n\t\t.from(schema.syncDevice)\n\t\t.limit(1)\n\t\t.get();\n\tconst localDeviceId = String(deviceRow?.device_id ?? \"\").trim();\n\n\tconst deletedRows = d\n\t\t.select()\n\t\t.from(schema.memoryItems)\n\t\t.where(\n\t\t\tand(\n\t\t\t\tor(isNotNull(schema.memoryItems.deleted_at), eq(schema.memoryItems.active, 0)),\n\t\t\t\tsql`NOT EXISTS (\n\t\t\t\t\tSELECT 1\n\t\t\t\t\tFROM replication_ops ro\n\t\t\t\t\tWHERE ro.entity_type = 'memory_item'\n\t\t\t\t\t AND ro.entity_id = ${schema.memoryItems.import_key}\n\t\t\t\t\t AND ro.op_type = 'delete'\n\t\t\t\t\t AND ro.clock_rev = COALESCE(${schema.memoryItems.rev}, 0)\n\t\t\t\t)`,\n\t\t\t),\n\t\t)\n\t\t.orderBy(schema.memoryItems.updated_at)\n\t\t.limit(limit)\n\t\t.all();\n\n\tconst remaining = Math.max(0, limit - deletedRows.length);\n\tlet rows = deletedRows;\n\tif (remaining > 0) {\n\t\tconst upsertRows = d\n\t\t\t.select()\n\t\t\t.from(schema.memoryItems)\n\t\t\t.where(\n\t\t\t\tand(\n\t\t\t\t\tisNull(schema.memoryItems.deleted_at),\n\t\t\t\t\teq(schema.memoryItems.active, 1),\n\t\t\t\t\tsql`NOT EXISTS (\n\t\t\t\t\t\tSELECT 1\n\t\t\t\t\t\tFROM replication_ops ro\n\t\t\t\t\t\tWHERE ro.entity_type = 'memory_item'\n\t\t\t\t\t\t AND ro.entity_id = ${schema.memoryItems.import_key}\n\t\t\t\t\t\t AND ro.op_type = 'upsert'\n\t\t\t\t\t\t AND ro.clock_rev = COALESCE(${schema.memoryItems.rev}, 0)\n\t\t\t\t\t)`,\n\t\t\t\t),\n\t\t\t)\n\t\t\t.orderBy(schema.memoryItems.updated_at)\n\t\t\t.limit(remaining)\n\t\t\t.all();\n\t\trows = [...rows, ...upsertRows];\n\t}\n\n\tif (rows.length === 0) return 0;\n\n\tconst now = new Date().toISOString();\n\tlet inserted = 0;\n\n\tfor (const row of rows) {\n\t\tconst rowId = Number(row.id ?? 0);\n\t\tif (!rowId) continue;\n\n\t\tconst metadata =\n\t\t\ttypeof row.metadata_json === \"string\"\n\t\t\t\t? fromJson(row.metadata_json)\n\t\t\t\t: fromJsonNullableLike(row.metadata_json);\n\t\tconst metadataClockDeviceId =\n\t\t\ttypeof metadata.clock_device_id === \"string\" ? metadata.clock_device_id.trim() : \"\";\n\t\tconst originDeviceId =\n\t\t\tmetadataClockDeviceId && metadataClockDeviceId !== \"local\"\n\t\t\t\t? metadataClockDeviceId\n\t\t\t\t: localDeviceId;\n\n\t\tlet importKey = String(row.import_key ?? \"\").trim();\n\t\tif (!importKey) {\n\t\t\tif (!originDeviceId) continue;\n\t\t\timportKey = `legacy:${originDeviceId}:memory_item:${rowId}`;\n\t\t\tassignMemoryImportKey(db, rowId, importKey);\n\t\t}\n\n\t\tconst rev = Number(row.rev ?? 0);\n\t\tconst active = Number(row.active ?? 1);\n\t\tconst deletedAt = String(row.deleted_at ?? \"\").trim();\n\t\tconst opType: \"upsert\" | \"delete\" = deletedAt || active === 0 ? \"delete\" : \"upsert\";\n\t\tconst opId = `backfill:memory_item:${importKey}:${rev}:${opType}`;\n\n\t\tconst exists = d\n\t\t\t.select({ one: sql<number>`1` })\n\t\t\t.from(schema.replicationOps)\n\t\t\t.where(eq(schema.replicationOps.op_id, opId))\n\t\t\t.limit(1)\n\t\t\t.get();\n\t\tif (exists) continue;\n\n\t\tconst clockDeviceId = originDeviceId;\n\t\tif (!clockDeviceId) continue;\n\t\tconst scopeId = ensureMemoryScopeId(db, rowId);\n\t\tconst payload = buildPayloadFromMemoryRow({ ...row, scope_id: scopeId });\n\n\t\td.insert(schema.replicationOps)\n\t\t\t.values({\n\t\t\t\top_id: opId,\n\t\t\t\tentity_type: \"memory_item\",\n\t\t\t\tentity_id: importKey,\n\t\t\t\top_type: opType,\n\t\t\t\tpayload_json: toJson(payload),\n\t\t\t\tclock_rev: rev,\n\t\t\t\tclock_updated_at: String(row.updated_at ?? now),\n\t\t\t\tclock_device_id: clockDeviceId,\n\t\t\t\tdevice_id: clockDeviceId,\n\t\t\t\tcreated_at: now,\n\t\t\t\tscope_id: scopeId,\n\t\t\t})\n\t\t\t.onConflictDoNothing()\n\t\t\t.run();\n\n\t\tinserted++;\n\t}\n\n\treturn inserted;\n}\n\nfunction fromJsonNullableLike(value: unknown): Record<string, unknown> {\n\tif (typeof value === \"string\") return fromJson(value);\n\tif (value && typeof value === \"object\") return value as Record<string, unknown>;\n\treturn {};\n}\n\nfunction buildPayloadFromMemoryRow(row: MemoryItemRow): MemoryPayload {\n\tconst parseSqliteJson = (val: unknown): unknown => {\n\t\tif (typeof val !== \"string\") return val ?? null;\n\t\ttry {\n\t\t\treturn JSON.parse(val);\n\t\t} catch {\n\t\t\treturn val;\n\t\t}\n\t};\n\tconst metadataParsed = parseSqliteJson(row.metadata_json);\n\tconst metadataJson =\n\t\tmetadataParsed && typeof metadataParsed === \"object\" && !Array.isArray(metadataParsed)\n\t\t\t? (metadataParsed as Record<string, unknown>)\n\t\t\t: {};\n\n\treturn {\n\t\tsession_id: row.session_id ?? null,\n\t\tkind: row.kind ?? null,\n\t\ttitle: row.title ?? null,\n\t\tsubtitle: row.subtitle ?? null,\n\t\tbody_text: row.body_text ?? null,\n\t\tconfidence: row.confidence ?? null,\n\t\ttags_text: row.tags_text ?? null,\n\t\tactive: row.active ?? null,\n\t\tcreated_at: row.created_at ?? null,\n\t\tupdated_at: row.updated_at ?? null,\n\t\tmetadata_json: metadataJson,\n\t\tactor_id: row.actor_id ?? null,\n\t\tactor_display_name: row.actor_display_name ?? null,\n\t\tvisibility: row.visibility ?? null,\n\t\tworkspace_id: row.workspace_id ?? null,\n\t\tworkspace_kind: row.workspace_kind ?? null,\n\t\torigin_device_id: row.origin_device_id ?? null,\n\t\torigin_source: row.origin_source ?? null,\n\t\ttrust_state: row.trust_state ?? null,\n\t\tnarrative: row.narrative ?? null,\n\t\tfacts: parseSqliteJson(row.facts),\n\t\tconcepts: parseSqliteJson(row.concepts),\n\t\tfiles_read: parseSqliteJson(row.files_read),\n\t\tfiles_modified: parseSqliteJson(row.files_modified),\n\t\tuser_prompt_id: row.user_prompt_id ?? null,\n\t\tprompt_number: row.prompt_number ?? null,\n\t\tdeleted_at: row.deleted_at ?? null,\n\t\tscope_id: row.scope_id ?? null,\n\t\thas_deleted_at: row.deleted_at != null,\n\t\trev: row.rev ?? 0,\n\t\timport_key: row.import_key ?? null,\n\t\t// Denormalized project from memory_items so the outbound payload\n\t\t// carries it without a session join. Callers may still override with\n\t\t// sessions.project for legacy rows whose memory_items.project is null.\n\t\tproject: row.project ?? null,\n\t};\n}\n\n/**\n * Apply inbound replication ops from a remote peer.\n *\n * Runs all ops in a single transaction. For each op:\n * - Skips if device_id matches localDeviceId (don't re-apply own ops)\n * - Skips if op_id already exists (idempotent)\n * - For upsert: finds existing memory by import_key; if existing has a newer\n * clock, counts as conflict and skips; otherwise INSERT or UPDATE\n * - For delete: soft-deletes (active=0, deleted_at) by import_key\n * - Records the applied op in replication_ops\n */\nfunction rejectUnretiredScopeFailures(\n\tdb: Database,\n\tops: ReplicationOp[],\n\tlocalDeviceId: string,\n\toptions: InboundScopeValidationOptions,\n): ApplyResult | null {\n\tconst eligible = ops.filter((op) => !retirementBlocksMemoryOp(db, op));\n\tconst rejected = rejectInboundScopeFailures(db, eligible, localDeviceId, options);\n\tif (rejected) rejected.skipped += ops.length - eligible.length;\n\treturn rejected;\n}\n\nfunction skipOwnRetiredOrAppliedOp(\n\tdb: Database,\n\td: ReturnType<typeof drizzle>,\n\top: ReplicationOp,\n\tlocalDeviceId: string,\n): boolean {\n\tif (skipOwnOrRetiredMemoryOp(db, op, localDeviceId)) return true;\n\treturn (\n\t\td\n\t\t\t.select({ one: sql<number>`1` })\n\t\t\t.from(schema.replicationOps)\n\t\t\t.where(eq(schema.replicationOps.op_id, op.op_id))\n\t\t\t.get() !== undefined\n\t);\n}\n\nfunction rollbackReplicationOp(\n\tdb: Database,\n\tresult: ApplyResult,\n\tvectorWork: Map<number, \"upsert\" | \"delete\">,\n): void {\n\tdb.exec(\"ROLLBACK TO codemem_replication_op\");\n\tresult.applied = 0;\n\tresult.skipped = 0;\n\tresult.conflicts = 0;\n\tvectorWork.clear();\n}\n\nfunction finishReplicationOp(\n\tdb: Database,\n\tresult: ApplyResult,\n\teffects: {\n\t\tbatchResult: ApplyResult;\n\t\topVectorWork: Map<number, \"upsert\" | \"delete\">;\n\t\tupsertMemoryIds: Set<number>;\n\t\tdeleteMemoryIds: Set<number>;\n\t\tactivityPeer?: string;\n\t},\n\topId: string,\n): void {\n\trecordAppliedReceipt(db, effects.activityPeer, result.applied, opId);\n\tdb.exec(\"RELEASE codemem_replication_op\");\n\teffects.batchResult.applied += result.applied;\n\teffects.batchResult.skipped += result.skipped;\n\teffects.batchResult.conflicts += result.conflicts;\n\teffects.batchResult.errors.push(...result.errors);\n\tfor (const [memoryId, operation] of effects.opVectorWork) {\n\t\tif (operation === \"upsert\") {\n\t\t\teffects.deleteMemoryIds.delete(memoryId);\n\t\t\teffects.upsertMemoryIds.add(memoryId);\n\t\t} else {\n\t\t\teffects.upsertMemoryIds.delete(memoryId);\n\t\t\teffects.deleteMemoryIds.add(memoryId);\n\t\t}\n\t}\n}\n\nfunction recordAppliedReceipt(\n\tdb: Database,\n\tpeer: string | undefined,\n\tapplied: number,\n\topId: string,\n): void {\n\tif (peer && applied > 0) recordSyncTransferReceipts(db, peer, \"receive\", [opId]);\n}\n\nfunction applyAccessCleanupForLocalDevice(\n\tdb: Database,\n\td: ReturnType<typeof drizzle>,\n\top: ReplicationOp,\n\tcontext: {\n\t\tlocalDeviceId: string;\n\t\tqueueVectorDelete: (memoryId: number) => void;\n\t},\n): boolean {\n\tconst cleanup = parseAccessCleanupPayload(op);\n\tif (!cleanup.cleanup_scope_id) return false;\n\tconst existing = d\n\t\t.select({\n\t\t\tid: schema.memoryItems.id,\n\t\t\torigin_device_id: schema.memoryItems.origin_device_id,\n\t\t\tscope_id: schema.memoryItems.scope_id,\n\t\t})\n\t\t.from(schema.memoryItems)\n\t\t.where(eq(schema.memoryItems.import_key, op.entity_id))\n\t\t.limit(1)\n\t\t.get();\n\tif (!existing) return true;\n\tif (hasRecordedLocalCreation(db, op.entity_id)) return false;\n\tconst sourceDeviceId = cleanText(op.clock_device_id) ?? cleanText(op.device_id);\n\tconst originDeviceId = cleanText(existing.origin_device_id);\n\tif (!sourceDeviceId || !originDeviceId || originDeviceId !== sourceDeviceId) return false;\n\t// Local-looking labels preserve ambiguous data, never prove authorship.\n\tif (originDeviceId === context.localDeviceId || originDeviceId === \"local\") return false;\n\tif (cleanText(existing.scope_id) !== cleanup.cleanup_scope_id) return false;\n\tclearRefsBeforeMemoryDeletion(db, Number(existing.id));\n\td.delete(schema.memoryItems).where(eq(schema.memoryItems.id, existing.id)).run();\n\tcontext.queueVectorDelete(Number(existing.id));\n\treturn true;\n}\n\nexport function applyReplicationOps(\n\tdb: Database,\n\tops: ReplicationOp[],\n\tlocalDeviceId: string,\n\tscanner?: SecretScanner,\n\toptions: ApplyReplicationOpsOptions = {},\n): ApplyResult {\n\tconst peer = options.activityPeerDeviceId;\n\tif (!peer) return applyReplicationOpsInternal(db, ops, localDeviceId, scanner, options);\n\tensureSyncTransferActivitySchema(db);\n\ttry {\n\t\treturn db.transaction(() => {\n\t\t\tconst result = applyReplicationOpsInternal(db, ops, localDeviceId, scanner, {\n\t\t\t\t...options,\n\t\t\t\tactivityPeerDeviceId: peer,\n\t\t\t});\n\t\t\tlet errorCode: \"scope_rejected\" | \"apply_failed\" | undefined;\n\t\t\tif (result.rejected > 0) errorCode = \"scope_rejected\";\n\t\t\telse if (result.errors.length > 0) errorCode = \"apply_failed\";\n\t\t\trecordSyncTransferObservation(db, peer, \"receive\", {\n\t\t\t\t...options.activityOptions,\n\t\t\t\terrorCode,\n\t\t\t\tsource: options.activitySource,\n\t\t\t});\n\t\t\treturn result;\n\t\t})();\n\t} catch (error) {\n\t\trecordSyncTransferObservation(db, peer, \"receive\", {\n\t\t\terrorCode: \"apply_failed\",\n\t\t\tsource: options.activitySource,\n\t\t});\n\t\tthrow error;\n\t}\n}\n\nfunction applyReplicationOpsInternal(\n\tdb: Database,\n\tops: ReplicationOp[],\n\tlocalDeviceId: string,\n\tscanner: SecretScanner | undefined,\n\toptions: ApplyReplicationOpsOptions,\n): ApplyResult {\n\tconst d = drizzle(db, { schema });\n\t// Peer-shipped content goes through the same redaction policy as\n\t// locally-authored writes. Callers that maintain their own scanner\n\t// (typically a MemoryStore instance) should pass it so workspace-level\n\t// rule overrides apply uniformly. Otherwise fall back to defaults.\n\tconst activeScanner = scanner ?? new SecretScanner();\n\tconst result: ApplyResult = emptyApplyResult();\n\tconst rejected = rejectedInboundBatch(db, ops, localDeviceId, options);\n\tif (rejected) return rejected;\n\tconst upsertMemoryIds = new Set<number>();\n\tconst deleteMemoryIds = new Set<number>();\n\tconst opVectorWork = new Map<number, \"upsert\" | \"delete\">();\n\tconst queueVectorUpsert = (memoryId: number): void => {\n\t\tif (!Number.isInteger(memoryId) || memoryId <= 0) return;\n\t\topVectorWork.set(memoryId, \"upsert\");\n\t};\n\tconst queueVectorDelete = (memoryId: number): void => {\n\t\tif (!Number.isInteger(memoryId) || memoryId <= 0) return;\n\t\topVectorWork.set(memoryId, \"delete\");\n\t};\n\tconst applyAccessCleanupOp = (op: ReplicationOp): boolean =>\n\t\tapplyAccessCleanupForLocalDevice(db, d, op, { localDeviceId, queueVectorDelete });\n\n\tconst effects = {\n\t\tbatchResult: result,\n\t\topVectorWork,\n\t\tupsertMemoryIds,\n\t\tdeleteMemoryIds,\n\t\tactivityPeer: options.activityPeerDeviceId,\n\t};\n\tconst applyAll = db.transaction(() => {\n\t\tfor (const op of ops) {\n\t\t\tconst result = emptyApplyResult();\n\t\t\topVectorWork.clear();\n\t\t\t// Per-op failures must roll back content, provenance, refs, and op acknowledgement together.\n\t\t\tdb.exec(\"SAVEPOINT codemem_replication_op\");\n\t\t\ttry {\n\t\t\t\t// Skip own, retired, and already-applied ops.\n\t\t\t\tif (skipOwnRetiredOrAppliedOp(db, d, op, localDeviceId)) {\n\t\t\t\t\tresult.skipped++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst reassignment =\n\t\t\t\t\top.op_type === REASSIGN_SCOPE_OP_TYPE ? parseReassignScopePayload(op) : null;\n\t\t\t\tif (reassignment?.side === \"old\") {\n\t\t\t\t\tconst current = d\n\t\t\t\t\t\t.select({\n\t\t\t\t\t\t\tid: schema.memoryItems.id,\n\t\t\t\t\t\t\torigin_device_id: schema.memoryItems.origin_device_id,\n\t\t\t\t\t\t\trev: schema.memoryItems.rev,\n\t\t\t\t\t\t\tupdated_at: schema.memoryItems.updated_at,\n\t\t\t\t\t\t\tmetadata_json: schema.memoryItems.metadata_json,\n\t\t\t\t\t\t\tscope_id: schema.memoryItems.scope_id,\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.from(schema.memoryItems)\n\t\t\t\t\t\t.where(eq(schema.memoryItems.import_key, op.entity_id))\n\t\t\t\t\t\t.get();\n\t\t\t\t\tif (\n\t\t\t\t\t\t!current ||\n\t\t\t\t\t\t(cleanText(current.scope_id) ?? DEFAULT_SYNC_SCOPE_ID) !== reassignment.old_scope_id\n\t\t\t\t\t) {\n\t\t\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\t\t\tresult.skipped++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (reassignment.old_scope_id === DEFAULT_SYNC_SCOPE_ID) {\n\t\t\t\t\t\tconst senderDeviceId = cleanText(op.clock_device_id);\n\t\t\t\t\t\tconst originDeviceId = cleanText(current.origin_device_id);\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!senderDeviceId ||\n\t\t\t\t\t\t\tcleanText(op.device_id) !== senderDeviceId ||\n\t\t\t\t\t\t\t!originDeviceId ||\n\t\t\t\t\t\t\toriginDeviceId !== senderDeviceId ||\n\t\t\t\t\t\t\toriginDeviceId === localDeviceId\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthrow new Error(\"reassign_origin_mismatch\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst currentClock = clockTuple(\n\t\t\t\t\t\tcurrent.rev ?? 0,\n\t\t\t\t\t\tcurrent.updated_at ?? \"\",\n\t\t\t\t\t\tclockDeviceIdFromMetadataJson(current.metadata_json),\n\t\t\t\t\t);\n\t\t\t\t\tconst incomingClock = clockTuple(op.clock_rev, op.clock_updated_at, op.clock_device_id);\n\t\t\t\t\tif (!isNewerClock(incomingClock, currentClock)) {\n\t\t\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\t\t\tresult.conflicts++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst metadata = foreignRevisionMetadata(db, op, current.metadata_json);\n\t\t\t\t\tmetadata.last_scope_reassignment = reassignment;\n\t\t\t\t\td.update(schema.memoryItems)\n\t\t\t\t\t\t.set({\n\t\t\t\t\t\t\tactive: 0,\n\t\t\t\t\t\t\tdeleted_at: op.clock_updated_at,\n\t\t\t\t\t\t\trev: op.clock_rev,\n\t\t\t\t\t\t\tupdated_at: op.clock_updated_at,\n\t\t\t\t\t\t\tmetadata_json: toJson(metadata),\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.where(eq(schema.memoryItems.id, current.id))\n\t\t\t\t\t\t.run();\n\t\t\t\t\tqueueVectorDelete(Number(current.id));\n\t\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\t\tresult.applied++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (op.op_type === ACCESS_CLEANUP_OP_TYPE) {\n\t\t\t\t\tconst cleaned = applyAccessCleanupOp(op);\n\t\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\t\tif (cleaned) result.applied++;\n\t\t\t\t\telse result.skipped++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (op.op_type === \"upsert\" || reassignment?.side === \"new\") {\n\t\t\t\t\tconst importKey = op.entity_id;\n\t\t\t\t\tconst opScopeId =\n\t\t\t\t\t\ttypeof op.scope_id === \"string\" && op.scope_id.trim().length > 0\n\t\t\t\t\t\t\t? op.scope_id.trim()\n\t\t\t\t\t\t\t: null;\n\t\t\t\t\tconst memRow = d\n\t\t\t\t\t\t.select({\n\t\t\t\t\t\t\tid: schema.memoryItems.id,\n\t\t\t\t\t\t\trev: schema.memoryItems.rev,\n\t\t\t\t\t\t\tupdated_at: schema.memoryItems.updated_at,\n\t\t\t\t\t\t\ttitle: schema.memoryItems.title,\n\t\t\t\t\t\t\tbody_text: schema.memoryItems.body_text,\n\t\t\t\t\t\t\tactive: schema.memoryItems.active,\n\t\t\t\t\t\t\tdeleted_at: schema.memoryItems.deleted_at,\n\t\t\t\t\t\t\tmetadata_json: schema.memoryItems.metadata_json,\n\t\t\t\t\t\t\tscope_id: schema.memoryItems.scope_id,\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.from(schema.memoryItems)\n\t\t\t\t\t\t.where(eq(schema.memoryItems.import_key, importKey))\n\t\t\t\t\t\t.get();\n\n\t\t\t\t\tif (memRow) {\n\t\t\t\t\t\tconst existingClockDeviceId = clockDeviceIdFromMetadataJson(memRow.metadata_json);\n\t\t\t\t\t\tconst existingClock = clockTuple(\n\t\t\t\t\t\t\tmemRow.rev ?? 0,\n\t\t\t\t\t\t\tmemRow.updated_at ?? \"\",\n\t\t\t\t\t\t\texistingClockDeviceId,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst opClock = clockTuple(op.clock_rev, op.clock_updated_at, op.clock_device_id);\n\n\t\t\t\t\t\tconst sameReassignmentClock =\n\t\t\t\t\t\t\treassignment?.side === \"new\" &&\n\t\t\t\t\t\t\topClock[0] === existingClock[0] &&\n\t\t\t\t\t\t\topClock[1] === existingClock[1] &&\n\t\t\t\t\t\t\topClock[2] === existingClock[2] &&\n\t\t\t\t\t\t\t(cleanText(memRow.scope_id) ?? DEFAULT_SYNC_SCOPE_ID) === reassignment.old_scope_id;\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\treassignment &&\n\t\t\t\t\t\t\t![reassignment.old_scope_id, reassignment.new_scope_id].includes(\n\t\t\t\t\t\t\t\tcleanText(memRow.scope_id) ?? DEFAULT_SYNC_SCOPE_ID,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthrow new Error(\"reassign_existing_scope_mismatch\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!isNewerClock(opClock, existingClock) && !sameReassignmentClock) {\n\t\t\t\t\t\t\tresult.conflicts++;\n\t\t\t\t\t\t\t// Still record the op so we don't re-process it\n\t\t\t\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Update existing row from payload — skip if malformed\n\t\t\t\t\t\tconst payload = parseMemoryPayload(op, result.errors);\n\t\t\t\t\t\tif (!payload) {\n\t\t\t\t\t\t\t// A malformed payload can never be applied. Record the op so\n\t\t\t\t\t\t\t// it is acknowledged exactly once (not re-parsed and re-errored\n\t\t\t\t\t\t\t// every pass) and the inbound cursor can eventually advance\n\t\t\t\t\t\t\t// past it instead of stalling forever.\n\t\t\t\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\t\t\t\tresult.skipped++;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tredactMemoryFields(payload, activeScanner);\n\t\t\t\t\t\tconst metaObj = foreignRevisionMetadata(db, op, payload.metadata_json);\n\t\t\t\t\t\tconst nextTitle = resolveReplicatedTextUpdate(payload.title, memRow.title);\n\t\t\t\t\t\tconst nextBodyText = resolveReplicatedTextUpdate(payload.body_text, memRow.body_text);\n\t\t\t\t\t\tconst contentChanged =\n\t\t\t\t\t\t\tnextTitle !== (memRow.title ?? \"\") || nextBodyText !== (memRow.body_text ?? \"\");\n\t\t\t\t\t\tconst wasInactive = Number(memRow.active ?? 1) === 0 || memRow.deleted_at != null;\n\t\t\t\t\t\tconst nextActive =\n\t\t\t\t\t\t\tpayload.active != null ? Number(payload.active) : Number(memRow.active ?? 1);\n\t\t\t\t\t\tconst nextDeletedAt = payload.has_deleted_at\n\t\t\t\t\t\t\t? payload.deleted_at\n\t\t\t\t\t\t\t: (memRow.deleted_at ?? null);\n\t\t\t\t\t\tconst becomesActive = nextActive !== 0 && nextDeletedAt == null;\n\t\t\t\t\t\t// Keep `active` consistent with the tombstone: when the row stays\n\t\t\t\t\t\t// (or becomes) tombstoned, force active=0 so a field-omitting\n\t\t\t\t\t\t// upsert that carries active=1 cannot resurrect a deleted memory\n\t\t\t\t\t\t// (read paths filter on active=1).\n\t\t\t\t\t\tconst writtenActive = nextDeletedAt != null ? 0 : nextActive;\n\t\t\t\t\t\t// Base the vector decision on the FINAL persisted state, not the\n\t\t\t\t\t\t// raw payload: a row that stays (or becomes) tombstoned — active=0\n\t\t\t\t\t\t// or deleted_at set — must have its embeddings removed, not\n\t\t\t\t\t\t// re-upserted (the vector queue lets an upsert cancel a pending\n\t\t\t\t\t\t// delete, which would leave a deleted memory searchable).\n\t\t\t\t\t\tconst shouldDeleteVectors = nextDeletedAt != null || writtenActive === 0;\n\t\t\t\t\t\tconst shouldQueueVectorUpsert =\n\t\t\t\t\t\t\t!shouldDeleteVectors && (contentChanged || (wasInactive && becomesActive));\n\n\t\t\t\t\t\td.update(schema.memoryItems)\n\t\t\t\t\t\t\t.set({\n\t\t\t\t\t\t\t\tkind: sql`COALESCE(${payload.kind}, ${schema.memoryItems.kind})`,\n\t\t\t\t\t\t\t\ttitle: sql`COALESCE(${payload.title}, ${schema.memoryItems.title})`,\n\t\t\t\t\t\t\t\tsubtitle: payload.subtitle,\n\t\t\t\t\t\t\t\tbody_text: sql`COALESCE(${payload.body_text}, ${schema.memoryItems.body_text})`,\n\t\t\t\t\t\t\t\tconfidence: sql`COALESCE(${payload.confidence != null ? Number(payload.confidence) : null}, ${schema.memoryItems.confidence})`,\n\t\t\t\t\t\t\t\ttags_text: sql`COALESCE(NULLIF(TRIM(${payload.tags_text}), ''), ${schema.memoryItems.tags_text})`,\n\t\t\t\t\t\t\t\tactive: writtenActive,\n\t\t\t\t\t\t\t\tupdated_at: op.clock_updated_at,\n\t\t\t\t\t\t\t\tmetadata_json: toJson(metaObj),\n\t\t\t\t\t\t\t\trev: op.clock_rev,\n\t\t\t\t\t\t\t\t// Honor the wire intent flag: only clear/set the tombstone\n\t\t\t\t\t\t\t\t// when the payload actually carried `deleted_at`; otherwise\n\t\t\t\t\t\t\t\t// preserve the existing value (nextDeletedAt). Guards against\n\t\t\t\t\t\t\t\t// a field-omitting upsert resurrecting a tombstoned row.\n\t\t\t\t\t\t\t\tdeleted_at: nextDeletedAt,\n\t\t\t\t\t\t\t\tactor_id: sql`COALESCE(${payload.actor_id}, ${schema.memoryItems.actor_id})`,\n\t\t\t\t\t\t\t\tactor_display_name: sql`COALESCE(${payload.actor_display_name}, ${schema.memoryItems.actor_display_name})`,\n\t\t\t\t\t\t\t\tvisibility: sql`COALESCE(${payload.visibility}, ${schema.memoryItems.visibility})`,\n\t\t\t\t\t\t\t\tworkspace_id: sql`COALESCE(${payload.workspace_id}, ${schema.memoryItems.workspace_id})`,\n\t\t\t\t\t\t\t\tworkspace_kind: sql`COALESCE(${payload.workspace_kind}, ${schema.memoryItems.workspace_kind})`,\n\t\t\t\t\t\t\t\torigin_device_id: sql`COALESCE(${payload.origin_device_id}, ${schema.memoryItems.origin_device_id})`,\n\t\t\t\t\t\t\t\torigin_source: sql`COALESCE(${payload.origin_source}, ${schema.memoryItems.origin_source})`,\n\t\t\t\t\t\t\t\ttrust_state: sql`COALESCE(${payload.trust_state}, ${schema.memoryItems.trust_state})`,\n\t\t\t\t\t\t\t\tnarrative: payload.narrative,\n\t\t\t\t\t\t\t\tfacts: toJsonNullable(payload.facts),\n\t\t\t\t\t\t\t\tconcepts: toJsonNullable(payload.concepts),\n\t\t\t\t\t\t\t\tfiles_read: toJsonNullable(payload.files_read),\n\t\t\t\t\t\t\t\tfiles_modified: toJsonNullable(payload.files_modified),\n\t\t\t\t\t\t\t\tuser_prompt_id: payload.user_prompt_id,\n\t\t\t\t\t\t\t\tprompt_number: payload.prompt_number,\n\t\t\t\t\t\t\t\tscope_id: sql`COALESCE(${opScopeId}, ${schema.memoryItems.scope_id})`,\n\t\t\t\t\t\t\t\t// Backfill project on existing rows when the inbound\n\t\t\t\t\t\t\t\t// payload carries it; preserve the existing value when\n\t\t\t\t\t\t\t\t// the sender (older code) omitted the field.\n\t\t\t\t\t\t\t\tproject: sql`COALESCE(${typeof payload.project === \"string\" && payload.project.trim() ? payload.project.trim() : null}, ${schema.memoryItems.project})`,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.where(eq(schema.memoryItems.import_key, importKey))\n\t\t\t\t\t\t\t.run();\n\t\t\t\t\t\t// Re-populate junction tables with updated file/concept refs\n\t\t\t\t\t\tclearMemoryRefs(db, Number(memRow.id));\n\t\t\t\t\t\tpopulateMemoryRefs(\n\t\t\t\t\t\t\tdb,\n\t\t\t\t\t\t\tNumber(memRow.id),\n\t\t\t\t\t\t\tasStringArrayOrNull(payload.files_read),\n\t\t\t\t\t\t\tasStringArrayOrNull(payload.files_modified),\n\t\t\t\t\t\t\tasStringArrayOrNull(payload.concepts),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (shouldDeleteVectors) queueVectorDelete(Number(memRow.id));\n\t\t\t\t\t\telse if (shouldQueueVectorUpsert) queueVectorUpsert(Number(memRow.id));\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Insert new memory item — skip if malformed\n\t\t\t\t\t\tconst payload = parseMemoryPayload(op, result.errors);\n\t\t\t\t\t\tif (!payload) {\n\t\t\t\t\t\t\t// See the update branch: record malformed ops so they are\n\t\t\t\t\t\t\t// acknowledged once and never block inbound cursor progress.\n\t\t\t\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\t\t\t\tresult.skipped++;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tredactMemoryFields(payload, activeScanner);\n\t\t\t\t\t\tconst replicatedProject =\n\t\t\t\t\t\t\ttypeof payload.project === \"string\" && payload.project.trim()\n\t\t\t\t\t\t\t\t? payload.project.trim()\n\t\t\t\t\t\t\t\t: null;\n\t\t\t\t\t\tconst sessionId = ensureSessionForReplication(\n\t\t\t\t\t\t\td,\n\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\top.clock_updated_at,\n\t\t\t\t\t\t\treplicatedProject,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst metaObj = foreignRevisionMetadata(db, op, payload.metadata_json);\n\t\t\t\t\t\tconst insertedRows = d\n\t\t\t\t\t\t\t.insert(schema.memoryItems)\n\t\t\t\t\t\t\t.values({\n\t\t\t\t\t\t\t\tsession_id: sessionId,\n\t\t\t\t\t\t\t\tkind: payload.kind ?? \"discovery\",\n\t\t\t\t\t\t\t\ttitle: payload.title ?? \"\",\n\t\t\t\t\t\t\t\tsubtitle: payload.subtitle,\n\t\t\t\t\t\t\t\tbody_text: payload.body_text ?? \"\",\n\t\t\t\t\t\t\t\tconfidence: payload.confidence != null ? Number(payload.confidence) : 0.5,\n\t\t\t\t\t\t\t\ttags_text: resolveReplicatedTags(payload),\n\t\t\t\t\t\t\t\tactive: payload.active != null ? Number(payload.active) : 1,\n\t\t\t\t\t\t\t\tcreated_at: payload.created_at ?? op.clock_updated_at,\n\t\t\t\t\t\t\t\tupdated_at: op.clock_updated_at,\n\t\t\t\t\t\t\t\tmetadata_json: toJson(metaObj),\n\t\t\t\t\t\t\t\timport_key: importKey,\n\t\t\t\t\t\t\t\tdeleted_at: payload.deleted_at,\n\t\t\t\t\t\t\t\trev: op.clock_rev,\n\t\t\t\t\t\t\t\tactor_id: payload.actor_id,\n\t\t\t\t\t\t\t\tactor_display_name: payload.actor_display_name,\n\t\t\t\t\t\t\t\tvisibility: payload.visibility,\n\t\t\t\t\t\t\t\tworkspace_id: payload.workspace_id,\n\t\t\t\t\t\t\t\tworkspace_kind: payload.workspace_kind,\n\t\t\t\t\t\t\t\torigin_device_id: payload.origin_device_id,\n\t\t\t\t\t\t\t\torigin_source: payload.origin_source,\n\t\t\t\t\t\t\t\ttrust_state: payload.trust_state,\n\t\t\t\t\t\t\t\tnarrative: payload.narrative,\n\t\t\t\t\t\t\t\tfacts: toJsonNullable(payload.facts),\n\t\t\t\t\t\t\t\tconcepts: toJsonNullable(payload.concepts),\n\t\t\t\t\t\t\t\tfiles_read: toJsonNullable(payload.files_read),\n\t\t\t\t\t\t\t\tfiles_modified: toJsonNullable(payload.files_modified),\n\t\t\t\t\t\t\t\tuser_prompt_id: payload.user_prompt_id,\n\t\t\t\t\t\t\t\tprompt_number: payload.prompt_number,\n\t\t\t\t\t\t\t\tscope_id: opScopeId,\n\t\t\t\t\t\t\t\t// Persist replicated project name so the Projects read\n\t\t\t\t\t\t\t\t// model can surface this memory under its originating\n\t\t\t\t\t\t\t\t// project identity without joining through sessions.\n\t\t\t\t\t\t\t\tproject: replicatedProject,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.returning({ id: schema.memoryItems.id })\n\t\t\t\t\t\t\t.all();\n\t\t\t\t\t\tconst insertedId = Number(insertedRows[0]?.id ?? 0);\n\t\t\t\t\t\t// Populate junction tables for the new memory\n\t\t\t\t\t\tpopulateMemoryRefs(\n\t\t\t\t\t\t\tdb,\n\t\t\t\t\t\t\tinsertedId,\n\t\t\t\t\t\t\tasStringArrayOrNull(payload.files_read),\n\t\t\t\t\t\t\tasStringArrayOrNull(payload.files_modified),\n\t\t\t\t\t\t\tasStringArrayOrNull(payload.concepts),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (payload.deleted_at != null || Number(payload.active ?? 1) === 0) {\n\t\t\t\t\t\t\tqueueVectorDelete(insertedId);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tqueueVectorUpsert(insertedId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (op.op_type === \"delete\") {\n\t\t\t\t\tconst importKey = op.entity_id;\n\t\t\t\t\tconst opScopeId =\n\t\t\t\t\t\ttypeof op.scope_id === \"string\" && op.scope_id.trim().length > 0\n\t\t\t\t\t\t\t? op.scope_id.trim()\n\t\t\t\t\t\t\t: null;\n\t\t\t\t\tconst existingForDelete = d\n\t\t\t\t\t\t.select({\n\t\t\t\t\t\t\tid: schema.memoryItems.id,\n\t\t\t\t\t\t\trev: schema.memoryItems.rev,\n\t\t\t\t\t\t\tupdated_at: schema.memoryItems.updated_at,\n\t\t\t\t\t\t\tmetadata_json: schema.memoryItems.metadata_json,\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.from(schema.memoryItems)\n\t\t\t\t\t\t.where(eq(schema.memoryItems.import_key, importKey))\n\t\t\t\t\t\t.limit(1)\n\t\t\t\t\t\t.get();\n\n\t\t\t\t\tif (existingForDelete) {\n\t\t\t\t\t\t// Clock-compare: only delete if the incoming op is newer\n\t\t\t\t\t\tconst existingClock = clockTuple(\n\t\t\t\t\t\t\t// Match the upsert path's `rev ?? 0` so Lamport tie-breaks are\n\t\t\t\t\t\t\t// symmetric when an existing row has a NULL rev.\n\t\t\t\t\t\t\texistingForDelete.rev ?? 0,\n\t\t\t\t\t\t\texistingForDelete.updated_at ?? \"\",\n\t\t\t\t\t\t\tclockDeviceIdFromMetadataJson(existingForDelete.metadata_json),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst incomingClock = clockTuple(op.clock_rev, op.clock_updated_at, op.clock_device_id);\n\t\t\t\t\t\tif (!isNewerClock(incomingClock, existingClock)) {\n\t\t\t\t\t\t\tresult.conflicts++;\n\t\t\t\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst now = new Date().toISOString();\n\t\t\t\t\t\tconst deleteMetadata = foreignRevisionMetadata(db, op, existingForDelete.metadata_json);\n\t\t\t\t\t\td.update(schema.memoryItems)\n\t\t\t\t\t\t\t.set({\n\t\t\t\t\t\t\t\tactive: 0,\n\t\t\t\t\t\t\t\tdeleted_at: sql`COALESCE(${schema.memoryItems.deleted_at}, ${now})`,\n\t\t\t\t\t\t\t\trev: op.clock_rev,\n\t\t\t\t\t\t\t\tupdated_at: op.clock_updated_at,\n\t\t\t\t\t\t\t\tmetadata_json: toJson(deleteMetadata),\n\t\t\t\t\t\t\t\tscope_id: sql`COALESCE(${opScopeId}, ${schema.memoryItems.scope_id})`,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.where(eq(schema.memoryItems.id, existingForDelete.id))\n\t\t\t\t\t\t\t.run();\n\t\t\t\t\t\tqueueVectorDelete(Number(existingForDelete.id));\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// import_key not found: record the delete as a tombstone for\n\t\t\t\t\t\t// future resolution, but it mutated nothing — count it as\n\t\t\t\t\t\t// skipped rather than applied.\n\t\t\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\t\t\tresult.skipped++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tresult.skipped++;\n\t\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Record the applied op\n\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\tresult.applied++;\n\t\t\t} catch (err) {\n\t\t\t\trollbackReplicationOp(db, result, opVectorWork);\n\t\t\t\tresult.errors.push(`op ${op.op_id}: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\t} finally {\n\t\t\t\tfinishReplicationOp(db, result, effects, op.op_id);\n\t\t\t}\n\t\t}\n\t});\n\n\treturn completeAppliedReplicationOps(applyAll, result, upsertMemoryIds, deleteMemoryIds);\n}\n\nfunction completeAppliedReplicationOps(\n\tapplyAll: () => void,\n\tresult: ApplyResult,\n\tupsertMemoryIds: Set<number>,\n\tdeleteMemoryIds: Set<number>,\n): ApplyResult {\n\tapplyAll();\n\tresult.vectorWork = {\n\t\tupsertMemoryIds: [...upsertMemoryIds],\n\t\tdeleteMemoryIds: [...deleteMemoryIds],\n\t};\n\treturn result;\n}\n\nfunction rejectedInboundBatch(\n\tdb: Database,\n\tops: ReplicationOp[],\n\tlocalDeviceId: string,\n\toptions: ApplyReplicationOpsOptions,\n): ApplyResult | null {\n\tif (!options.inboundScopeValidation) return null;\n\treturn rejectUnretiredScopeFailures(db, ops, localDeviceId, options.inboundScopeValidation);\n}\n\n/** Apply authenticated inbound operations using the caller's scanner and scope policy. */\nexport function applyPeerReplicationOps(\n\tstore: { db: Database; scanner: SecretScanner },\n\tops: ReplicationOp[],\n\tlocalDeviceId: string,\n\toptions: ApplyReplicationOpsOptions & { peerDeviceId: string },\n): ApplyResult {\n\treturn applyReplicationOps(store.db, ops, localDeviceId, store.scanner, {\n\t\t...options,\n\t\tactivityPeerDeviceId: options.peerDeviceId,\n\t\tactivitySource: \"inbound\",\n\t});\n}\n\n/** Insert a replication op row into the replication_ops table (ignore on conflict). */\nfunction insertReplicationOpRow(d: ReturnType<typeof drizzle>, op: ReplicationOp): void {\n\td.insert(schema.replicationOps)\n\t\t.values({\n\t\t\top_id: op.op_id,\n\t\t\tentity_type: op.entity_type,\n\t\t\tentity_id: op.entity_id,\n\t\t\top_type: op.op_type,\n\t\t\tpayload_json: op.payload_json,\n\t\t\tclock_rev: op.clock_rev,\n\t\t\tclock_updated_at: op.clock_updated_at,\n\t\t\tclock_device_id: op.clock_device_id,\n\t\t\tdevice_id: op.device_id,\n\t\t\tcreated_at: op.created_at,\n\t\t\tscope_id: op.scope_id ?? null,\n\t\t})\n\t\t.onConflictDoNothing()\n\t\t.run();\n}\n\n/**\n * Ensure a session row exists for replication inserts.\n * Creates a minimal session if one doesn't exist yet.\n */\nfunction ensureSessionForReplication(\n\td: ReturnType<typeof drizzle>,\n\tsessionId: number | null,\n\tcreatedAt: string,\n\tproject?: string | null,\n): number {\n\tif (sessionId != null) {\n\t\tconst row = d\n\t\t\t.select({ id: schema.sessions.id })\n\t\t\t.from(schema.sessions)\n\t\t\t.where(eq(schema.sessions.id, sessionId))\n\t\t\t.get();\n\t\tif (row) return sessionId;\n\t}\n\t// Create a new session for replicated data, preserving the source project.\n\tconst now = createdAt || new Date().toISOString();\n\tconst rows = d\n\t\t.insert(schema.sessions)\n\t\t.values({\n\t\t\tstarted_at: now,\n\t\t\tproject: project ?? null,\n\t\t\tuser: \"sync\",\n\t\t\ttool_version: \"sync_replication\",\n\t\t\tmetadata_json: toJson({ source: \"sync\" }),\n\t\t})\n\t\t.returning({ id: schema.sessions.id })\n\t\t.all();\n\tconst id = rows[0]?.id;\n\tif (id == null) throw new Error(\"session insert returned no id\");\n\treturn id;\n}\n","import type { Database } from \"./db.js\";\nimport {\n\tgetMaintenanceJob,\n\ttype MaintenanceJobSnapshot,\n\ttype StartMaintenanceJobInput,\n\tstartMaintenanceJob,\n\tupdateMaintenanceJob,\n} from \"./maintenance-jobs.js\";\n\nexport const VECTOR_MODEL_MIGRATION_JOB = \"vector_model_migration\";\nexport const SYNC_INCREMENTAL_TRIGGER = \"sync_incremental\";\n\nexport class VectorMigrationJobGenerationError extends RangeError {}\n\nexport interface VectorBackfillWork {\n\tupsertMemoryIds: readonly number[];\n\tdeleteMemoryIds: readonly number[];\n}\n\nexport type VectorBackfillQueueMetadata = {\n\ttarget_model?: string | null;\n\trequested_model?: string | null;\n\trequested_revision?: string | null;\n\tremoved_stale_rows?: number;\n\tcleanup_pending?: boolean;\n\ttrigger?: string | null;\n\tpending_upsert_memory_ids?: number[];\n\tpending_delete_memory_ids?: number[];\n\tqueue_revision?: number;\n\tjob_generation?: number;\n\t/** Local repair may drain queued IDs without resuming a cancelled migration. */\n\tlocal_repair_preserves_migration_state?: boolean;\n};\n\n/** Replacement identity is allocated with the write, including inside an outer transaction. */\nexport function startVectorMigrationJob(\n\tdb: Database,\n\tinput: Omit<StartMaintenanceJobInput, \"kind\">,\n): MaintenanceJobSnapshot {\n\treturn db\n\t\t.transaction(() => {\n\t\t\tconst existingJob = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\t\tconst storedGeneration = existingJob?.metadata?.job_generation;\n\t\t\tconst generation = storedGeneration === undefined ? 0 : storedGeneration;\n\t\t\tif (\n\t\t\t\ttypeof generation !== \"number\" ||\n\t\t\t\t!Number.isSafeInteger(generation) ||\n\t\t\t\tgeneration < 0 ||\n\t\t\t\tgeneration === Number.MAX_SAFE_INTEGER\n\t\t\t) {\n\t\t\t\tthrow new VectorMigrationJobGenerationError(\n\t\t\t\t\t\"Vector migration job generation is invalid or exhausted\",\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn startMaintenanceJob(db, {\n\t\t\t\t...input,\n\t\t\t\tkind: VECTOR_MODEL_MIGRATION_JOB,\n\t\t\t\tmetadata: { ...input.metadata, job_generation: generation + 1 },\n\t\t\t});\n\t\t})\n\t\t.immediate();\n}\n\nfunction uniquePositiveIds(memoryIds: readonly number[]): number[] {\n\treturn [\n\t\t...new Set(memoryIds.filter((memoryId) => Number.isInteger(memoryId) && memoryId > 0)),\n\t].sort((a, b) => a - b);\n}\n\nexport function metadataMemoryIds(value: unknown): number[] {\n\tif (!Array.isArray(value)) return [];\n\treturn uniquePositiveIds(value.filter((item): item is number => typeof item === \"number\"));\n}\n\nexport function mergeQueuedSyncMemoryIds(\n\tmetadata: VectorBackfillQueueMetadata,\n\twork: VectorBackfillWork,\n): Pick<VectorBackfillQueueMetadata, \"pending_upsert_memory_ids\" | \"pending_delete_memory_ids\"> {\n\tconst pendingUpsertMemoryIds = new Set(metadataMemoryIds(metadata.pending_upsert_memory_ids));\n\tconst pendingDeleteMemoryIds = new Set(metadataMemoryIds(metadata.pending_delete_memory_ids));\n\n\tfor (const memoryId of uniquePositiveIds(work.deleteMemoryIds)) {\n\t\tpendingUpsertMemoryIds.delete(memoryId);\n\t\tpendingDeleteMemoryIds.add(memoryId);\n\t}\n\tfor (const memoryId of uniquePositiveIds(work.upsertMemoryIds)) {\n\t\tpendingDeleteMemoryIds.delete(memoryId);\n\t\tpendingUpsertMemoryIds.add(memoryId);\n\t}\n\n\treturn {\n\t\tpending_upsert_memory_ids: [...pendingUpsertMemoryIds],\n\t\tpending_delete_memory_ids: [...pendingDeleteMemoryIds],\n\t};\n}\n\nfunction retainedQueueMetadata(\n\tjob: MaintenanceJobSnapshot | null,\n\toptions: { resumeMigration?: boolean },\n): VectorBackfillQueueMetadata {\n\tconst metadata = (job?.metadata ?? {}) as VectorBackfillQueueMetadata;\n\tif (job?.status === \"cancelled\" && !options.resumeMigration) {\n\t\treturn metadata;\n\t}\n\tif (job && job.status !== \"completed\" && job.status !== \"cancelled\") return metadata;\n\tconst cleanupMetadata: VectorBackfillQueueMetadata = metadata.cleanup_pending\n\t\t? {\n\t\t\t\tcleanup_pending: true,\n\t\t\t\ttarget_model: metadata.target_model,\n\t\t\t\trequested_model: metadata.requested_model,\n\t\t\t\trequested_revision: metadata.requested_revision,\n\t\t\t\tremoved_stale_rows: metadata.removed_stale_rows,\n\t\t\t\tqueue_revision: metadata.queue_revision,\n\t\t\t}\n\t\t: {};\n\tif (job?.status === \"cancelled\" && metadata.local_repair_preserves_migration_state) {\n\t\t// Explicit sync starts fresh, but repair IDs accumulated during cancellation must survive.\n\t\treturn {\n\t\t\t...cleanupMetadata,\n\t\t\tpending_upsert_memory_ids: metadata.pending_upsert_memory_ids,\n\t\t\tpending_delete_memory_ids: metadata.pending_delete_memory_ids,\n\t\t\tqueue_revision: metadata.queue_revision,\n\t\t};\n\t}\n\treturn cleanupMetadata;\n}\n\n/** Persist intent on this connection; nested calls commit only with the outer transaction. */\nexport function queueVectorBackfill(\n\tdb: Database,\n\twork: VectorBackfillWork,\n\toptions: { resumeMigration?: boolean } = {},\n): void {\n\tconst queuedWork = mergeQueuedSyncMemoryIds({}, work);\n\tif (\n\t\t(queuedWork.pending_upsert_memory_ids?.length ?? 0) === 0 &&\n\t\t(queuedWork.pending_delete_memory_ids?.length ?? 0) === 0\n\t) {\n\t\treturn;\n\t}\n\n\tdb.transaction(() => {\n\t\tconst existingJob = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\tconst existingMetadata = retainedQueueMetadata(existingJob, options);\n\t\tconst metadata: VectorBackfillQueueMetadata = {\n\t\t\t...existingMetadata,\n\t\t\t...mergeQueuedSyncMemoryIds(existingMetadata, work),\n\t\t\tqueue_revision: Number(existingMetadata.queue_revision ?? 0) + 1,\n\t\t};\n\t\tif (\n\t\t\t!options.resumeMigration &&\n\t\t\t(existingJob?.status === \"failed\" || existingJob?.status === \"cancelled\")\n\t\t) {\n\t\t\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\t\tmetadata: {\n\t\t\t\t\t...metadata,\n\t\t\t\t\tlocal_repair_preserves_migration_state: existingJob.status === \"cancelled\" || undefined,\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\t// The worker uses this trigger to drain queued IDs before migration cutover.\n\t\tmetadata.trigger = existingMetadata.trigger ?? SYNC_INCREMENTAL_TRIGGER;\n\t\tmetadata.local_repair_preserves_migration_state = undefined;\n\t\tconst message = options.resumeMigration\n\t\t\t? \"Queued vector catch-up for incremental sync data\"\n\t\t\t: \"Queued vector catch-up for memories\";\n\t\tconst pendingWorkCount =\n\t\t\tmetadataMemoryIds(metadata.pending_upsert_memory_ids).length +\n\t\t\tmetadataMemoryIds(metadata.pending_delete_memory_ids).length;\n\n\t\tif (!existingJob || existingJob.status === \"completed\" || existingJob.status === \"cancelled\") {\n\t\t\tstartVectorMigrationJob(db, {\n\t\t\t\ttitle: \"Re-indexing memories\",\n\t\t\t\tstatus: \"pending\",\n\t\t\t\tmessage,\n\t\t\t\tprogressTotal: null,\n\t\t\t\tmetadata,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\tstatus: \"pending\",\n\t\t\tmessage,\n\t\t\tprogressCurrent:\n\t\t\t\texistingJob.status === \"failed\"\n\t\t\t\t\t? 0\n\t\t\t\t\t: Math.min(existingJob.progress.current, pendingWorkCount),\n\t\t\tprogressTotal: existingJob.progress.total,\n\t\t\tmetadata,\n\t\t});\n\t}).immediate();\n}\n","import type { Database } from \"better-sqlite3\";\nimport { readVectorCorpusFence, type VectorCorpusFence } from \"./vector-corpus-epoch.js\";\nimport { createVectorMetadataSnapshot } from \"./vector-metadata-snapshot.js\";\nimport {\n\tcountIncompleteActiveMemoryVectorCoverage,\n\tpruneObsoleteTargetVectorsFromCatalog,\n} from \"./vectors.js\";\n\ntype MutationFence = VectorCorpusFence & { dataVersion: number; totalChanges: number };\n\nfunction readFence(db: Database, phase: string): MutationFence {\n\treturn {\n\t\t...readVectorCorpusFence(db),\n\t\tdataVersion: Number(db.pragma(\"data_version\", { simple: true })),\n\t\ttotalChanges: Number(\n\t\t\tdb.prepare(`/* vector-cutover-${phase} */ SELECT total_changes()`).pluck().get(),\n\t\t),\n\t};\n}\n\ntype MetadataRow = {\n\trowid: number;\n\tmemory_id: number | null;\n\tmodel: string | null;\n\tcontent_hash: string | null;\n};\n\nfunction hasExactNumericIds(row: MetadataRow): boolean {\n\treturn (\n\t\tNumber.isSafeInteger(row.rowid) &&\n\t\t(row.memory_id === null || Number.isSafeInteger(row.memory_id))\n\t);\n}\n\nfunction compareCatalog(\n\tdb: Database,\n\tmetadata: Database,\n\tmodel: string,\n\texpectedCount: number,\n): string | null {\n\tconst deadline = performance.now() + 2000;\n\tconst find = metadata.prepare(\n\t\t\"SELECT memory_id, model, content_hash FROM vector_metadata WHERE rowid = ?\",\n\t);\n\tconst current = db\n\t\t.prepare(\n\t\t\t\"SELECT rowid, memory_id, model, content_hash FROM memory_vectors /* vector-cutover-exact-metadata */\",\n\t\t)\n\t\t.safeIntegers();\n\tlet count = 0;\n\tfor (const raw of current.iterate() as Iterable<\n\t\tOmit<MetadataRow, \"rowid\" | \"memory_id\"> & { rowid: bigint; memory_id: bigint | null }\n\t>) {\n\t\tif (performance.now() > deadline)\n\t\t\treturn \"Target metadata comparison exceeded 2 seconds; retrying\";\n\t\t// Read every row so a native step cannot spend the whole budget skipping\n\t\t// a long run of non-target rows before control returns to JavaScript.\n\t\tif (raw.model !== model) continue;\n\t\tconst row: MetadataRow = {\n\t\t\t...raw,\n\t\t\trowid: Number(raw.rowid),\n\t\t\tmemory_id: raw.memory_id === null ? null : Number(raw.memory_id),\n\t\t};\n\t\tif (!hasExactNumericIds(row))\n\t\t\treturn \"Target metadata IDs exceed the exact numeric range; retrying\";\n\t\tconst saved = find.get(row.rowid) as MetadataRow | undefined;\n\t\tif (\n\t\t\t!saved ||\n\t\t\tsaved.memory_id !== row.memory_id ||\n\t\t\tsaved.model !== row.model ||\n\t\t\tsaved.content_hash !== row.content_hash\n\t\t)\n\t\t\treturn \"Target vector metadata changed during validation; retrying\";\n\t\tcount++;\n\t}\n\tif (performance.now() > deadline)\n\t\treturn \"Target metadata comparison exceeded 2 seconds; retrying\";\n\t// Unique rowids + exact membership + cardinality proves equality in both directions.\n\tif (count !== expectedCount) return \"Target vector metadata changed during validation; retrying\";\n\treturn null;\n}\n\n/**\n * Keep the catalog alive through finalization; it is NOT a source TEMP table.\n * Blob/chunk_index-only writes cannot change hash coverage and are intentionally ignored.\n */\nexport type VectorCutoverValidation = {\n\tdeleted: number;\n\tuncovered: number;\n\tclose: () => void;\n\tretryReason: () => string | null;\n\tcorpusRetryReason: () => string | null;\n\tmetadataRetryReason: () => string | null;\n\tnoteOwnWrites: () => void;\n};\n\nexport function prepareVectorCutoverValidation(\n\tdb: Database,\n\tmodel: string,\n\toptions: { signal?: AbortSignal; phase?: \"cleanup-\"; pruneScope?: \"all\" | \"active-only\" } = {},\n): VectorCutoverValidation {\n\tconst phase = options.phase ?? \"\";\n\tconst before = readFence(db, `${phase}prune-start`);\n\tconst metadata = createVectorMetadataSnapshot(db, { model });\n\ttry {\n\t\tconst deleted = pruneObsoleteTargetVectorsFromCatalog(db, model, metadata, options);\n\t\tlet afterPrune = readFence(db, `${phase}prune-end`);\n\t\tconst uncovered = countIncompleteActiveMemoryVectorCoverage(db, model, { metadata });\n\t\tconst expectedCount = Number(\n\t\t\tmetadata.prepare(\"SELECT COUNT(*) FROM vector_metadata\").pluck().get(),\n\t\t);\n\t\tconst corpusRetryReason = (): string | null => {\n\t\t\tif (options.signal?.aborted) return \"Cutover paused during shutdown; retrying\";\n\t\t\tconst current = readFence(db, \"validation\");\n\t\t\tif (current.schemaVersion !== before.schemaVersion)\n\t\t\t\treturn \"Database schema changed during validation; retrying\";\n\t\t\tif (before.epoch !== null) {\n\t\t\t\tif (current.epoch !== before.epoch)\n\t\t\t\t\treturn `Memory changes arrived during ${phase}cutover validation; retrying`;\n\t\t\t} else if (\n\t\t\t\tbefore.dataVersion !== afterPrune.dataVersion ||\n\t\t\t\tcurrent.dataVersion !== afterPrune.dataVersion ||\n\t\t\t\tcurrent.totalChanges !== afterPrune.totalChanges\n\t\t\t) {\n\t\t\t\treturn `Memory changes arrived during ${phase}cutover validation; retrying`;\n\t\t\t}\n\t\t\treturn null;\n\t\t};\n\t\tconst metadataRetryReason = () => compareCatalog(db, metadata, model, expectedCount);\n\t\treturn {\n\t\t\tdeleted,\n\t\t\tuncovered,\n\t\t\tclose: () => metadata.close(),\n\t\t\t// Must be called under BEGIN IMMEDIATE. Body hashing already happened above.\n\t\t\tretryReason: () => corpusRetryReason() ?? metadataRetryReason(),\n\t\t\tcorpusRetryReason,\n\t\t\tmetadataRetryReason,\n\t\t\t// Only immediately after our synchronous delete/job writes, before yielding.\n\t\t\t// Keep the original data_version: other connections still invalidate fallback.\n\t\t\tnoteOwnWrites: () => {\n\t\t\t\tafterPrune = {\n\t\t\t\t\t...afterPrune,\n\t\t\t\t\ttotalChanges: Number(db.prepare(\"SELECT total_changes()\").pluck().get()),\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\tmetadata.close();\n\t\tthrow error;\n\t}\n}\n","import type { Database as SqliteDatabase } from \"better-sqlite3\";\nimport { connect, isEmbeddingDisabled, loadSqliteVec, resolveDbPath } from \"./db.js\";\nimport {\n\tDEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL,\n\ttype EmbeddingClient,\n\tgetEmbeddingClient,\n\tresolveEmbeddingClientVectorIdentityLabel,\n\ttryResolveEmbeddingVectorIdentityLabel,\n} from \"./embeddings.js\";\nimport {\n\tcompleteMaintenanceJob,\n\tfailMaintenanceJob,\n\tgetMaintenanceJob,\n\tisTransientSqliteBusy,\n\ttype MaintenanceJobSnapshot,\n\tupdateMaintenanceJob,\n} from \"./maintenance-jobs.js\";\nimport type { ReplicationVectorWork } from \"./sync-replication.js\";\nimport {\n\tmergeQueuedSyncMemoryIds,\n\tmetadataMemoryIds,\n\tqueueVectorBackfill,\n\tSYNC_INCREMENTAL_TRIGGER,\n\tstartVectorMigrationJob,\n\tVECTOR_MODEL_MIGRATION_JOB,\n\ttype VectorBackfillQueueMetadata,\n\tVectorMigrationJobGenerationError,\n} from \"./vector-backfill-queue.js\";\nimport { readVectorCorpusFence } from \"./vector-corpus-epoch.js\";\nimport {\n\tprepareVectorCutoverValidation,\n\ttype VectorCutoverValidation,\n} from \"./vector-cutover-validation.js\";\nimport { resolveVectorLayout } from \"./vector-layout.js\";\nimport { prepareVectorWrites } from \"./vector-writes.js\";\nimport {\n\tbackfillVectors,\n\tfindMemoryIdsWithCompleteActiveVectorCoverage,\n\tfindMemoryIdsWithCurrentTargetCoverage,\n\tpruneStaleCurrentModelVectors,\n} from \"./vectors.js\";\n\nexport { VECTOR_MODEL_MIGRATION_JOB } from \"./vector-backfill-queue.js\";\n\nconst LEGACY_DEFAULT_EMBEDDING_MODEL = \"Xenova/bge-small-en-v1.5\";\nconst SYNC_BOOTSTRAP_TRIGGER = \"sync_bootstrap\";\n\nexport interface VectorModelMigrationOptions {\n\tbatchSize?: number;\n\tintervalMs?: number;\n\tidleIntervalMs?: number;\n\t/**\n\t * Wall-clock budget for one tick. While work remains, the runner keeps\n\t * running batches on the same connection until this much time has passed.\n\t * Each batch still commits in its own short write transaction. 0 runs one\n\t * batch per tick.\n\t */\n\ttickBudgetMs?: number;\n\tdbPath?: string;\n\tsignal?: AbortSignal;\n}\n\n// Runner uses this cadence after a tick that detected no work. A live\n// migration or queued sync work switches back to intervalMs automatically.\nconst IDLE_INTERVAL_MS = 60_000;\n\n// Another connection held the write lock past busy_timeout. Retry soon with a\n// growing delay instead of treating lock contention as an idle database.\nconst BUSY_RETRY_BASE_MS = 5_000;\nconst BUSY_RETRY_MAX_MS = 30_000;\n// After this many locked ticks in a row (about 4 minutes), tell the UI why\n// catch-up is not moving.\nconst BUSY_TICKS_BEFORE_LOCK_NOTICE = 10;\nconst LOCK_WAIT_MESSAGE = \"Waiting for the database lock\";\n\nfunction busyRetryDelayMs(consecutiveBusyTicks: number): number {\n\tconst exponent = Math.max(0, consecutiveBusyTicks - 1);\n\treturn Math.min(BUSY_RETRY_MAX_MS, BUSY_RETRY_BASE_MS * 2 ** exponent);\n}\n\nfunction yieldToEventLoop(): Promise<void> {\n\treturn new Promise((resolve) => setImmediate(resolve));\n}\n\n// Module-level singleton so the queue writers can nudge the runner out of\n// its long idle cadence the moment new incremental/bootstrap work lands.\n// Assumes one active runner per process (the viewer serve loop), which\n// matches the current deployment model.\nlet activeRunner: VectorModelMigrationRunner | null = null;\n\ntype MemoryRow = { id: number; title: string | null; body_text: string | null };\n\ntype MigrationMetadata = VectorBackfillQueueMetadata & {\n\tsource_model?: string | null;\n\tlast_cursor_id?: number;\n\tprocessed_embeddable?: number;\n\tembeddable_total?: number;\n\tuncovered_target_memories?: number;\n\tstale_scan_exhausted?: boolean;\n\tstale_scan_exhausted_max_rowid?: number;\n\treconciliation_target_coverage_complete?: boolean;\n\tcutover_retry_count?: number;\n};\n\nfunction deleteVectorsForMemoryIds(db: SqliteDatabase, memoryIds: number[]): void {\n\tif (memoryIds.length === 0) return;\n\tconst write = prepareVectorWrites(db);\n\tdb.transaction(() => write({ deleteMemoryIds: memoryIds })).immediate();\n}\n\nfunction sameQueuedSyncWork(a: MigrationMetadata, b: MigrationMetadata): boolean {\n\treturn (\n\t\tNumber(a.queue_revision ?? 0) === Number(b.queue_revision ?? 0) &&\n\t\tJSON.stringify(metadataMemoryIds(a.pending_upsert_memory_ids)) ===\n\t\t\tJSON.stringify(metadataMemoryIds(b.pending_upsert_memory_ids)) &&\n\t\tJSON.stringify(metadataMemoryIds(a.pending_delete_memory_ids)) ===\n\t\t\tJSON.stringify(metadataMemoryIds(b.pending_delete_memory_ids))\n\t);\n}\n\nfunction buildDrainedQueuedSyncMetadata(options: {\n\tmetadata: MigrationMetadata;\n\tpendingUpsertMemoryIds: number[];\n\tbatchUpsertMemoryIds: number[];\n\tcoveredBatchUpsertMemoryIds: Set<number>;\n\tclient: EmbeddingClient;\n\ttargetModel: string;\n\tprunedRows: number;\n}): MigrationMetadata {\n\tconst targetChanged =\n\t\toptions.metadata.target_model != null && options.metadata.target_model !== options.targetModel;\n\tconst retainedMetadata: MigrationMetadata = targetChanged\n\t\t? {\n\t\t\t\ttrigger: options.metadata.trigger,\n\t\t\t\tpending_delete_memory_ids: options.metadata.pending_delete_memory_ids,\n\t\t\t\tpending_upsert_memory_ids: options.metadata.pending_upsert_memory_ids,\n\t\t\t\tjob_generation: options.metadata.job_generation,\n\t\t\t\tsource_model: null,\n\t\t\t\tlast_cursor_id: 0,\n\t\t\t\tprocessed_embeddable: 0,\n\t\t\t}\n\t\t: options.metadata;\n\tconst retainedBatchUpserts = options.batchUpsertMemoryIds.filter(\n\t\t(memoryId) => !options.coveredBatchUpsertMemoryIds.has(memoryId),\n\t);\n\treturn {\n\t\t...retainedMetadata,\n\t\ttarget_model: options.targetModel,\n\t\trequested_model: options.client.model,\n\t\trequested_revision:\n\t\t\toptions.client.identity?.requestedRevision ?? options.client.identity?.revision ?? null,\n\t\tremoved_stale_rows: Number(options.metadata.removed_stale_rows ?? 0) + options.prunedRows,\n\t\tpending_delete_memory_ids: [],\n\t\tpending_upsert_memory_ids: [\n\t\t\t...retainedBatchUpserts,\n\t\t\t...options.pendingUpsertMemoryIds.slice(options.batchUpsertMemoryIds.length),\n\t\t],\n\t};\n}\n\nfunction pendingQueuedSyncCount(metadata: MigrationMetadata): number {\n\treturn (\n\t\tmetadataMemoryIds(metadata.pending_delete_memory_ids).length +\n\t\tmetadataMemoryIds(metadata.pending_upsert_memory_ids).length\n\t);\n}\n\n/**\n * Incremental sync jobs with queued changes drain a batch and return before the\n * migration batch loop, so the pass never reaches cutover validation.\n */\nfunction drainsQueuedSyncBeforeCutover(metadata: MigrationMetadata): boolean {\n\treturn (\n\t\t(metadata.trigger ?? SYNC_INCREMENTAL_TRIGGER) === SYNC_INCREMENTAL_TRIGGER &&\n\t\tpendingQueuedSyncCount(metadata) > 0\n\t);\n}\n\nfunction shouldCompleteIncrementalSync(\n\tdb: SqliteDatabase,\n\tmetadata: MigrationMetadata,\n\ttargetModel: string,\n): boolean {\n\tif (pendingQueuedSyncCount(metadata) > 0) return false;\n\tif (hasSourceModelVectors(db, targetModel)) return false;\n\treturn (\n\t\t(metadata.trigger ?? SYNC_INCREMENTAL_TRIGGER) === SYNC_INCREMENTAL_TRIGGER &&\n\t\t!metadata.source_model &&\n\t\t!metadata.last_cursor_id &&\n\t\tmetadata.embeddable_total == null\n\t);\n}\n\nfunction writeQueuedSyncResult(\n\tdb: SqliteDatabase,\n\tjob: NonNullable<ReturnType<typeof getMaintenanceJob>>,\n\tmetadata: MigrationMetadata,\n\ttargetModel: string,\n): { completed: boolean; metadata: MigrationMetadata } {\n\tif (preservesCancelledMigration(job)) {\n\t\tconst preservedMetadata: MigrationMetadata = {\n\t\t\t...job.metadata,\n\t\t\tpending_upsert_memory_ids: metadata.pending_upsert_memory_ids,\n\t\t\tpending_delete_memory_ids: metadata.pending_delete_memory_ids,\n\t\t\tqueue_revision: metadata.queue_revision,\n\t\t};\n\t\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, { metadata: preservedMetadata });\n\t\treturn { completed: false, metadata: preservedMetadata };\n\t}\n\tconst remainingWorkCount = pendingQueuedSyncCount(metadata);\n\tif (shouldCompleteIncrementalSync(db, metadata, targetModel)) {\n\t\tcompleteMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\tmessage: \"Finished vector catch-up for incremental sync data\",\n\t\t\tprogressCurrent: 0,\n\t\t\tprogressTotal: null,\n\t\t\tmetadata,\n\t\t});\n\t\treturn { completed: true, metadata };\n\t}\n\n\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\tstatus: remainingWorkCount > 0 ? \"running\" : job.status,\n\t\tmessage:\n\t\t\tremainingWorkCount > 0\n\t\t\t\t? `Queued vector catch-up has ${remainingWorkCount} memory change(s) remaining`\n\t\t\t\t: job.message,\n\t\tprogressCurrent: 0,\n\t\tprogressTotal: null,\n\t\tmetadata,\n\t});\n\treturn { completed: false, metadata };\n}\n\ntype QueuedSyncResult = {\n\tcompleted: boolean;\n\tmetadata: MigrationMetadata;\n\tsuperseded?: boolean;\n\tjob?: MigrationJob;\n};\n\nfunction pruneCoveredRequeues(\n\tdb: SqliteDatabase,\n\tmetadata: MigrationMetadata,\n\tcovered: Set<number>,\n\ttargetModel: string,\n): number {\n\tconst memoryIds = metadataMemoryIds(metadata.pending_upsert_memory_ids).filter((id) =>\n\t\tcovered.has(id),\n\t);\n\treturn pruneStaleCurrentModelVectors(db, memoryIds, targetModel);\n}\n\nfunction mergeDrainedQueuedSyncMetadata(\n\tlatest: MigrationMetadata,\n\tdrained: MigrationMetadata,\n\tcovered: Set<number>,\n): MigrationMetadata {\n\tconst pendingUpserts = metadataMemoryIds(latest.pending_upsert_memory_ids).filter(\n\t\t(id) => !covered.has(id),\n\t);\n\treturn {\n\t\t...drained,\n\t\t...mergeQueuedSyncMemoryIds(\n\t\t\t{ ...latest, pending_upsert_memory_ids: pendingUpserts },\n\t\t\t{\n\t\t\t\tupsertMemoryIds: metadataMemoryIds(drained.pending_upsert_memory_ids),\n\t\t\t\tdeleteMemoryIds: metadataMemoryIds(drained.pending_delete_memory_ids),\n\t\t\t},\n\t\t),\n\t\tqueue_revision: latest.queue_revision,\n\t};\n}\n\nfunction finalizeQueuedSyncVectorWork(\n\tdb: SqliteDatabase,\n\toptions: {\n\t\tjob: NonNullable<ReturnType<typeof getMaintenanceJob>>;\n\t\tmetadata: MigrationMetadata;\n\t\tpendingUpsertMemoryIds: number[];\n\t\tbatchUpsertMemoryIds: number[];\n\t\tclient: EmbeddingClient;\n\t\ttargetModel: string;\n\t},\n): QueuedSyncResult {\n\treturn (\n\t\twithMigrationJobOwner(db, options.job, () => {\n\t\t\tlet prunedRows = pruneStaleCurrentModelVectors(\n\t\t\t\tdb,\n\t\t\t\toptions.batchUpsertMemoryIds,\n\t\t\t\toptions.targetModel,\n\t\t\t);\n\t\t\tconst latestJob = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\t\tif (!sameMigrationJob(options.job, latestJob)) {\n\t\t\t\treturn { completed: false, metadata: options.metadata, superseded: true };\n\t\t\t}\n\t\t\tconst coveredBatchUpsertMemoryIds = new Set(\n\t\t\t\tfindMemoryIdsWithCompleteActiveVectorCoverage(\n\t\t\t\t\tdb,\n\t\t\t\t\toptions.batchUpsertMemoryIds,\n\t\t\t\t\toptions.targetModel,\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst latestMetadata = (latestJob?.metadata ?? {}) as MigrationMetadata;\n\t\t\tconst queuedWorkChanged = !sameQueuedSyncWork(latestMetadata, options.metadata);\n\t\t\tif (queuedWorkChanged) {\n\t\t\t\tprunedRows += pruneCoveredRequeues(\n\t\t\t\t\tdb,\n\t\t\t\t\tlatestMetadata,\n\t\t\t\t\tcoveredBatchUpsertMemoryIds,\n\t\t\t\t\toptions.targetModel,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst drainedMetadata = buildDrainedQueuedSyncMetadata({\n\t\t\t\t...options,\n\t\t\t\tcoveredBatchUpsertMemoryIds,\n\t\t\t\tprunedRows,\n\t\t\t});\n\t\t\tlet nextMetadata = drainedMetadata;\n\t\t\tif (queuedWorkChanged) {\n\t\t\t\tnextMetadata = mergeDrainedQueuedSyncMetadata(\n\t\t\t\t\tlatestMetadata,\n\t\t\t\t\tdrainedMetadata,\n\t\t\t\t\tcoveredBatchUpsertMemoryIds,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst result = writeQueuedSyncResult(\n\t\t\t\tdb,\n\t\t\t\tlatestJob ?? options.job,\n\t\t\t\t{\n\t\t\t\t\t...nextMetadata,\n\t\t\t\t\tlocal_repair_preserves_migration_state:\n\t\t\t\t\t\tlatestMetadata.local_repair_preserves_migration_state,\n\t\t\t\t},\n\t\t\t\toptions.targetModel,\n\t\t\t);\n\t\t\treturn { ...result, job: getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB) };\n\t\t}) ?? { completed: false, metadata: options.metadata, superseded: true }\n\t);\n}\n\nexport function wakeActiveVectorMigrationRunner(): void {\n\tactiveRunner?.wake();\n}\n\nexport function queueVectorBackfillForIncrementalSync(\n\tdb: SqliteDatabase,\n\twork: ReplicationVectorWork,\n): void {\n\tconst queuedWork = mergeQueuedSyncMemoryIds({}, work);\n\tif (\n\t\t(queuedWork.pending_upsert_memory_ids?.length ?? 0) === 0 &&\n\t\t(queuedWork.pending_delete_memory_ids?.length ?? 0) === 0\n\t) {\n\t\treturn;\n\t}\n\n\tqueueVectorBackfill(db, work, { resumeMigration: true });\n\twakeActiveVectorMigrationRunner();\n}\n\nasync function runQueuedSyncVectorWork(\n\tdb: SqliteDatabase,\n\tjob: NonNullable<ReturnType<typeof getMaintenanceJob>>,\n\tclient: EmbeddingClient,\n\ttargetModel: string,\n\tbatchSize: number,\n\tsignal?: AbortSignal,\n): Promise<QueuedSyncResult> {\n\tconst metadata = (job.metadata ?? {}) as MigrationMetadata;\n\tconst pendingDeleteMemoryIds = metadataMemoryIds(metadata.pending_delete_memory_ids);\n\tconst pendingUpsertMemoryIds = metadataMemoryIds(metadata.pending_upsert_memory_ids);\n\tif (pendingDeleteMemoryIds.length === 0 && pendingUpsertMemoryIds.length === 0) {\n\t\treturn { completed: false, metadata };\n\t}\n\n\tconst ownsWork = withMigrationJobOwner(db, job, () => {\n\t\tdeleteVectorsForMemoryIds(db, pendingDeleteMemoryIds);\n\t\treturn true;\n\t});\n\tif (!ownsWork) return { completed: false, metadata, superseded: true };\n\tconst batchUpsertMemoryIds = pendingUpsertMemoryIds.slice(0, batchSize);\n\tif (batchUpsertMemoryIds.length > 0) {\n\t\tawait backfillVectors(db, { memoryIds: batchUpsertMemoryIds, signal, client });\n\t\t// If the abort fired mid-batch, backfillVectors may have only\n\t\t// processed a prefix. Skip the prune-and-drop bookkeeping so the\n\t\t// unprocessed IDs stay in pending_upsert_memory_ids for the next\n\t\t// tick to retry.\n\t\tif (signal?.aborted) {\n\t\t\treturn { completed: false, metadata };\n\t\t}\n\t}\n\treturn finalizeQueuedSyncVectorWork(db, {\n\t\tjob,\n\t\tmetadata,\n\t\tpendingUpsertMemoryIds,\n\t\tbatchUpsertMemoryIds,\n\t\tclient,\n\t\ttargetModel,\n\t});\n}\n\nexport function queueVectorBackfillForSyncBootstrap(\n\tdb: SqliteDatabase,\n\toptions: { embeddableTotal?: number | null } = {},\n): void {\n\tconst embeddableTotal =\n\t\ttypeof options.embeddableTotal === \"number\" && options.embeddableTotal >= 0\n\t\t\t? options.embeddableTotal\n\t\t\t: null;\n\tdb.transaction(() => {\n\t\tconst existingJob = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\tconst existingMetadata = (existingJob?.metadata ?? {}) as MigrationMetadata;\n\t\tconst metadata: MigrationMetadata = {\n\t\t\tlast_cursor_id: 0,\n\t\t\tprocessed_embeddable: 0,\n\t\t\ttrigger: SYNC_BOOTSTRAP_TRIGGER,\n\t\t\tpending_upsert_memory_ids: metadataMemoryIds(existingMetadata.pending_upsert_memory_ids),\n\t\t\tpending_delete_memory_ids: metadataMemoryIds(existingMetadata.pending_delete_memory_ids),\n\t\t\t// Bootstrap resets the scan, not the queued work. Retain its revision so\n\t\t\t// later enqueues cannot reuse a revision observed by an in-flight drain.\n\t\t\tqueue_revision: existingMetadata.queue_revision,\n\t\t};\n\t\tif (embeddableTotal != null) {\n\t\t\tmetadata.embeddable_total = embeddableTotal;\n\t\t}\n\t\tstartVectorMigrationJob(db, {\n\t\t\ttitle: \"Re-indexing memories\",\n\t\t\tstatus: \"pending\",\n\t\t\tmessage: \"Queued vector catch-up for synced bootstrap data\",\n\t\t\tprogressTotal: embeddableTotal,\n\t\t\tmetadata,\n\t\t});\n\t}).immediate();\n\twakeActiveVectorMigrationRunner();\n}\n\nfunction vectorModels(db: SqliteDatabase): Array<{ model: string; rows: number }> {\n\treturn db\n\t\t.prepare(\n\t\t\t\"SELECT model, COUNT(*) AS rows FROM memory_vectors GROUP BY model ORDER BY rows DESC, model ASC\",\n\t\t)\n\t\t.all() as Array<{ model: string; rows: number }>;\n}\n\ntype SourceModelScanResult = {\n\tfound: boolean;\n\t/** Last rowid the scan examined, or null when the legacy full-scan path ran. */\n\tscannedMaxRowId: number | null;\n};\n\nfunction exactVectorRowId(value: bigint): number | null {\n\tif (value < BigInt(Number.MIN_SAFE_INTEGER) || value > BigInt(Number.MAX_SAFE_INTEGER))\n\t\treturn null;\n\treturn Number(value);\n}\n\nfunction exactVectorRowIdPage(rows: { rowid: bigint }[]): { rowid: number }[] | null {\n\tconst exactRows: { rowid: number }[] = [];\n\tfor (const row of rows) {\n\t\tconst rowid = exactVectorRowId(row.rowid);\n\t\tif (rowid === null) return null;\n\t\texactRows.push({ rowid });\n\t}\n\treturn exactRows;\n}\n\nfunction scanForSourceModelVectorsAfter(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\tafterRowId: number,\n): SourceModelScanResult {\n\tif (!Number.isSafeInteger(afterRowId)) return { found: true, scannedMaxRowId: null };\n\tif (!hasMemoryVectorRowidsShadowTable(db)) {\n\t\tconst found = Boolean(\n\t\t\tdb.prepare(\"SELECT 1 FROM memory_vectors WHERE model != ? LIMIT 1\").pluck().get(targetModel),\n\t\t);\n\t\treturn { found, scannedMaxRowId: null };\n\t}\n\tconst selectRowIds = db\n\t\t.prepare(\n\t\t\t`SELECT rowid FROM ${vectorRowidsTable(db)} WHERE rowid > ? ORDER BY rowid ASC LIMIT ? /* vector-source-scan-rowids */`,\n\t\t)\n\t\t.safeIntegers();\n\tconst selectMetadata = db.prepare(\n\t\t\"SELECT memory_id, content_hash, model FROM memory_vectors WHERE rowid = ?\",\n\t);\n\tlet cursor = afterRowId;\n\twhile (true) {\n\t\tconst rows = exactVectorRowIdPage(selectRowIds.all(cursor, 250) as { rowid: bigint }[]);\n\t\t// An unsupported ID is unexamined work, not evidence of scan exhaustion.\n\t\tif (rows === null) return { found: true, scannedMaxRowId: null };\n\t\tif (rows.length === 0) return { found: false, scannedMaxRowId: cursor };\n\t\tfor (const row of rows) {\n\t\t\tconst metadata = selectMetadata.get(row.rowid) as { model: string } | undefined;\n\t\t\tif (metadata && metadata.model !== targetModel) {\n\t\t\t\treturn { found: true, scannedMaxRowId: null };\n\t\t\t}\n\t\t}\n\t\tcursor = rows.at(-1)?.rowid ?? cursor;\n\t}\n}\n\nfunction hasSourceModelVectorsAfter(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\tafterRowId: number,\n): boolean {\n\treturn scanForSourceModelVectorsAfter(db, targetModel, afterRowId).found;\n}\n\nfunction hasSourceModelVectors(db: SqliteDatabase, targetModel: string): boolean {\n\treturn hasSourceModelVectorsAfter(db, targetModel, 0);\n}\n\nfunction hasMemoryVectorRowidsShadowTable(db: SqliteDatabase): boolean {\n\tconst layout = resolveVectorLayout(db);\n\tif (layout.kind === \"absent\") return false;\n\tconst tables = db.prepare(\"PRAGMA table_list\").all() as Array<{ name: string }>;\n\treturn tables.some((table) => table.name === layout.rowidsName);\n}\n\nfunction vectorRowidsTable(\n\tdb: SqliteDatabase,\n): \"memory_vectors_rowids\" | \"memory_vectors_v1_rowids\" {\n\tconst layout = resolveVectorLayout(db);\n\tif (layout.kind === \"absent\") throw new Error(\"vector_table_required\");\n\treturn layout.rowidsName;\n}\n\nfunction readMaxMemoryVectorRowId(db: SqliteDatabase): number | null {\n\tif (!hasMemoryVectorRowidsShadowTable(db)) return null;\n\tconst row = db\n\t\t.prepare(`SELECT MAX(rowid) AS max_rowid FROM ${vectorRowidsTable(db)}`)\n\t\t.safeIntegers()\n\t\t.get() as { max_rowid: bigint | null } | undefined;\n\tif (row?.max_rowid == null) return 0;\n\treturn exactVectorRowId(row.max_rowid);\n}\n\nfunction checkCompletedStaleScan(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\tmetadata: MigrationMetadata,\n): { canReturn: boolean; metadata: MigrationMetadata } {\n\tif (metadata.cleanup_pending) return { canReturn: false, metadata };\n\tif (!metadata.stale_scan_exhausted) {\n\t\t// Jobs completed before the flag existed have no watermark. One clean\n\t\t// compatibility scan is unavoidable, but persist its result so upgraded\n\t\t// databases don't repeat it on every idle tick.\n\t\tconst scan = scanForSourceModelVectorsAfter(db, targetModel, 0);\n\t\tif (scan.found) return { canReturn: false, metadata };\n\t\tif (scan.scannedMaxRowId == null) return { canReturn: true, metadata };\n\t\tconst persisted = {\n\t\t\t...metadata,\n\t\t\tstale_scan_exhausted: true,\n\t\t\tstale_scan_exhausted_max_rowid: scan.scannedMaxRowId,\n\t\t};\n\t\treturn { canReturn: true, metadata: persisted };\n\t}\n\tconst exhaustedMaxRowId = metadata.stale_scan_exhausted_max_rowid;\n\tconst currentMaxRowId = readMaxMemoryVectorRowId(db);\n\tif (\n\t\ttypeof exhaustedMaxRowId === \"number\" &&\n\t\tNumber.isSafeInteger(exhaustedMaxRowId) &&\n\t\tcurrentMaxRowId != null &&\n\t\tcurrentMaxRowId <= exhaustedMaxRowId\n\t) {\n\t\treturn { canReturn: true, metadata };\n\t}\n\tif (\n\t\ttypeof exhaustedMaxRowId === \"number\" &&\n\t\tNumber.isSafeInteger(exhaustedMaxRowId) &&\n\t\tcurrentMaxRowId != null &&\n\t\t!hasSourceModelVectorsAfter(db, targetModel, exhaustedMaxRowId)\n\t) {\n\t\tconst refreshed = { ...metadata, stale_scan_exhausted_max_rowid: currentMaxRowId };\n\t\treturn { canReturn: true, metadata: refreshed };\n\t}\n\tconst invalidated = {\n\t\t...metadata,\n\t\tstale_scan_exhausted: undefined,\n\t\tstale_scan_exhausted_max_rowid: undefined,\n\t};\n\treturn { canReturn: false, metadata: invalidated };\n}\n\nfunction countEmbeddableActiveMemories(db: SqliteDatabase): number {\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT COUNT(*) AS c FROM memory_items\n\t\t\t WHERE active = 1\n\t\t\t AND TRIM(COALESCE(title, '') || COALESCE(body_text, '')) != ''`,\n\t\t)\n\t\t.get() as { c?: number } | undefined;\n\treturn Number(row?.c ?? 0);\n}\n\nfunction describeIncompleteTargetMemories(count: number): string {\n\treturn `${count} ${count === 1 ? \"memory\" : \"memories\"}`;\n}\n\nfunction selectNextMigrationBatch(\n\tdb: SqliteDatabase,\n\tafterId: number,\n\tbatchSize: number,\n): MemoryRow[] {\n\treturn db\n\t\t.prepare(\n\t\t\t`SELECT id, title, body_text\n\t\t\t FROM memory_items\n\t\t\t WHERE active = 1 AND id > ?\n\t\t\t ORDER BY id ASC\n\t\t\t LIMIT ?`,\n\t\t)\n\t\t.all(afterId, batchSize) as MemoryRow[];\n}\n\nfunction isEmbeddableMemory(row: MemoryRow): boolean {\n\treturn (\n\t\t`${row.title ?? \"\"}\n${row.body_text ?? \"\"}`.trim().length > 0\n\t);\n}\n\nfunction nextMigrationMetadata(\n\tjob: ReturnType<typeof getMaintenanceJob>,\n\tsourceModel: string | null,\n\ttargetModel: string,\n\trequestedModel: string,\n\trequestedRevision: string,\n\tembeddableTotal: number,\n\toptions: {\n\t\trestartFromBeginning?: boolean;\n\t\treconciliationTargetCoverageComplete?: boolean;\n\t} = {},\n): MigrationMetadata {\n\tconst metadata = (job?.metadata ?? {}) as MigrationMetadata;\n\tconst pendingUpsertMemoryIds = metadataMemoryIds(metadata.pending_upsert_memory_ids);\n\tconst pendingDeleteMemoryIds = metadataMemoryIds(metadata.pending_delete_memory_ids);\n\tconst pending_upsert_memory_ids =\n\t\tpendingUpsertMemoryIds.length > 0 ? pendingUpsertMemoryIds : undefined;\n\tconst pending_delete_memory_ids =\n\t\tpendingDeleteMemoryIds.length > 0 ? pendingDeleteMemoryIds : undefined;\n\tif (metadata.target_model !== targetModel || options.restartFromBeginning) {\n\t\treturn {\n\t\t\ttrigger: metadata.trigger,\n\t\t\treconciliation_target_coverage_complete:\n\t\t\t\toptions.reconciliationTargetCoverageComplete || undefined,\n\t\t\tpending_upsert_memory_ids,\n\t\t\tpending_delete_memory_ids,\n\t\t\tqueue_revision: metadata.queue_revision,\n\t\t\tjob_generation: metadata.job_generation,\n\t\t\tsource_model: sourceModel,\n\t\t\ttarget_model: targetModel,\n\t\t\trequested_model: requestedModel,\n\t\t\trequested_revision: requestedRevision,\n\t\t\tlast_cursor_id: 0,\n\t\t\tprocessed_embeddable: 0,\n\t\t\tembeddable_total: embeddableTotal,\n\t\t};\n\t}\n\treturn {\n\t\t...metadata,\n\t\tpending_upsert_memory_ids,\n\t\tpending_delete_memory_ids,\n\t\tsource_model: sourceModel ?? metadata.source_model ?? null,\n\t\ttarget_model: targetModel,\n\t\trequested_model: requestedModel,\n\t\trequested_revision: requestedRevision,\n\t\tlast_cursor_id: Number(metadata.last_cursor_id ?? 0),\n\t\tprocessed_embeddable: Number(metadata.processed_embeddable ?? 0),\n\t\tembeddable_total: Number(metadata.embeddable_total ?? embeddableTotal),\n\t\tremoved_stale_rows: metadata.removed_stale_rows,\n\t};\n}\n\ntype StaleDeleteOptions = {\n\tcleanupOwner?: { job: MigrationJob };\n\tcheckFence?: () => string | null;\n};\n\ntype CurrentStaleRow = { rowid: number; memoryId: number | null };\n\nfunction collectCurrentStaleRows(\n\tdb: SqliteDatabase,\n\trowIds: number[],\n\ttargetModel: string,\n\tsignal?: AbortSignal,\n): { rows: CurrentStaleRow[]; retainedFallback: boolean } {\n\tconst selectCurrent = db\n\t\t.prepare(\"SELECT memory_id, model FROM memory_vectors WHERE rowid = ?\")\n\t\t.safeIntegers();\n\tconst rows: CurrentStaleRow[] = [];\n\tif (rowIds.some((rowid) => !Number.isSafeInteger(rowid))) {\n\t\tthrow new RangeError(\"Vector metadata IDs exceed the exact numeric range\");\n\t}\n\tfor (const rowid of rowIds) {\n\t\tif (signal?.aborted) break;\n\t\tconst current = selectCurrent.get(rowid) as\n\t\t\t| { memory_id: bigint | null; model: string }\n\t\t\t| undefined;\n\t\tif (!current || current.model === targetModel) continue;\n\t\tconst memoryId = current.memory_id === null ? null : Number(current.memory_id);\n\t\tif (memoryId !== null && !Number.isSafeInteger(memoryId)) {\n\t\t\tthrow new RangeError(\"Vector metadata IDs exceed the exact numeric range\");\n\t\t}\n\t\trows.push({ rowid, memoryId });\n\t}\n\treturn { rows, retainedFallback: false };\n}\n\nfunction deleteCoveredStaleRows(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\trows: CurrentStaleRow[],\n\tsignal?: AbortSignal,\n): { deleted: number; retainedFallback: boolean } {\n\tconst coverage = findMemoryIdsWithCurrentTargetCoverage(\n\t\tdb,\n\t\trows.flatMap((row) => (row.memoryId === null ? [] : [row.memoryId])),\n\t\ttargetModel,\n\t);\n\tconst rowIds: number[] = [];\n\tlet retainedFallback = false;\n\tfor (const row of rows) {\n\t\tif (signal?.aborted) break;\n\t\tif (row.memoryId !== null && !coverage.has(row.memoryId)) {\n\t\t\tretainedFallback = true;\n\t\t\tcontinue;\n\t\t}\n\t\trowIds.push(row.rowid);\n\t}\n\tconst { deleted } = prepareVectorWrites(db)({ deleteRowIds: rowIds, signal });\n\treturn { deleted, retainedFallback };\n}\n\nfunction deleteCheckedStaleRows(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\trowIds: number[],\n\tsignal?: AbortSignal,\n\toptions: StaleDeleteOptions = {},\n): { deleted: number; retainedFallback: boolean } {\n\treturn db\n\t\t.transaction(() => {\n\t\t\tif (options.cleanupOwner && !isCurrentCleanupJob(db, targetModel, options.cleanupOwner))\n\t\t\t\treturn { deleted: 0, retainedFallback: false };\n\t\t\tif (options.checkFence?.()) return { deleted: 0, retainedFallback: true };\n\t\t\tconst current = collectCurrentStaleRows(db, rowIds, targetModel, signal);\n\t\t\tif (signal?.aborted) return { deleted: 0, retainedFallback: current.retainedFallback };\n\t\t\tconst result = deleteCoveredStaleRows(db, targetModel, current.rows, signal);\n\t\t\treturn {\n\t\t\t\tdeleted: result.deleted,\n\t\t\t\tretainedFallback: current.retainedFallback || result.retainedFallback,\n\t\t\t};\n\t\t})\n\t\t.immediate();\n}\n\nfunction appendStaleRowIds(\n\tdb: SqliteDatabase,\n\trows: { rowid: number }[],\n\ttargetModel: string,\n\tstaleRowIds: number[],\n): number {\n\tconst selectMetadata = db.prepare(\n\t\t\"SELECT memory_id, content_hash, model FROM memory_vectors WHERE rowid = ?\",\n\t);\n\tlet cursor = 0;\n\tfor (const row of rows) {\n\t\tconst metadata = selectMetadata.get(row.rowid) as { model: string } | undefined;\n\t\tif (metadata && metadata.model !== targetModel) staleRowIds.push(row.rowid);\n\t\tcursor = row.rowid;\n\t\tif (staleRowIds.length === 250) break;\n\t}\n\treturn cursor;\n}\n\nfunction scanStaleModelVectorRows(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\tsignal?: AbortSignal,\n): {\n\trowIds: number[];\n\texhausted: boolean;\n\tscannedMaxRowId: number | null;\n} {\n\tconst batchSize = 250;\n\tif (!hasMemoryVectorRowidsShadowTable(db)) {\n\t\tconst rawRows = db\n\t\t\t.prepare(\"SELECT rowid FROM memory_vectors WHERE model != ? ORDER BY rowid ASC LIMIT ?\")\n\t\t\t.safeIntegers()\n\t\t\t.all(targetModel, batchSize) as { rowid: bigint }[];\n\t\tconst rows = exactVectorRowIdPage(rawRows);\n\t\tif (rows === null) throw new RangeError(\"Vector metadata IDs exceed the exact numeric range\");\n\t\treturn {\n\t\t\trowIds: rows.map((row) => row.rowid),\n\t\t\texhausted: rows.length < batchSize,\n\t\t\tscannedMaxRowId: null,\n\t\t};\n\t}\n\n\tconst selectRowIds = db\n\t\t.prepare(\n\t\t\t`SELECT rowid FROM ${vectorRowidsTable(db)} WHERE rowid > ? ORDER BY rowid ASC LIMIT ? /* vector-stale-scan-rowids */`,\n\t\t)\n\t\t.safeIntegers();\n\tconst staleRowIds: number[] = [];\n\tlet afterRowId = 0;\n\tlet exhausted = false;\n\twhile (staleRowIds.length < batchSize && !signal?.aborted) {\n\t\tconst rows = exactVectorRowIdPage(\n\t\t\tselectRowIds.all(afterRowId, batchSize) as { rowid: bigint }[],\n\t\t);\n\t\t// Fail through the runner instead of repeatedly rescanning an unsafe page.\n\t\tif (rows === null) throw new RangeError(\"Vector metadata IDs exceed the exact numeric range\");\n\t\tif (rows.length === 0) {\n\t\t\texhausted = true;\n\t\t\tbreak;\n\t\t}\n\t\tafterRowId = appendStaleRowIds(db, rows, targetModel, staleRowIds);\n\t\tconst lastRowId = rows.at(-1)?.rowid;\n\t\tif (rows.length < batchSize && afterRowId === lastRowId) exhausted = true;\n\t}\n\t// The watermark is the last rowid this scan actually examined. Rows inserted\n\t// above it by a concurrent writer were never inspected and must be re-checked\n\t// on the next pass, so it must not be read from MAX(rowid) after the fact.\n\tconst scannedMaxRowId = exhausted ? afterRowId : null;\n\treturn { rowIds: staleRowIds, exhausted, scannedMaxRowId };\n}\n\nfunction deleteStaleModelVectors(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\tsignal?: AbortSignal,\n\toptions: StaleDeleteOptions = {},\n): { deleted: number; exhausted: boolean; scannedMaxRowId: number | null } {\n\tif (signal?.aborted) return { deleted: 0, exhausted: false, scannedMaxRowId: null };\n\tconst scan = scanStaleModelVectorRows(db, targetModel, signal);\n\tif (signal?.aborted) return { deleted: 0, exhausted: false, scannedMaxRowId: null };\n\t// Stop after one bounded batch so the event loop can deliver shutdown before\n\t// the next migration pass. Deleted rows are the durable cleanup cursor.\n\tconst result = deleteCheckedStaleRows(db, targetModel, scan.rowIds, signal, options);\n\treturn {\n\t\tdeleted: result.deleted,\n\t\texhausted: scan.exhausted && !result.retainedFallback && !signal?.aborted,\n\t\tscannedMaxRowId: scan.scannedMaxRowId,\n\t};\n}\n\nfunction isCurrentCleanupJob(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\texpectedOwner?: { job: MigrationJob },\n): boolean {\n\tconst job = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\tconst metadata = (job?.metadata ?? {}) as MigrationMetadata;\n\treturn (\n\t\tjob?.status === \"completed\" &&\n\t\tmetadata.target_model === targetModel &&\n\t\tpendingQueuedSyncCount(metadata) === 0 &&\n\t\t(expectedOwner === undefined || JSON.stringify(job) === JSON.stringify(expectedOwner.job))\n\t);\n}\n\nfunction cleanupStaleModels(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n): { removed: number; exhausted: boolean; scannedMaxRowId: number | null } {\n\tconst cleanup = deleteStaleModelVectors(db, targetModel);\n\t// Also prune obsolete rows within the target model: coverage is a subset\n\t// check, so a memory can be \"covered\" while retaining target rows for content\n\t// that no longer exists (interrupted migration, or an edit/redaction without\n\t// vector maintenance). Leaving them lets MIN-distance recall surface stale\n\t// content after the migration reports success.\n\t// The detached catalog supports pruning under the owner's write transaction\n\t// without changing temp_store on the source connection.\n\tconst validation = prepareVectorCutoverValidation(db, targetModel);\n\ttry {\n\t\treturn {\n\t\t\tremoved: cleanup.deleted + validation.deleted,\n\t\t\texhausted: cleanup.exhausted,\n\t\t\tscannedMaxRowId: cleanup.scannedMaxRowId,\n\t\t};\n\t} finally {\n\t\tvalidation.close();\n\t}\n}\n\ntype MigrationJob = ReturnType<typeof getMaintenanceJob>;\ntype MigrationPassOwner = { job: MigrationJob; failureHandled: boolean };\n\nfunction hasInFlightMigrationJob(job: MigrationJob): boolean {\n\treturn job?.status === \"running\" || job?.status === \"pending\" || job?.status === \"failed\";\n}\n\nfunction isActiveMigrationJob(job: MigrationJob): boolean {\n\treturn job?.status === \"running\" || job?.status === \"pending\";\n}\n\nfunction sameMigrationJob(original: MigrationJob, latest: MigrationJob): boolean {\n\tif (!original || !latest) return original === latest;\n\tconst before = original.metadata ?? {};\n\tconst after = latest.metadata ?? {};\n\treturn (\n\t\t(before.job_generation ?? 0) === (after.job_generation ?? 0) &&\n\t\toriginal.started_at === latest.started_at &&\n\t\t(original.status === \"cancelled\") === (latest.status === \"cancelled\") &&\n\t\tbefore.target_model === after.target_model &&\n\t\tbefore.requested_model === after.requested_model &&\n\t\tbefore.requested_revision === after.requested_revision\n\t);\n}\n\n/** Queue revisions may change within one job without invalidating its owner. */\nfunction withMigrationJobOwner<T>(\n\tdb: SqliteDatabase,\n\towner: MigrationJob,\n\twrite: (latest: MigrationJob) => T,\n): T | undefined {\n\treturn db\n\t\t.transaction(() => {\n\t\t\tconst latest = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\t\tif (!sameMigrationJob(owner, latest)) return undefined;\n\t\t\treturn write(latest);\n\t\t})\n\t\t.immediate();\n}\n\ntype CutoverProgress = {\n\tmetadata: MigrationMetadata;\n\tprogressCurrent: number;\n\tprogressTotal: number;\n};\n\nfunction sameCutoverJob(\n\toriginal: MigrationJob,\n\tlatest: MigrationJob,\n\ttargetModel: string,\n): boolean {\n\tif (\n\t\t!original ||\n\t\t!latest ||\n\t\t!sameMigrationJob(original, latest) ||\n\t\tlatest.status === \"cancelled\" ||\n\t\tlatest.started_at !== original.started_at\n\t)\n\t\treturn false;\n\tconst before = (original.metadata ?? {}) as MigrationMetadata;\n\tconst after = (latest.metadata ?? {}) as MigrationMetadata;\n\treturn (\n\t\tafter.target_model === before.target_model &&\n\t\tafter.requested_model === before.requested_model &&\n\t\tafter.requested_revision === before.requested_revision &&\n\t\t(after.target_model == null || after.target_model === targetModel)\n\t);\n}\n\nfunction completeCoveredSyncJob(\n\tdb: SqliteDatabase,\n\towner: MigrationJob,\n\ttargetModel: string,\n\trequestMetadata: MigrationMetadata,\n): boolean {\n\treturn (\n\t\twithMigrationJobOwner(db, owner, (latest) => {\n\t\t\tconst uncovered = db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT COUNT(*) AS c FROM memory_items\n\t\t\t WHERE active = 1\n\t\t\t AND id NOT IN (SELECT DISTINCT memory_id FROM memory_vectors WHERE model = ?)`,\n\t\t\t\t)\n\t\t\t\t.get(targetModel) as { c?: number } | undefined;\n\t\t\tif (Number(uncovered?.c ?? 0) > 0) return false;\n\t\t\tconst indexedTotal = countEmbeddableActiveMemories(db);\n\t\t\tcompleteMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\t\tmessage: \"Finished re-indexing memories\",\n\t\t\t\tprogressCurrent: indexedTotal,\n\t\t\t\tprogressTotal: indexedTotal,\n\t\t\t\tmetadata: {\n\t\t\t\t\t...latest?.metadata,\n\t\t\t\t\t...requestMetadata,\n\t\t\t\t\tsource_model: null,\n\t\t\t\t\ttarget_model: targetModel,\n\t\t\t\t\tprocessed_embeddable: indexedTotal,\n\t\t\t\t\tembeddable_total: indexedTotal,\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn true;\n\t\t}) !== false\n\t);\n}\n\nfunction completeEmptySourceMigration(\n\tdb: SqliteDatabase,\n\towner: MigrationJob,\n\ttargetModel: string,\n\tsourceModel: string,\n\trequestMetadata: MigrationMetadata,\n): void {\n\twithMigrationJobOwner(db, owner, (latest) => {\n\t\tif (countEmbeddableActiveMemories(db) > 0) return;\n\t\tconst cleanup = cleanupStaleModels(db, targetModel);\n\t\tconst staleScanExhausted = cleanup.exhausted && cleanup.scannedMaxRowId != null;\n\t\tconst job = startVectorMigrationJob(db, {\n\t\t\ttitle: \"Re-indexing memories\",\n\t\t\tmessage:\n\t\t\t\tcleanup.removed > 0\n\t\t\t\t\t? `Removed ${cleanup.removed} stale vector rows`\n\t\t\t\t\t: \"No embeddable memories to re-index\",\n\t\t\tprogressTotal: 0,\n\t\t\tmetadata: {\n\t\t\t\t...requestMetadata,\n\t\t\t\t...mergeQueuedSyncMemoryIds(latest?.metadata ?? {}, {\n\t\t\t\t\tupsertMemoryIds: [],\n\t\t\t\t\tdeleteMemoryIds: [],\n\t\t\t\t}),\n\t\t\t\tqueue_revision: latest?.metadata?.queue_revision,\n\t\t\t\tsource_model: sourceModel,\n\t\t\t\ttarget_model: targetModel,\n\t\t\t\tremoved_stale_rows: cleanup.removed,\n\t\t\t\tcleanup_pending: !cleanup.exhausted,\n\t\t\t\tstale_scan_exhausted: staleScanExhausted || undefined,\n\t\t\t\tstale_scan_exhausted_max_rowid: staleScanExhausted\n\t\t\t\t\t? (cleanup.scannedMaxRowId ?? undefined)\n\t\t\t\t\t: undefined,\n\t\t\t},\n\t\t});\n\t\tcompleteMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\tprogressCurrent: 0,\n\t\t\tprogressTotal: 0,\n\t\t\tmetadata: job.metadata,\n\t\t});\n\t});\n}\n\nfunction writeCutoverFailure(\n\tdb: SqliteDatabase,\n\tprogress: CutoverProgress,\n\tuncovered: number,\n): void {\n\tfailMaintenanceJob(\n\t\tdb,\n\t\tVECTOR_MODEL_MIGRATION_JOB,\n\t\t`Target vector coverage is incomplete for ${describeIncompleteTargetMemories(uncovered)}`,\n\t\t{\n\t\t\tmessage: \"Vector re-indexing stopped before cutover; existing valid vectors remain available\",\n\t\t\tmetadata: {\n\t\t\t\t...progress.metadata,\n\t\t\t\treconciliation_target_coverage_complete: undefined,\n\t\t\t\tlast_cursor_id: 0,\n\t\t\t\tprocessed_embeddable: 0,\n\t\t\t\tcutover_retry_count: 0,\n\t\t\t\tuncovered_target_memories: uncovered,\n\t\t\t},\n\t\t},\n\t);\n}\n\nfunction writeValidatedCutover(\n\tdb: SqliteDatabase,\n\tprogress: CutoverProgress,\n\tvalidation: VectorCutoverValidation,\n\tshouldStop?: () => boolean,\n): MigrationJob {\n\tconst retryReason = validation.retryReason();\n\tif (retryReason || shouldStop?.()) {\n\t\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\t...progress,\n\t\t\tstatus: \"running\",\n\t\t\tmessage: retryReason ?? \"Cutover paused during shutdown; retrying\",\n\t\t\tmetadata: {\n\t\t\t\t...progress.metadata,\n\t\t\t\tcutover_retry_count: Number(progress.metadata.cutover_retry_count ?? 0) + 1,\n\t\t\t},\n\t\t});\n\t\treturn null;\n\t}\n\tif (validation.uncovered > 0) {\n\t\twriteCutoverFailure(db, progress, validation.uncovered);\n\t\treturn null;\n\t}\n\treturn completeMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t...progress,\n\t\tmessage: \"Finished re-indexing; removing stale vectors\",\n\t\tmetadata: {\n\t\t\t...progress.metadata,\n\t\t\tcleanup_pending: true,\n\t\t\tstale_scan_exhausted: undefined,\n\t\t\tstale_scan_exhausted_max_rowid: undefined,\n\t\t\tcutover_retry_count: 0,\n\t\t\tuncovered_target_memories: undefined,\n\t\t},\n\t});\n}\n\nfunction commitMigrationCutover(\n\tdb: SqliteDatabase,\n\toptions: {\n\t\toriginalJob: MigrationJob;\n\t\ttargetModel: string;\n\t\tprogress: CutoverProgress;\n\t\tvalidation: VectorCutoverValidation;\n\t\tshouldStop?: () => boolean;\n\t},\n): (CutoverProgress & { cleanupJob: NonNullable<MigrationJob> }) | null {\n\treturn db\n\t\t.transaction(() => {\n\t\t\tconst latest = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\t\tif (!sameCutoverJob(options.originalJob, latest, options.targetModel)) return null;\n\t\t\tconst latestMetadata = (latest?.metadata ?? {}) as MigrationMetadata;\n\t\t\tconst sameQueue = sameQueuedSyncWork(latestMetadata, options.progress.metadata);\n\t\t\tif (sameQueue && JSON.stringify(latest) !== JSON.stringify(options.originalJob)) return null;\n\t\t\tconst progress: CutoverProgress = {\n\t\t\t\t...options.progress,\n\t\t\t\tmetadata: {\n\t\t\t\t\t...(sameQueue ? options.progress.metadata : latestMetadata),\n\t\t\t\t\tlast_cursor_id: options.progress.metadata.last_cursor_id,\n\t\t\t\t\tprocessed_embeddable: options.progress.progressCurrent,\n\t\t\t\t\tembeddable_total: options.progress.progressTotal,\n\t\t\t\t\tremoved_stale_rows:\n\t\t\t\t\t\tMath.max(\n\t\t\t\t\t\t\tNumber(latestMetadata.removed_stale_rows ?? 0),\n\t\t\t\t\t\t\tNumber(options.progress.metadata.removed_stale_rows ?? 0),\n\t\t\t\t\t\t) + options.validation.deleted,\n\t\t\t\t},\n\t\t\t};\n\t\t\tif (!sameQueue || pendingQueuedSyncCount(latestMetadata) > 0) {\n\t\t\t\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\t\t\t...progress,\n\t\t\t\t\tstatus: \"running\",\n\t\t\t\t\tmessage: \"Draining vector changes queued before cutover\",\n\t\t\t\t});\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst cleanupJob = writeValidatedCutover(\n\t\t\t\tdb,\n\t\t\t\tprogress,\n\t\t\t\toptions.validation,\n\t\t\t\toptions.shouldStop,\n\t\t\t);\n\t\t\treturn cleanupJob ? { ...progress, cleanupJob } : null;\n\t\t})\n\t\t.immediate();\n}\n\nasync function finalizeMigrationCutover(\n\tdb: SqliteDatabase,\n\towner: { job: MigrationJob },\n\ttargetModel: string,\n\tmetadata: MigrationMetadata,\n\tlastCursorId: number,\n\tprocessedEmbeddable: number,\n\tembeddableTotal: number,\n\tsignal?: AbortSignal,\n\tshouldStop?: () => boolean,\n): Promise<void> {\n\tconst originalJob = owner.job;\n\tconst validation = prepareVectorCutoverValidation(db, targetModel, { signal });\n\ttry {\n\t\tconst committed = commitMigrationCutover(db, {\n\t\t\toriginalJob,\n\t\t\ttargetModel,\n\t\t\tvalidation,\n\t\t\tshouldStop,\n\t\t\tprogress: {\n\t\t\t\tmetadata: { ...metadata, last_cursor_id: lastCursorId },\n\t\t\t\tprogressCurrent: processedEmbeddable,\n\t\t\t\tprogressTotal: embeddableTotal,\n\t\t\t},\n\t\t});\n\t\tif (!committed) return;\n\t\towner.job = committed.cleanupJob;\n\t\tvalidation.noteOwnWrites();\n\t\tawait drainStaleModelVectors(db, targetModel, {\n\t\t\texpectedJob: committed.cleanupJob,\n\t\t\tvalidation,\n\t\t\tpreviouslyRemoved: Number(committed.metadata.removed_stale_rows ?? 0),\n\t\t\tprunedTargetRows: 0,\n\t\t\tsignal,\n\t\t\tshouldStop,\n\t\t});\n\t} finally {\n\t\tvalidation.close();\n\t}\n}\n\nfunction detectSourceModel(db: SqliteDatabase, targetModel: string): string | null {\n\tconst rows = vectorModels(db).filter((row) => row.model !== targetModel);\n\treturn rows[0]?.model ?? null;\n}\n\nfunction mergedRemovedRows(\n\tlatestMetadata: MigrationMetadata,\n\tpreviouslyRemoved: number,\n\tnewlyRemoved: number,\n): number {\n\treturn Math.max(Number(latestMetadata.removed_stale_rows ?? 0), previouslyRemoved) + newlyRemoved;\n}\n\nfunction deferCompletedCleanup(\n\tdb: SqliteDatabase,\n\texpectedCleanup: { job: MigrationJob; targetModel: string },\n\tpreviouslyRemoved: number,\n\tprunedTargetRows: number,\n\tmessage: string,\n): void {\n\tdb.transaction(() => {\n\t\tif (!isCurrentCleanupJob(db, expectedCleanup.targetModel)) return;\n\t\tconst latestJob = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\t// The unlocked fence/shutdown check may have raced a replacement job or\n\t\t// queued work. Only the exact cleanup job we checked may be deferred.\n\t\tif (JSON.stringify(latestJob) !== JSON.stringify(expectedCleanup.job)) return;\n\t\tconst latestMetadata = (latestJob?.metadata ?? {}) as MigrationMetadata;\n\t\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\tstatus: \"completed\",\n\t\t\tmessage,\n\t\t\tmetadata: {\n\t\t\t\t...latestMetadata,\n\t\t\t\tremoved_stale_rows: mergedRemovedRows(latestMetadata, previouslyRemoved, prunedTargetRows),\n\t\t\t\tcleanup_pending: true,\n\t\t\t\tstale_scan_exhausted: undefined,\n\t\t\t\tstale_scan_exhausted_max_rowid: undefined,\n\t\t\t\treconciliation_target_coverage_complete: undefined,\n\t\t\t},\n\t\t});\n\t}).immediate();\n}\n\nfunction restartMigrationForIncompleteCoverage(\n\tdb: SqliteDatabase,\n\tpreviouslyRemoved: number,\n\tprunedTargetRows: number,\n\tuncovered: number,\n): void {\n\tdb.transaction(() => {\n\t\tconst latestJob = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\tconst latestMetadata = (latestJob?.metadata ?? {}) as MigrationMetadata;\n\t\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\tstatus: \"pending\",\n\t\t\tmessage: \"Target coverage changed before cleanup; rebuilding missing vectors\",\n\t\t\tprogressCurrent: 0,\n\t\t\tprogressTotal: null,\n\t\t\tmetadata: {\n\t\t\t\t...latestMetadata,\n\t\t\t\tcleanup_pending: false,\n\t\t\t\tstale_scan_exhausted: undefined,\n\t\t\t\tstale_scan_exhausted_max_rowid: undefined,\n\t\t\t\treconciliation_target_coverage_complete: undefined,\n\t\t\t\tsource_model: null,\n\t\t\t\tlast_cursor_id: 0,\n\t\t\t\tprocessed_embeddable: 0,\n\t\t\t\tembeddable_total: undefined,\n\t\t\t\tremoved_stale_rows: mergedRemovedRows(latestMetadata, previouslyRemoved, prunedTargetRows),\n\t\t\t\tuncovered_target_memories: uncovered,\n\t\t\t},\n\t\t});\n\t}).immediate();\n}\n\nfunction cleanupResultMessage(options: {\n\tcompleted: boolean;\n\tremoved: number;\n\tretryReason: string | null;\n\tcleanup: { exhausted: boolean; deleted: number };\n}): string {\n\tif (options.completed)\n\t\treturn options.removed > 0\n\t\t\t? `Finished re-indexing and removed ${options.removed} stale vector rows`\n\t\t\t: \"Finished re-indexing memories\";\n\tif (!options.cleanup.exhausted && options.cleanup.deleted === 0)\n\t\treturn \"Memory changes arrived during cleanup; retrying\";\n\treturn options.retryReason ?? \"Finished re-indexing; removing stale vectors\";\n}\n\nfunction recordResumedCleanupResult(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\toptions: {\n\t\texpectedJob: MigrationJob;\n\t\tcleanup: { deleted: number; exhausted: boolean; scannedMaxRowId: number | null };\n\t\tvalidation: VectorCutoverValidation;\n\t\tpreviouslyRemoved: number;\n\t\tprunedTargetRows: number;\n\t},\n): { completed: boolean; job: NonNullable<MigrationJob> } | null {\n\treturn db\n\t\t.transaction(() => {\n\t\t\tif (!isCurrentCleanupJob(db, targetModel, { job: options.expectedJob })) return null;\n\t\t\tconst latestJob = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\t\tconst latestMetadata = (latestJob?.metadata ?? {}) as MigrationMetadata;\n\t\t\tconst newlyRemoved = options.prunedTargetRows + options.cleanup.deleted;\n\t\t\tconst removed = mergedRemovedRows(latestMetadata, options.previouslyRemoved, newlyRemoved);\n\t\t\tconst retryReason =\n\t\t\t\toptions.validation.corpusRetryReason() ??\n\t\t\t\t(options.cleanup.exhausted ? options.validation.metadataRetryReason() : null);\n\t\t\tconst cleanupCompleted = options.cleanup.exhausted && !retryReason;\n\t\t\tconst exhaustedMaxRowId = cleanupCompleted ? options.cleanup.scannedMaxRowId : null;\n\t\t\tconst message = cleanupResultMessage({\n\t\t\t\tcompleted: cleanupCompleted,\n\t\t\t\tremoved,\n\t\t\t\tretryReason,\n\t\t\t\tcleanup: options.cleanup,\n\t\t\t});\n\t\t\tconst job = updateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\t\tstatus: \"completed\",\n\t\t\t\tmessage,\n\t\t\t\tmetadata: {\n\t\t\t\t\t...latestMetadata,\n\t\t\t\t\tremoved_stale_rows: removed,\n\t\t\t\t\tcleanup_pending: !cleanupCompleted,\n\t\t\t\t\tstale_scan_exhausted: cleanupCompleted || undefined,\n\t\t\t\t\tstale_scan_exhausted_max_rowid: exhaustedMaxRowId ?? undefined,\n\t\t\t\t\treconciliation_target_coverage_complete: undefined,\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn job ? { completed: cleanupCompleted, job } : null;\n\t\t})\n\t\t.immediate();\n}\n\nasync function yieldToCleanupInterrupts(): Promise<void> {\n\tawait new Promise<void>((resolve) => setImmediate(resolve));\n}\n\nfunction cleanupShouldPause(options: {\n\tsignal?: AbortSignal;\n\tshouldStop?: () => boolean;\n}): boolean {\n\tif (options.signal?.aborted) return true;\n\treturn options.shouldStop?.() === true;\n}\n\nasync function drainStaleModelVectors(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\toptions: {\n\t\texpectedJob: MigrationJob;\n\t\tvalidation: VectorCutoverValidation;\n\t\tpreviouslyRemoved: number;\n\t\tprunedTargetRows: number;\n\t\tsignal?: AbortSignal;\n\t\tshouldStop?: () => boolean;\n\t},\n): Promise<boolean> {\n\tlet prunedTargetRows = options.prunedTargetRows;\n\tlet expectedJob = options.expectedJob;\n\twhile (true) {\n\t\tconst cleanupJob = expectedJob;\n\t\tif (!isCurrentCleanupJob(db, targetModel, { job: cleanupJob })) return false;\n\t\tconst reason = options.validation.corpusRetryReason();\n\t\tif (reason) {\n\t\t\tdeferCompletedCleanup(\n\t\t\t\tdb,\n\t\t\t\t{ job: cleanupJob, targetModel },\n\t\t\t\toptions.previouslyRemoved,\n\t\t\t\tprunedTargetRows,\n\t\t\t\t\"Memory changes arrived during cleanup; retrying\",\n\t\t\t);\n\t\t\treturn false;\n\t\t}\n\t\tif (cleanupShouldPause(options)) {\n\t\t\tdeferCompletedCleanup(\n\t\t\t\tdb,\n\t\t\t\t{ job: cleanupJob, targetModel },\n\t\t\t\toptions.previouslyRemoved,\n\t\t\t\tprunedTargetRows,\n\t\t\t\t\"Cleanup paused during shutdown; retrying\",\n\t\t\t);\n\t\t\treturn false;\n\t\t}\n\t\tconst cleanup = deleteStaleModelVectors(db, targetModel, options.signal, {\n\t\t\tcleanupOwner: { job: cleanupJob },\n\t\t\tcheckFence: options.validation.corpusRetryReason,\n\t\t});\n\t\toptions.validation.noteOwnWrites();\n\t\tconst recorded = recordResumedCleanupResult(db, targetModel, {\n\t\t\texpectedJob: cleanupJob,\n\t\t\tcleanup,\n\t\t\tvalidation: options.validation,\n\t\t\tpreviouslyRemoved: options.previouslyRemoved,\n\t\t\tprunedTargetRows,\n\t\t});\n\t\toptions.validation.noteOwnWrites();\n\t\tif (!recorded) return false;\n\t\texpectedJob = recorded.job;\n\t\tif (recorded.completed) return true;\n\t\tif (cleanupShouldPause(options)) return false;\n\t\tif (cleanup.deleted === 0) return false;\n\t\tprunedTargetRows = 0;\n\t\tawait yieldToCleanupInterrupts();\n\t}\n}\n\ntype CompletedCleanupPassResult = {\n\tcontinueMigration: boolean;\n\trestartFromBeginning: boolean;\n\tstaleScanExhausted: boolean;\n\tvalidatedTargetCoverageComplete: boolean;\n};\n\nfunction acceptCompletedCleanupValidation(\n\tdb: SqliteDatabase,\n\toptions: {\n\t\toriginalJob: MigrationJob;\n\t\ttargetModel: string;\n\t\tvalidation: VectorCutoverValidation;\n\t\tpreviouslyRemoved: number;\n\t\tshouldStop?: () => boolean;\n\t},\n): boolean {\n\treturn db\n\t\t.transaction(() => {\n\t\t\tif (!isCurrentCleanupJob(db, options.targetModel, { job: options.originalJob })) return false;\n\t\t\tconst reason = options.validation.retryReason();\n\t\t\tif (reason || options.shouldStop?.()) {\n\t\t\t\tdeferCompletedCleanup(\n\t\t\t\t\tdb,\n\t\t\t\t\t{ job: options.originalJob, targetModel: options.targetModel },\n\t\t\t\t\toptions.previouslyRemoved,\n\t\t\t\t\toptions.validation.deleted,\n\t\t\t\t\treason ?? \"Cleanup paused during shutdown; retrying\",\n\t\t\t\t);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (options.validation.uncovered > 0) {\n\t\t\t\trestartMigrationForIncompleteCoverage(\n\t\t\t\t\tdb,\n\t\t\t\t\toptions.previouslyRemoved,\n\t\t\t\t\toptions.validation.deleted,\n\t\t\t\t\toptions.validation.uncovered,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn true;\n\t\t})\n\t\t.immediate();\n}\n\nfunction readCompletedScanFence(db: SqliteDatabase): string {\n\treturn JSON.stringify({\n\t\t...readVectorCorpusFence(db),\n\t\tdataVersion: Number(db.pragma(\"data_version\", { simple: true })),\n\t\ttotalChanges: Number(db.prepare(\"SELECT total_changes()\").pluck().get()),\n\t});\n}\n\nfunction prepareCompletedCleanupOwner(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\texpectedJob: MigrationJob,\n) {\n\tif (!isCurrentCleanupJob(db, targetModel, { job: expectedJob })) return null;\n\tconst metadata = (expectedJob?.metadata ?? {}) as MigrationMetadata;\n\tconst before = readCompletedScanFence(db);\n\t// Compatibility scans may walk the entire index; do not reserve the writer here.\n\tconst staleScan = checkCompletedStaleScan(db, targetModel, metadata);\n\treturn db\n\t\t.transaction(() => {\n\t\t\tif (!isCurrentCleanupJob(db, targetModel, { job: expectedJob })) return null;\n\t\t\tif (readCompletedScanFence(db) !== before) return null;\n\t\t\tif (staleScan.metadata !== metadata) {\n\t\t\t\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, { metadata: staleScan.metadata });\n\t\t\t}\n\t\t\tif (staleScan.canReturn) return null;\n\t\t\t// Keep the checked owner, including any watermark invalidation, across validation.\n\t\t\treturn {\n\t\t\t\tmetadata: staleScan.metadata,\n\t\t\t\tjob: getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB),\n\t\t\t};\n\t\t})\n\t\t.immediate();\n}\n\nasync function finishCompletedCleanupPass(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\tmetadata: MigrationMetadata,\n\toriginalJob: MigrationJob,\n\tsignal?: AbortSignal,\n\tshouldStop?: () => boolean,\n): Promise<CompletedCleanupPassResult> {\n\tconst stop: CompletedCleanupPassResult = {\n\t\tcontinueMigration: false,\n\t\trestartFromBeginning: false,\n\t\tstaleScanExhausted: false,\n\t\tvalidatedTargetCoverageComplete: false,\n\t};\n\tif (signal?.aborted) return stop;\n\n\tconst previouslyRemoved = Number(metadata.removed_stale_rows ?? 0);\n\tconst validation = prepareVectorCutoverValidation(db, targetModel, { signal, phase: \"cleanup-\" });\n\tconst prunedTargetRows = validation.deleted;\n\tlet accepted: boolean;\n\ttry {\n\t\taccepted = acceptCompletedCleanupValidation(db, {\n\t\t\toriginalJob,\n\t\t\ttargetModel,\n\t\t\tvalidation,\n\t\t\tpreviouslyRemoved,\n\t\t\tshouldStop,\n\t\t});\n\t\tif (!accepted) return stop;\n\t\tif (validation.uncovered > 0) {\n\t\t\treturn {\n\t\t\t\tcontinueMigration: true,\n\t\t\t\trestartFromBeginning: false,\n\t\t\t\tstaleScanExhausted: false,\n\t\t\t\tvalidatedTargetCoverageComplete: false,\n\t\t\t};\n\t\t}\n\t\tif (!metadata.cleanup_pending) {\n\t\t\treturn {\n\t\t\t\tcontinueMigration: true,\n\t\t\t\trestartFromBeginning: true,\n\t\t\t\tstaleScanExhausted: metadata.stale_scan_exhausted === true,\n\t\t\t\tvalidatedTargetCoverageComplete: false,\n\t\t\t};\n\t\t}\n\n\t\tconst cleanupCompleted = await drainStaleModelVectors(db, targetModel, {\n\t\t\texpectedJob: originalJob,\n\t\t\tvalidation,\n\t\t\tpreviouslyRemoved,\n\t\t\tprunedTargetRows,\n\t\t\tsignal,\n\t\t\tshouldStop,\n\t\t});\n\t\tif (!cleanupCompleted) return stop;\n\t\treturn {\n\t\t\tcontinueMigration: true,\n\t\t\trestartFromBeginning: true,\n\t\t\tstaleScanExhausted: true,\n\t\t\t// Cleanup yields between batches. Per-row deletes remain safe, but a\n\t\t\t// whole-corpus proof cannot be carried across those yields.\n\t\t\tvalidatedTargetCoverageComplete: false,\n\t\t};\n\t} finally {\n\t\tvalidation.close();\n\t}\n}\n\nfunction resolveMigrationStartMessage(\n\tsourceModel: string | null,\n\ttargetModel: string,\n\ttargetDisplay: string,\n): string {\n\tconst servesCompatibleLegacySource =\n\t\tsourceModel === LEGACY_DEFAULT_EMBEDDING_MODEL &&\n\t\ttargetModel === DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL;\n\tif (servesCompatibleLegacySource) {\n\t\treturn `Building ${targetDisplay} vectors while semantic search continues on the compatible legacy index`;\n\t}\n\tif (sourceModel) {\n\t\treturn `Building ${targetDisplay} vectors while semantic search uses FTS-only`;\n\t}\n\treturn `Building ${targetDisplay} vectors`;\n}\n\nfunction preservesCancelledMigration(job: MaintenanceJobSnapshot | null): boolean {\n\treturn (\n\t\tjob?.status === \"cancelled\" && job.metadata?.local_repair_preserves_migration_state === true\n\t);\n}\n\nfunction prepareMigrationJob(db: SqliteDatabase, job: MigrationJob): MigrationJob | undefined {\n\tif (!job || job.status === \"cancelled\" || !job.metadata?.local_repair_preserves_migration_state) {\n\t\treturn job;\n\t}\n\t// Failed jobs retry automatically. Only cancelled jobs keep the local-repair-only policy.\n\treturn db\n\t\t.transaction(() => {\n\t\t\tconst latestJob = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\t\tif (!sameMigrationJob(job, latestJob)) return undefined;\n\t\t\treturn updateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\t\tmetadata: { ...latestJob?.metadata, local_repair_preserves_migration_state: undefined },\n\t\t\t});\n\t\t})\n\t\t.immediate();\n}\n\nasync function resolveMigrationClient(\n\tdb: SqliteDatabase,\n\texistingJob: MaintenanceJobSnapshot | null,\n): Promise<EmbeddingClient | null> {\n\tconst isInFlightJob = isActiveMigrationJob(existingJob);\n\tif (isEmbeddingDisabled()) {\n\t\tif (isInFlightJob) {\n\t\t\twithMigrationJobOwner(db, existingJob, () =>\n\t\t\t\tfailMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, \"Embeddings are disabled\", {\n\t\t\t\t\tmessage: \"Vector re-indexing is waiting for embeddings to be enabled\",\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t...(existingJob?.metadata ?? {}),\n\t\t\t\t\t\treconciliation_target_coverage_complete: undefined,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\treturn null;\n\t}\n\tconst client = await getEmbeddingClient();\n\tif (!client) {\n\t\tif (isInFlightJob) {\n\t\t\twithMigrationJobOwner(db, existingJob, () =>\n\t\t\t\tfailMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, \"Embedding client unavailable\", {\n\t\t\t\t\tmessage: \"Vector re-indexing is waiting for the embedding client\",\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t...(existingJob?.metadata ?? {}),\n\t\t\t\t\t\treconciliation_target_coverage_complete: undefined,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\treturn null;\n\t}\n\treturn client;\n}\n\nasync function drainLocalRepairsWithoutResumingCancelledMigration(\n\tdb: SqliteDatabase,\n\tjob: MaintenanceJobSnapshot | null,\n\toptions: { batchSize?: number; signal?: AbortSignal },\n): Promise<boolean> {\n\tif (!job || !preservesCancelledMigration(job)) return false;\n\tif (pendingQueuedSyncCount(job.metadata ?? {}) === 0) return true;\n\tconst client = await resolveMigrationClient(db, job);\n\tif (!client) return true;\n\tawait runQueuedSyncVectorWork(\n\t\tdb,\n\t\tjob,\n\t\tclient,\n\t\tresolveEmbeddingClientVectorIdentityLabel(client),\n\t\tMath.max(1, options.batchSize ?? 50),\n\t\toptions.signal,\n\t);\n\treturn true;\n}\n\nexport async function runVectorMigrationPass(\n\tdb: SqliteDatabase,\n\toptions: { batchSize?: number; signal?: AbortSignal; shouldStop?: () => boolean } = {},\n): Promise<void> {\n\tawait runTrackedVectorMigrationPass(db, options, { job: null, failureHandled: false });\n}\n\nasync function runTrackedVectorMigrationPass(\n\tdb: SqliteDatabase,\n\toptions: { batchSize?: number; signal?: AbortSignal; shouldStop?: () => boolean },\n\towner: MigrationPassOwner,\n): Promise<void> {\n\towner.failureHandled = false;\n\ttry {\n\t\towner.job = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\tconst preparedJob = prepareMigrationJob(db, owner.job);\n\t\tif (preparedJob === undefined) return;\n\t\towner.job = preparedJob;\n\t\tawait runOwnedVectorMigrationPass(db, options, owner);\n\t} catch (error) {\n\t\trecordOwnedMigrationFailure(db, error, owner);\n\t\tthrow error;\n\t}\n}\n\nfunction recordOwnedMigrationFailure(\n\tdb: SqliteDatabase,\n\terror: unknown,\n\towner: MigrationPassOwner,\n): void {\n\towner.failureHandled = true;\n\t// Allocation failures leave the previous job intact, including its error.\n\tif (error instanceof VectorMigrationJobGenerationError || isTransientSqliteBusy(error)) return;\n\ttry {\n\t\trecordFailedMigrationJob(db, error, owner.job);\n\t} catch (writeError) {\n\t\tif (isTransientSqliteBusy(writeError)) {\n\t\t\tconsole.warn(\"Vector migration runner failed\", error);\n\t\t\tthrow writeError;\n\t\t}\n\t\tconsole.warn(\"Vector migration runner could not record its failure\", writeError);\n\t}\n}\n\nasync function runOwnedVectorMigrationPass(\n\tdb: SqliteDatabase,\n\toptions: { batchSize?: number; signal?: AbortSignal; shouldStop?: () => boolean },\n\towner: { job: MigrationJob },\n): Promise<void> {\n\tlet existingJob = owner.job;\n\tif (await drainLocalRepairsWithoutResumingCancelledMigration(db, existingJob, options)) return;\n\tconst client = await resolveMigrationClient(db, existingJob);\n\tif (!client) return;\n\tif (!withMigrationJobOwner(db, existingJob, () => true)) return;\n\tif (existingJob?.status === \"cancelled\") return;\n\tconst targetModel = resolveEmbeddingClientVectorIdentityLabel(client);\n\tconst requestedModel = client.model;\n\tconst requestedRevision = client.identity?.requestedRevision ?? client.identity?.revision;\n\tif (!requestedRevision) {\n\t\tthrow new TypeError(\"Embedding runtime identity is required to migrate persisted vectors\");\n\t}\n\tconst requestMetadata = {\n\t\trequested_model: requestedModel,\n\t\trequested_revision: requestedRevision,\n\t};\n\tconst targetDisplay = client.identity?.revision\n\t\t? `${client.model}@${client.identity.revision.slice(0, 12)}`\n\t\t: client.model;\n\tconst effectiveBatchSize = Math.max(1, options.batchSize ?? 50);\n\tconst existingMetadata = (existingJob?.metadata ?? {}) as MigrationMetadata;\n\tconst queuedSyncWorkCount =\n\t\tmetadataMemoryIds(existingMetadata.pending_upsert_memory_ids).length +\n\t\tmetadataMemoryIds(existingMetadata.pending_delete_memory_ids).length;\n\tlet restartCompletedMigration = false;\n\tlet reconciliationTargetCoverageComplete = false;\n\tconst completedMetadata = existingMetadata;\n\tif (\n\t\texistingJob?.status === \"completed\" &&\n\t\tcompletedMetadata.target_model === targetModel &&\n\t\tqueuedSyncWorkCount === 0\n\t) {\n\t\tconst cleanupOwner = prepareCompletedCleanupOwner(db, targetModel, existingJob);\n\t\tif (!cleanupOwner) return;\n\t\tconst cleanupResult = await finishCompletedCleanupPass(\n\t\t\tdb,\n\t\t\ttargetModel,\n\t\t\tcleanupOwner.metadata,\n\t\t\tcleanupOwner.job,\n\t\t\toptions.signal,\n\t\t\toptions.shouldStop,\n\t\t);\n\t\tif (\n\t\t\t!cleanupResult.continueMigration ||\n\t\t\toptions.signal?.aborted ||\n\t\t\t(cleanupResult.restartFromBeginning &&\n\t\t\t\t(cleanupResult.staleScanExhausted || !hasSourceModelVectors(db, targetModel)))\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\trestartCompletedMigration = cleanupResult.restartFromBeginning;\n\t\treconciliationTargetCoverageComplete = cleanupResult.validatedTargetCoverageComplete;\n\t\tconst refreshed = withMigrationJobOwner(db, existingJob, (latest) => latest);\n\t\tif (!refreshed) return;\n\t\texistingJob = refreshed;\n\t\towner.job = existingJob;\n\t}\n\tif (existingJob) {\n\t\tconst queuedSyncWork = await runQueuedSyncVectorWork(\n\t\t\tdb,\n\t\t\texistingJob,\n\t\t\tclient,\n\t\t\ttargetModel,\n\t\t\teffectiveBatchSize,\n\t\t\toptions.signal,\n\t\t);\n\t\tif (queuedSyncWork.completed || queuedSyncWork.superseded || options.signal?.aborted) {\n\t\t\treturn;\n\t\t}\n\t\tif (drainsQueuedSyncBeforeCutover(queuedSyncWork.metadata)) {\n\t\t\treturn;\n\t\t}\n\t\towner.job = queuedSyncWork.job ?? existingJob;\n\t\tconst refreshed = withMigrationJobOwner(db, owner.job, (latest) => latest);\n\t\tif (!refreshed) return;\n\t\texistingJob = refreshed;\n\t\towner.job = existingJob;\n\t}\n\tconst sourceModel = detectSourceModel(db, targetModel);\n\tconst hasInFlightJob = hasInFlightMigrationJob(existingJob);\n\t// An incremental job may finish when its queue drains. Full scans must\n\t// still visit every memory so backfillVectors can repair partial chunks.\n\tconst existingMeta = (existingJob?.metadata ?? {}) as MigrationMetadata;\n\tconst existingJobTrigger = existingMeta.trigger;\n\t// Bootstrap is a fresh corpus scan. An old row for each ID does not prove\n\t// current chunk coverage, especially for edits below the previous cursor.\n\tconst fromSyncTrigger = existingJobTrigger === SYNC_INCREMENTAL_TRIGGER;\n\tconst hasKnownIncompleteCoverage = Number(existingMeta.uncovered_target_memories ?? 0) > 0;\n\tif (!sourceModel && fromSyncTrigger && hasInFlightJob && !hasKnownIncompleteCoverage) {\n\t\tif (completeCoveredSyncJob(db, existingJob, targetModel, requestMetadata)) return;\n\t}\n\t// Use cached embeddable_total from an in-progress job to avoid a full table scan per tick.\n\t// Only recompute when starting a fresh migration or when the job is terminal.\n\tconst isResumingJob = isActiveMigrationJob(existingJob);\n\tconst embeddableTotal =\n\t\tisResumingJob && existingMeta.target_model === targetModel && existingMeta.embeddable_total\n\t\t\t? Number(existingMeta.embeddable_total)\n\t\t\t: countEmbeddableActiveMemories(db);\n\tif (embeddableTotal <= 0 && hasInFlightJob && !sourceModel) {\n\t\twithMigrationJobOwner(db, existingJob, () =>\n\t\t\tcompleteMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\t\tmessage: \"No embeddable memories to re-index\",\n\t\t\t\tprogressCurrent: 0,\n\t\t\t\tprogressTotal: 0,\n\t\t\t\tmetadata: {\n\t\t\t\t\t...existingMeta,\n\t\t\t\t\t...requestMetadata,\n\t\t\t\t\tlast_cursor_id: 0,\n\t\t\t\t\tprocessed_embeddable: 0,\n\t\t\t\t\tembeddable_total: 0,\n\t\t\t\t},\n\t\t\t}),\n\t\t);\n\t\treturn;\n\t}\n\tif (sourceModel && embeddableTotal <= 0) {\n\t\tcompleteEmptySourceMigration(db, existingJob, targetModel, sourceModel, requestMetadata);\n\t\treturn;\n\t}\n\n\tconst job = existingJob;\n\tlet metadata = nextMigrationMetadata(\n\t\tjob,\n\t\tsourceModel,\n\t\ttargetModel,\n\t\trequestedModel,\n\t\trequestedRevision,\n\t\tembeddableTotal,\n\t\t{\n\t\t\trestartFromBeginning: restartCompletedMigration,\n\t\t\treconciliationTargetCoverageComplete,\n\t\t},\n\t);\n\tif (!job || job.status === \"completed\" || job.status === \"failed\") {\n\t\tconst started = withMigrationJobOwner(db, job, (latest) =>\n\t\t\tstartVectorMigrationJob(db, {\n\t\t\t\ttitle: \"Re-indexing memories\",\n\t\t\t\tmessage: resolveMigrationStartMessage(sourceModel, targetModel, targetDisplay),\n\t\t\t\tprogressTotal: embeddableTotal,\n\t\t\t\tmetadata: {\n\t\t\t\t\t...metadata,\n\t\t\t\t\t...mergeQueuedSyncMemoryIds(latest?.metadata ?? {}, {\n\t\t\t\t\t\tupsertMemoryIds: [],\n\t\t\t\t\t\tdeleteMemoryIds: [],\n\t\t\t\t\t}),\n\t\t\t\t\tqueue_revision: latest?.metadata?.queue_revision,\n\t\t\t\t},\n\t\t\t}),\n\t\t);\n\t\tif (!started) return;\n\t\towner.job = started;\n\t\tmetadata = started.metadata as MigrationMetadata;\n\t}\n\n\tconst batchRows = selectNextMigrationBatch(db, metadata.last_cursor_id ?? 0, effectiveBatchSize);\n\tconst batchIds = batchRows.map((row) => row.id);\n\tconst embeddableInBatch = batchRows.filter(isEmbeddableMemory).length;\n\tconst lastCursorId = batchRows.at(-1)?.id ?? metadata.last_cursor_id ?? 0;\n\tconst processedEmbeddable = Math.min(\n\t\tembeddableTotal,\n\t\t(metadata.processed_embeddable ?? 0) + embeddableInBatch,\n\t);\n\n\tif (batchIds.length > 0) {\n\t\tawait backfillVectors(db, { memoryIds: batchIds, signal: options.signal, client });\n\t\t// If the signal fired mid-batch, backfillVectors may have processed\n\t\t// only a prefix of batchRows. Don't advance the cursor or mark the\n\t\t// job completed in that case — the next tick after restart needs to\n\t\t// re-process this batch from the same cursor to cover any rows the\n\t\t// abort skipped. Leave the metadata untouched.\n\t\tif (options.signal?.aborted) return;\n\t\tconst prunedCoveredRows = withMigrationJobOwner(db, owner.job, () =>\n\t\t\tpruneStaleCurrentModelVectors(db, batchIds, targetModel),\n\t\t);\n\t\tif (prunedCoveredRows === undefined) return;\n\t\tconst metadataAfterPrune: MigrationMetadata = {\n\t\t\t...metadata,\n\t\t\tremoved_stale_rows: Number(metadata.removed_stale_rows ?? 0) + prunedCoveredRows,\n\t\t};\n\t\tif (batchRows.length < effectiveBatchSize) {\n\t\t\tawait finalizeMigrationCutover(\n\t\t\t\tdb,\n\t\t\t\towner,\n\t\t\t\ttargetModel,\n\t\t\t\tmetadataAfterPrune,\n\t\t\t\tlastCursorId,\n\t\t\t\tprocessedEmbeddable,\n\t\t\t\tembeddableTotal,\n\t\t\t\toptions.signal,\n\t\t\t\toptions.shouldStop,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tdb.transaction(() => {\n\t\t\tconst latestJob = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\t\tif (!sameMigrationJob(owner.job, latestJob)) return;\n\t\t\tconst latestMetadata = (latestJob?.metadata ?? {}) as MigrationMetadata;\n\t\t\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\t\tstatus: \"running\",\n\t\t\t\tmessage: `Re-indexed ${processedEmbeddable} of ${embeddableTotal} memories with ${targetDisplay}`,\n\t\t\t\tprogressCurrent: processedEmbeddable,\n\t\t\t\tprogressTotal: embeddableTotal,\n\t\t\t\tmetadata: {\n\t\t\t\t\t...(sameQueuedSyncWork(latestMetadata, metadata) ? metadataAfterPrune : latestMetadata),\n\t\t\t\t\tremoved_stale_rows:\n\t\t\t\t\t\tNumber(latestMetadata.removed_stale_rows ?? metadata.removed_stale_rows ?? 0) +\n\t\t\t\t\t\tprunedCoveredRows,\n\t\t\t\t\tlast_cursor_id: lastCursorId,\n\t\t\t\t\tprocessed_embeddable: processedEmbeddable,\n\t\t\t\t\tembeddable_total: embeddableTotal,\n\t\t\t\t},\n\t\t\t});\n\t\t}).immediate();\n\t\treturn;\n\t}\n\n\tif (metadata.last_cursor_id && metadata.last_cursor_id > 0) {\n\t\tawait finalizeMigrationCutover(\n\t\t\tdb,\n\t\t\towner,\n\t\t\ttargetModel,\n\t\t\tmetadata,\n\t\t\tmetadata.last_cursor_id,\n\t\t\tembeddableTotal,\n\t\t\tembeddableTotal,\n\t\t\toptions.signal,\n\t\t\toptions.shouldStop,\n\t\t);\n\t}\n}\n\nfunction recordFailedMigrationJob(db: SqliteDatabase, error: unknown, owner: MigrationJob): void {\n\twithMigrationJobOwner(db, owner, (job) => {\n\t\tif (!job || job.status === \"cancelled\") return;\n\t\tconst metadata = job.metadata ?? {};\n\t\tfailMaintenanceJob(\n\t\t\tdb,\n\t\t\tVECTOR_MODEL_MIGRATION_JOB,\n\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t{ metadata: { ...metadata, reconciliation_target_coverage_complete: undefined } },\n\t\t);\n\t});\n}\n\n/**\n * Returns false only when the lock blocked the write, so the caller can try\n * again later. A job that is no longer in flight keeps its own message.\n */\nfunction writeLockWaitNotice(db: SqliteDatabase): boolean {\n\ttry {\n\t\tdb.transaction(() => {\n\t\t\tconst job = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\t\tif (job?.status !== \"running\" && job?.status !== \"pending\") return;\n\t\t\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, { message: LOCK_WAIT_MESSAGE });\n\t\t}).immediate();\n\t\treturn true;\n\t} catch (error) {\n\t\tif (isTransientSqliteBusy(error)) return false;\n\t\tthrow error;\n\t}\n}\n\nexport class VectorModelMigrationRunner {\n\tprivate readonly dbPath: string;\n\tprivate readonly signal?: AbortSignal;\n\tprivate readonly batchSize: number;\n\tprivate readonly intervalMs: number;\n\tprivate readonly idleIntervalMs: number;\n\tprivate readonly tickBudgetMs: number;\n\tprivate active = false;\n\tprivate timer: ReturnType<typeof setTimeout> | null = null;\n\tprivate currentRun: Promise<void> | null = null;\n\tprivate lastTickWasIdle = false;\n\tprivate consecutiveBusyTicks = 0;\n\tprivate lockNoticeWritten = false;\n\n\tconstructor(options: VectorModelMigrationOptions = {}) {\n\t\tthis.dbPath = resolveDbPath(options.dbPath);\n\t\tthis.signal = options.signal;\n\t\tthis.batchSize = Math.max(1, options.batchSize ?? 50);\n\t\tthis.intervalMs = Math.max(1000, options.intervalMs ?? 5000);\n\t\tthis.idleIntervalMs = Math.max(1000, options.idleIntervalMs ?? IDLE_INTERVAL_MS);\n\t\tthis.tickBudgetMs = Math.max(0, options.tickBudgetMs ?? 0);\n\t}\n\n\tstart(): void {\n\t\tif (this.active) return;\n\t\tthis.active = true;\n\t\tthis.lastTickWasIdle = false;\n\t\tactiveRunner = this;\n\t\tthis.schedule(100);\n\t}\n\n\tasync stop(): Promise<void> {\n\t\tthis.active = false;\n\t\tif (activeRunner === this) activeRunner = null;\n\t\tif (this.timer) {\n\t\t\tclearTimeout(this.timer);\n\t\t\tthis.timer = null;\n\t\t}\n\t\tif (this.currentRun) await this.currentRun;\n\t}\n\n\t/**\n\t * Pulls the runner out of its idle cadence and schedules an immediate\n\t * tick. Queue writers (sync bootstrap / incremental replication) call\n\t * this through {@link wakeActiveVectorMigrationRunner} so freshly\n\t * replicated memories don't sit unembedded for the full idle interval.\n\t */\n\twake(): void {\n\t\tif (!this.active) return;\n\t\tthis.lastTickWasIdle = false;\n\t\tif (this.timer) {\n\t\t\tclearTimeout(this.timer);\n\t\t\tthis.timer = null;\n\t\t\tthis.schedule(100);\n\t\t}\n\t}\n\n\tprivate schedule(delayMs: number): void {\n\t\tif (!this.active || this.signal?.aborted) return;\n\t\tthis.timer = setTimeout(() => {\n\t\t\tthis.timer = null;\n\t\t\tthis.currentRun = this.runOnce()\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tconsole.error(\"Vector migration runner tick failed:\", err);\n\t\t\t\t})\n\t\t\t\t.finally(() => {\n\t\t\t\t\tthis.currentRun = null;\n\t\t\t\t\tthis.schedule(this.nextDelayMs());\n\t\t\t\t});\n\t\t}, delayMs);\n\t\tif (typeof this.timer === \"object\" && \"unref\" in this.timer) this.timer.unref();\n\t}\n\n\tprivate nextDelayMs(): number {\n\t\tif (this.consecutiveBusyTicks > 0) return busyRetryDelayMs(this.consecutiveBusyTicks);\n\t\treturn this.lastTickWasIdle ? this.idleIntervalMs : this.intervalMs;\n\t}\n\n\tprivate async runOnce(): Promise<void> {\n\t\tif (!this.active || this.signal?.aborted) return;\n\t\tlet db: SqliteDatabase | null = null;\n\t\tlet owner: MigrationPassOwner | null = null;\n\t\ttry {\n\t\t\tdb = connect(this.dbPath) as SqliteDatabase;\n\t\t\towner = { job: getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB), failureHandled: false };\n\t\t\tloadSqliteVec(db);\n\t\t\tthis.lastTickWasIdle = await this.runPassesWithinBudget(db, owner);\n\t\t\tthis.consecutiveBusyTicks = 0;\n\t\t\tthis.lockNoticeWritten = false;\n\t\t} catch (error) {\n\t\t\tthis.handleOwnedTickFailure(db, error, owner);\n\t\t} finally {\n\t\t\tdb?.close();\n\t\t}\n\t}\n\n\t/**\n\t * Runs passes on one connection until the job goes idle, the runner stops,\n\t * or the tick budget is spent, and returns whether the last pass left the\n\t * job idle. Every pass commits its own short write transactions, and\n\t * inference runs outside them, so a longer tick does not lengthen any single\n\t * write transaction. It does run more of them per minute.\n\t */\n\tprivate async runPassesWithinBudget(\n\t\tdb: SqliteDatabase,\n\t\towner: MigrationPassOwner,\n\t): Promise<boolean> {\n\t\tconst deadline = Date.now() + this.tickBudgetMs;\n\t\twhile (true) {\n\t\t\tawait runTrackedVectorMigrationPass(\n\t\t\t\tdb,\n\t\t\t\t{\n\t\t\t\t\tbatchSize: this.batchSize,\n\t\t\t\t\tsignal: this.signal,\n\t\t\t\t\tshouldStop: () => !this.active,\n\t\t\t\t},\n\t\t\t\towner,\n\t\t\t);\n\t\t\towner.failureHandled = false;\n\t\t\towner.job = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\t\tconst idle = this.computeIdle(db);\n\t\t\tif (idle || !this.active || this.signal?.aborted || Date.now() >= deadline) return idle;\n\t\t\t// No transaction is open here. Let shutdown and timers run between batches.\n\t\t\tawait yieldToEventLoop();\n\t\t}\n\t}\n\n\tprivate handleOwnedTickFailure(\n\t\tdb: SqliteDatabase | null,\n\t\terror: unknown,\n\t\towner: MigrationPassOwner | null,\n\t): void {\n\t\ttry {\n\t\t\tif (db && owner && !owner.failureHandled) recordOwnedMigrationFailure(db, error, owner);\n\t\t} catch (writeError) {\n\t\t\tthis.handleTickFailure(db, writeError);\n\t\t\treturn;\n\t\t}\n\t\tthis.handleTickFailure(db, error);\n\t}\n\n\tprivate handleTickFailure(db: SqliteDatabase | null, error: unknown): void {\n\t\tif (isTransientSqliteBusy(error)) {\n\t\t\tthis.recordBusyTick(db, error);\n\t\t\treturn;\n\t\t}\n\t\tthis.consecutiveBusyTicks = 0;\n\t\tthis.lockNoticeWritten = false;\n\t\t// Treat exceptions as idle — a thrown tick is not going to unthrow\n\t\t// at 5s cadence. The failMaintenanceJob record captures the error;\n\t\t// the next tick at IDLE_INTERVAL_MS will retry.\n\t\tthis.lastTickWasIdle = true;\n\t\tconsole.warn(\"Vector migration runner failed\", error);\n\t}\n\n\t/**\n\t * Lock contention is transient, so the job keeps its status instead of\n\t * showing a failure, and the next tick runs well before the idle interval.\n\t */\n\tprivate recordBusyTick(db: SqliteDatabase | null, error: unknown): void {\n\t\tthis.consecutiveBusyTicks += 1;\n\t\tconst retrySeconds = busyRetryDelayMs(this.consecutiveBusyTicks) / 1000;\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconsole.warn(\n\t\t\t`Vector migration runner found the database locked (${message}); retrying in ${retrySeconds}s`,\n\t\t);\n\t\tthis.noteLongLockWait(db);\n\t}\n\n\t/**\n\t * Best effort, once per locked streak: the write itself needs the lock, so an\n\t * attempt blocked by the lock is retried on the next locked tick.\n\t */\n\tprivate noteLongLockWait(db: SqliteDatabase | null): void {\n\t\tif (!db || this.lockNoticeWritten) return;\n\t\tif (this.consecutiveBusyTicks < BUSY_TICKS_BEFORE_LOCK_NOTICE) return;\n\t\ttry {\n\t\t\tthis.lockNoticeWritten = writeLockWaitNotice(db);\n\t\t} catch (error) {\n\t\t\tconsole.warn(\"Vector migration runner could not record the lock wait\", error);\n\t\t\tthis.lockNoticeWritten = true;\n\t\t}\n\t}\n\n\tprivate computeIdle(db: SqliteDatabase): boolean {\n\t\t// Embeddings disabled → the pass returns immediately with no work\n\t\t// possible. Polling fast adds nothing.\n\t\tif (isEmbeddingDisabled()) return true;\n\t\tconst job = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\tif (job) {\n\t\t\t// Local repairs drain without resuming cancelled migrations.\n\t\t\t// Failed jobs retain their existing automatic retry behavior.\n\t\t\tconst meta = (job.metadata ?? {}) as MigrationMetadata;\n\t\t\tif (job.status === \"running\" || job.status === \"pending\") {\n\t\t\t\t// A cutover retry slows the runner because each retry re-runs full\n\t\t\t\t// validation scans. Queued incremental work drains before cutover,\n\t\t\t\t// so a retry count left over from an earlier attempt must not slow it.\n\t\t\t\tif (drainsQueuedSyncBeforeCutover(meta)) return false;\n\t\t\t\treturn Number(meta.cutover_retry_count ?? 0) > 0;\n\t\t\t}\n\t\t\tconst queued =\n\t\t\t\tmetadataMemoryIds(meta.pending_upsert_memory_ids).length +\n\t\t\t\tmetadataMemoryIds(meta.pending_delete_memory_ids).length;\n\t\t\tif (queued > 0) return false;\n\t\t\t// A completed job with cleanup still owed (bounded stale batch not yet\n\t\t\t// exhausted, or a deferred cleanup pass) is known work, not a quiet\n\t\t\t// database. Keep it on the active cadence so it finishes promptly.\n\t\t\treturn !meta.cleanup_pending || preservesCancelledMigration(job);\n\t\t}\n\t\t// No job row yet. Peek coverage directly to tell whether the first\n\t\t// tick on a fresh DB genuinely had nothing to do.\n\t\tconst targetModel = tryResolveEmbeddingVectorIdentityLabel();\n\t\tif (!targetModel) return true;\n\t\ttry {\n\t\t\tconst uncovered = db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT COUNT(*) AS c FROM memory_items\n\t\t\t\t\t WHERE active = 1\n\t\t\t\t\t AND TRIM(COALESCE(title, '') || COALESCE(body_text, '')) != ''\n\t\t\t\t\t AND id NOT IN (SELECT DISTINCT memory_id FROM memory_vectors WHERE model = ?)`,\n\t\t\t\t)\n\t\t\t\t.get(targetModel) as { c?: number } | undefined;\n\t\t\tif (Number(uncovered?.c ?? 0) > 0) return false;\n\t\t\treturn detectSourceModel(db, targetModel) === null;\n\t\t} catch (error) {\n\t\t\t// Don't silently tick fast forever on a query failure; log so it\n\t\t\t// shows up in dogfood logs. Conservatively treat as non-idle so\n\t\t\t// the next tick tries again at full cadence.\n\t\t\tconsole.warn(\"Vector migration runner idle peek failed\", error);\n\t\t\treturn false;\n\t\t}\n\t}\n}\n","import { realpathSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { posix } from \"node:path\";\n\nexport function normalizePortablePath(value: string): string {\n\tconst normalized = posix.normalize(value.replaceAll(\"\\\\\", \"/\"));\n\treturn normalized === \"/\" ? normalized : normalized.replace(/\\/+$/, \"\");\n}\n\nexport function comparablePortablePath(value: string): string {\n\treturn /^[A-Za-z]:\\//.test(value) ? value.toLowerCase() : value;\n}\n\nexport function resolveComparablePath(value: string): string {\n\ttry {\n\t\treturn comparablePortablePath(normalizePortablePath(realpathSync(value)));\n\t} catch {\n\t\treturn comparablePortablePath(normalizePortablePath(value));\n\t}\n}\n\nexport function normalizeInstallEntryPath(entryPath: string): string {\n\tif (!entryPath) return \"\";\n\ttry {\n\t\treturn normalizePortablePath(realpathSync(entryPath));\n\t} catch {\n\t\treturn normalizePortablePath(entryPath);\n\t}\n}\n\nfunction configuredMiseDataDirectories(env: Record<string, string | undefined>): string[] {\n\tconst explicitDataDirectory = env.MISE_DATA_DIR?.trim();\n\tif (explicitDataDirectory) return [explicitDataDirectory];\n\n\tconst candidates: string[] = [];\n\tconst xdgDataHome = env.XDG_DATA_HOME?.trim();\n\tif (xdgDataHome) return [posix.join(xdgDataHome, \"mise\")];\n\tconst localAppData = env.LOCALAPPDATA?.trim();\n\tif (localAppData) return [posix.join(localAppData, \"mise\")];\n\tconst home = env.HOME?.trim() || env.USERPROFILE?.trim() || homedir();\n\tif (home) candidates.push(posix.join(home, \".local/share/mise\"));\n\treturn candidates;\n}\n\nfunction versionUnderMiseDataDirectory(entryPath: string, dataDirectory: string): string | null {\n\tconst installPrefix = `${posix.join(\n\t\tresolveComparablePath(dataDirectory),\n\t\t\"installs/npm-codemem\",\n\t)}/`;\n\tif (!entryPath.startsWith(installPrefix)) return null;\n\tconst versionAndPath = entryPath.slice(installPrefix.length);\n\tconst separatorIndex = versionAndPath.indexOf(\"/\");\n\treturn separatorIndex > 0 ? versionAndPath.slice(0, separatorIndex) : null;\n}\n\nexport function miseInstallVersionFromPath(\n\tentryPath: string,\n\tenv: Record<string, string | undefined>,\n): string | null {\n\tconst comparableEntryPath = comparablePortablePath(normalizeInstallEntryPath(entryPath));\n\tfor (const dataDirectory of configuredMiseDataDirectories(env)) {\n\t\tconst version = versionUnderMiseDataDirectory(comparableEntryPath, dataDirectory);\n\t\tif (version) return version;\n\t}\n\tconst defaultMatch = /\\/mise\\/installs\\/npm-codemem\\/([^/]+)\\//.exec(comparableEntryPath);\n\tif (defaultMatch?.[1] !== undefined) return defaultMatch[1];\n\treturn null;\n}\n","import { randomUUID } from \"node:crypto\";\nimport { mkdir, open, readFile, rename, unlink } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { codememHomeDir } from \"./home.js\";\nimport {\n\tmiseInstallVersionFromPath,\n\tnormalizeInstallEntryPath,\n\tresolveComparablePath,\n} from \"./mise-install-path.js\";\n\nexport { resolveComparablePath };\n\nconst REGISTRY_URL_PREFIX = \"https://registry.npmjs.org/codemem/\";\nconst REQUEST_TIMEOUT_MS = 2_000;\nconst CACHE_MAX_AGE_MS = 6 * 60 * 60 * 1_000;\nconst FAILURE_RETRY_DELAY_MS = 15 * 60 * 1_000;\nconst MAX_RESPONSE_BYTES = 16 * 1_024;\nconst MAX_VERSION_LENGTH = 128;\nconst MAX_RUNNER_SOURCE_LENGTH = 4_096;\nconst RELEASE_CACHE_SCHEMA_VERSION = 2;\nconst AUTO_UPDATE_DELAY_MS = 24 * 60 * 60 * 1_000;\nconst SEMVER =\n\t/^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$/;\n\nexport type InstallKind =\n\t| \"npm-global\"\n\t| \"pnpm-global\"\n\t| \"mise\"\n\t| \"npx\"\n\t| \"docker\"\n\t| \"repo-dev\"\n\t| \"pinned\"\n\t| \"unknown\";\nexport type ReleaseChannel = \"alpha\" | \"beta\" | \"rc\" | \"latest\";\n\nconst KNOWN_INSTALL_KINDS: readonly InstallKind[] = [\n\t\"npm-global\",\n\t\"pnpm-global\",\n\t\"mise\",\n\t\"npx\",\n\t\"docker\",\n\t\"repo-dev\",\n\t\"pinned\",\n\t\"unknown\",\n];\n\nexport interface UpdateStatus {\n\tcurrent_version: string;\n\tchannel: ReleaseChannel | null;\n\tlatest_version: string | null;\n\tupdate_available: boolean;\n\tfirst_seen_at: string | null;\n\tchecked_at: string | null;\n\tstale: boolean;\n\tinstall_kind: InstallKind;\n\tauto_update_eligible: boolean;\n\trecommended_action: string;\n\terror: string | null;\n}\n\nexport function isExplicitUpdateInstallEligible(status: UpdateStatus): boolean {\n\tif (status.install_kind === \"npm-global\") return status.auto_update_eligible;\n\treturn (\n\t\t(status.install_kind === \"mise\" || status.install_kind === \"pnpm-global\") &&\n\t\tstatus.update_available &&\n\t\t!status.stale &&\n\t\tstatus.error === null\n\t);\n}\n\ninterface ReleaseCacheRecord {\n\tschema_version: typeof RELEASE_CACHE_SCHEMA_VERSION;\n\tchannel: ReleaseChannel;\n\tlatest_version: string;\n\tchecked_at: string;\n\tfirst_seen_at: string;\n}\n\nexport interface ReleaseCacheIo {\n\treadCache: () => Promise<string | null>;\n\twriteCacheAtomic: (contents: string) => Promise<void>;\n}\n\nexport interface InstallDetectionInput {\n\tentryPath: string;\n\tenv?: Record<string, string | undefined>;\n}\n\nexport interface ReleaseDiscoveryDependencies {\n\tfetch: (url: string, init?: RequestInit) => Promise<Response>;\n\tnow: () => Date;\n\treadCache: () => Promise<string | null>;\n\twriteCacheAtomic: (contents: string) => Promise<void>;\n\ttimeoutSignal: (milliseconds: number) => AbortSignal;\n}\n\nexport interface ReleaseCheckOptions {\n\tcurrentVersion: string;\n\tinstallKind: InstallKind;\n\trefresh?: boolean;\n}\n\nexport interface ReleaseDiscovery {\n\tcheck(options: ReleaseCheckOptions): Promise<UpdateStatus>;\n}\n\ninterface ReleaseResolution {\n\trecord: ReleaseCacheRecord | null;\n\tstale: boolean;\n\terror: string | null;\n}\n\ninterface ParsedSemver {\n\tcore: [number, number, number];\n\tprerelease: string[];\n}\n\ninterface ReleaseDiscoveryState {\n\tinFlight: Map<ReleaseChannel, Promise<ReleaseResolution>>;\n\tmemoryResolutions: Map<ReleaseChannel, { resolution: ReleaseResolution; resolvedAtMs: number }>;\n}\n\nfunction parseSemver(value: unknown): ParsedSemver | null {\n\tif (typeof value !== \"string\" || value.length === 0 || value.length > MAX_VERSION_LENGTH) {\n\t\treturn null;\n\t}\n\tconst match = SEMVER.exec(value);\n\tif (!match) return null;\n\tconst parts = match.slice(1, 4).map(Number);\n\tif (!parts.every(Number.isSafeInteger)) return null;\n\tconst prerelease = match[4]?.split(\".\") ?? [];\n\tif (prerelease.some((identifier) => /^\\d+$/.test(identifier) && /^0\\d/.test(identifier))) {\n\t\treturn null;\n\t}\n\treturn { core: parts as [number, number, number], prerelease };\n}\n\nexport function releaseChannelForVersion(value: unknown): ReleaseChannel | null {\n\tconst parsed = parseSemver(value);\n\tif (!parsed) return null;\n\tif (parsed.prerelease.length === 0) return \"latest\";\n\tconst channel = parsed.prerelease[0];\n\treturn channel === \"alpha\" || channel === \"beta\" || channel === \"rc\" ? channel : null;\n}\n\nexport function isReleaseVersionForChannel(\n\tvalue: unknown,\n\tchannel: ReleaseChannel,\n): value is string {\n\treturn releaseChannelForVersion(value) === channel;\n}\n\nexport function isStableReleaseVersion(value: unknown): value is string {\n\treturn releaseChannelForVersion(value) === \"latest\";\n}\n\nfunction comparePrereleaseIdentifier(left: string | undefined, right: string | undefined): number {\n\tif (left === undefined) return right === undefined ? 0 : -1;\n\tif (right === undefined) return 1;\n\tif (left === right) return 0;\n\tconst leftNumeric = /^\\d+$/.test(left);\n\tconst rightNumeric = /^\\d+$/.test(right);\n\tif (leftNumeric && rightNumeric && left.length !== right.length) {\n\t\treturn Math.sign(left.length - right.length);\n\t}\n\tif (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1;\n\treturn left < right ? -1 : 1;\n}\n\nfunction comparePrerelease(left: string[], right: string[]): number {\n\tif (left.length === 0) return right.length === 0 ? 0 : 1;\n\tif (right.length === 0) return -1;\n\tfor (let index = 0; index < Math.max(left.length, right.length); index += 1) {\n\t\tconst comparison = comparePrereleaseIdentifier(left[index], right[index]);\n\t\tif (comparison !== 0) return comparison;\n\t}\n\treturn 0;\n}\n\nfunction compareSemver(left: string, right: string): number | null {\n\tconst leftVersion = parseSemver(left);\n\tconst rightVersion = parseSemver(right);\n\tif (!leftVersion || !rightVersion) return null;\n\tfor (const index of [0, 1, 2] as const) {\n\t\tconst difference = leftVersion.core[index] - rightVersion.core[index];\n\t\tif (difference !== 0) return Math.sign(difference);\n\t}\n\treturn comparePrerelease(leftVersion.prerelease, rightVersion.prerelease);\n}\n\nfunction parseIsoTimestamp(value: unknown): string | null {\n\tif (typeof value !== \"string\") return null;\n\tconst timestamp = new Date(value);\n\treturn Number.isFinite(timestamp.getTime()) && timestamp.toISOString() === value ? value : null;\n}\n\nfunction parseCache(\n\tcontents: string | null,\n\tnow: Date,\n\tchannel: ReleaseChannel,\n): ReleaseCacheRecord | null {\n\tif (contents === null) return null;\n\ttry {\n\t\tconst value: unknown = JSON.parse(contents);\n\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\t\tconst candidate = value as Record<string, unknown>;\n\t\tconst isLegacyStableCache = candidate.schema_version === 1 && channel === \"latest\";\n\t\tif (!isLegacyStableCache && candidate.schema_version !== RELEASE_CACHE_SCHEMA_VERSION)\n\t\t\treturn null;\n\t\tconst cachedChannel = isLegacyStableCache ? \"latest\" : candidate.channel;\n\t\tif (cachedChannel !== channel) return null;\n\t\tconst latestVersion =\n\t\t\ttypeof candidate.latest_version === \"string\" &&\n\t\t\tisReleaseVersionForChannel(candidate.latest_version, channel)\n\t\t\t\t? candidate.latest_version\n\t\t\t\t: null;\n\t\tconst checkedAt = parseIsoTimestamp(candidate.checked_at);\n\t\tconst firstSeenAt = parseIsoTimestamp(candidate.first_seen_at);\n\t\tif (!latestVersion || !checkedAt || !firstSeenAt) return null;\n\t\tconst checkedTime = Date.parse(checkedAt);\n\t\tconst firstSeenTime = Date.parse(firstSeenAt);\n\t\tif (checkedTime > now.getTime() || firstSeenTime > checkedTime) return null;\n\t\treturn {\n\t\t\tschema_version: RELEASE_CACHE_SCHEMA_VERSION,\n\t\t\tchannel,\n\t\t\tlatest_version: latestVersion,\n\t\t\tchecked_at: checkedAt,\n\t\t\tfirst_seen_at: firstSeenAt,\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction isFresh(record: ReleaseCacheRecord, now: Date): boolean {\n\treturn now.getTime() - Date.parse(record.checked_at) < CACHE_MAX_AGE_MS;\n}\n\nfunction errorMessage(error: unknown): string {\n\tif (error instanceof Error && (error.name === \"AbortError\" || error.name === \"TimeoutError\")) {\n\t\treturn \"registry request timed out\";\n\t}\n\treturn error instanceof Error && error.message ? error.message : \"release discovery failed\";\n}\n\nasync function readBoundedResponseBody(response: Response): Promise<string> {\n\tconst contentLength = response.headers.get(\"content-length\");\n\tif (contentLength !== null) {\n\t\tif (!/^\\d+$/.test(contentLength)) {\n\t\t\tawait response.body?.cancel();\n\t\t\tthrow new Error(\"invalid registry response: invalid Content-Length\");\n\t\t}\n\t\tconst declaredBytes = Number(contentLength);\n\t\tif (!Number.isSafeInteger(declaredBytes) || declaredBytes > MAX_RESPONSE_BYTES) {\n\t\t\tawait response.body?.cancel();\n\t\t\tthrow new Error(\"invalid registry response: payload too large\");\n\t\t}\n\t}\n\tif (!response.body) throw new Error(\"invalid registry response: missing body\");\n\n\tconst reader = response.body.getReader();\n\tconst chunks: Uint8Array[] = [];\n\tlet receivedBytes = 0;\n\ttry {\n\t\twhile (true) {\n\t\t\tconst result = await reader.read();\n\t\t\tif (result.done) break;\n\t\t\treceivedBytes += result.value.byteLength;\n\t\t\tif (receivedBytes > MAX_RESPONSE_BYTES) {\n\t\t\t\tawait reader.cancel();\n\t\t\t\tthrow new Error(\"invalid registry response: payload too large\");\n\t\t\t}\n\t\t\tchunks.push(result.value);\n\t\t}\n\t} finally {\n\t\treader.releaseLock();\n\t}\n\n\tconst body = new Uint8Array(receivedBytes);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tbody.set(chunk, offset);\n\t\toffset += chunk.byteLength;\n\t}\n\ttry {\n\t\treturn new TextDecoder(\"utf-8\", { fatal: true }).decode(body);\n\t} catch {\n\t\tthrow new Error(\"invalid registry response payload\");\n\t}\n}\n\nasync function fetchLatestVersion(\n\tdeps: ReleaseDiscoveryDependencies,\n\tchannel: ReleaseChannel,\n): Promise<string> {\n\tconst registryUrl = `${REGISTRY_URL_PREFIX}${channel}`;\n\tconst response = await deps.fetch(registryUrl, {\n\t\theaders: { accept: \"application/json\" },\n\t\tredirect: \"error\",\n\t\tsignal: deps.timeoutSignal(REQUEST_TIMEOUT_MS),\n\t});\n\tif (!response.ok) {\n\t\tawait response.body?.cancel();\n\t\tthrow new Error(`registry request failed with status ${response.status}`);\n\t}\n\tif (response.url) {\n\t\tconst finalUrl = new URL(response.url);\n\t\tif (finalUrl.href !== registryUrl) {\n\t\t\tawait response.body?.cancel();\n\t\t\tthrow new Error(\"invalid registry response URL\");\n\t\t}\n\t}\n\tconst body = await readBoundedResponseBody(response);\n\tlet payload: unknown;\n\ttry {\n\t\tpayload = JSON.parse(body);\n\t} catch {\n\t\tthrow new Error(\"invalid registry response payload\");\n\t}\n\tif (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n\t\tthrow new Error(\"invalid registry response payload\");\n\t}\n\tconst version = (payload as Record<string, unknown>).version;\n\tif (typeof version !== \"string\" || !isReleaseVersionForChannel(version, channel)) {\n\t\tthrow new Error(\"invalid registry version\");\n\t}\n\treturn version;\n}\n\nfunction recommendedAction(\n\tinstallKind: InstallKind,\n\tcurrentVersion: string,\n\tlatestVersion: string | null,\n\tupdateAvailable: boolean,\n\tchannel: ReleaseChannel | null,\n): string {\n\tif (installKind === \"repo-dev\") {\n\t\treturn \"Package-release updates do not apply to repository source. Run git pull, pnpm install, and pnpm build in the codemem repository.\";\n\t}\n\tif (!channel || !isReleaseVersionForChannel(currentVersion, channel)) {\n\t\treturn \"Verify the current codemem version and try again.\";\n\t}\n\tif (!latestVersion) return \"Check network access and try again.\";\n\tif (!updateAvailable) {\n\t\tconst releaseLabel = channel === \"latest\" ? \"stable\" : channel;\n\t\treturn `No action required; codemem is on the latest ${releaseLabel} release.`;\n\t}\n\tswitch (installKind) {\n\t\tcase \"npm-global\":\n\t\t\treturn `${process.platform === \"linux\" ? \"env ONNXRUNTIME_NODE_INSTALL=skip \" : \"\"}npm install -g codemem@${latestVersion}`;\n\t\tcase \"pnpm-global\":\n\t\t\treturn `${process.platform === \"linux\" ? \"env ONNXRUNTIME_NODE_INSTALL=skip \" : \"\"}pnpm add -g codemem@${latestVersion} @codemem/embeddings@${latestVersion}`;\n\t\tcase \"mise\":\n\t\t\treturn process.platform === \"linux\"\n\t\t\t\t? `env ONNXRUNTIME_NODE_INSTALL=skip mise use -g npm:codemem@${latestVersion}`\n\t\t\t\t: `mise use -g npm:codemem@${latestVersion}`;\n\t\tcase \"npx\":\n\t\t\treturn `Update your launcher to request codemem@${latestVersion} and @codemem/embeddings@${latestVersion} together.`;\n\t\tcase \"docker\":\n\t\t\treturn `Set CODEMEM_VERSION=${latestVersion}, then run CODEMEM_VERSION=${latestVersion} docker compose build --pull and docker compose up -d.`;\n\t\tcase \"pinned\":\n\t\t\treturn `Update the pinned codemem version to ${latestVersion}, then restart codemem.`;\n\t\tdefault:\n\t\t\treturn `Update codemem to ${latestVersion} using your installation method.`;\n\t}\n}\n\nfunction hasNewerPackageRelease(\n\tinstallKind: InstallKind,\n\tcurrentVersion: string,\n\tlatestVersion: string | null,\n): boolean {\n\tif (installKind === \"repo-dev\" || latestVersion === null) return false;\n\tconst comparison = compareSemver(latestVersion, currentVersion);\n\treturn comparison !== null && comparison > 0;\n}\n\nfunction toStatus(\n\tresolution: ReleaseResolution,\n\toptions: ReleaseCheckOptions,\n\tchannel: ReleaseChannel | null,\n): UpdateStatus {\n\tconst latestVersion = resolution.record?.latest_version ?? null;\n\tconst updateAvailable = hasNewerPackageRelease(\n\t\toptions.installKind,\n\t\toptions.currentVersion,\n\t\tlatestVersion,\n\t);\n\treturn {\n\t\tcurrent_version: options.currentVersion,\n\t\tchannel,\n\t\tlatest_version: latestVersion,\n\t\tupdate_available: updateAvailable,\n\t\tfirst_seen_at: resolution.record?.first_seen_at ?? null,\n\t\tchecked_at: resolution.record?.checked_at ?? null,\n\t\tstale: resolution.stale,\n\t\tinstall_kind: options.installKind,\n\t\tauto_update_eligible:\n\t\t\toptions.installKind === \"npm-global\" &&\n\t\t\tupdateAvailable &&\n\t\t\t!resolution.stale &&\n\t\t\tresolution.error === null &&\n\t\t\tresolution.record !== null &&\n\t\t\tDate.parse(resolution.record.checked_at) - Date.parse(resolution.record.first_seen_at) >=\n\t\t\t\tAUTO_UPDATE_DELAY_MS,\n\t\trecommended_action: recommendedAction(\n\t\t\toptions.installKind,\n\t\t\toptions.currentVersion,\n\t\t\tlatestVersion,\n\t\t\tupdateAvailable,\n\t\t\tchannel,\n\t\t),\n\t\terror: resolution.error,\n\t};\n}\n\nfunction canReuseMemoryResolution(\n\tstate: ReleaseDiscoveryState,\n\tchannel: ReleaseChannel,\n\tnow: Date,\n): boolean {\n\tconst memoryResolution = state.memoryResolutions.get(channel);\n\tif (!memoryResolution) return false;\n\tconst ageMs = Math.max(0, now.getTime() - memoryResolution.resolvedAtMs);\n\tconst { resolution } = memoryResolution;\n\tif (resolution.record && !resolution.stale && isFresh(resolution.record, now)) return true;\n\treturn resolution.error !== null && ageMs < FAILURE_RETRY_DELAY_MS;\n}\n\nasync function refreshRelease(\n\tdeps: ReleaseDiscoveryDependencies,\n\tcached: ReleaseCacheRecord | null,\n\tnow: Date,\n\tchannel: ReleaseChannel,\n): Promise<ReleaseResolution> {\n\ttry {\n\t\tconst latestVersion = await fetchLatestVersion(deps, channel);\n\t\tconst timestamp = now.toISOString();\n\t\tconst record: ReleaseCacheRecord = {\n\t\t\tschema_version: RELEASE_CACHE_SCHEMA_VERSION,\n\t\t\tchannel,\n\t\t\tlatest_version: latestVersion,\n\t\t\tchecked_at: timestamp,\n\t\t\tfirst_seen_at: cached?.latest_version === latestVersion ? cached.first_seen_at : timestamp,\n\t\t};\n\t\ttry {\n\t\t\tawait deps.writeCacheAtomic(JSON.stringify(record));\n\t\t\treturn { record, stale: false, error: null };\n\t\t} catch (error) {\n\t\t\treturn { record, stale: false, error: `cache write failed: ${errorMessage(error)}` };\n\t\t}\n\t} catch (error) {\n\t\treturn { record: cached, stale: cached !== null, error: errorMessage(error) };\n\t}\n}\n\nfunction withCacheReadError(\n\tresolution: ReleaseResolution,\n\tcacheReadError: string | null,\n): ReleaseResolution {\n\treturn cacheReadError && !resolution.error\n\t\t? { ...resolution, error: cacheReadError }\n\t\t: resolution;\n}\n\nasync function readReleaseCache(\n\tdeps: ReleaseDiscoveryDependencies,\n\tnow: Date,\n\tchannel: ReleaseChannel,\n): Promise<{ cached: ReleaseCacheRecord | null; error: string | null }> {\n\ttry {\n\t\treturn { cached: parseCache(await deps.readCache(), now, channel), error: null };\n\t} catch (error) {\n\t\treturn { cached: null, error: `cache read failed: ${errorMessage(error)}` };\n\t}\n}\n\nasync function checkRelease(\n\tdeps: ReleaseDiscoveryDependencies,\n\tstate: ReleaseDiscoveryState,\n\toptions: ReleaseCheckOptions,\n): Promise<UpdateStatus> {\n\tconst now = deps.now();\n\tconst channel = releaseChannelForVersion(options.currentVersion);\n\tif (!channel) {\n\t\treturn toStatus(\n\t\t\t{ record: null, stale: false, error: \"unsupported installed release channel\" },\n\t\t\toptions,\n\t\t\tnull,\n\t\t);\n\t}\n\tconst cache = await readReleaseCache(deps, now, channel);\n\tif (!options.refresh && cache.cached && isFresh(cache.cached, now)) {\n\t\treturn toStatus({ record: cache.cached, stale: false, error: null }, options, channel);\n\t}\n\tconst memoryResolution = state.memoryResolutions.get(channel);\n\tif (!options.refresh && memoryResolution && canReuseMemoryResolution(state, channel, now)) {\n\t\treturn toStatus(withCacheReadError(memoryResolution.resolution, cache.error), options, channel);\n\t}\n\tlet request = state.inFlight.get(channel);\n\tif (!request) {\n\t\trequest = refreshRelease(deps, cache.cached, now, channel).finally(() => {\n\t\t\tstate.inFlight.delete(channel);\n\t\t});\n\t\tstate.inFlight.set(channel, request);\n\t}\n\tconst resolution = await request;\n\tstate.memoryResolutions.set(channel, { resolution, resolvedAtMs: deps.now().getTime() });\n\treturn toStatus(withCacheReadError(resolution, cache.error), options, channel);\n}\n\nexport function createReleaseDiscovery(deps: ReleaseDiscoveryDependencies): ReleaseDiscovery {\n\tconst state: ReleaseDiscoveryState = {\n\t\tinFlight: new Map(),\n\t\tmemoryResolutions: new Map(),\n\t};\n\treturn { check: (options) => checkRelease(deps, state, options) };\n}\n\nfunction defaultCachePath(): string {\n\treturn join(codememHomeDir(), \".codemem\", \"release-discovery.json\");\n}\n\nexport function createReleaseCacheIo(cachePath: string): ReleaseCacheIo {\n\tconst directory = dirname(cachePath);\n\treturn {\n\t\tasync readCache(): Promise<string | null> {\n\t\t\ttry {\n\t\t\t\treturn await readFile(cachePath, \"utf8\");\n\t\t\t} catch (error) {\n\t\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\tasync writeCacheAtomic(contents: string): Promise<void> {\n\t\t\tawait mkdir(directory, { recursive: true, mode: 0o700 });\n\t\t\tconst temporaryPath = join(\n\t\t\t\tdirectory,\n\t\t\t\t`.release-discovery.${process.pid}.${randomUUID()}.tmp`,\n\t\t\t);\n\t\t\tlet handle: Awaited<ReturnType<typeof open>> | null = null;\n\t\t\ttry {\n\t\t\t\thandle = await open(temporaryPath, \"wx\", 0o600);\n\t\t\t\tawait handle.writeFile(contents, \"utf8\");\n\t\t\t\tawait handle.sync();\n\t\t\t\tawait handle.close();\n\t\t\t\thandle = null;\n\t\t\t\tawait rename(temporaryPath, cachePath);\n\t\t\t} catch (error) {\n\t\t\t\tawait handle?.close().catch(() => undefined);\n\t\t\t\tawait unlink(temporaryPath).catch(() => undefined);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t};\n}\n\nfunction isPinnedSource(source: string): boolean {\n\tif (!source || source.length > MAX_RUNNER_SOURCE_LENGTH) return false;\n\tconst containsWhitespace = (value: string): boolean => {\n\t\tfor (const character of value) {\n\t\t\tif (character.trim() === \"\") return true;\n\t\t}\n\t\treturn false;\n\t};\n\tconst normalized = source.toLowerCase();\n\tif (normalized.startsWith(\"codemem@\")) {\n\t\tconst requested = source.slice(\"codemem@\".length);\n\t\treturn (\n\t\t\trequested.length > 0 &&\n\t\t\t!containsWhitespace(requested) &&\n\t\t\t![\"latest\", \"next\", \"*\"].includes(requested.toLowerCase())\n\t\t);\n\t}\n\tif (!source.startsWith(\"git+\") && !source.includes(\".git\")) return false;\n\tconst queryIndex = source.indexOf(\"?\");\n\tconst fragmentIndex = source.indexOf(\"#\");\n\tconst boundaryIndexes = [queryIndex, fragmentIndex].filter((index) => index >= 0);\n\tconst boundary = boundaryIndexes.length > 0 ? Math.min(...boundaryIndexes) : source.length;\n\tconst withoutQuery = source.slice(0, boundary);\n\tconst gitRefIndex = withoutQuery.toLowerCase().lastIndexOf(\".git@\");\n\tconst gitRef = gitRefIndex >= 0 ? withoutQuery.slice(gitRefIndex + \".git@\".length) : \"\";\n\tif (gitRef.length > 0 && !gitRef.includes(\"/\") && !containsWhitespace(gitRef)) return true;\n\tconst fragment = fragmentIndex >= 0 ? source.slice(fragmentIndex + 1) : \"\";\n\treturn fragment.length > 0 && !containsWhitespace(fragment);\n}\n\nfunction miseInstallKindForPath(\n\tentryPath: string,\n\tenv: Record<string, string | undefined>,\n): \"mise\" | \"unknown\" | null {\n\tconst version = miseInstallVersionFromPath(entryPath, env);\n\tif (version === null) return null;\n\treturn parseSemver(version) === null ? \"unknown\" : \"mise\";\n}\n\nfunction narrowedInstallKind(\n\tentryPath: string,\n\texplicit: string,\n\tenv: Record<string, string | undefined>,\n): InstallKind | null {\n\tif (!explicit) return null;\n\tif (!KNOWN_INSTALL_KINDS.includes(explicit as InstallKind)) return \"unknown\";\n\tif (explicit === \"mise\" && miseInstallKindForPath(entryPath, env) !== \"mise\") return \"unknown\";\n\tif ([\"docker\", \"repo-dev\", \"pinned\", \"unknown\"].includes(explicit)) {\n\t\treturn explicit as InstallKind;\n\t}\n\treturn null;\n}\n\nfunction runnerInstallKind(runner: string): InstallKind | null {\n\treturn runner === \"node\" || runner === \"uv\" ? \"repo-dev\" : null;\n}\n\nfunction pnpmVirtualStoreVersion(packagePath: string): string | null {\n\tconst match =\n\t\t/^\\.pnpm\\/codemem@([^/_]+)(?:_[^/]+)?\\/node_modules\\/codemem\\/dist\\/index\\.js$/i.exec(\n\t\t\tpackagePath,\n\t\t);\n\treturn match?.[1] && parseSemver(match[1]) !== null ? match[1] : null;\n}\n\nfunction pnpmGlobalRelativePath(\n\tentryPath: string,\n\tenv: Record<string, string | undefined>,\n): string | null {\n\tconst pnpmHome = env.PNPM_HOME?.trim();\n\tif (pnpmHome) {\n\t\tconst prefix = `${resolveComparablePath(pnpmHome)}/global/`;\n\t\treturn entryPath.startsWith(prefix) ? entryPath.slice(prefix.length) : null;\n\t}\n\tconst marker = \"/pnpm/global/\";\n\tconst markerIndex = entryPath.indexOf(marker);\n\treturn markerIndex >= 0 ? entryPath.slice(markerIndex + marker.length) : null;\n}\n\nfunction isPnpmGlobalEntryPath(\n\tentryPath: string,\n\tenv: Record<string, string | undefined>,\n): boolean {\n\tconst relativePath = pnpmGlobalRelativePath(entryPath, env);\n\tif (!relativePath) return false;\n\tconst layout = /^(?:[1-9]\\d*\\/|v[1-9]\\d*\\/[^/]+\\/node_modules\\/)/i.exec(relativePath);\n\tif (!layout) return false;\n\treturn pnpmVirtualStoreVersion(relativePath.slice(layout[0].length)) !== null;\n}\n\nfunction isPnpmDlxEntryPath(entryPath: string): boolean {\n\tconst match =\n\t\t/\\/(?:pnpm\\/dlx\\/[^/]+\\/[^/]+|\\.pnpm\\/dlx\\/[^/]+)\\/node_modules\\/(\\.pnpm\\/codemem@.+)$/i.exec(\n\t\t\tentryPath,\n\t\t);\n\treturn match?.[1] !== undefined && pnpmVirtualStoreVersion(match[1]) !== null;\n}\n\nfunction installKindForEntryPath(\n\tentryPath: string,\n\tenv: Record<string, string | undefined>,\n): InstallKind {\n\tconst miseInstallKind = miseInstallKindForPath(entryPath, env);\n\tif (miseInstallKind) return miseInstallKind;\n\tif (/\\/_npx\\//.test(entryPath) || isPnpmDlxEntryPath(entryPath)) return \"npx\";\n\tif (/\\/installs\\/npm-codemem\\/[^/]+\\//.test(entryPath)) return \"unknown\";\n\tif (isPnpmGlobalEntryPath(resolveComparablePath(entryPath), env)) return \"pnpm-global\";\n\tif (/\\/lib\\/node_modules\\/codemem\\/dist\\/index\\.js$/.test(entryPath)) return \"npm-global\";\n\tif (/\\/AppData\\/Roaming\\/npm\\/node_modules\\/codemem\\/dist\\/index\\.js$/i.test(entryPath)) {\n\t\treturn \"npm-global\";\n\t}\n\treturn \"unknown\";\n}\n\nexport function detectInstallKind(input: InstallDetectionInput): InstallKind {\n\tconst env = input.env ?? {};\n\tconst source = env.CODEMEM_RUNNER_FROM?.trim() ?? \"\";\n\tif (isPinnedSource(source)) return \"pinned\";\n\n\tconst entryPath = normalizeInstallEntryPath(input.entryPath);\n\tif (/\\/packages\\/cli\\/src\\/index\\.ts$/.test(entryPath)) return \"repo-dev\";\n\n\tconst explicit = env.CODEMEM_INSTALL_KIND?.trim().toLowerCase();\n\tconst narrowedKind = narrowedInstallKind(entryPath, explicit ?? \"\", env);\n\tif (narrowedKind) return narrowedKind;\n\n\tconst runner = env.CODEMEM_RUNNER?.trim().toLowerCase();\n\treturn runnerInstallKind(runner ?? \"\") ?? installKindForEntryPath(entryPath, env);\n}\n\nconst defaultReleaseDiscovery = createReleaseDiscovery({\n\tfetch: (url, init) => fetch(url, init),\n\tnow: () => new Date(),\n\treadCache: () => createReleaseCacheIo(defaultCachePath()).readCache(),\n\twriteCacheAtomic: (contents) =>\n\t\tcreateReleaseCacheIo(defaultCachePath()).writeCacheAtomic(contents),\n\ttimeoutSignal: (milliseconds) => AbortSignal.timeout(milliseconds),\n});\n\nexport interface GetUpdateStatusOptions {\n\tcurrentVersion: string;\n\tinstallKind?: InstallKind;\n\trefresh?: boolean;\n}\n\nexport function getUpdateStatus(options: GetUpdateStatusOptions): Promise<UpdateStatus> {\n\treturn defaultReleaseDiscovery.check({\n\t\tcurrentVersion: options.currentVersion,\n\t\tinstallKind: options.installKind ?? \"unknown\",\n\t\trefresh: options.refresh,\n\t});\n}\n","/**\n * Sync bootstrap: client-side snapshot consumer for re-bootstrapping\n * shared memories from a peer when the incremental op log is no longer\n * sufficient (generation mismatch, stale cursor beyond retained floor).\n *\n * The bootstrap protocol:\n * 1. Fetch paginated snapshot pages from GET /v1/snapshot\n * 2. Collect all canonical shared memory items (including tombstones)\n * 3. In a single transaction: wipe local synced memories for the requested\n * scope, apply snapshot, update replication cursor to baseline_cursor,\n * bump generation\n */\n\nimport { and, eq, inArray, isNotNull, isNull, ne, or, sql } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport type { ApiSyncMemorySnapshotPageResponse } from \"./api-types.js\";\nimport type { Database } from \"./db.js\";\nimport { toJson } from \"./db.js\";\nimport { recordForeignMemoryRevision } from \"./memory-creation-provenance.js\";\nimport { retirementAllowsSnapshot } from \"./memory-retirement-snapshot-guard.js\";\nimport * as schema from \"./schema.js\";\nimport { redactMemoryFields, SecretScanner } from \"./secret-scanner.js\";\nimport { snapshotSessionExportKeysForMemoryIds } from \"./session-export-identity-mutation.js\";\nimport { buildAuthHeaders, buildDirectPeerAuthHeaders } from \"./sync-auth.js\";\nimport { SYNC_BOOTSTRAP_CWD_PREFIX } from \"./sync-bootstrap-constants.js\";\nimport { LOCAL_SYNC_CAPABILITY, SYNC_CAPABILITY_HEADER } from \"./sync-capability.js\";\nimport { type RequestJsonExecutor, requestJson } from \"./sync-http-client.js\";\nimport {\n\tclearReplicationCursorLastApplied,\n\tclockDeviceIdFromMetadataJson,\n\tDEFAULT_SYNC_SCOPE_ID,\n\tisNewerClock,\n\tSCOPED_NULL_BASELINE_BOOTSTRAP_CURSOR_MARKER,\n\tsetReplicationCursor,\n\tsetSyncResetState,\n} from \"./sync-replication.js\";\nimport {\n\trecordSyncTransferObservation,\n\trecordSyncTransferReceipts,\n} from \"./sync-transfer-activity.js\";\nimport type { SyncMemorySnapshotItem, SyncResetRequired } from \"./types.js\";\nimport { queueVectorBackfillForSyncBootstrap } from \"./vector-migration.js\";\n\nexport { SYNC_BOOTSTRAP_CWD_PREFIX } from \"./sync-bootstrap-constants.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface BootstrapResult {\n\tok: boolean;\n\tapplied: number;\n\tdeleted: number;\n\terror?: string;\n}\n\nexport interface BootstrapApplicationOptions {\n\tactivityOptions?: { preserveError?: boolean };\n\tcursorPolicy?: \"preserve\";\n}\n\ninterface ExistingSnapshotRow {\n\tid: number;\n\trev: number | null;\n\tupdated_at: string;\n\tmetadata_json: string | null;\n}\n\nexport interface BootstrapOptions {\n\trequestExecutor?: RequestJsonExecutor;\n\t/** Source-only snapshots require recipient-bound transport and additive application. */\n\tsourceDeviceId?: string;\n\tkeysDir?: string;\n\tdbPath?: string;\n\tbootstrapGrantId?: string;\n\t/** Direct peer identity used to add recipient-bound v3 auth headers. */\n\trecipientId?: string;\n\t/** Max items per page request. Defaults to 200. */\n\tpageSize?: number;\n\t/** Timeout per HTTP request in seconds. Defaults to 10. */\n\ttimeoutS?: number;\n\t/** Safety cap on total snapshot items. Defaults to 100,000. */\n\tmaxItems?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Snapshot page fetcher\n// ---------------------------------------------------------------------------\n\ntype SnapshotPageResponse = ApiSyncMemorySnapshotPageResponse;\n\nfunction checkedSnapshotBoundary(\n\tpage: SnapshotPageResponse & { source_device_id?: unknown },\n\texpected: SyncResetRequired,\n\tsourceDeviceId?: string,\n) {\n\tif (sourceDeviceId && page.source_device_id !== sourceDeviceId)\n\t\tthrow new Error(\"retirement_snapshot_source_required\");\n\tif (\n\t\tpage.generation !== expected.generation ||\n\t\tpage.snapshot_id !== expected.snapshot_id ||\n\t\tpage.baseline_cursor !== expected.baseline_cursor\n\t)\n\t\tthrow new Error(\"snapshot_boundary_mismatch\");\n\treturn {\n\t\tgeneration: page.generation,\n\t\tsnapshot_id: page.snapshot_id,\n\t\tbaseline_cursor: page.baseline_cursor,\n\t};\n}\n\nfunction snapshotPageParams(\n\tresetInfo: SyncResetRequired,\n\tpageSize: number,\n\tpageToken: string | null,\n\tsourceDeviceId?: string,\n) {\n\tconst params = new URLSearchParams({\n\t\tgeneration: String(resetInfo.generation),\n\t\tsnapshot_id: resetInfo.snapshot_id,\n\t\tlimit: String(pageSize),\n\t});\n\tif (sourceDeviceId) params.set(\"source_device_id\", sourceDeviceId);\n\tif (resetInfo.baseline_cursor) params.set(\"baseline_cursor\", resetInfo.baseline_cursor);\n\tif (resetInfo.scope_id) params.set(\"scope_id\", resetInfo.scope_id);\n\tif (pageToken) params.set(\"page_token\", pageToken);\n\treturn params;\n}\n\nfunction checkedSnapshotSource(options?: BootstrapOptions): string | undefined {\n\tconst source = options?.sourceDeviceId;\n\tif (source !== undefined && (!source || source !== options?.recipientId?.trim()))\n\t\tthrow new Error(\"retirement_snapshot_source_required\");\n\treturn source;\n}\n\nfunction snapshotRequestExecutor(options?: BootstrapOptions): RequestJsonExecutor {\n\treturn options?.requestExecutor ?? requestJson;\n}\n\n/**\n * Fetch all snapshot pages from a peer's /v1/snapshot endpoint.\n * Returns the full list of items and the boundary metadata.\n */\nexport async function fetchAllSnapshotPages(\n\tbaseUrl: string,\n\tresetInfo: SyncResetRequired,\n\tdeviceId: string,\n\toptions?: BootstrapOptions,\n): Promise<{\n\titems: SyncMemorySnapshotItem[];\n\tgeneration: number;\n\tsnapshot_id: string;\n\tbaseline_cursor: string | null;\n}> {\n\tconst pageSize = options?.pageSize ?? 200;\n\tconst timeoutS = options?.timeoutS ?? 10;\n\tconst requestExecutor = snapshotRequestExecutor(options);\n\tconst keysDir = options?.keysDir;\n\tconst dbPath = options?.dbPath;\n\tconst bootstrapGrantId = options?.bootstrapGrantId?.trim() || undefined;\n\tconst recipientId = options?.recipientId?.trim() || undefined;\n\tconst maxItems = options?.maxItems ?? 100_000;\n\tconst sourceDeviceId = checkedSnapshotSource(options);\n\n\tconst allItems: SyncMemorySnapshotItem[] = [];\n\tlet pageToken: string | null = null;\n\tlet boundary: { generation: number; snapshot_id: string; baseline_cursor: string | null } | null =\n\t\tnull;\n\n\tfor (;;) {\n\t\tconst params = snapshotPageParams(resetInfo, pageSize, pageToken, sourceDeviceId);\n\n\t\tconst url = `${baseUrl}/v1/snapshot?${params.toString()}`;\n\t\tconst authOptions = {\n\t\t\tdeviceId,\n\t\t\tmethod: \"GET\",\n\t\t\turl,\n\t\t\tbodyBytes: Buffer.alloc(0),\n\t\t\tbootstrapGrantId,\n\t\t\tkeysDir,\n\t\t\tdbPath,\n\t\t};\n\t\tconst headers = {\n\t\t\t// Public callers that omit a recipient retain the legacy v2 wire contract. All\n\t\t\t// in-repo direct-peer callers provide recipientId and therefore emit v3.\n\t\t\t...(recipientId === undefined\n\t\t\t\t? buildAuthHeaders(authOptions)\n\t\t\t\t: buildDirectPeerAuthHeaders({ ...authOptions, recipientId })),\n\t\t\t[SYNC_CAPABILITY_HEADER]: LOCAL_SYNC_CAPABILITY,\n\t\t};\n\n\t\tconst [status, payload] = await requestExecutor(\"GET\", url, { headers, timeoutS });\n\t\tif (status !== 200 || !payload) {\n\t\t\tconst error = payload?.error ? String(payload.error) : \"\";\n\t\t\tconst reason = payload?.reason ? String(payload.reason) : \"\";\n\t\t\tconst detail = error ? (reason ? `${error}:${reason}` : error) : `status ${status}`;\n\t\t\tthrow new Error(`snapshot fetch failed: ${detail}`);\n\t\t}\n\n\t\tconst page = payload as unknown as SnapshotPageResponse;\n\t\tif (!Array.isArray(page.items) || page.generation == null) {\n\t\t\tthrow new Error(\"invalid snapshot response shape\");\n\t\t}\n\n\t\tboundary = checkedSnapshotBoundary(page, resetInfo, sourceDeviceId);\n\t\tallItems.push(...page.items);\n\n\t\tif (allItems.length > maxItems) {\n\t\t\tthrow new Error(\n\t\t\t\t`snapshot too large: ${allItems.length} items exceeds safety limit of ${maxItems}`,\n\t\t\t);\n\t\t}\n\n\t\tif (!page.has_more || !page.next_page_token) {\n\t\t\tbreak;\n\t\t}\n\t\tpageToken = page.next_page_token;\n\t}\n\n\tif (!boundary) {\n\t\tthrow new Error(\"no snapshot pages returned\");\n\t}\n\n\treturn { items: allItems, ...boundary };\n}\n\n// ---------------------------------------------------------------------------\n// Local application\n// ---------------------------------------------------------------------------\n\n/**\n * Parse a snapshot item's payload_json into memory fields.\n * Returns null if the payload is malformed.\n */\nfunction parseSnapshotPayload(item: SyncMemorySnapshotItem): Record<string, unknown> | null {\n\tif (!item.payload_json) return null;\n\ttry {\n\t\tconst parsed = JSON.parse(item.payload_json);\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return null;\n\t\treturn parsed as Record<string, unknown>;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction isEmbeddableSnapshotPayload(payload: Record<string, unknown>): boolean {\n\tconst title = typeof payload.title === \"string\" ? payload.title : \"\";\n\tconst bodyText = typeof payload.body_text === \"string\" ? payload.body_text : \"\";\n\treturn `${title}\\n${bodyText}`.trim().length > 0;\n}\n\nfunction retirementSnapshotItems(\n\tdb: Database,\n\titems: SyncMemorySnapshotItem[],\n\tscope: string | null,\n): SyncMemorySnapshotItem[] {\n\treturn items.filter((item) => {\n\t\tconst payload = parseSnapshotPayload(item);\n\t\treturn payload && retirementAllowsSnapshot(db, item.entity_id, payload, scope);\n\t});\n}\n\nfunction normalizeBootstrapScopeId(scopeId: unknown): string | null {\n\tif (typeof scopeId !== \"string\") return null;\n\tconst trimmed = scopeId.trim();\n\treturn trimmed.length > 0 ? trimmed : null;\n}\n\nfunction snapshotPayloadScopeId(\n\tpayload: Record<string, unknown>,\n\tbootstrapScopeId: string | null,\n): string | null {\n\tif (bootstrapScopeId) return bootstrapScopeId;\n\treturn normalizeBootstrapScopeId(payload.scope_id);\n}\n\nfunction validateSnapshotScopes(\n\titems: SyncMemorySnapshotItem[],\n\tbootstrapScopeId: string | null,\n): void {\n\tif (bootstrapScopeId === DEFAULT_SYNC_SCOPE_ID) throw new Error(\"scope_mismatch\");\n\tfor (const item of items) {\n\t\tconst payload = parseSnapshotPayload(item);\n\t\tif (!payload) continue;\n\t\tconst payloadScopeId = normalizeBootstrapScopeId(payload.scope_id);\n\t\tif (!bootstrapScopeId) throw new Error(\"scope_mismatch\");\n\t\tif (payloadScopeId && payloadScopeId !== bootstrapScopeId) {\n\t\t\tthrow new Error(\"scope_mismatch\");\n\t\t}\n\t}\n}\n\nconst bootstrapSessionCache = new Map<string, number>();\n\nfunction ensureSessionForBootstrap(\n\td: ReturnType<typeof drizzle>,\n\tupdatedAt: string,\n\tproject?: string | null,\n): number {\n\tconst projectKey = project ?? \"__none__\";\n\tconst cached = bootstrapSessionCache.get(projectKey);\n\tif (cached != null) return cached;\n\n\tconst cwd = project ? `${SYNC_BOOTSTRAP_CWD_PREFIX}:${project}` : SYNC_BOOTSTRAP_CWD_PREFIX;\n\tconst existing = d\n\t\t.select({ id: schema.sessions.id })\n\t\t.from(schema.sessions)\n\t\t.where(eq(schema.sessions.cwd, cwd))\n\t\t.limit(1)\n\t\t.get();\n\tif (existing) {\n\t\tbootstrapSessionCache.set(projectKey, existing.id);\n\t\treturn existing.id;\n\t}\n\n\tconst rows = d\n\t\t.insert(schema.sessions)\n\t\t.values({\n\t\t\tstarted_at: updatedAt,\n\t\t\tcwd,\n\t\t\tproject: project ?? null,\n\t\t\tuser: \"sync\",\n\t\t\ttool_version: \"bootstrap\",\n\t\t})\n\t\t.returning({ id: schema.sessions.id })\n\t\t.all();\n\tconst id = rows[0]?.id ?? 0;\n\tbootstrapSessionCache.set(projectKey, id);\n\treturn id;\n}\n\nfunction shouldReplaceExistingSnapshotRows(\n\texistingRows: ExistingSnapshotRow[],\n\titem: SyncMemorySnapshotItem,\n): boolean {\n\tif (existingRows.length === 0) return true;\n\t// Mirror the canonical last-writer-wins clock used by incremental\n\t// replication: rev → updated_at → clock_device_id. Without the device-id\n\t// tie-break, an exact rev+timestamp tie that the snapshot should win would\n\t// be skipped here while the scoped cursor/baseline still advances, leaving\n\t// the stale local row with no later pull to correct it.\n\tconst candidate: [number, string, string] = [\n\t\titem.clock_rev,\n\t\titem.clock_updated_at,\n\t\titem.clock_device_id,\n\t];\n\treturn existingRows.every((row) =>\n\t\tisNewerClock(candidate, [\n\t\t\ttypeof row.rev === \"number\" ? row.rev : 0,\n\t\t\trow.updated_at,\n\t\t\tclockDeviceIdFromMetadataJson(row.metadata_json),\n\t\t]),\n\t);\n}\n\nfunction insertSnapshotItem(\n\td: ReturnType<typeof drizzle>,\n\titem: SyncMemorySnapshotItem,\n\tbootstrapScopeId: string | null,\n\tactiveScanner: SecretScanner,\n): { applied: boolean; embeddable: boolean } {\n\tconst payload = parseSnapshotPayload(item);\n\tif (!payload) return { applied: false, embeddable: false };\n\tredactMemoryFields(payload, activeScanner);\n\tconst scopeId = snapshotPayloadScopeId(payload, bootstrapScopeId);\n\tconst project =\n\t\ttypeof payload.project === \"string\" && payload.project.trim() ? payload.project.trim() : null;\n\tconst sessionId = ensureSessionForBootstrap(d, new Date().toISOString(), project);\n\n\tconst metaRaw = payload.metadata_json;\n\tconst meta =\n\t\tmetaRaw && typeof metaRaw === \"object\" && !Array.isArray(metaRaw)\n\t\t\t? (metaRaw as Record<string, unknown>)\n\t\t\t: {};\n\tmeta.clock_device_id = item.clock_device_id;\n\n\tconst isDeleted = item.op_type === \"delete\";\n\n\td.insert(schema.memoryItems)\n\t\t.values({\n\t\t\tsession_id: sessionId,\n\t\t\tkind: typeof payload.kind === \"string\" ? payload.kind : \"discovery\",\n\t\t\ttitle: typeof payload.title === \"string\" ? payload.title : \"\",\n\t\t\tsubtitle: typeof payload.subtitle === \"string\" ? payload.subtitle : null,\n\t\t\tbody_text: typeof payload.body_text === \"string\" ? payload.body_text : \"\",\n\t\t\tconfidence: typeof payload.confidence === \"number\" ? payload.confidence : 0.5,\n\t\t\ttags_text: typeof payload.tags_text === \"string\" ? payload.tags_text : \"\",\n\t\t\tactive: isDeleted ? 0 : 1,\n\t\t\tcreated_at:\n\t\t\t\ttypeof payload.created_at === \"string\" ? payload.created_at : item.clock_updated_at,\n\t\t\tupdated_at: item.clock_updated_at,\n\t\t\tmetadata_json: toJson(meta),\n\t\t\timport_key: item.entity_id,\n\t\t\tdeleted_at: isDeleted ? item.clock_updated_at : null,\n\t\t\trev: item.clock_rev,\n\t\t\tactor_id: typeof payload.actor_id === \"string\" ? payload.actor_id : null,\n\t\t\tactor_display_name:\n\t\t\t\ttypeof payload.actor_display_name === \"string\" ? payload.actor_display_name : null,\n\t\t\tvisibility: typeof payload.visibility === \"string\" ? payload.visibility : \"shared\",\n\t\t\tworkspace_id:\n\t\t\t\ttypeof payload.workspace_id === \"string\" ? payload.workspace_id : \"shared:default\",\n\t\t\tworkspace_kind:\n\t\t\t\ttypeof payload.workspace_kind === \"string\" ? payload.workspace_kind : \"shared\",\n\t\t\torigin_device_id:\n\t\t\t\ttypeof payload.origin_device_id === \"string\"\n\t\t\t\t\t? payload.origin_device_id\n\t\t\t\t\t: item.clock_device_id,\n\t\t\torigin_source: typeof payload.origin_source === \"string\" ? payload.origin_source : null,\n\t\t\ttrust_state: typeof payload.trust_state === \"string\" ? payload.trust_state : \"trusted\",\n\t\t\tnarrative: typeof payload.narrative === \"string\" ? payload.narrative : null,\n\t\t\tfacts: Array.isArray(payload.facts) ? JSON.stringify(payload.facts) : null,\n\t\t\tconcepts: Array.isArray(payload.concepts) ? JSON.stringify(payload.concepts) : null,\n\t\t\tfiles_read: Array.isArray(payload.files_read) ? JSON.stringify(payload.files_read) : null,\n\t\t\tfiles_modified: Array.isArray(payload.files_modified)\n\t\t\t\t? JSON.stringify(payload.files_modified)\n\t\t\t\t: null,\n\t\t\tuser_prompt_id: typeof payload.user_prompt_id === \"number\" ? payload.user_prompt_id : null,\n\t\t\tprompt_number: typeof payload.prompt_number === \"number\" ? payload.prompt_number : null,\n\t\t\tscope_id: scopeId,\n\t\t\t// Persist the originating project name from the snapshot so the\n\t\t\t// Projects read model can surface this memory under its real\n\t\t\t// project identity on this receiver.\n\t\t\tproject,\n\t\t})\n\t\t.run();\n\n\treturn { applied: true, embeddable: !isDeleted && isEmbeddableSnapshotPayload(payload) };\n}\n\nfunction clearScopedAckedCursor(db: Database, peerDeviceId: string, scopeId: string): void {\n\tdrizzle(db, { schema })\n\t\t.update(schema.replicationCursorsV2)\n\t\t.set({ last_acked_cursor: null, updated_at: new Date().toISOString() })\n\t\t.where(\n\t\t\tand(\n\t\t\t\teq(schema.replicationCursorsV2.peer_device_id, peerDeviceId),\n\t\t\t\teq(schema.replicationCursorsV2.scope_id, scopeId),\n\t\t\t),\n\t\t)\n\t\t.run();\n}\n\n/**\n * Apply a bootstrap snapshot to the local database, atomically replacing\n * synced memories in the requested scope with the snapshot contents.\n *\n * This runs in a single IMMEDIATE transaction:\n * 1. For an explicit scope, delete local shared-visibility memory_items in\n * that scope (preserving private and other-scope rows). Unscoped bootstrap\n * is non-destructive because its serving lane contains no regular rows.\n * 2. Insert all snapshot items (upsert handles tombstones via active/deleted_at)\n * 3. Update the replication cursor to baseline_cursor\n * 4. Bump the local generation + snapshot_id to match the peer\n */\nexport function applyBootstrapSnapshot(\n\tdb: Database,\n\tpeerDeviceId: string,\n\titems: SyncMemorySnapshotItem[],\n\tresetInfo: SyncResetRequired,\n\tscanner?: SecretScanner,\n\toptions?: BootstrapApplicationOptions,\n): BootstrapResult {\n\tconst result = newBootstrapResult();\n\t// Bootstrap items are peer-authored content. Run them through the same\n\t// scanner as locally-authored writes; without this, a single bootstrap\n\t// from a misbehaving peer could re-populate the local store with secrets\n\t// the peer emitted before they ran scanner-aware versions.\n\tconst activeScanner = scanner ?? new SecretScanner();\n\tconst bootstrapScopeId = normalizeBootstrapScopeId(resetInfo.scope_id);\n\tvalidateSnapshotScopes(items, bootstrapScopeId);\n\n\tdb.transaction(() => {\n\t\tconst d = drizzle(db, { schema });\n\t\tlet embeddableApplied = 0;\n\n\t\t// 1. Delete local sync-eligible memories only for an explicit bootstrap scope.\n\t\t// - Only memories with import_key (i.e. previously synced) are deleted.\n\t\t// - Bootstrap for one Sharing domain must not wipe rows from another.\n\t\t// - Only explicitly private memories are preserved; NULL visibility is\n\t\t// treated as sync-eligible (matching syncVisibilityAllowed semantics)\n\t\t// to avoid leaving stale rows that could create duplicate import_keys.\n\t\t// - The dirty-local gate in sync-pass ensures we only reach here when\n\t\t// no unsynced shared changes exist.\n\t\tif (bootstrapScopeId) {\n\t\t\tresult.deleted = deleteSyncedMemoriesInScope(db, bootstrapScopeId);\n\t\t}\n\n\t\t// 2. Insert snapshot items, grouping by project.\n\t\tbootstrapSessionCache.clear();\n\n\t\tfor (const item of retirementSnapshotItems(db, items, bootstrapScopeId)) {\n\t\t\tconst inserted = insertSnapshotItem(d, item, bootstrapScopeId, activeScanner);\n\t\t\tif (!inserted.applied) continue;\n\t\t\trecordForeignMemoryRevision(db, item.entity_id, \"bootstrap\");\n\t\t\tif (inserted.embeddable) embeddableApplied++;\n\t\t\tresult.applied++;\n\t\t\trecordSnapshotReceipt(db, peerDeviceId, item, bootstrapScopeId);\n\t\t}\n\n\t\t// 3. Update replication cursor to baseline_cursor. For scoped null-baseline\n\t\t// snapshots, baseline_cursor can be null; store a hidden marker in the\n\t\t// scoped cursor row so status can distinguish \"this peer/scope bootstrap\n\t\t// completed without a cursor boundary\" from \"this scope was never attempted\".\n\t\tif (resetInfo.baseline_cursor || resetInfo.scope_id) {\n\t\t\tif (resetInfo.scope_id && !resetInfo.baseline_cursor) {\n\t\t\t\tclearReplicationCursorLastApplied(db, peerDeviceId, resetInfo.scope_id);\n\t\t\t}\n\t\t\tif (resetInfo.scope_id && resetInfo.baseline_cursor) {\n\t\t\t\tclearScopedAckedCursor(db, peerDeviceId, resetInfo.scope_id);\n\t\t\t}\n\t\t\tsetReplicationCursor(\n\t\t\t\tdb,\n\t\t\t\tpeerDeviceId,\n\t\t\t\t{\n\t\t\t\t\tlastApplied: resetInfo.baseline_cursor,\n\t\t\t\t\tlastAcked: resetInfo.baseline_cursor\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: SCOPED_NULL_BASELINE_BOOTSTRAP_CURSOR_MARKER,\n\t\t\t\t},\n\t\t\t\tresetInfo.scope_id,\n\t\t\t);\n\t\t}\n\n\t\t// 4. Bump local generation + snapshot_id to match the peer.\n\t\tsetSyncResetState(\n\t\t\tdb,\n\t\t\t{\n\t\t\t\tgeneration: resetInfo.generation,\n\t\t\t\tsnapshot_id: resetInfo.snapshot_id,\n\t\t\t\tbaseline_cursor: resetInfo.baseline_cursor,\n\t\t\t},\n\t\t\tresetInfo.scope_id,\n\t\t);\n\n\t\tqueueVectorBackfillForSyncBootstrap(db, { embeddableTotal: embeddableApplied });\n\n\t\tfinishSnapshotActivity(db, peerDeviceId, result, options);\n\t}).immediate();\n\n\treturn result;\n}\n\nfunction deleteSyncedMemoriesInScope(db: Database, scopeId: string): number {\n\tconst d = drizzle(db, { schema });\n\tconst deletePredicate = and(\n\t\tisNotNull(schema.memoryItems.import_key),\n\t\teq(schema.memoryItems.scope_id, scopeId),\n\t\tne(sql`COALESCE(${schema.memoryItems.visibility}, '')`, \"private\"),\n\t);\n\tconst affectedRows = d\n\t\t.select({ id: schema.memoryItems.id })\n\t\t.from(schema.memoryItems)\n\t\t.where(deletePredicate)\n\t\t.all();\n\tsnapshotSessionExportKeysForMemoryIds(\n\t\tdb,\n\t\taffectedRows.map((row) => row.id),\n\t);\n\treturn d.delete(schema.memoryItems).where(deletePredicate).run().changes;\n}\n\nfunction advanceMergedSnapshotBoundary(\n\tdb: Database,\n\tpeerDeviceId: string,\n\tresetInfo: SyncResetRequired,\n\toptions?: BootstrapApplicationOptions,\n): void {\n\tif (options?.cursorPolicy === \"preserve\") return;\n\tif (resetInfo.baseline_cursor || resetInfo.scope_id) {\n\t\tif (resetInfo.scope_id && !resetInfo.baseline_cursor)\n\t\t\tclearReplicationCursorLastApplied(db, peerDeviceId, resetInfo.scope_id);\n\t\tif (resetInfo.scope_id && resetInfo.baseline_cursor)\n\t\t\tclearScopedAckedCursor(db, peerDeviceId, resetInfo.scope_id);\n\t\tsetReplicationCursor(\n\t\t\tdb,\n\t\t\tpeerDeviceId,\n\t\t\t{\n\t\t\t\tlastApplied: resetInfo.baseline_cursor,\n\t\t\t\tlastAcked: resetInfo.baseline_cursor\n\t\t\t\t\t? undefined\n\t\t\t\t\t: SCOPED_NULL_BASELINE_BOOTSTRAP_CURSOR_MARKER,\n\t\t\t},\n\t\t\tresetInfo.scope_id,\n\t\t);\n\t}\n\tsetSyncResetState(\n\t\tdb,\n\t\t{\n\t\t\tgeneration: resetInfo.generation,\n\t\t\tsnapshot_id: resetInfo.snapshot_id,\n\t\t\tbaseline_cursor: resetInfo.baseline_cursor,\n\t\t},\n\t\tresetInfo.scope_id,\n\t);\n}\n\n/**\n * Additively merge a peer snapshot into an already-populated scope.\n *\n * Unlike `applyBootstrapSnapshot`, this does not delete local imported rows that\n * are absent from the peer snapshot. It only inserts missing snapshot entities\n * or replaces stale copies of the same snapshot entity. Use this when a scoped\n * peer has no cursor yet but the receiver already has rows in that scope from\n * another source, making destructive bootstrap unsafe.\n * Source subsets must preserve the whole-scope cursor and reset boundary.\n */\nexport function mergeBootstrapSnapshot(\n\tdb: Database,\n\tpeerDeviceId: string,\n\titems: SyncMemorySnapshotItem[],\n\tresetInfo: SyncResetRequired,\n\tscanner?: SecretScanner,\n\toptions?: BootstrapApplicationOptions,\n): BootstrapResult {\n\tconst result = newBootstrapResult();\n\tconst activeScanner = scanner ?? new SecretScanner();\n\tconst bootstrapScopeId = normalizeBootstrapScopeId(resetInfo.scope_id);\n\tvalidateSnapshotScopes(items, bootstrapScopeId);\n\tconst mergeScopePredicate = bootstrapScopeId\n\t\t? eq(schema.memoryItems.scope_id, bootstrapScopeId)\n\t\t: or(\n\t\t\t\tisNull(schema.memoryItems.scope_id),\n\t\t\t\teq(schema.memoryItems.scope_id, DEFAULT_SYNC_SCOPE_ID),\n\t\t\t);\n\n\tdb.transaction(() => {\n\t\tconst d = drizzle(db, { schema });\n\t\tlet embeddableApplied = 0;\n\t\tbootstrapSessionCache.clear();\n\n\t\tfor (const item of retirementSnapshotItems(db, items, bootstrapScopeId)) {\n\t\t\tif (!parseSnapshotPayload(item)) continue;\n\t\t\tconst existingRows = d\n\t\t\t\t.select({\n\t\t\t\t\tid: schema.memoryItems.id,\n\t\t\t\t\trev: schema.memoryItems.rev,\n\t\t\t\t\tupdated_at: schema.memoryItems.updated_at,\n\t\t\t\t\tmetadata_json: schema.memoryItems.metadata_json,\n\t\t\t\t})\n\t\t\t\t.from(schema.memoryItems)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(schema.memoryItems.import_key, item.entity_id),\n\t\t\t\t\t\tmergeScopePredicate,\n\t\t\t\t\t\tne(sql`COALESCE(${schema.memoryItems.visibility}, '')`, \"private\"),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.all();\n\n\t\t\tif (!shouldReplaceExistingSnapshotRows(existingRows, item)) continue;\n\n\t\t\tconst existingIds = existingRows.map((row) => row.id);\n\t\t\tif (existingIds.length > 0) {\n\t\t\t\tsnapshotSessionExportKeysForMemoryIds(db, existingIds);\n\t\t\t\tconst deleteResult = d\n\t\t\t\t\t.delete(schema.memoryItems)\n\t\t\t\t\t.where(inArray(schema.memoryItems.id, existingIds))\n\t\t\t\t\t.run();\n\t\t\t\tresult.deleted += deleteResult.changes;\n\t\t\t}\n\n\t\t\tconst inserted = insertSnapshotItem(d, item, bootstrapScopeId, activeScanner);\n\t\t\tif (!inserted.applied) continue;\n\t\t\trecordForeignMemoryRevision(db, item.entity_id, \"bootstrap\");\n\t\t\tif (inserted.embeddable) embeddableApplied++;\n\t\t\tresult.applied++;\n\t\t\trecordSnapshotReceipt(db, peerDeviceId, item, bootstrapScopeId);\n\t\t}\n\n\t\tadvanceMergedSnapshotBoundary(db, peerDeviceId, resetInfo, options);\n\n\t\tqueueVectorBackfillForSyncBootstrap(db, { embeddableTotal: embeddableApplied });\n\t\tfinishSnapshotActivity(db, peerDeviceId, result, options);\n\t}).immediate();\n\n\treturn result;\n}\n\nfunction recordSnapshotReceipt(\n\tdb: Database,\n\tpeerDeviceId: string,\n\titem: SyncMemorySnapshotItem,\n\tscopeId: string | null,\n): void {\n\tconst id = JSON.stringify([\n\t\tscopeId,\n\t\titem.entity_id,\n\t\titem.op_type,\n\t\titem.clock_rev,\n\t\titem.clock_updated_at,\n\t\titem.clock_device_id,\n\t]);\n\trecordSyncTransferReceipts(db, peerDeviceId, \"receive\", [id], { kind: \"snapshot\" });\n}\n\nfunction finishSnapshotActivity(\n\tdb: Database,\n\tpeerDeviceId: string,\n\tresult: BootstrapResult,\n\toptions?: BootstrapApplicationOptions,\n): void {\n\trecordSyncTransferObservation(db, peerDeviceId, \"receive\", options?.activityOptions);\n\tresult.ok = true;\n}\n\nfunction newBootstrapResult(): BootstrapResult {\n\treturn { ok: false, applied: 0, deleted: 0 };\n}\n","/**\n * Peer discovery and address management for the codemem sync system.\n *\n * Handles address normalization, deduplication, peer address storage,\n * and cross-platform mDNS advertise/discover via `bonjour-service`.\n */\n\nimport { createRequire } from \"node:module\";\nimport { eq } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport {\n\tformatHostPort,\n\tmergeAddresses,\n\tmergeCoordinatorPeerAddresses,\n\tnormalizeAddress,\n} from \"./address-utils.js\";\nimport { readCoordinatorSyncConfig } from \"./coordinator-sync-config.js\";\nimport {\n\ttype Database,\n\tensureSyncAttemptFailureCategoryColumn,\n\tensureSyncAttemptTransportColumn,\n} from \"./db.js\";\nimport * as schema from \"./schema.js\";\nimport type { SyncAttemptFailureCategory } from \"./sync-pass.js\";\nimport { loadManualPeerAddresses, loadPeerAddresses } from \"./sync-peer-addresses.js\";\n\nconst requireFromHere = createRequire(import.meta.url);\n\n// Re-export for consumers that import from sync-discovery\nexport {\n\taddressDedupeKey,\n\tformatHostPort,\n\tmergeAddresses,\n\tnormalizeAddress,\n} from \"./address-utils.js\";\nexport { loadPeerAddresses, updatePeerAddresses } from \"./sync-peer-addresses.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nexport const DEFAULT_SERVICE_TYPE = \"_codemem._tcp.local.\";\n\n// ---------------------------------------------------------------------------\n// Address selection\n// ---------------------------------------------------------------------------\n\n/**\n * Select addresses to dial, preferring mDNS-discovered addresses.\n *\n * mDNS addresses come first, then stored addresses (deduplicated).\n */\nexport function selectDialAddresses(options: { stored: string[]; mdns: string[] }): string[] {\n\tif (options.mdns.length === 0) {\n\t\treturn mergeAddresses(options.stored, []);\n\t}\n\treturn mergeAddresses(options.mdns, options.stored);\n}\n\n// ---------------------------------------------------------------------------\n// Peer address storage (DB)\n// ---------------------------------------------------------------------------\n\n/**\n * Record a sync attempt in the sync_attempts table and update peer status.\n */\nexport function recordSyncAttempt(\n\tdb: Database,\n\tpeerDeviceId: string,\n\toptions: {\n\t\tok: boolean;\n\t\topsIn?: number;\n\t\topsOut?: number;\n\t\terror?: string;\n\t\tfailureCategory?: SyncAttemptFailureCategory;\n\t\ttransport?: \"direct\" | \"relay\";\n\t},\n): void {\n\t// Exported for direct callers whose connect() skips the additive schema pass.\n\tensureSyncAttemptFailureCategoryColumn(db);\n\tensureSyncAttemptTransportColumn(db);\n\tconst d = drizzle(db, { schema });\n\tconst now = new Date().toISOString();\n\td.insert(schema.syncAttempts)\n\t\t.values({\n\t\t\tpeer_device_id: peerDeviceId,\n\t\t\tstarted_at: now,\n\t\t\tfinished_at: now,\n\t\t\tok: options.ok ? 1 : 0,\n\t\t\tops_in: options.opsIn ?? 0,\n\t\t\tops_out: options.opsOut ?? 0,\n\t\t\terror: options.error ?? null,\n\t\t\tfailure_category: options.ok ? null : (options.failureCategory ?? \"other\"),\n\t\t\ttransport: options.transport ?? null,\n\t\t})\n\t\t.run();\n\n\tif (options.ok) {\n\t\td.update(schema.syncPeers)\n\t\t\t.set({ last_sync_at: now, last_error: null })\n\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t.run();\n\t} else {\n\t\td.update(schema.syncPeers)\n\t\t\t.set({ last_error: options.error ?? null })\n\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t.run();\n\t}\n}\n\n/**\n * Record a successful sync and promote the working address to the front.\n *\n * Returns the reordered address list.\n */\nexport function recordPeerSuccess(\n\tdb: Database,\n\tpeerDeviceId: string,\n\taddress: string | null,\n): string[] {\n\tconst normalized = normalizeAddress(address ?? \"\");\n\tconst now = new Date().toISOString();\n\tconst promote = db.transaction((deviceId: string, promotedAddress: string, syncedAt: string) => {\n\t\tconst addresses = loadPeerAddresses(db, deviceId);\n\t\tconst remaining = promotedAddress\n\t\t\t? addresses.filter((item) => normalizeAddress(item) !== promotedAddress)\n\t\t\t: addresses;\n\t\tconst manual = loadManualPeerAddresses(db, deviceId) ?? addresses;\n\t\tconst ordered = mergeCoordinatorPeerAddresses(\n\t\t\t[],\n\t\t\tpromotedAddress ? [promotedAddress, ...remaining] : addresses,\n\t\t\tmanual,\n\t\t\t{\n\t\t\t\trequiredFreshAddresses: promotedAddress ? 1 : 0,\n\t\t\t\tsuccessfulAddress: promotedAddress || undefined,\n\t\t\t},\n\t\t);\n\t\tconst d = drizzle(db, { schema });\n\t\td.update(schema.syncPeers)\n\t\t\t.set({\n\t\t\t\taddresses_json: JSON.stringify(ordered),\n\t\t\t\tmanual_addresses_json: JSON.stringify(manual),\n\t\t\t\t...(promotedAddress ? { last_success_address: promotedAddress } : {}),\n\t\t\t\tlast_sync_at: syncedAt,\n\t\t\t\tlast_seen_at: syncedAt,\n\t\t\t\tlast_error: null,\n\t\t\t})\n\t\t\t.where(eq(schema.syncPeers.peer_device_id, deviceId))\n\t\t\t.run();\n\t\treturn ordered;\n\t});\n\treturn promote.immediate(peerDeviceId, normalized, now);\n}\n\n// ---------------------------------------------------------------------------\n// Project filters\n// ---------------------------------------------------------------------------\n\n/**\n * Set per-peer project include/exclude filters.\n *\n * Pass null for both to clear the override (inherit global config).\n */\nexport function setPeerProjectFilter(\n\tdb: Database,\n\tpeerDeviceId: string,\n\toptions: {\n\t\tinclude: string[] | null;\n\t\texclude: string[] | null;\n\t},\n): void {\n\tconst includeJson = options.include === null ? null : JSON.stringify(options.include);\n\tconst excludeJson = options.exclude === null ? null : JSON.stringify(options.exclude);\n\tconst d = drizzle(db, { schema });\n\td.update(schema.syncPeers)\n\t\t.set({ projects_include_json: includeJson, projects_exclude_json: excludeJson })\n\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t.run();\n}\n\n/**\n * Set the claimed_local_actor flag for a peer.\n */\nexport function setPeerLocalActorClaim(db: Database, peerDeviceId: string, claimed: boolean): void {\n\tconst d = drizzle(db, { schema });\n\td.update(schema.syncPeers)\n\t\t.set({ claimed_local_actor: claimed ? 1 : 0 })\n\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t.run();\n}\n\n// ---------------------------------------------------------------------------\n// mDNS peer discovery (cross-platform via bonjour-service)\n// ---------------------------------------------------------------------------\n\nexport interface MdnsEntry {\n\tname?: string;\n\thost?: string;\n\tport?: number;\n\taddress?: Uint8Array | string;\n\tproperties?: Record<string, string | Uint8Array>;\n}\n\nexport function normalizeMdnsTxtProperties(\n\ttxt: Record<string, unknown>,\n): Record<string, string | Uint8Array> {\n\tconst properties: Record<string, string | Uint8Array> = {};\n\tfor (const [key, value] of Object.entries(txt)) {\n\t\tproperties[key] = value instanceof Uint8Array ? value : String(value);\n\t}\n\treturn properties;\n}\n\nconst MDNS_SERVICE_TYPE = \"codemem\"; // advertises as _codemem._tcp.local.\n\n/**\n * Returns true when mDNS discovery should be active on this device.\n *\n * Reads the merged codemem config (so the Settings UI toggle is\n * authoritative) with an env-var override (`CODEMEM_SYNC_MDNS`) for\n * one-off runs. Previously env-only, which silently ignored the UI\n * toggle.\n */\nexport function mdnsEnabled(): boolean {\n\tconst envValue = process.env.CODEMEM_SYNC_MDNS;\n\tif (envValue) return envValue === \"1\" || envValue.toLowerCase() === \"true\";\n\ttry {\n\t\treturn readCoordinatorSyncConfig().syncMdns;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// Lazy-import `bonjour-service` so users who disable embeddings or run\n// in environments where the multicast socket can't bind don't pay the\n// startup cost. Returns null when the module isn't available.\ninterface BonjourLike {\n\tpublish: (opts: { name: string; type: string; port: number; txt?: Record<string, string> }) => {\n\t\tstop: (cb?: () => void) => void;\n\t};\n\tfind: (\n\t\topts: { type: string },\n\t\tonUp?: (svc: {\n\t\t\tname: string;\n\t\t\thost?: string;\n\t\t\tfqdn?: string;\n\t\t\tport: number;\n\t\t\taddresses?: string[];\n\t\t\ttxt?: Record<string, string>;\n\t\t}) => void,\n\t) => { stop: () => void };\n\tdestroy: () => void;\n}\n\ntype BonjourCtor = new (\n\topts?: Record<string, unknown>,\n\terrorCallback?: (err: Error) => void,\n) => BonjourLike;\n\nfunction loadBonjour(): BonjourLike | null {\n\ttry {\n\t\tconst mod = requireFromHere(\"bonjour-service\") as {\n\t\t\tBonjour?: BonjourCtor;\n\t\t\tdefault?: BonjourCtor;\n\t\t};\n\t\tconst Ctor = mod.Bonjour ?? mod.default;\n\t\tif (!Ctor) return null;\n\t\t// Pass an error callback so mDNS runtime errors (bind failures on\n\t\t// restricted containers, interface churn, multicast blocked) stay\n\t\t// contained instead of propagating as uncaught exceptions and\n\t\t// taking down the sync/viewer process. Degrades to no-op on error.\n\t\treturn new Ctor(undefined, (err: Error) => {\n\t\t\tconsole.warn(\"[codemem] mDNS runtime error (non-fatal):\", err?.message ?? err);\n\t\t});\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n// Shared Bonjour instance: advertise + discover reuse a single multicast\n// socket, refcounted across callers. This avoids churn where each call would\n// otherwise spin up a fresh bind-release cycle and race its own publish/find\n// against destroy(). The instance is lazily created on first acquire and torn\n// down when the last caller releases.\nlet sharedInstance: BonjourLike | null = null;\nlet sharedRefcount = 0;\n\nfunction acquireBonjour(): BonjourLike | null {\n\tif (sharedInstance) {\n\t\tsharedRefcount += 1;\n\t\treturn sharedInstance;\n\t}\n\tconst instance = loadBonjour();\n\tif (!instance) return null;\n\tsharedInstance = instance;\n\tsharedRefcount = 1;\n\treturn sharedInstance;\n}\n\nfunction releaseBonjour(): void {\n\tif (!sharedInstance) return;\n\tsharedRefcount = Math.max(0, sharedRefcount - 1);\n\tif (sharedRefcount > 0) return;\n\tconst instance = sharedInstance;\n\tsharedInstance = null;\n\ttry {\n\t\tinstance.destroy();\n\t} catch {\n\t\t// best effort\n\t}\n}\n\n/**\n * Internal: reset shared instance state. Exposed for tests only.\n */\nexport function __resetMdnsForTests(): void {\n\tif (sharedInstance) {\n\t\ttry {\n\t\t\tsharedInstance.destroy();\n\t\t} catch {\n\t\t\t// best effort\n\t\t}\n\t}\n\tsharedInstance = null;\n\tsharedRefcount = 0;\n}\n\n/**\n * Advertise this device as a codemem sync peer via mDNS.\n *\n * Returns a closer that tears down the advertisement. No-op when mDNS\n * is disabled, when `bonjour-service` failed to load, or when the\n * multicast socket cannot bind.\n */\nexport function advertiseMdns(deviceId: string, port: number): { close(): void } {\n\tif (!mdnsEnabled()) return { close() {} };\n\tif (!deviceId || !port || !Number.isFinite(port)) return { close() {} };\n\n\tconst bonjour = acquireBonjour();\n\tif (!bonjour) return { close() {} };\n\n\tlet advertisement: { stop: (cb?: () => void) => void } | null = null;\n\ttry {\n\t\tadvertisement = bonjour.publish({\n\t\t\tname: `codemem-${deviceId.slice(0, 12)}`,\n\t\t\ttype: MDNS_SERVICE_TYPE,\n\t\t\tport,\n\t\t\ttxt: { device_id: deviceId },\n\t\t});\n\t} catch {\n\t\treleaseBonjour();\n\t\treturn { close() {} };\n\t}\n\n\tlet closed = false;\n\treturn {\n\t\tclose() {\n\t\t\tif (closed) return;\n\t\t\tclosed = true;\n\t\t\tconst release = () => releaseBonjour();\n\t\t\ttry {\n\t\t\t\t// Wait for publish to acknowledge the stop before releasing the\n\t\t\t\t// shared instance so the unpublish actually reaches the wire.\n\t\t\t\tadvertisement?.stop(() => release());\n\t\t\t} catch {\n\t\t\t\trelease();\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Discover codemem sync peers via mDNS. Blocks up to `timeoutMs` (default\n * 1500) collecting `_codemem._tcp.local.` responders, then returns the\n * entries it saw. No-op / empty array when mDNS is disabled or the\n * module couldn't load.\n */\nexport async function discoverPeersViaMdns(timeoutMs = 1500): Promise<MdnsEntry[]> {\n\tif (!mdnsEnabled()) return [];\n\n\tconst bonjour = acquireBonjour();\n\tif (!bonjour) return [];\n\n\tconst found: MdnsEntry[] = [];\n\tconst seen = new Set<string>();\n\t// Ignore late `onUp` callbacks that fire after the timeout elapses — the\n\t// browser's `stop()` is best-effort and can race in-flight dispatches.\n\tlet acceptingResults = true;\n\tlet browser: { stop: () => void } | null = null;\n\ttry {\n\t\tbrowser = bonjour.find({ type: MDNS_SERVICE_TYPE }, (svc) => {\n\t\t\tif (!acceptingResults) return;\n\t\t\tconst key = `${svc.name}|${svc.host ?? svc.fqdn ?? \"\"}|${svc.port}`;\n\t\t\tif (seen.has(key)) return;\n\t\t\tseen.add(key);\n\t\t\tconst addresses = Array.isArray(svc.addresses) ? svc.addresses : [];\n\t\t\tconst resolvedAddress =\n\t\t\t\taddresses.find((addr) => addr && /^[\\d.]+$/.test(addr)) ??\n\t\t\t\taddresses.find((addr) => typeof addr === \"string\" && addr.trim().length > 0);\n\t\t\tconst rawTxt = svc.txt ?? {};\n\t\t\tfound.push({\n\t\t\t\tname: svc.name,\n\t\t\t\thost: (svc.host || svc.fqdn || \"\").replace(/\\.$/, \"\"),\n\t\t\t\tport: svc.port,\n\t\t\t\taddress: resolvedAddress,\n\t\t\t\tproperties: normalizeMdnsTxtProperties(rawTxt),\n\t\t\t});\n\t\t});\n\t\tawait new Promise<void>((resolve) => setTimeout(resolve, Math.max(100, timeoutMs)));\n\t} finally {\n\t\tacceptingResults = false;\n\t\ttry {\n\t\t\tbrowser?.stop();\n\t\t} catch {\n\t\t\t// best effort\n\t\t}\n\t\treleaseBonjour();\n\t}\n\treturn found;\n}\n\n/**\n * Extract addresses for a specific peer from mDNS discovery entries.\n */\nexport function mdnsAddressesForPeer(peerDeviceId: string, entries: MdnsEntry[]): string[] {\n\tconst addresses: string[] = [];\n\tfor (const entry of entries) {\n\t\tconst props = entry.properties ?? {};\n\t\tlet deviceId: string | Uint8Array | undefined =\n\t\t\tprops.device_id ??\n\t\t\t((props as Record<string, unknown>).device_id as string | Uint8Array | undefined);\n\t\tif (deviceId == null) continue;\n\t\tif (deviceId instanceof Uint8Array) {\n\t\t\tdeviceId = new TextDecoder().decode(deviceId);\n\t\t}\n\t\tif (deviceId !== peerDeviceId) continue;\n\n\t\tconst port = entry.port ?? 0;\n\t\tif (!port) continue;\n\n\t\t// Prefer entry.address (resolved IP) over entry.host (service name).\n\t\t// mDNS responses often carry a service-name host (e.g. _codemem._tcp.local)\n\t\t// that isn't directly dialable, but include the usable IP in address.\n\t\tconst address = (entry as Record<string, unknown>).address as string | undefined;\n\t\tconst host = entry.host ?? \"\";\n\t\tconst dialHost = address && !address.includes(\".local\") ? address : host;\n\t\tif (dialHost && !dialHost.includes(\"_tcp.local\") && !dialHost.includes(\"_udp.local\")) {\n\t\t\tconst normalized = normalizeAddress(formatHostPort(dialHost, port));\n\t\t\tif (normalized) addresses.push(normalized);\n\t\t}\n\t}\n\treturn addresses;\n}\n","import type { Database } from \"./db.js\";\n\nexport interface SyncChannelBoundary {\n\tgeneration: number;\n\tsnapshot_id: string;\n\tbaseline_cursor: string | null;\n}\n\nexport interface SyncChannelProgress extends SyncChannelBoundary {\n\tlast_acked_cursor: string | null;\n}\n\ninterface ProgressTarget {\n\tpeerDeviceId: string;\n\tscopeId: string;\n\tboundary: SyncChannelBoundary;\n}\n\n// Installed only by the opt-in channel pass, after explicit scope authorization.\nfunction ensureSyncChannelProgress(db: Database): void {\n\tdb.exec(`CREATE TABLE IF NOT EXISTS sync_channel_progress (\n\t\tpeer_device_id TEXT NOT NULL,\n\t\tscope_id TEXT NOT NULL,\n\t\tgeneration INTEGER NOT NULL,\n\t\tsnapshot_id TEXT NOT NULL,\n\t\tbaseline_cursor TEXT,\n\t\tlast_acked_cursor TEXT,\n\t\tPRIMARY KEY (peer_device_id, scope_id)\n\t)`);\n}\n\nexport function getSyncChannelProgress(\n\tdb: Database,\n\tpeerDeviceId: string,\n\tscopeId: string,\n): SyncChannelProgress | null {\n\tensureSyncChannelProgress(db);\n\treturn (\n\t\t(db\n\t\t\t.prepare(`SELECT generation, snapshot_id, baseline_cursor, last_acked_cursor\n\t\tFROM sync_channel_progress WHERE peer_device_id = ? AND scope_id = ?`)\n\t\t\t.get(peerDeviceId, scopeId) as SyncChannelProgress | undefined) ?? null\n\t);\n}\n\nexport function clearSyncChannelProgress(\n\tdb: Database,\n\tpeerDeviceId: string,\n\tscopeId: string,\n): void {\n\tensureSyncChannelProgress(db);\n\tdb.prepare(\"DELETE FROM sync_channel_progress WHERE peer_device_id = ? AND scope_id = ?\").run(\n\t\tpeerDeviceId,\n\t\tscopeId,\n\t);\n}\n\nexport function hasCompletedSyncChannelBoundary(\n\tprogress: SyncChannelProgress | null,\n\tboundary: SyncChannelBoundary,\n): boolean {\n\treturn (\n\t\tprogress !== null &&\n\t\tprogress.generation === boundary.generation &&\n\t\tprogress.snapshot_id === boundary.snapshot_id &&\n\t\tprogress.baseline_cursor === boundary.baseline_cursor\n\t);\n}\n\n/** Save only after durable pull success. A changed peer boundary invalidates its outbound ACK. */\nexport function saveSyncChannelCompletedBoundary(db: Database, target: ProgressTarget): void {\n\tensureSyncChannelProgress(db);\n\tconst { peerDeviceId, scopeId, boundary } = target;\n\tdb.prepare(`INSERT INTO sync_channel_progress\n\t\t(peer_device_id, scope_id, generation, snapshot_id, baseline_cursor, last_acked_cursor)\n\t\tVALUES (?, ?, ?, ?, ?, NULL)\n\t\tON CONFLICT (peer_device_id, scope_id) DO UPDATE SET\n\t\tlast_acked_cursor = CASE WHEN generation = excluded.generation\n\t\t\tAND snapshot_id = excluded.snapshot_id AND baseline_cursor IS excluded.baseline_cursor\n\t\t\tTHEN last_acked_cursor ELSE NULL END,\n\t\tgeneration = excluded.generation, snapshot_id = excluded.snapshot_id,\n\t\tbaseline_cursor = excluded.baseline_cursor`).run(\n\t\tpeerDeviceId,\n\t\tscopeId,\n\t\tboundary.generation,\n\t\tboundary.snapshot_id,\n\t\tboundary.baseline_cursor,\n\t);\n}\n\n/** Bind ACK to the completed pull boundary, including when another pass changed it meanwhile. */\nexport function saveSyncChannelOutboundAck(\n\tdb: Database,\n\ttarget: ProgressTarget & { cursor: string },\n): void {\n\tconst { peerDeviceId, scopeId, boundary, cursor } = target;\n\tconst result = db\n\t\t.prepare(`UPDATE sync_channel_progress SET last_acked_cursor = ?\n\t\tWHERE peer_device_id = ? AND scope_id = ? AND generation = ? AND snapshot_id = ?\n\t\tAND baseline_cursor IS ? AND (last_acked_cursor IS NULL OR last_acked_cursor <= ?)`)\n\t\t.run(\n\t\t\tcursor,\n\t\t\tpeerDeviceId,\n\t\t\tscopeId,\n\t\t\tboundary.generation,\n\t\t\tboundary.snapshot_id,\n\t\t\tboundary.baseline_cursor,\n\t\t\tcursor,\n\t\t);\n\tif (result.changes !== 1) throw new Error(\"channel progress changed\");\n}\n","import type { SyncFailureCategory } from \"./sync-pass.js\";\n\nexport type RecordedSyncFailureCategory = SyncFailureCategory | \"compatibility\";\n\n// Checked in order; the first matching phrase decides the category.\nconst SYNC_FAILURE_PHRASES: Array<[SyncFailureCategory, string[]]> = [\n\t[\"trust\", [\"fingerprint mismatch\", \"peer not pinned\"]],\n\t[\"scope\", [\"scope_rejected\", \"scope rejected\", \"missing_scope\", \"stale_epoch\", \"scope_inactive\"]],\n\t[\n\t\t\"connectivity\",\n\t\t[\n\t\t\t\"no dialable peer addresses\",\n\t\t\t\"fetch failed\",\n\t\t\t\"connection refused\",\n\t\t\t\"network\",\n\t\t\t\"timeout\",\n\t\t\t\"503\",\n\t\t\t\"502\",\n\t\t\t\"504\",\n\t\t\t\"peer status failed\",\n\t\t\t\"peer ops fetch failed\",\n\t\t\t\"snapshot fetch failed\",\n\t\t],\n\t],\n];\n\nexport function categorizeSyncFailure(error: string | undefined): SyncFailureCategory {\n\tconst lower = String(error ?? \"\").toLowerCase();\n\tif (!lower) return \"other\";\n\tif (lower.includes(\"401\") && lower.includes(\"unauthorized\")) return \"trust\";\n\tconst match = SYNC_FAILURE_PHRASES.find(([, phrases]) =>\n\t\tphrases.some((phrase) => lower.includes(phrase)),\n\t);\n\treturn match?.[0] ?? \"other\";\n}\n\n// Aggregated per-Space and inbound-apply errors embed arbitrary Space IDs and\n// nested error text whose delimiters are ambiguous, and the runtime category\n// for them is not persisted. Report them as `other` rather than guess.\nconst AGGREGATE_PREFIXES = [\"scoped sync incomplete:\", \"inbound apply incomplete\"];\n\n// The sync pass writes these phrases only after the peer returned an HTTP\n// response (status/error formats vary); transport failures are recorded as raw\n// fetch errors instead. A response is a reachability problem only when a\n// gateway or unavailable status says so.\nconst ANSWERED_RESPONSE_PHRASES = [\n\t\"peer status failed\",\n\t\"peer ops fetch failed\",\n\t\"peer ops push failed\",\n\t\"snapshot fetch failed\",\n];\n// JSON error bodies can drop the status (for example `snapshot fetch failed:\n// sync_auth_store_busy` from a 503), so also match stable busy codes.\nconst UNREACHABLE_STATUS_PATTERN = /\\b50[234]\\b|sync_auth_store_busy/;\n\n// Peer addresses can contain any word (for example `http://authbox.local`).\n// Drop whitespace-separated tokens that contain a URL scheme separator; a\n// linear token scan avoids backtracking on untrusted input.\nfunction withoutPeerAddresses(text: string): string {\n\treturn text\n\t\t.split(/\\s+/)\n\t\t.filter((token) => !token.includes(\"://\"))\n\t\t.join(\" \");\n}\n\n/**\n * Classify an error string persisted in `sync_attempts`, using the same\n * categories the sync pass assigns at runtime. Returns `other` whenever the\n * stored text cannot be classified unambiguously.\n */\nexport function classifyRecordedSyncFailure(\n\terror: string | null | undefined,\n): RecordedSyncFailureCategory {\n\tconst text = String(error ?? \"\").trim();\n\tif (!text) return \"other\";\n\tif (AGGREGATE_PREFIXES.some((prefix) => text.toLowerCase().startsWith(prefix))) return \"other\";\n\tconst withoutAddresses = withoutPeerAddresses(text);\n\tconst lower = withoutAddresses.toLowerCase();\n\tif (lower.includes(\"protocol mismatch\")) return \"compatibility\";\n\tconst category = categorizeSyncFailure(withoutAddresses);\n\tconst peerAnswered = ANSWERED_RESPONSE_PHRASES.some((phrase) => lower.includes(phrase));\n\tif (category === \"connectivity\" && peerAnswered && !UNREACHABLE_STATUS_PATTERN.test(lower)) {\n\t\treturn \"other\";\n\t}\n\treturn category;\n}\n\nconst STORED_CATEGORY_PRIORITY: RecordedSyncFailureCategory[] = [\n\t\"trust\",\n\t\"scope\",\n\t\"compatibility\",\n\t\"connectivity\",\n];\n\n/**\n * Category persisted for a failed multi-address attempt. Each address error is\n * classified on its own, without the address, so peer URLs and delimiter text\n * inside an error cannot change the result. The most actionable category wins\n * when addresses disagree.\n */\nexport function storedAddressFailureCategory(\n\taddressErrors: Array<{ address: string; error: string }>,\n\tfallbackError: string,\n): RecordedSyncFailureCategory {\n\tif (addressErrors.length === 0) return categorizeSyncFailure(fallbackError);\n\tconst categories = new Set(addressErrors.map((item) => classifyRecordedSyncFailure(item.error)));\n\treturn STORED_CATEGORY_PRIORITY.find((category) => categories.has(category)) ?? \"other\";\n}\n","/**\n * Sync pass orchestrator: coordinates a single sync exchange with a peer device.\n *\n * Handles the pull→apply→push cycle for replication ops, with address\n * fallback, fingerprint verification, and cursor tracking.\n * Ported from codemem/sync/sync_pass.py.\n */\n\nimport { and, desc, eq, gt, or } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport { MAX_PEER_ADDRESSES, mergeAddresses } from \"./address-utils.js\";\nimport type { Database } from \"./db.js\";\nimport { ensureAdditiveSchemaCompatibility, ensureSyncAttemptTransportColumn } from \"./db.js\";\nimport type { RelayFailureReason } from \"./relay-failure-reason.js\";\nimport { isStableReleaseVersion } from \"./release-discovery.js\";\nimport * as schema from \"./schema.js\";\nimport type { SecretScanner } from \"./secret-scanner.js\";\nimport { buildDirectPeerAuthHeaders } from \"./sync-auth.js\";\nimport {\n\tapplyBootstrapSnapshot,\n\tfetchAllSnapshotPages,\n\tmergeBootstrapSnapshot,\n} from \"./sync-bootstrap.js\";\nimport {\n\tLOCAL_SYNC_CAPABILITY,\n\tLOCAL_SYNC_FEATURES,\n\tnegotiateSyncCapability,\n\tnormalizeSyncCapability,\n\tnormalizeSyncFeatures,\n\tSYNC_AUTHORIZATION_REFRESH_HEADER,\n\tSYNC_CAPABILITY_HEADER,\n\tSYNC_FEATURES_HEADER,\n\ttype SyncCapability,\n\tsupportsSyncFeature,\n} from \"./sync-capability.js\";\nimport {\n\tgetSyncChannelProgress,\n\thasCompletedSyncChannelBoundary,\n} from \"./sync-channel-progress.js\";\nimport { recordPeerSuccess } from \"./sync-discovery.js\";\nimport {\n\tcategorizeSyncFailure,\n\tstoredAddressFailureCategory,\n} from \"./sync-failure-classification.js\";\nimport { buildBaseUrl, type RequestJsonExecutor, requestJson } from \"./sync-http-client.js\";\nimport { ensureDeviceIdentity } from \"./sync-identity.js\";\nimport {\n\tapplyReplicationOps,\n\tbackfillReplicationOps,\n\tchunkOpsBySize,\n\tclearReplicationCursorLastApplied,\n\textractReplicationOps,\n\ttype FilterReplicationSkipped,\n\tfilterReplicationOpsForSyncWithStatus,\n\tgetReplicationCursor,\n\thasUnsyncedSharedMemoryChanges,\n\tmigrateLegacyImportKeys,\n\treconcileStalePeerReceivedRows,\n\tSCOPED_NULL_BASELINE_BOOTSTRAP_CURSOR_MARKER,\n\tsetReplicationCursor,\n} from \"./sync-replication.js\";\nimport {\n\trecordSyncTransferObservation,\n\trecordSyncTransferReceipts,\n\ttype SyncTransferErrorCode,\n} from \"./sync-transfer-activity.js\";\nimport type { ReplicationOp, SyncMemorySnapshotItem, SyncResetRequired } from \"./types.js\";\nimport { queueVectorBackfillForIncrementalSync } from \"./vector-migration.js\";\nimport { bestEffortMaintainVectorsForSyncFallback } from \"./vectors.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/** Default max body size for sync POST requests (1 MiB). */\nconst MAX_SYNC_BODY_BYTES = 1_048_576;\n\n/**\n * One-shot warning latch so sync-apply paths log a single line per process if\n * a caller forgot to thread the scanner through. Workspace-level rule overrides\n * silently fail to apply to peer-shipped content otherwise.\n */\nlet syncOnceScannerWarned = false;\n\n/**\n * Default op fetch/push limit per round.\n *\n * The server caps this at 1000 per request (see viewer-server /v1/ops).\n * Callers can override via SyncPassOptions.limit; the sync daemon resolves\n * it from the sync_ops_limit config key / CODEMEM_SYNC_OPS_LIMIT env var.\n */\nconst DEFAULT_LIMIT = 500;\n\n/** Elevated page size for initial bootstrap of never-synced peers. */\nconst BOOTSTRAP_PAGE_SIZE = 2000;\n\n/**\n * Per-page snapshot fetch timeout for bootstrap / scoped merge recovery.\n * Larger than the default incremental timeout because snapshot pages can be\n * substantially bigger and slower to assemble on the serving peer.\n */\nconst BOOTSTRAP_REQUEST_TIMEOUT_S = 60;\n\n// Initiated windows share one observation. Only the final receive result resolves errors.\nconst RECEIVE_WINDOW_OPTIONS = { activityOptions: { preserveError: true } };\n\n/** Current sync protocol version expected from peers. */\nconst EXPECTED_SYNC_PROTOCOL_VERSION = \"2\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type SyncFailureCategory = \"trust\" | \"scope\" | \"connectivity\" | \"other\";\n\n/**\n * Category persisted on `sync_attempts.failure_category`. Wider than the\n * runtime `SyncFailureCategory` so stored diagnostics can tell protocol\n * mismatches apart without changing callers that switch on the runtime type.\n */\nexport type SyncAttemptFailureCategory = SyncFailureCategory | \"compatibility\";\n\nexport interface SyncResult {\n\tok: boolean;\n\ttransport?: \"direct\" | \"traversal\" | \"relay\" | \"wait\";\n\t/** Why a `wait` result skipped relay on purpose. The direct attempt record stands alone. */\n\trelaySkipped?: \"relay_peer_unsupported\" | \"relay_backoff\";\n\terror?: string;\n\tfailureCategory?: SyncFailureCategory;\n\treceiveFailureCode?: SyncTransferErrorCode;\n\taddress?: string;\n\topsIn: number;\n\topsOut: number;\n\topsSkipped?: number;\n\tskippedOut?: FilterReplicationSkipped | null;\n\taddressErrors: Array<{ address: string; error: string }>;\n\tresetRequired?: SyncResetRequired;\n\t/**\n\t * Per-Space sync outcomes when both peers negotiate the `scoped` sync\n\t * capability. Each entry covers a non-default scope returned by the peer's\n\t * `authorized_scopes` advertisement. Unset for legacy / `aware` peers; in\n\t * that case the top-level `opsIn` / `opsOut` describe the only sync pass\n\t * that ran (default scope).\n\t *\n\t * Top-level `opsIn` / `opsOut` aggregate the default-scope pass plus every\n\t * scoped pass, so existing callers stay correct without per-scope\n\t * awareness. A failure in a single scope sets the entry's `ok=false` but\n\t * does not block other scopes, and does not affect the default-scope\n\t * outcome. The top-level `ok` is true only when every per-scope result is\n\t * `ok`, matching the design's \"all-or-nothing\" report.\n\t */\n\tperScopeResults?: SyncScopeResult[];\n}\n\n/**\n * Outcome of a single per-Space sync pass within a larger `syncOnce` exchange.\n *\n * Lives alongside `SyncResult` rather than nested into it because each scope\n * has its own cursor / reset state and can fail independently. Aggregating the\n * per-scope counts into `SyncResult.opsIn` / `opsOut` preserves backward\n * compatibility for callers that only need totals.\n */\nexport interface SyncScopeResult {\n\tscope_id: string;\n\tlabel?: string;\n\tok: boolean;\n\tfailureCategory?: SyncFailureCategory;\n\treceiveFailureCode?: SyncTransferErrorCode;\n\topsIn: number;\n\topsOut: number;\n\terror?: string;\n\t/** First local relay route failure for a relay channel pass. Never sent to peers. */\n\trelayFailureReason?: RelayFailureReason;\n\tresetRequired?: SyncResetRequired;\n\t/**\n\t * True when the pass began with an empty cursor and no local rows in the\n\t * scope, triggering a `/v1/snapshot` bootstrap. False for incremental\n\t * `/v1/ops` passes. Useful for diagnostics and UI progress reporting.\n\t */\n\tbootstrapped: boolean;\n}\n\nexport interface SyncPassOptions {\n\trequestExecutor?: RequestJsonExecutor;\n\t/** @internal A selected pass defers address-level diagnostics to its final result. */\n\tattemptRecorder?: typeof recordSyncAttempt;\n\t/** @internal Transport selection records exhausted connection probes only after fallback. */\n\tdeferConnectionFailure?: boolean;\n\treachability?: import(\"./sync-reachability-pass.js\").SyncReachabilityOptions;\n\tlimit?: number;\n\tkeysDir?: string;\n\tdbPath?: string;\n\trefreshAuthorization?: boolean;\n\t/**\n\t * Secret scanner used to redact peer-shipped content on apply. Callers that\n\t * own a `MemoryStore` should pass `store.scanner` so workspace-level rule\n\t * overrides apply uniformly to local writes and sync-receive. Omitting it\n\t * falls back to default rules only and prints a one-time warning.\n\t */\n\tscanner?: SecretScanner;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Check if a cursor candidate advances beyond the current position.\n *\n * Cursors are `timestamp|op_id` strings that sort lexicographically.\n */\nexport function cursorAdvances(current: string | null, candidate: string | null): boolean {\n\tif (!candidate) return false;\n\tif (!candidate.includes(\"|\")) return false;\n\tif (!current) return true;\n\treturn candidate > current;\n}\n\n/**\n * Extract an error detail string from a JSON response payload.\n */\nfunction errorDetail(payload: Record<string, unknown> | null): string | null {\n\tif (!payload) return null;\n\tconst error = payload.error;\n\tconst reason = payload.reason;\n\tif (typeof error === \"string\" && typeof reason === \"string\") {\n\t\treturn `${error}:${reason}`;\n\t}\n\tif (typeof error === \"string\") return error;\n\treturn null;\n}\n\n/**\n * Summarize address errors into a single error string.\n */\nfunction summarizeAddressErrors(\n\taddressErrors: Array<{ address: string; error: string }>,\n): string | null {\n\tif (addressErrors.length === 0) return null;\n\tconst parts = addressErrors.map((item) => `${item.address}: ${item.error}`);\n\treturn `all addresses failed | ${parts.join(\" || \")}`;\n}\n\nfunction asOptionalCursor(value: unknown): string | null {\n\tif (typeof value !== \"string\") return null;\n\tconst trimmed = value.trim();\n\treturn trimmed.length > 0 ? trimmed : null;\n}\n\nfunction parsePeerResetBoundary(payload: Record<string, unknown> | null): {\n\tscope_id: string | null;\n\tgeneration: number;\n\tsnapshot_id: string;\n\tbaseline_cursor: string | null;\n\tretained_floor_cursor: string | null;\n} | null {\n\tconst raw = payload?.sync_reset;\n\tif (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return null;\n\tconst boundary = raw as Record<string, unknown>;\n\tif (!Number.isFinite(boundary.generation)) return null;\n\tif (typeof boundary.snapshot_id !== \"string\" || boundary.snapshot_id.trim().length === 0) {\n\t\treturn null;\n\t}\n\tconst baseline = asOptionalCursor(boundary.baseline_cursor);\n\treturn {\n\t\tscope_id: asOptionalCursor(boundary.scope_id),\n\t\tgeneration: Number(boundary.generation),\n\t\tsnapshot_id: boundary.snapshot_id.trim(),\n\t\tbaseline_cursor: baseline,\n\t\tretained_floor_cursor: asOptionalCursor(boundary.retained_floor_cursor),\n\t};\n}\n\nfunction isValidIncrementalOpsResponse(payload: Record<string, unknown> | null): payload is {\n\treset_required: false;\n\tgeneration: number;\n\tsnapshot_id: string;\n\tbaseline_cursor: string | null;\n\tretained_floor_cursor: string | null;\n\tops: unknown[];\n\tnext_cursor: string | null;\n\tskipped: number;\n} {\n\tif (payload?.reset_required !== false) return false;\n\tif (!Number.isFinite(payload.generation)) return false;\n\tif (typeof payload.snapshot_id !== \"string\" || payload.snapshot_id.trim().length === 0)\n\t\treturn false;\n\tif (!(payload.baseline_cursor == null || typeof payload.baseline_cursor === \"string\"))\n\t\treturn false;\n\tif (\n\t\t!(payload.retained_floor_cursor == null || typeof payload.retained_floor_cursor === \"string\")\n\t) {\n\t\treturn false;\n\t}\n\tif (!Array.isArray(payload.ops)) return false;\n\tif (!(payload.next_cursor == null || typeof payload.next_cursor === \"string\")) return false;\n\tif (!Number.isFinite(payload.skipped)) return false;\n\treturn true;\n}\n\ninterface SyncCapabilityDiagnostics {\n\tlocal: SyncCapability;\n\tpeer: SyncCapability;\n\tnegotiated: SyncCapability;\n}\n\nfunction capabilityDiagnostics(peerCapability: unknown): SyncCapabilityDiagnostics {\n\tconst peer = normalizeSyncCapability(peerCapability);\n\treturn {\n\t\tlocal: LOCAL_SYNC_CAPABILITY,\n\t\tpeer,\n\t\tnegotiated: negotiateSyncCapability(LOCAL_SYNC_CAPABILITY, peer),\n\t};\n}\n\nfunction capabilityHeader(): Record<string, string> {\n\t// Diagnostic advertisement only. This unsigned GET header can opt an\n\t// authenticated paired peer into scoped metadata enumeration, but never into\n\t// scoped data access; receivers must still authorize every scoped request.\n\treturn {\n\t\t[SYNC_CAPABILITY_HEADER]: LOCAL_SYNC_CAPABILITY,\n\t\t[SYNC_FEATURES_HEADER]: LOCAL_SYNC_FEATURES.join(\",\"),\n\t};\n}\n\nfunction defaultCapabilityDiagnostics(): SyncCapabilityDiagnostics {\n\treturn capabilityDiagnostics(\"unsupported\");\n}\n\nfunction persistPeerRuntimeVersion(\n\tdb: Database,\n\tpeerDeviceId: string,\n\tstatusPayload: Record<string, unknown>,\n): void {\n\tconst matchingDevice = statusPayload.device_id === peerDeviceId;\n\tconst runtimeVersion =\n\t\tmatchingDevice && isStableReleaseVersion(statusPayload.runtime_version)\n\t\t\t? statusPayload.runtime_version\n\t\t\t: null;\n\t// A status reply without the field is an older peer: store an empty list, which\n\t// is a known answer, so relay fallback can tell \"no relay\" from \"never seen\".\n\tconst features = matchingDevice\n\t\t? JSON.stringify(normalizeSyncFeatures(statusPayload.sync_features))\n\t\t: null;\n\ttry {\n\t\tdb.prepare(\n\t\t\t`UPDATE sync_peers\n\t\t\t SET runtime_version = ?, runtime_version_observed_at = ?,\n\t\t\t sync_features_json = COALESCE(?, sync_features_json),\n\t\t\t sync_features_observed_at = COALESCE(?, sync_features_observed_at)\n\t\t\t WHERE peer_device_id = ?`,\n\t\t).run(\n\t\t\truntimeVersion,\n\t\t\truntimeVersion ? new Date().toISOString() : null,\n\t\t\tfeatures,\n\t\t\tfeatures === null ? null : new Date().toISOString(),\n\t\t\tpeerDeviceId,\n\t\t);\n\t} catch {\n\t\t// Informational metadata must never affect sync availability or trust.\n\t}\n}\n\nasync function reconcilePeerRowsBeforeExchange(\n\tdb: Database,\n\toptions: { localDeviceId: string; peerDeviceId: string; keysDir?: string },\n): Promise<void> {\n\tconst reconciliation = reconcileStalePeerReceivedRows(db, options);\n\tif (reconciliation.deleted_memory_ids.length === 0) return;\n\tconst vectorWork = {\n\t\tupsertMemoryIds: [],\n\t\tdeleteMemoryIds: reconciliation.deleted_memory_ids,\n\t};\n\ttry {\n\t\tqueueVectorBackfillForIncrementalSync(db, vectorWork);\n\t} catch (queueError) {\n\t\tconst fallback = await bestEffortMaintainVectorsForSyncFallback(db, vectorWork);\n\t\tif (fallback.errors.length > 0) {\n\t\t\tconst queueDetail = queueError instanceof Error ? queueError.message : String(queueError);\n\t\t\tthrow new Error(\n\t\t\t\t`peer recovery vector cleanup failed: ${queueDetail}; fallback failed: ${fallback.errors.join(\"; \")}`,\n\t\t\t);\n\t\t}\n\t}\n}\n\nfunction reconcileReceivedRowsForExchange(\n\tdb: Database,\n\toptions: { deviceId: string; peerDeviceId: string; keysDir?: string },\n): ReturnType<typeof reconcileStalePeerReceivedRows> {\n\treturn reconcileStalePeerReceivedRows(db, {\n\t\tlocalDeviceId: options.deviceId,\n\t\tpeerDeviceId: options.peerDeviceId,\n\t\tkeysDir: options.keysDir,\n\t});\n}\n\n/**\n * Record a sync attempt in the sync_attempts table.\n */\nexport function recordSyncAttempt(\n\tdb: Database,\n\tpeerDeviceId: string,\n\toptions: {\n\t\tok: boolean;\n\t\topsIn?: number;\n\t\topsOut?: number;\n\t\terror?: string;\n\t\tfailureCategory?: SyncAttemptFailureCategory;\n\t\tcapabilities?: SyncCapabilityDiagnostics;\n\t\ttransport?: SyncResult[\"transport\"];\n\t},\n): void {\n\tensureSyncAttemptTransportColumn(db);\n\tconst d = drizzle(db, { schema });\n\tconst now = new Date().toISOString();\n\tconst capabilities = options.capabilities ?? defaultCapabilityDiagnostics();\n\td.insert(schema.syncAttempts)\n\t\t.values({\n\t\t\tpeer_device_id: peerDeviceId,\n\t\t\tstarted_at: now,\n\t\t\tfinished_at: now,\n\t\t\tok: options.ok ? 1 : 0,\n\t\t\tops_in: options.opsIn ?? 0,\n\t\t\tops_out: options.opsOut ?? 0,\n\t\t\terror: options.error ?? null,\n\t\t\tlocal_sync_capability: capabilities.local,\n\t\t\tpeer_sync_capability: capabilities.peer,\n\t\t\tnegotiated_sync_capability: capabilities.negotiated,\n\t\t\tfailure_category: options.ok ? null : (options.failureCategory ?? \"other\"),\n\t\t\ttransport:\n\t\t\t\toptions.transport === \"direct\" || options.transport === \"relay\" ? options.transport : null,\n\t\t})\n\t\t.run();\n}\n\n/**\n * Load outbound replication ops for the local device since a cursor.\n *\n * Returns `[ops, nextCursor]`. The cursor is `created_at|op_id`.\n */\nfunction loadLocalOpsSince(\n\tdb: Database,\n\tcursor: string | null,\n\tdeviceId: string,\n\tlimit: number,\n): [ReplicationOp[], string | null] {\n\tconst d = drizzle(db, { schema });\n\tconst { replicationOps: ops } = schema;\n\tlet rows: ReplicationOp[];\n\tif (cursor) {\n\t\tconst sepIdx = cursor.indexOf(\"|\");\n\t\tconst cursorTs = sepIdx >= 0 ? cursor.slice(0, sepIdx) : cursor;\n\t\tconst cursorOpId = sepIdx >= 0 ? cursor.slice(sepIdx + 1) : \"\";\n\t\trows = d\n\t\t\t.select()\n\t\t\t.from(ops)\n\t\t\t.where(\n\t\t\t\tand(\n\t\t\t\t\teq(ops.device_id, deviceId),\n\t\t\t\t\tor(\n\t\t\t\t\t\tgt(ops.created_at, cursorTs),\n\t\t\t\t\t\tand(eq(ops.created_at, cursorTs), gt(ops.op_id, cursorOpId)),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t)\n\t\t\t.orderBy(ops.created_at, ops.op_id)\n\t\t\t.limit(limit)\n\t\t\t.all() as ReplicationOp[];\n\t} else {\n\t\trows = d\n\t\t\t.select()\n\t\t\t.from(ops)\n\t\t\t.where(eq(ops.device_id, deviceId))\n\t\t\t.orderBy(ops.created_at, ops.op_id)\n\t\t\t.limit(limit)\n\t\t\t.all() as ReplicationOp[];\n\t}\n\n\tif (rows.length === 0) return [[], null];\n\tconst last = rows.at(-1);\n\tif (!last) return [[], null];\n\tconst nextCursor = `${last.created_at}|${last.op_id}`;\n\treturn [rows, nextCursor];\n}\n\n// ---------------------------------------------------------------------------\n// Push ops\n// ---------------------------------------------------------------------------\n\n/**\n * Push ops to a peer endpoint with auth headers.\n *\n * On 413 (too large), splits the batch in half and retries recursively.\n */\nconst MAX_PUSH_SPLIT_DEPTH = 8;\n\nfunction hasPeerApplyErrors(payload: Record<string, unknown>): boolean {\n\tif (Object.hasOwn(payload, \"error\")) {\n\t\tconst error = payload.error;\n\t\tif (error != null) return true;\n\t}\n\t// Legacy peers may omit errors. A present field must explicitly report no failures.\n\tif (!Object.hasOwn(payload, \"errors\")) return false;\n\tconst errors = payload.errors;\n\treturn !Array.isArray(errors) || errors.length > 0;\n}\n\nasync function pushOps(\n\tpostUrl: string,\n\tdeviceId: string,\n\trecipientId: string,\n\tops: ReplicationOp[],\n\trequestExecutor: RequestJsonExecutor,\n\tonAcknowledged: (ops: ReplicationOp[]) => void,\n\tkeysDir?: string,\n\tdbPath?: string,\n\tdepth = 0,\n): Promise<void> {\n\tconst body = {\n\t\tops,\n\t\tsync_capability: LOCAL_SYNC_CAPABILITY,\n\t\tsync_features: LOCAL_SYNC_FEATURES,\n\t};\n\tconst bodyBytes = Buffer.from(JSON.stringify(body), \"utf-8\");\n\tconst headers = {\n\t\t...buildDirectPeerAuthHeaders({\n\t\t\tdeviceId,\n\t\t\trecipientId,\n\t\t\tmethod: \"POST\",\n\t\t\turl: postUrl,\n\t\t\tbodyBytes,\n\t\t\tkeysDir,\n\t\t\tdbPath,\n\t\t}),\n\t\t...capabilityHeader(),\n\t};\n\tconst [status, payload] = await requestExecutor(\"POST\", postUrl, {\n\t\theaders,\n\t\tbody,\n\t\tbodyBytes,\n\t});\n\n\tif (status === 200 && payload != null) {\n\t\tif (hasPeerApplyErrors(payload)) {\n\t\t\tthrow new Error(\"peer ops push failed (200: peer reported apply errors)\");\n\t\t}\n\t\tonAcknowledged(ops);\n\t\treturn;\n\t}\n\n\tconst detail = errorDetail(payload);\n\tif (\n\t\tstatus === 413 &&\n\t\tops.length > 1 &&\n\t\tdepth < MAX_PUSH_SPLIT_DEPTH &&\n\t\t(detail === \"payload_too_large\" || detail === \"too_many_ops\")\n\t) {\n\t\tconst mid = Math.floor(ops.length / 2);\n\t\tfor (const batch of [ops.slice(0, mid), ops.slice(mid)]) {\n\t\t\tawait pushOps(\n\t\t\t\tpostUrl,\n\t\t\t\tdeviceId,\n\t\t\t\trecipientId,\n\t\t\t\tbatch,\n\t\t\t\trequestExecutor,\n\t\t\t\tonAcknowledged,\n\t\t\t\tkeysDir,\n\t\t\t\tdbPath,\n\t\t\t\tdepth + 1,\n\t\t\t);\n\t\t}\n\t\treturn;\n\t}\n\n\tconst suffix = detail ? ` (${status}: ${detail})` : ` (${status})`;\n\tthrow new Error(`peer ops push failed${suffix}`);\n}\n\n// ---------------------------------------------------------------------------\n// Per-scope sync helpers (scoped capability path)\n// ---------------------------------------------------------------------------\n\n/**\n * Wire shape of a single entry in the `authorized_scopes` array returned by\n * `/v1/status` when both peers negotiate the `scoped` capability.\n */\ninterface PeerAuthorizedScope {\n\tscope_id: string;\n\tlabel?: string;\n\tauthority_type?: string;\n\tmembership_epoch?: number;\n\tsync_reset: {\n\t\tscope_id: string | null;\n\t\tgeneration: number;\n\t\tsnapshot_id: string;\n\t\tbaseline_cursor: string | null;\n\t\tretained_floor_cursor: string | null;\n\t};\n\t/** The peer's pull cursor for this device's ops in the scope, when it reports one. */\n\tapplied_cursor: string | null;\n}\n\n/** A reported `created_at|op_id` pull cursor, or null when absent or malformed. */\nfunction asAppliedCursor(value: unknown): string | null {\n\tconst cursor = asOptionalCursor(value);\n\tif (!cursor) return null;\n\t// Both parts must be present: a bare separator would sort after every real cursor.\n\tconst separator = cursor.indexOf(\"|\");\n\treturn separator > 0 && separator < cursor.length - 1 ? cursor : null;\n}\n\n/**\n * Parse and validate a peer's `authorized_scopes` advertisement.\n *\n * Returns an empty array (not null) for any malformed value so the per-scope\n * loop is a safe no-op for legacy peers that don't emit the field. Each\n * accepted entry must carry a non-empty `scope_id` and a complete\n * `sync_reset` boundary; partially-formed entries are dropped silently rather\n * than failing the whole pass.\n */\nfunction parseAuthorizedScopes(value: unknown): PeerAuthorizedScope[] {\n\tif (!Array.isArray(value)) return [];\n\tconst entries: PeerAuthorizedScope[] = [];\n\tfor (const raw of value) {\n\t\tif (!raw || typeof raw !== \"object\") continue;\n\t\tconst record = raw as Record<string, unknown>;\n\t\tconst scopeId = typeof record.scope_id === \"string\" ? record.scope_id.trim() : \"\";\n\t\tif (!scopeId) continue;\n\t\tconst reset = record.sync_reset;\n\t\tif (!reset || typeof reset !== \"object\") continue;\n\t\tconst resetRecord = reset as Record<string, unknown>;\n\t\tconst generation = Number(resetRecord.generation);\n\t\tif (!Number.isFinite(generation)) continue;\n\t\tconst snapshotId =\n\t\t\ttypeof resetRecord.snapshot_id === \"string\" ? resetRecord.snapshot_id.trim() : \"\";\n\t\tif (!snapshotId) continue;\n\t\tentries.push({\n\t\t\tscope_id: scopeId,\n\t\t\tapplied_cursor: asAppliedCursor(record.applied_cursor),\n\t\t\tlabel: typeof record.label === \"string\" ? record.label : undefined,\n\t\t\tauthority_type: typeof record.authority_type === \"string\" ? record.authority_type : undefined,\n\t\t\tmembership_epoch:\n\t\t\t\ttypeof record.membership_epoch === \"number\" ? record.membership_epoch : undefined,\n\t\t\tsync_reset: {\n\t\t\t\tscope_id: typeof resetRecord.scope_id === \"string\" ? resetRecord.scope_id : null,\n\t\t\t\tgeneration,\n\t\t\t\tsnapshot_id: snapshotId,\n\t\t\t\tbaseline_cursor: asOptionalCursor(resetRecord.baseline_cursor),\n\t\t\t\tretained_floor_cursor: asOptionalCursor(resetRecord.retained_floor_cursor),\n\t\t\t},\n\t\t});\n\t}\n\treturn entries;\n}\n\n/**\n * True when the local DB has any memory_items belonging to the given scope.\n * Used to decide between bootstrap (no local rows) and incremental (some local\n * rows) on first pull for a scope. Matches the predicate\n * `loadMemorySnapshotPageForPeer` uses for snapshot eligibility.\n */\nfunction hasLocalRowsInScope(db: Database, scopeId: string): boolean {\n\tconst row = db\n\t\t.prepare(\"SELECT 1 FROM memory_items WHERE import_key IS NOT NULL AND scope_id = ? LIMIT 1\")\n\t\t.get(scopeId) as { 1: number } | undefined;\n\treturn row !== undefined;\n}\n\nfunction scopedSnapshotAccessFailure(\n\tdb: Database,\n\toptions: { scopeId: string; peerDeviceId: string; localDeviceId: string },\n): SyncResetRequired[\"reason\"] | null {\n\tconst scope = db\n\t\t.prepare(\n\t\t\t`SELECT authority_type, status, membership_epoch\n\t\t\t FROM replication_scopes\n\t\t\t WHERE scope_id = ?`,\n\t\t)\n\t\t.get(options.scopeId) as\n\t\t| { authority_type: string | null; status: string | null; membership_epoch: number | null }\n\t\t| undefined;\n\tif (!scope) return \"missing_scope\";\n\tif (scope.status !== \"active\") return \"scope_inactive\";\n\tif (scope.authority_type === \"local\") return \"missing_scope\";\n\n\tconst requiredEpoch = Number(scope.membership_epoch ?? 0);\n\tfor (const deviceId of [options.localDeviceId, options.peerDeviceId]) {\n\t\tconst membership = db\n\t\t\t.prepare(\n\t\t\t\t`SELECT status, membership_epoch\n\t\t\t\t FROM scope_memberships\n\t\t\t\t WHERE scope_id = ? AND device_id = ?`,\n\t\t\t)\n\t\t\t.get(options.scopeId, deviceId) as\n\t\t\t| { status: string | null; membership_epoch: number | null }\n\t\t\t| undefined;\n\t\tif (!membership) return \"missing_scope\";\n\t\tif (membership.status !== \"active\") return \"scope_inactive\";\n\t\tif (Number(membership.membership_epoch ?? 0) < requiredEpoch) return \"stale_epoch\";\n\t}\n\n\treturn null;\n}\n\nfunction scopedSnapshotAccessDeniedResult(\n\tbaseUrl: string,\n\tresetInfo: SyncResetRequired,\n\treason: SyncResetRequired[\"reason\"],\n): SyncResult {\n\treturn {\n\t\tok: false,\n\t\taddress: baseUrl,\n\t\terror: `reset_required:${reason}`,\n\t\tfailureCategory: scopeResetFailureCategory(reason),\n\t\topsIn: 0,\n\t\topsOut: 0,\n\t\taddressErrors: [],\n\t\tresetRequired: { ...resetInfo, reason },\n\t};\n}\n\nfunction scopeFailureCategory(error: string | undefined): SyncFailureCategory {\n\treturn categorizeSyncFailure(error);\n}\n\nfunction scopeResetFailureCategory(reason: SyncResetRequired[\"reason\"]): SyncFailureCategory {\n\tswitch (reason) {\n\t\tcase \"missing_scope\":\n\t\tcase \"scope_inactive\":\n\t\tcase \"stale_epoch\":\n\t\t\treturn \"scope\";\n\t\tcase \"boundary_mismatch\":\n\t\tcase \"generation_mismatch\":\n\t\tcase \"initial_bootstrap\":\n\t\tcase \"stale_cursor\":\n\t\tcase \"unsupported_scope\":\n\t\t\treturn \"other\";\n\t}\n\treturn \"other\";\n}\n\nfunction aggregateScopeFailureCategory(\n\tresults: SyncScopeResult[],\n): SyncFailureCategory | undefined {\n\tconst failed = results.filter((result) => !result.ok);\n\tif (failed.length === 0) return undefined;\n\tconst categories = new Set(\n\t\tfailed.map((result) => result.failureCategory ?? scopeFailureCategory(result.error)),\n\t);\n\treturn categories.size === 1 ? Array.from(categories)[0] : \"other\";\n}\n\n/**\n * Run the per-Space iteration after a successful default-scope sync.\n *\n * Returns the per-scope outcomes plus the aggregate inbound op count so the\n * caller can update its top-level `SyncResult`. Failures inside individual\n * scopes are reported in the returned array; the function itself never\n * throws.\n */\nasync function runScopedSync(\n\tdb: Database,\n\trequestExecutor: RequestJsonExecutor,\n\toptions: {\n\t\tpeerDeviceId: string;\n\t\tbaseUrl: string;\n\t\tdeviceId: string;\n\t\tstatusPayload: Record<string, unknown>;\n\t\tkeysDir?: string;\n\t\tdbPath?: string;\n\t\tscanner?: SecretScanner;\n\t\tlimit: number;\n\t},\n): Promise<{ results: SyncScopeResult[]; totalOpsIn: number }> {\n\tconst authorizedScopes = parseAuthorizedScopes(options.statusPayload.authorized_scopes);\n\tif (authorizedScopes.length === 0) {\n\t\treturn { results: [], totalOpsIn: 0 };\n\t}\n\tconst results: SyncScopeResult[] = [];\n\tlet totalOpsIn = 0;\n\tfor (const scope of authorizedScopes) {\n\t\tconst scopeResult = await syncOneScope(db, {\n\t\t\tpeerDeviceId: options.peerDeviceId,\n\t\t\tbaseUrl: options.baseUrl,\n\t\t\tdeviceId: options.deviceId,\n\t\t\trequestExecutor,\n\t\t\tscope,\n\t\t\tkeysDir: options.keysDir,\n\t\t\tdbPath: options.dbPath,\n\t\t\tscanner: options.scanner,\n\t\t\tlimit: options.limit,\n\t\t});\n\t\tresults.push(scopeResult);\n\t\tif (!scopeResult.ok)\n\t\t\trecordSyncTransferObservation(db, options.peerDeviceId, \"receive\", {\n\t\t\t\terrorCode: scopeReceiveFailure(scopeResult),\n\t\t\t});\n\t\tif (scopeResult.ok) totalOpsIn += scopeResult.opsIn;\n\t}\n\treturn { results, totalOpsIn };\n}\n\nfunction scopeReceiveFailure(result: SyncScopeResult): SyncTransferErrorCode {\n\tif (result.receiveFailureCode) return result.receiveFailureCode;\n\treturn result.failureCategory === \"scope\" ? \"scope_rejected\" : \"exchange_failed\";\n}\n\n// A successful sibling window cannot resolve another scope's failed apply.\nfunction aggregateReceiveFailure(\n\tresults: SyncScopeResult[],\n\toptions: { applyErrors?: readonly string[] } = {},\n): SyncTransferErrorCode | undefined {\n\tconst failures = results.filter((result) => !result.ok).map(scopeReceiveFailure);\n\tif ((options.applyErrors?.length ?? 0) > 0 || failures.includes(\"apply_failed\"))\n\t\treturn \"apply_failed\";\n\tif (failures.includes(\"scope_rejected\")) return \"scope_rejected\";\n\tif (failures.length > 0) return \"exchange_failed\";\n\treturn undefined;\n}\n\nfunction applyReceiveFailure(errors: readonly string[]): \"apply_failed\" | undefined {\n\treturn errors.length > 0 ? \"apply_failed\" : undefined;\n}\n\nfunction mergedReceiveVectorWork(\n\twork: ReturnType<typeof applyReplicationOps>[\"vectorWork\"],\n\tdeletedMemoryIds: number[],\n) {\n\treturn {\n\t\tupsertMemoryIds: work.upsertMemoryIds,\n\t\tdeleteMemoryIds: [...work.deleteMemoryIds, ...deletedMemoryIds],\n\t};\n}\n\nfunction mergeScopeSnapshot(\n\tdb: Database,\n\tpeerDeviceId: string,\n\titems: SyncMemorySnapshotItem[],\n\tresetInfo: SyncResetRequired,\n\tscanner: SecretScanner | undefined,\n) {\n\treturn mergeBootstrapSnapshot(\n\t\tdb,\n\t\tpeerDeviceId,\n\t\titems,\n\t\tresetInfo,\n\t\tscanner,\n\t\tRECEIVE_WINDOW_OPTIONS,\n\t);\n}\n\nfunction applyScopeSnapshot(\n\tdb: Database,\n\tpeerDeviceId: string,\n\titems: SyncMemorySnapshotItem[],\n\tresetInfo: SyncResetRequired,\n\tscanner: SecretScanner | undefined,\n) {\n\treturn applyBootstrapSnapshot(\n\t\tdb,\n\t\tpeerDeviceId,\n\t\titems,\n\t\tresetInfo,\n\t\tscanner,\n\t\tRECEIVE_WINDOW_OPTIONS,\n\t);\n}\n\ninterface ScopedPeerPullOptions {\n\tpeerDeviceId: string;\n\tbaseUrl: string;\n\tdeviceId: string;\n\tscope: PeerAuthorizedScope;\n\trequestExecutor: RequestJsonExecutor;\n\tkeysDir?: string;\n\tdbPath?: string;\n\tscanner?: SecretScanner;\n\tlimit: number;\n\t/** Explicit per-peer completion overrides the legacy marker, including on boundary changes. */\n\tcompletedNullBaseline?: boolean;\n\tsourceDeviceId?: string;\n\tvalidateCurrentAuthorization?: () => void;\n\t/** Must finish synchronously before the inbound cursor can be cleared. */\n\tinvalidateCompletedBoundary?: () => void;\n}\n\nfunction resetScopedPullProgress(db: Database, options: ScopedPeerPullOptions): void {\n\t// Dropping completion first prevents an interrupted reset from skipping recovery.\n\toptions.invalidateCompletedBoundary?.();\n\tclearReplicationCursorLastApplied(db, options.peerDeviceId, options.scope.scope_id);\n}\n\nfunction scopedNullBaselineIsCurrent(options: {\n\tmarker: boolean;\n\tcompleted?: boolean;\n\tbaseline: string | null;\n}): boolean {\n\treturn (options.completed ?? options.marker) && options.baseline == null;\n}\n\nfunction scopedBootstrapOptions(options: ScopedPeerPullOptions) {\n\treturn {\n\t\trequestExecutor: options.requestExecutor,\n\t\tkeysDir: options.keysDir,\n\t\tdbPath: options.dbPath,\n\t\trecipientId: options.peerDeviceId,\n\t\tpageSize: BOOTSTRAP_PAGE_SIZE,\n\t\ttimeoutS: BOOTSTRAP_REQUEST_TIMEOUT_S,\n\t\tsourceDeviceId: options.sourceDeviceId,\n\t};\n}\n\n/**\n * Sync a single Sharing-domain scope with a peer. Caller is responsible for\n * having already authenticated against the peer (via legacy default-scope\n * sync) and having an `authorized_scopes` entry from `/v1/status`.\n *\n * Branches on per-scope cursor state:\n * - `bootstrapped=true`: no cursor and no local rows in this scope → fetch\n * the full snapshot page-by-page via `/v1/snapshot?scope_id=X` and apply\n * atomically via `applyBootstrapSnapshot`.\n * - `bootstrapped=false`: pull `/v1/ops?scope_id=X&since=<cursor>` and apply\n * through the normal `applyReplicationOps` path.\n *\n * Outbound ops are NOT pushed per-scope here. The default-scope outbound push\n * that ran in `syncOnce` already streams ops with their per-op `scope_id`\n * metadata intact, and the peer's outbound filter (`outboundScopeAllowed`)\n * applies the same membership gate per row. Re-pushing per scope would be a\n * waste; the receiver's per-scope pull on the next pass picks up anything it\n * missed.\n */\nasync function syncOneScope(\n\tdb: Database,\n\toptions: ScopedPeerPullOptions,\n): Promise<SyncScopeResult> {\n\tconst { peerDeviceId, baseUrl, deviceId, scope, keysDir, dbPath, scanner, limit } = options;\n\tconst bootstrapOptions = scopedBootstrapOptions(options);\n\tconst scopeId = scope.scope_id;\n\tconst [lastApplied, lastAcked] = getReplicationCursor(db, peerDeviceId, scopeId);\n\tconst hasNullBaselineBootstrapMarker = lastAcked === SCOPED_NULL_BASELINE_BOOTSTRAP_CURSOR_MARKER;\n\tconst nullBaselineBootstrapStillCurrent = scopedNullBaselineIsCurrent({\n\t\tmarker: hasNullBaselineBootstrapMarker,\n\t\tcompleted: options.completedNullBaseline,\n\t\tbaseline: scope.sync_reset.baseline_cursor,\n\t});\n\tconst localRowsPresent = hasLocalRowsInScope(db, scopeId);\n\tconst shouldMergeRecoverScope =\n\t\tlastApplied == null && localRowsPresent && !nullBaselineBootstrapStillCurrent;\n\tconst shouldBootstrapEmptyScope =\n\t\tlastApplied == null && !localRowsPresent && !nullBaselineBootstrapStillCurrent;\n\tif (shouldMergeRecoverScope || shouldBootstrapEmptyScope) {\n\t\tconst accessFailure = scopedSnapshotAccessFailure(db, {\n\t\t\tscopeId,\n\t\t\tpeerDeviceId,\n\t\t\tlocalDeviceId: deviceId,\n\t\t});\n\t\tif (accessFailure) {\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: false,\n\t\t\t\tfailureCategory: scopeResetFailureCategory(accessFailure),\n\t\t\t\topsIn: 0,\n\t\t\t\topsOut: 0,\n\t\t\t\terror: `reset_required:${accessFailure}`,\n\t\t\t\tresetRequired: {\n\t\t\t\t\treset_required: true,\n\t\t\t\t\treason: accessFailure,\n\t\t\t\t\tscope_id: scopeId,\n\t\t\t\t\tgeneration: scope.sync_reset.generation,\n\t\t\t\t\tsnapshot_id: scope.sync_reset.snapshot_id,\n\t\t\t\t\tbaseline_cursor: scope.sync_reset.baseline_cursor,\n\t\t\t\t\tretained_floor_cursor: scope.sync_reset.retained_floor_cursor,\n\t\t\t\t},\n\t\t\t\tbootstrapped: false,\n\t\t\t};\n\t\t}\n\t}\n\n\t// If this peer/scope has no cursor but the receiver already has rows in the\n\t// scope, a destructive bootstrap is unsafe and incremental from an empty\n\t// cursor can be a permanent no-op on peers that only retain snapshot state.\n\t// Recover additively by merging the advertised scoped snapshot: missing or\n\t// stale copies of the same snapshot entity are applied, but rows absent from\n\t// the peer snapshot are preserved.\n\tif (shouldMergeRecoverScope) {\n\t\ttry {\n\t\t\tconst resetInfo: SyncResetRequired = {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tgeneration: scope.sync_reset.generation,\n\t\t\t\tsnapshot_id: scope.sync_reset.snapshot_id,\n\t\t\t\tbaseline_cursor: scope.sync_reset.baseline_cursor,\n\t\t\t\tretained_floor_cursor: scope.sync_reset.retained_floor_cursor,\n\t\t\t\treset_required: true,\n\t\t\t\treason: \"initial_bootstrap\" as SyncResetRequired[\"reason\"],\n\t\t\t};\n\t\t\tconst { items } = await fetchAllSnapshotPages(baseUrl, resetInfo, deviceId, bootstrapOptions);\n\t\t\toptions.validateCurrentAuthorization?.();\n\t\t\tconst mergeResult = mergeScopeSnapshot(db, peerDeviceId, items, resetInfo, scanner);\n\t\t\tif (!mergeResult.ok) {\n\t\t\t\tconst error = \"scoped merge bootstrap apply failed\";\n\t\t\t\treturn {\n\t\t\t\t\tscope_id: scopeId,\n\t\t\t\t\tlabel: scope.label,\n\t\t\t\t\tok: false,\n\t\t\t\t\tfailureCategory: \"other\",\n\t\t\t\t\topsIn: 0,\n\t\t\t\t\topsOut: 0,\n\t\t\t\t\terror,\n\t\t\t\t\tbootstrapped: true,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: true,\n\t\t\t\topsIn: mergeResult.applied,\n\t\t\t\topsOut: 0,\n\t\t\t\tbootstrapped: true,\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tconst detail = err instanceof Error ? err.message.trim() || err.constructor.name : \"unknown\";\n\t\t\tconst error = `scoped merge bootstrap failed: ${detail}`;\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: false,\n\t\t\t\tfailureCategory: scopeFailureCategory(error),\n\t\t\t\topsIn: 0,\n\t\t\t\topsOut: 0,\n\t\t\t\terror,\n\t\t\t\tbootstrapped: true,\n\t\t\t};\n\t\t}\n\t}\n\n\t// Bootstrap when this device has never pulled the scope and has no local\n\t// rows. Populated scopes without a peer cursor are handled by the additive\n\t// merge-recovery branch above so this destructive bootstrap path stays safe.\n\tif (shouldBootstrapEmptyScope) {\n\t\ttry {\n\t\t\tconst resetInfo: SyncResetRequired = {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tgeneration: scope.sync_reset.generation,\n\t\t\t\tsnapshot_id: scope.sync_reset.snapshot_id,\n\t\t\t\tbaseline_cursor: scope.sync_reset.baseline_cursor,\n\t\t\t\tretained_floor_cursor: scope.sync_reset.retained_floor_cursor,\n\t\t\t\treset_required: true,\n\t\t\t\treason: \"initial_bootstrap\" as SyncResetRequired[\"reason\"],\n\t\t\t};\n\t\t\tconst { items } = await fetchAllSnapshotPages(baseUrl, resetInfo, deviceId, bootstrapOptions);\n\t\t\toptions.validateCurrentAuthorization?.();\n\t\t\t// TOCTOU re-check: another process (CLI write, plugin, concurrent\n\t\t\t// sync pass) could have created shared memories in this scope while\n\t\t\t// the snapshot was downloading. applyBootstrapSnapshot wipes all\n\t\t\t// shared rows for the scope before inserting the snapshot, so\n\t\t\t// proceeding would clobber those writes. Mirror the same guard the\n\t\t\t// default-scope auto-bootstrap path already enforces in syncOnce\n\t\t\t// (see \"needs_attention:shared_memories_appeared_during_bootstrap\").\n\t\t\tif (hasLocalRowsInScope(db, scopeId)) {\n\t\t\t\tconst error = \"needs_attention:shared_memories_appeared_during_bootstrap\";\n\t\t\t\treturn {\n\t\t\t\t\tscope_id: scopeId,\n\t\t\t\t\tlabel: scope.label,\n\t\t\t\t\tok: false,\n\t\t\t\t\tfailureCategory: \"other\",\n\t\t\t\t\topsIn: 0,\n\t\t\t\t\topsOut: 0,\n\t\t\t\t\terror,\n\t\t\t\t\tbootstrapped: true,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst bootstrapResult = applyScopeSnapshot(db, peerDeviceId, items, resetInfo, scanner);\n\t\t\tif (!bootstrapResult.ok) {\n\t\t\t\tconst error = \"bootstrap apply failed\";\n\t\t\t\treturn {\n\t\t\t\t\tscope_id: scopeId,\n\t\t\t\t\tlabel: scope.label,\n\t\t\t\t\tok: false,\n\t\t\t\t\tfailureCategory: \"other\",\n\t\t\t\t\topsIn: 0,\n\t\t\t\t\topsOut: 0,\n\t\t\t\t\terror,\n\t\t\t\t\tbootstrapped: true,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: true,\n\t\t\t\topsIn: bootstrapResult.applied,\n\t\t\t\topsOut: 0,\n\t\t\t\tbootstrapped: true,\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tconst detail = err instanceof Error ? err.message.trim() || err.constructor.name : \"unknown\";\n\t\t\tconst error = `scoped bootstrap failed: ${detail}`;\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: false,\n\t\t\t\tfailureCategory: scopeFailureCategory(error),\n\t\t\t\topsIn: 0,\n\t\t\t\topsOut: 0,\n\t\t\t\terror,\n\t\t\t\tbootstrapped: true,\n\t\t\t};\n\t\t}\n\t}\n\n\t// Incremental: pull /v1/ops?scope_id=X&since=<lastApplied>.\n\ttry {\n\t\tconst queryParams = new URLSearchParams({\n\t\t\tscope_id: scopeId,\n\t\t\tsince: lastApplied ?? \"\",\n\t\t\tlimit: String(limit),\n\t\t\tgeneration: String(scope.sync_reset.generation),\n\t\t\tsnapshot_id: scope.sync_reset.snapshot_id,\n\t\t});\n\t\tif (scope.sync_reset.baseline_cursor) {\n\t\t\tqueryParams.set(\"baseline_cursor\", scope.sync_reset.baseline_cursor);\n\t\t}\n\t\tconst url = `${baseUrl}/v1/ops?${queryParams.toString()}`;\n\t\tconst headers = {\n\t\t\t...buildDirectPeerAuthHeaders({\n\t\t\t\tdeviceId,\n\t\t\t\trecipientId: peerDeviceId,\n\t\t\t\tmethod: \"GET\",\n\t\t\t\turl,\n\t\t\t\tbodyBytes: Buffer.alloc(0),\n\t\t\t\tkeysDir,\n\t\t\t\tdbPath,\n\t\t\t}),\n\t\t\t...capabilityHeader(),\n\t\t};\n\t\tconst [status, payload] = await options.requestExecutor(\"GET\", url, { headers });\n\t\toptions.validateCurrentAuthorization?.();\n\n\t\tif (status === 409 && payload?.reset_required === true) {\n\t\t\t// Per-scope reset requested. Clear the stale scoped cursor so the\n\t\t\t// next pass picks a fresh bootstrap path instead of replaying the\n\t\t\t// same invalid boundary forever. We deliberately do not auto-bootstrap from here\n\t\t\t// to avoid surprising state changes mid-loop; the default-scope\n\t\t\t// auto-bootstrap path remains the canonical recovery mechanism.\n\t\t\tresetScopedPullProgress(db, options);\n\t\t\tconst reason = ((): SyncResetRequired[\"reason\"] => {\n\t\t\t\tswitch (payload.reason) {\n\t\t\t\t\tcase \"generation_mismatch\":\n\t\t\t\t\tcase \"boundary_mismatch\":\n\t\t\t\t\tcase \"missing_scope\":\n\t\t\t\t\tcase \"scope_inactive\":\n\t\t\t\t\tcase \"stale_epoch\":\n\t\t\t\t\tcase \"unsupported_scope\":\n\t\t\t\t\t\treturn payload.reason;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn \"stale_cursor\";\n\t\t\t\t}\n\t\t\t})();\n\t\t\tconst error = `reset_required:${reason}`;\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: false,\n\t\t\t\tfailureCategory: scopeResetFailureCategory(reason),\n\t\t\t\topsIn: 0,\n\t\t\t\topsOut: 0,\n\t\t\t\terror,\n\t\t\t\tresetRequired: {\n\t\t\t\t\treset_required: true,\n\t\t\t\t\treason,\n\t\t\t\t\tscope_id: typeof payload.scope_id === \"string\" ? payload.scope_id : scopeId,\n\t\t\t\t\tgeneration: Number(payload.generation ?? scope.sync_reset.generation),\n\t\t\t\t\tsnapshot_id: String(payload.snapshot_id ?? scope.sync_reset.snapshot_id),\n\t\t\t\t\tbaseline_cursor:\n\t\t\t\t\t\ttypeof payload.baseline_cursor === \"string\" ? payload.baseline_cursor.trim() : null,\n\t\t\t\t\tretained_floor_cursor:\n\t\t\t\t\t\ttypeof payload.retained_floor_cursor === \"string\"\n\t\t\t\t\t\t\t? payload.retained_floor_cursor.trim()\n\t\t\t\t\t\t\t: null,\n\t\t\t\t},\n\t\t\t\tbootstrapped: false,\n\t\t\t};\n\t\t}\n\n\t\tif (status !== 200 || payload == null) {\n\t\t\tconst detail = errorDetail(payload);\n\t\t\tconst suffix = detail ? ` (${status}: ${detail})` : ` (${status})`;\n\t\t\tconst error = `peer scoped ops fetch failed${suffix}`;\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: false,\n\t\t\t\tfailureCategory: scopeFailureCategory(error),\n\t\t\t\topsIn: 0,\n\t\t\t\topsOut: 0,\n\t\t\t\terror,\n\t\t\t\tbootstrapped: false,\n\t\t\t};\n\t\t}\n\n\t\tif (!isValidIncrementalOpsResponse(payload)) {\n\t\t\tconst error = \"invalid scoped ops response\";\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: false,\n\t\t\t\tfailureCategory: \"other\",\n\t\t\t\topsIn: 0,\n\t\t\t\topsOut: 0,\n\t\t\t\terror,\n\t\t\t\tbootstrapped: false,\n\t\t\t};\n\t\t}\n\n\t\tconst ops = extractReplicationOps(payload);\n\t\tconst mismatched = ops.find(\n\t\t\t(op) => op.device_id !== peerDeviceId || op.clock_device_id !== peerDeviceId,\n\t\t);\n\t\tif (mismatched) {\n\t\t\tconst error = `inbound op device mismatch:${mismatched.op_id}`;\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: false,\n\t\t\t\tfailureCategory: \"other\",\n\t\t\t\topsIn: 0,\n\t\t\t\topsOut: 0,\n\t\t\t\terror,\n\t\t\t\tbootstrapped: false,\n\t\t\t};\n\t\t}\n\n\t\tconst applyOptions = scopedInboundOptions(peerDeviceId, keysDir);\n\t\tconst applied = applyReplicationOps(db, ops, deviceId, scanner, applyOptions);\n\t\tif (applied.rejected > 0) {\n\t\t\tconst reason = applied.rejections[0]?.reason ?? \"scope_rejected\";\n\t\t\tconst error = `inbound scope rejected:${reason}`;\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: false,\n\t\t\t\tfailureCategory: \"scope\",\n\t\t\t\topsIn: 0,\n\t\t\t\topsOut: 0,\n\t\t\t\terror,\n\t\t\t\tbootstrapped: false,\n\t\t\t};\n\t\t}\n\n\t\tconst reconciliation = reconcileReceivedRowsForExchange(db, options);\n\t\tconst vectorWork = mergedReceiveVectorWork(\n\t\t\tapplied.vectorWork,\n\t\t\treconciliation.deleted_memory_ids,\n\t\t);\n\t\ttry {\n\t\t\tqueueVectorBackfillForIncrementalSync(db, vectorWork);\n\t\t} catch (queueErr) {\n\t\t\tconst fallback = await bestEffortMaintainVectorsForSyncFallback(db, vectorWork);\n\t\t\tif (fallback.errors.length > 0) {\n\t\t\t\tconst error = `vector catch-up failed: ${queueErr instanceof Error ? queueErr.message : String(queueErr)}; fallback failed: ${fallback.errors.join(\"; \")}`;\n\t\t\t\treturn {\n\t\t\t\t\tscope_id: scopeId,\n\t\t\t\t\tlabel: scope.label,\n\t\t\t\t\tok: false,\n\t\t\t\t\tfailureCategory: \"other\",\n\t\t\t\t\treceiveFailureCode: applyReceiveFailure(applied.errors),\n\t\t\t\t\topsIn: 0,\n\t\t\t\t\topsOut: 0,\n\t\t\t\t\terror,\n\t\t\t\t\tbootstrapped: false,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\toptions.validateCurrentAuthorization?.();\n\t\tconst inboundCursorCandidate = asOptionalCursor(payload.next_cursor);\n\t\t// Never advance the inbound cursor past a pass that had apply errors: a\n\t\t// failed op that was not durably recorded would otherwise be skipped\n\t\t// forever (silent data loss). Holding the cursor retries it next pass.\n\t\t// Do NOT \"fix\" a persistent stall by recording throwing ops — that\n\t\t// reintroduces the silent data loss this guards against.\n\t\tif (applied.errors.length > 0) {\n\t\t\tprocess.stderr.write(\n\t\t\t\t`[codemem] sync: holding inbound cursor for scope ${scopeId} — ${applied.errors.length} op(s) failed to apply and will be retried\\n`,\n\t\t\t);\n\t\t}\n\t\tif (applied.errors.length === 0 && cursorAdvances(lastApplied, inboundCursorCandidate)) {\n\t\t\tsetReplicationCursor(db, peerDeviceId, { lastApplied: inboundCursorCandidate }, scopeId);\n\t\t}\n\n\t\tif (applied.errors.length > 0) {\n\t\t\t// Cursor was held (apply errors) — inbound replication for this scope\n\t\t\t// is incomplete and stalled on this window. Report failure so a\n\t\t\t// persistent stall surfaces instead of looking like a healthy sync.\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: false,\n\t\t\t\tfailureCategory: \"other\",\n\t\t\t\topsIn: applied.applied,\n\t\t\t\treceiveFailureCode: \"apply_failed\",\n\t\t\t\topsOut: 0,\n\t\t\t\terror: `inbound apply incomplete: ${applied.errors.length} op(s) failed; cursor held for retry`,\n\t\t\t\tbootstrapped: hasNullBaselineBootstrapMarker,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tscope_id: scopeId,\n\t\t\tlabel: scope.label,\n\t\t\tok: true,\n\t\t\topsIn: applied.applied,\n\t\t\topsOut: 0,\n\t\t\tbootstrapped: hasNullBaselineBootstrapMarker,\n\t\t};\n\t} catch (err) {\n\t\tconst detail = err instanceof Error ? err.message.trim() || err.constructor.name : \"unknown\";\n\t\tconst error = `scoped incremental failed: ${detail}`;\n\t\treturn {\n\t\t\tscope_id: scopeId,\n\t\t\tlabel: scope.label,\n\t\t\tok: false,\n\t\t\tfailureCategory: scopeFailureCategory(error),\n\t\t\topsIn: 0,\n\t\t\topsOut: 0,\n\t\t\terror,\n\t\t\tbootstrapped: false,\n\t\t};\n\t}\n}\n\n// Internal transport entrypoint. The caller authenticates one selected scope first.\nexport { syncOneScope as syncScopedPeerPull };\n\n// ---------------------------------------------------------------------------\n// Preflight\n// ---------------------------------------------------------------------------\n\n/** Run migration + replication backfill preflight. */\nexport function syncPassPreflight(db: Database): void {\n\tensureAdditiveSchemaCompatibility(db);\n\tmigrateLegacyImportKeys(db, 2000);\n\tbackfillReplicationOps(db, 200);\n}\n\ntype PeerResetBoundary = NonNullable<ReturnType<typeof parsePeerResetBoundary>>;\n\nfunction scopedInboundOptions(peerDeviceId: string, keysDir: string | undefined) {\n\treturn {\n\t\t...RECEIVE_WINDOW_OPTIONS,\n\t\tactivityPeerDeviceId: peerDeviceId,\n\t\tinboundScopeValidation: { peerDeviceId },\n\t\tkeysDir,\n\t};\n}\n\ninterface SyncExchangeContext {\n\trequestExecutor: RequestJsonExecutor;\n\trecordAttempt: typeof recordSyncAttempt;\n\tdeferConnectionFailure: boolean;\n\tdb: Database;\n\tpeerDeviceId: string;\n\tdeviceId: string;\n\tpinnedFingerprint: string;\n\tpendingBootstrapGrantId: string | undefined;\n\tlimit: number;\n\tkeysDir: string | undefined;\n\tdbPath: string | undefined;\n\tscanner: SecretScanner | undefined;\n\trefreshAuthorization: boolean;\n}\n\ninterface SyncCursorState {\n\tlastApplied: string | null;\n\tlastAcked: string | null;\n}\n\ninterface NegotiatedPeerExchange {\n\tbaseUrl: string;\n\tstatusPayload: Record<string, unknown>;\n\tresetBoundary: PeerResetBoundary;\n\tcapabilities: SyncCapabilityDiagnostics;\n}\n\nclass PeerProtocolMismatchError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"PeerProtocolMismatchError\";\n\t}\n}\n\nclass PeerNegotiationError extends Error {\n\treadonly capabilities: SyncCapabilityDiagnostics;\n\treadonly protocolMismatch: boolean;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tcapabilities: SyncCapabilityDiagnostics,\n\t\toptions: { protocolMismatch: boolean },\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"PeerNegotiationError\";\n\t\tthis.capabilities = capabilities;\n\t\tthis.protocolMismatch = options.protocolMismatch;\n\t}\n}\n\nasync function negotiatePeerExchange(\n\tcontext: SyncExchangeContext,\n\tbaseUrl: string,\n): Promise<NegotiatedPeerExchange> {\n\tconst statusUrl = `${baseUrl}/v1/status`;\n\tconst statusHeaders = {\n\t\t...buildDirectPeerAuthHeaders({\n\t\t\tdeviceId: context.deviceId,\n\t\t\trecipientId: context.peerDeviceId,\n\t\t\tmethod: \"GET\",\n\t\t\turl: statusUrl,\n\t\t\tbodyBytes: Buffer.alloc(0),\n\t\t\tkeysDir: context.keysDir,\n\t\t\tdbPath: context.dbPath,\n\t\t\tbootstrapGrantId: context.pendingBootstrapGrantId,\n\t\t}),\n\t\t...capabilityHeader(),\n\t\t...(context.refreshAuthorization ? { [SYNC_AUTHORIZATION_REFRESH_HEADER]: \"1\" } : {}),\n\t};\n\tconst [statusCode, statusPayload] = await context.requestExecutor(\"GET\", statusUrl, {\n\t\theaders: statusHeaders,\n\t});\n\tif (statusCode !== 200 || !statusPayload) {\n\t\tconst detail = errorDetail(statusPayload);\n\t\tconst suffix = detail ? ` (${statusCode}: ${detail})` : ` (${statusCode})`;\n\t\tthrow new Error(`peer status failed${suffix}`);\n\t}\n\tif (statusPayload.fingerprint !== context.pinnedFingerprint) {\n\t\tthrow new Error(\"peer fingerprint mismatch\");\n\t}\n\tpersistPeerRuntimeVersion(context.db, context.peerDeviceId, statusPayload);\n\tconst capabilities = capabilityDiagnostics(statusPayload.sync_capability);\n\ttry {\n\t\tif (String(statusPayload.protocol_version ?? \"\") !== EXPECTED_SYNC_PROTOCOL_VERSION) {\n\t\t\tthrow new PeerProtocolMismatchError(\n\t\t\t\t`peer protocol mismatch (expected ${EXPECTED_SYNC_PROTOCOL_VERSION}, got ${String(statusPayload.protocol_version ?? \"missing\")})`,\n\t\t\t);\n\t\t}\n\t\tconst resetBoundary = parsePeerResetBoundary(statusPayload);\n\t\tif (!resetBoundary) throw new Error(\"peer status missing sync_reset boundary\");\n\t\tawait reconcilePeerRowsBeforeExchange(context.db, {\n\t\t\tlocalDeviceId: context.deviceId,\n\t\t\tpeerDeviceId: context.peerDeviceId,\n\t\t\tkeysDir: context.keysDir,\n\t\t});\n\t\tif (context.pendingBootstrapGrantId) {\n\t\t\tcontext.db\n\t\t\t\t.prepare(`UPDATE sync_peers SET pending_bootstrap_grant_id = NULL\n\t\t\t\t\tWHERE peer_device_id = ? AND pending_bootstrap_grant_id = ?`)\n\t\t\t\t.run(context.peerDeviceId, context.pendingBootstrapGrantId);\n\t\t}\n\t\treturn { baseUrl, statusPayload, resetBoundary, capabilities };\n\t} catch (error) {\n\t\tconst message =\n\t\t\terror instanceof Error ? error.message.trim() || error.constructor.name : \"unknown\";\n\t\tthrow new PeerNegotiationError(message, capabilities, {\n\t\t\tprotocolMismatch: error instanceof PeerProtocolMismatchError,\n\t\t});\n\t}\n}\n\nfunction sharedMemoryCount(db: Database): number {\n\treturn Number(\n\t\t(\n\t\t\tdb.prepare(\"SELECT count(*) as n FROM memory_items WHERE import_key IS NOT NULL\").get() as {\n\t\t\t\tn: number;\n\t\t\t}\n\t\t)?.n ?? 0,\n\t);\n}\n\nfunction snapshotAccessDenied(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n\treset: SyncResetRequired,\n): SyncResult | null {\n\tif (!reset.scope_id) return null;\n\tconst failure = scopedSnapshotAccessFailure(context.db, {\n\t\tscopeId: reset.scope_id,\n\t\tpeerDeviceId: context.peerDeviceId,\n\t\tlocalDeviceId: context.deviceId,\n\t});\n\tif (!failure) return null;\n\tconst result = scopedSnapshotAccessDeniedResult(peer.baseUrl, reset, failure);\n\tcontext.recordAttempt(context.db, context.peerDeviceId, {\n\t\tok: false,\n\t\terror: `reset_required:${failure}`,\n\t\tfailureCategory: result.failureCategory,\n\t\tcapabilities: peer.capabilities,\n\t});\n\treturn result;\n}\n\ntype SnapshotItems = Awaited<ReturnType<typeof fetchAllSnapshotPages>>[\"items\"];\n\nasync function finishInitialBootstrap(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n\tresetInfo: SyncResetRequired,\n\titems: SnapshotItems,\n): Promise<SyncResult> {\n\tconst bootstrap = applyBootstrapSnapshot(\n\t\tcontext.db,\n\t\tcontext.peerDeviceId,\n\t\titems,\n\t\tresetInfo,\n\t\tcontext.scanner,\n\t\tRECEIVE_WINDOW_OPTIONS,\n\t);\n\tif (!bootstrap.ok) throw new Error(\"initial bootstrap apply failed\");\n\tconst scoped =\n\t\tpeer.capabilities.negotiated === \"scoped\"\n\t\t\t? await runScopedSync(context.db, context.requestExecutor, {\n\t\t\t\t\tpeerDeviceId: context.peerDeviceId,\n\t\t\t\t\tbaseUrl: peer.baseUrl,\n\t\t\t\t\tdeviceId: context.deviceId,\n\t\t\t\t\tstatusPayload: peer.statusPayload,\n\t\t\t\t\tkeysDir: context.keysDir,\n\t\t\t\t\tdbPath: context.dbPath,\n\t\t\t\t\tscanner: context.scanner,\n\t\t\t\t\tlimit: context.limit,\n\t\t\t\t})\n\t\t\t: { results: [], totalOpsIn: 0 };\n\tconst ok = scoped.results.every((result) => result.ok);\n\tconst error = ok\n\t\t? undefined\n\t\t: `scoped sync incomplete: ${scoped.results\n\t\t\t\t.filter((result) => !result.ok)\n\t\t\t\t.map((result) => `${result.scope_id}=${result.error ?? \"unknown\"}`)\n\t\t\t\t.join(\"; \")}`;\n\tconst failureCategory = aggregateScopeFailureCategory(scoped.results);\n\trecordPeerSuccess(context.db, context.peerDeviceId, peer.baseUrl);\n\tcontext.recordAttempt(context.db, context.peerDeviceId, {\n\t\tok,\n\t\topsIn: bootstrap.applied + scoped.totalOpsIn,\n\t\topsOut: 0,\n\t\tcapabilities: peer.capabilities,\n\t\terror,\n\t\tfailureCategory,\n\t});\n\treturn {\n\t\tok,\n\t\taddress: peer.baseUrl,\n\t\tfailureCategory,\n\t\topsIn: bootstrap.applied + scoped.totalOpsIn,\n\t\topsOut: 0,\n\t\taddressErrors: [],\n\t\treceiveFailureCode: aggregateReceiveFailure(scoped.results),\n\t\tperScopeResults: scoped.results.length > 0 ? scoped.results : undefined,\n\t};\n}\n\nasync function performInitialBootstrap(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n): Promise<SyncResult> {\n\tconst resetInfo = {\n\t\tscope_id: peer.resetBoundary.scope_id,\n\t\tgeneration: peer.resetBoundary.generation,\n\t\tsnapshot_id: peer.resetBoundary.snapshot_id,\n\t\tbaseline_cursor: peer.resetBoundary.baseline_cursor ?? null,\n\t\tretained_floor_cursor: peer.resetBoundary.retained_floor_cursor ?? null,\n\t\treset_required: true as const,\n\t\treason: \"initial_bootstrap\" as const,\n\t};\n\tconst accessDenied = snapshotAccessDenied(context, peer, resetInfo);\n\tif (accessDenied) return accessDenied;\n\tconst { items } = await fetchAllSnapshotPages(peer.baseUrl, resetInfo, context.deviceId, {\n\t\trequestExecutor: context.requestExecutor,\n\t\tkeysDir: context.keysDir,\n\t\tdbPath: context.dbPath,\n\t\trecipientId: context.peerDeviceId,\n\t\tpageSize: BOOTSTRAP_PAGE_SIZE,\n\t\ttimeoutS: BOOTSTRAP_REQUEST_TIMEOUT_S,\n\t});\n\tconst postFetchSharedCount = sharedMemoryCount(context.db);\n\tif (postFetchSharedCount > 0) {\n\t\tcontext.recordAttempt(context.db, context.peerDeviceId, {\n\t\t\tok: false,\n\t\t\terror: \"needs_attention:shared_memories_appeared_during_bootstrap\",\n\t\t\tfailureCategory: \"other\",\n\t\t\tcapabilities: peer.capabilities,\n\t\t});\n\t\treturn {\n\t\t\tok: false,\n\t\t\taddress: peer.baseUrl,\n\t\t\terror: `needs attention: ${postFetchSharedCount} shared memory change(s) appeared during initial bootstrap fetch`,\n\t\t\tfailureCategory: \"other\",\n\t\t\topsIn: 0,\n\t\t\topsOut: 0,\n\t\t\taddressErrors: [],\n\t\t};\n\t}\n\treturn finishInitialBootstrap(context, peer, resetInfo, items);\n}\n\nasync function tryInitialBootstrap(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n\tcursors: SyncCursorState,\n): Promise<SyncResult | null> {\n\tif (cursors.lastApplied !== null || cursors.lastAcked !== null) return null;\n\tif (sharedMemoryCount(context.db) !== 0) return null;\n\ttry {\n\t\treturn await performInitialBootstrap(context, peer);\n\t} catch (error) {\n\t\tconst detail = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(`initial bootstrap failed: ${detail}`);\n\t}\n}\n\nfunction resetRequiredFromPayload(payload: Record<string, unknown>): SyncResetRequired {\n\tconst reason =\n\t\tpayload.reason === \"generation_mismatch\" ||\n\t\tpayload.reason === \"boundary_mismatch\" ||\n\t\tpayload.reason === \"missing_scope\" ||\n\t\tpayload.reason === \"unsupported_scope\"\n\t\t\t? payload.reason\n\t\t\t: \"stale_cursor\";\n\treturn {\n\t\treset_required: true,\n\t\treason,\n\t\tscope_id: typeof payload.scope_id === \"string\" ? payload.scope_id : null,\n\t\tgeneration: Number(payload.generation ?? 1),\n\t\tsnapshot_id: String(payload.snapshot_id ?? \"\"),\n\t\tbaseline_cursor: asOptionalCursor(payload.baseline_cursor),\n\t\tretained_floor_cursor: asOptionalCursor(payload.retained_floor_cursor),\n\t};\n}\n\nfunction resetBlockedResult(\n\tbaseUrl: string,\n\tcount: number,\n\tresetRequired: SyncResetRequired,\n\twhen: \"before\" | \"during\",\n): SyncResult {\n\tconst timing = when === \"during\" ? \" appeared during bootstrap fetch\" : \" block automatic reset\";\n\treturn {\n\t\tok: false,\n\t\taddress: baseUrl,\n\t\terror: `needs attention: ${count} unsynced shared memory change(s)${timing}`,\n\t\tfailureCategory: \"other\",\n\t\topsIn: 0,\n\t\topsOut: 0,\n\t\taddressErrors: [],\n\t\tresetRequired,\n\t};\n}\n\nfunction failedResetBootstrap(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n\tresetRequired: SyncResetRequired,\n\terror: unknown,\n): SyncResult {\n\tconst detail = error instanceof Error ? error.message : String(error);\n\tcontext.recordAttempt(context.db, context.peerDeviceId, {\n\t\tok: false,\n\t\terror: `bootstrap_failed:${detail}`,\n\t\tfailureCategory: \"other\",\n\t\tcapabilities: peer.capabilities,\n\t});\n\treturn {\n\t\tok: false,\n\t\taddress: peer.baseUrl,\n\t\terror: `bootstrap failed: ${detail}`,\n\t\tfailureCategory: \"other\",\n\t\topsIn: 0,\n\t\topsOut: 0,\n\t\taddressErrors: [],\n\t\tresetRequired,\n\t};\n}\n\nasync function performResetBootstrap(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n\tresetRequired: SyncResetRequired,\n): Promise<SyncResult> {\n\tconst dirtyLocal = hasUnsyncedSharedMemoryChanges(context.db);\n\tif (dirtyLocal.dirty) {\n\t\tcontext.recordAttempt(context.db, context.peerDeviceId, {\n\t\t\tok: false,\n\t\t\terror: `needs_attention:local_unsynced_shared_memory:${dirtyLocal.count}`,\n\t\t\tfailureCategory: \"other\",\n\t\t\tcapabilities: peer.capabilities,\n\t\t});\n\t\treturn resetBlockedResult(peer.baseUrl, dirtyLocal.count, resetRequired, \"before\");\n\t}\n\ttry {\n\t\tconst accessDenied = snapshotAccessDenied(context, peer, resetRequired);\n\t\tif (accessDenied) return accessDenied;\n\t\tconst { items } = await fetchAllSnapshotPages(peer.baseUrl, resetRequired, context.deviceId, {\n\t\t\trequestExecutor: context.requestExecutor,\n\t\t\tkeysDir: context.keysDir,\n\t\t\tdbPath: context.dbPath,\n\t\t\trecipientId: context.peerDeviceId,\n\t\t\ttimeoutS: BOOTSTRAP_REQUEST_TIMEOUT_S,\n\t\t});\n\t\tconst dirtyAfterFetch = hasUnsyncedSharedMemoryChanges(context.db);\n\t\tif (dirtyAfterFetch.dirty) {\n\t\t\tcontext.recordAttempt(context.db, context.peerDeviceId, {\n\t\t\t\tok: false,\n\t\t\t\terror: `needs_attention:local_unsynced_shared_memory:${dirtyAfterFetch.count}`,\n\t\t\t\tfailureCategory: \"other\",\n\t\t\t\tcapabilities: peer.capabilities,\n\t\t\t});\n\t\t\treturn resetBlockedResult(peer.baseUrl, dirtyAfterFetch.count, resetRequired, \"during\");\n\t\t}\n\t\tconst bootstrapResult = applyBootstrapSnapshot(\n\t\t\tcontext.db,\n\t\t\tcontext.peerDeviceId,\n\t\t\titems,\n\t\t\tresetRequired,\n\t\t\tcontext.scanner,\n\t\t\tRECEIVE_WINDOW_OPTIONS,\n\t\t);\n\t\tif (!bootstrapResult.ok) throw new Error(\"bootstrap apply failed\");\n\t\trecordPeerSuccess(context.db, context.peerDeviceId, peer.baseUrl);\n\t\tcontext.recordAttempt(context.db, context.peerDeviceId, {\n\t\t\tok: true,\n\t\t\topsIn: bootstrapResult.applied,\n\t\t\topsOut: 0,\n\t\t\tcapabilities: peer.capabilities,\n\t\t});\n\t\treturn {\n\t\t\tok: true,\n\t\t\taddress: peer.baseUrl,\n\t\t\topsIn: bootstrapResult.applied,\n\t\t\topsOut: 0,\n\t\t\taddressErrors: [],\n\t\t};\n\t} catch (error) {\n\t\treturn failedResetBootstrap(context, peer, resetRequired, error);\n\t}\n}\n\ninterface PulledDefaultOps {\n\tkind: \"ops\";\n\tpayload: Record<string, unknown>;\n\tops: ReplicationOp[];\n}\n\ninterface PulledResetResult {\n\tkind: \"result\";\n\tresult: SyncResult;\n}\n\nasync function pullDefaultScope(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n\tlastApplied: string | null,\n): Promise<PulledDefaultOps | PulledResetResult> {\n\tconst queryParams = new URLSearchParams({\n\t\tsince: lastApplied ?? \"\",\n\t\tlimit: String(context.limit),\n\t\tgeneration: String(peer.resetBoundary.generation),\n\t\tsnapshot_id: peer.resetBoundary.snapshot_id,\n\t});\n\tif (peer.resetBoundary.baseline_cursor) {\n\t\tqueryParams.set(\"baseline_cursor\", peer.resetBoundary.baseline_cursor);\n\t}\n\tconst getUrl = `${peer.baseUrl}/v1/ops?${queryParams.toString()}`;\n\tconst getHeaders = {\n\t\t...buildDirectPeerAuthHeaders({\n\t\t\tdeviceId: context.deviceId,\n\t\t\trecipientId: context.peerDeviceId,\n\t\t\tmethod: \"GET\",\n\t\t\turl: getUrl,\n\t\t\tbodyBytes: Buffer.alloc(0),\n\t\t\tkeysDir: context.keysDir,\n\t\t\tdbPath: context.dbPath,\n\t\t}),\n\t\t...capabilityHeader(),\n\t};\n\tconst [status, payload] = await context.requestExecutor(\"GET\", getUrl, { headers: getHeaders });\n\tif (status === 409 && payload?.reset_required === true) {\n\t\treturn {\n\t\t\tkind: \"result\",\n\t\t\tresult: await performResetBootstrap(context, peer, resetRequiredFromPayload(payload)),\n\t\t};\n\t}\n\tif (status !== 200 || payload == null) {\n\t\tconst detail = errorDetail(payload);\n\t\tconst suffix = detail ? ` (${status}: ${detail})` : ` (${status})`;\n\t\tthrow new Error(`peer ops fetch failed${suffix}`);\n\t}\n\tif (!isValidIncrementalOpsResponse(payload)) throw new Error(\"invalid ops response\");\n\tconst ops = extractReplicationOps(payload);\n\tconst mismatchedOp = ops.find(\n\t\t(op) => op.device_id !== context.peerDeviceId || op.clock_device_id !== context.peerDeviceId,\n\t);\n\tif (mismatchedOp) throw new Error(`inbound op device mismatch:${mismatchedOp.op_id}`);\n\treturn { kind: \"ops\", payload, ops };\n}\n\ntype AppliedReplicationOps = ReturnType<typeof applyReplicationOps>;\n\nasync function applyPulledDefaultOps(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n\tpulled: PulledDefaultOps,\n\tlastApplied: string | null,\n): Promise<{ applied: AppliedReplicationOps; lastApplied: string | null }> {\n\tconst inboundScopeValidation =\n\t\tpeer.capabilities.negotiated === \"unsupported\"\n\t\t\t? { peerDeviceId: context.peerDeviceId, enabled: false }\n\t\t\t: { peerDeviceId: context.peerDeviceId };\n\tconst applied = applyReplicationOps(context.db, pulled.ops, context.deviceId, context.scanner, {\n\t\t...RECEIVE_WINDOW_OPTIONS,\n\t\tactivityPeerDeviceId: context.peerDeviceId,\n\t\tinboundScopeValidation,\n\t\tkeysDir: context.keysDir,\n\t});\n\tif (applied.rejected > 0) {\n\t\tconst firstReason = applied.rejections[0]?.reason ?? \"scope_rejected\";\n\t\tthrow new Error(`inbound scope rejected:${firstReason}`);\n\t}\n\tconst reconciliation = reconcileStalePeerReceivedRows(context.db, {\n\t\tlocalDeviceId: context.deviceId,\n\t\tpeerDeviceId: context.peerDeviceId,\n\t\tkeysDir: context.keysDir,\n\t});\n\tconst vectorWork = {\n\t\tupsertMemoryIds: applied.vectorWork.upsertMemoryIds,\n\t\tdeleteMemoryIds: [...applied.vectorWork.deleteMemoryIds, ...reconciliation.deleted_memory_ids],\n\t};\n\ttry {\n\t\tqueueVectorBackfillForIncrementalSync(context.db, vectorWork);\n\t} catch (queueError) {\n\t\tconst fallback = await bestEffortMaintainVectorsForSyncFallback(context.db, vectorWork);\n\t\tif (fallback.errors.length > 0) {\n\t\t\tconst details = fallback.errors.join(\"; \");\n\t\t\tthrow new Error(\n\t\t\t\t`vector catch-up queue failed: ${queueError instanceof Error ? queueError.message : String(queueError)}; fallback failed: ${details}`,\n\t\t\t);\n\t\t}\n\t}\n\tconst inboundCursor = asOptionalCursor(pulled.payload.next_cursor);\n\tif (applied.errors.length > 0) {\n\t\tprocess.stderr.write(\n\t\t\t`[codemem] sync: holding inbound cursor for peer ${context.peerDeviceId} — ${applied.errors.length} op(s) failed to apply and will be retried\\n`,\n\t\t);\n\t}\n\tif (applied.errors.length !== 0 || !cursorAdvances(lastApplied, inboundCursor)) {\n\t\treturn { applied, lastApplied };\n\t}\n\tsetReplicationCursor(context.db, context.peerDeviceId, { lastApplied: inboundCursor });\n\treturn { applied, lastApplied: inboundCursor };\n}\n\n/**\n * Drop scoped ops the peer already holds, so a path switch does not resend them.\n *\n * The relay channel acknowledges per scope in `sync_channel_progress`, while\n * this legacy push tracks one interleaved cursor. A scope's position is the\n * later of the channel ACK, when its boundary still matches the peer's current\n * one, and the pull cursor the peer reports in status. Ops at or before that\n * position were already applied there. Legacy peers report no scopes, so\n * nothing is dropped for them.\n */\nfunction withoutOpsPeerAlreadyHolds(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n\tops: ReplicationOp[],\n): ReplicationOp[] {\n\tconst held = new Map<string, string>();\n\tfor (const scope of parseAuthorizedScopes(peer.statusPayload.authorized_scopes)) {\n\t\tconst progress = getSyncChannelProgress(context.db, context.peerDeviceId, scope.scope_id);\n\t\tconst acked = hasCompletedSyncChannelBoundary(progress, scope.sync_reset)\n\t\t\t? (progress?.last_acked_cursor ?? null)\n\t\t\t: null;\n\t\tconst position = [acked, scope.applied_cursor]\n\t\t\t.filter((cursor): cursor is string => cursor !== null)\n\t\t\t.sort()\n\t\t\t.at(-1);\n\t\tif (position) held.set(scope.scope_id, position);\n\t}\n\tif (held.size === 0) return ops;\n\treturn ops.filter((op) => {\n\t\tconst position = op.scope_id ? held.get(op.scope_id) : undefined;\n\t\treturn position === undefined || `${op.created_at}|${op.op_id}` > position;\n\t});\n}\n\ninterface PushedDefaultOps {\n\toutboundOps: ReplicationOp[];\n\tskippedOutbound: FilterReplicationSkipped | null | undefined;\n\topsSkipped: number;\n\tlastAcked: string | null;\n}\n\nasync function pushDefaultScope(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n\tlastAcked: string | null,\n): Promise<PushedDefaultOps> {\n\tconst [outboundWindow, outboundCursor] = loadLocalOpsSince(\n\t\tcontext.db,\n\t\tlastAcked,\n\t\tcontext.deviceId,\n\t\tcontext.limit,\n\t);\n\tconst [allowedOps, filteredOutboundCursor, skippedOutbound] =\n\t\tfilterReplicationOpsForSyncWithStatus(context.db, outboundWindow, context.peerDeviceId, {\n\t\t\tlocalDeviceId: context.deviceId,\n\t\t\tsupportsReassignScope: supportsSyncFeature(\n\t\t\t\tpeer.statusPayload.sync_features,\n\t\t\t\t\"reassign_scope\",\n\t\t\t),\n\t\t});\n\tconst outboundOps = withoutOpsPeerAlreadyHolds(context, peer, allowedOps);\n\tconst postUrl = `${peer.baseUrl}/v1/ops`;\n\t// An idle sender still verifies the signed POST path without claiming any transfer.\n\tconst batches = outboundOps.length > 0 ? chunkOpsBySize(outboundOps, MAX_SYNC_BODY_BYTES) : [[]];\n\tfor (const batch of batches) {\n\t\tawait pushOps(\n\t\t\tpostUrl,\n\t\t\tcontext.deviceId,\n\t\t\tcontext.peerDeviceId,\n\t\t\tbatch,\n\t\t\tcontext.requestExecutor,\n\t\t\t(acknowledged) => {\n\t\t\t\tcontext.db.transaction(() => {\n\t\t\t\t\trecordSyncTransferReceipts(\n\t\t\t\t\t\tcontext.db,\n\t\t\t\t\t\tcontext.peerDeviceId,\n\t\t\t\t\t\t\"send\",\n\t\t\t\t\t\tacknowledged.map((op) => op.op_id),\n\t\t\t\t\t);\n\t\t\t\t\trecordSyncTransferObservation(context.db, context.peerDeviceId, \"send\");\n\t\t\t\t})();\n\t\t\t},\n\t\t\tcontext.keysDir,\n\t\t\tcontext.dbPath,\n\t\t);\n\t}\n\tconst ackCursor = filteredOutboundCursor ?? outboundCursor;\n\tlet nextLastAcked = lastAcked;\n\tif (ackCursor && cursorAdvances(lastAcked, ackCursor)) {\n\t\tsetReplicationCursor(context.db, context.peerDeviceId, { lastAcked: ackCursor });\n\t\tnextLastAcked = ackCursor;\n\t}\n\treturn {\n\t\toutboundOps,\n\t\tskippedOutbound,\n\t\topsSkipped: skippedOutbound?.skipped_count ?? 0,\n\t\tlastAcked: nextLastAcked,\n\t};\n}\n\nfunction incrementalReceiveErrors(\n\tapplyErrors: readonly string[],\n\tscopes: SyncScopeResult[],\n): string[] {\n\tconst errors: string[] = [];\n\tif (applyErrors.length > 0) {\n\t\terrors.push(\n\t\t\t`inbound apply incomplete: ${applyErrors.length} op(s) failed; cursor held for retry`,\n\t\t);\n\t}\n\tconst failedScopes = scopes.filter((result) => !result.ok);\n\tif (failedScopes.length > 0) {\n\t\terrors.push(\n\t\t\t`scoped sync incomplete: ${failedScopes\n\t\t\t\t.map((result) => `${result.scope_id}=${result.error ?? \"unknown\"}`)\n\t\t\t\t.join(\"; \")}`,\n\t\t);\n\t}\n\treturn errors;\n}\n\nasync function finishIncrementalExchange(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n\tapplied: AppliedReplicationOps,\n\tpushed: PushedDefaultOps,\n): Promise<SyncResult> {\n\tconst scoped =\n\t\tpeer.capabilities.negotiated === \"scoped\"\n\t\t\t? await runScopedSync(context.db, context.requestExecutor, {\n\t\t\t\t\tpeerDeviceId: context.peerDeviceId,\n\t\t\t\t\tbaseUrl: peer.baseUrl,\n\t\t\t\t\tdeviceId: context.deviceId,\n\t\t\t\t\tstatusPayload: peer.statusPayload,\n\t\t\t\t\tkeysDir: context.keysDir,\n\t\t\t\t\tdbPath: context.dbPath,\n\t\t\t\t\tscanner: context.scanner,\n\t\t\t\t\tlimit: context.limit,\n\t\t\t\t})\n\t\t\t: { results: [], totalOpsIn: 0 };\n\tconst allScopesOk = scoped.results.every((result) => result.ok);\n\tconst inboundIncomplete = applied.errors.length > 0;\n\tconst errors = incrementalReceiveErrors(applied.errors, scoped.results);\n\tconst ok = allScopesOk && !inboundIncomplete;\n\tconst error = errors.length > 0 ? errors.join(\"; \") : undefined;\n\tconst failureCategory = inboundIncomplete\n\t\t? \"other\"\n\t\t: aggregateScopeFailureCategory(scoped.results);\n\tif (!inboundIncomplete) recordPeerSuccess(context.db, context.peerDeviceId, peer.baseUrl);\n\tcontext.recordAttempt(context.db, context.peerDeviceId, {\n\t\tok,\n\t\topsIn: applied.applied + scoped.totalOpsIn,\n\t\topsOut: pushed.outboundOps.length,\n\t\tcapabilities: peer.capabilities,\n\t\terror,\n\t\tfailureCategory,\n\t});\n\treturn {\n\t\tok,\n\t\taddress: peer.baseUrl,\n\t\terror,\n\t\tfailureCategory,\n\t\topsIn: applied.applied + scoped.totalOpsIn,\n\t\topsOut: pushed.outboundOps.length,\n\t\topsSkipped: pushed.opsSkipped,\n\t\tskippedOut: pushed.skippedOutbound ?? null,\n\t\taddressErrors: [],\n\t\treceiveFailureCode: aggregateReceiveFailure(scoped.results, { applyErrors: applied.errors }),\n\t\tperScopeResults: scoped.results.length > 0 ? scoped.results : undefined,\n\t};\n}\n\ntype SyncAddressOutcome =\n\t| { kind: \"success\"; result: SyncResult }\n\t| {\n\t\t\tkind: \"failure\";\n\t\t\terror: unknown;\n\t\t\tcapabilities: SyncCapabilityDiagnostics | undefined;\n\t\t\tnegotiationFailed?: boolean;\n\t };\n\nfunction recordReceiveResult<\n\tT extends {\n\t\tok: boolean;\n\t\tfailureCategory?: SyncFailureCategory;\n\t\treceiveFailureCode?: SyncTransferErrorCode;\n\t},\n>(context: SyncExchangeContext, result: T, options: { preserveError?: boolean } = {}): T {\n\tlet errorCode: SyncTransferErrorCode | undefined;\n\tif (!result.ok) {\n\t\terrorCode =\n\t\t\tresult.receiveFailureCode ??\n\t\t\t(result.failureCategory === \"scope\" ? \"scope_rejected\" : \"exchange_failed\");\n\t}\n\trecordSyncTransferObservation(context.db, context.peerDeviceId, \"receive\", {\n\t\t...options,\n\t\terrorCode,\n\t});\n\treturn result;\n}\n\nasync function syncAddress(\n\tcontext: SyncExchangeContext,\n\tbaseUrl: string,\n\tcursors: SyncCursorState,\n): Promise<SyncAddressOutcome> {\n\tlet peer: NegotiatedPeerExchange;\n\ttry {\n\t\tpeer = await negotiatePeerExchange(context, baseUrl);\n\t} catch (error) {\n\t\treturn {\n\t\t\tkind: \"failure\",\n\t\t\terror,\n\t\t\tcapabilities: error instanceof PeerNegotiationError ? error.capabilities : undefined,\n\t\t\tnegotiationFailed: true,\n\t\t};\n\t}\n\tlet direction: \"send\" | \"receive\" = \"receive\";\n\ttry {\n\t\tconst bootstrap = await tryInitialBootstrap(context, peer, cursors);\n\t\tif (bootstrap) {\n\t\t\trecordReceiveResult(context, bootstrap);\n\t\t\treturn { kind: \"success\", result: bootstrap };\n\t\t}\n\t\tconst pulled = await pullDefaultScope(context, peer, cursors.lastApplied);\n\t\tif (pulled.kind === \"result\") {\n\t\t\t// Reset recovery checks only the default scope, not the remaining receive scopes.\n\t\t\trecordReceiveResult(context, pulled.result, RECEIVE_WINDOW_OPTIONS.activityOptions);\n\t\t\treturn { kind: \"success\", result: pulled.result };\n\t\t}\n\t\tconst applied = await applyPulledDefaultOps(context, peer, pulled, cursors.lastApplied);\n\t\tcursors.lastApplied = applied.lastApplied;\n\t\tdirection = \"send\";\n\t\tconst pushed = await pushDefaultScope(context, peer, cursors.lastAcked);\n\t\tcursors.lastAcked = pushed.lastAcked;\n\t\tdirection = \"receive\";\n\t\treturn {\n\t\t\tkind: \"success\",\n\t\t\tresult: recordReceiveResult(\n\t\t\t\tcontext,\n\t\t\t\tawait finishIncrementalExchange(context, peer, applied.applied, pushed),\n\t\t\t),\n\t\t};\n\t} catch (error) {\n\t\trecordSyncTransferObservation(context.db, context.peerDeviceId, direction, {\n\t\t\terrorCode: \"exchange_failed\",\n\t\t});\n\t\treturn { kind: \"failure\", error, capabilities: peer.capabilities };\n\t}\n}\n\nfunction warnMissingSyncScanner(scanner: SecretScanner | undefined): void {\n\tif (scanner || syncOnceScannerWarned) return;\n\tsyncOnceScannerWarned = true;\n\tprocess.stderr.write(\n\t\t\"[codemem] sync apply running without explicit scanner — workspace-level secret rules will not apply to inbound peer content\\n\",\n\t);\n}\n\nfunction peerPin(\n\tdb: Database,\n\tpeerDeviceId: string,\n): { pinnedFingerprint: string; pendingBootstrapGrantId: string | undefined } {\n\tconst d = drizzle(db, { schema });\n\tconst row = d\n\t\t.select({\n\t\t\tpinned_fingerprint: schema.syncPeers.pinned_fingerprint,\n\t\t\tpending_bootstrap_grant_id: schema.syncPeers.pending_bootstrap_grant_id,\n\t\t})\n\t\t.from(schema.syncPeers)\n\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t.get();\n\treturn {\n\t\tpinnedFingerprint: row?.pinned_fingerprint ?? \"\",\n\t\tpendingBootstrapGrantId: row?.pending_bootstrap_grant_id?.trim() || undefined,\n\t};\n}\n\nfunction unavailableIdentityResult(\n\tdb: Database,\n\tpeerDeviceId: string,\n\terror: unknown,\n\trecordAttempt = recordSyncAttempt,\n): SyncResult {\n\tconst detail =\n\t\terror instanceof Error ? error.message.trim() || error.constructor.name : \"unknown\";\n\tconst message = `device identity unavailable: ${detail}`;\n\trecordAttempt(db, peerDeviceId, { ok: false, error: message, failureCategory: \"other\" });\n\treturn {\n\t\tok: false,\n\t\terror: message,\n\t\tfailureCategory: \"other\",\n\t\topsIn: 0,\n\t\topsOut: 0,\n\t\taddressErrors: [],\n\t};\n}\n\ntype PreparedSyncExchange =\n\t| { kind: \"ready\"; context: SyncExchangeContext; cursors: SyncCursorState }\n\t| { kind: \"result\"; result: SyncResult };\n\nfunction prepareSyncExchange(\n\tdb: Database,\n\tpeerDeviceId: string,\n\toptions: SyncPassOptions | undefined,\n): PreparedSyncExchange {\n\tensureAdditiveSchemaCompatibility(db);\n\twarnMissingSyncScanner(options?.scanner);\n\tconst { pinnedFingerprint, pendingBootstrapGrantId } = peerPin(db, peerDeviceId);\n\tif (!pinnedFingerprint) {\n\t\treturn {\n\t\t\tkind: \"result\",\n\t\t\tresult: {\n\t\t\t\tok: false,\n\t\t\t\terror: \"peer not pinned\",\n\t\t\t\tfailureCategory: \"trust\",\n\t\t\t\topsIn: 0,\n\t\t\t\topsOut: 0,\n\t\t\t\taddressErrors: [],\n\t\t\t},\n\t\t};\n\t}\n\tlet deviceId: string;\n\ttry {\n\t\t[deviceId] = ensureDeviceIdentity(db, { keysDir: options?.keysDir });\n\t} catch (error) {\n\t\treturn {\n\t\t\tkind: \"result\",\n\t\t\tresult: unavailableIdentityResult(db, peerDeviceId, error, options?.attemptRecorder),\n\t\t};\n\t}\n\tconst [lastApplied, lastAcked] = getReplicationCursor(db, peerDeviceId);\n\treturn {\n\t\tkind: \"ready\",\n\t\tcontext: {\n\t\t\trequestExecutor: options?.requestExecutor ?? requestJson,\n\t\t\trecordAttempt: (attemptDb, peerId, attempt) => {\n\t\t\t\tconst record = options?.attemptRecorder ?? recordSyncAttempt;\n\t\t\t\t// This exchange dials a peer directly. Relay selection happens outside syncOnce.\n\t\t\t\trecord(attemptDb, peerId, { ...attempt, transport: \"direct\" });\n\t\t\t},\n\t\t\tdeferConnectionFailure: options?.deferConnectionFailure ?? false,\n\t\t\tdb,\n\t\t\tpeerDeviceId,\n\t\t\tdeviceId,\n\t\t\tpinnedFingerprint,\n\t\t\tpendingBootstrapGrantId,\n\t\t\tlimit: options?.limit ?? DEFAULT_LIMIT,\n\t\t\tkeysDir: options?.keysDir,\n\t\t\tdbPath: options?.dbPath,\n\t\t\tscanner: options?.scanner,\n\t\t\trefreshAuthorization: options?.refreshAuthorization ?? false,\n\t\t},\n\t\tcursors: { lastApplied, lastAcked },\n\t};\n}\n\nfunction failedAddressResult(\n\tdb: Database,\n\tpeerDeviceId: string,\n\taddressErrors: Array<{ address: string; error: string }>,\n\tattemptedAny: boolean,\n\tcapabilities: SyncCapabilityDiagnostics | undefined,\n\toptions: { protocolMismatch: boolean; recordAttempt: typeof recordSyncAttempt },\n): SyncResult {\n\tlet error = summarizeAddressErrors(addressErrors);\n\tif (!attemptedAny) error = \"no dialable peer addresses\";\n\tif (!error) error = \"sync failed without diagnostic detail\";\n\tconst failureCategory = categorizeSyncFailure(error);\n\toptions.recordAttempt(db, peerDeviceId, {\n\t\tok: false,\n\t\terror,\n\t\tfailureCategory: options.protocolMismatch\n\t\t\t? \"compatibility\"\n\t\t\t: storedAddressFailureCategory(addressErrors, error),\n\t\tcapabilities,\n\t});\n\treturn {\n\t\tok: false,\n\t\terror,\n\t\tfailureCategory,\n\t\topsIn: 0,\n\t\topsOut: 0,\n\t\taddressErrors,\n\t};\n}\n\nasync function tryPeerAddresses(\n\tcontext: SyncExchangeContext,\n\tcursors: SyncCursorState,\n\taddresses: string[],\n): Promise<SyncResult> {\n\tconst addressErrors: Array<{ address: string; error: string }> = [];\n\tlet attemptedAny = false;\n\tlet negotiated = false;\n\tlet capabilities: SyncCapabilityDiagnostics | undefined;\n\t// A protocol mismatch is only reported after the pinned fingerprint\n\t// matched, so the peer was reachable and trusted but incompatible.\n\tlet protocolMismatch = false;\n\tconst boundedAddresses = mergeAddresses(addresses, [], {\n\t\tmaxAddresses: MAX_PEER_ADDRESSES,\n\t});\n\tfor (const address of boundedAddresses) {\n\t\tconst baseUrl = buildBaseUrl(address);\n\t\tif (!baseUrl) continue;\n\t\tattemptedAny = true;\n\t\tconst exchange = await syncAddress(context, baseUrl, cursors);\n\t\tif (exchange.kind === \"success\") return exchange.result;\n\t\tif (!exchange.negotiationFailed) negotiated = true;\n\t\tif (exchange.capabilities) capabilities = exchange.capabilities;\n\t\tif (exchange.error instanceof PeerNegotiationError && exchange.error.protocolMismatch) {\n\t\t\tprotocolMismatch = true;\n\t\t}\n\t\tconst detail =\n\t\t\texchange.error instanceof Error\n\t\t\t\t? exchange.error.message.trim() || exchange.error.constructor.name\n\t\t\t\t: \"unknown\";\n\t\taddressErrors.push({ address: baseUrl, error: detail });\n\t}\n\tconst result = failedAddressResult(\n\t\tcontext.db,\n\t\tcontext.peerDeviceId,\n\t\taddressErrors,\n\t\tattemptedAny,\n\t\tcapabilities,\n\t\t{ protocolMismatch, recordAttempt: context.recordAttempt },\n\t);\n\treturn recordExhaustedConnectionFailure(context, result, { attemptedAny, negotiated });\n}\n\nfunction recordExhaustedConnectionFailure(\n\tcontext: SyncExchangeContext,\n\tresult: SyncResult,\n\toptions: { attemptedAny: boolean; negotiated: boolean },\n): SyncResult {\n\tif (!options.attemptedAny || options.negotiated) return result;\n\tresult.receiveFailureCode = \"exchange_failed\";\n\tif (!context.deferConnectionFailure) {\n\t\trecordSyncTransferObservation(context.db, context.peerDeviceId, \"receive\", {\n\t\t\terrorCode: \"exchange_failed\",\n\t\t});\n\t}\n\treturn result;\n}\n\n// ---------------------------------------------------------------------------\n// Main sync loop\n// ---------------------------------------------------------------------------\n\n/**\n * Execute a single sync exchange with a peer across the given addresses.\n *\n * Tries each address in order. On first success, returns immediately.\n * On all failures, collects address-level errors and returns them.\n */\nexport async function syncOnce(\n\tdb: Database,\n\tpeerDeviceId: string,\n\taddresses: string[],\n\toptions?: SyncPassOptions,\n): Promise<SyncResult> {\n\tconst prepared = prepareSyncExchange(db, peerDeviceId, options);\n\tif (prepared.kind === \"result\") return prepared.result;\n\treturn tryPeerAddresses(prepared.context, prepared.cursors, addresses);\n}\n\n// ---------------------------------------------------------------------------\n// Connectivity backoff (for daemon use)\n// ---------------------------------------------------------------------------\n\n/** Connectivity error patterns indicating peer is offline. */\nconst CONNECTIVITY_ERROR_PATTERNS = [\n\t\"no route to host\",\n\t\"connection refused\",\n\t\"network is unreachable\",\n\t\"timed out\",\n\t\"name or service not known\",\n\t\"nodename nor servname provided\",\n\t\"errno 65\",\n\t\"errno 61\",\n\t\"errno 60\",\n\t\"errno 111\",\n] as const;\n\nconst PEER_BACKOFF_BASE_S = 120;\nconst PEER_BACKOFF_MAX_S = 1800;\n\n/** Check if an error string indicates a network connectivity failure. */\nexport function isConnectivityError(error: string | null): boolean {\n\tif (!error) return false;\n\tconst lower = error.toLowerCase();\n\treturn CONNECTIVITY_ERROR_PATTERNS.some((pattern) => lower.includes(pattern));\n}\n\n/** Count consecutive recent failures that are connectivity errors. */\nexport function consecutiveConnectivityFailures(\n\tdb: Database,\n\tpeerDeviceId: string,\n\tlimit = 10,\n): number {\n\tconst d = drizzle(db, { schema });\n\tconst rows = d\n\t\t.select({ ok: schema.syncAttempts.ok, error: schema.syncAttempts.error })\n\t\t.from(schema.syncAttempts)\n\t\t.where(eq(schema.syncAttempts.peer_device_id, peerDeviceId))\n\t\t.orderBy(desc(schema.syncAttempts.started_at))\n\t\t.limit(limit)\n\t\t.all();\n\n\tlet count = 0;\n\tfor (const row of rows) {\n\t\tif (row.ok) break;\n\t\tif (isConnectivityError(row.error)) {\n\t\t\tcount++;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn count;\n}\n\n/** Calculate backoff duration with jitter to avoid thundering herd. */\nexport function peerBackoffSeconds(consecutiveFailures: number): number {\n\tif (consecutiveFailures <= 1) return 0;\n\tconst exponent = Math.min(consecutiveFailures - 1, 8);\n\tconst base = Math.min(PEER_BACKOFF_BASE_S * 2 ** (exponent - 1), PEER_BACKOFF_MAX_S);\n\t// Add 50% jitter: base * [0.5, 1.0)\n\treturn base * (0.5 + Math.random() * 0.5);\n}\n\n/** Check if a peer should be skipped due to repeated connectivity failures. */\nexport function shouldSkipOfflinePeer(db: Database, peerDeviceId: string): boolean {\n\tconst failures = consecutiveConnectivityFailures(db, peerDeviceId);\n\tif (failures < 2) return false;\n\tconst backoffS = peerBackoffSeconds(failures);\n\tif (backoffS <= 0) return false;\n\n\tconst d = drizzle(db, { schema });\n\tconst row = d\n\t\t.select({ started_at: schema.syncAttempts.started_at })\n\t\t.from(schema.syncAttempts)\n\t\t.where(eq(schema.syncAttempts.peer_device_id, peerDeviceId))\n\t\t.orderBy(desc(schema.syncAttempts.started_at))\n\t\t.limit(1)\n\t\t.get();\n\n\tif (!row?.started_at) return false;\n\ttry {\n\t\tconst lastAttempt = new Date(row.started_at).getTime();\n\t\tconst now = Date.now();\n\t\tconst elapsedS = (now - lastAttempt) / 1000;\n\t\treturn elapsedS < backoffS;\n\t} catch {\n\t\treturn false;\n\t}\n}\n","import { type ClientRequest, type IncomingMessage, request } from \"node:http\";\nimport { performance } from \"node:perf_hooks\";\nimport type { Duplex } from \"node:stream\";\nimport { finished } from \"node:stream/promises\";\nimport { adoptPeerHttpConnection, PeerHttpLifetime } from \"./peer-http-client-lifecycle.js\";\nimport { preparePeerHttpRequest, readPeerHttpBodyLength } from \"./peer-http-headers.js\";\nimport { PeerHttpExchangeError } from \"./peer-http-policy.js\";\nimport { PeerHttpWireAudit } from \"./peer-http-wire-audit.js\";\nimport { RelayNoiseDuplex } from \"./relay-noise-stream.js\";\nimport type { RequestJsonExecutor } from \"./sync-http-client.js\";\n\nexport interface OwnedPeerHttpConnection {\n\treadonly duplex: Duplex;\n\t/** Resolves only after clean underlying raw I/O AND resource disposal. */\n\treadonly completion: Promise<void>;\n\t/** Idempotently owns the entire channel and settles within the cleanup grace. */\n\tdispose(error: Error): Promise<void>;\n}\n\nexport interface PeerHttpConnectionFactory {\n\topen(options: { signal: AbortSignal; deadlineMs: number }): Promise<OwnedPeerHttpConnection>;\n}\n\ntype Owner = ReturnType<typeof adoptPeerHttpConnection>;\ntype ValidOwner = Extract<Owner, { valid: true }>;\ntype Prepared = ReturnType<typeof preparePeerHttpRequest>;\n\nfunction requireFreshConnection(duplex: Duplex): void {\n\tif (\n\t\t!(duplex instanceof RelayNoiseDuplex) ||\n\t\tduplex.destroyed ||\n\t\tduplex.errored ||\n\t\tduplex.readableEnded ||\n\t\tduplex.writableEnded ||\n\t\tduplex.readableLength !== 0 ||\n\t\tduplex.writableLength !== 0 ||\n\t\tduplex.readableFlowing === true\n\t)\n\t\tthrow new PeerHttpExchangeError(\"transport\");\n}\n\nfunction decodeResponse(bytes: Buffer): Record<string, unknown> | null {\n\tif (bytes.length === 0) return null;\n\ttry {\n\t\tconst value: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n\t\tif (typeof value === \"object\" && value !== null && !Array.isArray(value))\n\t\t\treturn value as Record<string, unknown>;\n\t\treturn { error: \"unexpected_json_type\" };\n\t} catch {\n\t\treturn { error: \"non_json_response\" };\n\t}\n}\n\nfunction receiveResponse(\n\tresponse: IncomingMessage,\n\taudit: PeerHttpWireAudit,\n\tlifetime: PeerHttpLifetime,\n\tmaxBodyBytes: number,\n) {\n\treturn new Promise<{ status: number; bytes: Buffer }>((resolve, reject) => {\n\t\tresponse.once(\"error\", () => reject(lifetime.fail(\"transport\")));\n\t\tresponse.once(\"aborted\", () => reject(lifetime.fail(\"framing\")));\n\t\ttry {\n\t\t\tconst status = response.statusCode;\n\t\t\tif (response.httpVersion !== \"1.1\" || status === undefined || status < 200 || status > 599)\n\t\t\t\tthrow new PeerHttpExchangeError(\"framing\");\n\t\t\tconst length = readPeerHttpBodyLength(response.rawHeaders, {\n\t\t\t\tdirection: \"response\",\n\t\t\t\tmaxBodyBytes,\n\t\t\t});\n\t\t\taudit.expectBodyBytes(length);\n\t\t\tconst bytes = Buffer.alloc(length);\n\t\t\tlet received = 0;\n\t\t\tresponse.on(\"data\", (chunk: Buffer) => {\n\t\t\t\tif (!Buffer.isBuffer(chunk) || received + chunk.length > length) {\n\t\t\t\t\treject(lifetime.fail(\"framing\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tchunk.copy(bytes, received);\n\t\t\t\treceived += chunk.length;\n\t\t\t});\n\t\t\tresponse.once(\"end\", () => {\n\t\t\t\tif (!response.complete || received !== length || response.rawTrailers.length !== 0)\n\t\t\t\t\treject(lifetime.fail(\"framing\"));\n\t\t\t\telse resolve({ status, bytes });\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst code = error instanceof PeerHttpExchangeError ? error.code : \"framing\";\n\t\t\treject(lifetime.fail(code));\n\t\t}\n\t});\n}\n\nasync function writeRequest(\n\treq: ClientRequest,\n\tbody: Buffer,\n\tlifetime: PeerHttpLifetime,\n): Promise<void> {\n\tfor (let offset = 0; offset < body.length; offset += 16384) {\n\t\tlet drained = false;\n\t\tlet written = false;\n\t\tlet resume = (): void => {};\n\t\tconst onDrain = (): void => {\n\t\t\tdrained = true;\n\t\t\tresume();\n\t\t};\n\t\ttry {\n\t\t\tawait lifetime.wait(\n\t\t\t\tnew Promise<void>((resolve, reject) => {\n\t\t\t\t\tresume = () => {\n\t\t\t\t\t\tif (drained && written) resolve();\n\t\t\t\t\t};\n\t\t\t\t\treq.once(\"drain\", onDrain);\n\t\t\t\t\tdrained = req.write(body.subarray(offset, offset + 16384), (error) => {\n\t\t\t\t\t\tif (error) reject(lifetime.fail(\"transport\"));\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\twritten = true;\n\t\t\t\t\t\t\tresume();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tresume();\n\t\t\t\t}),\n\t\t\t);\n\t\t} finally {\n\t\t\treq.off(\"drain\", onDrain);\n\t\t}\n\t}\n\tawait lifetime.wait(new Promise<void>((resolve) => req.end(resolve)));\n}\n\nfunction observePlaintext(duplex: Duplex, lifetime: PeerHttpLifetime) {\n\t// Native headers classify a declared excess before the audit binds the validated length.\n\tconst audit = new PeerHttpWireAudit({ direction: \"response\" });\n\tconst eof = Promise.withResolvers<void>();\n\tvoid eof.promise.catch(() => {});\n\tconst data = (chunk: unknown): void => {\n\t\ttry {\n\t\t\taudit.observe(chunk);\n\t\t} catch {\n\t\t\tlifetime.fail(\"framing\");\n\t\t}\n\t};\n\tconst end = (): void => {\n\t\ttry {\n\t\t\taudit.finish();\n\t\t\teof.resolve();\n\t\t} catch {\n\t\t\teof.reject(lifetime.fail(\"framing\"));\n\t\t}\n\t};\n\tconst error = (): void => {\n\t\tlifetime.fail(\"transport\");\n\t};\n\tduplex.on(\"data\", data);\n\tduplex.once(\"end\", end);\n\tduplex.on(\"error\", error);\n\treturn {\n\t\taudit,\n\t\teof: eof.promise,\n\t\tremove: () => {\n\t\t\tduplex.off(\"data\", data);\n\t\t\tduplex.off(\"end\", end);\n\t\t\tduplex.off(\"error\", error);\n\t\t},\n\t};\n}\n\nfunction startRequest(\n\tduplex: Duplex,\n\tprepared: Prepared,\n\taudit: PeerHttpWireAudit,\n\tlifetime: PeerHttpLifetime,\n) {\n\tconst response = Promise.withResolvers<{ status: number; bytes: Buffer }>();\n\tvoid response.promise.catch(() => {});\n\tconst req = request(\n\t\t{\n\t\t\tmethod: prepared.method,\n\t\t\thostname: prepared.hostname,\n\t\t\tpath: prepared.path,\n\t\t\theaders: prepared.headers,\n\t\t\tsetHost: false,\n\t\t\tmaxHeaderSize: 16384,\n\t\t\tcreateConnection: () => duplex,\n\t\t\tlookup: () => {\n\t\t\t\tthrow new PeerHttpExchangeError(\"transport\");\n\t\t\t},\n\t\t\tsignal: lifetime.controller.signal,\n\t\t},\n\t\t(incoming) => {\n\t\t\tvoid receiveResponse(incoming, audit, lifetime, prepared.maxResponseBytes).then((result) => {\n\t\t\t\ttry {\n\t\t\t\t\tduplex.end();\n\t\t\t\t\tresponse.resolve(result);\n\t\t\t\t} catch {\n\t\t\t\t\tresponse.reject(lifetime.fail(\"transport\"));\n\t\t\t\t}\n\t\t\t}, response.reject);\n\t\t},\n\t);\n\t// Preserve every field for policy validation. The independent byte cap still applies.\n\treq.maxHeadersCount = 0;\n\treq.once(\"socket\", () => duplex.resume());\n\treq.on(\"error\", () => lifetime.fail(\"transport\"));\n\tfor (const event of [\"information\", \"continue\", \"upgrade\", \"connect\"])\n\t\treq.on(event, () => lifetime.fail(\"framing\"));\n\treturn { req, response: response.promise };\n}\n\nasync function exchange(owner: ValidOwner, prepared: Prepared, lifetime: PeerHttpLifetime) {\n\trequireFreshConnection(owner.duplex);\n\t// Node installs its parser on the next tick. Resume only after its socket event.\n\towner.duplex.pause();\n\tconst observer = observePlaintext(owner.duplex, lifetime);\n\tconst plaintextCompletion = finished(owner.duplex, { cleanup: true });\n\tvoid plaintextCompletion.catch(() => {});\n\ttry {\n\t\tconst { req, response } = startRequest(owner.duplex, prepared, observer.audit, lifetime);\n\t\tconst [result] = await lifetime.wait(\n\t\t\tPromise.all([\n\t\t\t\tresponse,\n\t\t\t\tobserver.eof,\n\t\t\t\tplaintextCompletion,\n\t\t\t\towner.completion,\n\t\t\t\twriteRequest(req, prepared.body, lifetime),\n\t\t\t]),\n\t\t);\n\t\tlifetime.check();\n\t\tconst payload = decodeResponse(result.bytes);\n\t\tlifetime.check();\n\t\treturn [result.status, payload] as [number, Record<string, unknown> | null];\n\t} finally {\n\t\tobserver.remove();\n\t}\n}\n\ninterface ExecutorOptions {\n\tfactory: PeerHttpConnectionFactory;\n\tsignal?: AbortSignal;\n\tdeadlineMs?: number;\n}\n\nfunction captureExecutorOptions(options: ExecutorOptions) {\n\ttry {\n\t\tconst { factory, signal, deadlineMs } = options;\n\t\tconst open = factory.open.bind(factory);\n\t\tif (\n\t\t\t(deadlineMs !== undefined && !Number.isFinite(deadlineMs)) ||\n\t\t\t(signal !== undefined && !(signal instanceof AbortSignal))\n\t\t)\n\t\t\tthrow new Error();\n\t\treturn { open, signal, deadlineMs };\n\t} catch {\n\t\tthrow new PeerHttpExchangeError(\"framing\");\n\t}\n}\n\n/** Inert injected executor. One fresh owned Noise connection per call, with no retry or fallback. */\nexport function createPeerHttpExecutor(options: ExecutorOptions): RequestJsonExecutor {\n\tconst { open, signal, deadlineMs } = captureExecutorOptions(options);\n\treturn async (method, url, requestOptions = {}) => {\n\t\tconst startedAt = performance.now();\n\t\tconst prepared = preparePeerHttpRequest(method, url, requestOptions);\n\t\tconst deadline = Math.min(startedAt + prepared.lifetimeMs, deadlineMs ?? Infinity);\n\t\tconst lifetime = new PeerHttpLifetime(deadline, signal);\n\t\tlet owner: Owner | undefined;\n\t\ttry {\n\t\t\tlifetime.check();\n\t\t\tconst opening = Promise.resolve(\n\t\t\t\topen({ signal: lifetime.controller.signal, deadlineMs: deadline }),\n\t\t\t).then((connection) => {\n\t\t\t\towner = adoptPeerHttpConnection(connection);\n\t\t\t\tif (owner.valid) void owner.completion.catch(() => lifetime.fail(\"transport\"));\n\t\t\t\tif (lifetime.failed) void owner.dispose(lifetime.fail(\"transport\")).catch(() => {});\n\t\t\t\treturn owner;\n\t\t\t});\n\t\t\tconst acquired = await lifetime.wait(opening);\n\t\t\tif (!acquired.valid) throw lifetime.fail(\"transport\");\n\t\t\treturn await exchange(acquired, prepared, lifetime);\n\t\t} catch {\n\t\t\tconst failure = lifetime.fail(\"transport\");\n\t\t\tif (owner) await owner.dispose(failure);\n\t\t\tthrow failure;\n\t\t} finally {\n\t\t\tlifetime.close();\n\t\t}\n\t};\n}\n","import { and, eq } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport type { Database } from \"./db.js\";\nimport * as schema from \"./schema.js\";\nimport {\n\ttype CachedScopeAuthorization,\n\tgetEffectiveCachedScopeAuthorization,\n} from \"./scope-membership-cache.js\";\nimport { isScopedSyncCapability, type SyncCapability } from \"./sync-capability.js\";\nimport {\n\tDEFAULT_SYNC_SCOPE_ID,\n\tgetReplicationCursor,\n\tgetSyncResetState,\n\tSCOPED_NULL_BASELINE_BOOTSTRAP_CURSOR_MARKER,\n} from \"./sync-replication.js\";\n\nexport const SYNC_SCOPE_QUERY_PARAM = \"scope_id\";\n\n// An absent signing key must not turn into an unbound managed-cache lookup.\nfunction scopeSigningKey(publicKey: string | null | undefined): string {\n\treturn publicKey ?? \"\";\n}\n\nexport type SyncScopeRequestMode = \"legacy\" | \"scoped\";\nexport type SyncScopeResetReason =\n\t| \"missing_scope\"\n\t| \"unsupported_scope\"\n\t| \"stale_epoch\"\n\t| \"scope_inactive\";\n\nexport interface SyncScopeRequestOk {\n\tok: true;\n\tmode: SyncScopeRequestMode;\n\tscope_id: string | null;\n}\n\nexport interface SyncScopeRequestError {\n\tok: false;\n\treason: SyncScopeResetReason;\n}\n\nexport type SyncScopeRequest = SyncScopeRequestOk | SyncScopeRequestError;\n\nexport interface SyncResetBoundaryShape {\n\tgeneration: number;\n\tsnapshot_id: string;\n\tbaseline_cursor: string | null;\n\tretained_floor_cursor: string | null;\n}\n\n/**\n * Parse a sync scope request and validate it against caller authorization.\n *\n * Legacy callers (`negotiatedCapability !== \"scoped\"`) MUST NOT pass a\n * scope_id; doing so is rejected as `unsupported_scope` so the wire format\n * stays predictable when the lower-ranked side cannot interpret per-scope\n * responses anyway.\n *\n * Scoped callers (`negotiatedCapability === \"scoped\"`) may pass a scope_id.\n * The server verifies both the local device and the calling peer are active,\n * current-epoch members of the requested scope before accepting. Failed\n * authorization maps to wire\n * reasons that the client can act on:\n * - `missing_scope`: scope unknown, inactive, or caller is not a member.\n * - `stale_epoch`: caller membership exists but epoch is behind authority.\n * - `scope_inactive`: scope membership was revoked or scope is closed.\n *\n * Callers that pass no scope_id continue to be served via the legacy default\n * scope path regardless of capability.\n */\nexport function parseSyncScopeRequest(\n\tvalue: unknown,\n\tprovided: boolean,\n\tcontext?: {\n\t\tdb?: Database;\n\t\tlocalDeviceId?: string | null;\n\t\tlocalSigningPublicKey?: string | null;\n\t\tnegotiatedCapability?: SyncCapability;\n\t\tpeerDeviceId?: string | null;\n\t\tauthenticatedPeerSigningKey?: string | null;\n\t},\n): SyncScopeRequest {\n\tif (!provided) {\n\t\treturn { ok: true, mode: \"legacy\", scope_id: null };\n\t}\n\n\tconst scopeId = typeof value === \"string\" ? value.trim() : \"\";\n\tif (!scopeId) {\n\t\treturn { ok: false, reason: \"missing_scope\" };\n\t}\n\n\tconst negotiated = context?.negotiatedCapability;\n\tif (!negotiated || !isScopedSyncCapability(negotiated)) {\n\t\t// Caller is on the legacy default-scope wire format. Refuse the\n\t\t// scope_id rather than silently downgrading: the response shape\n\t\t// will not carry the per-scope boundary the caller expects.\n\t\treturn { ok: false, reason: \"unsupported_scope\" };\n\t}\n\n\tconst db = context.db;\n\tconst localDeviceId = context.localDeviceId?.trim();\n\tconst peerDeviceId = context.peerDeviceId?.trim();\n\tif (!db || !localDeviceId || !peerDeviceId) {\n\t\t// Caller advertised scoped capability but the route did not thread\n\t\t// the authentication context through. Fail closed.\n\t\treturn { ok: false, reason: \"missing_scope\" };\n\t}\n\n\tconst localAuthorization = getEffectiveCachedScopeAuthorization(db, {\n\t\tdeviceId: localDeviceId,\n\t\tscopeId,\n\t\texpectedPublicKey: context.localSigningPublicKey ?? \"\",\n\t});\n\tconst localErrorReason = scopeAuthorizationFailureReason(localAuthorization);\n\tif (localErrorReason) {\n\t\treturn { ok: false, reason: localErrorReason };\n\t}\n\n\tconst authorization = getEffectiveCachedScopeAuthorization(db, {\n\t\tdeviceId: peerDeviceId,\n\t\tscopeId,\n\t\texpectedPublicKey: context.authenticatedPeerSigningKey ?? \"\",\n\t});\n\tconst errorReason = scopeAuthorizationFailureReason(authorization);\n\tif (errorReason) {\n\t\treturn { ok: false, reason: errorReason };\n\t}\n\n\treturn { ok: true, mode: \"scoped\", scope_id: scopeId };\n}\n\n/**\n * Map a cached scope authorization result to a wire reset reason, or null\n * when the caller is fully authorized for the scope.\n */\nexport function scopeAuthorizationFailureReason(\n\tauthorization: CachedScopeAuthorization,\n): SyncScopeResetReason | null {\n\tif (authorization.scope?.authority_type === \"local\") return \"missing_scope\";\n\tif (authorization.authorized) return null;\n\n\tswitch (authorization.state) {\n\t\tcase \"stale_epoch\":\n\t\t\treturn \"stale_epoch\";\n\t\tcase \"revoked\":\n\t\tcase \"scope_inactive\":\n\t\t\treturn \"scope_inactive\";\n\t\tdefault:\n\t\t\treturn \"missing_scope\";\n\t}\n}\n\nexport function addSyncScopeToBoundary<T extends SyncResetBoundaryShape>(\n\tboundary: T,\n\tscopeId: string | null,\n): T & { scope_id: string | null } {\n\treturn { ...boundary, scope_id: scopeId };\n}\n\nexport function syncScopeResetRequiredPayload(\n\tboundary: SyncResetBoundaryShape,\n\treason: SyncScopeResetReason,\n\tsyncCapability: SyncCapability,\n\tscopeId?: string | null,\n): SyncResetBoundaryShape & {\n\terror: \"reset_required\";\n\treset_required: true;\n\tsync_capability: SyncCapability;\n\treason: SyncScopeResetReason;\n\tscope_id: string | null;\n} {\n\treturn {\n\t\terror: \"reset_required\",\n\t\treset_required: true,\n\t\tsync_capability: syncCapability,\n\t\treason,\n\t\t...addSyncScopeToBoundary(boundary, scopeId ?? null),\n\t};\n}\n\n/**\n * Authorized-scope entry advertised on /v1/status when both peers negotiate\n * the `scoped` capability. Each entry carries the per-scope reset boundary\n * (`sync_reset_state_v2` row) so the client can immediately request that\n * scope's snapshot or incremental ops without an extra round trip.\n */\nexport interface AuthorizedScopeEntry {\n\tscope_id: string;\n\tlabel: string;\n\tauthority_type: string;\n\tmembership_epoch: number;\n\tsync_reset: SyncResetBoundaryShape & { scope_id: string | null };\n\t/**\n\t * The `created_at|op_id` cursor of the last op this device applied from the\n\t * calling peer in this Space, or null. Only the authenticated peer's own\n\t * cursor is reported. A peer that pushes can start after it.\n\t */\n\tapplied_cursor?: string | null;\n}\n\n/**\n * Enumerate scopes the calling peer is authorized to sync with the local\n * device, suitable for advertising on /v1/status under scoped capability.\n *\n * Inclusion rule: a scope is returned when\n * - it exists in `replication_scopes` with status `active`, and\n * - both the local device and the peer device have active membership rows\n * in `scope_memberships`, and\n * - the scope's `authority_type` is not `local`.\n *\n * The legacy `local-default` scope is intentionally excluded. Scoped peers\n * still run the legacy default-scope path alongside per-scope sync to handle\n * pre-Spaces data, so listing it here would duplicate work and require new\n * code paths in the loaders to emit \"explicit\" default-scope rows.\n *\n * The returned `sync_reset` value is the per-scope boundary; calling\n * `getSyncResetState(db, scope_id)` lazily creates a row if one does not\n * exist yet so first-time scopes get a stable generation/snapshot_id.\n */\nexport function listAuthorizedScopesForPeer(\n\tdb: Database,\n\toptions: {\n\t\tlocalDeviceId: string;\n\t\tpeerDeviceId: string;\n\t\tlocalSigningPublicKey?: string | null;\n\t\tauthenticatedPeerSigningKey?: string | null;\n\t\tscopeId?: string;\n\t},\n): AuthorizedScopeEntry[] {\n\tconst memberships = listAuthorizedScopeMembershipsForPeer(db, options).filter(\n\t\t(scope) => options.scopeId === undefined || scope.scope_id === options.scopeId,\n\t);\n\treturn memberships.map((scope) => {\n\t\tconst reset = getSyncResetState(db, scope.scope_id);\n\t\tconst [appliedCursor] = getReplicationCursor(db, options.peerDeviceId, scope.scope_id);\n\t\treturn {\n\t\t\t...scope,\n\t\t\tapplied_cursor: appliedCursor,\n\t\t\tsync_reset: {\n\t\t\t\tscope_id: scope.scope_id,\n\t\t\t\tgeneration: reset.generation,\n\t\t\t\tsnapshot_id: reset.snapshot_id,\n\t\t\t\tbaseline_cursor: reset.baseline_cursor,\n\t\t\t\tretained_floor_cursor: reset.retained_floor_cursor,\n\t\t\t},\n\t\t};\n\t});\n}\n\n// Diagnostics need membership and cursor reads, not creation of reset boundaries.\nfunction listAuthorizedScopeMembershipsForPeer(\n\tdb: Database,\n\toptions: Parameters<typeof listAuthorizedScopesForPeer>[1],\n): Omit<AuthorizedScopeEntry, \"sync_reset\">[] {\n\tconst localDeviceId = options.localDeviceId.trim();\n\tconst peerDeviceId = options.peerDeviceId.trim();\n\tif (!localDeviceId || !peerDeviceId || localDeviceId === peerDeviceId) {\n\t\treturn [];\n\t}\n\n\tconst d = drizzle(db, { schema });\n\tconst localMemberships = d\n\t\t.select({\n\t\t\tscope_id: schema.scopeMemberships.scope_id,\n\t\t\tmembership_epoch: schema.scopeMemberships.membership_epoch,\n\t\t})\n\t\t.from(schema.scopeMemberships)\n\t\t.where(\n\t\t\tand(\n\t\t\t\teq(schema.scopeMemberships.device_id, localDeviceId),\n\t\t\t\teq(schema.scopeMemberships.status, \"active\"),\n\t\t\t),\n\t\t)\n\t\t.all();\n\n\tif (localMemberships.length === 0) return [];\n\n\tconst entries: Omit<AuthorizedScopeEntry, \"sync_reset\">[] = [];\n\tfor (const local of localMemberships) {\n\t\tif (!local.scope_id || local.scope_id === DEFAULT_SYNC_SCOPE_ID) continue;\n\t\tconst localAuth = getEffectiveCachedScopeAuthorization(db, {\n\t\t\tdeviceId: localDeviceId,\n\t\t\tscopeId: local.scope_id,\n\t\t\texpectedPublicKey: scopeSigningKey(options.localSigningPublicKey),\n\t\t});\n\t\tif (!localAuth.authorized || localAuth.scope?.authority_type === \"local\") continue;\n\n\t\t// Peer must also be an active member of the same scope, at the same\n\t\t// or higher membership_epoch as the local row, before we advertise.\n\t\tconst peerAuth = getEffectiveCachedScopeAuthorization(db, {\n\t\t\tdeviceId: peerDeviceId,\n\t\t\tscopeId: local.scope_id,\n\t\t\texpectedPublicKey: scopeSigningKey(options.authenticatedPeerSigningKey),\n\t\t});\n\t\tif (!peerAuth.authorized || !peerAuth.scope || peerAuth.scope.status !== \"active\") continue;\n\n\t\tentries.push({\n\t\t\tscope_id: local.scope_id,\n\t\t\tlabel: peerAuth.scope.label,\n\t\t\tauthority_type: peerAuth.scope.authority_type,\n\t\t\tmembership_epoch: Number(peerAuth.scope.membership_epoch ?? local.membership_epoch ?? 0),\n\t\t});\n\t}\n\n\tentries.sort((a, b) => a.scope_id.localeCompare(b.scope_id));\n\treturn entries;\n}\n\n/**\n * Per-Space sync state for a given peer, suitable for both the CLI status\n * display and the `/api/sync/status` / `/api/sync/peers` viewer payload.\n *\n * Renders the intersection of local + peer scope memberships against the\n * per-scope cursor state stored in `replication_cursors_v2`. Consumers use\n * this surface to show \"synced / pending\" per Space instead of the legacy\n * peer-level `last_sync=ok`, which is the diagnostic gap that hid the\n * codemem-ruu6 regression while ~18k scoped rows silently failed to\n * replicate.\n *\n * Returns an empty array when local device identity has not yet been\n * initialized or when there is no membership overlap.\n */\nexport interface PerPeerScopeSyncEntry {\n\tscope_id: string;\n\tlabel: string;\n\tauthority_type: string;\n\tmembership_epoch: number;\n\tlast_applied_cursor: string | null;\n\tlast_acked_cursor: string | null;\n\tbootstrapped: boolean;\n}\n\nexport function listPerPeerScopeSyncState(\n\tdb: Database,\n\toptions: {\n\t\tlocalDeviceId: string | null;\n\t\tpeerDeviceId: string;\n\t\tlocalSigningPublicKey?: string | null;\n\t\tauthenticatedPeerSigningKey?: string | null;\n\t},\n): PerPeerScopeSyncEntry[] {\n\tconst localDeviceId = options.localDeviceId?.trim() ?? \"\";\n\tconst peerDeviceId = options.peerDeviceId.trim();\n\tif (!localDeviceId || !peerDeviceId) return [];\n\tconst scopes = listAuthorizedScopeMembershipsForPeer(db, {\n\t\t...options,\n\t\tlocalDeviceId,\n\t\tpeerDeviceId,\n\t});\n\tconst readCursor = db.prepare(\n\t\t`SELECT last_applied_cursor, last_acked_cursor FROM replication_cursors_v2\n\t\t WHERE peer_device_id = ? AND scope_id = ?`,\n\t);\n\treturn scopes.map((scope) => {\n\t\tconst cursor = readCursor.get(peerDeviceId, scope.scope_id) as\n\t\t\t| { last_applied_cursor: string | null; last_acked_cursor: string | null }\n\t\t\t| undefined;\n\t\tconst lastApplied = cursor?.last_applied_cursor ?? null;\n\t\tconst lastAcked = cursor?.last_acked_cursor ?? null;\n\t\tconst hasNullBaselineBootstrapMarker =\n\t\t\tlastAcked === SCOPED_NULL_BASELINE_BOOTSTRAP_CURSOR_MARKER;\n\t\treturn {\n\t\t\tscope_id: scope.scope_id,\n\t\t\tlabel: scope.label,\n\t\t\tauthority_type: scope.authority_type,\n\t\t\tmembership_epoch: scope.membership_epoch,\n\t\t\tlast_applied_cursor: lastApplied,\n\t\t\tlast_acked_cursor: hasNullBaselineBootstrapMarker ? null : lastAcked,\n\t\t\tbootstrapped: lastApplied != null || hasNullBaselineBootstrapMarker,\n\t\t};\n\t});\n}\n","import { performance } from \"node:perf_hooks\";\nimport type { Database } from \"./db.js\";\nimport { createPeerHttpExecutor, type PeerHttpConnectionFactory } from \"./peer-http-client.js\";\nimport { adoptPeerHttpConnection } from \"./peer-http-client-lifecycle.js\";\nimport { parseRelayEd25519PublicKey } from \"./relay-ed25519.js\";\nimport type { RelayFailureReason } from \"./relay-failure-reason.js\";\nimport { readAuthenticatedRelayNoisePeerPin } from \"./relay-noise.js\";\nimport type { SecretScanner } from \"./secret-scanner.js\";\nimport { buildDirectPeerAuthHeaders } from \"./sync-auth.js\";\nimport {\n\tLOCAL_SYNC_FEATURES,\n\tSYNC_CAPABILITY_HEADER,\n\tSYNC_FEATURES_HEADER,\n\tsupportsSyncFeature,\n} from \"./sync-capability.js\";\nimport {\n\tclearSyncChannelProgress,\n\tgetSyncChannelProgress,\n\thasCompletedSyncChannelBoundary,\n\ttype SyncChannelBoundary,\n\tsaveSyncChannelCompletedBoundary,\n\tsaveSyncChannelOutboundAck,\n} from \"./sync-channel-progress.js\";\nimport type { RequestJsonExecutor } from \"./sync-http-client.js\";\nimport { ensureDeviceIdentity, fingerprintPublicKey } from \"./sync-identity.js\";\nimport { type SyncScopeResult, syncScopedPeerPull } from \"./sync-pass.js\";\nimport { filterReplicationOpsForSyncWithStatus } from \"./sync-replication.js\";\nimport { parseSyncScopeRequest } from \"./sync-scope-protocol.js\";\nimport {\n\trecordSyncTransferObservation,\n\trecordSyncTransferReceipts,\n} from \"./sync-transfer-activity.js\";\nimport type { ReplicationOp } from \"./types.js\";\n\nconst MAX_BODY_BYTES = 1_048_576;\nexport interface ScopedChannelSyncOptions {\n\tdb: Database;\n\tpeerDeviceId: string;\n\tscopeId: string;\n\tlogicalOrigin: string;\n\t/** Relay factories report their first route failure, which the result records locally. */\n\tfactory: PeerHttpConnectionFactory & { failureReason?: () => RelayFailureReason | undefined };\n\tkeysDir?: string;\n\tdbPath?: string;\n\tscanner?: SecretScanner;\n\tlimit?: number;\n\tsignal?: AbortSignal;\n\tdeadlineMs?: number;\n}\ntype Identity = { device_id: string; public_key: string; fingerprint: string };\ntype Peer = { public_key: string; pinned_fingerprint: string };\ntype Scope = Parameters<typeof syncScopedPeerPull>[1][\"scope\"];\ntype Context = ReturnType<typeof captureContext>;\n\nfunction canonicalKey(key: string): string {\n\treturn `ssh-ed25519 ${Buffer.from(parseRelayEd25519PublicKey(key).wireKey).toString(\"base64\")}`;\n}\n\nfunction currentIdentity(db: Database): Identity {\n\tconst row = db\n\t\t.prepare(\"SELECT device_id, public_key, fingerprint FROM sync_device LIMIT 1\")\n\t\t.get() as Identity | undefined;\n\tif (!row?.device_id || fingerprintPublicKey(row.public_key) !== row.fingerprint)\n\t\tthrow new Error(\"channel identity invalid\");\n\tcanonicalKey(row.public_key);\n\treturn row;\n}\n\nfunction currentPeer(db: Database, peerDeviceId: string): Peer {\n\tconst row = db\n\t\t.prepare(\"SELECT public_key, pinned_fingerprint FROM sync_peers WHERE peer_device_id = ?\")\n\t\t.get(peerDeviceId) as Peer | undefined;\n\tif (\n\t\t!row?.public_key ||\n\t\t!row.pinned_fingerprint ||\n\t\tfingerprintPublicKey(row.public_key) !== row.pinned_fingerprint\n\t)\n\t\tthrow new Error(\"channel peer trust invalid\");\n\tcanonicalKey(row.public_key);\n\treturn row;\n}\n\nfunction captureContext(input: ScopedChannelSyncOptions) {\n\tconst passDeadline = performance.now() + 60_000;\n\tconst options = { ...input };\n\tconst origin = new URL(options.logicalOrigin);\n\tif (![\"http:\", \"https:\"].includes(origin.protocol) || origin.origin !== options.logicalOrigin)\n\t\tthrow new Error(\"channel origin invalid\");\n\tif (!options.scopeId || options.scopeId.trim() !== options.scopeId)\n\t\tthrow new Error(\"channel scope invalid\");\n\tif (options.limit !== undefined && (!Number.isInteger(options.limit) || options.limit < 1))\n\t\tthrow new Error(\"channel limit invalid\");\n\tif (options.deadlineMs !== undefined && !Number.isFinite(options.deadlineMs))\n\t\tthrow new Error(\"channel deadline invalid\");\n\tensureDeviceIdentity(options.db, { keysDir: options.keysDir });\n\treturn {\n\t\t...options,\n\t\tdeadlineMs: Math.min(options.deadlineMs ?? passDeadline, passDeadline),\n\t\tlimit: Math.min(options.limit ?? 500, 1000),\n\t\tlocal: currentIdentity(options.db),\n\t\tpeer: currentPeer(options.db, options.peerDeviceId),\n\t\topen: options.factory.open.bind(options.factory),\n\t};\n}\n\nfunction checkAuthorization(context: Context): void {\n\tconst local = currentIdentity(context.db);\n\tconst peer = currentPeer(context.db, context.peerDeviceId);\n\tif (\n\t\tlocal.device_id !== context.local.device_id ||\n\t\tlocal.public_key !== context.local.public_key ||\n\t\tpeer.public_key !== context.peer.public_key ||\n\t\tpeer.pinned_fingerprint !== context.peer.pinned_fingerprint\n\t)\n\t\tthrow new Error(\"channel trust changed\");\n\tconst admission = parseSyncScopeRequest(context.scopeId, true, {\n\t\tdb: context.db,\n\t\tlocalDeviceId: local.device_id,\n\t\tlocalSigningPublicKey: local.public_key,\n\t\tpeerDeviceId: context.peerDeviceId,\n\t\tauthenticatedPeerSigningKey: peer.public_key,\n\t\tnegotiatedCapability: \"scoped\",\n\t});\n\tif (!admission.ok) throw new Error(\"channel scope authorization denied\");\n}\n\nfunction validatePullPayload(context: Context, url: URL, payload: Record<string, unknown>): void {\n\tif (payload.scope_id !== context.scopeId) throw new Error(\"channel response scope invalid\");\n\tif (url.pathname === \"/v1/ops\") {\n\t\tif (!Array.isArray(payload.ops)) throw new Error(\"channel ops invalid\");\n\t\tfor (const raw of payload.ops) {\n\t\t\tconst op = raw as Partial<ReplicationOp> | null;\n\t\t\tif (\n\t\t\t\t!op ||\n\t\t\t\top.scope_id !== context.scopeId ||\n\t\t\t\top.device_id !== context.peerDeviceId ||\n\t\t\t\top.clock_device_id !== context.peerDeviceId\n\t\t\t)\n\t\t\t\tthrow new Error(\"channel op source or scope invalid\");\n\t\t}\n\t}\n\tif (url.pathname === \"/v1/snapshot\" && !Array.isArray(payload.items))\n\t\tthrow new Error(\"channel snapshot invalid\");\n}\n\nfunction channelExecutor(context: Context): RequestJsonExecutor {\n\tconst execute = createPeerHttpExecutor({\n\t\tsignal: context.signal,\n\t\tdeadlineMs: context.deadlineMs,\n\t\tfactory: {\n\t\t\topen: async (options) => {\n\t\t\t\tcheckAuthorization(context);\n\t\t\t\tconst connection = await context.open(options);\n\t\t\t\tconst owned = adoptPeerHttpConnection(connection);\n\t\t\t\ttry {\n\t\t\t\t\tcheckAuthorization(context);\n\t\t\t\t\tif (\n\t\t\t\t\t\t!owned.valid ||\n\t\t\t\t\t\treadAuthenticatedRelayNoisePeerPin(owned.duplex) !==\n\t\t\t\t\t\t\tcanonicalKey(context.peer.public_key)\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow new Error(\"channel peer pin mismatch\");\n\t\t\t\t\treturn owned;\n\t\t\t\t} catch {\n\t\t\t\t\tawait owned.dispose(new Error(\"channel trust invalid\"));\n\t\t\t\t\tthrow new Error(\"channel trust invalid\");\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t});\n\treturn async (method, target, options = {}) => {\n\t\tcheckAuthorization(context);\n\t\tconst url = new URL(target);\n\t\tif (url.origin !== context.logicalOrigin) throw new Error(\"channel target invalid\");\n\t\tconst response = await execute(method, target, options);\n\t\tcheckAuthorization(context);\n\t\tconst [status, payload] = response;\n\t\tif (method === \"GET\" && url.pathname !== \"/v1/status\" && status === 200 && payload)\n\t\t\tvalidatePullPayload(context, url, payload);\n\t\tif (status >= 400 && status !== 409 && status !== 413)\n\t\t\tthrow new Error(\"channel request failed\");\n\t\treturn response;\n\t};\n}\n\nfunction signedHeaders(context: Context, method: string, url: string, bodyBytes: Buffer) {\n\treturn {\n\t\t...buildDirectPeerAuthHeaders({\n\t\t\tdeviceId: context.local.device_id,\n\t\t\trecipientId: context.peerDeviceId,\n\t\t\tmethod,\n\t\t\turl,\n\t\t\tbodyBytes,\n\t\t\tkeysDir: context.keysDir,\n\t\t\tdbPath: context.dbPath,\n\t\t}),\n\t\t[SYNC_CAPABILITY_HEADER]: \"scoped\",\n\t\t[SYNC_FEATURES_HEADER]: LOCAL_SYNC_FEATURES.join(\",\"),\n\t};\n}\n\nfunction checkedBoundary(value: unknown, scopeId: string): Scope[\"sync_reset\"] {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value))\n\t\tthrow new Error(\"channel status invalid\");\n\tconst b = value as Scope[\"sync_reset\"];\n\tif (\n\t\tb.scope_id !== scopeId ||\n\t\t!Number.isSafeInteger(b.generation) ||\n\t\tb.generation < 1 ||\n\t\ttypeof b.snapshot_id !== \"string\" ||\n\t\t!b.snapshot_id.trim() ||\n\t\t!(b.baseline_cursor === null || typeof b.baseline_cursor === \"string\") ||\n\t\t!(b.retained_floor_cursor === null || typeof b.retained_floor_cursor === \"string\")\n\t)\n\t\tthrow new Error(\"channel status invalid\");\n\treturn b;\n}\n\nasync function fetchStatus(context: Context, execute: RequestJsonExecutor) {\n\tconst url = `${context.logicalOrigin}/v1/status?${new URLSearchParams({ scope_id: context.scopeId })}`;\n\tconst [status, payload] = await execute(\"GET\", url, {\n\t\theaders: signedHeaders(context, \"GET\", url, Buffer.alloc(0)),\n\t});\n\tif (\n\t\tstatus !== 200 ||\n\t\t!payload ||\n\t\tpayload.device_id !== context.peerDeviceId ||\n\t\tpayload.fingerprint !== context.peer.pinned_fingerprint ||\n\t\tString(payload.protocol_version) !== \"2\" ||\n\t\tpayload.sync_capability !== \"scoped\" ||\n\t\t!Array.isArray(payload.authorized_scopes) ||\n\t\tpayload.authorized_scopes.length !== 1\n\t)\n\t\tthrow new Error(\"channel status invalid\");\n\tconst scope = payload.authorized_scopes[0] as Scope | null;\n\tif (!scope || scope.scope_id !== context.scopeId) throw new Error(\"channel status invalid\");\n\tconst boundary = checkedBoundary(scope.sync_reset, context.scopeId);\n\tconst top = checkedBoundary(payload.sync_reset, context.scopeId);\n\tfor (const key of [\n\t\t\"generation\",\n\t\t\"snapshot_id\",\n\t\t\"baseline_cursor\",\n\t\t\"retained_floor_cursor\",\n\t] as const)\n\t\tif (top[key] !== boundary[key]) throw new Error(\"channel status invalid\");\n\treturn { scope, features: payload.sync_features, appliedCursor: appliedCursor(scope) };\n}\n\n/** The peer's pull cursor for this device, when it reports one in the right shape. */\nfunction appliedCursor(scope: Scope): string | null {\n\tconst value = (scope as { applied_cursor?: unknown }).applied_cursor;\n\tif (typeof value !== \"string\") return null;\n\tconst trimmed = value.trim();\n\tconst separator = trimmed.indexOf(\"|\");\n\treturn separator > 0 && separator < trimmed.length - 1 ? trimmed : null;\n}\n\n/** Cursors order by `created_at` text, then op ID, the same order the push window uses. */\nfunction laterCursor(a: string | null, b: string | null): string | null {\n\tif (!a) return b;\n\tif (!b) return a;\n\tconst [aTime, aOp] = [a.slice(0, a.indexOf(\"|\")), a.slice(a.indexOf(\"|\") + 1)];\n\tconst [bTime, bOp] = [b.slice(0, b.indexOf(\"|\")), b.slice(b.indexOf(\"|\") + 1)];\n\tif (aTime !== bTime) return aTime > bTime ? a : b;\n\treturn aOp >= bOp ? a : b;\n}\n\nfunction loadOutbound(\n\tcontext: Context,\n\tboundary: SyncChannelBoundary,\n\tappliedByPeer: string | null,\n): ReplicationOp[] {\n\tconst progress = getSyncChannelProgress(context.db, context.peerDeviceId, context.scopeId);\n\tif (!hasCompletedSyncChannelBoundary(progress, boundary))\n\t\tthrow new Error(\"channel progress changed\");\n\t// The peer may already hold ops this channel never sent, for example from\n\t// direct sync before relay. Start after whichever position is later.\n\tconst cursor = laterCursor(progress?.last_acked_cursor ?? null, appliedByPeer);\n\tconst separator = cursor?.indexOf(\"|\") ?? -1;\n\tconst timestamp = cursor?.slice(0, separator) ?? \"\";\n\tconst opId = cursor?.slice(separator + 1) ?? \"\";\n\treturn context.db\n\t\t.prepare(`SELECT * FROM replication_ops WHERE device_id = ? AND scope_id = ?\n\t\tAND (? IS NULL OR created_at > ? OR (created_at = ? AND op_id > ?))\n\t\tORDER BY created_at, op_id LIMIT ?`)\n\t\t.all(\n\t\t\tcontext.local.device_id,\n\t\t\tcontext.scopeId,\n\t\t\tcursor,\n\t\t\ttimestamp,\n\t\t\ttimestamp,\n\t\t\topId,\n\t\t\tcontext.limit,\n\t\t) as ReplicationOp[];\n}\n\nfunction pushBody(scopeId: string, ops: ReplicationOp[]): Buffer {\n\treturn Buffer.from(\n\t\tJSON.stringify({\n\t\t\tscope_id: scopeId,\n\t\t\tops,\n\t\t\tsync_capability: \"scoped\",\n\t\t\tsync_features: LOCAL_SYNC_FEATURES,\n\t\t}),\n\t);\n}\n\nfunction planBatches(scopeId: string, ops: ReplicationOp[]): ReplicationOp[][] {\n\tif (ops.length === 0) return [];\n\tif (pushBody(scopeId, ops).length <= MAX_BODY_BYTES) return [ops];\n\tif (ops.length === 1) throw new Error(\"channel operation too large\");\n\tconst middle = Math.floor(ops.length / 2);\n\treturn [\n\t\t...planBatches(scopeId, ops.slice(0, middle)),\n\t\t...planBatches(scopeId, ops.slice(middle)),\n\t];\n}\n\nfunction checkPushReply(payload: Record<string, unknown> | null, scopeId: string): void {\n\tif (\n\t\t!payload ||\n\t\tpayload.scope_id !== scopeId ||\n\t\tpayload.error != null ||\n\t\t(payload.errors !== undefined &&\n\t\t\t(!Array.isArray(payload.errors) || payload.errors.length !== 0)) ||\n\t\t(payload.rejected !== undefined && payload.rejected !== 0) ||\n\t\t(payload.rejections !== undefined &&\n\t\t\t(!Array.isArray(payload.rejections) || payload.rejections.length !== 0))\n\t)\n\t\tthrow new Error(\"channel push rejected\");\n}\n\nasync function pushBatch(\n\tcontext: Context,\n\texecute: RequestJsonExecutor,\n\tops: ReplicationOp[],\n): Promise<void> {\n\tconst url = `${context.logicalOrigin}/v1/ops`;\n\tconst bodyBytes = pushBody(context.scopeId, ops);\n\tconst [status, payload] = await execute(\"POST\", url, {\n\t\tbodyBytes,\n\t\theaders: signedHeaders(context, \"POST\", url, bodyBytes),\n\t});\n\tif (\n\t\tstatus === 413 &&\n\t\t(payload?.error === \"payload_too_large\" || payload?.error === \"too_many_ops\") &&\n\t\tops.length > 1\n\t) {\n\t\tconst middle = Math.floor(ops.length / 2);\n\t\tawait pushBatch(context, execute, ops.slice(0, middle));\n\t\tawait pushBatch(context, execute, ops.slice(middle));\n\t\treturn;\n\t}\n\tif (status !== 200) throw new Error(\"channel push failed\");\n\tcheckPushReply(payload, context.scopeId);\n\tcheckAuthorization(context);\n\tcontext.db.transaction(() => {\n\t\trecordSyncTransferReceipts(\n\t\t\tcontext.db,\n\t\t\tcontext.peerDeviceId,\n\t\t\t\"send\",\n\t\t\tops.map((op) => op.op_id),\n\t\t);\n\t\trecordSyncTransferObservation(context.db, context.peerDeviceId, \"send\");\n\t})();\n}\n\nasync function pushOutbound(\n\tcontext: Context,\n\texecute: RequestJsonExecutor,\n\tfeatures: unknown,\n\tboundary: SyncChannelBoundary,\n\tappliedByPeer: string | null,\n): Promise<number> {\n\tcheckAuthorization(context);\n\tconst window = loadOutbound(context, boundary, appliedByPeer);\n\tconst [ops, cursor] = filterReplicationOpsForSyncWithStatus(\n\t\tcontext.db,\n\t\twindow,\n\t\tcontext.peerDeviceId,\n\t\t{\n\t\t\tlocalDeviceId: context.local.device_id,\n\t\t\tsupportsReassignScope: supportsSyncFeature(features, \"reassign_scope\"),\n\t\t},\n\t);\n\tconst save = (acked: string) =>\n\t\tsaveSyncChannelOutboundAck(context.db, {\n\t\t\tpeerDeviceId: context.peerDeviceId,\n\t\t\tscopeId: context.scopeId,\n\t\t\tboundary,\n\t\t\tcursor: acked,\n\t\t});\n\t// Each confirmed batch saves its own ACK, so a pass that runs out of time keeps\n\t// what the peer already applied instead of resending the whole window next pass.\n\tfor (const batch of planBatches(context.scopeId, ops)) {\n\t\tawait pushBatch(context, execute, batch);\n\t\tcheckAuthorization(context);\n\t\tconst last = batch.at(-1);\n\t\tif (last) save(`${last.created_at}|${last.op_id}`);\n\t}\n\tcheckAuthorization(context);\n\t// The window cursor also covers ops filtered out after the last one sent. An\n\t// empty window means the peer's reported position already covers everything.\n\tconst saved = getSyncChannelProgress(context.db, context.peerDeviceId, context.scopeId);\n\tconst reached = laterCursor(laterCursor(cursor, appliedByPeer), saved?.last_acked_cursor ?? null);\n\t// A peer whose reported position is behind the saved ACK changes nothing.\n\tif (reached && reached !== saved?.last_acked_cursor) save(reached);\n\treturn ops.length;\n}\n\n/** Appends the factory's first relay reason, if any, to the existing generic local error. */\nfunction failedResult(\n\tresult: SyncScopeResult,\n\tfactory: ScopedChannelSyncOptions[\"factory\"],\n\terror: string,\n): SyncScopeResult {\n\tconst reason = factory.failureReason?.();\n\tif (!reason) return { ...result, ok: false, error };\n\treturn { ...result, ok: false, error: `${error}: ${reason}`, relayFailureReason: reason };\n}\n\nfunction failedPullResult(\n\toptions: ScopedChannelSyncOptions,\n\tresult: SyncScopeResult,\n): SyncScopeResult {\n\tconst errorCode =\n\t\tresult.receiveFailureCode ??\n\t\t(result.failureCategory === \"scope\" ? \"scope_rejected\" : \"exchange_failed\");\n\trecordSyncTransferObservation(options.db, options.peerDeviceId, \"receive\", { errorCode });\n\treturn failedResult(result, options.factory, \"channel pull failed\");\n}\n\n/** Internal, opt-in scoped exchange. Never discovers addresses or refreshes authorization. */\nexport async function syncScopedChannelOnce(\n\toptions: ScopedChannelSyncOptions,\n): Promise<SyncScopeResult> {\n\tlet sending = false;\n\tlet result: SyncScopeResult = {\n\t\tscope_id: options.scopeId,\n\t\tok: false,\n\t\topsIn: 0,\n\t\topsOut: 0,\n\t\tbootstrapped: false,\n\t};\n\ttry {\n\t\tconst context = captureContext(options);\n\t\tcheckAuthorization(context);\n\t\tconst execute = channelExecutor(context);\n\t\tconst status = await fetchStatus(context, execute);\n\t\tcheckAuthorization(context);\n\t\tconst progress = getSyncChannelProgress(context.db, context.peerDeviceId, context.scopeId);\n\t\tresult = await syncScopedPeerPull(context.db, {\n\t\t\tpeerDeviceId: context.peerDeviceId,\n\t\t\tbaseUrl: context.logicalOrigin,\n\t\t\tdeviceId: context.local.device_id,\n\t\t\tscope: status.scope,\n\t\t\trequestExecutor: execute,\n\t\t\tkeysDir: context.keysDir,\n\t\t\tdbPath: context.dbPath,\n\t\t\tscanner: context.scanner,\n\t\t\tlimit: context.limit,\n\t\t\tcompletedNullBaseline: hasCompletedSyncChannelBoundary(progress, status.scope.sync_reset),\n\t\t\tsourceDeviceId: context.peerDeviceId,\n\t\t\tvalidateCurrentAuthorization: () => checkAuthorization(context),\n\t\t\tinvalidateCompletedBoundary: () =>\n\t\t\t\tclearSyncChannelProgress(context.db, context.peerDeviceId, context.scopeId),\n\t\t});\n\t\tif (!result.ok) return failedPullResult(options, result);\n\t\t// One Space per pass proves the receive path works, but other scopes stay unretried.\n\t\trecordSyncTransferObservation(context.db, context.peerDeviceId, \"receive\", {\n\t\t\tpreserveScopedError: true,\n\t\t});\n\t\tcheckAuthorization(context);\n\t\tsaveSyncChannelCompletedBoundary(context.db, {\n\t\t\tpeerDeviceId: context.peerDeviceId,\n\t\t\tscopeId: context.scopeId,\n\t\t\tboundary: status.scope.sync_reset,\n\t\t});\n\t\tsending = true;\n\t\tconst opsOut = await pushOutbound(\n\t\t\tcontext,\n\t\t\texecute,\n\t\t\tstatus.features,\n\t\t\tstatus.scope.sync_reset,\n\t\t\tstatus.appliedCursor,\n\t\t);\n\t\treturn { ...result, opsOut };\n\t} catch {\n\t\trecordSyncTransferObservation(options.db, options.peerDeviceId, sending ? \"send\" : \"receive\", {\n\t\t\terrorCode: \"exchange_failed\",\n\t\t});\n\t\treturn failedResult(result, options.factory, \"scoped channel exchange failed\");\n\t}\n}\n","import { performance } from \"node:perf_hooks\";\nimport type { Database } from \"./db.js\";\nimport { isRelayPeerClient, type RelayPeerClient } from \"./relay-peer-client.js\";\nimport { isStableReleaseVersion } from \"./release-discovery.js\";\nimport { supportsSyncFeature } from \"./sync-capability.js\";\nimport { syncScopedChannelOnce } from \"./sync-channel-pass.js\";\nimport { type RequestJsonExecutor, requestJson } from \"./sync-http-client.js\";\nimport {\n\ttype SyncPassOptions,\n\ttype SyncResult,\n\ttype SyncScopeResult,\n\tsyncOnce,\n} from \"./sync-pass.js\";\nimport { recordSyncTransferObservation } from \"./sync-transfer-activity.js\";\n\nexport interface SyncReachabilityOptions {\n\t/** One explicitly authorized Space for relay fallback. Direct sync retains its existing scope behavior. */\n\treadonly scopeId: string;\n\treadonly logicalOrigin: string;\n\treadonly relay?: RelayPeerClient;\n\treadonly signal?: AbortSignal;\n\treadonly deadlineMs?: number;\n}\n\nexport type SyncReachabilityMaintenance = Pick<\n\tSyncReachabilityOptions,\n\t\"relay\" | \"signal\" | \"deadlineMs\"\n>;\n\n/**\n * Per-peer reachability for the sync daemon. The caller owns every relay\n * client's lifecycle and must close the clients during shutdown.\n */\nexport interface SyncPeerReachabilityResolver {\n\t/** This tick's relay route for one peer, or undefined for direct-only sync. */\n\tforPeer(db: Database, peerDeviceId: string): SyncReachabilityOptions | undefined;\n\t/** Relay clients whose registration the daemon maintains once per tick. */\n\tclients(): readonly RelayPeerClient[];\n\t/** Cancels maintenance and every pass this resolver selects. */\n\treadonly signal?: AbortSignal;\n}\n\n/** Reuses the existing reconciliation tick. Maintenance failure never blocks direct sync. */\nexport async function maintainSyncReachability(\n\toptions: SyncReachabilityMaintenance,\n): Promise<void> {\n\tif (!isRelayPeerClient(options.relay)) return;\n\ttry {\n\t\tawait options.relay.maintainRegistration(\n\t\t\toptions.signal ?? new AbortController().signal,\n\t\t\tMath.min(options.deadlineMs ?? Infinity, performance.now() + 3000),\n\t\t);\n\t} catch {\n\t\t// A later selected relay attempt reports failure through the normal pass result.\n\t}\n}\n\nconst activePeers = new WeakMap<Database, Set<string>>();\nconst activeRelayPeers = new WeakMap<RelayPeerClient, Set<string>>();\nconst NETWORK_CODES = new Set([\n\t\"ECONNREFUSED\",\n\t\"ECONNRESET\",\n\t\"ENETUNREACH\",\n\t\"EHOSTUNREACH\",\n\t\"ENOTFOUND\",\n\t\"EAI_AGAIN\",\n\t\"ETIMEDOUT\",\n\t\"UND_ERR_CONNECT_TIMEOUT\",\n\t\"UND_ERR_HEADERS_TIMEOUT\",\n\t\"UND_ERR_SOCKET\",\n]);\n\nfunction networkFailure(error: unknown): boolean {\n\tif (!error || typeof error !== \"object\") return false;\n\tconst value = error as { name?: string; code?: string; cause?: unknown };\n\tif (value.name === \"TimeoutError\" || (value.code && NETWORK_CODES.has(value.code))) return true;\n\tif (!value.cause || typeof value.cause !== \"object\") return false;\n\tconst cause = value.cause as { code?: string };\n\treturn cause.code !== undefined && NETWORK_CODES.has(cause.code);\n}\n\nfunction failure(transport: \"direct\" | \"wait\", error: string): SyncResult {\n\treturn {\n\t\tok: false,\n\t\ttransport,\n\t\terror,\n\t\tfailureCategory: \"other\",\n\t\topsIn: 0,\n\t\topsOut: 0,\n\t\taddressErrors: [],\n\t};\n}\n\nfunction requireActive(signal: AbortSignal, deadline: number): void {\n\tif (signal.aborted || performance.now() >= deadline)\n\t\tthrow new Error(\"Sync pass cancelled or expired\");\n}\n\nclass DirectPass {\n\tcommittedOrigin: string | null = null;\n\tterminal = false;\n\tattempts = 0;\n\tprivate readonly probeDeadline: number;\n\tconstructor(\n\t\tprivate readonly execute: RequestJsonExecutor,\n\t\tprivate readonly fingerprint: string,\n\t\tprivate readonly signal: AbortSignal,\n\t\tprivate readonly deadline: number,\n\t\tprivate readonly directDeadline: number,\n\t) {\n\t\tthis.probeDeadline = Math.min(deadline, performance.now() + 10_000);\n\t}\n\n\tprivate requestOrigin(method: string, url: string): string {\n\t\trequireActive(this.signal, this.committedOrigin === null ? this.deadline : this.directDeadline);\n\t\tconst origin = new URL(url).origin;\n\t\tif (this.terminal || (this.committedOrigin !== null && this.committedOrigin !== origin))\n\t\t\tthrow new Error(\"Sync transport is already committed\");\n\t\tif (\n\t\t\tthis.committedOrigin === null &&\n\t\t\t(method !== \"GET\" || !new URL(url).pathname.endsWith(\"/v1/status\"))\n\t\t) {\n\t\t\tthis.terminal = true;\n\t\t\tthrow new Error(\"Sync status is required before application requests\");\n\t\t}\n\t\treturn origin;\n\t}\n\n\treadonly request: RequestJsonExecutor = async (method, url, options = {}) => {\n\t\tconst origin = this.requestOrigin(method, url);\n\t\ttry {\n\t\t\tconst remaining =\n\t\t\t\t(this.committedOrigin === null ? this.probeDeadline : this.directDeadline) -\n\t\t\t\tperformance.now();\n\t\t\tif (remaining <= 0)\n\t\t\t\tthrow new DOMException(\"Direct reachability deadline expired\", \"TimeoutError\");\n\t\t\tthis.attempts++;\n\t\t\tconst response = await this.execute(method, url, {\n\t\t\t\t...options,\n\t\t\t\tredirect: \"error\",\n\t\t\t\tsignal: this.signal,\n\t\t\t\ttimeoutS: Math.min(options.timeoutS ?? 3, remaining / 1000),\n\t\t\t});\n\t\t\trequireActive(\n\t\t\t\tthis.signal,\n\t\t\t\tthis.committedOrigin === null ? this.deadline : this.directDeadline,\n\t\t\t);\n\t\t\tif (this.committedOrigin === null) {\n\t\t\t\tif (response[0] === 200 && response[1]?.fingerprint === this.fingerprint)\n\t\t\t\t\tthis.committedOrigin = origin;\n\t\t\t\telse this.terminal = true;\n\t\t\t}\n\t\t\treturn response;\n\t\t} catch (error) {\n\t\t\tif (this.committedOrigin !== null || this.signal.aborted || !networkFailure(error))\n\t\t\t\tthis.terminal = true;\n\t\t\tthrow error;\n\t\t}\n\t};\n}\n\nasync function selectedPass(\n\tdb: Database,\n\tpeerDeviceId: string,\n\taddresses: string[],\n\toptions: SyncPassOptions,\n\treachability: SyncReachabilityOptions,\n): Promise<SyncResult> {\n\tconst deadline = Math.min(reachability.deadlineMs ?? Infinity, performance.now() + 60_000);\n\tconst signal = reachability.signal ?? new AbortController().signal;\n\tif (\n\t\t(reachability.deadlineMs !== undefined && !Number.isFinite(reachability.deadlineMs)) ||\n\t\t!Number.isFinite(deadline) ||\n\t\t!reachability.scopeId.trim()\n\t)\n\t\treturn failure(\"wait\", \"Invalid sync pass configuration\");\n\trequireActive(signal, deadline);\n\tconst peer = db\n\t\t.prepare(\"SELECT pinned_fingerprint, public_key FROM sync_peers WHERE peer_device_id = ?\")\n\t\t.get(peerDeviceId) as { pinned_fingerprint: string; public_key: string } | undefined;\n\tif (!peer?.pinned_fingerprint)\n\t\treturn { ...failure(\"direct\", \"Peer is not pinned\"), failureCategory: \"trust\" };\n\tconst direct = new DirectPass(\n\t\toptions.requestExecutor ?? requestJson,\n\t\tpeer.pinned_fingerprint,\n\t\tsignal,\n\t\tdeadline,\n\t\treachability.deadlineMs ?? Infinity,\n\t);\n\tconst result = await syncOnce(db, peerDeviceId, addresses, {\n\t\t...options,\n\t\trequestExecutor: direct.request,\n\t\tattemptRecorder: options.attemptRecorder ?? (() => {}),\n\t\tdeferConnectionFailure: true,\n\t});\n\tif (result.ok || direct.committedOrigin !== null || direct.terminal)\n\t\treturn { ...result, transport: \"direct\" };\n\tif (direct.attempts === 0 && result.error !== \"no dialable peer addresses\")\n\t\treturn { ...result, transport: \"direct\" };\n\t// The traversal engine has no approved runtime capability. No RTC networking starts here.\n\tif (!reachability.relay) return { ...result, transport: \"wait\" };\n\tif (!isRelayPeerClient(reachability.relay))\n\t\treturn {\n\t\t\t...failure(\"wait\", \"Relay transport is unavailable\"),\n\t\t\treceiveFailureCode: result.receiveFailureCode,\n\t\t};\n\trequireActive(signal, deadline);\n\treturn relayPass(db, peerDeviceId, peer.public_key, options, reachability, signal, result);\n}\n\nasync function relayPass(\n\tdb: Database,\n\tpeerDeviceId: string,\n\tpeerPublicKey: string,\n\toptions: SyncPassOptions,\n\treachability: SyncReachabilityOptions,\n\tsignal: AbortSignal,\n\tdirect: SyncResult,\n): Promise<SyncResult> {\n\tif (!isRelayPeerClient(reachability.relay))\n\t\treturn {\n\t\t\t...failure(\"wait\", \"Relay transport is unavailable\"),\n\t\t\treceiveFailureCode: direct.receiveFailureCode,\n\t\t};\n\t// A skipped relay is a wait, so the pass records only the direct attempt, as it\n\t// does when no relay is configured.\n\tconst skip = relaySkipReason(db, peerDeviceId);\n\tif (skip) return { ...direct, transport: \"wait\", relaySkipped: skip };\n\tconst scoped = await syncScopedChannelOnce({\n\t\tdb,\n\t\tpeerDeviceId,\n\t\tscopeId: reachability.scopeId,\n\t\tlogicalOrigin: reachability.logicalOrigin,\n\t\tfactory: reachability.relay.factory(peerDeviceId, peerPublicKey),\n\t\tkeysDir: options.keysDir,\n\t\tdbPath: options.dbPath,\n\t\tscanner: options.scanner,\n\t\tlimit: options.limit,\n\t\tsignal,\n\t\t// Direct attempts to unreachable addresses can use most of the pass deadline.\n\t\t// Relay gets its own lifetime, bounded only by an explicit caller deadline.\n\t\tdeadlineMs: reachability.deadlineMs,\n\t});\n\trecordRelayOutcome(db, peerDeviceId, scoped);\n\treturn relayResult(scoped, direct);\n}\n\nconst RELAY_REJECTION_BACKOFF_MS = [2, 4, 8, 16, 30].map((minutes) => minutes * 60_000);\n/** A \"no relay client\" observation is trusted this long; after that the rejection back-off applies. */\nconst RELAY_UNSUPPORTED_TTL_MS = 24 * 60 * 60_000;\n\n/**\n * Why relay is not tried for this peer right now, or null to try it.\n *\n * A peer that last advertised `relay_aware` without `relay` over direct sync runs\n * no relay client, so the realm has no route for it. That observation expires after\n * a day, because the peer may turn relay on while direct sync is unavailable. A peer\n * without `relay_aware` may still relay on an early build, unless a recent stable\n * version identifies it as pre-0.48. Unknown or expired versions remain eligible.\n * A peer that recently\n * sent REJECTED is retried on a growing schedule, since REJECTED carries no\n * reason and most often means the peer is offline or not on relay.\n */\nfunction relaySkipReason(db: Database, peerDeviceId: string): SyncResult[\"relaySkipped\"] | null {\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT sync_features_json, sync_features_observed_at, relay_retry_after,\n\t\t\truntime_version, runtime_version_observed_at\n\t\t\tFROM sync_peers WHERE peer_device_id = ?`,\n\t\t)\n\t\t.get(peerDeviceId) as\n\t\t| {\n\t\t\t\tsync_features_json: string | null;\n\t\t\t\tsync_features_observed_at: string | null;\n\t\t\t\trelay_retry_after: string | null;\n\t\t\t\truntime_version: string | null;\n\t\t\t\truntime_version_observed_at: string | null;\n\t\t }\n\t\t| undefined;\n\tif (!row) return null;\n\tconst features = row.sync_features_json === null ? null : parseJson(row.sync_features_json);\n\tconst observedAt = Date.parse(row.sync_features_observed_at ?? \"\");\n\tconst age = Date.now() - observedAt;\n\tif (\n\t\tfeatures !== null &&\n\t\tage >= 0 &&\n\t\tage < RELAY_UNSUPPORTED_TTL_MS &&\n\t\tsupportsSyncFeature(features, \"relay_aware\") &&\n\t\t!supportsSyncFeature(features, \"relay\")\n\t)\n\t\treturn \"relay_peer_unsupported\";\n\tif (!supportsSyncFeature(features, \"relay\") && recentlyObservedLegacyPeer(row))\n\t\treturn \"relay_peer_unsupported\";\n\tif (row.relay_retry_after && row.relay_retry_after > new Date().toISOString())\n\t\treturn \"relay_backoff\";\n\treturn null;\n}\n\nfunction recentlyObservedLegacyPeer(peer: {\n\truntime_version: string | null;\n\truntime_version_observed_at: string | null;\n}): boolean {\n\tif (!isStableReleaseVersion(peer.runtime_version)) return false;\n\tconst age = Date.now() - Date.parse(peer.runtime_version_observed_at ?? \"\");\n\tif (!(age >= 0 && age < RELAY_UNSUPPORTED_TTL_MS)) return false;\n\tconst parts = peer.runtime_version.split(\".\");\n\treturn Number(parts[0]) === 0 && Number(parts[1]) < 48;\n}\n\nfunction parseJson(text: string): unknown {\n\ttry {\n\t\treturn JSON.parse(text);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction recordRelayOutcome(db: Database, peerDeviceId: string, result: SyncScopeResult): void {\n\tconst now = new Date().toISOString();\n\tif (result.ok) {\n\t\tdb.prepare(\n\t\t\t`UPDATE sync_peers SET last_sync_at = ?, last_seen_at = ?, last_error = NULL,\n\t\t\trelay_retry_after = NULL, relay_rejections = 0 WHERE peer_device_id = ?`,\n\t\t).run(now, now, peerDeviceId);\n\t\treturn;\n\t}\n\tif (result.relayFailureReason !== \"relay_rejected\") return;\n\tconst rejections =\n\t\t((\n\t\t\tdb\n\t\t\t\t.prepare(\"SELECT relay_rejections FROM sync_peers WHERE peer_device_id = ?\")\n\t\t\t\t.get(peerDeviceId) as { relay_rejections: number } | undefined\n\t\t)?.relay_rejections ?? 0) + 1;\n\tconst backoff =\n\t\tRELAY_REJECTION_BACKOFF_MS[Math.min(rejections, RELAY_REJECTION_BACKOFF_MS.length) - 1];\n\tdb.prepare(\n\t\t\"UPDATE sync_peers SET relay_retry_after = ?, relay_rejections = ? WHERE peer_device_id = ?\",\n\t).run(new Date(Date.now() + (backoff ?? 0)).toISOString(), rejections, peerDeviceId);\n}\n\nfunction relayResult(scoped: SyncScopeResult, direct: SyncResult): SyncResult {\n\treturn {\n\t\tok: scoped.ok,\n\t\ttransport: \"relay\",\n\t\topsIn: scoped.opsIn,\n\t\topsOut: scoped.opsOut,\n\t\terror: scoped.error,\n\t\tfailureCategory: scoped.failureCategory,\n\t\tresetRequired: scoped.resetRequired,\n\t\tperScopeResults: [scoped],\n\t\taddressErrors: direct.addressErrors,\n\t};\n}\n\n/** Opt-in direct → approved traversal when available → relay → wait. Never changes paths after status. */\nexport async function runReachableSyncPass(\n\tdb: Database,\n\tpeerDeviceId: string,\n\taddresses: string[],\n\toptions: SyncPassOptions,\n): Promise<SyncResult> {\n\tconst reachability = options.reachability;\n\tif (!reachability) return syncOnce(db, peerDeviceId, addresses, options);\n\tlet active = activePeers.get(db);\n\tif (!active) {\n\t\tactive = new Set();\n\t\tactivePeers.set(db, active);\n\t}\n\tlet relayActive: Set<string> | undefined;\n\tif (isRelayPeerClient(reachability.relay)) {\n\t\trelayActive = activeRelayPeers.get(reachability.relay);\n\t\tif (!relayActive) {\n\t\t\trelayActive = new Set();\n\t\t\tactiveRelayPeers.set(reachability.relay, relayActive);\n\t\t}\n\t}\n\tif (active.has(peerDeviceId) || relayActive?.has(peerDeviceId))\n\t\treturn failure(\"wait\", \"Peer sync is already in progress\");\n\t// Manual and daemon passes can share a relay client through separate DB handles.\n\t// Acquire both before direct work so fallback never competes with an admitted pass.\n\tactive.add(peerDeviceId);\n\trelayActive?.add(peerDeviceId);\n\ttry {\n\t\tconst result = await selectedPass(db, peerDeviceId, addresses, options, reachability);\n\t\tif (!result.ok && result.transport !== \"relay\" && result.receiveFailureCode) {\n\t\t\trecordSyncTransferObservation(db, peerDeviceId, \"receive\", {\n\t\t\t\terrorCode: result.receiveFailureCode,\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t} catch {\n\t\treturn failure(\"wait\", \"Sync pass cancelled or failed\");\n\t} finally {\n\t\tactive.delete(peerDeviceId);\n\t\trelayActive?.delete(peerDeviceId);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA6DA,IAAM,KACL,8MAUY,KAA8B;CAE1C;EAAE,MAAM;EAAqB,SAAS;CAAiC;CAEvE;EACC,MAAM;EACN,SAAS;EACT,YAAY;CACb;CAGA;EAAE,MAAM;EAAsB,SAAS;CAA2B;CAClE;EAAE,MAAM;EAA0B,SAAS;CAAmC;CAC9E;EAAE,MAAM;EAAgB,SAAS;CAA2B;CAC5D;EAAE,MAAM;EAAqB,SAAS;CAA2B;CACjE;EAAE,MAAM;EAAuB,SAAS;CAA2B;CACnE;EAAE,MAAM;EAAwB,SAAS;CAA2B;CAGpE;EAAE,MAAM;EAAO,SAAS;CAAwE;CAGhG;EAAE,MAAM;EAAkB,SAAS;CAA6B;CAChE;EAAE,MAAM;EAAe,SAAS;CAAoC;CACpE;EAAE,MAAM;EAAmB,SAAS;CAAgC;CACpE;EAAE,MAAM;EAAmB,SAAS;CAAgC;CACpE;EAAE,MAAM;EAAqB,SAAS;CAAoD;CAI1F;EACC,MAAM;EACN,SAAS;EACT,YAAY;CACb;CAKA;EACC,MAAM;EACN,SACC;CACF;CAIA;EACC,MAAM;EACN,SACC;EACD,YAAY;EACZ,aAAa;CACd;AACD;AAGA,SAAS,GAAe,GAAsB;CAC7C,IAAI,EAAK,WAAW,GAAG,OAAO;CAC9B,IAAM,oBAAO,IAAI,IAAoB;CACrC,KAAK,IAAM,KAAM,GAAM,EAAK,IAAI,IAAK,EAAK,IAAI,CAAE,KAAK,KAAK,CAAC;CAC3D,IAAI,IAAI;CACR,KAAK,IAAM,KAAS,EAAK,OAAO,GAAG;EAClC,IAAM,IAAI,IAAQ,EAAK;EACvB,KAAK,IAAI,KAAK,KAAK,CAAC;CACrB;CACA,OAAO;AACR;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ET,AADA,EAAO,OAAO,CAAY,GAC1B,GAAa,OAAO,CAAY;CACjC;AACD"}
|
|
1
|
+
{"version":3,"file":"sync-reachability-pass-CUe5bK61.js","names":[],"sources":["../src/secret-scanner.ts","../src/repository-mapping-aliases.ts","../src/policy-team-device-eligibility.ts","../src/sync-bootstrap-constants.ts","../src/maintenance-jobs.ts","../src/session-export-identity.ts","../src/session-export-identity-mutation.ts","../src/ref-populate.ts","../src/vector-metadata-rows.ts","../src/vector-metadata-snapshot.ts","../src/vector-writes.ts","../src/vectors.ts","../src/repository-discovery-cache.ts","../src/scope-stamping.ts","../src/memory-retirement-snapshot-guard.ts","../src/recipient-policy-reconciliation.ts","../src/tags.ts","../src/sync-replication.ts","../src/vector-backfill-queue.ts","../src/vector-cutover-validation.ts","../src/vector-migration.ts","../src/mise-install-path.ts","../src/release-discovery.ts","../src/sync-bootstrap.ts","../src/sync-discovery.ts","../src/sync-channel-progress.ts","../src/sync-failure-classification.ts","../src/sync-pass.ts","../src/peer-http-client.ts","../src/sync-scope-protocol.ts","../src/sync-channel-pass.ts","../src/sync-reachability-pass.ts"],"sourcesContent":["/**\n * Write-time secret scanner for the codemem store.\n *\n * Detects common secrets in memory write payloads (titles, bodies, narratives,\n * structured fields, and free-form metadata) and replaces them with\n * `[REDACTED:<kind>]` markers before persistence. There is no override flag:\n * codemem has no legitimate use case for storing live secrets, so any escape\n * hatch becomes the bypass that makes scanning theater.\n *\n * Scope of this foundation: the local-write chokepoint inside `MemoryStore.remember`.\n * Other writers into `memory_items` (sync-replication apply, sync-bootstrap\n * snapshot apply, AI/maintenance backfills of narrative/facts/concepts/tags)\n * are NOT scanned by this module yet — they are addressed by dependent bd\n * issues (codemem-hflk for sync-receive, codemem-tzrn for compaction/AI output,\n * codemem-vb2s for retroactive sweep over already-stored content). Workspace-level\n * rule overrides (codemem-ben8) and the test-fixture allowlist (codemem-jasn)\n * plug in via `ScannerOptions` without changing this module's shape.\n */\n\nexport interface SecretRule {\n\t/** Stable identifier surfaced in the redaction marker and detection log. */\n\tkind: string;\n\t/** Regex used to find candidate matches. Must be a global regex. */\n\tpattern: RegExp;\n\t/**\n\t * Optional minimum Shannon entropy (bits/char) the matched substring must\n\t * meet to be redacted. Filters out low-entropy false positives like\n\t * common words that happen to look like a secret.\n\t */\n\tminEntropy?: number;\n\t/**\n\t * If set, only the indicated capture group (1-based) is replaced. Useful\n\t * for context-aware rules where the match includes a known prefix that\n\t * should be preserved.\n\t */\n\tredactGroup?: number;\n}\n\nexport interface ScanDetection {\n\tkind: string;\n\tcount: number;\n}\n\nexport interface ScanResult {\n\tredacted: string;\n\tdetections: ScanDetection[];\n}\n\nexport interface ScannerOptions {\n\t/** Additional rules merged with `DEFAULT_RULES`. */\n\trules?: SecretRule[];\n\t/**\n\t * Strings or regexes that bypass redaction even when matched. NOTE: string\n\t * entries match by exact equality against the matched substring; regex\n\t * entries are tested with `RegExp.test()` (partial match by default; use\n\t * anchors for exact match).\n\t */\n\tallowlist?: Array<string | RegExp>;\n}\n\n/** Field names whose string values should be treated as secret-bearing. */\nconst SECRET_BEARING_KEY =\n\t/^(?:secret|token|password|passwd|pwd|auth|bearer|credential|api[_-]?key|access[_-]?key|client[_-]?secret|private[_-]?key|access[_-]?token|refresh[_-]?token|id[_-]?token|bearer[_-]?token|api[_-]?token)$/i;\n\n/**\n * Built-in default rules. Conservative: prefer well-known prefixes and\n * structural patterns over raw entropy to keep the false-positive rate low.\n *\n * Rule precedence is order-dependent. More-specific rules MUST come before\n * more-general ones — see the OpenAI rule, which uses a negative lookahead to\n * avoid swallowing Anthropic keys regardless of order.\n */\nexport const DEFAULT_RULES: SecretRule[] = [\n\t// AWS — both halves of an access key pair\n\t{ kind: \"aws_access_key_id\", pattern: /\\b(?:AKIA|ASIA)[0-9A-Z]{16}\\b/g },\n\t// AWS secret access key — 40 base64-ish chars; require entropy to filter FPs\n\t{\n\t\tkind: \"aws_secret_access_key\",\n\t\tpattern: /(?<![A-Za-z0-9/+=])[A-Za-z0-9/+=]{40}(?![A-Za-z0-9/+=])/g,\n\t\tminEntropy: 4.5,\n\t},\n\n\t// GitHub token family\n\t{ kind: \"github_pat_classic\", pattern: /\\bghp_[A-Za-z0-9]{36}\\b/g },\n\t{ kind: \"github_pat_finegrained\", pattern: /\\bgithub_pat_[A-Za-z0-9_]{82}\\b/g },\n\t{ kind: \"github_oauth\", pattern: /\\bgho_[A-Za-z0-9]{36}\\b/g },\n\t{ kind: \"github_user_token\", pattern: /\\bghu_[A-Za-z0-9]{36}\\b/g },\n\t{ kind: \"github_server_token\", pattern: /\\bghs_[A-Za-z0-9]{36}\\b/g },\n\t{ kind: \"github_refresh_token\", pattern: /\\bghr_[A-Za-z0-9]{36}\\b/g },\n\n\t// JWT — three base64url segments separated by dots, header begins with eyJ\n\t{ kind: \"jwt\", pattern: /\\beyJ[A-Za-z0-9_-]{10,}\\.eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\b/g },\n\n\t// Common provider keys\n\t{ kind: \"google_api_key\", pattern: /\\bAIza[0-9A-Za-z_-]{35}\\b/g },\n\t{ kind: \"slack_token\", pattern: /\\bxox[abprs]-[A-Za-z0-9-]{10,}\\b/g },\n\t{ kind: \"stripe_live_key\", pattern: /\\bsk_live_[0-9a-zA-Z]{24,}\\b/g },\n\t{ kind: \"stripe_test_key\", pattern: /\\bsk_test_[0-9a-zA-Z]{24,}\\b/g },\n\t{ kind: \"anthropic_api_key\", pattern: /\\bsk-ant-(?:api|admin)\\d{2}-[A-Za-z0-9_-]{80,}\\b/g },\n\t// OpenAI keys: negative lookahead for `ant-` so Anthropic keys do not match here\n\t// even if rule order changes. Entropy floor avoids false-positive on internal\n\t// `sk-` prefixed identifiers that happen to be long enough.\n\t{\n\t\tkind: \"openai_api_key\",\n\t\tpattern: /\\bsk-(?!ant-)(?:proj-|svcacct-)?[A-Za-z0-9_-]{32,}\\b/g,\n\t\tminEntropy: 3.5,\n\t},\n\n\t// PEM-encoded private keys (RSA/EC/DSA/OpenSSH/PGP). Note: PGP MESSAGE\n\t// blocks, SSH2 ENCRYPTED PRIVATE KEY, and PuTTY user-key files are NOT\n\t// matched by this rule and remain a known gap (deferred backlog).\n\t{\n\t\tkind: \"pem_private_key\",\n\t\tpattern:\n\t\t\t/-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----[\\s\\S]+?-----END (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----/g,\n\t},\n\n\t// Context-aware generic secret: secret/token/password = \"<value>\"\n\t// Only the captured value (group 1) is redacted; the prefix is preserved.\n\t{\n\t\tkind: \"generic_assigned_secret\",\n\t\tpattern:\n\t\t\t/\\b(?:secret|token|password|passwd|pwd|auth|bearer|credential|api[_-]?key|access[_-]?key|client[_-]?secret|access[_-]?token|refresh[_-]?token|id[_-]?token|bearer[_-]?token|api[_-]?token)\\s*[:=]\\s*[\"']?([A-Za-z0-9+/=_.-]{20,})[\"']?/gi,\n\t\tminEntropy: 3.5,\n\t\tredactGroup: 1,\n\t},\n];\n\n/** Shannon entropy in bits per character. */\nfunction shannonEntropy(text: string): number {\n\tif (text.length === 0) return 0;\n\tconst freq = new Map<string, number>();\n\tfor (const ch of text) freq.set(ch, (freq.get(ch) ?? 0) + 1);\n\tlet h = 0;\n\tfor (const count of freq.values()) {\n\t\tconst p = count / text.length;\n\t\th -= p * Math.log2(p);\n\t}\n\treturn h;\n}\n\nfunction ensureGlobal(re: RegExp): RegExp {\n\tif (re.flags.includes(\"g\")) return re;\n\treturn new RegExp(re.source, `${re.flags}g`);\n}\n\nfunction isAllowlisted(match: string, allowlist: Array<string | RegExp>): boolean {\n\tfor (const entry of allowlist) {\n\t\tif (typeof entry === \"string\") {\n\t\t\tif (entry === match) return true;\n\t\t} else {\n\t\t\t// `RegExp.test()` advances `lastIndex` on regexes with `g` or `y`\n\t\t\t// flags, which would make repeated allowlist checks return\n\t\t\t// alternating results. Reset before testing so the decision is\n\t\t\t// stable across calls regardless of caller-supplied flags.\n\t\t\tif (entry.global || entry.sticky) entry.lastIndex = 0;\n\t\t\tif (entry.test(match)) return true;\n\t\t}\n\t}\n\treturn false;\n}\n\n/**\n * Detect whether `value` is a \"plain\" object (`{}` literal or `Object.create(null)`),\n * vs a class instance / built-in like Date, Map, Set, RegExp, Buffer, typed array.\n * Plain objects are walked recursively; non-plain objects are returned as-is so\n * we don't silently corrupt them by reconstructing as `{}`.\n */\nfunction isPlainObject(value: object): boolean {\n\tconst proto = Object.getPrototypeOf(value);\n\treturn proto === null || proto === Object.prototype;\n}\n\nexport class SecretScanner {\n\tprivate readonly rules: SecretRule[];\n\tprivate readonly allowlist: Array<string | RegExp>;\n\n\tconstructor(opts: ScannerOptions = {}) {\n\t\tthis.rules = [...DEFAULT_RULES, ...(opts.rules ?? [])];\n\t\tthis.allowlist = opts.allowlist ?? [];\n\t}\n\n\t/** Scan a single string. Returns the redacted form and per-kind detection counts. */\n\tscan(text: string): ScanResult {\n\t\tif (!text || typeof text !== \"string\") return { redacted: text, detections: [] };\n\t\tlet redacted = text;\n\t\tconst counts = new Map<string, number>();\n\t\tfor (const rule of this.rules) {\n\t\t\tconst re = ensureGlobal(rule.pattern);\n\t\t\tredacted = redacted.replace(re, (...args) => {\n\t\t\t\t// args = [match, ...groups, offset, fullString, groupsObj?]\n\t\t\t\tconst match = args[0] as string;\n\t\t\t\tconst target =\n\t\t\t\t\trule.redactGroup != null ? ((args[rule.redactGroup] as string | undefined) ?? \"\") : match;\n\t\t\t\tif (!target) return match;\n\t\t\t\tif (isAllowlisted(target, this.allowlist)) return match;\n\t\t\t\tif (rule.minEntropy != null && shannonEntropy(target) < rule.minEntropy) return match;\n\t\t\t\tcounts.set(rule.kind, (counts.get(rule.kind) ?? 0) + 1);\n\t\t\t\tconst marker = `[REDACTED:${rule.kind}]`;\n\t\t\t\tif (rule.redactGroup != null) {\n\t\t\t\t\treturn match.replace(target, marker);\n\t\t\t\t}\n\t\t\t\treturn marker;\n\t\t\t});\n\t\t}\n\t\tconst detections = Array.from(counts.entries()).map(([kind, count]) => ({ kind, count }));\n\t\treturn { redacted, detections };\n\t}\n\n\t/**\n\t * Recursively walk a value, scanning every string. String values whose\n\t * containing key name matches a secret-bearing field are redacted whole if\n\t * non-trivial. Non-plain objects (Date, Map, Set, RegExp, Buffer, typed\n\t * arrays, class instances) are returned as-is to avoid silent corruption.\n\t * Cycles are detected via a `seen` set so misbehaving callers cannot\n\t * stack-overflow the scanner.\n\t */\n\tredactValue(value: unknown, parentKey?: string): { value: unknown; detections: ScanDetection[] } {\n\t\treturn this.redactValueInternal(value, parentKey, new WeakSet());\n\t}\n\n\tprivate redactValueInternal(\n\t\tvalue: unknown,\n\t\tparentKey: string | undefined,\n\t\tseen: WeakSet<object>,\n\t): { value: unknown; detections: ScanDetection[] } {\n\t\tif (typeof value === \"string\") {\n\t\t\tif (parentKey && SECRET_BEARING_KEY.test(parentKey) && this.looksLikeSecretValue(value)) {\n\t\t\t\tif (isAllowlisted(value, this.allowlist)) {\n\t\t\t\t\treturn { value, detections: [] };\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tvalue: \"[REDACTED:context_secret]\",\n\t\t\t\t\tdetections: [{ kind: \"context_secret\", count: 1 }],\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst result = this.scan(value);\n\t\t\treturn { value: result.redacted, detections: result.detections };\n\t\t}\n\t\tif (Array.isArray(value)) {\n\t\t\tif (seen.has(value)) return { value, detections: [] };\n\t\t\tseen.add(value);\n\t\t\tconst out: unknown[] = [];\n\t\t\tconst merged = new Map<string, number>();\n\t\t\tfor (const item of value) {\n\t\t\t\tconst r = this.redactValueInternal(item, parentKey, seen);\n\t\t\t\tout.push(r.value);\n\t\t\t\tfor (const d of r.detections) merged.set(d.kind, (merged.get(d.kind) ?? 0) + d.count);\n\t\t\t}\n\t\t\treturn { value: out, detections: aggregateMap(merged) };\n\t\t}\n\t\tif (value !== null && typeof value === \"object\") {\n\t\t\tif (seen.has(value)) return { value, detections: [] };\n\t\t\tif (!isPlainObject(value)) {\n\t\t\t\t// Non-plain objects (Date, Map, Set, RegExp, Buffer, typed arrays,\n\t\t\t\t// class instances) are returned unchanged. Walking them would\n\t\t\t\t// silently strip prototype methods and corrupt state.\n\t\t\t\treturn { value, detections: [] };\n\t\t\t}\n\t\t\tseen.add(value);\n\t\t\tconst obj = value as Record<string, unknown>;\n\t\t\tconst out: Record<string, unknown> = {};\n\t\t\tconst merged = new Map<string, number>();\n\t\t\tfor (const [k, v] of Object.entries(obj)) {\n\t\t\t\tconst r = this.redactValueInternal(v, k, seen);\n\t\t\t\tout[k] = r.value;\n\t\t\t\tfor (const d of r.detections) merged.set(d.kind, (merged.get(d.kind) ?? 0) + d.count);\n\t\t\t}\n\t\t\treturn { value: out, detections: aggregateMap(merged) };\n\t\t}\n\t\treturn { value, detections: [] };\n\t}\n\n\tprivate looksLikeSecretValue(text: string): boolean {\n\t\t// Threshold of 8 chars filters obvious placeholders (\"n/a\", \"true\", short\n\t\t// human values) while still catching anything long enough to plausibly\n\t\t// be a secret. URL values get a free pass since auth callback URLs are\n\t\t// commonly stored under \"auth\"-named keys.\n\t\tif (text.length < 8) return false;\n\t\tif (/^(?:https?|ftp|file):\\/\\//i.test(text)) return false;\n\t\tif (/^(?:\\[REDACTED:|<.*>|\\{\\{.*\\}\\}|null|undefined)$/i.test(text.trim())) return false;\n\t\treturn true;\n\t}\n}\n\nfunction aggregateMap(map: Map<string, number>): ScanDetection[] {\n\treturn Array.from(map.entries()).map(([kind, count]) => ({ kind, count }));\n}\n\n/**\n * Build `ScannerOptions` from a parsed codemem config object's\n * `secret_scanner` block. Workspace-scoped rule overrides and an allowlist\n * for known-safe matches are accepted under a single config key so a team\n * can tighten or loosen the default policy without forking codemem.\n *\n * Expected shape (all keys optional):\n * ```jsonc\n * {\n * \"secret_scanner\": {\n * \"rules\": [\n * { \"kind\": \"internal_token\", \"pattern\": \"\\\\bACME-[A-Z0-9]{10}\\\\b\", \"flags\": \"g\", \"minEntropy\": 3.0 }\n * ],\n * \"allowlist\": [\n * \"AKIAFAKEFIXTURE0001\", // string entries match by exact equality\n * \"/^test-fixture-.*$/i\" // strings of the form /pattern/flags become regexes\n * ]\n * }\n * }\n * ```\n *\n * Malformed entries are silently dropped — config errors should never block\n * a workspace from opening.\n */\nexport function loadScannerOptionsFromConfig(\n\tconfig: Record<string, unknown> | null | undefined,\n): ScannerOptions {\n\tconst empty: ScannerOptions = {};\n\tif (!config || typeof config !== \"object\") return empty;\n\tconst block = (config as { secret_scanner?: unknown }).secret_scanner;\n\tif (!block || typeof block !== \"object\" || Array.isArray(block)) return empty;\n\tconst out: ScannerOptions = {};\n\n\tconst rawRules = (block as { rules?: unknown }).rules;\n\tif (Array.isArray(rawRules)) {\n\t\tconst rules: SecretRule[] = [];\n\t\tfor (const entry of rawRules) {\n\t\t\tif (!entry || typeof entry !== \"object\" || Array.isArray(entry)) continue;\n\t\t\tconst e = entry as Record<string, unknown>;\n\t\t\tif (typeof e.kind !== \"string\" || typeof e.pattern !== \"string\") continue;\n\t\t\tconst flagsRaw = typeof e.flags === \"string\" ? e.flags : \"g\";\n\t\t\tconst flags = flagsRaw.includes(\"g\") ? flagsRaw : `${flagsRaw}g`;\n\t\t\tlet pattern: RegExp;\n\t\t\ttry {\n\t\t\t\tpattern = new RegExp(e.pattern, flags);\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst rule: SecretRule = { kind: e.kind, pattern };\n\t\t\tif (typeof e.minEntropy === \"number\" && Number.isFinite(e.minEntropy)) {\n\t\t\t\trule.minEntropy = e.minEntropy;\n\t\t\t}\n\t\t\tif (\n\t\t\t\ttypeof e.redactGroup === \"number\" &&\n\t\t\t\tNumber.isInteger(e.redactGroup) &&\n\t\t\t\te.redactGroup > 0\n\t\t\t) {\n\t\t\t\trule.redactGroup = e.redactGroup;\n\t\t\t}\n\t\t\trules.push(rule);\n\t\t}\n\t\tif (rules.length > 0) out.rules = rules;\n\t}\n\n\tconst rawAllowlist = (block as { allowlist?: unknown }).allowlist;\n\tif (Array.isArray(rawAllowlist)) {\n\t\tconst allowlist: Array<string | RegExp> = [];\n\t\tfor (const entry of rawAllowlist) {\n\t\t\tif (typeof entry !== \"string\" || entry.length === 0) continue;\n\t\t\t// Strings of the form /pattern/flags are parsed as regex; everything\n\t\t\t// else is treated as a literal.\n\t\t\tconst re = parseRegexLiteral(entry);\n\t\t\tallowlist.push(re ?? entry);\n\t\t}\n\t\tif (allowlist.length > 0) out.allowlist = allowlist;\n\t}\n\n\treturn out;\n}\n\nfunction parseRegexLiteral(value: string): RegExp | null {\n\tif (value.length < 2 || value[0] !== \"/\") return null;\n\tconst lastSlash = value.lastIndexOf(\"/\");\n\tif (lastSlash <= 0) return null;\n\tconst pattern = value.slice(1, lastSlash);\n\tconst flags = value.slice(lastSlash + 1);\n\tif (!/^[gimsuy]*$/.test(flags)) return null;\n\t// Allowlist regexes are tested via RegExp.test which is stateful when `g`\n\t// or `y` is set. Strip those flags up front so a configured /^foo/g\n\t// behaves the same as /^foo/ — the runtime guard in isAllowlisted is\n\t// belt-and-suspenders, this is the suspenders.\n\tconst safeFlags = flags.replace(/[gy]/g, \"\");\n\ttry {\n\t\treturn new RegExp(pattern, safeFlags);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Merge multiple detection lists into a single per-kind summary. */\nexport function mergeDetections(...lists: ScanDetection[][]): ScanDetection[] {\n\tconst merged = new Map<string, number>();\n\tfor (const list of lists) {\n\t\tfor (const d of list) merged.set(d.kind, (merged.get(d.kind) ?? 0) + d.count);\n\t}\n\treturn aggregateMap(merged);\n}\n\n/**\n * Shape of a parsed inbound memory payload (sync-replication or sync-bootstrap).\n * Any field that is `undefined` is left untouched. The struct is mutated in\n * place by `redactMemoryFields` so callers can redact-then-insert without\n * cloning.\n */\nexport interface MemoryFieldRedactionTarget {\n\ttitle?: string | null;\n\tsubtitle?: string | null;\n\tbody_text?: string | null;\n\ttags_text?: string | null;\n\tnarrative?: string | null;\n\tfacts?: unknown;\n\tconcepts?: unknown;\n\tfiles_read?: unknown;\n\tfiles_modified?: unknown;\n\tmetadata_json?: unknown;\n\t/**\n\t * Peer-controlled identity strings persisted alongside content. They show\n\t * up in the viewer and exports verbatim, so a malicious peer could smuggle\n\t * a secret in a display name. Scanned for the same well-known patterns as\n\t * everything else; not subject to context_secret heuristics since they\n\t * legitimately contain free-form text.\n\t */\n\tactor_display_name?: string | null;\n\torigin_source?: string | null;\n}\n\n/**\n * Redact secrets from a parsed inbound memory payload before persistence.\n * Used by sync-receive (sync-replication.ts) and bootstrap-snapshot apply\n * (sync-bootstrap.ts) so peer-shipped content goes through the same scanner\n * as locally-authored writes. Mutates the target in place; returns the merged\n * detection summary across all scanned fields.\n */\nexport function redactMemoryFields<T extends MemoryFieldRedactionTarget>(\n\ttarget: T,\n\tscanner: SecretScanner,\n): { target: T; detections: ScanDetection[] } {\n\tconst lists: ScanDetection[][] = [];\n\n\tconst scanStringField = (key: keyof MemoryFieldRedactionTarget): void => {\n\t\tconst value = (target as MemoryFieldRedactionTarget)[key];\n\t\tif (typeof value === \"string\" && value.length > 0) {\n\t\t\tconst result = scanner.scan(value);\n\t\t\t(target as MemoryFieldRedactionTarget)[key] = result.redacted;\n\t\t\tlists.push(result.detections);\n\t\t}\n\t};\n\tscanStringField(\"title\");\n\tscanStringField(\"subtitle\");\n\tscanStringField(\"body_text\");\n\tscanStringField(\"narrative\");\n\tscanStringField(\"actor_display_name\");\n\tscanStringField(\"origin_source\");\n\n\t// tags_text is a whitespace-joined string here. Local writes scan each tag\n\t// individually before joining (store.ts), so to keep behavior consistent\n\t// when peer payloads arrive pre-joined we split, scan-per-tag, and rejoin.\n\tconst rawTagsText = (target as MemoryFieldRedactionTarget).tags_text;\n\tif (typeof rawTagsText === \"string\" && rawTagsText.length > 0) {\n\t\tconst parts = rawTagsText.split(/\\s+/).filter(Boolean);\n\t\tconst scannedParts: string[] = [];\n\t\tfor (const part of parts) {\n\t\t\tconst result = scanner.scan(part);\n\t\t\tscannedParts.push(result.redacted);\n\t\t\tlists.push(result.detections);\n\t\t}\n\t\t(target as MemoryFieldRedactionTarget).tags_text = scannedParts.join(\" \");\n\t}\n\n\tfor (const key of [\"facts\", \"concepts\", \"files_read\", \"files_modified\"] as const) {\n\t\tconst value = (target as MemoryFieldRedactionTarget)[key];\n\t\tif (Array.isArray(value)) {\n\t\t\tconst next: unknown[] = [];\n\t\t\tfor (const item of value) {\n\t\t\t\tif (typeof item === \"string\") {\n\t\t\t\t\tconst result = scanner.scan(item);\n\t\t\t\t\tnext.push(result.redacted);\n\t\t\t\t\tlists.push(result.detections);\n\t\t\t\t} else {\n\t\t\t\t\tnext.push(item);\n\t\t\t\t}\n\t\t\t}\n\t\t\t(target as MemoryFieldRedactionTarget)[key] = next;\n\t\t}\n\t}\n\n\tif (target.metadata_json && typeof target.metadata_json === \"object\") {\n\t\tconst result = scanner.redactValue(target.metadata_json);\n\t\ttarget.metadata_json = result.value;\n\t\tlists.push(result.detections);\n\t}\n\n\treturn { target, detections: mergeDetections(...lists) };\n}\n","import { isAbsolute } from \"node:path\";\nimport type { Database } from \"./db.js\";\nimport { repositoryIdentityFromMetadata, resolveGitRepositoryIdentity } from \"./project.js\";\nimport { cleanProjectIdentity } from \"./project-identity.js\";\nimport {\n\tLOCAL_DEFAULT_SCOPE_ID,\n\tresolveProjectScope,\n\ttype ScopeMapping,\n} from \"./scope-resolution.js\";\n\nconst GIT_IDENTITY_CACHE_TTL_MS = 5_000;\nconst GIT_IDENTITY_CACHE_MAX_ENTRIES = 256;\nconst gitIdentityCache = new Map<string, { expiresAt: number; identity: string }>();\nconst syntheticRepositoryAliases = new WeakSet<object>();\nconst recordedWorkspacesByIdentityMap = new WeakMap<object, ReadonlySet<string>>();\n\nexport function normalizeRepositoryWorkspaceIdentity(\n\tvalue: string | null | undefined,\n): string | null {\n\tconst cleaned = value?.trim();\n\tif (!cleaned) return null;\n\treturn cleaned.replaceAll(\"\\\\\", \"/\").replace(/\\/+$/u, \"\") || cleaned;\n}\n\nconst normalizeIdentity = normalizeRepositoryWorkspaceIdentity;\n\nexport function hasRecordedRepositoryWorkspace(\n\trepositoryIdentities: ReadonlyMap<string, string>,\n\tworkspace: string | null | undefined,\n): boolean {\n\tconst normalized = normalizeIdentity(workspace);\n\treturn Boolean(\n\t\tnormalized && recordedWorkspacesByIdentityMap.get(repositoryIdentities)?.has(normalized),\n\t);\n}\n\nfunction cachedGitRepositoryIdentity(cwd: string): string | null {\n\tconst normalizedCwd = normalizeIdentity(cwd);\n\tif (!normalizedCwd) return null;\n\tconst now = Date.now();\n\tconst cached = gitIdentityCache.get(normalizedCwd);\n\tif (cached && cached.expiresAt > now) return cached.identity;\n\tif (cached) gitIdentityCache.delete(normalizedCwd);\n\tconst identity = normalizeIdentity(resolveGitRepositoryIdentity(cwd)?.identity);\n\tif (!identity) return null;\n\tif (gitIdentityCache.size >= GIT_IDENTITY_CACHE_MAX_ENTRIES) {\n\t\tconst oldestKey = gitIdentityCache.keys().next().value;\n\t\tif (oldestKey) gitIdentityCache.delete(oldestKey);\n\t}\n\tgitIdentityCache.set(normalizedCwd, {\n\t\texpiresAt: now + GIT_IDENTITY_CACHE_TTL_MS,\n\t\tidentity,\n\t});\n\treturn identity;\n}\n\nfunction gitRepositoryIdentity(cwd: string, bypassCache: boolean): string | null {\n\tif (!bypassCache) return cachedGitRepositoryIdentity(cwd);\n\tconst normalizedCwd = normalizeIdentity(cwd);\n\tif (!normalizedCwd) return null;\n\tgitIdentityCache.delete(normalizedCwd);\n\treturn normalizeIdentity(resolveGitRepositoryIdentity(cwd)?.identity);\n}\n\nfunction recordedRepositoryIdentity(row: {\n\tgit_remote?: string | null;\n\tmetadata_json?: string | null;\n\trepository_identity?: string | null;\n}): string | null {\n\treturn normalizeIdentity(\n\t\tcleanProjectIdentity(row.repository_identity) ??\n\t\t\tcleanProjectIdentity(repositoryIdentityFromMetadata(row.metadata_json)) ??\n\t\t\tcleanProjectIdentity(row.git_remote),\n\t);\n}\n\nfunction recordedRepositoryEvidence(row: {\n\tcwd: string;\n\tgit_remote?: string | null;\n\tmetadata_json?: string | null;\n\trepository_identity?: string | null;\n}): { cwd: string; fromMetadata: boolean; repositoryIdentity: string } | null {\n\tconst cwd = normalizeIdentity(row.cwd);\n\tif (!cwd) return null;\n\tconst metadataIdentity = normalizeIdentity(\n\t\tcleanProjectIdentity(row.repository_identity) ??\n\t\t\tcleanProjectIdentity(repositoryIdentityFromMetadata(row.metadata_json)),\n\t);\n\tconst repositoryIdentity =\n\t\tmetadataIdentity ?? normalizeIdentity(cleanProjectIdentity(row.git_remote));\n\tif (!repositoryIdentity) return null;\n\treturn { cwd, fromMetadata: metadataIdentity != null, repositoryIdentity };\n}\n\nfunction addRecordedRepositoryIdentity(\n\tidentities: Map<string, Set<string>>,\n\tcwd: string,\n\trepositoryIdentity: string,\n): void {\n\tconst recorded = identities.get(cwd) ?? new Set<string>();\n\trecorded.add(repositoryIdentity);\n\tidentities.set(cwd, recorded);\n}\n\nfunction recordedRepositoryIdentities(\n\trows: Array<{\n\t\tcwd: string;\n\t\tgit_remote?: string | null;\n\t\tmetadata_json?: string | null;\n\t\trepository_identity?: string | null;\n\t}>,\n): {\n\tbyWorkspace: Map<string, Set<string>>;\n\tknown: Set<string>;\n} {\n\tconst metadataByWorkspace = new Map<string, Set<string>>();\n\tconst remoteByWorkspace = new Map<string, Set<string>>();\n\tconst known = new Set<string>();\n\tfor (const row of rows) {\n\t\tconst evidence = recordedRepositoryEvidence(row);\n\t\tif (!evidence) continue;\n\t\taddRecordedRepositoryIdentity(\n\t\t\tevidence.fromMetadata ? metadataByWorkspace : remoteByWorkspace,\n\t\t\tevidence.cwd,\n\t\t\tevidence.repositoryIdentity,\n\t\t);\n\t}\n\tconst byWorkspace = new Map<string, Set<string>>();\n\tfor (const cwd of new Set([...metadataByWorkspace.keys(), ...remoteByWorkspace.keys()])) {\n\t\tconst recorded = new Set([\n\t\t\t...(metadataByWorkspace.get(cwd) ?? []),\n\t\t\t...(remoteByWorkspace.get(cwd) ?? []),\n\t\t]);\n\t\tif (recorded.size === 0) continue;\n\t\tbyWorkspace.set(cwd, recorded);\n\t\tfor (const repositoryIdentity of recorded) known.add(repositoryIdentity);\n\t}\n\treturn { byWorkspace, known };\n}\n\nexport function recordedRepositoryIdentitySetsByWorkspace(db: Database): Map<string, Set<string>> {\n\tconst rows = db\n\t\t.prepare(\n\t\t\t`SELECT DISTINCT cwd, git_remote, metadata_json\n\t\t\t FROM sessions\n\t\t\t WHERE cwd IS NOT NULL AND TRIM(cwd) <> ''\n\t\t\t AND ((json_valid(metadata_json)\n\t\t\t AND json_type(metadata_json, '$.codemem_repository_identity') = 'text')\n\t\t\t OR (git_remote IS NOT NULL AND TRIM(git_remote) <> ''))`,\n\t\t)\n\t\t.all() as Array<{ cwd: string; git_remote: string | null; metadata_json: string | null }>;\n\treturn recordedRepositoryIdentities(rows).byWorkspace;\n}\n\nexport function recordedRepositoryIdentityEvidence(db: Database): {\n\tbyWorkspace: Map<string, string>;\n\tknown: Set<string>;\n\trecordedWorkspaces: Set<string>;\n} {\n\tconst byWorkspaceSets = recordedRepositoryIdentitySetsByWorkspace(db);\n\tconst byWorkspace = new Map<string, string>();\n\tconst recordedWorkspaces = new Set(byWorkspaceSets.keys());\n\tconst known = new Set<string>();\n\trecordedWorkspacesByIdentityMap.set(byWorkspace, recordedWorkspaces);\n\tfor (const [cwd, identities] of byWorkspaceSets) {\n\t\tfor (const identity of identities) known.add(identity);\n\t\tif (identities.size !== 1) continue;\n\t\tconst [repositoryIdentity] = identities;\n\t\tif (repositoryIdentity) byWorkspace.set(cwd, repositoryIdentity);\n\t}\n\treturn {\n\t\tbyWorkspace,\n\t\tknown,\n\t\trecordedWorkspaces,\n\t};\n}\n\nexport function repositoryIdentityMapFromEvidence(\n\trows: Array<{ cwd: string; recordedIdentities: string[]; filesystemIdentity: string | null }>,\n\tknown: ReadonlySet<string>,\n): Map<string, string> {\n\tconst identities = new Map<string, string>();\n\tconst recordedWorkspaces = new Set<string>();\n\trecordedWorkspacesByIdentityMap.set(identities, recordedWorkspaces);\n\tfor (const row of rows) {\n\t\tif (row.recordedIdentities.length > 0) {\n\t\t\trecordedWorkspaces.add(row.cwd);\n\t\t\tif (row.recordedIdentities.length === 1) {\n\t\t\t\tconst identity = row.recordedIdentities[0];\n\t\t\t\tif (identity) identities.set(row.cwd, identity);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (row.filesystemIdentity && known.has(row.filesystemIdentity)) {\n\t\t\tidentities.set(row.cwd, row.filesystemIdentity);\n\t\t}\n\t}\n\treturn identities;\n}\n\nexport function discoverKnownRepositoryIdentity(\n\tcwd: string,\n\tknownRepositoryIdentities: ReadonlySet<string>,\n): string | null {\n\tif (!isAbsolute(cwd)) return null;\n\tconst repositoryIdentity = cachedGitRepositoryIdentity(cwd);\n\treturn repositoryIdentity && knownRepositoryIdentities.has(repositoryIdentity)\n\t\t? repositoryIdentity\n\t\t: null;\n}\n\n/** Recorded evidence shared only for the lifetime of one inventory request. */\nexport interface RepositoryIdentitySnapshot {\n\treadonly recordedByWorkspace: ReadonlyMap<string, ReadonlySet<string>>;\n\treadonly workspaces: readonly { readonly cwd: string }[];\n}\n\nexport function readRepositoryIdentitySnapshot(db: Database): RepositoryIdentitySnapshot {\n\tconst recordedByWorkspace = recordedRepositoryIdentitySetsByWorkspace(db);\n\tconst workspaces = db\n\t\t.prepare(\n\t\t\t`SELECT DISTINCT cwd\n\t\t\t FROM sessions\n\t\t\t WHERE cwd IS NOT NULL AND TRIM(cwd) <> ''\n\t\t\t ORDER BY cwd`,\n\t\t)\n\t\t.all() as Array<{ cwd: string }>;\n\treturn { recordedByWorkspace, workspaces };\n}\n\nexport function repositoryIdentitiesByWorkspace(\n\tdb: Database,\n\toptions: {\n\t\tknownRepositoryIdentities?: Iterable<string | null | undefined>;\n\t\trepositoryIdentitySnapshot?: RepositoryIdentitySnapshot;\n\t} = {},\n): Map<string, string> {\n\tconst snapshot = options.repositoryIdentitySnapshot ?? readRepositoryIdentitySnapshot(db);\n\t// Each consumer may mutate its map or supply different identities for discovery.\n\tconst identities = new Map<string, string>();\n\tconst recordedWorkspaces = new Set<string>();\n\trecordedWorkspacesByIdentityMap.set(identities, recordedWorkspaces);\n\taddUnambiguousRecordedEvidence(identities, recordedWorkspaces, snapshot.recordedByWorkspace);\n\tconst known = new Set<string>();\n\tfor (const recorded of snapshot.recordedByWorkspace.values()) {\n\t\tfor (const identity of recorded) known.add(identity);\n\t}\n\tfor (const identity of options.knownRepositoryIdentities ?? []) {\n\t\tconst normalized = normalizeIdentity(cleanProjectIdentity(identity));\n\t\tif (normalized) known.add(normalized);\n\t}\n\tfor (const row of snapshot.workspaces) {\n\t\tconst cwd = normalizeIdentity(row.cwd);\n\t\tif (!cwd || identities.has(cwd) || recordedWorkspaces.has(cwd)) continue;\n\t\tconst repositoryIdentity = discoverKnownRepositoryIdentity(row.cwd, known);\n\t\tif (repositoryIdentity) identities.set(cwd, repositoryIdentity);\n\t}\n\treturn identities;\n}\n\nexport function canonicalRepositoryProjectIdentity(\n\trepositoryIdentities: ReadonlyMap<string, string>,\n\tvalue: string,\n): string {\n\tconst identity = normalizeIdentity(value);\n\tif (!identity) return value;\n\treturn repositoryIdentities.get(identity) ?? identity;\n}\n\nexport function repositoryIdentityForWorkspace(\n\trepositoryIdentities: ReadonlyMap<string, string>,\n\tinput: {\n\t\tcwd?: string | null;\n\t\tgitRemote: string | null;\n\t\tmetadataJson?: string | null;\n\t\trepositoryIdentity?: string | null;\n\t},\n): string | null {\n\tconst recorded =\n\t\tnormalizeIdentity(cleanProjectIdentity(input.repositoryIdentity)) ??\n\t\tnormalizeIdentity(cleanProjectIdentity(repositoryIdentityFromMetadata(input.metadataJson)));\n\tif (recorded) return recorded;\n\tconst gitRemote = normalizeIdentity(cleanProjectIdentity(input.gitRemote));\n\tif (gitRemote) return gitRemote;\n\tconst cwd = normalizeIdentity(input.cwd);\n\treturn cwd ? (repositoryIdentities.get(cwd) ?? null) : null;\n}\n\nexport function recordedRepositoryIdentitiesByWorkspace(\n\tdb: Database,\n\tworkspaceIdentities: Iterable<string | null | undefined>,\n\toptions: { freshWorkspaces?: Iterable<string | null | undefined> } = {},\n): Map<string, string> {\n\treturn recordedRepositoryIdentityEvidenceByWorkspace(db, workspaceIdentities, options)\n\t\t.byWorkspace;\n}\n\nfunction collectRecordedRepositoryEvidence(\n\trows: Array<{ cwd: string; git_remote: string | null; metadata_json: string | null }>,\n\trequested: ReadonlySet<string>,\n): { known: Set<string>; recordedByWorkspace: Map<string, Set<string>> } {\n\tconst recorded = recordedRepositoryIdentities(rows);\n\treturn {\n\t\tknown: recorded.known,\n\t\trecordedByWorkspace: new Map(\n\t\t\t[...recorded.byWorkspace].filter(([workspace]) => requested.has(workspace)),\n\t\t),\n\t};\n}\n\nfunction addUnambiguousRecordedEvidence(\n\tidentities: Map<string, string>,\n\trecordedWorkspaces: Set<string>,\n\trecordedByWorkspace: ReadonlyMap<string, ReadonlySet<string>>,\n): void {\n\tfor (const [workspaceIdentity, recorded] of recordedByWorkspace) {\n\t\trecordedWorkspaces.add(workspaceIdentity);\n\t\tif (recorded.size !== 1) continue;\n\t\tconst [repositoryIdentity] = recorded;\n\t\tif (repositoryIdentity) identities.set(workspaceIdentity, repositoryIdentity);\n\t}\n}\n\nfunction addDiscoveredRepositoryEvidence(\n\tidentities: Map<string, string>,\n\trecordedWorkspaces: ReadonlySet<string>,\n\tworkspaceIdentities: string[],\n\tknownRepositoryIdentities: ReadonlySet<string>,\n\tfreshWorkspaces: ReadonlySet<string>,\n): void {\n\tfor (const workspaceIdentity of workspaceIdentities) {\n\t\tif (recordedWorkspaces.has(workspaceIdentity) || !isAbsolute(workspaceIdentity)) continue;\n\t\tconst discovered = gitRepositoryIdentity(\n\t\t\tworkspaceIdentity,\n\t\t\tfreshWorkspaces.has(workspaceIdentity),\n\t\t);\n\t\tif (discovered && knownRepositoryIdentities.has(discovered)) {\n\t\t\tidentities.set(workspaceIdentity, discovered);\n\t\t}\n\t}\n}\n\nexport function recordedRepositoryIdentityEvidenceByWorkspace(\n\tdb: Database,\n\tworkspaceIdentities: Iterable<string | null | undefined>,\n\toptions: { freshWorkspaces?: Iterable<string | null | undefined> } = {},\n): {\n\tbyWorkspace: Map<string, string>;\n\trecordedWorkspaces: Set<string>;\n} {\n\tconst identities = new Map<string, string>();\n\tconst recordedWorkspaces = new Set<string>();\n\trecordedWorkspacesByIdentityMap.set(identities, recordedWorkspaces);\n\tconst normalizedWorkspaces = [\n\t\t...new Set(\n\t\t\t[...workspaceIdentities]\n\t\t\t\t.map((identity) => normalizeIdentity(identity))\n\t\t\t\t.filter((identity): identity is string => identity != null),\n\t\t),\n\t];\n\tconst freshWorkspaces = new Set(\n\t\t[...(options.freshWorkspaces ?? [])]\n\t\t\t.map((identity) => normalizeIdentity(identity))\n\t\t\t.filter((identity): identity is string => identity != null),\n\t);\n\tconst requested = new Set(normalizedWorkspaces);\n\tconst rows = db\n\t\t.prepare(\n\t\t\t`SELECT cwd, git_remote, metadata_json FROM sessions\n\t\t\t WHERE cwd IS NOT NULL AND TRIM(cwd) <> '' ORDER BY id DESC`,\n\t\t)\n\t\t.all() as Array<{ cwd: string; git_remote: string | null; metadata_json: string | null }>;\n\tconst evidence = collectRecordedRepositoryEvidence(rows, requested);\n\taddUnambiguousRecordedEvidence(identities, recordedWorkspaces, evidence.recordedByWorkspace);\n\taddDiscoveredRepositoryEvidence(\n\t\tidentities,\n\t\trecordedWorkspaces,\n\t\tnormalizedWorkspaces,\n\t\tevidence.known,\n\t\tfreshWorkspaces,\n\t);\n\treturn { byWorkspace: identities, recordedWorkspaces };\n}\n\nexport function recordedWorkspacesForRepositoryIdentity(\n\tdb: Database,\n\trepositoryIdentity: string,\n): Map<string, string> {\n\tconst normalizedRepositoryIdentity = normalizeIdentity(repositoryIdentity);\n\tif (!normalizedRepositoryIdentity) return new Map();\n\tconst rows = db\n\t\t.prepare(\n\t\t\t`SELECT DISTINCT cwd, git_remote, metadata_json\n\t\t\t FROM sessions\n\t\t\t WHERE cwd IS NOT NULL AND TRIM(cwd) <> ''\n\t\t\t AND (RTRIM(REPLACE(TRIM(git_remote), char(92), '/'), '/') = ?\n\t\t\t OR (json_valid(metadata_json)\n\t\t\t AND json_type(metadata_json, '$.codemem_repository_identity') = 'text'\n\t\t\t AND RTRIM(REPLACE(TRIM(json_extract(metadata_json, '$.codemem_repository_identity')), char(92), '/'), '/') = ?))\n\t\t\t ORDER BY cwd`,\n\t\t)\n\t\t.all(normalizedRepositoryIdentity, normalizedRepositoryIdentity) as Array<{\n\t\tcwd: string;\n\t\tgit_remote: string | null;\n\t\tmetadata_json: string | null;\n\t}>;\n\tconst matchingRows = rows.filter(\n\t\t(row) => recordedRepositoryIdentity(row) === normalizedRepositoryIdentity,\n\t);\n\tconst evidence = recordedRepositoryIdentityEvidenceByWorkspace(\n\t\tdb,\n\t\tmatchingRows.map((row) => row.cwd),\n\t);\n\treturn new Map(\n\t\t[...evidence.byWorkspace].filter(([, identity]) => identity === normalizedRepositoryIdentity),\n\t);\n}\n\nfunction compareMappingPrecedence(left: ScopeMapping, right: ScopeMapping): number {\n\tconst leftUpdatedAt = Date.parse(left.updated_at ?? \"\") || 0;\n\tconst rightUpdatedAt = Date.parse(right.updated_at ?? \"\") || 0;\n\treturn (\n\t\t(right.priority ?? 0) - (left.priority ?? 0) ||\n\t\trightUpdatedAt - leftUpdatedAt ||\n\t\t(right.id ?? 0) - (left.id ?? 0)\n\t);\n}\n\nfunction mappedRepositoryIdentity(\n\tidentity: string,\n\trepositoryIdentities: ReadonlyMap<string, string>,\n\tknownRepositoryIdentities: Set<string>,\n\tdiscoverFilesystem: boolean,\n): string | null {\n\tconst recorded = repositoryIdentities.get(identity);\n\tif (recorded) return recorded;\n\tif (recordedWorkspacesByIdentityMap.get(repositoryIdentities)?.has(identity)) return null;\n\tif (!discoverFilesystem || !isAbsolute(identity)) return null;\n\tconst discovered = cachedGitRepositoryIdentity(identity);\n\treturn discovered && knownRepositoryIdentities.has(discovered) ? discovered : null;\n}\n\nfunction mappingsGroupedByRepository<T extends ScopeMapping>(\n\tmappings: T[],\n\trepositoryIdentities: ReadonlyMap<string, string>,\n\tdiscoverFilesystem: boolean,\n): Map<string, T[]> {\n\tconst grouped = new Map<string, T[]>();\n\tconst knownRepositoryIdentities = new Set(repositoryIdentities.values());\n\tfor (const mapping of mappings) {\n\t\tconst identity = normalizeIdentity(mapping.workspace_identity);\n\t\tif (!identity) continue;\n\t\tconst repositoryIdentity = mappedRepositoryIdentity(\n\t\t\tidentity,\n\t\t\trepositoryIdentities,\n\t\t\tknownRepositoryIdentities,\n\t\t\tdiscoverFilesystem,\n\t\t);\n\t\tif (!repositoryIdentity || repositoryIdentity === identity) continue;\n\t\tconst repositoryMappings = grouped.get(repositoryIdentity) ?? [];\n\t\trepositoryMappings.push(mapping);\n\t\tgrouped.set(repositoryIdentity, repositoryMappings);\n\t}\n\treturn grouped;\n}\n\nexport function withRepositoryMappingAliasesFromIdentities<T extends ScopeMapping>(\n\tmappings: T[],\n\trepositoryIdentities: ReadonlyMap<string, string>,\n\toptions: { discoverFilesystem?: boolean } = {},\n): T[] {\n\tif (mappings.length === 0) return mappings;\n\tconst explicitIdentities = new Set(\n\t\tmappings\n\t\t\t.map((mapping) => normalizeIdentity(mapping.workspace_identity))\n\t\t\t.filter((identity): identity is string => identity != null),\n\t);\n\tconst mappingsByRepository = mappingsGroupedByRepository(\n\t\tmappings,\n\t\trepositoryIdentities,\n\t\toptions.discoverFilesystem === true,\n\t);\n\tconst aliases = new Map<string, T>();\n\tfor (const [repositoryIdentity, repositoryMappings] of mappingsByRepository) {\n\t\tif (explicitIdentities.has(repositoryIdentity)) continue;\n\t\tconst scopeIds = new Set(repositoryMappings.map((mapping) => mapping.scope_id));\n\t\tif (scopeIds.size !== 1) continue;\n\t\tconst mapping = repositoryMappings.toSorted(compareMappingPrecedence)[0];\n\t\tif (mapping) {\n\t\t\tconst alias = { ...mapping, workspace_identity: repositoryIdentity };\n\t\t\tsyntheticRepositoryAliases.add(alias);\n\t\t\taliases.set(repositoryIdentity, alias);\n\t\t}\n\t}\n\treturn [...mappings, ...aliases.values()];\n}\n\nfunction repositoryWorkspacesForMappings(\n\tmappings: ScopeMapping[],\n\trepositoryIdentities: ReadonlyMap<string, string>,\n\trepositoryIdentity: string,\n): Set<string> {\n\tconst workspaces = new Set(\n\t\t[...repositoryIdentities]\n\t\t\t.filter(([, identity]) => identity === repositoryIdentity)\n\t\t\t.map(([workspace]) => workspace),\n\t);\n\tconst knownRepositoryIdentities = new Set(repositoryIdentities.values());\n\tknownRepositoryIdentities.add(repositoryIdentity);\n\tfor (const mapping of mappings) {\n\t\tconst identity = normalizeIdentity(mapping.workspace_identity);\n\t\tif (!identity || identity === repositoryIdentity) continue;\n\t\tif (\n\t\t\tmappedRepositoryIdentity(identity, repositoryIdentities, knownRepositoryIdentities, true) ===\n\t\t\trepositoryIdentity\n\t\t) {\n\t\t\tworkspaces.add(identity);\n\t\t}\n\t}\n\treturn workspaces;\n}\n\nfunction repositoryScopeResolutions(\n\tmappings: ScopeMapping[],\n\trepositoryIdentity: string,\n\tworkspaces: ReadonlySet<string>,\n): { explicitLocalWinner: boolean; scopeIds: Set<string>; mappedScopeIds: Set<string> } {\n\tconst scopeIds = new Set<string>();\n\tconst mappedScopeIds = new Set<string>();\n\tlet explicitLocalWinner = false;\n\tconst candidateWorkspaces = workspaces.size > 0 ? workspaces : [null];\n\tfor (const cwd of candidateWorkspaces) {\n\t\tconst resolution = resolveProjectScope({ repositoryIdentity, cwd, mappings });\n\t\tscopeIds.add(resolution.scopeId);\n\t\tif (resolution.mapping) mappedScopeIds.add(resolution.scopeId);\n\t\tif (resolution.scopeId === LOCAL_DEFAULT_SCOPE_ID && resolution.mapping) {\n\t\t\texplicitLocalWinner = true;\n\t\t}\n\t}\n\treturn { explicitLocalWinner, scopeIds, mappedScopeIds };\n}\n\nexport function mappedScopeIdsForRepository(\n\tmappings: ScopeMapping[],\n\trepositoryIdentities: ReadonlyMap<string, string>,\n\trepositoryIdentity: string,\n): Set<string> {\n\tconst normalized = normalizeIdentity(repositoryIdentity);\n\tif (!normalized) return new Set();\n\tconst effectiveMappings = mappings.filter((mapping) => !syntheticRepositoryAliases.has(mapping));\n\tconst workspaces = repositoryWorkspacesForMappings(\n\t\teffectiveMappings,\n\t\trepositoryIdentities,\n\t\tnormalized,\n\t);\n\treturn repositoryScopeResolutions(effectiveMappings, normalized, workspaces).mappedScopeIds;\n}\n\nexport function hasConflictingRepositoryMappings(\n\tmappings: ScopeMapping[],\n\trepositoryIdentities: ReadonlyMap<string, string>,\n\trepositoryIdentity: string,\n): boolean {\n\tconst normalizedRepositoryIdentity = normalizeIdentity(repositoryIdentity);\n\tif (!normalizedRepositoryIdentity) return false;\n\tconst effectiveMappings = mappings.filter((mapping) => !syntheticRepositoryAliases.has(mapping));\n\tconst repositoryWorkspaces = repositoryWorkspacesForMappings(\n\t\teffectiveMappings,\n\t\trepositoryIdentities,\n\t\tnormalizedRepositoryIdentity,\n\t);\n\tconst { explicitLocalWinner, scopeIds } = repositoryScopeResolutions(\n\t\teffectiveMappings,\n\t\tnormalizedRepositoryIdentity,\n\t\trepositoryWorkspaces,\n\t);\n\tif (scopeIds.size <= 1) return false;\n\tif (explicitLocalWinner) return true;\n\tconst sharedScopes = new Set(\n\t\t[...scopeIds].filter((scopeId) => scopeId !== LOCAL_DEFAULT_SCOPE_ID),\n\t);\n\tif (sharedScopes.size !== 1 || !scopeIds.has(LOCAL_DEFAULT_SCOPE_ID)) return true;\n\tconst mappingsWithAliases = withRepositoryMappingAliasesFromIdentities(\n\t\teffectiveMappings,\n\t\trepositoryIdentities,\n\t\t{ discoverFilesystem: true },\n\t);\n\tconst fallback = resolveProjectScope({\n\t\trepositoryIdentity: normalizedRepositoryIdentity,\n\t\tmappings: mappingsWithAliases,\n\t\tallowRepositoryCwdFallback: false,\n\t});\n\treturn !fallback.mapping || !sharedScopes.has(fallback.scopeId);\n}\n\n/**\n * Treat an existing checkout-path mapping as a repository mapping after that\n * checkout gains trusted repository identity. This preserves pre-upgrade Space\n * assignments while making sibling worktrees inherit the same decision.\n */\nexport function withRepositoryMappingAliases<T extends ScopeMapping>(\n\tdb: Database,\n\tmappings: T[],\n\toptions: { repositoryIdentitySnapshot?: RepositoryIdentitySnapshot } = {},\n): T[] {\n\tif (mappings.length === 0) return mappings;\n\tconst repositoryIdentities = repositoryIdentitiesByWorkspace(db, options);\n\treturn withRepositoryMappingAliasesFromIdentities(mappings, repositoryIdentities, {\n\t\tdiscoverFilesystem: true,\n\t});\n}\n","import { isStrictRecipientPolicyId } from \"./recipient-policy-identifiers.js\";\n\nexport const POLICY_TEAM_DEVICE_ELIGIBILITY_MODES = [\n\t\"person_all_devices\",\n\t\"reviewed_allowlist\",\n] as const;\n\nexport type PolicyTeamDeviceEligibilityMode = (typeof POLICY_TEAM_DEVICE_ELIGIBILITY_MODES)[number];\n\nexport const POLICY_TEAM_DEVICE_DECISIONS = [\"included\", \"excluded\", \"unresolved\"] as const;\n\nexport type PolicyTeamDeviceDecision = (typeof POLICY_TEAM_DEVICE_DECISIONS)[number];\n\nexport type PolicyTeamDeviceEligibilityBlockCode =\n\t| \"team_device_eligibility_mode_invalid\"\n\t| \"team_device_decision_invalid\"\n\t| \"team_membership_invalid\"\n\t| \"team_membership_mode_invalid\"\n\t| \"team_member_identity_missing\"\n\t| \"team_member_identity_not_active\"\n\t| \"team_member_identity_merged\"\n\t| \"identity_device_invalid\";\n\nexport interface PolicyTeamDeviceEligibilityIdentity {\n\tidentityId: string;\n\tstatus: string;\n\tmergedIntoIdentityId: string | null;\n}\n\nexport interface PolicyTeamDeviceEligibilityMembership {\n\tidentityId: string;\n\tstatus: string;\n}\n\nexport interface PolicyTeamDeviceEligibilityDevice {\n\tidentityId: string;\n\tdeviceId: string;\n\tstatus: string;\n\tassignmentVersion: number;\n}\n\nexport interface PolicyTeamDeviceEligibilityDecision {\n\tdeviceId: string;\n\tdecision: string;\n\tassignmentVersion: number;\n}\n\nexport interface DerivePolicyTeamDeviceEligibilityInput {\n\tteamId: string;\n\tmode: string;\n\tmemberships: PolicyTeamDeviceEligibilityMembership[];\n\tidentities: PolicyTeamDeviceEligibilityIdentity[];\n\tdevices: PolicyTeamDeviceEligibilityDevice[];\n\tdecisions: PolicyTeamDeviceEligibilityDecision[];\n}\n\nexport interface PolicyTeamDeviceEligibilityBlock {\n\tcode: PolicyTeamDeviceEligibilityBlockCode;\n\treferenceId: string;\n}\n\nexport interface EligiblePolicyTeamDeviceEligibilityResult {\n\tstatus: \"eligible\";\n\tactiveMemberIdentityIds: string[];\n\teligibleDeviceIds: string[];\n\tblocked: [];\n}\n\nexport interface BlockedPolicyTeamDeviceEligibilityResult {\n\tstatus: \"blocked\";\n\tblocked: [PolicyTeamDeviceEligibilityBlock, ...PolicyTeamDeviceEligibilityBlock[]];\n}\n\nexport type PolicyTeamDeviceEligibilityResult =\n\t| EligiblePolicyTeamDeviceEligibilityResult\n\t| BlockedPolicyTeamDeviceEligibilityResult;\n\nconst MODES = new Set<string>(POLICY_TEAM_DEVICE_ELIGIBILITY_MODES);\nconst DECISIONS = new Set<string>(POLICY_TEAM_DEVICE_DECISIONS);\nconst DEVICE_STATUSES = new Set([\"active\", \"revoked\"]);\nconst INACTIVE_MEMBERSHIP_STATUSES = new Set([\"pending\", \"revoked\"]);\n// Surface authority-shape and principal-integrity failures before mutable\n// decision/device facts so callers expose the most security-relevant cause.\nconst BLOCK_PRECEDENCE: Record<PolicyTeamDeviceEligibilityBlockCode, number> = {\n\tteam_device_eligibility_mode_invalid: 0,\n\tteam_membership_invalid: 1,\n\tteam_membership_mode_invalid: 2,\n\tteam_member_identity_missing: 3,\n\tteam_member_identity_merged: 4,\n\tteam_member_identity_not_active: 5,\n\tteam_device_decision_invalid: 6,\n\tidentity_device_invalid: 7,\n};\n\nfunction compareText(left: string, right: string): number {\n\treturn left < right ? -1 : left > right ? 1 : 0;\n}\n\nexport function isPolicyTeamMembershipActiveForMode(mode: string, status: string): boolean {\n\treturn (\n\t\t(mode === \"person_all_devices\" && status === \"active\") ||\n\t\t(mode === \"reviewed_allowlist\" && status === \"reviewed_active\")\n\t);\n}\n\nfunction sortedBlocks(\n\tblocked: Iterable<PolicyTeamDeviceEligibilityBlock>,\n): PolicyTeamDeviceEligibilityBlock[] {\n\treturn [...blocked].toSorted(\n\t\t(left, right) =>\n\t\t\tBLOCK_PRECEDENCE[left.code] - BLOCK_PRECEDENCE[right.code] ||\n\t\t\tcompareText(left.referenceId, right.referenceId),\n\t);\n}\n\nfunction blockedResult(\n\tblocked: Iterable<PolicyTeamDeviceEligibilityBlock>,\n): BlockedPolicyTeamDeviceEligibilityResult {\n\tconst [first, ...rest] = sortedBlocks(blocked);\n\tif (!first) throw new Error(\"policy_team_device_eligibility_block_missing\");\n\treturn { status: \"blocked\", blocked: [first, ...rest] };\n}\n\nfunction collectDeviceDecisions(\n\tinput: Pick<DerivePolicyTeamDeviceEligibilityInput, \"teamId\" | \"mode\" | \"decisions\">,\n\taddBlock: (code: PolicyTeamDeviceEligibilityBlockCode, referenceId: string) => void,\n): Map<string, PolicyTeamDeviceEligibilityDecision> {\n\tconst decisions = new Map<string, PolicyTeamDeviceEligibilityDecision>();\n\tfor (const decision of input.decisions) {\n\t\tif (\n\t\t\t!isStrictRecipientPolicyId(decision.deviceId) ||\n\t\t\t!DECISIONS.has(decision.decision) ||\n\t\t\t!Number.isSafeInteger(decision.assignmentVersion) ||\n\t\t\tdecision.assignmentVersion < 0 ||\n\t\t\tdecisions.has(decision.deviceId) ||\n\t\t\t(input.mode === \"person_all_devices\" && decision.decision !== \"excluded\")\n\t\t) {\n\t\t\taddBlock(\"team_device_decision_invalid\", `${input.teamId}:${decision.deviceId}`);\n\t\t\tcontinue;\n\t\t}\n\t\tdecisions.set(decision.deviceId, decision);\n\t}\n\treturn decisions;\n}\n\nexport function derivePolicyTeamDeviceEligibility(\n\tinput: DerivePolicyTeamDeviceEligibilityInput,\n): PolicyTeamDeviceEligibilityResult {\n\tconst blocked = new Map<string, PolicyTeamDeviceEligibilityBlock>();\n\tconst addBlock = (code: PolicyTeamDeviceEligibilityBlockCode, referenceId: string): void => {\n\t\tblocked.set(`${code}\\u0000${referenceId}`, { code, referenceId });\n\t};\n\tif (!MODES.has(input.mode)) {\n\t\treturn blockedResult([\n\t\t\t{ code: \"team_device_eligibility_mode_invalid\", referenceId: input.teamId },\n\t\t]);\n\t}\n\tconst mode = input.mode as PolicyTeamDeviceEligibilityMode;\n\tconst activeMembers = new Set<string>();\n\tfor (const membership of input.memberships) {\n\t\tif (!isStrictRecipientPolicyId(membership.identityId)) {\n\t\t\taddBlock(\"team_membership_invalid\", `${input.teamId}:${membership.identityId}`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (isPolicyTeamMembershipActiveForMode(mode, membership.status)) {\n\t\t\tactiveMembers.add(membership.identityId);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!INACTIVE_MEMBERSHIP_STATUSES.has(membership.status)) {\n\t\t\taddBlock(\"team_membership_mode_invalid\", `${input.teamId}:${membership.identityId}`);\n\t\t}\n\t}\n\tconst identities = new Map(input.identities.map((identity) => [identity.identityId, identity]));\n\tfor (const identityId of activeMembers) {\n\t\tconst identity = identities.get(identityId);\n\t\tif (!identity) {\n\t\t\taddBlock(\"team_member_identity_missing\", identityId);\n\t\t\tcontinue;\n\t\t}\n\t\tif (identity.status === \"merged\" || identity.mergedIntoIdentityId) {\n\t\t\taddBlock(\"team_member_identity_merged\", identityId);\n\t\t\tcontinue;\n\t\t}\n\t\tif (identity.status !== \"active\") {\n\t\t\taddBlock(\"team_member_identity_not_active\", identityId);\n\t\t}\n\t}\n\tconst decisions = collectDeviceDecisions(input, addBlock);\n\tconst eligibleDeviceIds = new Set<string>();\n\tfor (const device of input.devices) {\n\t\tif (!activeMembers.has(device.identityId)) continue;\n\t\tif (!DEVICE_STATUSES.has(device.status)) {\n\t\t\taddBlock(\"identity_device_invalid\", device.deviceId);\n\t\t\tcontinue;\n\t\t}\n\t\tif (device.status !== \"active\") continue;\n\t\tif (\n\t\t\t!isStrictRecipientPolicyId(device.identityId) ||\n\t\t\t!isStrictRecipientPolicyId(device.deviceId) ||\n\t\t\t!Number.isSafeInteger(device.assignmentVersion) ||\n\t\t\tdevice.assignmentVersion < 0\n\t\t) {\n\t\t\taddBlock(\"identity_device_invalid\", device.deviceId);\n\t\t\tcontinue;\n\t\t}\n\t\tconst decision = decisions.get(device.deviceId);\n\t\t// A Team exclusion persists for this device ID when assignment metadata changes.\n\t\tif (mode === \"person_all_devices\" && decision?.decision === \"excluded\") continue;\n\t\tif (\n\t\t\tmode === \"person_all_devices\" ||\n\t\t\t(decision?.decision === \"included\" && decision.assignmentVersion === device.assignmentVersion)\n\t\t) {\n\t\t\teligibleDeviceIds.add(device.deviceId);\n\t\t}\n\t}\n\tif (blocked.size > 0) return blockedResult(blocked.values());\n\treturn {\n\t\tstatus: \"eligible\",\n\t\tactiveMemberIdentityIds: [...activeMembers].toSorted(compareText),\n\t\teligibleDeviceIds: [...eligibleDeviceIds].toSorted(compareText),\n\t\tblocked: [],\n\t};\n}\n","/**\n * Synthetic placeholder cwd used for sessions created during sync bootstrap.\n * Keep this in a dependency-free module so policy code can use it without\n * pulling the Node-only bootstrap runtime into Cloudflare Worker bundles.\n */\nexport const SYNC_BOOTSTRAP_CWD_PREFIX = \"__sync_bootstrap__\";\n","import type { Database } from \"./db.js\";\n\nexport type MaintenanceJobStatus = \"pending\" | \"running\" | \"completed\" | \"failed\" | \"cancelled\";\n\nexport interface MaintenanceJobRecord {\n\tkind: string;\n\ttitle: string;\n\tstatus: MaintenanceJobStatus;\n\tmessage: string | null;\n\tprogress_current: number;\n\tprogress_total: number | null;\n\tprogress_unit: string;\n\tmetadata_json: string | null;\n\tstarted_at: string | null;\n\tupdated_at: string;\n\tfinished_at: string | null;\n\terror: string | null;\n}\n\nexport interface MaintenanceJobSnapshot {\n\tkind: string;\n\ttitle: string;\n\tstatus: MaintenanceJobStatus;\n\tmessage: string | null;\n\tprogress: {\n\t\tcurrent: number;\n\t\ttotal: number | null;\n\t\tunit: string;\n\t};\n\tmetadata: Record<string, unknown> | null;\n\tstarted_at: string | null;\n\tupdated_at: string;\n\tfinished_at: string | null;\n\terror: string | null;\n}\n\nexport interface StartMaintenanceJobInput {\n\tkind: string;\n\ttitle: string;\n\tmessage?: string | null;\n\tprogressTotal?: number | null;\n\tprogressUnit?: string;\n\tmetadata?: Record<string, unknown> | null;\n\tstatus?: \"pending\" | \"running\";\n}\n\nexport interface UpdateMaintenanceJobInput {\n\tmessage?: string | null;\n\tprogressCurrent?: number;\n\tprogressTotal?: number | null;\n\tprogressUnit?: string;\n\tmetadata?: Record<string, unknown> | null;\n\tstatus?: MaintenanceJobStatus;\n}\n\nfunction ensureTable(db: Database): void {\n\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS maintenance_jobs (\n\t\t\tkind TEXT PRIMARY KEY,\n\t\t\ttitle TEXT NOT NULL,\n\t\t\tstatus TEXT NOT NULL,\n\t\t\tmessage TEXT,\n\t\t\tprogress_current INTEGER NOT NULL DEFAULT 0,\n\t\t\tprogress_total INTEGER,\n\t\t\tprogress_unit TEXT NOT NULL DEFAULT 'items',\n\t\t\tmetadata_json TEXT,\n\t\t\tstarted_at TEXT,\n\t\t\tupdated_at TEXT NOT NULL,\n\t\t\tfinished_at TEXT,\n\t\t\terror TEXT\n\t\t);\n\t\tCREATE INDEX IF NOT EXISTS idx_maintenance_jobs_status_updated\n\t\t\tON maintenance_jobs(status, updated_at);\n\t`);\n}\n\nfunction parseMetadata(value: string | null): Record<string, unknown> | null {\n\tif (!value) return null;\n\ttry {\n\t\tconst parsed = JSON.parse(value) as unknown;\n\t\tif (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n\t\t\treturn parsed as Record<string, unknown>;\n\t\t}\n\t} catch {\n\t\treturn null;\n\t}\n\treturn null;\n}\n\nfunction isTerminalStatus(status: MaintenanceJobStatus): boolean {\n\treturn status === \"completed\" || status === \"failed\" || status === \"cancelled\";\n}\n\nfunction resolveMessage(\n\tinput: UpdateMaintenanceJobInput,\n\texisting: MaintenanceJobSnapshot,\n): string | null {\n\tif (Object.hasOwn(input, \"message\")) {\n\t\treturn input.message ?? null;\n\t}\n\treturn existing.message;\n}\n\nfunction resolveMetadataJson(\n\tinput: UpdateMaintenanceJobInput,\n\texisting: MaintenanceJobSnapshot,\n): string | null {\n\tif (Object.hasOwn(input, \"metadata\")) {\n\t\treturn input.metadata ? JSON.stringify(input.metadata) : null;\n\t}\n\treturn existing.metadata ? JSON.stringify(existing.metadata) : null;\n}\n\nfunction toSnapshot(row: MaintenanceJobRecord | undefined): MaintenanceJobSnapshot | null {\n\tif (!row) return null;\n\tconst progressCurrent =\n\t\trow.status === \"completed\" && row.progress_total != null\n\t\t\t? row.progress_total\n\t\t\t: row.progress_current;\n\treturn {\n\t\tkind: row.kind,\n\t\ttitle: row.title,\n\t\tstatus: row.status,\n\t\tmessage: row.message,\n\t\tprogress: {\n\t\t\tcurrent: progressCurrent,\n\t\t\ttotal: row.progress_total,\n\t\t\tunit: row.progress_unit,\n\t\t},\n\t\tmetadata: parseMetadata(row.metadata_json),\n\t\tstarted_at: row.started_at,\n\t\tupdated_at: row.updated_at,\n\t\tfinished_at: row.finished_at,\n\t\terror: row.error,\n\t};\n}\n\nexport function getMaintenanceJob(db: Database, kind: string): MaintenanceJobSnapshot | null {\n\tensureTable(db);\n\tconst row = db.prepare(\"SELECT * FROM maintenance_jobs WHERE kind = ?\").get(kind) as\n\t\t| MaintenanceJobRecord\n\t\t| undefined;\n\treturn toSnapshot(row);\n}\n\nexport function listMaintenanceJobs(db: Database): MaintenanceJobSnapshot[] {\n\tensureTable(db);\n\tconst rows = db\n\t\t.prepare(\"SELECT * FROM maintenance_jobs ORDER BY updated_at DESC, kind ASC\")\n\t\t.all() as MaintenanceJobRecord[];\n\treturn rows\n\t\t.map((row) => toSnapshot(row))\n\t\t.filter((row): row is MaintenanceJobSnapshot => row != null);\n}\n\nexport function startMaintenanceJob(\n\tdb: Database,\n\tinput: StartMaintenanceJobInput,\n): MaintenanceJobSnapshot {\n\tensureTable(db);\n\tconst now = new Date().toISOString();\n\tconst status = input.status ?? \"running\";\n\tconst metadataJson = input.metadata ? JSON.stringify(input.metadata) : null;\n\tdb.prepare(\n\t\t`INSERT INTO maintenance_jobs(\n\t\t\tkind, title, status, message, progress_current, progress_total,\n\t\t\tprogress_unit, metadata_json, started_at, updated_at, finished_at, error\n\t\t) VALUES (?, ?, ?, ?, 0, ?, ?, ?, ?, ?, NULL, NULL)\n\t\tON CONFLICT(kind) DO UPDATE SET\n\t\t\ttitle = excluded.title,\n\t\t\tstatus = excluded.status,\n\t\t\tmessage = excluded.message,\n\t\t\tprogress_current = 0,\n\t\t\tprogress_total = excluded.progress_total,\n\t\t\tprogress_unit = excluded.progress_unit,\n\t\t\tmetadata_json = excluded.metadata_json,\n\t\t\tstarted_at = excluded.started_at,\n\t\t\tupdated_at = excluded.updated_at,\n\t\t\tfinished_at = NULL,\n\t\t\terror = NULL`,\n\t).run(\n\t\tinput.kind,\n\t\tinput.title,\n\t\tstatus,\n\t\tinput.message ?? null,\n\t\tinput.progressTotal ?? null,\n\t\tinput.progressUnit ?? \"items\",\n\t\tmetadataJson,\n\t\tnow,\n\t\tnow,\n\t);\n\tconst job = getMaintenanceJob(db, input.kind);\n\tif (!job) {\n\t\tthrow new Error(`Failed to start maintenance job: ${input.kind}`);\n\t}\n\treturn job;\n}\n\nexport function updateMaintenanceJob(\n\tdb: Database,\n\tkind: string,\n\tinput: UpdateMaintenanceJobInput,\n): MaintenanceJobSnapshot | null {\n\tensureTable(db);\n\tconst existing = getMaintenanceJob(db, kind);\n\tif (!existing) return null;\n\tconst now = new Date().toISOString();\n\tconst nextStatus = input.status ?? existing.status;\n\tconst transitioningToTerminal =\n\t\t!isTerminalStatus(existing.status) && isTerminalStatus(nextStatus);\n\tconst transitioningToRunning = isTerminalStatus(existing.status) && !isTerminalStatus(nextStatus);\n\tconst finishedAt = transitioningToTerminal\n\t\t? now\n\t\t: transitioningToRunning\n\t\t\t? null\n\t\t\t: existing.finished_at;\n\tconst error =\n\t\tnextStatus === \"failed\"\n\t\t\t? existing.error\n\t\t\t: nextStatus === \"completed\" || nextStatus === \"cancelled\" || transitioningToRunning\n\t\t\t\t? null\n\t\t\t\t: existing.error;\n\tdb.prepare(\n\t\t`UPDATE maintenance_jobs\n\t\t SET status = ?,\n\t\t message = ?,\n\t\t progress_current = ?,\n\t\t progress_total = ?,\n\t\t progress_unit = ?,\n\t\t metadata_json = ?,\n\t\t updated_at = ?,\n\t\t finished_at = ?,\n\t\t error = ?\n\t\t WHERE kind = ?`,\n\t).run(\n\t\tnextStatus,\n\t\tresolveMessage(input, existing),\n\t\tinput.progressCurrent ?? existing.progress.current,\n\t\tinput.progressTotal === undefined ? existing.progress.total : input.progressTotal,\n\t\tinput.progressUnit ?? existing.progress.unit,\n\t\tresolveMetadataJson(input, existing),\n\t\tnow,\n\t\tfinishedAt,\n\t\terror,\n\t\tkind,\n\t);\n\treturn getMaintenanceJob(db, kind);\n}\n\nexport function completeMaintenanceJob(\n\tdb: Database,\n\tkind: string,\n\tinput: Omit<UpdateMaintenanceJobInput, \"status\"> = {},\n): MaintenanceJobSnapshot | null {\n\treturn updateMaintenanceJob(db, kind, { ...input, status: \"completed\" });\n}\n\nexport function failMaintenanceJob(\n\tdb: Database,\n\tkind: string,\n\terror: string,\n\tinput: Omit<UpdateMaintenanceJobInput, \"status\"> = {},\n): MaintenanceJobSnapshot | null {\n\tensureTable(db);\n\tconst existing = getMaintenanceJob(db, kind);\n\tif (!existing) return null;\n\tconst now = new Date().toISOString();\n\tdb.prepare(\n\t\t`UPDATE maintenance_jobs\n\t\t SET status = 'failed',\n\t\t message = ?,\n\t\t progress_current = ?,\n\t\t\t progress_total = ?,\n\t\t\t progress_unit = ?,\n\t\t\t metadata_json = ?,\n\t\t\t updated_at = ?,\n\t\t\t finished_at = ?,\n\t\t\t error = ?\n\t\t WHERE kind = ?`,\n\t).run(\n\t\tresolveMessage(input, existing),\n\t\tinput.progressCurrent ?? existing.progress.current,\n\t\tinput.progressTotal === undefined ? existing.progress.total : input.progressTotal,\n\t\tinput.progressUnit ?? existing.progress.unit,\n\t\tresolveMetadataJson(input, existing),\n\t\tnow,\n\t\tnow,\n\t\terror,\n\t\tkind,\n\t);\n\treturn getMaintenanceJob(db, kind);\n}\n\nexport function ensureMaintenanceJobsSchema(db: Database): void {\n\tensureTable(db);\n}\n\n/**\n * A backfill write that loses the lock to another writer is not a job\n * failure: runners should skip the tick and retry instead of parking the job\n * as failed until the next process restart.\n */\nexport function isTransientSqliteBusy(error: unknown): boolean {\n\tconst code =\n\t\ttypeof error === \"object\" && error != null\n\t\t\t? String((error as { code?: unknown }).code ?? \"\")\n\t\t\t: \"\";\n\t// Extended codes such as SQLITE_BUSY_SNAPSHOT and SQLITE_LOCKED_SHAREDCACHE are the same condition.\n\tif (code.startsWith(\"SQLITE_BUSY\") || code.startsWith(\"SQLITE_LOCKED\")) return true;\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn /database (?:table )?is (?:locked|busy)/i.test(message);\n}\n","import { createHash } from \"node:crypto\";\nimport type { Database } from \"./db.js\";\n\nfunction nonblankString(value: unknown): string | null {\n\tif (typeof value !== \"string\") return null;\n\treturn value.trim() ? value : null;\n}\n\nfunction hashIdentity(value: string | readonly [string, string]): string {\n\treturn createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\");\n}\n\nexport function isCanonicalSessionKey(value: string | null): value is string {\n\treturn value != null && /^export-session:v1:[a-f0-9]{64}(?::remap:[a-f0-9]{64})?$/.test(value);\n}\n\nfunction firstNonblankMemoryKey(db: Database, sessionId: number): string | null {\n\t// Use all history, independent of mutable labels or the caller's readable subset.\n\tconst candidates = db\n\t\t.prepare(`SELECT import_key FROM memory_items\n\t\t\tWHERE session_id = ? AND import_key IS NOT NULL\n\t\t\tORDER BY id ASC`)\n\t\t.iterate(sessionId) as IterableIterator<Record<string, unknown>>;\n\tfor (const candidate of candidates) {\n\t\tconst key = nonblankString(candidate.import_key);\n\t\tif (key) return key;\n\t}\n\treturn null;\n}\n\n/** Resolve export bookkeeping identity without changing source rows or enrollment state. */\nexport function exportedSessionKey(db: Database, row: Record<string, unknown>): string {\n\tconst sourceKey = nonblankString(row.import_key);\n\tif (isCanonicalSessionKey(sourceKey)) return sourceKey;\n\tif (sourceKey) return `export-session:v1:${hashIdentity([\"import_key\", sourceKey])}`;\n\n\tconst memoryKey = firstNonblankMemoryKey(db, Number(row.id));\n\tif (!memoryKey)\n\t\tthrow new Error(\"session_identity_unavailable: session has no immutable source key\");\n\treturn `export-session:v1:${hashIdentity([\"memory_key\", memoryKey])}`;\n}\n\n/** Apply a project namespace to a validated canonical key, replacing any prior remap. */\nexport function remappedSessionKey(marker: string, remapProject: string): string {\n\tconst baseKey = marker.replace(/:remap:[a-f0-9]{64}$/, \"\");\n\treturn `${baseKey}:remap:${hashIdentity(remapProject)}`;\n}\n","import type { Statement } from \"better-sqlite3\";\nimport type { Database } from \"./db.js\";\nimport { exportedSessionKey } from \"./session-export-identity.js\";\n\nfunction hasHistoricalMemoryAnchor(statement: Statement, sessionId: number): boolean {\n\tconst candidates = statement.iterate(sessionId) as IterableIterator<Record<string, unknown>>;\n\tfor (const candidate of candidates) {\n\t\tif (typeof candidate.import_key === \"string\" && candidate.import_key.trim()) return true;\n\t}\n\treturn false;\n}\n\n/** Preserve bookkeeping identity before changing memory anchors, never grant access. */\nexport function snapshotSessionExportKeysForMemoryIds(\n\tdb: Database,\n\tmemoryIds: readonly number[],\n): void {\n\tif (!db.inTransaction) throw new Error(\"session_export_identity_transaction_required\");\n\t// One JSON parameter carries numeric IDs without SQLite's variable limit.\n\t// Resolve only the supplied memory primary keys, then deduplicate actual sessions\n\t// before any per-session anchor reads while the caller holds its transaction.\n\tconst sessions = db\n\t\t.prepare(`SELECT DISTINCT s.id, s.import_key FROM memory_items m\n\t\t\tJOIN sessions s ON s.id = m.session_id\n\t\t\tWHERE m.id IN (SELECT value FROM json_each(?))`)\n\t\t.all(JSON.stringify(memoryIds)) as { id: number; import_key: string | null }[];\n\tconst findAnchor = db.prepare(`SELECT import_key FROM memory_items\n\t\tWHERE session_id = ? AND import_key IS NOT NULL ORDER BY id ASC`);\n\t// Match the original key (including NULL or whitespace), never replace a new key.\n\tconst saveKey = db.prepare(\"UPDATE sessions SET import_key = ? WHERE id = ? AND import_key IS ?\");\n\tfor (const session of sessions) {\n\t\tif (session.import_key?.trim()) continue;\n\t\t// No prior helper identity exists without an anchor; cleanup must still proceed.\n\t\tif (!hasHistoricalMemoryAnchor(findAnchor, session.id)) continue;\n\t\tsaveKey.run(exportedSessionKey(db, session), session.id, session.import_key);\n\t}\n}\n","/**\n * Shared helpers for populating the `memory_file_refs` and\n * `memory_concept_refs` junction tables from the denormalized JSON arrays\n * stored on `memory_items` rows.\n *\n * Used at write time in `MemoryStore.remember()`, during replication apply,\n * and by the ref-backfill maintenance job.\n */\n\nimport type { Database as SqliteDatabase } from \"better-sqlite3\";\n\n/**\n * Normalize a concept string for storage/lookup: trim whitespace and\n * lowercase. Shared across write, backfill, and query paths so the\n * normalization rule lives in exactly one place.\n */\nexport function normalizeConcept(concept: string): string {\n\treturn concept.trim().toLowerCase();\n}\n\n/**\n * Delete all existing ref rows for a memory. Used before re-populating on\n * updates where the files/concepts may have changed.\n */\nexport function clearMemoryRefs(db: SqliteDatabase, memoryId: number): void {\n\tdb.prepare(\"DELETE FROM memory_file_refs WHERE memory_id = ?\").run(memoryId);\n\tdb.prepare(\"DELETE FROM memory_concept_refs WHERE memory_id = ?\").run(memoryId);\n}\n\n/**\n * Populate `memory_file_refs` and `memory_concept_refs` junction-table rows\n * for a single memory item. Uses `INSERT OR IGNORE` so calling this on an\n * already-populated memory is a safe no-op.\n *\n * Callers are responsible for running this inside a transaction when\n * atomicity with the parent insert/update is required.\n */\nexport function populateMemoryRefs(\n\tdb: SqliteDatabase,\n\tmemoryId: number,\n\tfilesRead: string[] | null,\n\tfilesModified: string[] | null,\n\tconcepts: string[] | null,\n): void {\n\tconst insertFileRef = db.prepare(\n\t\t\"INSERT OR IGNORE INTO memory_file_refs (memory_id, file_path, relation) VALUES (?, ?, ?)\",\n\t);\n\tif (filesRead) {\n\t\tfor (const path of filesRead) {\n\t\t\tif (typeof path !== \"string\" || !path) continue;\n\t\t\tinsertFileRef.run(memoryId, path, \"read\");\n\t\t}\n\t}\n\tif (filesModified) {\n\t\tfor (const path of filesModified) {\n\t\t\tif (typeof path !== \"string\" || !path) continue;\n\t\t\tinsertFileRef.run(memoryId, path, \"modified\");\n\t\t}\n\t}\n\tconst insertConceptRef = db.prepare(\n\t\t\"INSERT OR IGNORE INTO memory_concept_refs (memory_id, concept) VALUES (?, ?)\",\n\t);\n\tif (concepts) {\n\t\tfor (const concept of concepts) {\n\t\t\tif (typeof concept !== \"string\") continue;\n\t\t\tconst normalized = normalizeConcept(concept);\n\t\t\tif (normalized) insertConceptRef.run(memoryId, normalized);\n\t\t}\n\t}\n}\n","import type { Database } from \"./db.js\";\nimport { resolveVectorLayout } from \"./vector-layout.js\";\n\nexport type VectorMetadataFilter = { memoryIds?: readonly number[]; model?: string };\n\nexport type VectorMetadataRow = {\n\trowid: bigint;\n\tmemory_id: bigint | null;\n\tmodel: string | null;\n\tcontent_hash: string | null;\n};\n\n/**\n * Whether vector metadata can be read from the indexed `validated_vector_rows`\n * table instead of scanning vec0.\n *\n * In the v1 layout that table holds exactly one row per vec0 row, with the\n * same rowid, memory_id, model, chunk_index, and content_hash:\n * - The upgrade copies legacy vectors and runs the census that fills the table\n * from the copy in one transaction (`upgradeWithinTransaction`).\n * - Every later census (`startAudit`) deletes and refills the table from vec0\n * in one transaction.\n * - The only vec0 insert path (`insertRow`) writes both tables, and the\n * `memory_vectors` view rejects inserts and updates.\n * - Deletes through the view remove both rows and abort if the indexed row is\n * missing. `removeRow` deletes both rows directly.\n * - Audits change only `audit_state` and `reason`, which callers never read.\n *\n * Legacy layouts can invalidate the index and write vec0 without it, so they\n * keep reading vec0. A layout that fails validation also keeps the vec0 read,\n * which is what every caller did before.\n *\n * As a cheap check against writes outside these paths (for example a manual\n * delete from memory_vectors_v1), the row counts must also match vec0's rowid\n * table. Both counts read b-tree pages only.\n */\nexport function hasIndexedVectorMetadata(db: Database): boolean {\n\tlet layout: ReturnType<typeof resolveVectorLayout>;\n\ttry {\n\t\tlayout = resolveVectorLayout(db);\n\t} catch {\n\t\treturn false;\n\t}\n\tif (layout.kind !== \"v1\") return false;\n\tconst count = (table: string) =>\n\t\tNumber(db.prepare(`SELECT COUNT(*) FROM ${table}`).pluck().get());\n\treturn count(\"validated_vector_rows\") === count(layout.rowidsName);\n}\n\n/**\n * Walk the distinct models with one index seek each. The only index on\n * `validated_vector_rows` that contains memory_id leads with model, so a\n * memory-only filter must be expanded into (model, memory_id) lookups.\n */\nfunction indexedModels(db: Database): Array<string | null> {\n\tconst models = db\n\t\t.prepare(\n\t\t\t`WITH RECURSIVE models(model) AS (\n\t\t\t\tSELECT (SELECT MIN(model) FROM validated_vector_rows)\n\t\t\t\tUNION ALL\n\t\t\t\tSELECT (SELECT MIN(model) FROM validated_vector_rows WHERE model > models.model)\n\t\t\t\tFROM models WHERE models.model IS NOT NULL\n\t\t\t)\n\t\t\tSELECT model FROM models WHERE model IS NOT NULL`,\n\t\t)\n\t\t.pluck()\n\t\t.all() as string[];\n\tconst hasNullModel = db\n\t\t.prepare(\"SELECT 1 FROM validated_vector_rows WHERE model IS NULL LIMIT 1\")\n\t\t.get();\n\treturn hasNullModel ? [null, ...models] : models;\n}\n\nfunction* readIndexedRows(\n\tdb: Database,\n\t{ memoryIds, model }: VectorMetadataFilter,\n\tmarker: string,\n): Generator<VectorMetadataRow> {\n\tconst columns = \"rowid, memory_id, model, content_hash\";\n\tif (memoryIds === undefined) {\n\t\tconst where = model === undefined ? \"\" : \"WHERE model = ?\";\n\t\tconst params = model === undefined ? [] : [model];\n\t\tconst select = db\n\t\t\t.prepare(`SELECT ${columns} FROM validated_vector_rows ${where} /* ${marker} indexed */`)\n\t\t\t.safeIntegers();\n\t\tyield* select.iterate(...params) as Iterable<VectorMetadataRow>;\n\t\treturn;\n\t}\n\tconst ids = JSON.stringify(memoryIds);\n\t// Resolve the model list before iterating: the connection cannot run another\n\t// statement while an iterator is open.\n\tconst models = model === undefined ? indexedModels(db) : [model];\n\tconst select = db\n\t\t.prepare(\n\t\t\t`SELECT ${columns} FROM validated_vector_rows\n\t\t\t WHERE model IS ? AND memory_id IN (SELECT value FROM json_each(?)) /* ${marker} indexed */`,\n\t\t)\n\t\t.safeIntegers();\n\tfor (const value of models) yield* select.iterate(value, ids) as Iterable<VectorMetadataRow>;\n}\n\nfunction* readVec0Rows(\n\tdb: Database,\n\t{ memoryIds, model }: VectorMetadataFilter,\n\tmarker: string,\n): Generator<VectorMetadataRow> {\n\t// Restrict copied rows to this batch; vec0 may still scan memory IDs.\n\t// A JSON ID list uses one binding even when callers exceed SQLite's bind limit.\n\tconst conditions =\n\t\tmemoryIds === undefined ? [] : [\"memory_id IN (SELECT value FROM json_each(?))\"];\n\tconst params: Array<string> = memoryIds === undefined ? [] : [JSON.stringify(memoryIds)];\n\tif (model !== undefined) {\n\t\tconditions.push(\"model = ?\");\n\t\tparams.push(model);\n\t}\n\tconst where = conditions.length === 0 ? \"\" : `WHERE ${conditions.join(\" AND \")}`;\n\tconst select = db\n\t\t.prepare(\n\t\t\t`SELECT rowid, memory_id, model, content_hash FROM memory_vectors\n\t\t ${where} /* ${marker} */`,\n\t\t)\n\t\t.safeIntegers();\n\tyield* select.iterate(...params) as Iterable<VectorMetadataRow>;\n}\n\n/**\n * Stream rowid, memory_id, model, and content_hash for vector rows matching\n * the filter, as bigint IDs. Uses the indexed table when the layout keeps it\n * complete and vec0 otherwise. `marker` names the caller in the SQL comment.\n */\nexport function readVectorMetadataRows(\n\tdb: Database,\n\tfilter: VectorMetadataFilter,\n\tmarker: string,\n): Iterable<VectorMetadataRow> {\n\tif (filter.memoryIds?.length === 0) return [];\n\tif (hasIndexedVectorMetadata(db)) return readIndexedRows(db, filter, marker);\n\treturn readVec0Rows(db, filter, marker);\n}\n","import SqliteDatabase from \"better-sqlite3\";\nimport type { Database } from \"./db.js\";\nimport { readVectorMetadataRows, type VectorMetadataFilter } from \"./vector-metadata-rows.js\";\n\ntype VectorMetadataSnapshotOptions = VectorMetadataFilter;\n\nfunction copyVectorMetadata(\n\tdb: Database,\n\tmetadata: Database,\n\toptions: VectorMetadataSnapshotOptions,\n): void {\n\tif (options.memoryIds?.length === 0) return;\n\tconst insert = metadata.prepare(\n\t\t\"INSERT INTO vector_metadata(rowid, memory_id, model, content_hash) VALUES (?, ?, ?, ?)\",\n\t);\n\tmetadata.transaction(() => {\n\t\tfor (const row of readVectorMetadataRows(db, options, \"vector-metadata-snapshot\")) {\n\t\t\tif (\n\t\t\t\t!Number.isSafeInteger(Number(row.rowid)) ||\n\t\t\t\t(row.memory_id !== null && !Number.isSafeInteger(Number(row.memory_id)))\n\t\t\t) {\n\t\t\t\tthrow new RangeError(\"Vector metadata IDs exceed the exact numeric range\");\n\t\t\t}\n\t\t\tinsert.run(row.rowid, row.memory_id, row.model, row.content_hash);\n\t\t}\n\t})();\n}\n\n/**\n * Stream vector metadata once into an indexed, disposable SQLite database.\n * v1 layouts read the indexed mirror table; legacy layouts scan vec0.\n *\n * A separate temporary database avoids changing the source connection's\n * temp_store (which would destroy callers' TEMP tables). Its pager can spill\n * to disk, unlike a TEMP table on our temp_store=MEMORY source connection.\n * Every invocation owns its connection, including nested operations.\n *\n * Callers own its lifetime and must close it in finally. Retaining an idle\n * catalog across cleanup yields holds no source transaction or statement open.\n * A write recheck must build it inside the source's immediate transaction.\n */\nexport function createVectorMetadataSnapshot(\n\tdb: Database,\n\toptions: VectorMetadataSnapshotOptions = {},\n): Database {\n\tconst metadata = new SqliteDatabase(\"\");\n\ttry {\n\t\tmetadata.pragma(\"temp_store = FILE\");\n\t\tmetadata.pragma(\"cache_size = -1024\");\n\t\tmetadata.exec(`CREATE TABLE vector_metadata (\n\t\t\trowid INTEGER PRIMARY KEY,\n\t\t\tmemory_id INTEGER,\n\t\t\tmodel TEXT,\n\t\t\tcontent_hash TEXT\n\t\t)`);\n\t\tcopyVectorMetadata(db, metadata, options);\n\t\tmetadata.exec(\n\t\t\t\"CREATE INDEX vector_metadata_memory_model_hash ON vector_metadata(memory_id, model, content_hash)\",\n\t\t);\n\t\treturn metadata;\n\t} catch (error) {\n\t\tmetadata.close();\n\t\tthrow error;\n\t}\n}\n\nexport function withVectorMetadataSnapshot<T>(\n\tdb: Database,\n\tvisit: (metadata: Database) => T,\n\toptions: VectorMetadataSnapshotOptions = {},\n): T {\n\tconst metadata = createVectorMetadataSnapshot(db, options);\n\ttry {\n\t\treturn visit(metadata);\n\t} finally {\n\t\tmetadata.close();\n\t}\n}\n","/** Supported vector mutations. Callers own the synchronous writer transaction. */\nimport { type Database, tableExists } from \"./db.js\";\nimport { type VectorRowInput, vectorBytes } from \"./semantic/semantic-ranking.js\";\nimport { startAudit } from \"./semantic/validated-vector-index-audit.js\";\nimport {\n\tinsertRow,\n\tremoveRow,\n\trequireModel,\n\trequireVectorMetadata,\n} from \"./semantic/validated-vector-index-mutations.js\";\nimport {\n\tfinishMutation,\n\ttype IndexedRow,\n\tinvalidateValidatedIndex,\n\treadState,\n} from \"./semantic/validated-vector-index-state.js\";\nimport {\n\ttype IndexStatement,\n\tprepareCountStatements,\n\ttype RemoveStatements,\n} from \"./semantic/validated-vector-index-statements.js\";\nimport { resolveVectorLayout, type VectorLayout } from \"./vector-layout.js\";\nimport { readVectorMetadataRows } from \"./vector-metadata-rows.js\";\n\nexport interface VectorWriteBatch {\n\tinsert?: { model: string; rows: readonly VectorRowInput[]; expectedCount: number };\n\tdeleteRowIds?: readonly number[];\n\tdeleteMemoryIds?: readonly number[];\n\tsignal?: AbortSignal;\n}\n\ninterface WriteStatements {\n\tdb: Database;\n\tlayout?: VectorLayout;\n\tdeleteVector?: IndexStatement;\n\tselectVector?: IndexStatement;\n\tinsertVector?: IndexStatement;\n\tselectMemoryRows?: IndexStatement;\n\tmetadata?: ReturnType<typeof prepareMetadata>;\n}\n\n/** Statement lifetime is one maintenance operation, not one row or connection.\n * Preparing the operation is harmless outside a transaction; every batch requires one.\n */\nexport function prepareVectorWrites(db: Database) {\n\tconst statements: WriteStatements = { db };\n\treturn (batch: VectorWriteBatch) => writeVectorBatch(statements, batch);\n}\n\n/** Explicit model transition: rotate the generation and census old rows as pending.\n * The lifecycle driver audits those rows later; declaring a model never validates them.\n */\nexport function ensureVectorWriteModel(db: Database, model: string): boolean {\n\tif (!db.inTransaction) throw new Error(\"vector_write_transaction_required\");\n\trequireModel(model);\n\tif (!tableExists(db, \"validated_vector_state\")) return false;\n\tconst state = readState(db);\n\tconst knownModels: unknown = JSON.parse(state.known_models);\n\tif (!Array.isArray(knownModels) || !knownModels.every((entry) => typeof entry === \"string\"))\n\t\tthrow new Error(\"invalid_generation_models\");\n\tif (state.audit_started && knownModels.includes(model)) return false;\n\tstartAudit(db, { knownModels: [...new Set([...knownModels, model])] });\n\treturn true;\n}\n\nfunction writeVectorBatch(statements: WriteStatements, batch: VectorWriteBatch) {\n\tconst { db } = statements;\n\tif (!db.inTransaction) throw new Error(\"vector_write_transaction_required\");\n\tconst prepared = prepareInsertBatch(batch.insert);\n\tconst empty = { deleted: 0, deletedRowIds: [] as number[], inserted: 0 };\n\tif (!prepared.length && !batch.deleteRowIds?.length && !batch.deleteMemoryIds?.length)\n\t\treturn empty;\n\tconst layout = resolveVectorLayout(db);\n\tif (layout.kind === \"absent\") {\n\t\tif (prepared.length) throw new Error(\"vector_table_required\");\n\t\treturn empty;\n\t}\n\tresetLayoutStatements(statements, layout);\n\tconst state = prepareCatalogMutation(statements, batch, prepared);\n\tconst rowIds = collectDeleteRowIds(statements, batch);\n\tconst result = deleteRows(statements, rowIds, {\n\t\trebuild: state !== null && !state.audit_started,\n\t\tsignal: batch.signal,\n\t});\n\tinsertRows(statements, prepared, { indexed: state !== null && !result.rebuild });\n\tif (layout.kind === \"legacy\") finishLegacyMutation(db, state, result, prepared.length);\n\treturn {\n\t\tdeleted: result.deletedRowIds.length,\n\t\tdeletedRowIds: result.deletedRowIds,\n\t\tinserted: prepared.length,\n\t};\n}\n\nfunction finishLegacyMutation(\n\tdb: Database,\n\tstate: ReturnType<typeof readState> | null,\n\tresult: ReturnType<typeof deleteRows>,\n\tinserted: number,\n): void {\n\tif (!state) return;\n\tif (!result.deletedRowIds.length && !inserted && !(state.audit_started && result.rebuild)) return;\n\tif (result.rebuild) invalidateValidatedIndex(db);\n\telse finishMutation(db);\n}\n\nfunction resetLayoutStatements(statements: WriteStatements, layout: VectorLayout): void {\n\tif (statements.layout?.kind === layout.kind) return;\n\tstatements.layout = layout;\n\tstatements.deleteVector = undefined;\n\tstatements.selectVector = undefined;\n\tstatements.insertVector = undefined;\n\tstatements.selectMemoryRows = undefined;\n\tstatements.metadata = undefined;\n}\n\nfunction prepareCatalogMutation(\n\tstatements: WriteStatements,\n\tbatch: VectorWriteBatch,\n\trows: ReturnType<typeof prepareInsertBatch>,\n) {\n\tconst { db } = statements;\n\tif (!tableExists(db, \"validated_vector_state\")) {\n\t\tif (statements.layout?.kind === \"v1\") throw new Error(\"validated_index_not_initialized\");\n\t\treturn null;\n\t}\n\tconst state = readState(db);\n\tif (batch.insert) requireDeclaredModel(state.known_models, batch.insert.model);\n\tif (statements.layout?.kind === \"v1\" && rows.length && !state.audit_started)\n\t\tthrow new Error(\"start_audit_census_required\");\n\tstatements.metadata ??= prepareMetadata(db, prepareDeleteVector(statements), statements.layout);\n\tfor (const row of rows) {\n\t\tif (!statements.metadata.sourceExists.get(row.memoryId))\n\t\t\tthrow new Error(\"vector_source_memory_missing\");\n\t}\n\treturn state;\n}\n\nfunction collectDeleteRowIds(statements: WriteStatements, batch: VectorWriteBatch): Set<number> {\n\tconst ids = new Set(batch.deleteRowIds ?? []);\n\tif (!batch.deleteMemoryIds?.length) return ids;\n\tif (statements.layout?.kind === \"v1\") {\n\t\t// v1 keeps validated_vector_rows identical to vec0 (see hasIndexedVectorMetadata),\n\t\t// so (model, memory_id) index seeks replace a vec0 metadata scan. The\n\t\t// reader falls back to vec0 if the row counts disagree.\n\t\tconst rows = readVectorMetadataRows(\n\t\t\tstatements.db,\n\t\t\t{ memoryIds: batch.deleteMemoryIds },\n\t\t\t\"vector-delete-memory-rows\",\n\t\t);\n\t\tfor (const row of rows) ids.add(Number(row.rowid));\n\t\treturn ids;\n\t}\n\tstatements.selectMemoryRows ??= statements.db.prepare(`SELECT rowid FROM memory_vectors\n\t\tWHERE memory_id IN (SELECT value FROM json_each(?))`);\n\tfor (const row of statements.selectMemoryRows.all(JSON.stringify(batch.deleteMemoryIds)) as {\n\t\trowid: number;\n\t}[])\n\t\tids.add(row.rowid);\n\treturn ids;\n}\n\nfunction deleteRows(\n\tstatements: WriteStatements,\n\trowIds: Set<number>,\n\toptions: { rebuild: boolean; signal?: AbortSignal },\n) {\n\tlet rebuild = options.rebuild;\n\tconst deletedRowIds: number[] = [];\n\tfor (const rowid of rowIds) {\n\t\tif (options.signal?.aborted) break;\n\t\tconst result = deleteRow(statements, rowid, { rebuild });\n\t\trebuild = result.rebuild;\n\t\tif (result.deleted) deletedRowIds.push(rowid);\n\t}\n\treturn { rebuild, deletedRowIds };\n}\n\nfunction deleteRow(statements: WriteStatements, rowid: number, options: { rebuild: boolean }) {\n\tif (!Number.isSafeInteger(rowid)) throw new RangeError(\"unsafe_vector_rowid\");\n\tconst deleteVector = prepareDeleteVector(statements);\n\tif (statements.layout?.kind === \"v1\") {\n\t\tstatements.selectVector ??= statements.db.prepare(\n\t\t\t\"SELECT rowid FROM memory_vectors WHERE rowid = ?\",\n\t\t);\n\t\tconst exists = Boolean(statements.selectVector.get(BigInt(rowid)));\n\t\tif (exists) deleteVector.run(BigInt(rowid));\n\t\treturn { deleted: exists, rebuild: false };\n\t}\n\tconst metadata = statements.metadata;\n\tif (!metadata) return { deleted: deleteVector.run(BigInt(rowid)).changes > 0, rebuild: false };\n\tconst row = metadata.selectRow.get(rowid) as IndexedRow | undefined;\n\tconst physical = metadata.selectPhysical.get(BigInt(rowid)) as IndexedRow | undefined;\n\tconst rebuild = options.rebuild || !sameIndexedMetadata(row, physical);\n\tif (row && physical && !rebuild) {\n\t\tremoveRow(metadata.remove, row);\n\t\treturn { deleted: true, rebuild };\n\t}\n\treturn { deleted: deleteVector.run(BigInt(rowid)).changes > 0, rebuild };\n}\n\nfunction insertRows(\n\tstatements: WriteStatements,\n\trows: ReturnType<typeof prepareInsertBatch>,\n\toptions: { indexed: boolean },\n) {\n\tfor (const row of rows) {\n\t\tif (options.indexed && statements.metadata) {\n\t\t\tinsertRow(statements.metadata.insert, row, row.model, row.bytes);\n\t\t\tcontinue;\n\t\t}\n\t\tstatements.insertVector ??= statements.db.prepare(`INSERT INTO memory_vectors\n\t\t\t(embedding,memory_id,chunk_index,content_hash,model) VALUES(?,?,?,?,?)`);\n\t\tstatements.insertVector.run(\n\t\t\trow.bytes,\n\t\t\tBigInt(row.memoryId),\n\t\t\tBigInt(row.chunkIndex),\n\t\t\trow.contentHash,\n\t\t\trow.model,\n\t\t);\n\t}\n\tif (statements.layout?.kind === \"v1\" && rows.length) finishMutation(statements.db);\n}\n\nfunction prepareDeleteVector(statements: WriteStatements): IndexStatement {\n\tstatements.deleteVector ??= statements.db.prepare(\"DELETE FROM memory_vectors WHERE rowid = ?\");\n\treturn statements.deleteVector;\n}\n\nfunction sameIndexedMetadata(\n\tindexed: IndexedRow | undefined,\n\tphysical: IndexedRow | undefined,\n): boolean {\n\tif (!indexed || !physical) return indexed === physical;\n\treturn (\n\t\tindexed.memory_id === physical.memory_id &&\n\t\tindexed.model === physical.model &&\n\t\tindexed.chunk_index === physical.chunk_index &&\n\t\tindexed.content_hash === physical.content_hash\n\t);\n}\n\nfunction prepareInsertBatch(batch: VectorWriteBatch[\"insert\"]) {\n\tif (!batch) return [];\n\trequireModel(batch.model);\n\tif (!Number.isSafeInteger(batch.expectedCount) || batch.expectedCount !== batch.rows.length)\n\t\tthrow new TypeError(\"vector_count_mismatch\");\n\treturn batch.rows.map((row) => {\n\t\trequireVectorMetadata(row);\n\t\treturn { ...row, model: batch.model, bytes: vectorBytes(row.vector) };\n\t});\n}\n\nfunction requireDeclaredModel(knownModels: string, model: string): void {\n\tconst models: unknown = JSON.parse(knownModels);\n\tif (!Array.isArray(models) || !models.includes(model))\n\t\tthrow new TypeError(\"vector_model_not_declared_in_generation\");\n}\n\nfunction prepareMetadata(\n\tdb: Database,\n\tdeleteVector: IndexStatement,\n\tlayout: WriteStatements[\"layout\"],\n) {\n\tconst counts = prepareCountStatements(db);\n\tconst remove: RemoveStatements = {\n\t\tcounts,\n\t\tdeleteVector,\n\t\tdeleteIndexedRow: db.prepare(\"DELETE FROM validated_vector_rows WHERE rowid=?\"),\n\t\tdecrementAuditCounts:\n\t\t\tdb.prepare(`UPDATE validated_vector_state SET pending_count=pending_count-?,\n\t\t\tinvalid_count=invalid_count-? WHERE id=1`),\n\t};\n\treturn {\n\t\tremove,\n\t\tinsert: {\n\t\t\tcounts,\n\t\t\tinsertVector: preparePhysicalInsert(db, layout),\n\t\t\tinsertIndexedRow: db.prepare(`INSERT INTO validated_vector_rows\n\t\t\t\t(rowid,memory_id,model,chunk_index,content_hash,audit_state) VALUES(?,?,?,?,?,'valid')`),\n\t\t},\n\t\tselectRow: db.prepare(\"SELECT * FROM validated_vector_rows WHERE rowid=?\"),\n\t\tselectPhysical: db.prepare(\n\t\t\t\"SELECT memory_id,model,chunk_index,content_hash FROM memory_vectors WHERE rowid=?\",\n\t\t),\n\t\tsourceExists: db.prepare(\"SELECT 1 FROM memory_items WHERE id=?\"),\n\t};\n}\n\nfunction preparePhysicalInsert(db: Database, layout: WriteStatements[\"layout\"]): IndexStatement {\n\tif (layout?.kind === \"v1\")\n\t\treturn db.prepare(`INSERT INTO memory_vectors_v1\n\t\t(embedding,memory_id,chunk_index,content_hash,model) VALUES(?,?,?,?,?)`);\n\treturn db.prepare(`INSERT INTO memory_vectors\n\t\t(embedding,memory_id,chunk_index,content_hash,model) VALUES(?,?,?,?,?)`);\n}\n","/**\n * Vector store operations for semantic search.\n *\n * Ports codemem/store/vectors.py — backfill and on-insert vector writes\n * against the sqlite-vec `memory_vectors` virtual table.\n *\n * All functions accept a raw better-sqlite3 Database so they work outside\n * the MemoryStore class. Embedding is async; callers await then write\n * synchronously (matches the runtime-topology decision: main thread owns DB).\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport type { Statement } from \"better-sqlite3\";\nimport type { Database } from \"./db.js\";\nimport { isEmbeddingDisabled } from \"./db.js\";\nimport {\n\tassertEmbeddingClientIdentity,\n\tchunkText,\n\tDEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL,\n\ttype EmbeddingClient,\n\tembedTexts,\n\tgetEmbeddingClient,\n\tgetEmbeddingRuntimeStatus,\n\thashText,\n\tresolveEmbeddingClientVectorIdentityLabel,\n\tresolveEmbeddingModel,\n\tserializeFloat32,\n\ttryResolveEmbeddingRevision,\n\ttryResolveEmbeddingVectorIdentityLabel,\n} from \"./embeddings.js\";\nimport type { OwnershipFilterContext } from \"./filters.js\";\nimport {\n\tcompleteMaintenanceJob,\n\tgetMaintenanceJob,\n\tstartMaintenanceJob,\n} from \"./maintenance-jobs.js\";\nimport { projectColumnClause } from \"./project.js\";\nimport { snapshot } from \"./semantic/validated-vector-index-state.js\";\nimport {\n\tbuildAuthorizedSemanticMemoryIdsQuery,\n\tpendingVectorFreshness,\n\tresolveSemanticSearchModelFromCatalog,\n\tsemanticResult,\n} from \"./semantic-query.js\";\nimport type { ReplicationVectorWork } from \"./sync-replication.js\";\nimport type { MemoryFilters } from \"./types.js\";\nimport { resolveVectorLayout, vectorStoreExists } from \"./vector-layout.js\";\nimport {\n\tcreateVectorMetadataSnapshot,\n\twithVectorMetadataSnapshot,\n} from \"./vector-metadata-snapshot.js\";\nimport { ensureVectorWriteModel, prepareVectorWrites } from \"./vector-writes.js\";\n\nconst VECTOR_MODEL_MIGRATION_JOB = \"vector_model_migration\";\n// Keep resolved-client identity separate from migration progress: direct or\n// partial backfills must not claim that a model cutover completed.\nconst VECTOR_MODEL_IDENTITY_JOB = \"vector_model_identity\";\nconst LEGACY_DEFAULT_EMBEDDING_MODEL = \"Xenova/bge-small-en-v1.5\";\nconst BACKFILL_MEMORY_PAGE_SIZE = 50;\nconst BACKFILL_INFERENCE_BATCH_SIZE = 32;\nconst BACKFILL_CANDIDATE_TABLE_PREFIX = \"codemem_backfill_vector_candidates\";\n\ntype MemoryTextRow = {\n\tid: number;\n\ttitle: string | null;\n\tbody_text: string | null;\n\tcreated_at?: string;\n};\ntype PendingChunk = { text: string; chunkIndex: number; contentHash: string };\ntype PendingMemory = {\n\tmemoryId: number;\n\tsource: VectorSourceRow;\n\tchunks: PendingChunk[];\n\tvectors: Float32Array[];\n};\n\ntype VectorSourceRow = MemoryTextRow & {\n\timport_key: string | null;\n\tsession_id: number;\n\tcreated_at: string;\n\torigin_device_id: string | null;\n\trev: number | null;\n\tupdated_at: string;\n\tactive: number | null;\n\tdeleted_at: string | null;\n};\n\ntype BackfillMemoryRow = VectorSourceRow & { snapshot_seq: number };\n\nconst VECTOR_SOURCE_COLUMNS = `id, title, body_text, import_key, session_id, created_at,\n\torigin_device_id, rev, updated_at, active, deleted_at`;\nconst QUALIFIED_VECTOR_SOURCE_COLUMNS = VECTOR_SOURCE_COLUMNS.split(\",\")\n\t.map((column) => `memory_items.${column.trim()}`)\n\t.join(\", \");\n\nfunction readVectorSource(db: Database, memoryId: number): VectorSourceRow | undefined {\n\tif (!Number.isInteger(memoryId)) return undefined;\n\treturn db\n\t\t.prepare(`SELECT ${VECTOR_SOURCE_COLUMNS} FROM memory_items WHERE id = ?`)\n\t\t.get(memoryId) as VectorSourceRow | undefined;\n}\n\nfunction currentVectorSourceHashes(\n\tsaved: VectorSourceRow,\n\tcurrent: VectorSourceRow | undefined,\n): string[] {\n\t// Text equality alone cannot distinguish reuse of a deleted memory's numeric ID.\n\tif (\n\t\t!current ||\n\t\tcurrent.import_key !== saved.import_key ||\n\t\tcurrent.session_id !== saved.session_id ||\n\t\tcurrent.created_at !== saved.created_at ||\n\t\tcurrent.origin_device_id !== saved.origin_device_id ||\n\t\tcurrent.rev !== saved.rev ||\n\t\tcurrent.updated_at !== saved.updated_at ||\n\t\tcurrent.active !== saved.active ||\n\t\tcurrent.deleted_at !== saved.deleted_at\n\t) {\n\t\treturn [];\n\t}\n\t// Redaction can change text without advancing the revision or update timestamp.\n\treturn chunkHashes(memoryText(current.title, current.body_text));\n}\n\nfunction pendingBackfillMemory(source: VectorSourceRow, chunks: PendingChunk[]): PendingMemory {\n\treturn { memoryId: source.id, source, chunks, vectors: [] };\n}\n\nfunction assertVectorMemoryId(memoryId: number): void {\n\tif (!Number.isFinite(memoryId))\n\t\tthrow new TypeError(`Expected finite integer, received ${String(memoryId)}`);\n\tif (!Number.isInteger(memoryId))\n\t\tthrow new TypeError(`Expected integer, received ${String(memoryId)}`);\n}\n\nfunction createBackfillCandidateSnapshot(\n\tdb: Database,\n\tjoinClause: string,\n\twhere: string,\n\tparams: unknown[],\n\trowLimit: number,\n): string {\n\t// randomUUID is hex plus hyphens; stripping hyphens keeps this interpolated identifier safe.\n\tconst tableName = `${BACKFILL_CANDIDATE_TABLE_PREFIX}_${randomUUID().replaceAll(\"-\", \"\")}`;\n\tdb.exec(`\n\t\tCREATE TEMP TABLE ${tableName} (\n\t\t\tseq INTEGER PRIMARY KEY,\n\t\t\tmemory_id INTEGER NOT NULL\n\t\t)\n\t`);\n\tconst hasFiniteLimit = Number.isFinite(rowLimit);\n\tconst limitClause = hasFiniteLimit ? \"LIMIT ?\" : \"\";\n\tconst snapshotParams = hasFiniteLimit ? [...params, rowLimit] : params;\n\ttry {\n\t\tdb.prepare(\n\t\t\t`INSERT INTO ${tableName}(memory_id)\n\t\t\t SELECT memory_items.id\n\t\t\t FROM memory_items ${joinClause}\n\t\t\t WHERE ${where}\n\t\t\t ORDER BY memory_items.created_at ASC, memory_items.id ASC\n\t\t\t ${limitClause}`,\n\t\t).run(...snapshotParams);\n\t} catch (error) {\n\t\tdb.exec(`DROP TABLE IF EXISTS ${tableName}`);\n\t\tthrow error;\n\t}\n\treturn tableName;\n}\n\nfunction deleteBackfillCandidateSnapshot(db: Database, tableName: string): void {\n\tdb.exec(`DROP TABLE IF EXISTS ${tableName}`);\n}\n\n// Deliberately omits `enforceScopeVisibility` so semantic callers can never\n// disable the local read boundary — scopeVisibleFilterContext() always forces\n// it on below. Field list otherwise mirrors OwnershipFilterContext.\nexport type SemanticSearchScopeContext = Omit<OwnershipFilterContext, \"enforceScopeVisibility\">;\n\nfunction clampSemanticLimit(limit: number): number {\n\tif (limit === Number.POSITIVE_INFINITY) return 200;\n\tif (!Number.isFinite(limit)) return 1;\n\treturn Math.min(Math.max(1, Math.trunc(limit)), 200);\n}\n\nfunction listVectorModels(db: Database): Array<string | null> {\n\tif (!vectorStoreExists(db)) {\n\t\treturn [];\n\t}\n\ttry {\n\t\tconst rows = db.prepare(\"SELECT DISTINCT model FROM memory_vectors\").all() as Array<{\n\t\t\tmodel: string | null;\n\t\t}>;\n\t\t// Keep NULL and unknown labels: they must still prevent an unverified\n\t\t// mixed corpus from looking like an exclusively current-model corpus.\n\t\treturn rows.map((row) => row.model);\n\t} catch {\n\t\treturn [];\n\t}\n}\n\nfunction hasVectorRows(db: Database): boolean {\n\tif (!vectorStoreExists(db)) return false;\n\ttry {\n\t\treturn db.prepare(\"SELECT 1 FROM memory_vectors LIMIT 1\").get() != null;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction tryResolveConfiguredVectorIdentityLabel(db: Database): string | null {\n\tfor (const jobKind of [VECTOR_MODEL_IDENTITY_JOB, VECTOR_MODEL_MIGRATION_JOB]) {\n\t\tconst metadata = (getMaintenanceJob(db, jobKind)?.metadata ?? {}) as Record<string, unknown>;\n\t\tconst targetModel = tryResolveEmbeddingVectorIdentityLabel({\n\t\t\ttargetModel: metadata.target_model,\n\t\t\trequestedModel: metadata.requested_model,\n\t\t\trequestedRevision: metadata.requested_revision,\n\t\t});\n\t\tif (targetModel) return targetModel;\n\t}\n\treturn null;\n}\n\nfunction persistVectorIdentity(db: Database, client: EmbeddingClient, targetModel: string): void {\n\tif (!client.identity) {\n\t\tthrow new TypeError(\"Embedding runtime identity is required to persist vector metadata\");\n\t}\n\tconst metadata = {\n\t\ttarget_model: targetModel,\n\t\trequested_model: client.model,\n\t\trequested_revision: client.identity.requestedRevision ?? client.identity.revision,\n\t};\n\tconst existing = getMaintenanceJob(db, VECTOR_MODEL_IDENTITY_JOB);\n\tif (\n\t\texisting?.status === \"completed\" &&\n\t\texisting.metadata?.target_model === metadata.target_model &&\n\t\texisting.metadata.requested_model === metadata.requested_model &&\n\t\texisting.metadata.requested_revision === metadata.requested_revision\n\t) {\n\t\treturn;\n\t}\n\tstartMaintenanceJob(db, {\n\t\tkind: VECTOR_MODEL_IDENTITY_JOB,\n\t\ttitle: \"Embedding vector identity\",\n\t\tmessage: \"Recorded the canonical embedding identity used by vector writes\",\n\t\tprogressTotal: 1,\n\t\tmetadata,\n\t});\n\tcompleteMaintenanceJob(db, VECTOR_MODEL_IDENTITY_JOB, {\n\t\tprogressCurrent: 1,\n\t\tprogressTotal: 1,\n\t\tmetadata,\n\t});\n}\n\nexport function resolveSemanticSearchModel(db: Database, currentModel?: string): string | null {\n\tif (currentModel === undefined) {\n\t\tcurrentModel = tryResolveConfiguredVectorIdentityLabel(db) ?? undefined;\n\t\tif (currentModel === undefined) return null;\n\t}\n\treturn resolveSemanticSearchModelFromCatalog(\n\t\tcurrentModel,\n\t\tgetMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB),\n\t\tlistVectorModels(db),\n\t);\n}\n\n/**\n * Resolve every vector-model label that should be read together for the current\n * identity. During the compatible legacy-default rebuild this returns both the\n * legacy label and the revision-aware target so consumers see memories written\n * under either identity. Returns a single-element list otherwise, or `[]` when\n * no semantic corpus is currently serviceable.\n */\nexport function resolveSemanticSearchModels(db: Database, resolvedModel?: string): string[] {\n\tconst currentModel = resolvedModel ?? tryResolveConfiguredVectorIdentityLabel(db);\n\tif (currentModel == null) return [];\n\t// Primary selection and compatible expansion share this call's catalog,\n\t// never a cross-search snapshot that could survive a model cutover.\n\tconst job = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\tconst models = listVectorModels(db);\n\tconst primaryModel = resolveSemanticSearchModelFromCatalog(currentModel, job, models);\n\treturn expandSemanticSearchModels(db, primaryModel, currentModel, models);\n}\n\nfunction expandSemanticSearchModels(\n\tdb: Database,\n\tprimaryModel: string | null,\n\tcurrentModel: string,\n\tmodels?: readonly (string | null)[],\n): string[] {\n\tif (!primaryModel) return [];\n\tif (\n\t\tprimaryModel === LEGACY_DEFAULT_EMBEDDING_MODEL &&\n\t\tcurrentModel === DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL &&\n\t\t(models ?? listVectorModels(db)).includes(currentModel)\n\t) {\n\t\treturn [primaryModel, currentModel];\n\t}\n\treturn [primaryModel];\n}\n\nfunction chunkHashes(text: string): string[] {\n\treturn chunkText(text).map((chunk) => hashText(chunk));\n}\n\nfunction memoryText(title: string | null, bodyText: string | null): string {\n\treturn `${title ?? \"\"}\\n${bodyText ?? \"\"}`.trim();\n}\n\nexport function memoryHasCompleteVectorCoverage(\n\tdb: Database,\n\tmemory: MemoryTextRow,\n\tmodel: string,\n): boolean {\n\tconst expectedHashes = chunkHashes(memoryText(memory.title, memory.body_text));\n\tif (expectedHashes.length === 0) return true;\n\tconst existingRows = db\n\t\t.prepare(\"SELECT content_hash FROM memory_vectors WHERE memory_id = ? AND model = ?\")\n\t\t.all(memory.id, model) as Array<{ content_hash: string | null }>;\n\treturn expectedHashesExist(expectedHashes, existingRows);\n}\n\nexport function findMemoryIdsWithCompleteActiveVectorCoverage(\n\tdb: Database,\n\tmemoryIds: number[],\n\tmodel: string,\n): number[] {\n\tconst ids = uniqueMemoryIds(memoryIds);\n\tif (ids.length === 0) return [];\n\tconst placeholders = ids.map(() => \"?\").join(\", \");\n\tconst memories = db\n\t\t.prepare(\n\t\t\t`SELECT id, title, body_text FROM memory_items\n\t\t\t WHERE active = 1 AND id IN (${placeholders})`,\n\t\t)\n\t\t.all(...ids) as MemoryTextRow[];\n\tif (memories.length === 0) return ids;\n\t// The coverage query reads only these memories' rows for this model, so the\n\t// snapshot copies only those instead of the whole vector catalog.\n\tconst incompleteIds = withVectorMetadataSnapshot(\n\t\tdb,\n\t\t(metadata) => {\n\t\t\tconst selectHash = prepareSnapshotHashQuery(metadata);\n\t\t\treturn new Set(\n\t\t\t\tmemories\n\t\t\t\t\t.filter((memory) => !memoryHasSnapshotCoverage(selectHash, memory, model))\n\t\t\t\t\t.map((memory) => memory.id),\n\t\t\t);\n\t\t},\n\t\t{ memoryIds: memories.map((memory) => memory.id), model },\n\t);\n\t// Missing or inactive memories have no active coverage work and must not\n\t// remain queued forever. Their deletion work is tracked separately.\n\treturn ids.filter((memoryId) => !incompleteIds.has(memoryId));\n}\n\nfunction expectedHashesExist(\n\texpectedHashes: string[],\n\texistingRows: Array<{ content_hash: string | null }>,\n): boolean {\n\tconst existingHashes = new Set(\n\t\texistingRows.map((row) => row.content_hash).filter((hash): hash is string => hash != null),\n\t);\n\treturn expectedHashSetContains(expectedHashes, existingHashes);\n}\n\nfunction expectedHashSetContains(expectedHashes: string[], existingHashes: Set<string>): boolean {\n\treturn expectedHashes.every((hash) => existingHashes.has(hash));\n}\n\ntype SnapshotQuery = Statement<unknown[]>;\n\nfunction prepareSnapshotHashQuery(metadata: Database): SnapshotQuery {\n\treturn metadata.prepare(\n\t\t`SELECT 1 FROM vector_metadata\n\t\t WHERE memory_id = ? AND model = ? AND content_hash = ? LIMIT 1`,\n\t);\n}\n\nfunction memoryHasSnapshotCoverage(\n\tselectHash: SnapshotQuery,\n\tmemory: MemoryTextRow,\n\tmodel: string,\n): boolean {\n\tconst expectedHashes = chunkHashes(memoryText(memory.title, memory.body_text));\n\treturn snapshotHasExpectedHashes(selectHash, memory.id, model, expectedHashes);\n}\n\nfunction snapshotHasExpectedHashes(\n\tselectHash: SnapshotQuery,\n\tmemoryId: number,\n\tmodel: string,\n\texpectedHashes: string[],\n): boolean {\n\treturn expectedHashes.every((hash) => selectHash.get(memoryId, model, hash) != null);\n}\n\nexport function countIncompleteActiveMemoryVectorCoverage(\n\tdb: Database,\n\tmodel: string,\n\toptions: { metadata?: Database } = {},\n): number {\n\tlet incomplete = 0;\n\tvisitIncompleteActiveMemoryIds(db, model, () => incomplete++, options);\n\treturn incomplete;\n}\n\n/** Internal repair candidates, using the same current-hash coverage check as cutover. */\nexport function findIncompleteActiveMemoryIds(\n\tdb: Database,\n\tmodel: string,\n\toptions: { metadata?: Database } = {},\n): number[] {\n\tconst ids: number[] = [];\n\tvisitIncompleteActiveMemoryIds(db, model, (id) => ids.push(id), options);\n\treturn ids;\n}\n\nfunction visitIncompleteActiveMemoryIds(\n\tdb: Database,\n\tmodel: string,\n\tvisit: (id: number) => void,\n\toptions: { metadata?: Database },\n): void {\n\tconst batchSize = 250;\n\tlet afterId = 0;\n\tlet metadata: Database | null = options.metadata ?? null;\n\tlet selectHash: SnapshotQuery | null = null;\n\t// Keep cursor pages on the rowid range; the active/created index requires a sort per page.\n\tconst selectMemories = db.prepare(\n\t\t`SELECT id, title, body_text FROM memory_items NOT INDEXED\n\t\t WHERE active = 1\n\t\t AND TRIM(COALESCE(title, '') || COALESCE(body_text, '')) != ''\n\t\t AND id > ?\n\t\t ORDER BY id ASC\n\t\t LIMIT ? /* vector-coverage-validation */`,\n\t);\n\ttry {\n\t\twhile (true) {\n\t\t\tconst memories = selectMemories.all(afterId, batchSize) as MemoryTextRow[];\n\t\t\tif (memories.length === 0) break;\n\t\t\tif (memories.some((memory) => !Number.isSafeInteger(memory.id))) {\n\t\t\t\tthrow new RangeError(\"Vector coverage requires safe integer memory IDs\");\n\t\t\t}\n\t\t\tmetadata ??= createVectorMetadataSnapshot(db);\n\t\t\tselectHash ??= prepareSnapshotHashQuery(metadata);\n\t\t\tfor (const memory of memories) {\n\t\t\t\tif (!memoryHasSnapshotCoverage(selectHash, memory, model)) visit(memory.id);\n\t\t\t}\n\t\t\tafterId = memories.at(-1)?.id ?? afterId;\n\t\t}\n\t} finally {\n\t\tif (!options.metadata) metadata?.close();\n\t}\n}\n\n/** Recheck a delete batch under its writer transaction, using one metadata scan. */\nexport function findMemoryIdsWithCurrentTargetCoverage(\n\tdb: Database,\n\tmemoryIds: readonly number[],\n\tmodel: string,\n): Set<number> {\n\t// Unlike queue IDs, persisted metadata may reference zero or negative IDs.\n\t// Reject inexact IDs rather than checking coverage for a rounded memory ID.\n\tconst ids = [...new Set(memoryIds.filter(Number.isSafeInteger))];\n\tconst covered = new Set(ids);\n\tif (ids.length === 0) return covered;\n\tconst memories = db\n\t\t.prepare(\n\t\t\t`SELECT id, title, body_text FROM memory_items\n\t\t WHERE active = 1 AND id IN (SELECT value FROM json_each(?))`,\n\t\t)\n\t\t.all(JSON.stringify(ids)) as MemoryTextRow[];\n\t// Missing/inactive memories need no target coverage before removing fallback rows.\n\tif (memories.length === 0) return covered;\n\treturn withVectorMetadataSnapshot(\n\t\tdb,\n\t\t(metadata) => {\n\t\t\tconst selectHash = prepareSnapshotHashQuery(metadata);\n\t\t\tfor (const memory of memories) {\n\t\t\t\tif (!memoryHasSnapshotCoverage(selectHash, memory, model)) covered.delete(memory.id);\n\t\t\t}\n\t\t\treturn covered;\n\t\t},\n\t\t{ memoryIds: memories.map((memory) => memory.id), model },\n\t);\n}\n\n/**\n * Prune from the same catalog later used for cutover coverage and exact equality.\n * Only our successful deletes alter it: an external deletion must fail equality.\n */\ntype CatalogVectorRow = {\n\trowid: number;\n\tmemory_id: number | null;\n\tmodel: string;\n\tcontent_hash: string | null;\n};\n\ntype CatalogPruneOptions = { signal?: AbortSignal; pruneScope?: \"all\" | \"active-only\" };\n\nfunction catalogPruneCandidates(\n\tdb: Database,\n\trows: CatalogVectorRow[],\n\toptions: CatalogPruneOptions,\n): CatalogVectorRow[] {\n\tconst expectedByMemory = new Map<number | null, Set<string> | null>();\n\tconst selectMemory = db.prepare(\"SELECT title, body_text, active FROM memory_items WHERE id = ?\");\n\treturn rows.filter((row) => {\n\t\tif (!expectedByMemory.has(row.memory_id)) {\n\t\t\tconst memory = selectMemory.get(row.memory_id) as\n\t\t\t\t| (MemoryTextRow & { active: number })\n\t\t\t\t| undefined;\n\t\t\tconst expected =\n\t\t\t\tmemory?.active === 1\n\t\t\t\t\t? new Set(chunkHashes(memoryText(memory.title, memory.body_text)))\n\t\t\t\t\t: null;\n\t\t\texpectedByMemory.set(row.memory_id, expected);\n\t\t}\n\t\tconst expected = expectedByMemory.get(row.memory_id);\n\t\tif (options.pruneScope === \"active-only\" && expected == null) return false;\n\t\treturn !expected?.has(row.content_hash ?? \"\");\n\t});\n}\n\nfunction deleteCatalogPruneCandidates(\n\tdb: Database,\n\trows: CatalogVectorRow[],\n\tmodel: string,\n\toptions: CatalogPruneOptions,\n): number[] {\n\tconst { signal } = options;\n\tconst selectCurrent = db.prepare(\n\t\t\"SELECT rowid, memory_id, model, content_hash FROM memory_vectors WHERE rowid = ?\",\n\t);\n\tconst write = prepareVectorWrites(db);\n\treturn db\n\t\t.transaction(() => {\n\t\t\t// Re-read bodies and metadata after acquiring the writer lock. A candidate\n\t\t\t// may now be a current chunk, or its memory may have lost target coverage.\n\t\t\tconst currentRows = rows.filter((row) => {\n\t\t\t\tif (signal?.aborted) return false;\n\t\t\t\tconst current = selectCurrent.get(row.rowid) as CatalogVectorRow | undefined;\n\t\t\t\treturn sameCatalogVectorRow(row, current);\n\t\t\t});\n\t\t\tif (signal?.aborted) return [];\n\t\t\tconst obsolete = catalogPruneCandidates(db, currentRows, options);\n\t\t\tconst coverage = findMemoryIdsWithCurrentTargetCoverage(\n\t\t\t\tdb,\n\t\t\t\tobsolete.flatMap((row) => (row.memory_id === null ? [] : [row.memory_id])),\n\t\t\t\tmodel,\n\t\t\t);\n\t\t\tconst ids: number[] = [];\n\t\t\tfor (const row of obsolete) {\n\t\t\t\tif (signal?.aborted) break;\n\t\t\t\tconst covered = row.memory_id === null || coverage.has(row.memory_id);\n\t\t\t\tif (covered) ids.push(row.rowid);\n\t\t\t}\n\t\t\treturn write({ deleteRowIds: ids, signal }).deletedRowIds;\n\t\t})\n\t\t.immediate();\n}\n\nfunction sameCatalogVectorRow(\n\tsaved: CatalogVectorRow,\n\tcurrent: CatalogVectorRow | undefined,\n): boolean {\n\treturn (\n\t\tcurrent !== undefined &&\n\t\tcurrent.memory_id === saved.memory_id &&\n\t\tcurrent.model === saved.model &&\n\t\tcurrent.content_hash === saved.content_hash\n\t);\n}\n\nexport function pruneObsoleteTargetVectorsFromCatalog(\n\tdb: Database,\n\tmodel: string,\n\tmetadata: Database,\n\toptions: CatalogPruneOptions = {},\n): number {\n\tconst selectPage = metadata.prepare(\n\t\t\"SELECT rowid, memory_id, model, content_hash FROM vector_metadata WHERE model = ? AND (? IS NULL OR rowid > ?) ORDER BY rowid LIMIT 250\",\n\t);\n\tconst forgetRow = metadata.prepare(\"DELETE FROM vector_metadata WHERE rowid = ?\");\n\tlet cursor: number | null = null;\n\tlet deleted = 0;\n\twhile (!options.signal?.aborted) {\n\t\tconst rows = selectPage.all(model, cursor, cursor) as CatalogVectorRow[];\n\t\tif (rows.length === 0) break;\n\t\tconst obsolete = catalogPruneCandidates(db, rows, options);\n\t\tconst deletedIds =\n\t\t\tobsolete.length === 0 ? [] : deleteCatalogPruneCandidates(db, obsolete, model, options);\n\t\tmetadata.transaction(() => {\n\t\t\tfor (const rowid of deletedIds) forgetRow.run(rowid);\n\t\t})();\n\t\tdeleted += deletedIds.length;\n\t\tcursor = rows.at(-1)?.rowid ?? cursor;\n\t}\n\treturn deleted;\n}\n\nfunction hasMemoryVectorRowidsShadowTable(db: Database): boolean {\n\tconst layout = resolveVectorLayout(db);\n\tif (layout.kind === \"absent\") return false;\n\tconst tables = db.prepare(\"PRAGMA table_list\").all() as Array<{ name: string }>;\n\treturn tables.some((table) => table.name === layout.rowidsName);\n}\n\nfunction vectorRowidsTable(db: Database): \"memory_vectors_rowids\" | \"memory_vectors_v1_rowids\" {\n\tconst layout = resolveVectorLayout(db);\n\tif (layout.kind === \"absent\") throw new Error(\"vector_table_required\");\n\treturn layout.rowidsName;\n}\n\ntype TargetVectorRow = {\n\trowid: number;\n\tmemory_id: number;\n\tcontent_hash: string | null;\n};\n\ntype TargetVectorCoverageState = {\n\texpectedHashes: string[];\n\texpected: Set<string>;\n\texisting: Set<string>;\n};\n\nfunction collectTargetVectorRows(\n\tdb: Database,\n\tmodel: string,\n\tbatchSize: number,\n\tsignal?: AbortSignal,\n): boolean {\n\tconst selectRowIds = db.prepare(\n\t\t`SELECT rowid FROM ${vectorRowidsTable(db)} WHERE rowid > ? ORDER BY rowid ASC LIMIT ? /* vector-target-prune-rowids */`,\n\t);\n\tconst selectMetadata = db.prepare(\n\t\t\"SELECT memory_id, content_hash, model FROM memory_vectors WHERE rowid = ?\",\n\t);\n\tconst insertScanRow = db.prepare(\n\t\t\"INSERT INTO temp.vector_prune_scan(rowid, memory_id, content_hash) VALUES (?, ?, ?) /* vector-target-prune-spill */\",\n\t);\n\tconst insertScanPage = db.transaction((rows: TargetVectorRow[]) => {\n\t\tfor (const row of rows) insertScanRow.run(row.rowid, row.memory_id, row.content_hash);\n\t});\n\tlet afterRowId = 0;\n\twhile (!signal?.aborted) {\n\t\tconst rowIds = selectRowIds.all(afterRowId, batchSize) as Array<{ rowid: number }>;\n\t\tif (signal?.aborted) return false;\n\t\tif (rowIds.length === 0) return true;\n\t\tconst targetRows: TargetVectorRow[] = [];\n\t\tfor (const { rowid } of rowIds) {\n\t\t\tif (signal?.aborted) return false;\n\t\t\tconst metadata = selectMetadata.get(rowid) as\n\t\t\t\t| { memory_id: number; content_hash: string | null; model: string }\n\t\t\t\t| undefined;\n\t\t\tif (!metadata || metadata.model !== model) continue;\n\t\t\ttargetRows.push({\n\t\t\t\trowid,\n\t\t\t\tmemory_id: metadata.memory_id,\n\t\t\t\tcontent_hash: metadata.content_hash,\n\t\t\t});\n\t\t}\n\t\tif (signal?.aborted) return false;\n\t\tinsertScanPage.deferred(targetRows);\n\t\tafterRowId = rowIds.at(-1)?.rowid ?? afterRowId;\n\t\tif (rowIds.length < batchSize) return true;\n\t}\n\treturn false;\n}\n\nfunction visitTargetVectorRowsForMemories(\n\tdb: Database,\n\tmemoryIds: number[],\n\tbatchSize: number,\n\tvisit: (rows: TargetVectorRow[]) => void,\n\tsignal?: AbortSignal,\n): boolean {\n\tif (memoryIds.length === 0) return true;\n\tconst placeholders = memoryIds.map(() => \"?\").join(\", \");\n\tconst selectRows = db.prepare(\n\t\t`SELECT rowid, memory_id, content_hash FROM temp.vector_prune_scan\n\t\t WHERE memory_id IN (${placeholders}) AND rowid > ?\n\t\t ORDER BY rowid ASC LIMIT ? /* vector-target-prune-spill-page */`,\n\t);\n\tlet afterRowId = 0;\n\twhile (!signal?.aborted) {\n\t\tconst rows = selectRows.all(...memoryIds, afterRowId, batchSize) as TargetVectorRow[];\n\t\tif (signal?.aborted) return false;\n\t\tif (rows.length === 0) return true;\n\t\tvisit(rows);\n\t\tafterRowId = rows.at(-1)?.rowid ?? afterRowId;\n\t\tif (rows.length < batchSize) return true;\n\t}\n\treturn false;\n}\n\nfunction deleteVectorRows(db: Database, rowIds: number[]): number {\n\tconst write = prepareVectorWrites(db);\n\treturn db.transaction(() => write({ deleteRowIds: rowIds }).deleted).immediate();\n}\n\nfunction createTargetVectorCoverageStates(\n\tmemories: MemoryTextRow[],\n): Map<number, TargetVectorCoverageState> {\n\treturn new Map(\n\t\tmemories.map((memory): [number, TargetVectorCoverageState] => {\n\t\t\tconst expectedHashes = chunkHashes(memoryText(memory.title, memory.body_text));\n\t\t\treturn [\n\t\t\t\tmemory.id,\n\t\t\t\t{ expectedHashes, expected: new Set(expectedHashes), existing: new Set<string>() },\n\t\t\t];\n\t\t}),\n\t);\n}\n\nfunction summarizeTargetVectorCoverage(states: Map<number, TargetVectorCoverageState>): {\n\tcoveredMemoryIds: number[];\n\tincomplete: number;\n} {\n\tconst coveredMemoryIds: number[] = [];\n\tlet incomplete = 0;\n\tfor (const [memoryId, state] of states) {\n\t\tif (!expectedHashSetContains(state.expectedHashes, state.existing)) incomplete++;\n\t\telse coveredMemoryIds.push(memoryId);\n\t}\n\treturn { coveredMemoryIds, incomplete };\n}\n\nfunction pruneCoveredTargetVectorRows(\n\tdb: Database,\n\tstates: Map<number, TargetVectorCoverageState>,\n\tmemoryIds: number[],\n\tbatchSize: number,\n\tsignal?: AbortSignal,\n): { completed: boolean; deleted: number } {\n\tlet deleted = 0;\n\tconst completed = visitTargetVectorRowsForMemories(\n\t\tdb,\n\t\tmemoryIds,\n\t\tbatchSize,\n\t\t(rows) => {\n\t\t\tconst obsolete = rows\n\t\t\t\t.filter((row) => {\n\t\t\t\t\tconst expected = states.get(row.memory_id)?.expected;\n\t\t\t\t\treturn row.content_hash == null || !expected?.has(row.content_hash);\n\t\t\t\t})\n\t\t\t\t.map((row) => row.rowid);\n\t\t\tif (obsolete.length > 0) deleted += deleteVectorRows(db, obsolete);\n\t\t},\n\t\tsignal,\n\t);\n\treturn { completed, deleted };\n}\n\nfunction pruneActiveMemoryPage(\n\tdb: Database,\n\tmemories: MemoryTextRow[],\n\tbatchSize: number,\n\tsignal?: AbortSignal,\n): { completed: boolean; deleted: number; incomplete: number } {\n\tconst states = createTargetVectorCoverageStates(memories);\n\tconst memoryIds = memories.map((memory) => memory.id);\n\tconst covered = visitTargetVectorRowsForMemories(\n\t\tdb,\n\t\tmemoryIds,\n\t\tbatchSize,\n\t\t(rows) => {\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst state = states.get(row.memory_id);\n\t\t\t\tif (row.content_hash != null && state?.expected.has(row.content_hash)) {\n\t\t\t\t\tstate.existing.add(row.content_hash);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tsignal,\n\t);\n\tif (!covered) return { completed: false, deleted: 0, incomplete: 0 };\n\tconst coverage = summarizeTargetVectorCoverage(states);\n\tconst pruned = pruneCoveredTargetVectorRows(\n\t\tdb,\n\t\tstates,\n\t\tcoverage.coveredMemoryIds,\n\t\tbatchSize,\n\t\tsignal,\n\t);\n\tif (!pruned.completed) {\n\t\treturn { completed: false, deleted: pruned.deleted, incomplete: coverage.incomplete };\n\t}\n\tconst placeholders = memoryIds.map(() => \"?\").join(\", \");\n\tdb.prepare(`DELETE FROM temp.vector_prune_scan WHERE memory_id IN (${placeholders})`).run(\n\t\t...memoryIds,\n\t);\n\treturn { completed: true, deleted: pruned.deleted, incomplete: coverage.incomplete };\n}\n\nfunction pruneRemainingTargetVectorRows(\n\tdb: Database,\n\tbatchSize: number,\n\tsignal?: AbortSignal,\n): { completed: boolean; deleted: number } {\n\tconst selectRows = db.prepare(\n\t\t`SELECT rowid, memory_id, content_hash FROM temp.vector_prune_scan\n\t\t WHERE rowid > ? ORDER BY rowid ASC LIMIT ? /* vector-target-prune-spill-remainder */`,\n\t);\n\tlet afterRowId = 0;\n\tlet deleted = 0;\n\twhile (!signal?.aborted) {\n\t\tconst rows = selectRows.all(afterRowId, batchSize) as TargetVectorRow[];\n\t\tif (signal?.aborted) return { completed: false, deleted };\n\t\tif (rows.length === 0) return { completed: true, deleted };\n\t\tdeleted += deleteVectorRows(\n\t\t\tdb,\n\t\t\trows.map((row) => row.rowid),\n\t\t);\n\t\tafterRowId = rows.at(-1)?.rowid ?? afterRowId;\n\t\tif (rows.length < batchSize) return { completed: true, deleted };\n\t}\n\treturn { completed: false, deleted };\n}\n\nfunction pruneTargetVectorRowsFromShadowTable(\n\tdb: Database,\n\tmodel: string,\n\toptions: { signal?: AbortSignal },\n): { deleted: number; incompleteActiveCoverage: number | null } {\n\tconst batchSize = 250;\n\t// The connection defaults to temp_store=MEMORY, which would keep the spill\n\t// resident in SQLite's heap and leave peak memory O(total vectors). Force it\n\t// to disk for the prune so the bound is genuinely one page. temp_store cannot\n\t// change while temp tables exist, so this must bracket the CREATE/DROP.\n\tconst previousTempStore = readTempStore(db);\n\tdb.pragma(\"temp_store = FILE\");\n\ttry {\n\t\treturn pruneTargetVectorRowsWithSpill(db, model, batchSize, options.signal);\n\t} finally {\n\t\tdb.pragma(`temp_store = ${previousTempStore}`);\n\t}\n}\n\nfunction readTempStore(db: Database): number {\n\tconst value = db.pragma(\"temp_store\", { simple: true });\n\treturn typeof value === \"number\" ? value : 0;\n}\n\nfunction pruneTargetVectorRowsWithSpill(\n\tdb: Database,\n\tmodel: string,\n\tbatchSize: number,\n\tsignal: AbortSignal | undefined,\n): { deleted: number; incompleteActiveCoverage: number | null } {\n\tconst options = { signal };\n\tdb.exec(`CREATE TEMP TABLE IF NOT EXISTS vector_prune_scan (\n\t\trowid INTEGER PRIMARY KEY,\n\t\tmemory_id INTEGER NOT NULL,\n\t\tcontent_hash TEXT\n\t)`);\n\ttry {\n\t\tdb.exec(\n\t\t\t\"CREATE INDEX IF NOT EXISTS temp.vector_prune_scan_memory_id_idx ON vector_prune_scan(memory_id)\",\n\t\t);\n\t\tdb.exec(\"DELETE FROM temp.vector_prune_scan\");\n\t\tif (!collectTargetVectorRows(db, model, batchSize, options.signal)) {\n\t\t\treturn { deleted: 0, incompleteActiveCoverage: null };\n\t\t}\n\t\tconst selectMemories = db.prepare(\n\t\t\t`SELECT id, title, body_text FROM memory_items\n\t\t\t WHERE active = 1 AND id > ?\n\t\t\t ORDER BY id ASC LIMIT ?`,\n\t\t);\n\t\tlet afterMemoryId = 0;\n\t\tlet deleted = 0;\n\t\tlet incompleteActiveCoverage = 0;\n\t\twhile (!options.signal?.aborted) {\n\t\t\tconst memories = selectMemories.all(afterMemoryId, batchSize) as MemoryTextRow[];\n\t\t\tif (memories.length === 0) break;\n\t\t\tconst result = pruneActiveMemoryPage(db, memories, batchSize, options.signal);\n\t\t\tdeleted += result.deleted;\n\t\t\tif (!result.completed) return { deleted, incompleteActiveCoverage: null };\n\t\t\tincompleteActiveCoverage += result.incomplete;\n\t\t\tafterMemoryId = memories.at(-1)?.id ?? afterMemoryId;\n\t\t}\n\t\tif (options.signal?.aborted) return { deleted, incompleteActiveCoverage: null };\n\t\tconst remaining = pruneRemainingTargetVectorRows(db, batchSize, options.signal);\n\t\tdeleted += remaining.deleted;\n\t\treturn {\n\t\t\tdeleted,\n\t\t\tincompleteActiveCoverage: remaining.completed ? incompleteActiveCoverage : null,\n\t\t};\n\t} finally {\n\t\tdb.exec(\"DROP TABLE IF EXISTS temp.vector_prune_scan\");\n\t}\n}\n\nfunction pruneTargetVectorRowsWithLegacyScan(\n\tdb: Database,\n\tmodel: string,\n\toptions: { signal?: AbortSignal },\n): number {\n\tconst batchSize = 250;\n\tlet afterRowId = 0;\n\tlet deleted = 0;\n\tconst selectBatch = db.prepare(\n\t\t`SELECT mv.rowid AS rowid, mv.memory_id AS memory_id, mv.content_hash AS content_hash,\n\t\t mi.title AS title, mi.body_text AS body_text, mi.active AS active\n\t\t FROM memory_vectors mv\n\t\t LEFT JOIN memory_items mi ON mi.id = mv.memory_id\n\t\t WHERE mv.model = ? AND mv.rowid > ?\n\t\t ORDER BY mv.rowid ASC\n\t\t LIMIT ?`,\n\t);\n\tconst write = prepareVectorWrites(db);\n\twhile (!options.signal?.aborted) {\n\t\tconst rows = selectBatch.all(model, afterRowId, batchSize) as Array<\n\t\t\tTargetVectorRow & { title: string | null; body_text: string | null; active: number | null }\n\t\t>;\n\t\tif (rows.length === 0) break;\n\t\tconst obsoleteRowIds: number[] = [];\n\t\tconst expectedByMemory = new Map<number, Set<string>>();\n\t\tconst coverageByMemory = new Map<number, boolean>();\n\t\tfor (const row of rows) {\n\t\t\tif (row.active == null || row.active === 0) {\n\t\t\t\tobsoleteRowIds.push(row.rowid);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlet covered = coverageByMemory.get(row.memory_id);\n\t\t\tif (covered === undefined) {\n\t\t\t\tcovered = memoryHasCompleteVectorCoverage(\n\t\t\t\t\tdb,\n\t\t\t\t\t{ id: row.memory_id, title: row.title, body_text: row.body_text },\n\t\t\t\t\tmodel,\n\t\t\t\t);\n\t\t\t\tcoverageByMemory.set(row.memory_id, covered);\n\t\t\t}\n\t\t\tif (!covered) continue;\n\t\t\tconst expected =\n\t\t\t\texpectedByMemory.get(row.memory_id) ??\n\t\t\t\tnew Set(chunkHashes(memoryText(row.title, row.body_text)));\n\t\t\texpectedByMemory.set(row.memory_id, expected);\n\t\t\tif (row.content_hash == null || !expected.has(row.content_hash)) {\n\t\t\t\tobsoleteRowIds.push(row.rowid);\n\t\t\t}\n\t\t}\n\t\tdeleted += db.transaction(() => write({ deleteRowIds: obsoleteRowIds }).deleted).immediate();\n\t\tafterRowId = rows.at(-1)?.rowid ?? afterRowId;\n\t}\n\treturn deleted;\n}\n\n/**\n * Delete target-model vector rows whose content_hash is not part of their\n * memory's current chunk set. Coverage is a subset check, so a memory can be\n * \"covered\" while still retaining obsolete target rows — e.g. an interrupted\n * migration, or a title/body edit (like `codemem db scan-secrets` redaction)\n * without vector maintenance. Because semanticSearch ranks by MIN(distance)\n * across a memory's rows, those stale rows would keep pre-edit or redacted\n * content influencing recall after cutover. Incomplete memories are left\n * untouched so their current rows can still be repaired safely. Returns the\n * number of rows removed.\n */\nexport function pruneObsoleteTargetModelVectors(\n\tdb: Database,\n\tmodel: string,\n\toptions: { signal?: AbortSignal } = {},\n): number {\n\treturn pruneObsoleteTargetModelVectorsWithCoverage(db, model, options).deleted;\n}\n\nexport function pruneObsoleteTargetModelVectorsWithCoverage(\n\tdb: Database,\n\tmodel: string,\n\toptions: { signal?: AbortSignal } = {},\n): { deleted: number; incompleteActiveCoverage: number | null } {\n\tif (!hasMemoryVectorRowidsShadowTable(db)) {\n\t\treturn {\n\t\t\tdeleted: pruneTargetVectorRowsWithLegacyScan(db, model, options),\n\t\t\tincompleteActiveCoverage: null,\n\t\t};\n\t}\n\treturn pruneTargetVectorRowsFromShadowTable(db, model, options);\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface BackfillVectorsResult {\n\tchecked: number;\n\tembedded: number;\n\tinserted: number;\n\tskipped: number;\n}\n\nexport interface BackfillVectorsOptions {\n\tlimit?: number | null;\n\tsince?: string | null;\n\tproject?: string | null;\n\tactiveOnly?: boolean;\n\tdryRun?: boolean;\n\tmemoryIds?: number[] | null;\n\t/**\n\t * When provided, backfill stops between inference batches. The in-flight\n\t * batch finishes, and any memory with only partial output remains unwritten.\n\t * Used by the viewer serve shutdown sequence to bound SIGTERM latency.\n\t */\n\tsignal?: AbortSignal;\n\t/** Use an already-resolved client so vectors and their persisted label cannot diverge. */\n\tclient?: EmbeddingClient;\n}\n\nexport interface ReplicationVectorMaintenanceResult {\n\tdeleted: number;\n\tinserted: number;\n\terrors: string[];\n}\n\nexport type SemanticIndexState = \"healthy\" | \"pending\" | \"failed\" | \"degraded\" | \"disabled\";\n\nexport interface SemanticIndexDiagnostics {\n\tstate: SemanticIndexState;\n\tsummary: string;\n\tmode: \"semantic\" | \"keyword_only\";\n\tcurrent_model: string;\n\tsemantic_search_model: string | null;\n\tembeddable_memory_count: number;\n\tindexed_memory_count: number;\n\tpending_memory_count: number;\n\tmaintenance_job: {\n\t\tstatus: \"pending\" | \"running\" | \"failed\" | \"completed\" | \"cancelled\";\n\t\tmessage: string | null;\n\t\terror: string | null;\n\t\tprogress_current: number;\n\t\tprogress_total: number | null;\n\t} | null;\n}\n\nexport interface SemanticIndexDiagnosticsOptions {\n\t/**\n\t * Default true — runs a single indexed COUNT(DISTINCT) join. The slow\n\t * alternative does a vec0 probe per memory row, which blocks the event\n\t * loop; only set to false from non-request-path tooling that needs\n\t * per-chunk coverage precision.\n\t */\n\tfastCounts?: boolean;\n}\n\nfunction traceSemanticDiag<T>(label: string, fn: () => T): T {\n\tif (process.env.CODEMEM_TRACE_SEMANTIC_DIAGNOSTICS !== \"1\") return fn();\n\tconst startedAt = Date.now();\n\tconsole.warn(`[codemem semantic] ${label} start`);\n\ttry {\n\t\treturn fn();\n\t} finally {\n\t\tconsole.warn(`[codemem semantic] ${label} ${Date.now() - startedAt}ms`);\n\t}\n}\n\nfunction countEmbeddableActiveMemories(db: Database): number {\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT COUNT(*) AS c\n\t\t\t FROM memory_items\n\t\t\t WHERE active = 1\n\t\t\t AND TRIM(COALESCE(title, '') || COALESCE(body_text, '')) != ''`,\n\t\t)\n\t\t.get() as { c?: number } | undefined;\n\treturn Number(row?.c ?? 0);\n}\n\n/**\n * `memory_vectors` is a sqlite-vec virtual table. Querying it requires the\n * `vec0` module to be loaded into the active connection — a different\n * concern from the table merely existing in the schema. On platforms where\n * sqlite-vec failed to load (e.g. Linux ARM64 without the matching\n * platform package), the table can persist from a previous run while the\n * module is gone, so a JOIN crashes with `SQLITE_ERROR: no such module:\n * vec0`. Diagnostic counters must treat that case as \"0 indexed\", same as\n * the explicit `CODEMEM_EMBEDDING_DISABLED` path, instead of throwing.\n */\nfunction isVecModuleMissingError(error: unknown): boolean {\n\tif (!(error instanceof Error)) return false;\n\tconst message = error.message ?? \"\";\n\treturn /no such module:\\s*vec0/i.test(message);\n}\n\nfunction countIndexedActiveMemories(db: Database, models: string[]): number {\n\tif (isEmbeddingDisabled() || !vectorStoreExists(db)) return 0;\n\tlet rows: MemoryTextRow[];\n\ttry {\n\t\trows = db\n\t\t\t.prepare(\n\t\t\t\t`SELECT id, title, body_text\n\t\t\t\t FROM memory_items\n\t\t\t\t WHERE active = 1\n\t\t\t\t AND TRIM(COALESCE(title, '') || COALESCE(body_text, '')) != ''\n\t\t\t\t ORDER BY id ASC`,\n\t\t\t)\n\t\t\t.all() as MemoryTextRow[];\n\t} catch (error) {\n\t\tif (isVecModuleMissingError(error)) return 0;\n\t\tthrow error;\n\t}\n\ttry {\n\t\treturn withVectorMetadataSnapshot(db, (metadata) => {\n\t\t\tconst selectHash = prepareSnapshotHashQuery(metadata);\n\t\t\treturn rows.filter((row) =>\n\t\t\t\tmodels.some((model) => memoryHasSnapshotCoverage(selectHash, row, model)),\n\t\t\t).length;\n\t\t});\n\t} catch (error) {\n\t\tif (isVecModuleMissingError(error)) return 0;\n\t\tthrow error;\n\t}\n}\n\nfunction countIndexedActiveMemoriesFast(db: Database, models: string[]): number {\n\tif (isEmbeddingDisabled() || !vectorStoreExists(db)) return 0;\n\ttry {\n\t\tconst placeholders = models.map(() => \"?\").join(\", \");\n\t\tconst row = db\n\t\t\t.prepare(\n\t\t\t\t`SELECT COUNT(DISTINCT mi.id) AS c\n\t\t\t\t FROM memory_items mi\n\t\t\t\t JOIN memory_vectors mv ON mv.memory_id = mi.id\n\t\t\t\t WHERE mi.active = 1\n\t\t\t\t AND mv.model IN (${placeholders})\n\t\t\t\t AND TRIM(COALESCE(mi.title, '') || COALESCE(mi.body_text, '')) != ''`,\n\t\t\t)\n\t\t\t.get(...models) as { c?: number } | undefined;\n\t\treturn Number(row?.c ?? 0);\n\t} catch (error) {\n\t\tif (isVecModuleMissingError(error)) return 0;\n\t\tthrow error;\n\t}\n}\n\nfunction resolvePendingMemoryCount(\n\tfallbackPendingCount: number,\n\tjob: ReturnType<typeof getMaintenanceJob>,\n): number {\n\tif (!(job?.status === \"pending\" || job?.status === \"running\" || job?.status === \"failed\")) {\n\t\treturn fallbackPendingCount;\n\t}\n\tconst metadata = job?.metadata ?? {};\n\tconst total = Number(metadata.embeddable_total ?? job?.progress.total ?? Number.NaN);\n\tconst processed = Number(metadata.processed_embeddable ?? job?.progress.current ?? Number.NaN);\n\tif (Number.isFinite(total) && Number.isFinite(processed)) {\n\t\treturn Math.max(total - processed, 0);\n\t}\n\treturn fallbackPendingCount;\n}\n\nfunction summarizeSemanticIndexState(\n\tstate: SemanticIndexState,\n\tcounts: { embeddable: number; indexed: number; pending: number },\n\tjob: ReturnType<typeof getMaintenanceJob>,\n\truntimeUnavailable: boolean,\n): string {\n\tif (state === \"failed\") {\n\t\treturn job?.error ?? job?.message ?? \"Semantic-index catch-up failed\";\n\t}\n\tif (state === \"disabled\") {\n\t\treturn \"Semantic search is off because embeddings are disabled; keyword search remains available\";\n\t}\n\tif (state === \"degraded\") {\n\t\tif (runtimeUnavailable) {\n\t\t\treturn \"The embedding runtime is unavailable; sync data is available in keyword-only mode\";\n\t\t}\n\t\treturn \"Semantic-index coverage is unavailable; sync data is effectively running in keyword-only mode\";\n\t}\n\tif (state === \"pending\") {\n\t\tconst jobActive = job?.status === \"pending\" || job?.status === \"running\";\n\t\tconst jobMessage = jobActive ? job?.message : null;\n\t\treturn jobMessage ?? `${counts.pending} memory(s) still need semantic indexing`;\n\t}\n\tif (counts.embeddable === 0) {\n\t\treturn \"No embeddable memories need semantic indexing\";\n\t}\n\treturn `Semantic index is current for ${counts.indexed} embeddable mem${counts.indexed === 1 ? \"ory\" : \"ories\"}`;\n}\n\nfunction resolveSemanticIndexState(options: {\n\tembeddingsDisabled: boolean;\n\tembeddingRevisionMissing: boolean;\n\tidentityLabelUnresolved: boolean;\n\tjobStatus: NonNullable<ReturnType<typeof getMaintenanceJob>>[\"status\"] | undefined;\n\tactiveCatchUp: boolean;\n\tdegraded: boolean;\n\tpendingMemoryCount: number;\n}): SemanticIndexState {\n\t// Disabled embeddings also stop the catch-up runner, so a queued job would\n\t// otherwise read as pending forever.\n\tif (options.embeddingsDisabled) return \"disabled\";\n\tif (options.embeddingRevisionMissing) return \"degraded\";\n\tif (options.jobStatus === \"failed\") return \"failed\";\n\tif (options.identityLabelUnresolved) return \"pending\";\n\tif (options.activeCatchUp) return \"pending\";\n\tif (options.degraded) return \"degraded\";\n\tif (options.pendingMemoryCount > 0) return \"pending\";\n\treturn \"healthy\";\n}\n\nfunction resolveSemanticRuntime(db: Database): {\n\tembeddingModel: string;\n\tembeddingRevision: string | null;\n\tcurrentModel: string;\n\tsemanticSearchModel: string | null;\n\tembeddingsDisabled: boolean;\n\truntimeUnavailable: boolean;\n\tembeddingRevisionMissing: boolean;\n\tidentityLabelUnresolved: boolean;\n} {\n\tconst embeddingModel = traceSemanticDiag(\"resolveEmbeddingModel\", () => resolveEmbeddingModel());\n\tconst embeddingRevision = traceSemanticDiag(\"tryResolveEmbeddingRevision\", () =>\n\t\ttryResolveEmbeddingRevision(embeddingModel),\n\t);\n\tconst resolvedCurrentModel = traceSemanticDiag(\"tryResolveConfiguredVectorIdentityLabel\", () =>\n\t\ttryResolveConfiguredVectorIdentityLabel(db),\n\t);\n\tconst embeddingRevisionMissing = embeddingRevision == null;\n\tconst identityLabelUnresolved = !embeddingRevisionMissing && resolvedCurrentModel == null;\n\tconst currentModel =\n\t\tresolvedCurrentModel ??\n\t\t(embeddingRevision == null\n\t\t\t? `${embeddingModel} (missing CODEMEM_EMBEDDING_REVISION)`\n\t\t\t: `${embeddingModel}@${embeddingRevision} (revision unresolved)`);\n\tconst semanticSearchModel =\n\t\tembeddingRevisionMissing || identityLabelUnresolved\n\t\t\t? null\n\t\t\t: traceSemanticDiag(\"resolveSemanticSearchModel\", () =>\n\t\t\t\t\tresolveSemanticSearchModel(db, currentModel),\n\t\t\t\t);\n\tconst embeddingsDisabled = traceSemanticDiag(\"isEmbeddingDisabled\", () => isEmbeddingDisabled());\n\tconst runtimeUnavailable = getEmbeddingRuntimeStatus().state === \"unavailable\";\n\treturn {\n\t\tembeddingModel,\n\t\tembeddingRevision,\n\t\tcurrentModel,\n\t\tsemanticSearchModel,\n\t\tembeddingsDisabled,\n\t\truntimeUnavailable,\n\t\tembeddingRevisionMissing,\n\t\tidentityLabelUnresolved,\n\t};\n}\n\nfunction collectSemanticIndexCounts(\n\tdb: Database,\n\tcoverageModels: string[],\n\tfastCounts: boolean,\n): { embeddableMemoryCount: number; indexedMemoryCount: number } {\n\tconst embeddableMemoryCount = traceSemanticDiag(\"countEmbeddableActiveMemories\", () =>\n\t\tcountEmbeddableActiveMemories(db),\n\t);\n\tconst indexedMemoryCount = traceSemanticDiag(\n\t\tfastCounts ? \"countIndexedActiveMemoriesFast\" : \"countIndexedActiveMemories\",\n\t\t() =>\n\t\t\tfastCounts\n\t\t\t\t? countIndexedActiveMemoriesFast(db, coverageModels)\n\t\t\t\t: countIndexedActiveMemories(db, coverageModels),\n\t);\n\treturn { embeddableMemoryCount, indexedMemoryCount };\n}\n\ntype SemanticRuntime = ReturnType<typeof resolveSemanticRuntime>;\n\nfunction collectSemanticCoverage(\n\tdb: Database,\n\truntime: SemanticRuntime,\n\tfastCounts: boolean,\n): { embeddableMemoryCount: number; indexedMemoryCount: number } {\n\tif (runtime.embeddingRevisionMissing || runtime.identityLabelUnresolved) {\n\t\tconst embeddableMemoryCount = traceSemanticDiag(\"countEmbeddableActiveMemories\", () =>\n\t\t\tcountEmbeddableActiveMemories(db),\n\t\t);\n\t\treturn { embeddableMemoryCount, indexedMemoryCount: 0 };\n\t}\n\t// Count coverage under the same model labels search reads, so a corpus\n\t// served from compatible legacy vectors is not reported as unindexed.\n\tconst searchModels = expandSemanticSearchModels(\n\t\tdb,\n\t\truntime.semanticSearchModel,\n\t\truntime.currentModel,\n\t);\n\treturn collectSemanticIndexCounts(\n\t\tdb,\n\t\tsearchModels.length > 0 ? searchModels : [runtime.currentModel],\n\t\tfastCounts,\n\t);\n}\n\nfunction describeSemanticIndex(\n\tstate: SemanticIndexState,\n\truntime: SemanticRuntime,\n\tcounts: { embeddable: number; indexed: number; pending: number },\n\tjob: ReturnType<typeof getMaintenanceJob>,\n): string {\n\tif (state !== \"disabled\" && runtime.embeddingRevisionMissing) {\n\t\treturn `Semantic search is unavailable because ${runtime.embeddingModel} has no CODEMEM_EMBEDDING_REVISION; keyword search remains available`;\n\t}\n\tif (state !== \"disabled\" && runtime.identityLabelUnresolved) {\n\t\treturn `Semantic indexing is pending until ${runtime.embeddingModel}@${runtime.embeddingRevision} resolves to a canonical commit`;\n\t}\n\treturn summarizeSemanticIndexState(state, counts, job, runtime.runtimeUnavailable);\n}\n\nexport function getSemanticIndexDiagnostics(\n\tdb: Database,\n\toptions: SemanticIndexDiagnosticsOptions = {},\n): SemanticIndexDiagnostics {\n\tconst runtime = resolveSemanticRuntime(db);\n\tconst {\n\t\tcurrentModel,\n\t\tsemanticSearchModel,\n\t\tembeddingsDisabled,\n\t\truntimeUnavailable,\n\t\tembeddingRevisionMissing,\n\t\tidentityLabelUnresolved,\n\t} = runtime;\n\tconst { embeddableMemoryCount, indexedMemoryCount } = collectSemanticCoverage(\n\t\tdb,\n\t\truntime,\n\t\toptions.fastCounts !== false,\n\t);\n\tconst fallbackPendingCount = Math.max(embeddableMemoryCount - indexedMemoryCount, 0);\n\tconst job = traceSemanticDiag(\"getMaintenanceJob\", () =>\n\t\tgetMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB),\n\t);\n\tconst pendingMemoryCount = resolvePendingMemoryCount(fallbackPendingCount, job);\n\tconst degraded =\n\t\tembeddingRevisionMissing ||\n\t\t(embeddableMemoryCount > 0 &&\n\t\t\t(embeddingsDisabled || runtimeUnavailable || semanticSearchModel == null));\n\tconst state = resolveSemanticIndexState({\n\t\tembeddingsDisabled,\n\t\tembeddingRevisionMissing,\n\t\tidentityLabelUnresolved,\n\t\tjobStatus: job?.status,\n\t\tactiveCatchUp: job?.status === \"pending\" || job?.status === \"running\",\n\t\tdegraded,\n\t\tpendingMemoryCount,\n\t});\n\tconst summary = describeSemanticIndex(\n\t\tstate,\n\t\truntime,\n\t\t{ embeddable: embeddableMemoryCount, indexed: indexedMemoryCount, pending: pendingMemoryCount },\n\t\tjob,\n\t);\n\n\treturn {\n\t\tstate,\n\t\tsummary,\n\t\tmode:\n\t\t\tembeddingsDisabled || runtimeUnavailable || !semanticSearchModel\n\t\t\t\t? \"keyword_only\"\n\t\t\t\t: \"semantic\",\n\t\tcurrent_model: currentModel,\n\t\tsemantic_search_model: semanticSearchModel,\n\t\tembeddable_memory_count: embeddableMemoryCount,\n\t\tindexed_memory_count: indexedMemoryCount,\n\t\tpending_memory_count: pendingMemoryCount,\n\t\tmaintenance_job: job\n\t\t\t? {\n\t\t\t\t\tstatus: job.status,\n\t\t\t\t\tmessage: job.message,\n\t\t\t\t\terror: job.error,\n\t\t\t\t\tprogress_current: job.progress.current,\n\t\t\t\t\tprogress_total: job.progress.total,\n\t\t\t\t}\n\t\t\t: null,\n\t};\n}\n\nfunction uniqueMemoryIds(memoryIds: number[]): number[] {\n\treturn [...new Set(memoryIds.filter((memoryId) => Number.isInteger(memoryId) && memoryId > 0))];\n}\n\nfunction deleteVectorsForMemoryIds(db: Database, memoryIds: number[]): number {\n\tif (!vectorStoreExists(db) || memoryIds.length === 0) return 0;\n\tconst write = prepareVectorWrites(db);\n\treturn db.transaction(() => write({ deleteMemoryIds: memoryIds }).deleted).immediate();\n}\n\nfunction prepareSnapshotPruneQueries(metadata: Database, rowIds: number[]) {\n\treturn {\n\t\tselectHash: prepareSnapshotHashQuery(metadata),\n\t\tselectRows: metadata.prepare(\n\t\t\t\"SELECT rowid, model, content_hash FROM vector_metadata WHERE memory_id = ? AND model IN (?, ?)\",\n\t\t),\n\t\trowIds,\n\t};\n}\n\nfunction pruneSnapshotMemoryRows(\n\t{ selectHash, selectRows, rowIds }: ReturnType<typeof prepareSnapshotPruneQueries>,\n\tmemory: MemoryTextRow,\n\tmodel: string,\n): void {\n\tconst expectedHashes = chunkHashes(memoryText(memory.title, memory.body_text));\n\tif (!snapshotHasExpectedHashes(selectHash, memory.id, model, expectedHashes)) return;\n\tconst expected = new Set(expectedHashes);\n\tconst compatibleLegacyModel =\n\t\tmodel === DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL ? LEGACY_DEFAULT_EMBEDDING_MODEL : null;\n\tfor (const row of selectRows.iterate(memory.id, model, compatibleLegacyModel) as Iterable<{\n\t\trowid: number;\n\t\tmodel: string;\n\t\tcontent_hash: string | null;\n\t}>) {\n\t\tif (row.model === model && row.content_hash != null && expected.has(row.content_hash)) continue;\n\t\trowIds.push(row.rowid);\n\t}\n}\n\n/**\n * Prune stale target rows only after the memory's current target hashes are\n * complete. For the revision-aware default identity, also remove that memory's\n * compatible legacy rows so covered memories no longer rank on pre-edit content.\n */\nexport function pruneStaleCurrentModelVectors(\n\tdb: Database,\n\tmemoryIds: number[],\n\tmodel: string,\n): number {\n\tconst ids = uniqueMemoryIds(memoryIds);\n\tif (ids.length === 0) return 0;\n\tconst batchSize = 250;\n\tconst write = prepareVectorWrites(db);\n\tlet deleted = 0;\n\n\tfor (let offset = 0; offset < ids.length; offset += batchSize) {\n\t\tconst batchIds = ids.slice(offset, offset + batchSize);\n\t\tconst placeholders = batchIds.map(() => \"?\").join(\", \");\n\t\tconst pruneCoveredMemories = db.transaction(() =>\n\t\t\twithVectorMetadataSnapshot(\n\t\t\t\tdb,\n\t\t\t\t(metadata) => {\n\t\t\t\t\tconst rowIds: number[] = [];\n\t\t\t\t\tconst queries = prepareSnapshotPruneQueries(metadata, rowIds);\n\t\t\t\t\tconst rows = db\n\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t`SELECT id, title, body_text FROM memory_items\n\t\t\t\t\t WHERE id IN (${placeholders}) ORDER BY id ASC`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.all(...batchIds) as MemoryTextRow[];\n\t\t\t\t\tfor (const row of rows) {\n\t\t\t\t\t\tpruneSnapshotMemoryRows(queries, row, model);\n\t\t\t\t\t}\n\t\t\t\t\treturn write({ deleteRowIds: rowIds }).deleted;\n\t\t\t\t},\n\t\t\t\t{ memoryIds: batchIds },\n\t\t\t),\n\t\t);\n\t\tdeleted += pruneCoveredMemories.immediate();\n\t}\n\n\treturn deleted;\n}\n\n/**\n * Fallback-only sync maintenance path used when durable incremental queueing\n * fails after inbound replication has already been applied. New sync code\n * should prefer queueVectorBackfillForIncrementalSync so work survives restart.\n */\nexport async function bestEffortMaintainVectorsForSyncFallback(\n\tdb: Database,\n\twork: ReplicationVectorWork,\n): Promise<ReplicationVectorMaintenanceResult> {\n\tconst result: ReplicationVectorMaintenanceResult = { deleted: 0, inserted: 0, errors: [] };\n\tconst deleteMemoryIds = uniqueMemoryIds(work.deleteMemoryIds);\n\tconst upsertMemoryIds = uniqueMemoryIds(work.upsertMemoryIds);\n\n\tif (!vectorStoreExists(db)) {\n\t\treturn result;\n\t}\n\n\ttry {\n\t\tresult.deleted += deleteVectorsForMemoryIds(db, deleteMemoryIds);\n\t} catch (error) {\n\t\tresult.errors.push(\n\t\t\t`delete vectors failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t);\n\t}\n\n\tif (upsertMemoryIds.length === 0) return result;\n\n\ttry {\n\t\tconst client = await getEmbeddingClient();\n\t\tconst backfill = await backfillVectors(db, {\n\t\t\tmemoryIds: upsertMemoryIds,\n\t\t\tclient: client ?? undefined,\n\t\t});\n\t\tresult.inserted = backfill.inserted;\n\t\tif (backfill.checked > 0 && client) {\n\t\t\tresult.deleted += pruneStaleCurrentModelVectors(\n\t\t\t\tdb,\n\t\t\t\tupsertMemoryIds,\n\t\t\t\tresolveEmbeddingClientVectorIdentityLabel(client),\n\t\t\t);\n\t\t}\n\t} catch (error) {\n\t\tresult.errors.push(\n\t\t\t`backfill vectors failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t);\n\t}\n\n\treturn result;\n}\n\n// ---------------------------------------------------------------------------\n// storeVectors — called inline when a memory is created/remembered\n// ---------------------------------------------------------------------------\n\n/**\n * Embed and store vectors for a single memory item.\n * No-op when embeddings are disabled or the client is unavailable.\n */\nexport async function storeVectors(\n\tdb: Database,\n\tmemoryId: number,\n\ttitle: string,\n\tbodyText: string,\n\toptions: { signal?: AbortSignal } = {},\n): Promise<void> {\n\tif (options.signal?.aborted) return;\n\t// Capture before client initialization yields, so ID reuse during that wait is visible.\n\tconst source = readVectorSource(db, memoryId);\n\tconst client = await getEmbeddingClient();\n\tif (options.signal?.aborted) return;\n\tif (!client) return;\n\tassertEmbeddingClientIdentity(client);\n\tassertVectorMemoryId(memoryId);\n\tif (!source) return;\n\n\tconst text = `${title}\\n${bodyText}`.trim();\n\tconst chunks = chunkText(text);\n\tif (chunks.length === 0) return;\n\n\tconst embeddings = await embedTexts(chunks, client);\n\t// Inference cannot be canceled here; a closed owner must never commit its late result.\n\tif (options.signal?.aborted) return;\n\tif (embeddings.length !== chunks.length) throw new TypeError(\"vector_count_mismatch\");\n\n\tconst model = resolveEmbeddingClientVectorIdentityLabel(client);\n\tconst persistVectors = db.transaction(\n\t\t(entries: Array<{ vector: Float32Array; chunkIndex: number; contentHash: string }>) => {\n\t\t\tif (options.signal?.aborted) return;\n\t\t\tconst hashes = currentVectorSourceHashes(source, readVectorSource(db, memoryId));\n\t\t\tconst currentEntries = entries.filter(\n\t\t\t\t(entry) => hashes[entry.chunkIndex] === entry.contentHash,\n\t\t\t);\n\t\t\tif (currentEntries.length === 0) return;\n\t\t\tensureVectorWriteModel(db, model);\n\t\t\tprepareVectorWrites(db)({\n\t\t\t\tinsert: {\n\t\t\t\t\tmodel,\n\t\t\t\t\trows: currentEntries.map((entry) => ({ ...entry, memoryId })),\n\t\t\t\t\texpectedCount: currentEntries.length,\n\t\t\t\t},\n\t\t\t});\n\t\t\tpersistVectorIdentity(db, client, model);\n\t\t},\n\t);\n\tconst entries: Array<{ vector: Float32Array; chunkIndex: number; contentHash: string }> = [];\n\n\tfor (let i = 0; i < chunks.length; i++) {\n\t\tconst vector = embeddings[i];\n\t\tconst chunk = chunks[i];\n\t\tif (!vector || vector.length === 0) throw new TypeError(\"invalid_vector_shape\");\n\t\tif (!chunk) throw new TypeError(\"invalid_vector_chunk\");\n\t\tentries.push({ vector, chunkIndex: i, contentHash: hashText(chunk) });\n\t}\n\tif (entries.length === 0) return;\n\tpersistVectors.immediate(entries);\n}\n\n// ---------------------------------------------------------------------------\n// backfillVectors — CLI batch backfill\n// ---------------------------------------------------------------------------\n\nfunction insertCompletedBackfillMemories(\n\tdb: Database,\n\tcompleted: Set<PendingMemory>,\n\tmodel: string,\n): number {\n\tif (completed.size === 0) return 0;\n\tconst memoryIds = Array.from(completed, (memory) => memory.memoryId);\n\t// All memories completed by this inference batch intentionally commit or\n\t// roll back together; a write failure must not leave a partially inserted batch.\n\treturn db\n\t\t.transaction(() =>\n\t\t\twithVectorMetadataSnapshot(\n\t\t\t\tdb,\n\t\t\t\t(metadata) => {\n\t\t\t\t\tconst entries = collectCompletedBackfillRows(db, metadata, completed, model);\n\t\t\t\t\tif (!entries.length) return 0;\n\t\t\t\t\tensureVectorWriteModel(db, model);\n\t\t\t\t\treturn prepareVectorWrites(db)({\n\t\t\t\t\t\tinsert: { model, rows: entries, expectedCount: entries.length },\n\t\t\t\t\t}).inserted;\n\t\t\t\t},\n\t\t\t\t{ memoryIds },\n\t\t\t),\n\t\t)\n\t\t.immediate();\n}\n\nfunction collectCompletedBackfillRows(\n\tdb: Database,\n\tmetadata: Database,\n\tcompleted: Set<PendingMemory>,\n\tmodel: string,\n) {\n\tconst selectHash = prepareSnapshotHashQuery(metadata);\n\tconst selectSource = db.prepare(`SELECT ${VECTOR_SOURCE_COLUMNS} FROM memory_items WHERE id = ?`);\n\tconst entries: Array<{\n\t\tmemoryId: number;\n\t\tvector: Float32Array;\n\t\tchunkIndex: number;\n\t\tcontentHash: string;\n\t}> = [];\n\tfor (const memory of completed) {\n\t\tconst current = selectSource.get(memory.memoryId) as VectorSourceRow | undefined;\n\t\tconst hashes = currentVectorSourceHashes(memory.source, current);\n\t\tfor (const [index, chunk] of memory.chunks.entries()) {\n\t\t\tif (hashes[chunk.chunkIndex] !== chunk.contentHash) continue;\n\t\t\tif (selectHash.get(memory.memoryId, model, chunk.contentHash)) continue;\n\t\t\tentries.push({\n\t\t\t\tvector: memory.vectors[index] as Float32Array,\n\t\t\t\tmemoryId: memory.memoryId,\n\t\t\t\tchunkIndex: chunk.chunkIndex,\n\t\t\t\tcontentHash: chunk.contentHash,\n\t\t\t});\n\t\t}\n\t}\n\treturn entries;\n}\n\nfunction snapshotHashesByMemory(\n\tselectRows: SnapshotQuery,\n\tmemoryIds: number[],\n\tmodel: string,\n): Map<number, Set<string>> {\n\tconst hashesByMemory = new Map<number, Set<string>>();\n\tfor (const row of selectRows.iterate(model, JSON.stringify(memoryIds)) as Iterable<{\n\t\tmemory_id: number;\n\t\tcontent_hash: string | null;\n\t}>) {\n\t\tif (row.content_hash == null) continue;\n\t\tconst hashes = hashesByMemory.get(row.memory_id) ?? new Set<string>();\n\t\thashes.add(row.content_hash);\n\t\thashesByMemory.set(row.memory_id, hashes);\n\t}\n\treturn hashesByMemory;\n}\n\nfunction validateBackfillEmbeddings(\n\tembeddings: Float32Array[],\n\texpectedCount: number,\n\tdimensions: number,\n): void {\n\tif (embeddings.length !== expectedCount) {\n\t\tthrow new TypeError(\n\t\t\t`Embedding client returned ${embeddings.length} vectors for ${expectedCount} texts`,\n\t\t);\n\t}\n\tfor (const vector of embeddings) {\n\t\tif (vector.length !== dimensions) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`Embedding client returned vector dimension ${vector.length}, expected ${dimensions}`,\n\t\t\t);\n\t\t}\n\t\tfor (const value of vector) {\n\t\t\tif (!Number.isFinite(value)) {\n\t\t\t\tthrow new TypeError(\"Embedding client returned a non-finite vector value\");\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction collectCompletedBackfillMemories(\n\tbatch: Array<{ memory: PendingMemory; chunk: PendingChunk }>,\n\tembeddings: Float32Array[],\n): Set<PendingMemory> {\n\tconst completed = new Set<PendingMemory>();\n\tfor (const [index, { memory }] of batch.entries()) {\n\t\tconst vector = embeddings[index];\n\t\tif (!vector) throw new TypeError(\"Embedding client omitted a validated vector\");\n\t\tmemory.vectors.push(vector);\n\t\tif (memory.vectors.length === memory.chunks.length) completed.add(memory);\n\t}\n\treturn completed;\n}\n\n/**\n * Backfill vectors for memories that don't have them yet.\n * Matches Python's `backfill_vectors()` in store/vectors.py.\n */\nexport async function backfillVectors(\n\tdb: Database,\n\topts: BackfillVectorsOptions = {},\n): Promise<BackfillVectorsResult> {\n\tif (opts.client) assertEmbeddingClientIdentity(opts.client);\n\tconst client = opts.client ?? (await getEmbeddingClient());\n\tif (!client) return { checked: 0, embedded: 0, inserted: 0, skipped: 0 };\n\n\tconst { limit, since, project, activeOnly = true, dryRun = false, memoryIds, signal } = opts;\n\n\tconst params: unknown[] = [];\n\tconst whereClauses: string[] = [];\n\n\tif (activeOnly) whereClauses.push(\"memory_items.active = 1\");\n\tif (since) {\n\t\twhereClauses.push(\"memory_items.created_at >= ?\");\n\t\tparams.push(since);\n\t}\n\tif (project) {\n\t\tconst pc = projectColumnClause(\"COALESCE(sessions.project, memory_items.project)\", project);\n\t\tif (pc.clause) {\n\t\t\twhereClauses.push(pc.clause);\n\t\t\tparams.push(...pc.params);\n\t\t}\n\t}\n\tif (memoryIds && memoryIds.length > 0) {\n\t\tconst placeholders = memoryIds.map(() => \"?\").join(\",\");\n\t\twhereClauses.push(`memory_items.id IN (${placeholders})`);\n\t\tparams.push(...memoryIds);\n\t}\n\n\tconst where = whereClauses.length > 0 ? whereClauses.join(\" AND \") : \"1=1\";\n\tconst joinSessions = project != null;\n\tconst joinClause = joinSessions ? \"JOIN sessions ON sessions.id = memory_items.session_id\" : \"\";\n\tconst model = resolveEmbeddingClientVectorIdentityLabel(client);\n\tlet checked = 0;\n\tlet embedded = 0;\n\tlet inserted = 0;\n\tlet skipped = 0;\n\tconst rowLimit = limit != null && limit > 0 ? limit : Infinity;\n\tconst candidateTable = createBackfillCandidateSnapshot(db, joinClause, where, params, rowLimit);\n\tlet metadata: Database | null = null;\n\tlet selectPageHashes: SnapshotQuery | null = null;\n\n\ttry {\n\t\tconst selectPage = db.prepare(\n\t\t\t`SELECT candidates.seq AS snapshot_seq,\n\t\t\t ${QUALIFIED_VECTOR_SOURCE_COLUMNS}\n\t\t\t FROM ${candidateTable} AS candidates\n\t\t\t JOIN memory_items ON memory_items.id = candidates.memory_id\n\t\t\t WHERE candidates.seq > ?\n\t\t\t ORDER BY candidates.seq ASC\n\t\t\t LIMIT ?`,\n\t\t);\n\t\tlet cursorSeq = 0;\n\t\twhile (!signal?.aborted) {\n\t\t\tconst rows = selectPage.all(cursorSeq, BACKFILL_MEMORY_PAGE_SIZE) as BackfillMemoryRow[];\n\t\t\tif (rows.length === 0) break;\n\t\t\tconst lastRow = rows.at(-1) as BackfillMemoryRow;\n\t\t\t// This cursor lives only for this invocation. An aborted caller starts a fresh pass.\n\t\t\tcursorSeq = lastRow.snapshot_seq;\n\n\t\t\t// Reuse only during uninterrupted synchronous reads. Inference closes\n\t\t\t// this snapshot before yielding; the next page then reads current state.\n\t\t\tmetadata ??= createVectorMetadataSnapshot(db);\n\t\t\tselectPageHashes ??= metadata.prepare(\n\t\t\t\t`SELECT memory_id, content_hash FROM vector_metadata\n\t\t\t\t WHERE model = ? AND memory_id IN (SELECT value FROM json_each(?))`,\n\t\t\t);\n\t\t\tconst existingHashesByMemory = snapshotHashesByMemory(\n\t\t\t\tselectPageHashes,\n\t\t\t\trows.map((row) => row.id),\n\t\t\t\tmodel,\n\t\t\t);\n\n\t\t\tlet batch: Array<{ memory: PendingMemory; chunk: PendingChunk }> = [];\n\t\t\tconst flushBatch = async (): Promise<void> => {\n\t\t\t\tif (batch.length === 0) return;\n\t\t\t\tconst currentBatch = batch;\n\t\t\t\tbatch = [];\n\t\t\t\tmetadata?.close();\n\t\t\t\tmetadata = null;\n\t\t\t\tselectPageHashes = null;\n\t\t\t\tconst embeddings = await embedTexts(\n\t\t\t\t\tcurrentBatch.map(({ chunk }) => chunk.text),\n\t\t\t\t\tclient,\n\t\t\t\t);\n\t\t\t\tvalidateBackfillEmbeddings(embeddings, currentBatch.length, client.dimensions);\n\t\t\t\tembedded += embeddings.length;\n\t\t\t\tconst completed = collectCompletedBackfillMemories(currentBatch, embeddings);\n\t\t\t\t// Page hashes are planning hints only. Recheck the completed batch\n\t\t\t\t// after inference inside the immediate write boundary: vec0 has no\n\t\t\t\t// uniqueness constraint. Do not add our inserts to that snapshot;\n\t\t\t\t// distinct chunk_index rows may legitimately share the same hash.\n\t\t\t\tif (!dryRun) inserted += insertCompletedBackfillMemories(db, completed, model);\n\t\t\t\tfor (const memory of completed) {\n\t\t\t\t\tif (dryRun) inserted += memory.chunks.length;\n\t\t\t\t\tmemory.vectors.length = 0;\n\t\t\t\t\tmemory.chunks.length = 0;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tfor (const row of rows) {\n\t\t\t\tif (signal?.aborted) return { checked, embedded, inserted, skipped };\n\t\t\t\tchecked++;\n\t\t\t\tconst chunks = chunkText(memoryText(row.title, row.body_text));\n\t\t\t\tconst existingHashes = existingHashesByMemory.get(row.id) ?? new Set<string>();\n\t\t\t\tconst pendingChunks: PendingChunk[] = [];\n\t\t\t\tfor (const [chunkIndex, text] of chunks.entries()) {\n\t\t\t\t\tconst contentHash = hashText(text);\n\t\t\t\t\tif (existingHashes.has(contentHash)) {\n\t\t\t\t\t\tskipped++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tpendingChunks.push({ text, chunkIndex, contentHash });\n\t\t\t\t}\n\t\t\t\tif (pendingChunks.length === 0) continue;\n\t\t\t\tconst memory = pendingBackfillMemory(row, pendingChunks);\n\t\t\t\tfor (const chunk of pendingChunks) {\n\t\t\t\t\tbatch.push({ memory, chunk });\n\t\t\t\t\tif (batch.length < BACKFILL_INFERENCE_BATCH_SIZE) continue;\n\t\t\t\t\tawait flushBatch();\n\t\t\t\t\tif (!signal?.aborted) continue;\n\t\t\t\t\t// `embedded` includes valid inference discarded for an incomplete memory;\n\t\t\t\t\t// `inserted` counts only memories completed by this batch (also for dry-run).\n\t\t\t\t\treturn { checked, embedded, inserted, skipped };\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (batch.length > 0) await flushBatch();\n\t\t\tif (signal?.aborted) return { checked, embedded, inserted, skipped };\n\t\t}\n\t} finally {\n\t\tmetadata?.close();\n\t\tdeleteBackfillCandidateSnapshot(db, candidateTable);\n\t}\n\n\tif (!dryRun && (inserted > 0 || skipped > 0)) {\n\t\tpersistVectorIdentity(db, client, model);\n\t}\n\treturn { checked, embedded, inserted, skipped };\n}\n\n// ---------------------------------------------------------------------------\n// semanticSearch — vector KNN query\n// ---------------------------------------------------------------------------\n\nexport interface SemanticSearchResult {\n\tid: number;\n\tkind: string;\n\ttitle: string;\n\tbody_text: string;\n\tconfidence: number;\n\ttags_text: string;\n\tmetadata_json: string | null;\n\tcreated_at: string;\n\tupdated_at: string;\n\tsession_id: number;\n\tscore: number;\n\tdistance: number;\n\t/** Structured narrative from observation (carried through from memory_items.*). */\n\tnarrative: string | null;\n\t/** JSON-encoded string array of extracted facts. */\n\tfacts: string | null;\n}\n\nexport { semanticResult };\n\n/**\n * Search for memories by vector similarity using exact sqlite-vec distance.\n * Returns an empty array when embeddings are disabled or unavailable.\n *\n * Matches Python's `_semantic_search()` in store/search.py.\n */\nexport async function semanticSearch(\n\tdb: Database,\n\tquery: string,\n\tlimit: number,\n\tfilters: MemoryFilters | null,\n\tcontext: SemanticSearchScopeContext,\n\tsummarySessionId?: number | null,\n): Promise<SemanticSearchResult[]> {\n\tif (query.trim().length < 3) return [];\n\tif (!hasVectorRows(db)) return [];\n\tconst client = await getEmbeddingClient();\n\tif (!client) return [];\n\tconst searchModels = resolveSemanticSearchModels(\n\t\tdb,\n\t\tresolveEmbeddingClientVectorIdentityLabel(client),\n\t);\n\tif (searchModels.length === 0) return [];\n\tif (!context?.deviceId?.trim()) {\n\t\tthrow new Error(\"semantic_search_scope_context_required\");\n\t}\n\n\tconst embeddings = await embedTexts([query], client);\n\tif (embeddings.length === 0) return [];\n\n\tconst firstEmbedding = embeddings[0];\n\tif (!firstEmbedding) return [];\n\tconst queryEmbedding = serializeFloat32(firstEmbedding);\n\treturn rankSemanticEmbedding(\n\t\tdb,\n\t\tqueryEmbedding,\n\t\tsearchModels,\n\t\tlimit,\n\t\tfilters,\n\t\tcontext,\n\t\tsummarySessionId,\n\t);\n}\n\n/** Internal exact ranking stage shared with the read-only semantic worker. */\nexport function rankSemanticEmbedding(\n\tdb: Database,\n\tqueryEmbedding: Buffer,\n\tsearchModels: string[],\n\tlimit: number,\n\tfilters: MemoryFilters | null,\n\tcontext: SemanticSearchScopeContext,\n\tsummarySessionId?: number | null,\n): SemanticSearchResult[] {\n\tif (searchModels.length === 0) return [];\n\treturn snapshot(db, () =>\n\t\trankSemanticEmbeddingSnapshot(\n\t\t\tdb,\n\t\t\tqueryEmbedding,\n\t\t\tsearchModels,\n\t\t\tlimit,\n\t\t\tfilters,\n\t\t\tcontext,\n\t\t\tsummarySessionId,\n\t\t),\n\t);\n}\n\nfunction rankSemanticEmbeddingSnapshot(\n\tdb: Database,\n\tqueryEmbedding: Buffer,\n\tsearchModels: string[],\n\tlimit: number,\n\tfilters: MemoryFilters | null,\n\tcontext: SemanticSearchScopeContext,\n\tsummarySessionId?: number | null,\n): SemanticSearchResult[] {\n\tconst effectiveLimit = clampSemanticLimit(limit);\n\tconst authorizedIds = buildAuthorizedSemanticMemoryIdsQuery(filters, context, summarySessionId);\n\tconst freshness = pendingVectorFreshness(\n\t\tdb,\n\t\tfilters,\n\t\tcontext,\n\t\tsummarySessionId,\n\t\t\"memory_vectors.\",\n\t);\n\tconst modelPlaceholders = searchModels.map(() => \"?\").join(\", \");\n\n\t// Scope predicates must apply before vector ranking. sqlite-vec's MATCH/k\n\t// query ranks inside the virtual table before joined memory_items filters can\n\t// reliably constrain the candidate set, so use an exact distance scan over the\n\t// already-authorized memory rows instead of widening post-KNN candidates.\n\t// Materialize IDs so vec0 metadata probes do not reopen wide memory rows;\n\t// materialize the limited ranking before fetching the final result payloads.\n\tconst sql = `\n\t\tWITH authorized_ids AS MATERIALIZED (${authorizedIds.sql}),\n\t\tscoped_vectors AS MATERIALIZED (\n\t\t\tSELECT\n\t\t\t\tmemory_vectors.memory_id,\n\t\t\t\tMIN(vec_distance_l2(memory_vectors.embedding, ?)) AS distance\n\t\t\tFROM memory_vectors\n\t\t\tJOIN authorized_ids ON authorized_ids.id = memory_vectors.memory_id\n\t\t\tWHERE memory_vectors.model IN (${modelPlaceholders})\n\t\t\t${freshness.sql}\n\t\t\tGROUP BY memory_vectors.memory_id\n\t\t\tORDER BY distance ASC\n\t\t\tLIMIT ?\n\t\t)\n\t\tSELECT memory_items.*, scoped_vectors.distance\n\t\tFROM scoped_vectors\n\t\tJOIN memory_items ON memory_items.id = scoped_vectors.memory_id\n\t\tORDER BY scoped_vectors.distance ASC\n\t`;\n\n\tconst statement = db.prepare(sql);\n\tconst rows = statement.all(\n\t\t...authorizedIds.params,\n\t\tqueryEmbedding,\n\t\t...searchModels,\n\t\t...freshness.params,\n\t\teffectiveLimit,\n\t) as Array<Record<string, unknown>>;\n\n\treturn rows.map(semanticResult).slice(0, effectiveLimit);\n}\n","import { lstatSync, statSync } from \"node:fs\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport type { Database } from \"./db.js\";\nimport { resolveGitRepositoryIdentity } from \"./project.js\";\nimport { cleanProjectIdentity } from \"./project-identity.js\";\nimport {\n\tloadRepositoryDiscoveryEvidence,\n\ttype RepositoryWorkspaceEvidence,\n\treplaceRepositoryDiscoveryEvidence,\n\trepositoryDiscoveryRevision,\n} from \"./repository-discovery-index.js\";\nimport {\n\tnormalizeRepositoryWorkspaceIdentity,\n\trecordedRepositoryIdentitySetsByWorkspace,\n\trepositoryIdentityMapFromEvidence,\n} from \"./repository-mapping-aliases.js\";\n\nconst POSITIVE_DISCOVERY_TTL_MS = 5_000;\nconst MAX_IDENTITY_MAP_VARIANTS = 8;\n\ninterface DiscoverySnapshot {\n\trevision: number;\n\trows: Array<RepositoryWorkspaceEvidence & { recordedIdentities: string[] }>;\n\tworkspaces: Set<string>;\n\tknownRecorded: Set<string>;\n\tanchors: Map<string, string>;\n\texpiresAt: number;\n\tidentityMaps: Map<string, { identities: Map<string, string>; known: Set<string> }>;\n}\n\nconst snapshots = new WeakMap<Database, DiscoverySnapshot>();\n\nexport const __repositoryDiscoveryCacheTestHooks = {\n\tvariantCount: (db: Database): number => snapshots.get(db)?.identityMaps.size ?? 0,\n};\n\nfunction statFingerprint(path: string): string | null {\n\ttry {\n\t\tconst stat = statSync(path, { bigint: true });\n\t\treturn `${stat.dev}:${stat.ino}:${stat.mtimeNs}`;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction gitMarkerState(path: string): \"missing\" | \"present\" | \"uncertain\" {\n\ttry {\n\t\tlstatSync(join(path, \".git\"));\n\t\treturn \"present\";\n\t} catch (error) {\n\t\treturn (error as NodeJS.ErrnoException).code === \"ENOENT\" ? \"missing\" : \"uncertain\";\n\t}\n}\n\nfunction anchorFingerprint(path: string): string | null {\n\tconst fingerprint = statFingerprint(path);\n\tif (!fingerprint) return null;\n\tlet current = path;\n\twhile (true) {\n\t\tif (gitMarkerState(current) !== \"missing\") return null;\n\t\tconst parent = dirname(current);\n\t\tif (parent === current) return fingerprint;\n\t\tcurrent = parent;\n\t}\n}\n\nfunction anchored(path: string | null): { path: string; mtimeNs: string } | null {\n\tif (!path) return null;\n\tconst mtimeNs = anchorFingerprint(path);\n\treturn mtimeNs ? { path, mtimeNs } : null;\n}\n\nfunction missingGitAnchor(cwd: string): { path: string; mtimeNs: string } | null {\n\tif (!isAbsolute(cwd)) return null;\n\tlet path = resolve(cwd);\n\tlet anchorPath: string | null = null;\n\twhile (true) {\n\t\tif (statFingerprint(path) && !anchorPath) anchorPath = path;\n\t\tif (gitMarkerState(path) !== \"missing\") return null;\n\t\tconst parent = dirname(path);\n\t\tif (parent === path) return anchored(anchorPath);\n\t\tpath = parent;\n\t}\n}\n\nfunction inspectWorkspace(\n\tcwd: string,\n\trecordedIdentities: string[],\n\tcheckedAtMs: number,\n): RepositoryWorkspaceEvidence | null {\n\tif (recordedIdentities.length > 0 || !isAbsolute(cwd)) {\n\t\treturn {\n\t\t\tcwd,\n\t\t\trecordedIdentitiesJson: JSON.stringify(recordedIdentities),\n\t\t\tfilesystemIdentity: null,\n\t\t\tfilesystemAnchor: null,\n\t\t\tanchorMtimeNs: null,\n\t\t\tcheckedAtMs,\n\t\t};\n\t}\n\tconst filesystemIdentity = normalizeRepositoryWorkspaceIdentity(\n\t\tresolveGitRepositoryIdentity(cwd)?.identity,\n\t);\n\tconst anchor = filesystemIdentity ? null : missingGitAnchor(cwd);\n\tif (!filesystemIdentity && !anchor) return null;\n\treturn {\n\t\tcwd,\n\t\trecordedIdentitiesJson: \"[]\",\n\t\tfilesystemIdentity,\n\t\tfilesystemAnchor: anchor?.path ?? null,\n\t\tanchorMtimeNs: anchor?.mtimeNs ?? null,\n\t\tcheckedAtMs,\n\t};\n}\n\nfunction buildSnapshot(db: Database, revision: number): RepositoryWorkspaceEvidence[] | null {\n\tconst recorded = recordedRepositoryIdentitySetsByWorkspace(db);\n\tconst workspaces = db\n\t\t.prepare(\"SELECT DISTINCT cwd FROM sessions WHERE cwd IS NOT NULL AND TRIM(cwd) <> ''\")\n\t\t.pluck()\n\t\t.all() as string[];\n\tconst byCwd = new Map<string, RepositoryWorkspaceEvidence>();\n\tconst now = Date.now();\n\tfor (const workspace of workspaces) {\n\t\tconst cwd = normalizeRepositoryWorkspaceIdentity(workspace);\n\t\tif (!cwd || byCwd.has(cwd)) continue;\n\t\tconst row = inspectWorkspace(cwd, [...(recorded.get(cwd) ?? [])], now);\n\t\tif (!row) return null;\n\t\tbyCwd.set(cwd, row);\n\t}\n\tconst rows = [...byCwd.values()];\n\treturn replaceRepositoryDiscoveryEvidence(db, revision, rows) ? rows : null;\n}\n\nfunction parseRecordedIdentities(row: RepositoryWorkspaceEvidence): string[] | null {\n\tif (!row.cwd || row.cwd !== normalizeRepositoryWorkspaceIdentity(row.cwd)) return null;\n\ttry {\n\t\tconst identities: unknown = JSON.parse(row.recordedIdentitiesJson);\n\t\tif (!Array.isArray(identities) || identities.some((identity) => typeof identity !== \"string\")) {\n\t\t\treturn null;\n\t\t}\n\t\treturn identities;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction recordAnchor(\n\trow: RepositoryWorkspaceEvidence,\n\trecordedIdentities: string[],\n\tanchors: Map<string, string>,\n): boolean {\n\tif (!row.filesystemAnchor || !row.anchorMtimeNs) {\n\t\treturn Boolean(row.filesystemIdentity || recordedIdentities.length > 0 || !isAbsolute(row.cwd));\n\t}\n\tconst previous = anchors.get(row.filesystemAnchor);\n\tif (previous && previous !== row.anchorMtimeNs) return false;\n\tanchors.set(row.filesystemAnchor, row.anchorMtimeNs);\n\treturn true;\n}\n\nfunction parseSnapshot(\n\trevision: number,\n\trows: RepositoryWorkspaceEvidence[],\n): DiscoverySnapshot | null {\n\tconst knownRecorded = new Set<string>();\n\tconst anchors = new Map<string, string>();\n\tlet expiresAt = Number.POSITIVE_INFINITY;\n\tconst parsed = [] as DiscoverySnapshot[\"rows\"];\n\tfor (const row of rows) {\n\t\tconst recordedIdentities = parseRecordedIdentities(row);\n\t\tif (!recordedIdentities) return null;\n\t\tfor (const identity of recordedIdentities) knownRecorded.add(identity);\n\t\tif (row.filesystemIdentity)\n\t\t\texpiresAt = Math.min(expiresAt, row.checkedAtMs + POSITIVE_DISCOVERY_TTL_MS);\n\t\tif (!recordAnchor(row, recordedIdentities, anchors)) return null;\n\t\tparsed.push({ ...row, recordedIdentities });\n\t}\n\treturn {\n\t\trevision,\n\t\trows: parsed,\n\t\tworkspaces: new Set(parsed.map((row) => row.cwd)),\n\t\tknownRecorded,\n\t\tanchors,\n\t\texpiresAt,\n\t\tidentityMaps: new Map(),\n\t};\n}\n\nfunction stillFresh(snapshot: DiscoverySnapshot): boolean {\n\tif (Date.now() >= snapshot.expiresAt) return false;\n\tfor (const [path, mtimeNs] of snapshot.anchors) {\n\t\tif (anchorFingerprint(path) !== mtimeNs) return false;\n\t}\n\treturn true;\n}\n\nfunction currentSnapshot(db: Database, revision: number): DiscoverySnapshot | null {\n\tconst cached = snapshots.get(db);\n\tif (cached?.revision === revision && stillFresh(cached)) return cached;\n\tconst saved = cached?.revision === revision ? null : loadRepositoryDiscoveryEvidence(db);\n\tconst restored = saved ? parseSnapshot(revision, saved) : null;\n\tif (restored && stillFresh(restored)) {\n\t\tsnapshots.set(db, restored);\n\t\treturn restored;\n\t}\n\tlet rows: RepositoryWorkspaceEvidence[] | null;\n\ttry {\n\t\trows = buildSnapshot(db, revision);\n\t} catch {\n\t\treturn null;\n\t}\n\tif (!rows) return null;\n\tconst rebuilt = parseSnapshot(revision, rows);\n\tif (!rebuilt || !stillFresh(rebuilt)) return null;\n\tsnapshots.set(db, rebuilt);\n\treturn rebuilt;\n}\n\nfunction identityMapForSeeds(\n\tsnapshot: DiscoverySnapshot,\n\tseeds: ReadonlySet<string>,\n): { identities: Map<string, string>; known: Set<string> } {\n\tconst key = JSON.stringify([...seeds].toSorted());\n\tconst existing = snapshot.identityMaps.get(key);\n\tif (existing) {\n\t\tsnapshot.identityMaps.delete(key);\n\t\tsnapshot.identityMaps.set(key, existing);\n\t\treturn existing;\n\t}\n\tconst known = new Set(snapshot.knownRecorded);\n\tfor (const seed of seeds) known.add(seed);\n\tconst variant = { identities: repositoryIdentityMapFromEvidence(snapshot.rows, known), known };\n\tif (snapshot.identityMaps.size >= MAX_IDENTITY_MAP_VARIANTS) {\n\t\tconst oldestKey = snapshot.identityMaps.keys().next().value;\n\t\tif (oldestKey !== undefined) snapshot.identityMaps.delete(oldestKey);\n\t}\n\tsnapshot.identityMaps.set(key, variant);\n\treturn variant;\n}\n\nexport function repositoryIdentitiesFromIndexedEvidence(\n\tdb: Database,\n\tknownRepositoryIdentities: Array<string | null | undefined>,\n): { identities: Map<string, string>; known: Set<string>; workspaces: ReadonlySet<string> } | null {\n\tconst revision = repositoryDiscoveryRevision(db);\n\tif (revision == null) return null;\n\tconst snapshot = currentSnapshot(db, revision);\n\tif (!snapshot) return null;\n\tconst seeds = new Set<string>();\n\tfor (const identity of knownRepositoryIdentities) {\n\t\tconst normalized = normalizeRepositoryWorkspaceIdentity(cleanProjectIdentity(identity));\n\t\tif (normalized) seeds.add(normalized);\n\t}\n\tconst { identities, known } = identityMapForSeeds(snapshot, seeds);\n\tif (repositoryDiscoveryRevision(db) !== revision) return null;\n\treturn { identities, known, workspaces: snapshot.workspaces };\n}\n","import { isAbsolute } from \"node:path\";\nimport type { Database } from \"./db.js\";\nimport { resolveGitRepositoryIdentity } from \"./project.js\";\nimport { repositoryIdentitiesFromIndexedEvidence } from \"./repository-discovery-cache.js\";\nimport {\n\tdiscoverKnownRepositoryIdentity,\n\thasConflictingRepositoryMappings,\n\thasRecordedRepositoryWorkspace,\n\tnormalizeRepositoryWorkspaceIdentity,\n\trecordedRepositoryIdentityEvidenceByWorkspace,\n\trepositoryIdentitiesByWorkspace,\n\trepositoryIdentityForWorkspace,\n\twithRepositoryMappingAliasesFromIdentities,\n} from \"./repository-mapping-aliases.js\";\nimport {\n\tLOCAL_DEFAULT_SCOPE_ID,\n\tresolveProjectScope,\n\ttype ScopeMapping,\n} from \"./scope-resolution.js\";\n\ninterface SessionScopeRow {\n\tcwd: string | null;\n\tproject: string | null;\n\tgit_remote: string | null;\n\tgit_branch: string | null;\n\tmetadata_json: string | null;\n}\n\ntype IndexedRepositoryEvidence = NonNullable<\n\tReturnType<typeof repositoryIdentitiesFromIndexedEvidence>\n>;\n\nfunction refreshMappedWorkspace(\n\tindexed: IndexedRepositoryEvidence,\n\tworkspace: string | null | undefined,\n\tcurrentCwd: string | null,\n): void {\n\tconst mapped = normalizeRepositoryWorkspaceIdentity(workspace);\n\tif (!mapped || mapped === currentCwd || indexed.workspaces.has(mapped)) return;\n\tindexed.identities.delete(mapped);\n\tconst identity = discoverKnownRepositoryIdentity(mapped, indexed.known);\n\tif (identity) indexed.identities.set(mapped, identity);\n}\n\nfunction refreshIndexedWorkspaces(\n\tindexed: IndexedRepositoryEvidence,\n\trow: SessionScopeRow | null,\n\tmappedWorkspaces: Array<string | null | undefined>,\n): Set<string> {\n\tconst cwd = normalizeRepositoryWorkspaceIdentity(row?.cwd);\n\tconst recordedWorkspaces = new Set<string>();\n\tif (cwd && hasRecordedRepositoryWorkspace(indexed.identities, cwd)) {\n\t\trecordedWorkspaces.add(cwd);\n\t} else if (cwd) {\n\t\tindexed.identities.delete(cwd);\n\t\tif (isAbsolute(cwd)) {\n\t\t\tconst identity = normalizeRepositoryWorkspaceIdentity(\n\t\t\t\tresolveGitRepositoryIdentity(row?.cwd ?? cwd)?.identity,\n\t\t\t);\n\t\t\tif (identity && indexed.known.has(identity)) indexed.identities.set(cwd, identity);\n\t\t}\n\t}\n\tfor (const workspace of mappedWorkspaces) {\n\t\trefreshMappedWorkspace(indexed, workspace, cwd);\n\t}\n\treturn recordedWorkspaces;\n}\n\ninterface MemoryScopeRow extends SessionScopeRow {\n\tid: number;\n\tsession_id: number;\n\tworkspace_id: string | null;\n\tscope_id: string | null;\n}\n\nexport interface ResolveSessionScopeOptions {\n\tsessionId: number;\n\tworkspaceId?: string | null;\n\texplicitScopeId?: string | null;\n\tlocalDefaultScopeId?: string;\n\t/** Admission checks must not rebuild persisted repository evidence. */\n\treadOnly?: boolean;\n}\n\ninterface RepositoryScopeContext {\n\tallowRepositoryCwdFallback: boolean;\n\tmappings: ScopeMapping[];\n\trepositoryIdentity: string | null;\n}\n\nfunction clean(value: string | null | undefined): string | null {\n\tconst trimmed = value?.trim();\n\treturn trimmed ? trimmed : null;\n}\n\nfunction loadProjectScopeMappings(db: Database): ScopeMapping[] {\n\treturn db\n\t\t.prepare(\n\t\t\t`SELECT id, workspace_identity, project_pattern, scope_id, priority, source, updated_at\n\t\t\t FROM project_scope_mappings\n\t\t\t WHERE scope_id IS NOT NULL AND TRIM(scope_id) != ''\n\t\t\t ORDER BY priority DESC, id ASC`,\n\t\t)\n\t\t.all() as ScopeMapping[];\n}\n\nfunction hasRepositoryConflict(\n\tmappings: ScopeMapping[],\n\trepositoryIdentities: ReadonlyMap<string, string>,\n\trepositoryIdentity: string | null,\n): boolean {\n\treturn Boolean(\n\t\trepositoryIdentity &&\n\t\t\thasConflictingRepositoryMappings(mappings, repositoryIdentities, repositoryIdentity),\n\t);\n}\n\nfunction emptyRepositoryScopeContext(\n\trow: SessionScopeRow | null,\n\tmappings: ScopeMapping[],\n): RepositoryScopeContext {\n\treturn {\n\t\tallowRepositoryCwdFallback: true,\n\t\tmappings,\n\t\trepositoryIdentity: repositoryIdentityForWorkspace(new Map(), {\n\t\t\tcwd: row?.cwd,\n\t\t\tgitRemote: row?.git_remote ?? null,\n\t\t\tmetadataJson: row?.metadata_json,\n\t\t}),\n\t};\n}\n\nfunction addDiscoveredRepositoryWorkspaces(\n\tdb: Database,\n\trepositoryIdentities: Map<string, string>,\n\trepositoryIdentity: string,\n\tmappedWorkspaces: Array<string | null | undefined>,\n): void {\n\tconst discoveredWorkspaces = repositoryIdentitiesByWorkspace(db, {\n\t\tknownRepositoryIdentities: [repositoryIdentity, ...mappedWorkspaces],\n\t});\n\tfor (const [workspace, identity] of discoveredWorkspaces) {\n\t\tif (identity === repositoryIdentity) repositoryIdentities.set(workspace, identity);\n\t}\n}\n\nfunction scopeRepositoryEvidence(\n\tdb: Database,\n\trow: SessionScopeRow | null,\n\tmappedWorkspaces: Array<string | null | undefined>,\n\tmappingIdentitySeeds: Array<string | null | undefined>,\n\toptions: { readOnly?: boolean } = {},\n) {\n\tconst legacy = () => ({\n\t\tevidence: recordedRepositoryIdentityEvidenceByWorkspace(db, [row?.cwd, ...mappedWorkspaces], {\n\t\t\tfreshWorkspaces: [row?.cwd],\n\t\t}),\n\t\tindexed: false,\n\t});\n\t// Authorization must not rebuild the persisted discovery cache before it permits a write.\n\tif (options.readOnly) return legacy();\n\tconst indexed = repositoryIdentitiesFromIndexedEvidence(db, mappingIdentitySeeds);\n\tif (!indexed) return legacy();\n\tconst recordedWorkspaces = refreshIndexedWorkspaces(indexed, row, mappedWorkspaces);\n\treturn {\n\t\tevidence: { byWorkspace: indexed.identities, recordedWorkspaces },\n\t\tindexed: true,\n\t};\n}\n\nfunction discoverCurrentWorkspace(\n\tcwd: string | null,\n\trepositoryIdentities: Map<string, string>,\n\trecordedWorkspaces: ReadonlySet<string>,\n\tmappingIdentitySeeds: Array<string | null | undefined>,\n): void {\n\tif (!cwd || recordedWorkspaces.has(cwd)) return;\n\tconst known = new Set(\n\t\t[\n\t\t\t...repositoryIdentities.values(),\n\t\t\t...mappingIdentitySeeds.map((identity) => normalizeRepositoryWorkspaceIdentity(identity)),\n\t\t].filter((identity): identity is string => identity != null),\n\t);\n\tconst identity = discoverKnownRepositoryIdentity(cwd, known);\n\tif (identity) repositoryIdentities.set(cwd, identity);\n}\n\nfunction mappingIdentitySeeds(mappings: ScopeMapping[]) {\n\treturn mappings.flatMap((mapping) => [mapping.workspace_identity, mapping.project_pattern]);\n}\n\nfunction repositoryScopeContext(\n\tdb: Database,\n\trow: SessionScopeRow | null,\n\tmappings: ScopeMapping[],\n\toptions: { readOnly?: boolean } = {},\n): RepositoryScopeContext {\n\tif (mappings.length === 0) return emptyRepositoryScopeContext(row, mappings);\n\tconst mappedWorkspaces = mappings.map((mapping) => mapping.workspace_identity);\n\tconst identitySeeds = mappingIdentitySeeds(mappings);\n\tconst { evidence, indexed } = scopeRepositoryEvidence(\n\t\tdb,\n\t\trow,\n\t\tmappedWorkspaces,\n\t\tidentitySeeds,\n\t\toptions,\n\t);\n\tconst repositoryIdentities = evidence.byWorkspace;\n\tconst cwd = normalizeRepositoryWorkspaceIdentity(row?.cwd);\n\tconst ambiguousCwd = Boolean(\n\t\tcwd && evidence.recordedWorkspaces.has(cwd) && !repositoryIdentities.has(cwd),\n\t);\n\tif (!indexed)\n\t\tdiscoverCurrentWorkspace(cwd, repositoryIdentities, evidence.recordedWorkspaces, identitySeeds);\n\tconst repositoryIdentity = repositoryIdentityForWorkspace(repositoryIdentities, {\n\t\tcwd: row?.cwd,\n\t\tgitRemote: row?.git_remote ?? null,\n\t\tmetadataJson: row?.metadata_json,\n\t});\n\tif (repositoryIdentity && !indexed) {\n\t\taddDiscoveredRepositoryWorkspaces(db, repositoryIdentities, repositoryIdentity, identitySeeds);\n\t}\n\tconst repositoryConflict = hasRepositoryConflict(\n\t\tmappings,\n\t\trepositoryIdentities,\n\t\trepositoryIdentity,\n\t);\n\tconst unresolvedAmbiguousCwd = ambiguousCwd && !repositoryIdentity;\n\tlet effectiveMappings = mappings;\n\tif (repositoryConflict || unresolvedAmbiguousCwd) {\n\t\teffectiveMappings = [];\n\t} else if (!ambiguousCwd) {\n\t\teffectiveMappings = withRepositoryMappingAliasesFromIdentities(mappings, repositoryIdentities, {\n\t\t\tdiscoverFilesystem: true,\n\t\t});\n\t}\n\treturn {\n\t\tallowRepositoryCwdFallback: !ambiguousCwd && !repositoryConflict,\n\t\tmappings: effectiveMappings,\n\t\trepositoryIdentity,\n\t};\n}\n\nfunction loadSessionScopeRow(db: Database, sessionId: number): SessionScopeRow | null {\n\tconst row = db\n\t\t.prepare(\n\t\t\t\"SELECT cwd, project, git_remote, git_branch, metadata_json FROM sessions WHERE id = ? LIMIT 1\",\n\t\t)\n\t\t.get(sessionId) as SessionScopeRow | undefined;\n\treturn row ?? null;\n}\n\nexport function resolveSessionScopeId(db: Database, options: ResolveSessionScopeOptions): string {\n\tconst explicitScopeId = clean(options.explicitScopeId);\n\tif (explicitScopeId) return explicitScopeId;\n\tconst session = loadSessionScopeRow(db, options.sessionId);\n\tconst context = repositoryScopeContext(db, session, loadProjectScopeMappings(db), {\n\t\treadOnly: options.readOnly,\n\t});\n\tconst result = resolveProjectScope({\n\t\tallowRepositoryCwdFallback: context.allowRepositoryCwdFallback,\n\t\tgitRemote: session?.git_remote ?? null,\n\t\tgitBranch: session?.git_branch ?? null,\n\t\trepositoryIdentity: context.repositoryIdentity,\n\t\tcwd: session?.cwd ?? null,\n\t\tproject: session?.project ?? null,\n\t\tworkspaceId: options.workspaceId ?? null,\n\t\tlocalDefaultScopeId: options.localDefaultScopeId ?? LOCAL_DEFAULT_SCOPE_ID,\n\t\tmappings: context.mappings,\n\t});\n\treturn result.scopeId;\n}\n\nfunction loadMemoryScopeRow(db: Database, memoryId: number): MemoryScopeRow | null {\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT\n\t\t\t\tmi.id,\n\t\t\t\tmi.session_id,\n\t\t\t\tmi.workspace_id,\n\t\t\t\tmi.scope_id,\n\t\t\t\ts.cwd,\n\t\t\t\ts.project,\n\t\t\t\ts.git_remote,\n\t\t\t\ts.git_branch,\n\t\t\t\ts.metadata_json\n\t\t\t FROM memory_items mi\n\t\t\t LEFT JOIN sessions s ON s.id = mi.session_id\n\t\t\t WHERE mi.id = ?\n\t\t\t LIMIT 1`,\n\t\t)\n\t\t.get(memoryId) as MemoryScopeRow | undefined;\n\treturn row ?? null;\n}\n\n/** Resolve the eventual stamp without writing schema, caches, keys, or memory rows. */\nexport function resolveMemoryScopeId(\n\tdb: Database,\n\tmemoryId: number,\n\toptions: { mappings?: ScopeMapping[] } = {},\n): string | null {\n\tconst row = loadMemoryScopeRow(db, memoryId);\n\tif (!row) return null;\n\tconst existingScopeId = clean(row.scope_id);\n\tif (existingScopeId) return existingScopeId;\n\tconst context = repositoryScopeContext(\n\t\tdb,\n\t\trow,\n\t\toptions.mappings ?? loadProjectScopeMappings(db),\n\t\t{ readOnly: true },\n\t);\n\tconst result = resolveProjectScope({\n\t\tallowRepositoryCwdFallback: context.allowRepositoryCwdFallback,\n\t\tgitRemote: row.git_remote,\n\t\tgitBranch: row.git_branch,\n\t\trepositoryIdentity: context.repositoryIdentity,\n\t\tcwd: row.cwd,\n\t\tproject: row.project,\n\t\tworkspaceId: row.workspace_id,\n\t\tlocalDefaultScopeId: LOCAL_DEFAULT_SCOPE_ID,\n\t\tmappings: context.mappings,\n\t});\n\treturn result.scopeId;\n}\n\nexport function ensureMemoryScopeId(db: Database, memoryId: number): string | null {\n\tconst scopeId = resolveMemoryScopeId(db, memoryId);\n\tif (!scopeId) return null;\n\tconst row = loadMemoryScopeRow(db, memoryId);\n\tif (clean(row?.scope_id)) return scopeId;\n\tdb.prepare(\n\t\t`UPDATE memory_items\n\t\t SET scope_id = ?\n\t\t WHERE id = ?\n\t\t AND (scope_id IS NULL OR TRIM(scope_id) = '')`,\n\t).run(scopeId, memoryId);\n\treturn scopeId;\n}\n","import type { Database } from \"./db.js\";\nimport { hasMemoryScopeRetirement, isMemoryScopeRetired } from \"./memory-scope-retirement.js\";\n\n/** Snapshot payloads have no op envelope: history requires their own explicit scope. */\nexport function retirementAllowsSnapshot(\n\tdb: Database,\n\tentityId: string,\n\tpayload: Record<string, unknown>,\n\tenvelopeScope: string | null,\n): boolean {\n\tconst canonicalId = entityId.trim();\n\tif (!hasMemoryScopeRetirement(db, canonicalId)) return true;\n\tif (entityId !== canonicalId) return false;\n\tconst scope = typeof payload.scope_id === \"string\" ? payload.scope_id.trim() : \"\";\n\tif (!scope || scope !== envelopeScope || isMemoryScopeRetired(db, entityId, scope)) return false;\n\tconst metadata = payload.metadata_json;\n\tif (!metadata || typeof metadata !== \"object\" || Array.isArray(metadata)) return true;\n\tconst metadataScope = (metadata as Record<string, unknown>).scope_id;\n\treturn (\n\t\tmetadataScope == null || (typeof metadataScope === \"string\" && metadataScope.trim() === scope)\n\t);\n}\n","import type { Database } from \"./db.js\";\nimport { derivePolicyTeamDeviceEligibility } from \"./policy-team-device-eligibility.js\";\nimport { denyOverlayRow } from \"./recipient-policy-deny-overlay.js\";\n\nimport {\n\tisStrictRecipientPolicyId,\n\tisStrictRecipientPolicyProjectIdentity,\n\tlegacyRecipientPolicyDigest,\n} from \"./recipient-policy-identifiers.js\";\nimport {\n\tcanonicalRepositoryProjectIdentity,\n\trepositoryIdentitiesByWorkspace,\n} from \"./repository-mapping-aliases.js\";\n\nexport { getAnyRecipientPolicyDenyOverlayForScopeDevice } from \"./recipient-policy-deny-overlay.js\";\n\n// Preserve the established module-level import path while sharing one grammar.\nexport { isStrictRecipientPolicyId };\n\nexport type RecipientPolicyAuthorityState = \"legacy\" | \"eligible\" | \"active\" | \"rolled_back\";\n\nexport type RecipientPolicyDerivationBlockCode =\n\t| \"canonical_project_identity_invalid\"\n\t| \"project_recipient_invalid\"\n\t| \"identity_missing\"\n\t| \"identity_not_active\"\n\t| \"identity_merged\"\n\t| \"team_missing\"\n\t| \"team_not_active\"\n\t| \"team_membership_invalid\"\n\t| \"team_membership_mode_invalid\"\n\t| \"team_device_eligibility_mode_invalid\"\n\t| \"team_device_decision_invalid\"\n\t| \"team_member_identity_missing\"\n\t| \"team_member_identity_not_active\"\n\t| \"team_member_identity_merged\"\n\t| \"identity_device_invalid\"\n\t| \"device_identity_conflict\";\n\n// Keep first-block reporting stable and security-oriented rather than lexical.\nconst DERIVATION_BLOCK_PRECEDENCE: Record<RecipientPolicyDerivationBlockCode, number> = {\n\tcanonical_project_identity_invalid: 0,\n\tproject_recipient_invalid: 1,\n\tidentity_missing: 2,\n\tidentity_merged: 3,\n\tidentity_not_active: 4,\n\tteam_missing: 5,\n\tteam_not_active: 6,\n\tteam_device_eligibility_mode_invalid: 7,\n\tteam_membership_invalid: 8,\n\tteam_membership_mode_invalid: 9,\n\tteam_member_identity_missing: 10,\n\tteam_member_identity_merged: 11,\n\tteam_member_identity_not_active: 12,\n\tteam_device_decision_invalid: 13,\n\tdevice_identity_conflict: 14,\n\tidentity_device_invalid: 15,\n};\n\nexport interface RecipientPolicyDerivationIdentity {\n\tidentityId: string;\n\tstatus: string;\n\tmergedIntoIdentityId?: string | null;\n}\n\nexport interface RecipientPolicyDerivationTeam {\n\tteamId: string;\n\tstatus: string;\n\tdeviceEligibilityMode?: string;\n}\n\nexport interface RecipientPolicyDerivationTeamMembership {\n\tteamId: string;\n\tidentityId: string;\n\tstatus: string;\n}\n\nexport interface RecipientPolicyDerivationIdentityDevice {\n\tidentityId: string;\n\tdeviceId: string;\n\tstatus: string;\n\tassignmentVersion?: number;\n}\n\nexport interface RecipientPolicyDerivationTeamDeviceDecision {\n\tteamId: string;\n\tdeviceId: string;\n\tdecision: string;\n\tassignmentVersion: number;\n}\n\nexport interface RecipientPolicyDerivationProjectRecipient {\n\tcanonicalProjectIdentity: string;\n\trecipientKind: string;\n\trecipientId: string;\n\tstatus: string;\n}\n\nexport interface RecipientPolicyEffectiveDeviceSource {\n\tkind: \"direct_identity\" | \"team_membership\";\n\tteamId?: string;\n}\n\nexport interface StrictRecipientPolicyEffectiveDevice {\n\tcanonicalProjectIdentity: string;\n\tidentityId: string;\n\tdeviceId: string;\n\tsources: RecipientPolicyEffectiveDeviceSource[];\n}\n\nexport interface RecipientPolicyDerivationBlock {\n\tcode: RecipientPolicyDerivationBlockCode;\n\treferenceId: string;\n}\n\nexport interface DeriveRecipientPolicyEffectiveDevicesInput {\n\tcanonicalProjectIdentity: string;\n\tprojectRecipients: RecipientPolicyDerivationProjectRecipient[];\n\tidentities: RecipientPolicyDerivationIdentity[];\n\tteams: RecipientPolicyDerivationTeam[];\n\tteamMemberships: RecipientPolicyDerivationTeamMembership[];\n\tteamDeviceDecisions?: RecipientPolicyDerivationTeamDeviceDecision[];\n\tidentityDevices: RecipientPolicyDerivationIdentityDevice[];\n}\n\nexport interface StrictRecipientPolicyEffectiveDeviceDerivation {\n\tcanonicalProjectIdentity: string;\n\tstatus: \"eligible\" | \"blocked\";\n\tdevices: StrictRecipientPolicyEffectiveDevice[];\n\tblocked: RecipientPolicyDerivationBlock[];\n\tdesiredDevicesDigest: string;\n}\n\nexport interface RecipientPolicyAuthorityStateRecord {\n\tcanonicalProjectIdentity: string;\n\tauthorityState: RecipientPolicyAuthorityState;\n\tgeneration: number;\n\tdesiredDevicesDigest: string | null;\n\tcurrentDevicesDigest: string | null;\n\tstableParityEvidenceDigest: string | null;\n\tstableParityPassedAt: string | null;\n\tfreshSnapshotFingerprint: string | null;\n\tfreshSnapshotObservedAt: string | null;\n\tsafeErrorCode: string | null;\n\tstateChangedAt: string;\n\tlastErrorAt: string | null;\n\tattemptCount: number;\n\tlastAttemptAt: string | null;\n\tlastCompletedAt: string | null;\n\tleaseOwner: string | null;\n\tleaseAcquiredAt: string | null;\n\tleaseExpiresAt: string | null;\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\nexport interface UpsertRecipientPolicyAuthorityObservationInput {\n\tcanonicalProjectIdentity: string;\n\tgeneration: number;\n\tdesiredDevicesDigest: string;\n\tcurrentDevicesDigest: string | null;\n\tfreshSnapshotFingerprint: string | null;\n\tfreshSnapshotObservedAt: string | null;\n\tnow: string;\n}\n\nexport interface RecordRecipientPolicyAuthorityExecutionInput {\n\tcanonicalProjectIdentity: string;\n\tgeneration: number;\n\tattemptCount: number;\n\tlastAttemptAt: string | null;\n\tlastCompletedAt: string | null;\n\tsafeErrorCode: string | null;\n\tlastErrorAt: string | null;\n\tleaseOwner: string | null;\n\tleaseAcquiredAt: string | null;\n\tleaseExpiresAt: string | null;\n\tupdatedAt: string;\n}\n\nexport interface EnsureRecipientPolicyReconciliationStepInput {\n\tcanonicalProjectIdentity: string;\n\tgeneration: number;\n\tstepKey: string;\n\tpayloadDigest: string;\n\tnow: string;\n}\n\nexport interface RecordRecipientPolicyReconciliationStepStateInput {\n\tcanonicalProjectIdentity: string;\n\tgeneration: number;\n\tstepKey: string;\n\teffectId: string;\n\tstatus: \"pending\" | \"running\" | \"waiting\" | \"completed\" | \"failed\";\n\tattemptCount: number;\n\tstartedAt: string | null;\n\tcompletedAt: string | null;\n\tlastAttemptAt: string | null;\n\tsafeErrorCode: string | null;\n\terrorAt: string | null;\n\tleaseOwner: string | null;\n\tleaseAcquiredAt: string | null;\n\tleaseExpiresAt: string | null;\n\tupdatedAt: string;\n}\n\nexport interface RecipientPolicyReconciliationStepRecord {\n\tcanonicalProjectIdentity: string;\n\tgeneration: number;\n\tstepKey: string;\n\teffectId: string;\n\tpayloadDigest: string;\n\tstatus: string;\n\tattemptCount: number;\n\tstartedAt: string | null;\n\tcompletedAt: string | null;\n\tlastAttemptAt: string | null;\n\tsafeErrorCode: string | null;\n\terrorAt: string | null;\n\tleaseOwner: string | null;\n\tleaseAcquiredAt: string | null;\n\tleaseExpiresAt: string | null;\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\nexport interface PendingRecipientPolicyRevocationRefreshStep {\n\tgeneration: number;\n\tstepKey: string;\n}\n\nexport interface PendingRecipientPolicyRefreshStep {\n\tgeneration: number;\n\tstepKey: string;\n}\n\nexport interface PruneRecipientPolicyReconciliationStepsInput {\n\tcanonicalProjectIdentity: string;\n\tretainCompletedPerKind?: number;\n}\n\nexport interface PruneSupersededRecipientPolicyCapabilityStepsInput {\n\tcanonicalProjectIdentity: string;\n\tactiveGeneration: number;\n\tactivePassKey: string;\n}\n\nexport interface RecipientPolicyDenyOverlayRecord {\n\tcanonicalProjectIdentity: string;\n\tscopeId: string;\n\tdeviceId: string;\n\tgeneration: number;\n\treasonCode: string;\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\nconst KNOWN_DEVICE_STATUSES = new Set([\"active\", \"revoked\"]);\nconst DEFAULT_COMPLETED_STEP_RETENTION_PER_KIND = 256;\nconst MAX_PENDING_REVOCATION_REFRESH_STEPS = 64;\nconst MAX_RECONCILIATION_STEP_KEY_UTF16_UNITS = 1_024;\nconst RECONCILIATION_STEP_KEY_CONTROL_OR_FORMAT_CHARACTER = /[\\p{Cc}\\p{Cf}]/u;\nconst PRUNABLE_COMPLETED_STEP_PATTERNS = [\"capability:*\", \"refresh:*\"] as const;\nexport const PENDING_RECIPIENT_POLICY_REVOCATION_REFRESH_STEPS_SQL = `SELECT generation, step_key FROM recipient_policy_reconciliation_steps\n\t WHERE canonical_project_identity = ?\n\t AND step_key GLOB 'refresh-after-revocations-v2:*'\n\t AND status IN ('pending', 'running', 'failed')\n\t ORDER BY generation, step_key\n\t LIMIT ?`;\nconst KNOWN_RECIPIENT_STATUSES = new Set([\"active\", \"revoked\"]);\n\nfunction compareText(left: string, right: string): number {\n\treturn left < right ? -1 : left > right ? 1 : 0;\n}\n\nfunction isStrictRecipientPolicyReconciliationStepKey(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue === value.trim() &&\n\t\tvalue.length <= MAX_RECONCILIATION_STEP_KEY_UTF16_UNITS &&\n\t\t!RECONCILIATION_STEP_KEY_CONTROL_OR_FORMAT_CHARACTER.test(value)\n\t);\n}\n\nconst digest = legacyRecipientPolicyDigest;\n\nfunction sourceKey(source: RecipientPolicyEffectiveDeviceSource): string {\n\treturn source.kind === \"direct_identity\" ? source.kind : `${source.kind}\\u0000${source.teamId}`;\n}\n\nfunction block(\n\tblocked: Map<string, RecipientPolicyDerivationBlock>,\n\tcode: RecipientPolicyDerivationBlockCode,\n\treferenceId: string,\n): void {\n\tblocked.set(`${code}\\u0000${referenceId}`, { code, referenceId });\n}\n\nfunction activeIdentityCode(\n\tidentity: RecipientPolicyDerivationIdentity | undefined,\n\tmissing: RecipientPolicyDerivationBlockCode,\n\tinactive: RecipientPolicyDerivationBlockCode,\n\tmerged: RecipientPolicyDerivationBlockCode,\n): RecipientPolicyDerivationBlockCode | null {\n\tif (!identity) return missing;\n\tif (identity.status === \"merged\" || identity.mergedIntoIdentityId) return merged;\n\tif (identity.status !== \"active\") return inactive;\n\treturn null;\n}\n\nfunction addEffectiveDevice(\n\teffective: Map<string, StrictRecipientPolicyEffectiveDevice>,\n\tdeviceOwners: Map<string, string>,\n\tprojectId: string,\n\tidentityId: string,\n\tdeviceId: string,\n\tsource: RecipientPolicyEffectiveDeviceSource,\n\tblocked: Map<string, RecipientPolicyDerivationBlock>,\n): void {\n\tconst owner = deviceOwners.get(deviceId);\n\tif (owner && owner !== identityId) {\n\t\tblock(blocked, \"device_identity_conflict\", deviceId);\n\t\treturn;\n\t}\n\tdeviceOwners.set(deviceId, identityId);\n\tconst current = effective.get(deviceId);\n\tconst sources = new Map((current?.sources ?? []).map((item) => [sourceKey(item), item]));\n\tsources.set(sourceKey(source), source);\n\teffective.set(deviceId, {\n\t\tcanonicalProjectIdentity: projectId,\n\t\tidentityId,\n\t\tdeviceId,\n\t\tsources: [...sources.values()].toSorted((left, right) =>\n\t\t\tcompareText(sourceKey(left), sourceKey(right)),\n\t\t),\n\t});\n}\n\nexport function recipientPolicyDevicesDigest(\n\tdevices: readonly StrictRecipientPolicyEffectiveDevice[],\n): string {\n\treturn digest(\n\t\t\"recipient-policy-devices-v1\",\n\t\tdevices\n\t\t\t.toSorted(\n\t\t\t\t(left, right) =>\n\t\t\t\t\tcompareText(left.canonicalProjectIdentity, right.canonicalProjectIdentity) ||\n\t\t\t\t\tcompareText(left.deviceId, right.deviceId) ||\n\t\t\t\t\tcompareText(left.identityId, right.identityId),\n\t\t\t)\n\t\t\t.map((device) => ({\n\t\t\t\tcanonicalProjectIdentity: device.canonicalProjectIdentity,\n\t\t\t\tidentityId: device.identityId,\n\t\t\t\tdeviceId: device.deviceId,\n\t\t\t\tsources: device.sources.toSorted((left, right) =>\n\t\t\t\t\tcompareText(sourceKey(left), sourceKey(right)),\n\t\t\t\t),\n\t\t\t})),\n\t);\n}\n\nexport function deriveRecipientPolicyEffectiveDevices(\n\tinput: DeriveRecipientPolicyEffectiveDevicesInput,\n): StrictRecipientPolicyEffectiveDeviceDerivation {\n\tconst blocked = new Map<string, RecipientPolicyDerivationBlock>();\n\tif (!isStrictRecipientPolicyProjectIdentity(input.canonicalProjectIdentity)) {\n\t\tblock(blocked, \"canonical_project_identity_invalid\", input.canonicalProjectIdentity);\n\t}\n\tconst identities = new Map(input.identities.map((identity) => [identity.identityId, identity]));\n\tconst eligibilityIdentities = input.identities.map((identity) => ({\n\t\tidentityId: identity.identityId,\n\t\tstatus: identity.status,\n\t\tmergedIntoIdentityId: identity.mergedIntoIdentityId ?? null,\n\t}));\n\tconst teams = new Map(input.teams.map((team) => [team.teamId, team]));\n\tconst membershipsByTeam = new Map<string, RecipientPolicyDerivationTeamMembership[]>();\n\tfor (const membership of input.teamMemberships) {\n\t\tconst current = membershipsByTeam.get(membership.teamId) ?? [];\n\t\tcurrent.push(membership);\n\t\tmembershipsByTeam.set(membership.teamId, current);\n\t}\n\tconst decisionsByTeam = new Map<string, RecipientPolicyDerivationTeamDeviceDecision[]>();\n\tfor (const decision of input.teamDeviceDecisions ?? []) {\n\t\tconst current = decisionsByTeam.get(decision.teamId) ?? [];\n\t\tcurrent.push(decision);\n\t\tdecisionsByTeam.set(decision.teamId, current);\n\t}\n\tconst devicesByIdentity = new Map<string, RecipientPolicyDerivationIdentityDevice[]>();\n\tfor (const device of input.identityDevices) {\n\t\tconst current = devicesByIdentity.get(device.identityId) ?? [];\n\t\tcurrent.push(device);\n\t\tdevicesByIdentity.set(device.identityId, current);\n\t}\n\tconst legacyEligibilityDevices = input.identityDevices.map((device) => ({\n\t\t...device,\n\t\tassignmentVersion: device.assignmentVersion ?? 0,\n\t}));\n\tconst reviewedEligibilityDevices = input.identityDevices.map((device) => ({\n\t\t...device,\n\t\t// Reviewed access requires present assignment evidence. NaN deliberately\n\t\t// fails the shared safe-integer validation instead of treating omission as v0.\n\t\tassignmentVersion: device.assignmentVersion ?? Number.NaN,\n\t}));\n\tconst effective = new Map<string, StrictRecipientPolicyEffectiveDevice>();\n\tconst deviceOwners = new Map<string, string>();\n\tconst expandIdentity = (\n\t\tidentityId: string,\n\t\tsource: RecipientPolicyEffectiveDeviceSource,\n\t\tcodes: readonly [\n\t\t\tRecipientPolicyDerivationBlockCode,\n\t\t\tRecipientPolicyDerivationBlockCode,\n\t\t\tRecipientPolicyDerivationBlockCode,\n\t\t],\n\t\tallowedDeviceIds?: ReadonlySet<string>,\n\t): void => {\n\t\tconst identityCode = activeIdentityCode(identities.get(identityId), ...codes);\n\t\tif (identityCode) {\n\t\t\tblock(blocked, identityCode, identityId);\n\t\t\treturn;\n\t\t}\n\t\tfor (const device of devicesByIdentity.get(identityId) ?? []) {\n\t\t\tif (!KNOWN_DEVICE_STATUSES.has(device.status)) {\n\t\t\t\tblock(blocked, \"identity_device_invalid\", device.deviceId);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (device.status !== \"active\") continue;\n\t\t\tif (allowedDeviceIds && !allowedDeviceIds.has(device.deviceId)) continue;\n\t\t\tif (\n\t\t\t\t!isStrictRecipientPolicyId(device.identityId) ||\n\t\t\t\t!isStrictRecipientPolicyId(device.deviceId)\n\t\t\t) {\n\t\t\t\tblock(blocked, \"identity_device_invalid\", device.deviceId);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\taddEffectiveDevice(\n\t\t\t\teffective,\n\t\t\t\tdeviceOwners,\n\t\t\t\tinput.canonicalProjectIdentity,\n\t\t\t\tidentityId,\n\t\t\t\tdevice.deviceId,\n\t\t\t\tsource,\n\t\t\t\tblocked,\n\t\t\t);\n\t\t}\n\t};\n\tconst projectRecipients = input.projectRecipients.filter(\n\t\t(recipient) => recipient.canonicalProjectIdentity === input.canonicalProjectIdentity,\n\t);\n\tfor (const recipient of projectRecipients) {\n\t\tif (!KNOWN_RECIPIENT_STATUSES.has(recipient.status)) {\n\t\t\tblock(blocked, \"project_recipient_invalid\", recipient.recipientId);\n\t\t\tcontinue;\n\t\t}\n\t\tif (recipient.status !== \"active\") continue;\n\t\tif (!isStrictRecipientPolicyId(recipient.recipientId)) {\n\t\t\tblock(blocked, \"project_recipient_invalid\", recipient.recipientId);\n\t\t\tcontinue;\n\t\t}\n\t\tif (recipient.recipientKind === \"identity\") {\n\t\t\texpandIdentity(recipient.recipientId, { kind: \"direct_identity\" }, [\n\t\t\t\t\"identity_missing\",\n\t\t\t\t\"identity_not_active\",\n\t\t\t\t\"identity_merged\",\n\t\t\t]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (recipient.recipientKind !== \"team\") {\n\t\t\tblock(blocked, \"project_recipient_invalid\", recipient.recipientId);\n\t\t\tcontinue;\n\t\t}\n\t\tconst team = teams.get(recipient.recipientId);\n\t\tif (!team) {\n\t\t\tblock(blocked, \"team_missing\", recipient.recipientId);\n\t\t\tcontinue;\n\t\t}\n\t\tif (team.status !== \"active\") {\n\t\t\tblock(blocked, \"team_not_active\", recipient.recipientId);\n\t\t\tcontinue;\n\t\t}\n\t\tconst memberships = membershipsByTeam.get(team.teamId) ?? [];\n\t\tfor (const membership of memberships) {\n\t\t\tif (\n\t\t\t\t!isStrictRecipientPolicyId(membership.teamId) ||\n\t\t\t\t!isStrictRecipientPolicyId(membership.identityId)\n\t\t\t) {\n\t\t\t\tblock(blocked, \"team_membership_invalid\", `${membership.teamId}:${membership.identityId}`);\n\t\t\t}\n\t\t}\n\t\tconst eligibility = derivePolicyTeamDeviceEligibility({\n\t\t\tteamId: team.teamId,\n\t\t\tmode: team.deviceEligibilityMode ?? \"person_all_devices\",\n\t\t\tmemberships,\n\t\t\tidentities: eligibilityIdentities,\n\t\t\tdevices:\n\t\t\t\tteam.deviceEligibilityMode === \"reviewed_allowlist\"\n\t\t\t\t\t? reviewedEligibilityDevices\n\t\t\t\t\t: legacyEligibilityDevices,\n\t\t\tdecisions: decisionsByTeam.get(team.teamId) ?? [],\n\t\t});\n\t\tfor (const item of eligibility.blocked) block(blocked, item.code, item.referenceId);\n\t\tif (eligibility.status === \"blocked\") continue;\n\t\tconst eligibleDeviceIds = new Set(eligibility.eligibleDeviceIds);\n\t\tfor (const identityId of eligibility.activeMemberIdentityIds) {\n\t\t\texpandIdentity(\n\t\t\t\tidentityId,\n\t\t\t\t{ kind: \"team_membership\", teamId: team.teamId },\n\t\t\t\t[\n\t\t\t\t\t\"team_member_identity_missing\",\n\t\t\t\t\t\"team_member_identity_not_active\",\n\t\t\t\t\t\"team_member_identity_merged\",\n\t\t\t\t],\n\t\t\t\teligibleDeviceIds,\n\t\t\t);\n\t\t}\n\t}\n\tconst blockedItems = [...blocked.values()].toSorted(\n\t\t(left, right) =>\n\t\t\tDERIVATION_BLOCK_PRECEDENCE[left.code] - DERIVATION_BLOCK_PRECEDENCE[right.code] ||\n\t\t\tcompareText(left.referenceId, right.referenceId),\n\t);\n\tconst devices = [...effective.values()].toSorted(\n\t\t(left, right) =>\n\t\t\tcompareText(left.deviceId, right.deviceId) || compareText(left.identityId, right.identityId),\n\t);\n\tconst grantCandidates = blockedItems.length === 0 ? devices : [];\n\treturn {\n\t\tcanonicalProjectIdentity: input.canonicalProjectIdentity,\n\t\tstatus: blockedItems.length === 0 ? \"eligible\" : \"blocked\",\n\t\tdevices: grantCandidates,\n\t\tblocked: blockedItems,\n\t\tdesiredDevicesDigest: recipientPolicyDevicesDigest(grantCandidates),\n\t};\n}\n\ninterface StoredProjectRecipientRow {\n\tcanonical_project_identity: string;\n\trecipient_kind: string;\n\trecipient_id: string;\n\tstatus: string;\n\tupdated_at: string;\n}\n\nfunction canonicalProjectRecipientRows(\n\tdb: Database,\n\tcanonicalProjectIdentity: string,\n): StoredProjectRecipientRow[] {\n\tconst repositoryIdentities = repositoryIdentitiesByWorkspace(db);\n\tconst canonicalIdentity = canonicalRepositoryProjectIdentity(\n\t\trepositoryIdentities,\n\t\tcanonicalProjectIdentity,\n\t);\n\tconst aliases = [\n\t\t...new Set([\n\t\t\tcanonicalIdentity,\n\t\t\tcanonicalProjectIdentity,\n\t\t\t...[...repositoryIdentities]\n\t\t\t\t.filter(([, identity]) => identity === canonicalIdentity)\n\t\t\t\t.map(([workspace]) => workspace),\n\t\t]),\n\t];\n\tconst rows = db\n\t\t.prepare(\n\t\t\t`SELECT canonical_project_identity, recipient_kind, recipient_id, status, updated_at\n\t\t\t FROM project_recipients\n\t\t\t WHERE canonical_project_identity IN (SELECT value FROM json_each(?))\n\t\t\t ORDER BY recipient_kind, recipient_id`,\n\t\t)\n\t\t.all(JSON.stringify(aliases)) as StoredProjectRecipientRow[];\n\tconst rowsByRecipient = new Map<string, StoredProjectRecipientRow>();\n\tfor (const row of rows) {\n\t\tconst rowCanonicalIdentity = canonicalRepositoryProjectIdentity(\n\t\t\trepositoryIdentities,\n\t\t\trow.canonical_project_identity,\n\t\t);\n\t\tif (rowCanonicalIdentity !== canonicalIdentity) continue;\n\t\tconst key = `${row.recipient_kind}\\u0000${row.recipient_id}`;\n\t\tconst current = rowsByRecipient.get(key);\n\t\tif (!current) {\n\t\t\trowsByRecipient.set(key, row);\n\t\t\tcontinue;\n\t\t}\n\t\tconst currentIsCanonical = current.canonical_project_identity === canonicalIdentity;\n\t\tconst rowIsCanonical = row.canonical_project_identity === canonicalIdentity;\n\t\tif (currentIsCanonical && !rowIsCanonical) continue;\n\t\tif (rowIsCanonical || row.updated_at > current.updated_at) rowsByRecipient.set(key, row);\n\t}\n\treturn [...rowsByRecipient.values()].map((row) => ({\n\t\t...row,\n\t\tcanonical_project_identity: canonicalIdentity,\n\t}));\n}\n\nexport function deriveRecipientPolicyEffectiveDevicesFromDatabase(\n\tdb: Database,\n\tcanonicalProjectIdentity: string,\n): StrictRecipientPolicyEffectiveDeviceDerivation {\n\tconst repositoryIdentities = repositoryIdentitiesByWorkspace(db);\n\tconst canonicalIdentity = canonicalRepositoryProjectIdentity(\n\t\trepositoryIdentities,\n\t\tcanonicalProjectIdentity,\n\t);\n\tconst projectRecipients = canonicalProjectRecipientRows(db, canonicalIdentity);\n\tconst identities = db\n\t\t.prepare(\"SELECT actor_id, status, merged_into_actor_id FROM actors ORDER BY actor_id\")\n\t\t.all() as Array<{ actor_id: string; status: string; merged_into_actor_id: string | null }>;\n\tconst teams = db\n\t\t.prepare(\"SELECT team_id, status, device_eligibility_mode FROM policy_teams ORDER BY team_id\")\n\t\t.all() as Array<{\n\t\tteam_id: string;\n\t\tstatus: string;\n\t\tdevice_eligibility_mode: string;\n\t}>;\n\tconst teamMemberships = db\n\t\t.prepare(\n\t\t\t\"SELECT team_id, identity_id, status FROM policy_team_memberships ORDER BY team_id, identity_id\",\n\t\t)\n\t\t.all() as Array<{ team_id: string; identity_id: string; status: string }>;\n\tconst identityDevices = db\n\t\t.prepare(\n\t\t\t\"SELECT identity_id, device_id, status, assignment_version FROM identity_devices ORDER BY identity_id, device_id\",\n\t\t)\n\t\t.all() as Array<{\n\t\tidentity_id: string;\n\t\tdevice_id: string;\n\t\tstatus: string;\n\t\tassignment_version: number;\n\t}>;\n\tconst teamDeviceDecisions = db\n\t\t.prepare(\n\t\t\t\"SELECT team_id, device_id, decision, assignment_version FROM policy_team_device_decisions ORDER BY team_id, device_id\",\n\t\t)\n\t\t.all() as Array<{\n\t\tteam_id: string;\n\t\tdevice_id: string;\n\t\tdecision: string;\n\t\tassignment_version: number;\n\t}>;\n\treturn deriveRecipientPolicyEffectiveDevices({\n\t\tcanonicalProjectIdentity: canonicalIdentity,\n\t\tprojectRecipients: projectRecipients.map((row) => ({\n\t\t\tcanonicalProjectIdentity: row.canonical_project_identity,\n\t\t\trecipientKind: row.recipient_kind,\n\t\t\trecipientId: row.recipient_id,\n\t\t\tstatus: row.status,\n\t\t})),\n\t\tidentities: identities.map((row) => ({\n\t\t\tidentityId: row.actor_id,\n\t\t\tstatus: row.status,\n\t\t\tmergedIntoIdentityId: row.merged_into_actor_id,\n\t\t})),\n\t\tteams: teams.map((row) => ({\n\t\t\tteamId: row.team_id,\n\t\t\tstatus: row.status,\n\t\t\tdeviceEligibilityMode: row.device_eligibility_mode,\n\t\t})),\n\t\tteamMemberships: teamMemberships.map((row) => ({\n\t\t\tteamId: row.team_id,\n\t\t\tidentityId: row.identity_id,\n\t\t\tstatus: row.status,\n\t\t})),\n\t\tteamDeviceDecisions: teamDeviceDecisions.map((row) => ({\n\t\t\tteamId: row.team_id,\n\t\t\tdeviceId: row.device_id,\n\t\t\tdecision: row.decision,\n\t\t\tassignmentVersion: row.assignment_version,\n\t\t})),\n\t\tidentityDevices: identityDevices.map((row) => ({\n\t\t\tidentityId: row.identity_id,\n\t\t\tdeviceId: row.device_id,\n\t\t\tstatus: row.status,\n\t\t\tassignmentVersion: row.assignment_version,\n\t\t})),\n\t});\n}\n\nfunction authorityRow(row: Record<string, unknown>): RecipientPolicyAuthorityStateRecord {\n\treturn {\n\t\tcanonicalProjectIdentity: String(row.canonical_project_identity),\n\t\tauthorityState: row.authority_state as RecipientPolicyAuthorityState,\n\t\tgeneration: Number(row.generation),\n\t\tdesiredDevicesDigest: row.desired_devices_digest as string | null,\n\t\tcurrentDevicesDigest: row.current_devices_digest as string | null,\n\t\tstableParityEvidenceDigest: row.stable_parity_evidence_digest as string | null,\n\t\tstableParityPassedAt: row.stable_parity_passed_at as string | null,\n\t\tfreshSnapshotFingerprint: row.fresh_snapshot_fingerprint as string | null,\n\t\tfreshSnapshotObservedAt: row.fresh_snapshot_observed_at as string | null,\n\t\tsafeErrorCode: row.safe_error_code as string | null,\n\t\tstateChangedAt: String(row.state_changed_at),\n\t\tlastErrorAt: row.last_error_at as string | null,\n\t\tattemptCount: Number(row.attempt_count),\n\t\tlastAttemptAt: row.last_attempt_at as string | null,\n\t\tlastCompletedAt: row.last_completed_at as string | null,\n\t\tleaseOwner: row.lease_owner as string | null,\n\t\tleaseAcquiredAt: row.lease_acquired_at as string | null,\n\t\tleaseExpiresAt: row.lease_expires_at as string | null,\n\t\tcreatedAt: String(row.created_at),\n\t\tupdatedAt: String(row.updated_at),\n\t};\n}\n\nexport function getRecipientPolicyAuthorityState(\n\tdb: Database,\n\tcanonicalProjectIdentity: string,\n): RecipientPolicyAuthorityStateRecord | null {\n\tconst row = db\n\t\t.prepare(\"SELECT * FROM recipient_policy_authority_states WHERE canonical_project_identity = ?\")\n\t\t.get(canonicalProjectIdentity) as Record<string, unknown> | undefined;\n\treturn row ? authorityRow(row) : null;\n}\n\nexport function upsertRecipientPolicyAuthorityObservation(\n\tdb: Database,\n\tinput: UpsertRecipientPolicyAuthorityObservationInput,\n): RecipientPolicyAuthorityStateRecord {\n\tif (\n\t\t!isStrictRecipientPolicyProjectIdentity(input.canonicalProjectIdentity) ||\n\t\t!Number.isSafeInteger(input.generation) ||\n\t\tinput.generation < 0\n\t) {\n\t\tthrow new Error(\"recipient_policy_authority_observation_invalid\");\n\t}\n\tconst existing = getRecipientPolicyAuthorityState(db, input.canonicalProjectIdentity);\n\tif (existing && input.generation < existing.generation) {\n\t\tthrow new Error(\"recipient_policy_generation_stale\");\n\t}\n\tif (\n\t\texisting &&\n\t\tinput.generation === existing.generation &&\n\t\texisting.desiredDevicesDigest !== input.desiredDevicesDigest\n\t) {\n\t\tthrow new Error(\"recipient_policy_generation_conflict\");\n\t}\n\tdb.prepare(\n\t\t`INSERT INTO recipient_policy_authority_states(\n\t\t canonical_project_identity, authority_state, generation, desired_devices_digest,\n\t\t current_devices_digest, fresh_snapshot_fingerprint, fresh_snapshot_observed_at,\n\t\t state_changed_at, created_at, updated_at\n\t\t ) VALUES (?, 'legacy', ?, ?, ?, ?, ?, ?, ?, ?)\n\t\t ON CONFLICT(canonical_project_identity) DO UPDATE SET\n\t\t generation = excluded.generation,\n\t\t desired_devices_digest = excluded.desired_devices_digest,\n\t\t current_devices_digest = excluded.current_devices_digest,\n\t\t fresh_snapshot_fingerprint = excluded.fresh_snapshot_fingerprint,\n\t\t fresh_snapshot_observed_at = excluded.fresh_snapshot_observed_at,\n\t\t stable_parity_evidence_digest = CASE\n\t\t WHEN recipient_policy_authority_states.generation = excluded.generation\n\t\t THEN recipient_policy_authority_states.stable_parity_evidence_digest ELSE NULL END,\n\t\t stable_parity_passed_at = CASE\n\t\t WHEN recipient_policy_authority_states.generation = excluded.generation\n\t\t THEN recipient_policy_authority_states.stable_parity_passed_at ELSE NULL END,\n\t\t updated_at = excluded.updated_at`,\n\t).run(\n\t\tinput.canonicalProjectIdentity,\n\t\tinput.generation,\n\t\tinput.desiredDevicesDigest,\n\t\tinput.currentDevicesDigest,\n\t\tinput.freshSnapshotFingerprint,\n\t\tinput.freshSnapshotObservedAt,\n\t\tinput.now,\n\t\tinput.now,\n\t\tinput.now,\n\t);\n\tconst state = getRecipientPolicyAuthorityState(db, input.canonicalProjectIdentity);\n\tif (!state) throw new Error(\"recipient_policy_authority_state_missing\");\n\treturn state;\n}\n\nexport function recordRecipientPolicyStableParityPass(\n\tdb: Database,\n\tinput: {\n\t\tcanonicalProjectIdentity: string;\n\t\tgeneration: number;\n\t\tevidenceDigest: string;\n\t\tsnapshotFingerprint: string;\n\t\tpassedAt: string;\n\t},\n): RecipientPolicyAuthorityStateRecord {\n\tconst state = getRecipientPolicyAuthorityState(db, input.canonicalProjectIdentity);\n\tif (\n\t\t!state ||\n\t\tstate.generation !== input.generation ||\n\t\tstate.desiredDevicesDigest === null ||\n\t\tstate.desiredDevicesDigest !== state.currentDevicesDigest ||\n\t\tstate.freshSnapshotFingerprint !== input.snapshotFingerprint\n\t) {\n\t\tthrow new Error(\"recipient_policy_parity_evidence_invalid\");\n\t}\n\tif (\n\t\tstate.stableParityEvidenceDigest &&\n\t\t(state.stableParityEvidenceDigest !== input.evidenceDigest ||\n\t\t\tstate.stableParityPassedAt !== input.passedAt)\n\t) {\n\t\tthrow new Error(\"recipient_policy_parity_evidence_conflict\");\n\t}\n\tdb.prepare(\n\t\t`UPDATE recipient_policy_authority_states\n\t\t SET stable_parity_evidence_digest = ?, stable_parity_passed_at = ?, updated_at = ?\n\t\t WHERE canonical_project_identity = ?`,\n\t).run(input.evidenceDigest, input.passedAt, input.passedAt, input.canonicalProjectIdentity);\n\tconst updated = getRecipientPolicyAuthorityState(db, input.canonicalProjectIdentity);\n\tif (!updated) throw new Error(\"recipient_policy_authority_state_missing\");\n\treturn updated;\n}\n\nexport function recordRecipientPolicyAuthorityExecution(\n\tdb: Database,\n\tinput: RecordRecipientPolicyAuthorityExecutionInput,\n): RecipientPolicyAuthorityStateRecord {\n\tconst state = getRecipientPolicyAuthorityState(db, input.canonicalProjectIdentity);\n\tif (!state || state.generation !== input.generation) {\n\t\tthrow new Error(\"recipient_policy_authority_generation_missing\");\n\t}\n\tif (!Number.isSafeInteger(input.attemptCount) || input.attemptCount < state.attemptCount) {\n\t\tthrow new Error(\"recipient_policy_reconciliation_attempt_stale\");\n\t}\n\tdb.prepare(\n\t\t`UPDATE recipient_policy_authority_states SET\n\t\t attempt_count = ?, last_attempt_at = ?, last_completed_at = ?, safe_error_code = ?,\n\t\t last_error_at = ?, lease_owner = ?, lease_acquired_at = ?, lease_expires_at = ?,\n\t\t updated_at = ?\n\t\t WHERE canonical_project_identity = ? AND generation = ?`,\n\t).run(\n\t\tinput.attemptCount,\n\t\tinput.lastAttemptAt,\n\t\tinput.lastCompletedAt,\n\t\tinput.safeErrorCode,\n\t\tinput.lastErrorAt,\n\t\tinput.leaseOwner,\n\t\tinput.leaseAcquiredAt,\n\t\tinput.leaseExpiresAt,\n\t\tinput.updatedAt,\n\t\tinput.canonicalProjectIdentity,\n\t\tinput.generation,\n\t);\n\tconst updated = getRecipientPolicyAuthorityState(db, input.canonicalProjectIdentity);\n\tif (!updated) throw new Error(\"recipient_policy_authority_state_missing\");\n\treturn updated;\n}\n\nexport function deterministicRecipientPolicyReconciliationEffectId(input: {\n\tcanonicalProjectIdentity: string;\n\tgeneration: number;\n\tstepKey: string;\n\tpayloadDigest: string;\n}): string {\n\treturn digest(\"recipient-policy-reconciliation-effect-v1\", {\n\t\tcanonicalProjectIdentity: input.canonicalProjectIdentity,\n\t\tgeneration: input.generation,\n\t\tstepKey: input.stepKey,\n\t\tpayloadDigest: input.payloadDigest,\n\t});\n}\n\nfunction stepRow(row: Record<string, unknown>): RecipientPolicyReconciliationStepRecord {\n\treturn {\n\t\tcanonicalProjectIdentity: String(row.canonical_project_identity),\n\t\tgeneration: Number(row.generation),\n\t\tstepKey: String(row.step_key),\n\t\teffectId: String(row.effect_id),\n\t\tpayloadDigest: String(row.payload_digest),\n\t\tstatus: String(row.status),\n\t\tattemptCount: Number(row.attempt_count),\n\t\tstartedAt: row.started_at as string | null,\n\t\tcompletedAt: row.completed_at as string | null,\n\t\tlastAttemptAt: row.last_attempt_at as string | null,\n\t\tsafeErrorCode: row.safe_error_code as string | null,\n\t\terrorAt: row.error_at as string | null,\n\t\tleaseOwner: row.lease_owner as string | null,\n\t\tleaseAcquiredAt: row.lease_acquired_at as string | null,\n\t\tleaseExpiresAt: row.lease_expires_at as string | null,\n\t\tcreatedAt: String(row.created_at),\n\t\tupdatedAt: String(row.updated_at),\n\t};\n}\n\nexport function listPendingRecipientPolicyRevocationRefreshSteps(\n\tdb: Database,\n\tcanonicalProjectIdentity: string,\n\tlimit = MAX_PENDING_REVOCATION_REFRESH_STEPS,\n): PendingRecipientPolicyRevocationRefreshStep[] {\n\tif (\n\t\t!isStrictRecipientPolicyProjectIdentity(canonicalProjectIdentity) ||\n\t\t!Number.isSafeInteger(limit) ||\n\t\tlimit < 1 ||\n\t\tlimit > MAX_PENDING_REVOCATION_REFRESH_STEPS\n\t) {\n\t\tthrow new Error(\"recipient_policy_reconciliation_step_invalid\");\n\t}\n\tconst rows = db\n\t\t.prepare(PENDING_RECIPIENT_POLICY_REVOCATION_REFRESH_STEPS_SQL)\n\t\t.all(canonicalProjectIdentity, limit) as Array<{ generation: number; step_key: string }>;\n\treturn rows.map((row) => ({ generation: row.generation, stepKey: row.step_key }));\n}\n\nexport function listPendingRecipientPolicyRefreshSteps(\n\tdb: Database,\n\tcanonicalProjectIdentity: string,\n\tlimit = MAX_PENDING_REVOCATION_REFRESH_STEPS,\n): PendingRecipientPolicyRefreshStep[] {\n\tif (\n\t\t!isStrictRecipientPolicyProjectIdentity(canonicalProjectIdentity) ||\n\t\t!Number.isSafeInteger(limit) ||\n\t\tlimit < 1 ||\n\t\tlimit > MAX_PENDING_REVOCATION_REFRESH_STEPS\n\t) {\n\t\tthrow new Error(\"recipient_policy_reconciliation_step_invalid\");\n\t}\n\tconst rows = db\n\t\t.prepare(\n\t\t\t`SELECT generation, step_key FROM recipient_policy_reconciliation_steps\n\t\t\t WHERE canonical_project_identity = ?\n\t\t\t AND step_key GLOB 'refresh:*'\n\t\t\t AND status IN ('pending', 'running', 'failed')\n\t\t\t ORDER BY generation, step_key\n\t\t\t LIMIT ?`,\n\t\t)\n\t\t.all(canonicalProjectIdentity, limit) as Array<{ generation: number; step_key: string }>;\n\treturn rows.map((row) => ({ generation: row.generation, stepKey: row.step_key }));\n}\n\nexport function pruneRecipientPolicyReconciliationSteps(\n\tdb: Database,\n\tinput: PruneRecipientPolicyReconciliationStepsInput,\n): number {\n\tconst retainCompletedPerKind =\n\t\tinput.retainCompletedPerKind ?? DEFAULT_COMPLETED_STEP_RETENTION_PER_KIND;\n\tif (\n\t\t!isStrictRecipientPolicyProjectIdentity(input.canonicalProjectIdentity) ||\n\t\t!Number.isSafeInteger(retainCompletedPerKind) ||\n\t\tretainCompletedPerKind < 0\n\t) {\n\t\tthrow new Error(\"recipient_policy_reconciliation_step_invalid\");\n\t}\n\tconst remove = db.prepare(\n\t\t`DELETE FROM recipient_policy_reconciliation_steps\n\t\t WHERE canonical_project_identity = ? AND status = 'completed' AND step_key GLOB ?\n\t\t AND rowid NOT IN (\n\t\t\t SELECT rowid FROM recipient_policy_reconciliation_steps\n\t\t\t WHERE canonical_project_identity = ? AND status = 'completed' AND step_key GLOB ?\n\t\t\t ORDER BY updated_at DESC, generation DESC, step_key DESC\n\t\t\t LIMIT ?\n\t\t )`,\n\t);\n\treturn db\n\t\t.transaction(() => {\n\t\t\tlet deleted = 0;\n\t\t\tfor (const pattern of PRUNABLE_COMPLETED_STEP_PATTERNS) {\n\t\t\t\tdeleted += remove.run(\n\t\t\t\t\tinput.canonicalProjectIdentity,\n\t\t\t\t\tpattern,\n\t\t\t\t\tinput.canonicalProjectIdentity,\n\t\t\t\t\tpattern,\n\t\t\t\t\tretainCompletedPerKind,\n\t\t\t\t).changes;\n\t\t\t}\n\t\t\treturn deleted;\n\t\t})\n\t\t.immediate();\n}\n\nexport function pruneSupersededRecipientPolicyCapabilitySteps(\n\tdb: Database,\n\tinput: PruneSupersededRecipientPolicyCapabilityStepsInput,\n): number {\n\tif (\n\t\t!isStrictRecipientPolicyProjectIdentity(input.canonicalProjectIdentity) ||\n\t\t!Number.isSafeInteger(input.activeGeneration) ||\n\t\tinput.activeGeneration < 0 ||\n\t\t!isStrictRecipientPolicyId(input.activePassKey)\n\t) {\n\t\tthrow new Error(\"recipient_policy_reconciliation_step_invalid\");\n\t}\n\tconst activeStepPrefix = `capability:${input.activePassKey}:`;\n\treturn db\n\t\t.prepare(\n\t\t\t`DELETE FROM recipient_policy_reconciliation_steps\n\t\t\t WHERE canonical_project_identity = ?\n\t\t\t AND status IN ('pending', 'running', 'failed')\n\t\t\t AND step_key GLOB 'capability:*'\n\t\t\t AND (generation <> ? OR substr(step_key, 1, length(?)) <> ?)`,\n\t\t)\n\t\t.run(input.canonicalProjectIdentity, input.activeGeneration, activeStepPrefix, activeStepPrefix)\n\t\t.changes;\n}\n\nexport function ensureRecipientPolicyReconciliationStep(\n\tdb: Database,\n\tinput: EnsureRecipientPolicyReconciliationStepInput,\n): RecipientPolicyReconciliationStepRecord {\n\tif (\n\t\t!isStrictRecipientPolicyProjectIdentity(input.canonicalProjectIdentity) ||\n\t\t!isStrictRecipientPolicyReconciliationStepKey(input.stepKey) ||\n\t\t!Number.isSafeInteger(input.generation) ||\n\t\tinput.generation < 0\n\t) {\n\t\tthrow new Error(\"recipient_policy_reconciliation_step_invalid\");\n\t}\n\tconst effectId = deterministicRecipientPolicyReconciliationEffectId(input);\n\tconst existing = db\n\t\t.prepare(\n\t\t\t`SELECT * FROM recipient_policy_reconciliation_steps\n\t\t\t WHERE canonical_project_identity = ? AND generation = ? AND step_key = ?`,\n\t\t)\n\t\t.get(input.canonicalProjectIdentity, input.generation, input.stepKey) as\n\t\t| Record<string, unknown>\n\t\t| undefined;\n\tif (existing) {\n\t\tconst uncertainMigratedEffect =\n\t\t\texisting.effect_id !== effectId && [\"running\", \"failed\"].includes(String(existing.status));\n\t\tif (\n\t\t\texisting.payload_digest !== input.payloadDigest ||\n\t\t\t(existing.effect_id !== effectId && !uncertainMigratedEffect)\n\t\t) {\n\t\t\tthrow new Error(\"recipient_policy_reconciliation_step_conflict\");\n\t\t}\n\t\treturn stepRow(existing);\n\t}\n\tdb.prepare(\n\t\t`INSERT INTO recipient_policy_reconciliation_steps(\n\t\t canonical_project_identity, generation, step_key, effect_id, payload_digest,\n\t\t status, created_at, updated_at\n\t\t ) VALUES (?, ?, ?, ?, ?, 'pending', ?, ?)`,\n\t).run(\n\t\tinput.canonicalProjectIdentity,\n\t\tinput.generation,\n\t\tinput.stepKey,\n\t\teffectId,\n\t\tinput.payloadDigest,\n\t\tinput.now,\n\t\tinput.now,\n\t);\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT * FROM recipient_policy_reconciliation_steps\n\t\t\t WHERE canonical_project_identity = ? AND generation = ? AND step_key = ?`,\n\t\t)\n\t\t.get(input.canonicalProjectIdentity, input.generation, input.stepKey) as Record<\n\t\tstring,\n\t\tunknown\n\t>;\n\treturn stepRow(row);\n}\n\nexport function recordRecipientPolicyReconciliationStepState(\n\tdb: Database,\n\tinput: RecordRecipientPolicyReconciliationStepStateInput,\n): RecipientPolicyReconciliationStepRecord {\n\tconst existing = db\n\t\t.prepare(\n\t\t\t`SELECT * FROM recipient_policy_reconciliation_steps\n\t\t\t WHERE canonical_project_identity = ? AND generation = ? AND step_key = ?`,\n\t\t)\n\t\t.get(input.canonicalProjectIdentity, input.generation, input.stepKey) as\n\t\t| Record<string, unknown>\n\t\t| undefined;\n\tif (!existing || existing.effect_id !== input.effectId) {\n\t\tthrow new Error(\"recipient_policy_reconciliation_step_missing\");\n\t}\n\tif (\n\t\t!Number.isSafeInteger(input.attemptCount) ||\n\t\tinput.attemptCount < Number(existing.attempt_count)\n\t) {\n\t\tthrow new Error(\"recipient_policy_reconciliation_attempt_stale\");\n\t}\n\tdb.prepare(\n\t\t`UPDATE recipient_policy_reconciliation_steps SET\n\t\t status = ?, attempt_count = ?, started_at = ?, completed_at = ?, last_attempt_at = ?,\n\t\t safe_error_code = ?, error_at = ?, lease_owner = ?, lease_acquired_at = ?,\n\t\t lease_expires_at = ?, updated_at = ?\n\t\t WHERE canonical_project_identity = ? AND generation = ? AND step_key = ? AND effect_id = ?`,\n\t).run(\n\t\tinput.status,\n\t\tinput.attemptCount,\n\t\tinput.startedAt,\n\t\tinput.completedAt,\n\t\tinput.lastAttemptAt,\n\t\tinput.safeErrorCode,\n\t\tinput.errorAt,\n\t\tinput.leaseOwner,\n\t\tinput.leaseAcquiredAt,\n\t\tinput.leaseExpiresAt,\n\t\tinput.updatedAt,\n\t\tinput.canonicalProjectIdentity,\n\t\tinput.generation,\n\t\tinput.stepKey,\n\t\tinput.effectId,\n\t);\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT * FROM recipient_policy_reconciliation_steps\n\t\t\t WHERE canonical_project_identity = ? AND generation = ? AND step_key = ?`,\n\t\t)\n\t\t.get(input.canonicalProjectIdentity, input.generation, input.stepKey) as Record<\n\t\tstring,\n\t\tunknown\n\t>;\n\treturn stepRow(row);\n}\n\nexport function putRecipientPolicyDenyOverlay(\n\tdb: Database,\n\tinput: {\n\t\tcanonicalProjectIdentity: string;\n\t\tscopeId: string;\n\t\tdeviceId: string;\n\t\tgeneration: number;\n\t\treasonCode: string;\n\t\tnow: string;\n\t},\n): RecipientPolicyDenyOverlayRecord {\n\tif (\n\t\t!isStrictRecipientPolicyProjectIdentity(input.canonicalProjectIdentity) ||\n\t\t![input.scopeId, input.deviceId, input.reasonCode].every(isStrictRecipientPolicyId) ||\n\t\t!Number.isSafeInteger(input.generation) ||\n\t\tinput.generation < 0\n\t) {\n\t\tthrow new Error(\"recipient_policy_deny_overlay_invalid\");\n\t}\n\tconst existing = db\n\t\t.prepare(\n\t\t\t`SELECT * FROM recipient_policy_deny_overlays\n\t\t\t WHERE canonical_project_identity = ? AND scope_id = ? AND device_id = ?`,\n\t\t)\n\t\t.get(input.canonicalProjectIdentity, input.scopeId, input.deviceId) as\n\t\t| Record<string, unknown>\n\t\t| undefined;\n\tif (existing && input.generation < Number(existing.generation)) {\n\t\tthrow new Error(\"recipient_policy_deny_overlay_stale\");\n\t}\n\tdb.prepare(\n\t\t`INSERT INTO recipient_policy_deny_overlays(\n\t\t canonical_project_identity, scope_id, device_id, generation, reason_code, created_at, updated_at\n\t\t ) VALUES (?, ?, ?, ?, ?, ?, ?)\n\t\t ON CONFLICT(canonical_project_identity, scope_id, device_id) DO UPDATE SET\n\t\t generation = excluded.generation,\n\t\t reason_code = excluded.reason_code,\n\t\t updated_at = excluded.updated_at`,\n\t).run(\n\t\tinput.canonicalProjectIdentity,\n\t\tinput.scopeId,\n\t\tinput.deviceId,\n\t\tinput.generation,\n\t\tinput.reasonCode,\n\t\tinput.now,\n\t\tinput.now,\n\t);\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT * FROM recipient_policy_deny_overlays\n\t\t\t WHERE canonical_project_identity = ? AND scope_id = ? AND device_id = ?`,\n\t\t)\n\t\t.get(input.canonicalProjectIdentity, input.scopeId, input.deviceId) as Record<string, unknown>;\n\treturn denyOverlayRow(row);\n}\n\nexport function listRecipientPolicyDenyOverlays(\n\tdb: Database,\n\tcanonicalProjectIdentity: string,\n): RecipientPolicyDenyOverlayRecord[] {\n\treturn (\n\t\tdb\n\t\t\t.prepare(\n\t\t\t\t`SELECT * FROM recipient_policy_deny_overlays\n\t\t\t\t WHERE canonical_project_identity = ? ORDER BY scope_id, device_id`,\n\t\t\t)\n\t\t\t.all(canonicalProjectIdentity) as Array<Record<string, unknown>>\n\t).map(denyOverlayRow);\n}\n\nexport function clearRecipientPolicyDenyOverlay(\n\tdb: Database,\n\tinput: {\n\t\tcanonicalProjectIdentity: string;\n\t\tscopeId: string;\n\t\tdeviceId: string;\n\t\tverifiedGeneration: number;\n\t},\n): boolean {\n\tconst result = db\n\t\t.prepare(\n\t\t\t`DELETE FROM recipient_policy_deny_overlays\n\t\t\t WHERE canonical_project_identity = ? AND scope_id = ? AND device_id = ?\n\t\t\t AND generation <= ?`,\n\t\t)\n\t\t.run(input.canonicalProjectIdentity, input.scopeId, input.deviceId, input.verifiedGeneration);\n\treturn result.changes > 0;\n}\n","/**\n * Tag derivation — port of Python's codemem/store/tags.py.\n *\n * Derives searchable tags from memory kind, title, concepts, and file paths.\n * Used at ingest time to populate memory_items.tags_text inline (matching\n * Python's store_observation → derive_tags flow).\n */\n\nconst STOPWORDS = new Set([\n\t\"the\",\n\t\"and\",\n\t\"for\",\n\t\"with\",\n\t\"this\",\n\t\"that\",\n\t\"from\",\n\t\"are\",\n\t\"was\",\n\t\"were\",\n\t\"has\",\n\t\"have\",\n\t\"had\",\n\t\"not\",\n\t\"but\",\n\t\"can\",\n\t\"will\",\n\t\"all\",\n\t\"been\",\n\t\"each\",\n\t\"which\",\n\t\"their\",\n\t\"said\",\n\t\"its\",\n\t\"into\",\n\t\"than\",\n\t\"other\",\n\t\"some\",\n\t\"could\",\n\t\"them\",\n\t\"about\",\n\t\"then\",\n\t\"made\",\n\t\"after\",\n\t\"many\",\n\t\"also\",\n\t\"did\",\n\t\"just\",\n\t\"should\",\n\t\"over\",\n\t\"such\",\n\t\"there\",\n\t\"would\",\n\t\"more\",\n\t\"now\",\n\t\"very\",\n\t\"when\",\n\t\"what\",\n\t\"your\",\n\t\"how\",\n\t\"out\",\n\t\"our\",\n\t\"his\",\n\t\"her\",\n\t\"she\",\n\t\"him\",\n\t\"most\",\n]);\n\n/**\n * Normalize a raw value into a tag-safe lowercase slug.\n * Returns empty string if the value is empty, a stopword, or too short.\n */\nexport function normalizeTag(value: string, stopwords?: Set<string>): string {\n\tlet lowered = (value || \"\").trim().toLowerCase();\n\tif (!lowered) return \"\";\n\tlowered = lowered\n\t\t.replace(/[^a-z0-9_]+/g, \"-\")\n\t\t.replace(/-+/g, \"-\")\n\t\t.replace(/^-|-$/g, \"\");\n\tif (!lowered) return \"\";\n\tconst words = stopwords ?? STOPWORDS;\n\tif (words.has(lowered)) return \"\";\n\tif (lowered.length > 40) lowered = lowered.slice(0, 40).replace(/-$/, \"\");\n\treturn lowered;\n}\n\n/**\n * Extract tags from a file path (basename, parent dir, top-level dir).\n */\nexport function fileTags(pathValue: string, stopwords?: Set<string>): string[] {\n\tconst raw = (pathValue || \"\").trim();\n\tif (!raw) return [];\n\tconst parts = raw.split(/[\\\\/]+/).filter((p): p is string => !!p && p !== \".\" && p !== \"..\");\n\tif (!parts.length) return [];\n\n\tconst tags: string[] = [];\n\tconst last = parts.at(-1);\n\tif (last) {\n\t\tconst basename = normalizeTag(last, stopwords);\n\t\tif (basename) tags.push(basename);\n\t}\n\tif (parts.length >= 2) {\n\t\tconst secondLast = parts.at(-2);\n\t\tif (secondLast) {\n\t\t\tconst parent = normalizeTag(secondLast, stopwords);\n\t\t\tif (parent) tags.push(parent);\n\t\t}\n\t}\n\tif (parts.length >= 3) {\n\t\tconst first = parts.at(0);\n\t\tif (first) {\n\t\t\tconst top = normalizeTag(first, stopwords);\n\t\t\tif (top) tags.push(top);\n\t\t}\n\t}\n\treturn tags;\n}\n\n/**\n * Derive tags from memory metadata, matching Python's derive_tags().\n *\n * Sources (in priority order):\n * 1. Memory kind\n * 2. Concepts (from observer XML output)\n * 3. File paths (read + modified)\n * 4. Title tokens (fallback when nothing else produced tags)\n */\nexport function deriveTags(opts: {\n\tkind: string;\n\ttitle?: string;\n\tconcepts?: string[];\n\tfilesRead?: string[];\n\tfilesModified?: string[];\n\tstopwords?: Set<string>;\n}): string[] {\n\tconst words = opts.stopwords ?? STOPWORDS;\n\tconst tags: string[] = [];\n\n\tconst kindTag = normalizeTag(opts.kind, words);\n\tif (kindTag) tags.push(kindTag);\n\n\tfor (const concept of opts.concepts ?? []) {\n\t\tconst normalized = normalizeTag(concept, words);\n\t\tif (normalized) tags.push(normalized);\n\t}\n\n\tfor (const pathValue of [...(opts.filesRead ?? []), ...(opts.filesModified ?? [])]) {\n\t\ttags.push(...fileTags(pathValue, words));\n\t}\n\n\t// Fallback: extract tokens from title if no other tags were found\n\tif (!tags.length && opts.title) {\n\t\tfor (const match of opts.title.toLowerCase().matchAll(/[a-z0-9_]+/g)) {\n\t\t\tconst normalized = normalizeTag(match[0], words);\n\t\t\tif (normalized) tags.push(normalized);\n\t\t}\n\t}\n\n\t// Dedupe while preserving order, cap at 20\n\tconst deduped: string[] = [];\n\tconst seen = new Set<string>();\n\tfor (const tag of tags) {\n\t\tif (seen.has(tag)) continue;\n\t\tseen.add(tag);\n\t\tdeduped.push(tag);\n\t\tif (deduped.length >= 20) break;\n\t}\n\treturn deduped;\n}\n","/**\n * Sync replication: cursor tracking, op chunking, and payload extraction.\n *\n * Uses Drizzle ORM for all SQL queries so that column mismatches are\n * compile-time errors instead of silent data-loss bugs at runtime.\n *\n * Keeps replication functions decoupled from MemoryStore by accepting\n * a raw Database handle. Ported from codemem/sync/replication.py.\n */\n\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { and, desc, eq, gt, isNotNull, isNull, like, or, sql } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport type { Database } from \"./db.js\";\nimport { fromJson, fromJsonStrict, toJson, toJsonNullable } from \"./db.js\";\nimport {\n\thasMatchingLocalCreation,\n\thasRecordedLocalCreation,\n\trecordForeignMemoryRevision,\n} from \"./memory-creation-provenance.js\";\nimport { type LocalCreationContext, localCreationSourceIds } from \"./memory-local-capture.js\";\nimport { retirementAllowsSnapshot } from \"./memory-retirement-snapshot-guard.js\";\nimport {\n\tassertMemoryScopeNotRetired,\n\thasMemoryScopeRetirement,\n\tisMemoryScopeRetired,\n} from \"./memory-scope-retirement.js\";\nimport { memorySourceNamespace } from \"./memory-source-identity.js\";\nimport { readCodememConfigFile } from \"./observer-config.js\";\nimport { projectBasename } from \"./project.js\";\nimport { getAnyRecipientPolicyDenyOverlayForScopeDevice } from \"./recipient-policy-reconciliation.js\";\nimport { clearMemoryRefs, populateMemoryRefs } from \"./ref-populate.js\";\nimport * as schema from \"./schema.js\";\nimport { getCachedScopeAuthorization } from \"./scope-membership-cache.js\";\nimport { LEGACY_SHARED_REVIEW_SCOPE_ID } from \"./scope-resolution.js\";\nimport { ensureMemoryScopeId } from \"./scope-stamping.js\";\nimport { redactMemoryFields, SecretScanner } from \"./secret-scanner.js\";\nimport { snapshotSessionExportKeysForMemoryIds } from \"./session-export-identity-mutation.js\";\nimport { loadRuntimeSigningPublicKey } from \"./sync-identity.js\";\nimport {\n\tensureSyncTransferActivitySchema,\n\trecordSyncTransferObservation,\n\trecordSyncTransferReceipts,\n\ttype SyncTransferObservationSource,\n} from \"./sync-transfer-activity.js\";\nimport { deriveTags } from \"./tags.js\";\nimport type {\n\tReplicationOp,\n\tReplicationOpsAgePrunePlan,\n\tReplicationOpsPruneResult,\n\tSyncDirtyLocalState,\n\tSyncMemorySnapshotItem,\n} from \"./types.js\";\n\nexport const DEFAULT_SYNC_SCOPE_ID = \"local-default\";\nexport const ACCESS_CLEANUP_OP_TYPE = \"access_cleanup\";\nexport const REASSIGN_SCOPE_OP_TYPE = \"reassign_scope\";\nexport const SCOPED_NULL_BASELINE_BOOTSTRAP_CURSOR_MARKER =\n\t\"__codemem_scoped_null_baseline_bootstrap__\";\n\nexport interface SyncResetBoundary {\n\tscope_id?: string | null;\n\tgeneration: number;\n\tsnapshot_id: string;\n\tbaseline_cursor: string | null;\n\tretained_floor_cursor: string | null;\n}\n\nexport interface SyncResetRequired extends SyncResetBoundary {\n\treset_required: true;\n\treason:\n\t\t| \"stale_cursor\"\n\t\t| \"generation_mismatch\"\n\t\t| \"boundary_mismatch\"\n\t\t| \"missing_scope\"\n\t\t| \"scope_inactive\"\n\t\t| \"stale_epoch\"\n\t\t| \"unsupported_scope\";\n}\n\n/**\n * Serialized bytes of ops or snapshot items one pull page may carry. A relayed\n * exchange on the Durable Object host carries at most 2 MiB, and real memory\n * items average about 5 KB, so a 500-op or 2000-item page by count alone\n * would not fit. This matches the push batch limit. A page always carries at\n * least one entry, so a single larger entry still makes progress.\n */\nexport const SYNC_PAGE_MAX_BYTES = 1_048_576;\n\n/** Returns how many leading entries fit in `maxBytes` of JSON, at least one. */\nfunction entriesWithinBytes(entries: readonly unknown[], maxBytes: number): number {\n\tlet total = 0;\n\tfor (const [index, entry] of entries.entries()) {\n\t\ttotal += Buffer.byteLength(JSON.stringify(entry)) + 1;\n\t\tif (index > 0 && total > maxBytes) return index;\n\t}\n\treturn entries.length;\n}\n\ninterface LoadReplicationOpsForPeerBaseOptions {\n\tsince: string | null;\n\tlimit?: number;\n\t/** Serialized size cap for the returned ops. Defaults to SYNC_PAGE_MAX_BYTES. */\n\tmaxBytes?: number;\n\tgeneration?: number | null;\n\tsnapshotId?: string | null;\n\tbaselineCursor?: string | null;\n}\n\nexport type LoadReplicationOpsForPeerOptions =\n\t| (LoadReplicationOpsForPeerBaseOptions & {\n\t\t\tdeviceId?: string;\n\t\t\tscopeId?: null;\n\t })\n\t| (LoadReplicationOpsForPeerBaseOptions & {\n\t\t\tdeviceId: string;\n\t\t\tscopeId: string;\n\t });\n\nexport type LoadReplicationOpsForPeerResult =\n\t| {\n\t\t\treset_required: false;\n\t\t\tboundary: SyncResetBoundary;\n\t\t\tops: ReplicationOp[];\n\t\t\tnextCursor: string | null;\n\t }\n\t| {\n\t\t\treset_required: true;\n\t\t\treset: SyncResetRequired;\n\t };\n\nexport interface LoadMemorySnapshotPageForPeerOptions {\n\t/** Direct-source reset lane; the HTTP caller must require its own local device ID. */\n\tsourceDeviceId?: string;\n\tlimit?: number;\n\t/** Serialized size cap for the returned items. Defaults to SYNC_PAGE_MAX_BYTES. */\n\tmaxBytes?: number;\n\tpageToken?: string | null;\n\tpeerDeviceId?: string | null;\n\tscopeId?: string | null;\n\tgeneration?: number | null;\n\tsnapshotId?: string | null;\n\tbaselineCursor?: string | null;\n}\n\nexport interface LoadMemorySnapshotPageForPeerResult {\n\tboundary: SyncResetBoundary;\n\titems: SyncMemorySnapshotItem[];\n\tnextPageToken: string | null;\n\thasMore: boolean;\n}\n\ntype MemoryItemRow = typeof schema.memoryItems.$inferSelect;\n\ninterface MemoryPayload {\n\tsession_id: number | null;\n\tkind: string | null;\n\ttitle: string | null;\n\tsubtitle: string | null;\n\tbody_text: string | null;\n\tconfidence: number | null;\n\ttags_text: string | null;\n\tactive: number | null;\n\tcreated_at: string | null;\n\tupdated_at: string | null;\n\tmetadata_json: Record<string, unknown>;\n\tactor_id: string | null;\n\tactor_display_name: string | null;\n\tvisibility: string | null;\n\tworkspace_id: string | null;\n\tworkspace_kind: string | null;\n\torigin_device_id: string | null;\n\torigin_source: string | null;\n\ttrust_state: string | null;\n\tnarrative: string | null;\n\tfacts: unknown;\n\tconcepts: unknown;\n\tfiles_read: unknown;\n\tfiles_modified: unknown;\n\tuser_prompt_id: number | null;\n\tprompt_number: number | null;\n\tdeleted_at: string | null;\n\tscope_id: string | null;\n\t// Wire payloads use this as \"sender explicitly included deleted_at\" so we can\n\t// distinguish a tombstone clear (`deleted_at: null`) from an omitted field.\n\t// Row-derived payloads set it from current storage truth instead.\n\thas_deleted_at: boolean;\n\trev: number;\n\timport_key: string | null;\n\tproject?: string | null;\n}\n\ninterface AccessCleanupPayload {\n\tcleanup_scope_id: string | null;\n\treason: string | null;\n\ttarget_peer_device_id: string | null;\n}\n\nexport interface ReassignScopePayload {\n\toperation_id: string;\n\tmemory_id: string;\n\told_scope_id: string;\n\tnew_scope_id: string;\n\trevision: number;\n\tside: \"old\" | \"new\";\n}\n\nfunction requiredPayloadText(value: unknown): string | null {\n\treturn typeof value === \"string\" && value.trim() ? value.trim() : null;\n}\n\nexport function parseReassignScopePayload(op: ReplicationOp): ReassignScopePayload {\n\tif (op.op_type !== REASSIGN_SCOPE_OP_TYPE) throw new Error(\"reassign_payload_invalid\");\n\tconst payload = parsePayload(op.payload_json);\n\tconst operationId = requiredPayloadText(payload?.operation_id);\n\tconst memoryId = requiredPayloadText(payload?.memory_id);\n\tconst oldScopeId = requiredPayloadText(payload?.old_scope_id);\n\tconst newScopeId = requiredPayloadText(payload?.new_scope_id);\n\tconst side = payload?.side;\n\tconst revision = payload?.revision;\n\tif (\n\t\t!operationId ||\n\t\t!memoryId ||\n\t\tmemoryId !== op.entity_id ||\n\t\t!oldScopeId ||\n\t\t!newScopeId ||\n\t\toldScopeId === newScopeId ||\n\t\t(side !== \"old\" && side !== \"new\") ||\n\t\t!Number.isSafeInteger(revision) ||\n\t\tNumber(revision) <= 0 ||\n\t\tNumber(revision) !== op.clock_rev ||\n\t\tcleanText(op.scope_id) !== (side === \"old\" ? oldScopeId : newScopeId) ||\n\t\t(side === \"new\" && cleanText(payload?.scope_id) !== newScopeId)\n\t) {\n\t\tthrow new Error(\"reassign_payload_invalid\");\n\t}\n\treturn {\n\t\toperation_id: operationId,\n\t\tmemory_id: memoryId,\n\t\told_scope_id: oldScopeId,\n\t\tnew_scope_id: newScopeId,\n\t\trevision: Number(revision),\n\t\tside,\n\t};\n}\n\nfunction parseAccessCleanupPayload(op: ReplicationOp): AccessCleanupPayload {\n\tconst payload = parsePayload(op.payload_json);\n\treturn {\n\t\tcleanup_scope_id: cleanText(payload?.cleanup_scope_id ?? payload?.scope_id),\n\t\treason: cleanText(payload?.reason),\n\t\ttarget_peer_device_id: cleanText(payload?.target_peer_device_id),\n\t};\n}\n\nfunction accessCleanupTargetsPeer(op: ReplicationOp, peerDeviceId: string | null): boolean {\n\tconst cleanup = parseAccessCleanupPayload(op);\n\tif (!cleanup.cleanup_scope_id) return false;\n\treturn (\n\t\tcleanup.target_peer_device_id === null ||\n\t\tcleanup.target_peer_device_id === cleanText(peerDeviceId)\n\t);\n}\n\nfunction resolveReplicatedTextUpdate(\n\tnextValue: string | null | undefined,\n\tcurrentValue: string | null,\n): string {\n\tif (nextValue == null) return currentValue ?? \"\";\n\treturn nextValue;\n}\n\nfunction asNumberOrNull(value: unknown): number | null {\n\tif (value == null) return null;\n\tif (typeof value === \"number\" && Number.isFinite(value)) return value;\n\tif (typeof value === \"string\" && value.trim().length > 0) {\n\t\tconst parsed = Number(value);\n\t\tif (Number.isFinite(parsed)) return parsed;\n\t}\n\treturn null;\n}\n\nfunction asStringOrNull(value: unknown): string | null {\n\tif (value == null) return null;\n\treturn String(value);\n}\n\n/** Coerce an unknown payload field to `string[] | null` for ref population. */\nfunction asStringArrayOrNull(value: unknown): string[] | null {\n\tif (!Array.isArray(value)) return null;\n\tconst strings = value.filter((v): v is string => typeof v === \"string\");\n\treturn strings.length > 0 ? strings : null;\n}\n\nfunction parseMemoryPayload(op: ReplicationOp, errors: string[]): MemoryPayload | null {\n\tif (!op.payload_json) return null;\n\tlet raw: Record<string, unknown>;\n\ttry {\n\t\traw = fromJsonStrict(op.payload_json);\n\t} catch (err) {\n\t\terrors.push(\n\t\t\t`op ${op.op_id}: skipped — payload_json is not a valid object: ${err instanceof Error ? err.message : String(err)}`,\n\t\t);\n\t\treturn null;\n\t}\n\tconst metadataRaw = raw.metadata_json;\n\tconst metadata_json =\n\t\tmetadataRaw && typeof metadataRaw === \"object\" && !Array.isArray(metadataRaw)\n\t\t\t? { ...(metadataRaw as Record<string, unknown>) }\n\t\t\t: {};\n\treturn {\n\t\tsession_id: asNumberOrNull(raw.session_id),\n\t\tkind: asStringOrNull(raw.kind),\n\t\ttitle: asStringOrNull(raw.title),\n\t\tsubtitle: asStringOrNull(raw.subtitle),\n\t\tbody_text: asStringOrNull(raw.body_text),\n\t\tconfidence: asNumberOrNull(raw.confidence),\n\t\ttags_text: asStringOrNull(raw.tags_text),\n\t\tactive: asNumberOrNull(raw.active),\n\t\tcreated_at: asStringOrNull(raw.created_at),\n\t\tupdated_at: asStringOrNull(raw.updated_at),\n\t\tmetadata_json,\n\t\tactor_id: asStringOrNull(raw.actor_id),\n\t\tactor_display_name: asStringOrNull(raw.actor_display_name),\n\t\tvisibility: asStringOrNull(raw.visibility),\n\t\tworkspace_id: asStringOrNull(raw.workspace_id),\n\t\tworkspace_kind: asStringOrNull(raw.workspace_kind),\n\t\torigin_device_id: asStringOrNull(raw.origin_device_id),\n\t\torigin_source: asStringOrNull(raw.origin_source),\n\t\ttrust_state: asStringOrNull(raw.trust_state),\n\t\tnarrative: asStringOrNull(raw.narrative),\n\t\tfacts: raw.facts ?? null,\n\t\tconcepts: raw.concepts ?? null,\n\t\tfiles_read: raw.files_read ?? null,\n\t\tfiles_modified: raw.files_modified ?? null,\n\t\tuser_prompt_id: asNumberOrNull(raw.user_prompt_id),\n\t\tprompt_number: asNumberOrNull(raw.prompt_number),\n\t\tdeleted_at: asStringOrNull(raw.deleted_at),\n\t\tscope_id: asStringOrNull(raw.scope_id),\n\t\thas_deleted_at: Object.hasOwn(raw, \"deleted_at\"),\n\t\trev: asNumberOrNull(raw.rev) ?? 0,\n\t\timport_key: asStringOrNull(raw.import_key),\n\t\tproject: asStringOrNull(raw.project),\n\t};\n}\n\n/**\n * Resolve tags_text for a replicated memory: use incoming tags if non-empty,\n * otherwise derive tags from available metadata (kind, title, concepts, files).\n */\nfunction resolveReplicatedTags(payload: MemoryPayload): string {\n\tconst incoming = (payload.tags_text ?? \"\").trim();\n\tif (incoming) return incoming;\n\tconst concepts = Array.isArray(payload.concepts) ? payload.concepts.map(String) : [];\n\tconst filesRead = Array.isArray(payload.files_read) ? payload.files_read.map(String) : [];\n\tconst filesModified = Array.isArray(payload.files_modified)\n\t\t? payload.files_modified.map(String)\n\t\t: [];\n\tconst tags = deriveTags({\n\t\tkind: payload.kind ?? \"\",\n\t\ttitle: payload.title ?? undefined,\n\t\tconcepts,\n\t\tfilesRead,\n\t\tfilesModified,\n\t});\n\treturn tags.join(\" \");\n}\n\nfunction normalizeCursor(value: string | null | undefined): string | null {\n\tconst trimmed = String(value ?? \"\").trim();\n\treturn trimmed.length > 0 ? trimmed : null;\n}\n\nfunction normalizeSyncStateScopeId(scopeId: string | null | undefined): string {\n\tconst trimmed = String(scopeId ?? \"\").trim();\n\treturn trimmed.length > 0 ? trimmed : DEFAULT_SYNC_SCOPE_ID;\n}\n\nfunction shouldReturnScopeId(scopeId: string | null | undefined): boolean {\n\treturn scopeId !== undefined;\n}\n\nfunction resetBoundaryFromRow(\n\trow: {\n\t\tgeneration: number | null;\n\t\tsnapshot_id: string | null;\n\t\tbaseline_cursor: string | null;\n\t\tretained_floor_cursor: string | null;\n\t},\n\tscopeId: string,\n\tincludeScopeId: boolean,\n): SyncResetBoundary {\n\tconst boundary: SyncResetBoundary = {\n\t\tgeneration: Number(row.generation ?? 1),\n\t\tsnapshot_id: String(row.snapshot_id),\n\t\tbaseline_cursor: normalizeCursor(row.baseline_cursor),\n\t\tretained_floor_cursor: normalizeCursor(row.retained_floor_cursor),\n\t};\n\tif (includeScopeId) boundary.scope_id = scopeId;\n\treturn boundary;\n}\n\nfunction parseSnapshotPageToken(\n\ttoken: string | null | undefined,\n): { importKey: string; id: number } | null {\n\tconst raw = normalizeCursor(token);\n\tif (!raw) return null;\n\tconst idx = raw.lastIndexOf(\"|\");\n\tif (idx <= 0) return null;\n\tconst importKey = raw.slice(0, idx);\n\tconst id = Number(raw.slice(idx + 1));\n\tif (!importKey || !Number.isFinite(id)) return null;\n\treturn { importKey, id };\n}\n\nfunction makeSnapshotPageToken(importKey: string, id: number): string {\n\treturn `${importKey}|${id}`;\n}\n\nfunction ensureSyncResetStateTable(db: Database): void {\n\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS sync_reset_state (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\tgeneration INTEGER NOT NULL,\n\t\t\tsnapshot_id TEXT NOT NULL,\n\t\t\tbaseline_cursor TEXT,\n\t\t\tretained_floor_cursor TEXT,\n\t\t\tupdated_at TEXT NOT NULL\n\t\t)\n\t`);\n\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS sync_reset_state_v2 (\n\t\t\tscope_id TEXT PRIMARY KEY NOT NULL,\n\t\t\tgeneration INTEGER NOT NULL,\n\t\t\tsnapshot_id TEXT NOT NULL,\n\t\t\tbaseline_cursor TEXT,\n\t\t\tretained_floor_cursor TEXT,\n\t\t\tupdated_at TEXT NOT NULL\n\t\t)\n\t`);\n}\n\nfunction seedDefaultSyncResetStateFromLegacy(db: Database): void {\n\tdb.exec(`\n\t\tINSERT OR IGNORE INTO sync_reset_state_v2\n\t\t\t(scope_id, generation, snapshot_id, baseline_cursor, retained_floor_cursor, updated_at)\n\t\tSELECT '${DEFAULT_SYNC_SCOPE_ID}', generation, snapshot_id, baseline_cursor, retained_floor_cursor, updated_at\n\t\tFROM sync_reset_state\n\t\tWHERE id = 1\n\t`);\n}\n\nfunction mirrorDefaultSyncResetStateToLegacy(\n\tdb: Database,\n\tboundary: SyncResetBoundary,\n\tupdatedAt: string,\n): void {\n\tconst d = drizzle(db, { schema });\n\td.insert(schema.syncResetState)\n\t\t.values({\n\t\t\tid: 1,\n\t\t\tgeneration: boundary.generation,\n\t\t\tsnapshot_id: boundary.snapshot_id,\n\t\t\tbaseline_cursor: boundary.baseline_cursor,\n\t\t\tretained_floor_cursor: boundary.retained_floor_cursor,\n\t\t\tupdated_at: updatedAt,\n\t\t})\n\t\t.onConflictDoUpdate({\n\t\t\ttarget: schema.syncResetState.id,\n\t\t\tset: {\n\t\t\t\tgeneration: boundary.generation,\n\t\t\t\tsnapshot_id: boundary.snapshot_id,\n\t\t\t\tbaseline_cursor: boundary.baseline_cursor,\n\t\t\t\tretained_floor_cursor: boundary.retained_floor_cursor,\n\t\t\t\tupdated_at: updatedAt,\n\t\t\t},\n\t\t})\n\t\t.run();\n}\n\nexport function getSyncResetState(db: Database, scopeId?: string | null): SyncResetBoundary {\n\tensureSyncResetStateTable(db);\n\tconst effectiveScopeId = normalizeSyncStateScopeId(scopeId);\n\tconst includeScopeId = shouldReturnScopeId(scopeId);\n\tif (effectiveScopeId === DEFAULT_SYNC_SCOPE_ID) {\n\t\tseedDefaultSyncResetStateFromLegacy(db);\n\t}\n\tconst d = drizzle(db, { schema });\n\tconst existing = d\n\t\t.select()\n\t\t.from(schema.syncResetStateV2)\n\t\t.where(eq(schema.syncResetStateV2.scope_id, effectiveScopeId))\n\t\t.get();\n\tif (existing) {\n\t\treturn resetBoundaryFromRow(existing, effectiveScopeId, includeScopeId);\n\t}\n\n\tconst now = new Date().toISOString();\n\tconst created = {\n\t\tscope_id: effectiveScopeId,\n\t\tgeneration: 1,\n\t\tsnapshot_id: randomUUID(),\n\t\tbaseline_cursor: null,\n\t\tretained_floor_cursor: null,\n\t\tupdated_at: now,\n\t};\n\td.insert(schema.syncResetStateV2).values(created).run();\n\tconst boundary = resetBoundaryFromRow(created, effectiveScopeId, includeScopeId);\n\tif (effectiveScopeId === DEFAULT_SYNC_SCOPE_ID) {\n\t\tmirrorDefaultSyncResetStateToLegacy(db, boundary, now);\n\t}\n\treturn boundary;\n}\n\nexport function setSyncResetState(\n\tdb: Database,\n\tupdates: Partial<SyncResetBoundary> & { generation?: number },\n\tscopeId?: string | null,\n): SyncResetBoundary {\n\tconst requestedScopeId = scopeId !== undefined ? scopeId : updates.scope_id;\n\tconst effectiveScopeId = normalizeSyncStateScopeId(requestedScopeId);\n\tconst includeScopeId = scopeId !== undefined || updates.scope_id !== undefined;\n\tconst current = getSyncResetState(db, includeScopeId ? effectiveScopeId : undefined);\n\tconst now = new Date().toISOString();\n\tconst next: SyncResetBoundary = {\n\t\tgeneration: updates.generation ?? current.generation,\n\t\tsnapshot_id: updates.snapshot_id ?? current.snapshot_id,\n\t\tbaseline_cursor:\n\t\t\tupdates.baseline_cursor === undefined\n\t\t\t\t? current.baseline_cursor\n\t\t\t\t: normalizeCursor(updates.baseline_cursor),\n\t\tretained_floor_cursor:\n\t\t\tupdates.retained_floor_cursor === undefined\n\t\t\t\t? current.retained_floor_cursor\n\t\t\t\t: normalizeCursor(updates.retained_floor_cursor),\n\t};\n\tif (includeScopeId) next.scope_id = effectiveScopeId;\n\tconst d = drizzle(db, { schema });\n\td.insert(schema.syncResetStateV2)\n\t\t.values({\n\t\t\tscope_id: effectiveScopeId,\n\t\t\tgeneration: next.generation,\n\t\t\tsnapshot_id: next.snapshot_id,\n\t\t\tbaseline_cursor: next.baseline_cursor,\n\t\t\tretained_floor_cursor: next.retained_floor_cursor,\n\t\t\tupdated_at: now,\n\t\t})\n\t\t.onConflictDoUpdate({\n\t\t\ttarget: schema.syncResetStateV2.scope_id,\n\t\t\tset: {\n\t\t\t\tgeneration: next.generation,\n\t\t\t\tsnapshot_id: next.snapshot_id,\n\t\t\t\tbaseline_cursor: next.baseline_cursor,\n\t\t\t\tretained_floor_cursor: next.retained_floor_cursor,\n\t\t\t\tupdated_at: now,\n\t\t\t},\n\t\t})\n\t\t.run();\n\tif (effectiveScopeId === DEFAULT_SYNC_SCOPE_ID) {\n\t\tmirrorDefaultSyncResetStateToLegacy(db, next, now);\n\t}\n\treturn next;\n}\n\nfunction resetRequired(\n\tboundary: SyncResetBoundary,\n\treason: SyncResetRequired[\"reason\"],\n): LoadReplicationOpsForPeerResult {\n\treturn {\n\t\treset_required: true,\n\t\treset: {\n\t\t\treset_required: true,\n\t\t\treason,\n\t\t\t...boundary,\n\t\t},\n\t};\n}\n\nfunction foreignRevisionMetadata(\n\tdb: Database,\n\top: ReplicationOp,\n\tmetadata: Record<string, unknown> | string | null,\n): Record<string, unknown> {\n\trecordForeignMemoryRevision(db, op.entity_id, \"replication\");\n\tconst object = typeof metadata === \"string\" || metadata === null ? fromJson(metadata) : metadata;\n\treturn {\n\t\t...object,\n\t\tclock_device_id: op.clock_device_id,\n\t};\n}\n\nexport function clockDeviceIdFromMetadataJson(raw: string | null): string {\n\tconst metadata = fromJson(raw);\n\treturn typeof metadata.clock_device_id === \"string\" ? metadata.clock_device_id : \"\";\n}\n\n// Op chunking\n\n/**\n * Split replication ops into batches that fit within a byte-size limit.\n *\n * Each batch is serialized as `{\"ops\": [...]}` and must not exceed maxBytes\n * when UTF-8 encoded. Throws if a single op exceeds the limit.\n */\nexport function chunkOpsBySize(ops: ReplicationOp[], maxBytes: number): ReplicationOp[][] {\n\tconst encoder = new TextEncoder();\n\t// Overhead: {\"ops\":[]} = 9 bytes, comma between elements = 1 byte\n\tconst WRAPPER_OVERHEAD = 9;\n\tconst COMMA_OVERHEAD = 1;\n\n\tconst batches: ReplicationOp[][] = [];\n\tlet current: ReplicationOp[] = [];\n\tlet currentBytes = WRAPPER_OVERHEAD;\n\n\tfor (const op of ops) {\n\t\tconst opBytes = encoder.encode(JSON.stringify(op)).byteLength;\n\t\tconst addedBytes = current.length === 0 ? opBytes : opBytes + COMMA_OVERHEAD;\n\n\t\tif (currentBytes + addedBytes <= maxBytes) {\n\t\t\tcurrent.push(op);\n\t\t\tcurrentBytes += addedBytes;\n\t\t\tcontinue;\n\t\t}\n\t\tif (current.length === 0) {\n\t\t\tthrow new Error(\"single op exceeds size limit\");\n\t\t}\n\t\tbatches.push(current);\n\t\tcurrent = [op];\n\t\tcurrentBytes = WRAPPER_OVERHEAD + opBytes;\n\t\tif (currentBytes > maxBytes) {\n\t\t\tthrow new Error(\"single op exceeds size limit\");\n\t\t}\n\t}\n\tif (current.length > 0) {\n\t\tbatches.push(current);\n\t}\n\treturn batches;\n}\n\n// Cursor read/write\n\nfunction ensureReplicationCursorTables(db: Database): void {\n\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS replication_cursors (\n\t\t\tpeer_device_id TEXT PRIMARY KEY,\n\t\t\tlast_applied_cursor TEXT,\n\t\t\tlast_acked_cursor TEXT,\n\t\t\tupdated_at TEXT NOT NULL\n\t\t)\n\t`);\n\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS replication_cursors_v2 (\n\t\t\tpeer_device_id TEXT NOT NULL,\n\t\t\tscope_id TEXT NOT NULL,\n\t\t\tlast_applied_cursor TEXT,\n\t\t\tlast_acked_cursor TEXT,\n\t\t\tupdated_at TEXT NOT NULL,\n\t\t\tPRIMARY KEY (peer_device_id, scope_id)\n\t\t);\n\t\tCREATE INDEX IF NOT EXISTS idx_replication_cursors_v2_scope\n\t\t\tON replication_cursors_v2(scope_id)\n\t`);\n}\n\nfunction seedDefaultReplicationCursorFromLegacy(db: Database): void {\n\tdb.exec(`\n\t\tINSERT OR IGNORE INTO replication_cursors_v2\n\t\t\t(peer_device_id, scope_id, last_applied_cursor, last_acked_cursor, updated_at)\n\t\tSELECT peer_device_id, '${DEFAULT_SYNC_SCOPE_ID}', last_applied_cursor, last_acked_cursor, updated_at\n\t\tFROM replication_cursors\n\t`);\n}\n\nfunction mirrorDefaultReplicationCursorToLegacy(\n\tdb: Database,\n\tpeerDeviceId: string,\n\toptions: { lastApplied?: string | null; lastAcked?: string | null },\n\tupdatedAt: string,\n): void {\n\tconst lastApplied = options.lastApplied ?? null;\n\tconst lastAcked = options.lastAcked ?? null;\n\tconst d = drizzle(db, { schema });\n\td.insert(schema.replicationCursors)\n\t\t.values({\n\t\t\tpeer_device_id: peerDeviceId,\n\t\t\tlast_applied_cursor: lastApplied,\n\t\t\tlast_acked_cursor: lastAcked,\n\t\t\tupdated_at: updatedAt,\n\t\t})\n\t\t.onConflictDoUpdate({\n\t\t\ttarget: schema.replicationCursors.peer_device_id,\n\t\t\tset: {\n\t\t\t\tlast_applied_cursor: sql`COALESCE(excluded.last_applied_cursor, ${schema.replicationCursors.last_applied_cursor})`,\n\t\t\t\tlast_acked_cursor: sql`COALESCE(excluded.last_acked_cursor, ${schema.replicationCursors.last_acked_cursor})`,\n\t\t\t\tupdated_at: sql`excluded.updated_at`,\n\t\t\t},\n\t\t})\n\t\t.run();\n}\n\n/**\n * Read the replication cursor for a peer device.\n *\n * Returns `[lastApplied, lastAcked]` — both null when no cursor exists.\n */\nexport function getReplicationCursor(\n\tdb: Database,\n\tpeerDeviceId: string,\n\tscopeId?: string | null,\n): [lastApplied: string | null, lastAcked: string | null] {\n\tensureReplicationCursorTables(db);\n\tconst effectiveScopeId = normalizeSyncStateScopeId(scopeId);\n\tif (effectiveScopeId === DEFAULT_SYNC_SCOPE_ID) {\n\t\tseedDefaultReplicationCursorFromLegacy(db);\n\t}\n\tconst d = drizzle(db, { schema });\n\tconst row = d\n\t\t.select({\n\t\t\tlast_applied_cursor: schema.replicationCursorsV2.last_applied_cursor,\n\t\t\tlast_acked_cursor: schema.replicationCursorsV2.last_acked_cursor,\n\t\t})\n\t\t.from(schema.replicationCursorsV2)\n\t\t.where(\n\t\t\tand(\n\t\t\t\teq(schema.replicationCursorsV2.peer_device_id, peerDeviceId),\n\t\t\t\teq(schema.replicationCursorsV2.scope_id, effectiveScopeId),\n\t\t\t),\n\t\t)\n\t\t.get();\n\n\tif (!row) return [null, null];\n\treturn [row.last_applied_cursor, row.last_acked_cursor];\n}\n\n/**\n * Insert or update the replication cursor for a peer device.\n *\n * Uses COALESCE on update so callers can set only one of the two cursors\n * without clobbering the other.\n */\nexport function setReplicationCursor(\n\tdb: Database,\n\tpeerDeviceId: string,\n\toptions: { lastApplied?: string | null; lastAcked?: string | null } = {},\n\tscopeId?: string | null,\n): void {\n\tensureReplicationCursorTables(db);\n\tconst now = new Date().toISOString();\n\tconst effectiveScopeId = normalizeSyncStateScopeId(scopeId);\n\tif (effectiveScopeId === DEFAULT_SYNC_SCOPE_ID) {\n\t\tseedDefaultReplicationCursorFromLegacy(db);\n\t}\n\tconst lastApplied = options.lastApplied ?? null;\n\tconst lastAcked = options.lastAcked ?? null;\n\n\tconst d = drizzle(db, { schema });\n\t// Atomic UPSERT — avoids TOCTOU race with concurrent sync workers.\n\t// Drizzle's onConflictDoUpdate doesn't support COALESCE(excluded.col, col)\n\t// natively, so we use raw SQL for the SET expressions.\n\td.insert(schema.replicationCursorsV2)\n\t\t.values({\n\t\t\tpeer_device_id: peerDeviceId,\n\t\t\tscope_id: effectiveScopeId,\n\t\t\tlast_applied_cursor: lastApplied,\n\t\t\tlast_acked_cursor: lastAcked,\n\t\t\tupdated_at: now,\n\t\t})\n\t\t.onConflictDoUpdate({\n\t\t\ttarget: [schema.replicationCursorsV2.peer_device_id, schema.replicationCursorsV2.scope_id],\n\t\t\tset: {\n\t\t\t\tlast_applied_cursor: sql`COALESCE(excluded.last_applied_cursor, ${schema.replicationCursorsV2.last_applied_cursor})`,\n\t\t\t\tlast_acked_cursor: sql`COALESCE(excluded.last_acked_cursor, ${schema.replicationCursorsV2.last_acked_cursor})`,\n\t\t\t\tupdated_at: sql`excluded.updated_at`,\n\t\t\t},\n\t\t})\n\t\t.run();\n\tif (effectiveScopeId === DEFAULT_SYNC_SCOPE_ID) {\n\t\tmirrorDefaultReplicationCursorToLegacy(db, peerDeviceId, options, now);\n\t}\n}\n\nexport function clearReplicationCursorLastApplied(\n\tdb: Database,\n\tpeerDeviceId: string,\n\tscopeId?: string | null,\n): void {\n\tensureReplicationCursorTables(db);\n\tconst now = new Date().toISOString();\n\tconst effectiveScopeId = normalizeSyncStateScopeId(scopeId);\n\tdrizzle(db, { schema })\n\t\t.update(schema.replicationCursorsV2)\n\t\t.set({\n\t\t\tlast_applied_cursor: null,\n\t\t\tlast_acked_cursor: null,\n\t\t\tupdated_at: now,\n\t\t})\n\t\t.where(\n\t\t\tand(\n\t\t\t\teq(schema.replicationCursorsV2.peer_device_id, peerDeviceId),\n\t\t\t\teq(schema.replicationCursorsV2.scope_id, effectiveScopeId),\n\t\t\t),\n\t\t)\n\t\t.run();\n}\n\n// Payload extraction\n\n/**\n * Extract replication ops from a parsed JSON payload.\n *\n * Returns an empty array if the payload is not an object or lacks an `ops` array.\n */\n/** Required fields for a valid replication op. */\nconst REQUIRED_OP_FIELDS = [\n\t\"op_id\",\n\t\"entity_type\",\n\t\"entity_id\",\n\t\"op_type\",\n\t\"clock_rev\",\n\t\"clock_updated_at\",\n\t\"clock_device_id\",\n\t\"device_id\",\n\t\"created_at\",\n] as const;\n\n/**\n * Extract and validate replication ops from a parsed JSON payload.\n *\n * Returns an empty array if the payload is not an object or lacks an `ops` array.\n * Silently filters out ops missing required fields to prevent garbage data\n * from entering the replication pipeline.\n */\nexport function extractReplicationOps(payload: unknown): ReplicationOp[] {\n\tif (typeof payload !== \"object\" || payload === null) return [];\n\tconst obj = payload as Record<string, unknown>;\n\tconst ops = obj.ops;\n\tif (!Array.isArray(ops)) return [];\n\n\treturn ops.filter((op): op is ReplicationOp => {\n\t\tif (typeof op !== \"object\" || op === null) return false;\n\t\tconst record = op as Record<string, unknown>;\n\t\treturn REQUIRED_OP_FIELDS.every(\n\t\t\t(field) => record[field] !== undefined && record[field] !== null,\n\t\t);\n\t});\n}\n\n// Clock comparison\n\n/**\n * Build a clock tuple from individual fields.\n *\n * Clock tuples enable lexicographic comparison for last-writer-wins\n * conflict resolution: higher rev wins, tiebreak on updated_at, then device_id.\n */\nexport function clockTuple(\n\trev: number,\n\tupdatedAt: string,\n\tdeviceId: string,\n): [number, string, string] {\n\treturn [rev, updatedAt, deviceId];\n}\n\n/**\n * Return true if `candidate` clock is strictly newer than `existing`.\n *\n * Comparison order: rev (higher wins) → updated_at → device_id.\n * Mirrors Python's `_is_newer_clock` which relies on tuple ordering.\n */\nexport function isNewerClock(\n\tcandidate: [number, string, string],\n\texisting: [number, string, string],\n): boolean {\n\tif (candidate[0] !== existing[0]) return candidate[0] > existing[0];\n\tif (candidate[1] !== existing[1]) return candidate[1] > existing[1];\n\treturn candidate[2] > existing[2];\n}\n\n// Record a replication op\n\n/**\n * Generate and INSERT a single replication op for a memory item.\n *\n * Reads the memory item's clock fields (rev, updated_at, metadata_json)\n * from the DB, builds the op row, and inserts into `replication_ops`.\n * Returns the generated op_id (UUID).\n *\n * Uses Drizzle's typed select so all memory_items columns are captured\n * automatically — no hand-maintained column list to go out of sync.\n */\nexport function recordReplicationOp(\n\tdb: Database,\n\topts: {\n\t\tmemoryId: number;\n\t\topType: \"upsert\" | \"delete\";\n\t\tdeviceId: string;\n\t\tpayload?: Record<string, unknown>;\n\t\tscopeId?: string | null;\n\t\tclockRev?: number;\n\t\tclockUpdatedAt?: string;\n\t\tclockDeviceId?: string;\n\t\tcreatedAt?: string;\n\t\topId?: string;\n\t},\n): string {\n\tconst d = drizzle(db, { schema });\n\tconst opId = opts.opId ?? randomUUID();\n\tconst now = opts.createdAt ?? new Date().toISOString();\n\n\t// Read the full memory row — typed via Drizzle schema\n\tconst row = d\n\t\t.select()\n\t\t.from(schema.memoryItems)\n\t\t.where(eq(schema.memoryItems.id, opts.memoryId))\n\t\t.get();\n\n\tconst rev = opts.clockRev ?? Number(row?.rev ?? 0);\n\tconst updatedAt = opts.clockUpdatedAt ?? row?.updated_at ?? now;\n\tconst entityId = row?.import_key ?? String(opts.memoryId);\n\tconst metadata = fromJson(row?.metadata_json);\n\t// Backfill missing memory scope before emitting an op so storage, op row,\n\t// and payload all carry the same authoritative local scope.\n\tconst scopeId =\n\t\topts.scopeId !== undefined ? opts.scopeId : row ? ensureMemoryScopeId(db, opts.memoryId) : null;\n\tconst clockDeviceId =\n\t\ttypeof opts.clockDeviceId === \"string\" && opts.clockDeviceId.trim().length > 0\n\t\t\t? opts.clockDeviceId.trim()\n\t\t\t: typeof metadata.clock_device_id === \"string\" && metadata.clock_device_id.trim().length > 0\n\t\t\t\t? metadata.clock_device_id\n\t\t\t\t: opts.deviceId;\n\n\t// Resolve session project so peers can reconstruct the project association.\n\tconst sessionProject = row?.session_id\n\t\t? (d\n\t\t\t\t.select({ project: schema.sessions.project })\n\t\t\t\t.from(schema.sessions)\n\t\t\t\t.where(eq(schema.sessions.id, row.session_id))\n\t\t\t\t.get()?.project ?? null)\n\t\t: null;\n\n\t// Build payload from the memory row so peers can reconstruct the full item.\n\t// Explicit payload override wins except for authoritative scope_id on upserts.\n\tlet payloadJson: string | null;\n\tif (opts.payload) {\n\t\tpayloadJson = toJson(\n\t\t\trow && opts.opType === \"upsert\" ? { ...opts.payload, scope_id: scopeId } : opts.payload,\n\t\t);\n\t} else if (row && opts.opType === \"upsert\") {\n\t\t// Parse JSON-string columns so they round-trip as objects, not double-encoded strings\n\t\tconst parseSqliteJson = (val: string | null | undefined): unknown => {\n\t\t\tif (typeof val !== \"string\") return val ?? null;\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(val);\n\t\t\t} catch {\n\t\t\t\treturn val;\n\t\t\t}\n\t\t};\n\n\t\tpayloadJson = toJson({\n\t\t\tproject: sessionProject,\n\t\t\tsession_id: row.session_id,\n\t\t\tkind: row.kind,\n\t\t\ttitle: row.title,\n\t\t\tsubtitle: row.subtitle,\n\t\t\tbody_text: row.body_text,\n\t\t\tconfidence: row.confidence,\n\t\t\ttags_text: row.tags_text,\n\t\t\tactive: row.active,\n\t\t\tcreated_at: row.created_at,\n\t\t\tupdated_at: row.updated_at,\n\t\t\tmetadata_json: parseSqliteJson(row.metadata_json),\n\t\t\tactor_id: row.actor_id,\n\t\t\tactor_display_name: row.actor_display_name,\n\t\t\tvisibility: row.visibility,\n\t\t\tworkspace_id: row.workspace_id,\n\t\t\tworkspace_kind: row.workspace_kind,\n\t\t\torigin_device_id: row.origin_device_id,\n\t\t\torigin_source: row.origin_source,\n\t\t\ttrust_state: row.trust_state,\n\t\t\tfacts: parseSqliteJson(row.facts),\n\t\t\tnarrative: row.narrative,\n\t\t\tconcepts: parseSqliteJson(row.concepts),\n\t\t\tfiles_read: parseSqliteJson(row.files_read),\n\t\t\tfiles_modified: parseSqliteJson(row.files_modified),\n\t\t\tuser_prompt_id: row.user_prompt_id,\n\t\t\tprompt_number: row.prompt_number,\n\t\t\tdeleted_at: row.deleted_at,\n\t\t\tscope_id: scopeId,\n\t\t});\n\t} else {\n\t\tpayloadJson = null;\n\t}\n\n\td.insert(schema.replicationOps)\n\t\t.values({\n\t\t\top_id: opId,\n\t\t\tentity_type: \"memory_item\",\n\t\t\tentity_id: entityId,\n\t\t\top_type: opts.opType,\n\t\t\tpayload_json: payloadJson,\n\t\t\tclock_rev: rev,\n\t\t\tclock_updated_at: updatedAt,\n\t\t\tclock_device_id: clockDeviceId,\n\t\t\tdevice_id: opts.deviceId,\n\t\t\tcreated_at: now,\n\t\t\tscope_id: scopeId,\n\t\t})\n\t\t.run();\n\n\treturn opId;\n}\n\nfunction deterministicReassignOpId(\n\toperationId: string,\n\tmemoryId: string,\n\toldScopeId: string,\n\tnewScopeId: string,\n\tside: \"old\" | \"new\",\n): string {\n\treturn `reassign_${createHash(\"sha256\")\n\t\t.update(JSON.stringify([operationId, memoryId, oldScopeId, newScopeId, side]))\n\t\t.digest(\"hex\")}`;\n}\n\nfunction reassignmentEntityId(existing: MemoryItemRow): string {\n\treturn existing.import_key ?? String(existing.id);\n}\n\nfunction writeUnretiredReassignment(\n\tdb: Database,\n\tentityId: string,\n\tscopeId: string,\n\twrite: () => void,\n): void {\n\tdb.transaction(() => {\n\t\tassertMemoryScopeNotRetired(db, entityId, scopeId);\n\t\twrite();\n\t}).immediate();\n}\n\nexport function recordScopeReassignment(\n\tdb: Database,\n\topts: {\n\t\toperationId: string;\n\t\tmemoryId: number;\n\t\toldScopeId: string;\n\t\tnewScopeId: string;\n\t\tdeviceId: string;\n\t\tcreatedAt?: string;\n\t},\n): { revision: number; oldOpId: string; newOpId: string } {\n\tconst operationId = requiredPayloadText(opts.operationId);\n\tconst oldScopeId = requiredPayloadText(opts.oldScopeId);\n\tconst newScopeId = requiredPayloadText(opts.newScopeId);\n\tconst deviceId = requiredPayloadText(opts.deviceId);\n\tif (\n\t\t!operationId ||\n\t\t!oldScopeId ||\n\t\t!newScopeId ||\n\t\toldScopeId === newScopeId ||\n\t\t!deviceId ||\n\t\t!Number.isSafeInteger(opts.memoryId) ||\n\t\topts.memoryId <= 0\n\t) {\n\t\tthrow new Error(\"reassign_input_invalid\");\n\t}\n\tconst d = drizzle(db, { schema });\n\tconst existing = d\n\t\t.select()\n\t\t.from(schema.memoryItems)\n\t\t.where(eq(schema.memoryItems.id, opts.memoryId))\n\t\t.get();\n\tif (!existing) throw new Error(\"reassign_memory_not_found\");\n\tconst memoryId = reassignmentEntityId(existing);\n\tconst oldOpId = deterministicReassignOpId(operationId, memoryId, oldScopeId, newScopeId, \"old\");\n\tconst newOpId = deterministicReassignOpId(operationId, memoryId, oldScopeId, newScopeId, \"new\");\n\tconst existingOps = db\n\t\t.prepare(\"SELECT op_id, clock_rev FROM replication_ops WHERE op_id IN (?, ?)\")\n\t\t.all(oldOpId, newOpId) as Array<{ op_id: string; clock_rev: number }>;\n\tif (existingOps.length > 0) {\n\t\tif (\n\t\t\texistingOps.length !== 2 ||\n\t\t\texistingOps.some((op) => op.clock_rev !== existingOps[0]?.clock_rev)\n\t\t) {\n\t\t\tthrow new Error(\"reassign_replay_conflict\");\n\t\t}\n\t\treturn { revision: Number(existingOps[0]?.clock_rev ?? 0), oldOpId, newOpId };\n\t}\n\tif ((cleanText(existing.scope_id) ?? DEFAULT_SYNC_SCOPE_ID) !== oldScopeId) {\n\t\tthrow new Error(\"reassign_old_scope_mismatch\");\n\t}\n\tconst revision = Number(existing.rev ?? 0) + 1;\n\tconst createdAt = opts.createdAt ?? new Date().toISOString();\n\tconst metadata = fromJson(existing.metadata_json);\n\tObject.assign(metadata, { clock_device_id: deviceId, scope_id: newScopeId });\n\tmetadata.last_scope_reassignment = {\n\t\toperation_id: operationId,\n\t\told_scope_id: oldScopeId,\n\t\tnew_scope_id: newScopeId,\n\t\trevision,\n\t};\n\tconst write = db.transaction(() => {\n\t\td.update(schema.memoryItems)\n\t\t\t.set({\n\t\t\t\tscope_id: newScopeId,\n\t\t\t\trev: revision,\n\t\t\t\tupdated_at: createdAt,\n\t\t\t\tmetadata_json: toJson(metadata),\n\t\t\t})\n\t\t\t.where(eq(schema.memoryItems.id, opts.memoryId))\n\t\t\t.run();\n\t\tconst updated = d\n\t\t\t.select()\n\t\t\t.from(schema.memoryItems)\n\t\t\t.where(eq(schema.memoryItems.id, opts.memoryId))\n\t\t\t.get();\n\t\tif (!updated) throw new Error(\"reassign_memory_not_found\");\n\t\tconst sessionProject = updated.session_id\n\t\t\t? cleanText(\n\t\t\t\t\tdb.prepare(\"SELECT project FROM sessions WHERE id = ?\").pluck().get(updated.session_id),\n\t\t\t\t)\n\t\t\t: null;\n\t\tconst common = {\n\t\t\toperation_id: operationId,\n\t\t\tmemory_id: memoryId,\n\t\t\told_scope_id: oldScopeId,\n\t\t\tnew_scope_id: newScopeId,\n\t\t\trevision,\n\t\t};\n\t\tconst insert = db.prepare(`INSERT INTO replication_ops(\n\t\t\top_id, entity_type, entity_id, op_type, payload_json, clock_rev,\n\t\t\tclock_updated_at, clock_device_id, device_id, created_at, scope_id\n\t\t) VALUES (?, 'memory_item', ?, ?, ?, ?, ?, ?, ?, ?, ?)`);\n\t\tinsert.run(\n\t\t\toldOpId,\n\t\t\tmemoryId,\n\t\t\tREASSIGN_SCOPE_OP_TYPE,\n\t\t\ttoJson({ ...common, side: \"old\" }),\n\t\t\trevision,\n\t\t\tcreatedAt,\n\t\t\tdeviceId,\n\t\t\tdeviceId,\n\t\t\tcreatedAt,\n\t\t\toldScopeId,\n\t\t);\n\t\tinsert.run(\n\t\t\tnewOpId,\n\t\t\tmemoryId,\n\t\t\tREASSIGN_SCOPE_OP_TYPE,\n\t\t\ttoJson({\n\t\t\t\t...buildPayloadFromMemoryRow(updated),\n\t\t\t\tproject: cleanText(updated.project) ?? sessionProject,\n\t\t\t\t...common,\n\t\t\t\tside: \"new\",\n\t\t\t\tscope_id: newScopeId,\n\t\t\t}),\n\t\t\trevision,\n\t\t\tcreatedAt,\n\t\t\tdeviceId,\n\t\t\tdeviceId,\n\t\t\tcreatedAt,\n\t\t\tnewScopeId,\n\t\t);\n\t});\n\twriteUnretiredReassignment(db, memoryId, newScopeId, write);\n\treturn { revision, oldOpId, newOpId };\n}\n\nexport function recordAccessCleanupOp(\n\tdb: Database,\n\topts: {\n\t\timportKey: string;\n\t\tdeviceId: string;\n\t\tcleanupScopeId: string;\n\t\tclockRev: number;\n\t\tclockUpdatedAt: string;\n\t\tclockDeviceId?: string;\n\t\tcreatedAt?: string;\n\t\ttargetPeerDeviceId?: string | null;\n\t\treason?: string | null;\n\t\topId?: string;\n\t},\n): string {\n\tconst d = drizzle(db, { schema });\n\tconst opId = opts.opId ?? randomUUID();\n\tconst now = opts.createdAt ?? new Date().toISOString();\n\tconst payload = {\n\t\tcleanup_scope_id: opts.cleanupScopeId,\n\t\treason: cleanText(opts.reason) ?? \"scope_access_cleanup\",\n\t\t...(cleanText(opts.targetPeerDeviceId)\n\t\t\t? { target_peer_device_id: cleanText(opts.targetPeerDeviceId) }\n\t\t\t: {}),\n\t};\n\td.insert(schema.replicationOps)\n\t\t.values({\n\t\t\top_id: opId,\n\t\t\tentity_type: \"memory_item\",\n\t\t\tentity_id: opts.importKey,\n\t\t\top_type: ACCESS_CLEANUP_OP_TYPE,\n\t\t\tpayload_json: toJson(payload),\n\t\t\tclock_rev: opts.clockRev,\n\t\t\tclock_updated_at: opts.clockUpdatedAt,\n\t\t\tclock_device_id: opts.clockDeviceId ?? opts.deviceId,\n\t\t\tdevice_id: opts.deviceId,\n\t\t\tcreated_at: now,\n\t\t\tscope_id: DEFAULT_SYNC_SCOPE_ID,\n\t\t})\n\t\t.run();\n\treturn opId;\n}\n\n// Load replication ops with cursor pagination\n\n/** Parse a `created_at|op_id` cursor into its two components. */\nfunction parseCursor(cursor: string): [createdAt: string, opId: string] | null {\n\tconst idx = cursor.indexOf(\"|\");\n\tif (idx < 0) return null;\n\treturn [cursor.slice(0, idx), cursor.slice(idx + 1)];\n}\n\n/** Build a `created_at|op_id` cursor string. */\nfunction computeCursor(createdAt: string, opId: string): string {\n\treturn `${createdAt}|${opId}`;\n}\n\n/**\n * Load replication ops created after `cursor`, ordered by (created_at, op_id).\n *\n * Returns `[ops, nextCursor]` where nextCursor is the cursor for the last\n * returned row (or null if no rows matched). The cursor format is\n * `created_at|op_id`.\n */\nexport function loadReplicationOpsSince(\n\tdb: Database,\n\tcursor: string | null,\n\tlimit = 100,\n\tdeviceId?: string,\n\tscopeId?: string | null,\n): [ReplicationOp[], string | null] {\n\tconst d = drizzle(db, { schema });\n\tconst t = schema.replicationOps;\n\tconst conditions = [];\n\tconst scopeFilterRequested = scopeId !== undefined;\n\tconst effectiveScopeId = normalizeSyncStateScopeId(scopeId);\n\n\tif (cursor) {\n\t\tconst parsed = parseCursor(cursor);\n\t\tif (parsed) {\n\t\t\tconst [createdAt, opId] = parsed;\n\t\t\tconditions.push(\n\t\t\t\tor(gt(t.created_at, createdAt), and(eq(t.created_at, createdAt), gt(t.op_id, opId))),\n\t\t\t);\n\t\t}\n\t}\n\n\tif (deviceId) {\n\t\tconditions.push(\n\t\t\tor(and(eq(t.device_id, deviceId), eq(t.clock_device_id, deviceId)), eq(t.device_id, \"local\")),\n\t\t);\n\t}\n\n\tif (scopeFilterRequested) {\n\t\tconditions.push(\n\t\t\teffectiveScopeId === DEFAULT_SYNC_SCOPE_ID\n\t\t\t\t? or(isNull(t.scope_id), eq(t.scope_id, DEFAULT_SYNC_SCOPE_ID))\n\t\t\t\t: eq(t.scope_id, effectiveScopeId),\n\t\t);\n\t}\n\n\tconst whereClause = conditions.length > 0 ? and(...conditions) : undefined;\n\n\tconst rows = d\n\t\t.select()\n\t\t.from(t)\n\t\t.where(whereClause)\n\t\t.orderBy(t.created_at, t.op_id)\n\t\t.limit(limit)\n\t\t.all();\n\n\tconst ops: ReplicationOp[] = rows.map((r) => ({\n\t\top_id: r.op_id,\n\t\tentity_type: r.entity_type,\n\t\tentity_id: r.entity_id,\n\t\top_type: r.op_type,\n\t\tpayload_json: r.payload_json,\n\t\tclock_rev: r.clock_rev,\n\t\tclock_updated_at: r.clock_updated_at,\n\t\tclock_device_id: r.clock_device_id,\n\t\tdevice_id: r.device_id,\n\t\tcreated_at: r.created_at,\n\t\tscope_id: r.scope_id,\n\t}));\n\n\tlet nextCursor: string | null = null;\n\tif (rows.length > 0) {\n\t\tconst last = rows.at(-1);\n\t\tif (last) {\n\t\t\tnextCursor = computeCursor(last.created_at, last.op_id);\n\t\t}\n\t}\n\n\treturn [ops, nextCursor];\n}\n\n/**\n * Trims a pull page to the byte cap. The next page starts after the last op\n * returned, so ops filtered out after it are scanned and filtered again.\n */\nfunction opsPageWithinBytes(\n\tops: ReplicationOp[],\n\tnextCursor: string | null,\n\tmaxBytes = SYNC_PAGE_MAX_BYTES,\n): { ops: ReplicationOp[]; nextCursor: string | null } {\n\tconst kept = entriesWithinBytes(ops, maxBytes);\n\tconst last = ops[kept - 1];\n\tif (kept === ops.length || !last) return { ops, nextCursor };\n\treturn { ops: ops.slice(0, kept), nextCursor: computeCursor(last.created_at, last.op_id) };\n}\n\nexport function loadReplicationOpsForPeer(\n\tdb: Database,\n\toptions: LoadReplicationOpsForPeerOptions,\n): LoadReplicationOpsForPeerResult {\n\tconst scopeFilterRequested = options.scopeId !== undefined;\n\tconst effectiveScopeId = normalizeSyncStateScopeId(options.scopeId);\n\tconst boundary = getSyncResetState(db, scopeFilterRequested ? options.scopeId : undefined);\n\tconst since = normalizeCursor(options.since);\n\tconst requestedGeneration = options.generation ?? null;\n\tconst requestedSnapshotId = normalizeCursor(options.snapshotId);\n\tconst requestedBaselineCursor = normalizeCursor(options.baselineCursor);\n\tconst hasAnyBoundaryField =\n\t\trequestedGeneration != null || requestedSnapshotId != null || requestedBaselineCursor != null;\n\n\tif (requestedGeneration != null && requestedGeneration !== boundary.generation) {\n\t\treturn resetRequired(boundary, \"generation_mismatch\");\n\t}\n\n\tconst hasCompleteBoundary =\n\t\trequestedGeneration != null &&\n\t\trequestedSnapshotId != null &&\n\t\trequestedBaselineCursor === boundary.baseline_cursor;\n\n\tif (!hasAnyBoundaryField || !hasCompleteBoundary) {\n\t\treturn resetRequired(boundary, \"boundary_mismatch\");\n\t}\n\n\tif (\n\t\trequestedSnapshotId !== boundary.snapshot_id ||\n\t\trequestedBaselineCursor !== boundary.baseline_cursor\n\t) {\n\t\treturn resetRequired(boundary, \"boundary_mismatch\");\n\t}\n\n\tif (\n\t\tsince != null &&\n\t\tboundary.retained_floor_cursor != null &&\n\t\tsince < boundary.retained_floor_cursor\n\t) {\n\t\treturn resetRequired(boundary, \"stale_cursor\");\n\t}\n\n\tconst [ops, nextCursor] = loadReplicationOpsSince(\n\t\tdb,\n\t\tsince,\n\t\toptions.limit,\n\t\t// `/v1/ops` is an author stream, not a Space relay. Even when a\n\t\t// scoped request filters by `scope_id`, this keeps returned ops authored\n\t\t// by the serving device (plus legacy `local` rows) so receivers can keep\n\t\t// rejecting batches whose device_id / clock_device_id do not match the\n\t\t// authenticated peer.\n\t\toptions.deviceId,\n\t\teffectiveScopeId,\n\t);\n\tconst peerBoundaryOps = ops.filter((op) => {\n\t\tif (op.entity_type !== \"memory_item\") return true;\n\t\tif (retirementBlocksMemoryOp(db, op)) return false;\n\t\tif (op.op_type === ACCESS_CLEANUP_OP_TYPE || op.op_type === REASSIGN_SCOPE_OP_TYPE) {\n\t\t\treturn true;\n\t\t}\n\t\tconst scopeId = cleanText(op.scope_id);\n\t\treturn Boolean(scopeId && scopeId !== DEFAULT_SYNC_SCOPE_ID);\n\t});\n\tconst page = opsPageWithinBytes(peerBoundaryOps, nextCursor, options.maxBytes);\n\treturn { reset_required: false, boundary, ...page };\n}\n\nfunction snapshotClockDeviceId(payload: MemoryPayload, row: MemoryItemRow): string {\n\tconst metadata = payload.metadata_json;\n\tif (typeof metadata?.clock_device_id === \"string\" && metadata.clock_device_id.trim())\n\t\treturn metadata.clock_device_id.trim();\n\treturn String(row.origin_device_id ?? \"local\");\n}\n\nfunction unretiredSnapshotPayload(\n\tdb: Database,\n\trow: MemoryItemRow,\n\tsourceDeviceId?: string,\n): MemoryPayload | null {\n\tif (sourceDeviceId && memorySourceNamespace(row.import_key ?? \"\") !== sourceDeviceId) return null;\n\tconst payload = buildPayloadFromMemoryRow(row);\n\tif (\n\t\t!retirementAllowsSnapshot(\n\t\t\tdb,\n\t\t\tString(row.import_key ?? \"\"),\n\t\t\tpayload as unknown as Record<string, unknown>,\n\t\t\tcleanText(row.scope_id),\n\t\t)\n\t)\n\t\treturn null;\n\treturn payload;\n}\n\ntype SnapshotRow = { memory: MemoryItemRow; sessionProject: string | null };\n\n/** The snapshot item for one memory row, or null when the peer may not receive it. */\nfunction snapshotItemForPeer(\n\tdb: Database,\n\trow: SnapshotRow,\n\timportKey: string,\n\toptions: LoadMemorySnapshotPageForPeerOptions,\n): SyncMemorySnapshotItem | null {\n\tconst payload = unretiredSnapshotPayload(db, row.memory, options.sourceDeviceId);\n\tif (!payload) return null;\n\tconst record = payload as unknown as Record<string, unknown>;\n\tconst scope = { scope_id: row.memory.scope_id };\n\tconst peerDeviceId = options.peerDeviceId ?? null;\n\tif (\n\t\t(replicationOpRequiresPersonalScopeAuthorization(scope, record) ||\n\t\t\t!syncVisibilityAllowed(record)) &&\n\t\t!peerCanSyncPrivateOpByPersonalScopeGrant(db, scope, record, peerDeviceId)\n\t)\n\t\treturn null;\n\tif (!syncProjectAllowed(db, row.sessionProject, peerDeviceId)) return null;\n\t// Include session project in the payload so targets can associate\n\t// replicated memories with the correct project.\n\tconst payloadWithProject = { ...payload, project: row.sessionProject ?? null };\n\treturn {\n\t\tentity_id: importKey,\n\t\top_type: row.memory.deleted_at || row.memory.active === 0 ? \"delete\" : \"upsert\",\n\t\tpayload_json: toJson(payloadWithProject),\n\t\tclock_rev: Number(row.memory.rev ?? 0),\n\t\tclock_updated_at: String(\n\t\t\trow.memory.updated_at ?? row.memory.created_at ?? new Date().toISOString(),\n\t\t),\n\t\tclock_device_id: snapshotClockDeviceId(payload, row.memory),\n\t};\n}\n\nexport function loadMemorySnapshotPageForPeer(\n\tdb: Database,\n\toptions: LoadMemorySnapshotPageForPeerOptions,\n): LoadMemorySnapshotPageForPeerResult {\n\tconst scopeFilterRequested = options.scopeId !== undefined;\n\tconst effectiveScopeId = normalizeSyncStateScopeId(options.scopeId);\n\tconst boundary = getSyncResetState(db, scopeFilterRequested ? options.scopeId : undefined);\n\tif (scopeFilterRequested) {\n\t\tconst scope = db\n\t\t\t.prepare(\"SELECT authority_type FROM replication_scopes WHERE scope_id = ? LIMIT 1\")\n\t\t\t.get(effectiveScopeId) as { authority_type?: string | null } | undefined;\n\t\tif (scope?.authority_type === \"local\") {\n\t\t\treturn { boundary, items: [], nextPageToken: null, hasMore: false };\n\t\t}\n\t}\n\tif (options.generation !== boundary.generation) {\n\t\tthrow new Error(\"generation_mismatch\");\n\t}\n\tif (normalizeCursor(options.snapshotId) !== boundary.snapshot_id) {\n\t\tthrow new Error(\"boundary_mismatch\");\n\t}\n\tif (normalizeCursor(options.baselineCursor) !== boundary.baseline_cursor) {\n\t\tthrow new Error(\"boundary_mismatch\");\n\t}\n\tconst peerDeviceId = cleanText(options.peerDeviceId);\n\tif (\n\t\tscopeFilterRequested &&\n\t\tpeerDeviceId &&\n\t\tgetAnyRecipientPolicyDenyOverlayForScopeDevice(db, {\n\t\t\tscopeId: effectiveScopeId,\n\t\t\tdeviceId: peerDeviceId,\n\t\t})\n\t) {\n\t\treturn { boundary, items: [], nextPageToken: null, hasMore: false };\n\t}\n\n\t// Cap raised to 5000 to support elevated bootstrap page sizes (default 2000).\n\tconst limit = Math.max(1, Math.min(options.limit ?? 200, 5000));\n\tconst pageToken = parseSnapshotPageToken(options.pageToken);\n\tconst d = drizzle(db, { schema });\n\t// Scan batch must be >= limit so high page sizes don't degrade into\n\t// multiple keyset-pagination round-trips per page.\n\tconst scanBatchSize = Math.max(limit, Math.min(limit * 3, 10000));\n\tconst rowsAfterToken = (token: { importKey: string; id: number } | null, batchLimit: number) =>\n\t\td\n\t\t\t.select({\n\t\t\t\tmemory: schema.memoryItems,\n\t\t\t\tsessionProject: schema.sessions.project,\n\t\t\t})\n\t\t\t.from(schema.memoryItems)\n\t\t\t.innerJoin(schema.sessions, eq(schema.sessions.id, schema.memoryItems.session_id))\n\t\t\t.where(\n\t\t\t\tand(\n\t\t\t\t\tisNotNull(schema.memoryItems.import_key),\n\t\t\t\t\teffectiveScopeId === DEFAULT_SYNC_SCOPE_ID\n\t\t\t\t\t\t? sql`0 = 1`\n\t\t\t\t\t\t: eq(schema.memoryItems.scope_id, effectiveScopeId),\n\t\t\t\t\ttoken\n\t\t\t\t\t\t? or(\n\t\t\t\t\t\t\t\tgt(schema.memoryItems.import_key, token.importKey),\n\t\t\t\t\t\t\t\tand(\n\t\t\t\t\t\t\t\t\teq(schema.memoryItems.import_key, token.importKey),\n\t\t\t\t\t\t\t\t\tgt(schema.memoryItems.id, token.id),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: undefined,\n\t\t\t\t),\n\t\t\t)\n\t\t\t.orderBy(schema.memoryItems.import_key, schema.memoryItems.id)\n\t\t\t.limit(batchLimit)\n\t\t\t.all();\n\n\tconst items: SyncMemorySnapshotItem[] = [];\n\tconst maxBytes = options.maxBytes ?? SYNC_PAGE_MAX_BYTES;\n\tlet pageBytes = 0;\n\tlet nextScanToken = pageToken;\n\tlet lastScannedToken: string | null = null;\n\tlet hasMore = false;\n\tlet full = false;\n\n\twhile (items.length < limit && !full) {\n\t\tconst rows = rowsAfterToken(nextScanToken, scanBatchSize);\n\t\tif (rows.length === 0) break;\n\n\t\tfor (let index = 0; index < rows.length; index += 1) {\n\t\t\tconst row = rows[index];\n\t\t\tif (!row) continue;\n\t\t\tconst importKey = String(row.memory.import_key ?? \"\").trim();\n\t\t\tif (!importKey) continue;\n\t\t\t// An earlier row is always on the page when this is used, so it is never null then.\n\t\t\tconst tokenBeforeRow: string | null = lastScannedToken;\n\t\t\tlastScannedToken = makeSnapshotPageToken(importKey, Number(row.memory.id));\n\t\t\tnextScanToken = { importKey, id: Number(row.memory.id) };\n\t\t\tconst item = snapshotItemForPeer(db, row, importKey, options);\n\t\t\tif (!item) continue;\n\t\t\tconst itemBytes = Buffer.byteLength(JSON.stringify(item)) + 1;\n\t\t\tif (items.length > 0 && pageBytes + itemBytes > maxBytes) {\n\t\t\t\t// This row goes on the next page, so the token stops before it.\n\t\t\t\tlastScannedToken = tokenBeforeRow;\n\t\t\t\thasMore = true;\n\t\t\t\tfull = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\titems.push(item);\n\t\t\tpageBytes += itemBytes;\n\n\t\t\tif (items.length >= limit) {\n\t\t\t\thasMore = index < rows.length - 1 || rowsAfterToken(nextScanToken, 1).length > 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (full || items.length >= limit || rows.length < scanBatchSize) break;\n\t}\n\treturn {\n\t\tboundary,\n\t\titems,\n\t\tnextPageToken: hasMore ? lastScannedToken : null,\n\t\thasMore: hasMore && lastScannedToken != null,\n\t};\n}\n\nexport function hasUnsyncedSharedMemoryChanges(db: Database, limit = 25): SyncDirtyLocalState {\n\t// Single SQL query replacing the old O(N×M) JS loop that loaded every\n\t// memory item then queried replication_ops per-row. This uses NOT EXISTS\n\t// to find shared memories whose current rev lacks a matching replication op,\n\t// which is exactly the \"dirty\" condition the old loop was checking.\n\t//\n\t// Visibility matching follows syncVisibilityAllowed semantics:\n\t// - explicit 'shared', 'shared:default', 'shared:legacy' → sync-eligible\n\t// - NULL/empty visibility with non-private content → sync-eligible (legacy default)\n\t// - explicit 'private' or 'personal:*' → not sync-eligible\n\tconst stmt = db.prepare(`\n\t\tSELECT count(*) as n FROM (\n\t\t\tSELECT 1 FROM memory_items m\n\t\t\tWHERE m.import_key IS NOT NULL\n\t\t\t AND COALESCE(m.visibility, '') NOT LIKE 'private%'\n\t\t\t AND COALESCE(m.visibility, '') NOT LIKE 'personal%'\n\t\t\t AND NOT EXISTS (\n\t\t\t\tSELECT 1 FROM replication_ops r\n\t\t\t\tWHERE r.entity_type = 'memory_item'\n\t\t\t\t AND r.entity_id = m.import_key\n\t\t\t\t AND r.op_type = CASE WHEN m.deleted_at IS NOT NULL OR m.active = 0 THEN 'delete' ELSE 'upsert' END\n\t\t\t\t AND r.clock_rev = COALESCE(m.rev, 0)\n\t\t\t )\n\t\t\tLIMIT ?\n\t\t)\n\t`);\n\tconst row = stmt.get(limit) as { n: number } | undefined;\n\tconst count = Number(row?.n ?? 0);\n\treturn { dirty: count > 0, count };\n}\n\nexport function pruneReplicationOps(\n\tdb: Database,\n\toptions?: {\n\t\tmaxAgeDays?: number;\n\t\tmaxSizeBytes?: number;\n\t\tmaxDeleteOps?: number;\n\t\tmaxRuntimeMs?: number;\n\t\tscopeId?: string | null;\n\t},\n): ReplicationOpsPruneResult {\n\tconst maxAgeDays = Math.max(1, Math.floor(options?.maxAgeDays ?? 30));\n\tconst maxSizeBytes = Math.max(1, Math.floor(options?.maxSizeBytes ?? 512 * 1024 * 1024));\n\tconst maxDeleteOps = Math.max(1, Math.floor(options?.maxDeleteOps ?? Number.MAX_SAFE_INTEGER));\n\tconst maxRuntimeMs = Math.max(1, Math.floor(options?.maxRuntimeMs ?? Number.MAX_SAFE_INTEGER));\n\tconst scopeId = normalizeSyncStateScopeId(options?.scopeId);\n\tconst d = drizzle(db, { schema });\n\tconst cutoff = new Date(Date.now() - maxAgeDays * 24 * 60 * 60 * 1000).toISOString();\n\tconst startedAt = Date.now();\n\tlet deleted = 0;\n\tlet lastDeletedCursor: string | null = null;\n\tconst deleteThroughCursor = (createdAt: string, opId: string): number => {\n\t\tconst floorCursor = computeCursor(createdAt, opId);\n\t\treturn db\n\t\t\t.transaction(() => {\n\t\t\t\tconst result =\n\t\t\t\t\tscopeId === DEFAULT_SYNC_SCOPE_ID\n\t\t\t\t\t\t? (db\n\t\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\t\t`DELETE FROM replication_ops\n\t\t\t\t\t\t\t\t\t WHERE (scope_id IS NULL OR scope_id = ?)\n\t\t\t\t\t\t\t\t\t AND (created_at < ? OR (created_at = ? AND op_id <= ?))`,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t.run(scopeId, createdAt, createdAt, opId) as { changes?: number })\n\t\t\t\t\t\t: (db\n\t\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\t\t`DELETE FROM replication_ops\n\t\t\t\t\t\t\t\t\t WHERE scope_id = ?\n\t\t\t\t\t\t\t\t\t AND (created_at < ? OR (created_at = ? AND op_id <= ?))`,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t.run(scopeId, createdAt, createdAt, opId) as { changes?: number });\n\t\t\t\tconst changes = result.changes ?? 0;\n\t\t\t\tif (changes > 0) {\n\t\t\t\t\tsetSyncResetState(db, { retained_floor_cursor: floorCursor }, scopeId);\n\t\t\t\t}\n\t\t\t\treturn changes;\n\t\t\t})\n\t\t\t.immediate();\n\t};\n\tconst estimatedBytesBefore = estimateReplicationOpsScopeBytes(db, scopeId);\n\tif (estimatedBytesBefore == null) {\n\t\tthrow new Error(\"replication_ops_size_unavailable\");\n\t}\n\tlet stoppedByBudget = false;\n\tconst budgetExceeded = () => deleted >= maxDeleteOps || Date.now() - startedAt >= maxRuntimeMs;\n\n\twhile (true) {\n\t\tif (budgetExceeded()) {\n\t\t\tstoppedByBudget = true;\n\t\t\tbreak;\n\t\t}\n\t\tconst remainingDeleteBudget = Math.max(1, maxDeleteOps - deleted);\n\t\tconst ageBatchSize = Math.max(1, Math.min(remainingDeleteBudget, 10_000));\n\t\tconst ageCandidates = d\n\t\t\t.select({\n\t\t\t\top_id: schema.replicationOps.op_id,\n\t\t\t\tcreated_at: schema.replicationOps.created_at,\n\t\t\t})\n\t\t\t.from(schema.replicationOps)\n\t\t\t.where(\n\t\t\t\tand(\n\t\t\t\t\tsql`${schema.replicationOps.created_at} < ${cutoff}`,\n\t\t\t\t\tscopeId === DEFAULT_SYNC_SCOPE_ID\n\t\t\t\t\t\t? or(\n\t\t\t\t\t\t\t\tisNull(schema.replicationOps.scope_id),\n\t\t\t\t\t\t\t\teq(schema.replicationOps.scope_id, scopeId),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: eq(schema.replicationOps.scope_id, scopeId),\n\t\t\t\t),\n\t\t\t)\n\t\t\t.orderBy(schema.replicationOps.created_at, schema.replicationOps.op_id)\n\t\t\t.limit(ageBatchSize)\n\t\t\t.all();\n\t\tif (ageCandidates.length === 0) break;\n\t\tconst boundary = ageCandidates[ageCandidates.length - 1];\n\t\tif (!boundary) break;\n\t\tlastDeletedCursor = computeCursor(String(boundary.created_at), String(boundary.op_id));\n\t\tdeleted += deleteThroughCursor(String(boundary.created_at), String(boundary.op_id));\n\t\tif (budgetExceeded()) {\n\t\t\tstoppedByBudget = true;\n\t\t\tbreak;\n\t\t}\n\t\tif (ageCandidates.length < ageBatchSize) break;\n\t}\n\n\tlet estimatedSizeBytes = estimatedBytesBefore;\n\twhile (estimatedSizeBytes > maxSizeBytes) {\n\t\tif (budgetExceeded()) {\n\t\t\tstoppedByBudget = true;\n\t\t\tbreak;\n\t\t}\n\t\tconst remainingDeleteBudget = Math.max(1, maxDeleteOps - deleted);\n\t\tconst sizeBatchSize = Math.max(1, Math.min(remainingDeleteBudget, 10_000));\n\t\tconst oldestChunk = d\n\t\t\t.select({\n\t\t\t\top_id: schema.replicationOps.op_id,\n\t\t\t\tcreated_at: schema.replicationOps.created_at,\n\t\t\t})\n\t\t\t.from(schema.replicationOps)\n\t\t\t.where(\n\t\t\t\tscopeId === DEFAULT_SYNC_SCOPE_ID\n\t\t\t\t\t? or(isNull(schema.replicationOps.scope_id), eq(schema.replicationOps.scope_id, scopeId))\n\t\t\t\t\t: eq(schema.replicationOps.scope_id, scopeId),\n\t\t\t)\n\t\t\t.orderBy(schema.replicationOps.created_at, schema.replicationOps.op_id)\n\t\t\t.limit(sizeBatchSize)\n\t\t\t.all();\n\t\tconst boundary = oldestChunk[oldestChunk.length - 1];\n\t\tif (!boundary) break;\n\t\tlastDeletedCursor = computeCursor(String(boundary.created_at), String(boundary.op_id));\n\t\tdeleted += deleteThroughCursor(String(boundary.created_at), String(boundary.op_id));\n\t\tconst nextEstimatedSize = estimateReplicationOpsScopeBytes(db, scopeId);\n\t\tif (nextEstimatedSize == null) {\n\t\t\tthrow new Error(\"replication_ops_size_unavailable\");\n\t\t}\n\t\testimatedSizeBytes = nextEstimatedSize;\n\t}\n\n\tconst currentBoundary = getSyncResetState(db, scopeId);\n\tconst retainedFloorCursor =\n\t\tdeleted > 0 ? lastDeletedCursor : currentBoundary.retained_floor_cursor;\n\treturn {\n\t\tdeleted,\n\t\tretained_floor_cursor: retainedFloorCursor,\n\t\testimated_bytes_before: estimatedBytesBefore,\n\t\testimated_bytes_after: estimatedSizeBytes,\n\t\tstopped_by_budget: stoppedByBudget,\n\t};\n}\n\nexport interface ReplicationOpsPruneLoopResult {\n\ttotalDeleted: number;\n\tpasses: number;\n\tlastFloor: string | null;\n\tafterBytes: number;\n\tstoppedByBudget: boolean;\n}\n\nexport function pruneReplicationOpsUntilCaughtUp(\n\tdb: Database,\n\toptions: {\n\t\tmaxAgeDays: number;\n\t\tmaxSizeBytes: number;\n\t\tmaxDeleteOps: number;\n\t\tmaxRuntimeMs: number;\n\t\tscopeId?: string | null;\n\t\tmaxPasses?: number;\n\t\tsignal?: AbortSignal;\n\t\tonPass?: (pass: {\n\t\t\tpassNumber: number;\n\t\t\tdeleted: number;\n\t\t\tafterBytes: number;\n\t\t\tstoppedByBudget: boolean;\n\t\t}) => void;\n\t},\n): ReplicationOpsPruneLoopResult {\n\tconst maxPasses = Math.max(1, Math.floor(options.maxPasses ?? 25));\n\tlet totalDeleted = 0;\n\tlet passes = 0;\n\tlet lastFloor: string | null = null;\n\tlet afterBytes = estimateReplicationOpsStorageBytes(db) ?? 0;\n\tlet stoppedByBudget = false;\n\n\twhile (true) {\n\t\tif (options.signal?.aborted || passes >= maxPasses) {\n\t\t\tstoppedByBudget = true;\n\t\t\tbreak;\n\t\t}\n\t\tconst result = pruneReplicationOps(db, options);\n\t\tpasses += 1;\n\t\ttotalDeleted += result.deleted;\n\t\tlastFloor = result.retained_floor_cursor;\n\t\tafterBytes = result.estimated_bytes_after ?? estimateReplicationOpsStorageBytes(db) ?? 0;\n\t\tstoppedByBudget = result.stopped_by_budget ?? false;\n\t\toptions.onPass?.({\n\t\t\tpassNumber: passes,\n\t\t\tdeleted: result.deleted,\n\t\t\tafterBytes,\n\t\t\tstoppedByBudget,\n\t\t});\n\t\tif (result.deleted === 0 || !result.stopped_by_budget) break;\n\t}\n\n\treturn {\n\t\ttotalDeleted,\n\t\tpasses,\n\t\tlastFloor,\n\t\tafterBytes,\n\t\tstoppedByBudget,\n\t};\n}\n\nexport function bulkPruneReplicationOpsByAgeCutoff(\n\tdb: Database,\n\tmaxAgeDays: number,\n\tmaxDeleteOps = Number.MAX_SAFE_INTEGER,\n\tscopeIdInput?: string | null,\n): ReplicationOpsPruneResult {\n\tconst d = drizzle(db, { schema });\n\tconst scopeId = normalizeSyncStateScopeId(scopeIdInput);\n\tconst cutoff = new Date(\n\t\tDate.now() - Math.max(1, Math.floor(maxAgeDays)) * 24 * 60 * 60 * 1000,\n\t).toISOString();\n\tconst estimatedBytesBefore = estimateReplicationOpsScopeBytes(db, scopeId);\n\tif (estimatedBytesBefore == null) {\n\t\tthrow new Error(\"replication_ops_size_unavailable\");\n\t}\n\tconst oldestEligible = d\n\t\t.select({ op_id: schema.replicationOps.op_id, created_at: schema.replicationOps.created_at })\n\t\t.from(schema.replicationOps)\n\t\t.where(\n\t\t\tand(\n\t\t\t\tsql`${schema.replicationOps.created_at} < ${cutoff}`,\n\t\t\t\tscopeId === DEFAULT_SYNC_SCOPE_ID\n\t\t\t\t\t? or(isNull(schema.replicationOps.scope_id), eq(schema.replicationOps.scope_id, scopeId))\n\t\t\t\t\t: eq(schema.replicationOps.scope_id, scopeId),\n\t\t\t),\n\t\t)\n\t\t.orderBy(schema.replicationOps.created_at, schema.replicationOps.op_id)\n\t\t.limit(Math.max(1, maxDeleteOps))\n\t\t.all();\n\tconst boundary = oldestEligible[oldestEligible.length - 1];\n\tif (!boundary) {\n\t\tconst currentBoundary = getSyncResetState(db, scopeId);\n\t\treturn {\n\t\t\tdeleted: 0,\n\t\t\tretained_floor_cursor: currentBoundary.retained_floor_cursor,\n\t\t\testimated_bytes_before: estimatedBytesBefore,\n\t\t\testimated_bytes_after: estimatedBytesBefore,\n\t\t\tstopped_by_budget: false,\n\t\t};\n\t}\n\tconst retainedFloorCursor = computeCursor(String(boundary.created_at), String(boundary.op_id));\n\tconst deleted = db\n\t\t.transaction(() => {\n\t\t\tconst result =\n\t\t\t\tscopeId === DEFAULT_SYNC_SCOPE_ID\n\t\t\t\t\t? (db\n\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\t`DELETE FROM replication_ops\n\t\t\t\t\t\t\t\t WHERE (scope_id IS NULL OR scope_id = ?)\n\t\t\t\t\t\t\t\t AND (created_at < ? OR (created_at = ? AND op_id <= ?))`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.run(scopeId, boundary.created_at, boundary.created_at, boundary.op_id) as {\n\t\t\t\t\t\t\tchanges?: number;\n\t\t\t\t\t\t})\n\t\t\t\t\t: (db\n\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\t`DELETE FROM replication_ops\n\t\t\t\t\t\t\t\t WHERE scope_id = ?\n\t\t\t\t\t\t\t\t AND (created_at < ? OR (created_at = ? AND op_id <= ?))`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.run(scopeId, boundary.created_at, boundary.created_at, boundary.op_id) as {\n\t\t\t\t\t\t\tchanges?: number;\n\t\t\t\t\t\t});\n\t\t\tconst changes = result.changes ?? 0;\n\t\t\tif (changes > 0) {\n\t\t\t\tsetSyncResetState(db, { retained_floor_cursor: retainedFloorCursor }, scopeId);\n\t\t\t}\n\t\t\treturn changes;\n\t\t})\n\t\t.immediate();\n\tconst estimatedBytesAfter = estimateReplicationOpsScopeBytes(db, scopeId);\n\tif (estimatedBytesAfter == null) {\n\t\tthrow new Error(\"replication_ops_size_unavailable\");\n\t}\n\treturn {\n\t\tdeleted,\n\t\tretained_floor_cursor: retainedFloorCursor,\n\t\testimated_bytes_before: estimatedBytesBefore,\n\t\testimated_bytes_after: estimatedBytesAfter,\n\t\tstopped_by_budget: false,\n\t};\n}\n\nexport function planReplicationOpsAgePrune(\n\tdb: Database,\n\tmaxAgeDays: number,\n\tbatchOps: number,\n): ReplicationOpsAgePrunePlan {\n\tconst d = drizzle(db, { schema });\n\tconst cutoff = new Date(\n\t\tDate.now() - Math.max(1, Math.floor(maxAgeDays)) * 24 * 60 * 60 * 1000,\n\t).toISOString();\n\tconst countRow = d\n\t\t.select({ total: sql<number>`COUNT(*)` })\n\t\t.from(schema.replicationOps)\n\t\t.where(sql`${schema.replicationOps.created_at} < ${cutoff}`)\n\t\t.get();\n\tconst totalCountRow = d\n\t\t.select({ total: sql<number>`COUNT(*)` })\n\t\t.from(schema.replicationOps)\n\t\t.get();\n\tconst boundary = d\n\t\t.select({ op_id: schema.replicationOps.op_id, created_at: schema.replicationOps.created_at })\n\t\t.from(schema.replicationOps)\n\t\t.where(sql`${schema.replicationOps.created_at} < ${cutoff}`)\n\t\t.orderBy(desc(schema.replicationOps.created_at), desc(schema.replicationOps.op_id))\n\t\t.limit(1)\n\t\t.get();\n\tconst candidateOps = Number(countRow?.total ?? 0);\n\tconst totalOps = Number(totalCountRow?.total ?? 0);\n\tconst estimatedTotalBytes = estimateReplicationOpsStorageBytes(db) ?? 0;\n\tconst estimatedCandidateBytes =\n\t\ttotalOps > 0 ? Math.round((estimatedTotalBytes * candidateOps) / totalOps) : 0;\n\treturn {\n\t\tcandidate_ops: candidateOps,\n\t\testimated_candidate_bytes: Math.max(0, estimatedCandidateBytes),\n\t\tcutoff_cursor: boundary\n\t\t\t? computeCursor(String(boundary.created_at), String(boundary.op_id))\n\t\t\t: null,\n\t\testimated_batches: candidateOps > 0 ? Math.ceil(candidateOps / Math.max(1, batchOps)) : 0,\n\t};\n}\n\nfunction estimateReplicationOpsStorageBytes(db: Database): number | null {\n\ttry {\n\t\tconst row = db\n\t\t\t.prepare(\n\t\t\t\t`SELECT COALESCE(SUM(pgsize), 0) AS total_bytes\n\t\t\t\t FROM dbstat\n\t\t\t\t WHERE name = 'replication_ops'\n\t\t\t\t OR name LIKE 'idx_replication_ops_%'\n\t\t\t\t OR name LIKE 'sqlite_autoindex_replication_ops_%'`,\n\t\t\t)\n\t\t\t.get() as { total_bytes?: number | string | null } | undefined;\n\t\tconst total = Number(row?.total_bytes ?? 0);\n\t\treturn Number.isFinite(total) && total >= 0 ? total : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function estimateReplicationOpsScopeBytes(db: Database, scopeId: string): number | null {\n\tconst estimateSql = `SELECT COALESCE(SUM(\n\t\tLENGTH(COALESCE(op_id, '')) +\n\t\tLENGTH(COALESCE(entity_type, '')) +\n\t\tLENGTH(COALESCE(entity_id, '')) +\n\t\tLENGTH(COALESCE(op_type, '')) +\n\t\tLENGTH(COALESCE(payload_json, '')) +\n\t\tLENGTH(COALESCE(clock_updated_at, '')) +\n\t\tLENGTH(COALESCE(clock_device_id, '')) +\n\t\tLENGTH(COALESCE(device_id, '')) +\n\t\tLENGTH(COALESCE(created_at, '')) +\n\t\tLENGTH(COALESCE(scope_id, '')) +\n\t\t96\n\t), 0) AS total_bytes\n\tFROM replication_ops\n\tWHERE ${scopeId === DEFAULT_SYNC_SCOPE_ID ? \"scope_id IS NULL OR scope_id = ?\" : \"scope_id = ?\"}`;\n\ttry {\n\t\tconst row = db.prepare(estimateSql).get(scopeId) as\n\t\t\t| { total_bytes?: number | string | null }\n\t\t\t| undefined;\n\t\tconst total = Number(row?.total_bytes ?? 0);\n\t\treturn Number.isFinite(total) && total >= 0 ? total : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction cleanList(values: unknown): string[] {\n\tif (!Array.isArray(values)) return [];\n\tconst out: string[] = [];\n\tfor (const raw of values) {\n\t\tconst value = String(raw ?? \"\").trim();\n\t\tif (value) out.push(value);\n\t}\n\treturn out;\n}\n\nfunction parseStringList(value: unknown): string[] {\n\tif (Array.isArray(value)) return cleanList(value);\n\tif (typeof value === \"string\") {\n\t\treturn value\n\t\t\t.split(\",\")\n\t\t\t.map((part) => part.trim())\n\t\t\t.filter(Boolean);\n\t}\n\treturn [];\n}\n\nfunction parseJsonList(valuesJson: string | null | undefined): string[] {\n\tif (!valuesJson) return [];\n\ttry {\n\t\treturn cleanList(JSON.parse(valuesJson));\n\t} catch {\n\t\treturn [];\n\t}\n}\n\nfunction effectiveSyncProjectFilters(\n\tdb: Database,\n\tpeerDeviceId: string | null,\n): { include: string[]; exclude: string[] } {\n\tconst d = drizzle(db, { schema });\n\tconst config = readCodememConfigFile();\n\tconst includeOverride = process.env.CODEMEM_SYNC_PROJECTS_INCLUDE;\n\tconst excludeOverride = process.env.CODEMEM_SYNC_PROJECTS_EXCLUDE;\n\tconst globalInclude =\n\t\tincludeOverride !== undefined\n\t\t\t? parseStringList(includeOverride)\n\t\t\t: parseStringList(config.sync_projects_include);\n\tconst globalExclude =\n\t\texcludeOverride !== undefined\n\t\t\t? parseStringList(excludeOverride)\n\t\t\t: parseStringList(config.sync_projects_exclude);\n\tif (!peerDeviceId) return { include: globalInclude, exclude: globalExclude };\n\n\tconst row = d\n\t\t.select({\n\t\t\tprojects_include_json: schema.syncPeers.projects_include_json,\n\t\t\tprojects_exclude_json: schema.syncPeers.projects_exclude_json,\n\t\t})\n\t\t.from(schema.syncPeers)\n\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t.limit(1)\n\t\t.get();\n\tif (!row) return { include: globalInclude, exclude: globalExclude };\n\n\tconst hasOverride = row.projects_include_json != null || row.projects_exclude_json != null;\n\tif (!hasOverride) {\n\t\treturn { include: globalInclude, exclude: globalExclude };\n\t}\n\n\treturn {\n\t\tinclude: parseJsonList(row.projects_include_json),\n\t\texclude: parseJsonList(row.projects_exclude_json),\n\t};\n}\n\nexport function syncProjectAllowed(\n\tdb: Database,\n\tproject: string | null,\n\tpeerDeviceId: string | null,\n): boolean {\n\tconst { include, exclude } = effectiveSyncProjectFilters(db, peerDeviceId);\n\treturn syncProjectAllowedByFilters(project, { include, exclude });\n}\n\nexport function syncProjectAllowedByFilters(\n\tprojectValue: string | null,\n\tfilters: { include: string[]; exclude: string[] },\n): boolean {\n\tconst value = String(projectValue ?? \"\").trim();\n\tconst valueBase = projectBasename(value);\n\tfor (const blocked of filters.exclude) {\n\t\tif (blocked === value || blocked === valueBase) return false;\n\t}\n\tif (filters.include.length === 0) return true;\n\tfor (const allowed of filters.include) {\n\t\tif (allowed === value || allowed === valueBase) return true;\n\t}\n\treturn false;\n}\n\nexport function syncVisibilityAllowed(payload: Record<string, unknown> | null): boolean {\n\tif (!payload) return false;\n\tlet visibility = String(payload.visibility ?? \"\")\n\t\t.trim()\n\t\t.toLowerCase();\n\tconst metadata =\n\t\tpayload.metadata_json &&\n\t\ttypeof payload.metadata_json === \"object\" &&\n\t\t!Array.isArray(payload.metadata_json)\n\t\t\t? (payload.metadata_json as Record<string, unknown>)\n\t\t\t: {};\n\tconst metadataVisibility = String(metadata.visibility ?? \"\")\n\t\t.trim()\n\t\t.toLowerCase();\n\tif (!visibility && metadataVisibility) {\n\t\tvisibility = metadataVisibility;\n\t}\n\n\tif (!visibility) {\n\t\tlet workspaceKind = String(payload.workspace_kind ?? \"\")\n\t\t\t.trim()\n\t\t\t.toLowerCase();\n\t\tlet workspaceId = String(payload.workspace_id ?? \"\")\n\t\t\t.trim()\n\t\t\t.toLowerCase();\n\t\tif (!workspaceKind)\n\t\t\tworkspaceKind = String(metadata.workspace_kind ?? \"\")\n\t\t\t\t.trim()\n\t\t\t\t.toLowerCase();\n\t\tif (!workspaceId)\n\t\t\tworkspaceId = String(metadata.workspace_id ?? \"\")\n\t\t\t\t.trim()\n\t\t\t\t.toLowerCase();\n\t\tif (workspaceKind === \"shared\" || workspaceId.startsWith(\"shared:\")) {\n\t\t\tvisibility = \"shared\";\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn visibility === \"shared\";\n}\n\nfunction cleanText(value: unknown): string | null {\n\tconst trimmed = typeof value === \"string\" ? value.trim() : \"\";\n\treturn trimmed.length > 0 ? trimmed : null;\n}\n\nexport interface PersonalScopeGrantStatus {\n\tscope_id: string | null;\n\tauthorized: boolean;\n\tstate: string;\n}\n\nexport function personalScopeGrantStatusForPeer(\n\tdb: Database,\n\tinput: { peerDeviceId: string | null; actorId: string | null },\n): PersonalScopeGrantStatus {\n\tconst peerDeviceId = cleanText(input.peerDeviceId);\n\tconst actorId = cleanText(input.actorId);\n\tif (!peerDeviceId || !actorId) {\n\t\treturn { scope_id: null, authorized: false, state: \"missing_peer_or_actor\" };\n\t}\n\tconst scopeId = `personal:${actorId}`;\n\tconst auth = getCachedScopeAuthorization(db, { deviceId: peerDeviceId, scopeId });\n\treturn { scope_id: scopeId, authorized: auth.authorized, state: auth.state };\n}\n\nfunction personalScopeAuthorizationRequirement(\n\top: Pick<ReplicationOp, \"scope_id\">,\n\tpayload: Record<string, unknown> | null,\n): { required: boolean; scopeId: string | null } {\n\tconst metadata =\n\t\tpayload?.metadata_json &&\n\t\ttypeof payload.metadata_json === \"object\" &&\n\t\t!Array.isArray(payload.metadata_json)\n\t\t\t? (payload.metadata_json as Record<string, unknown>)\n\t\t\t: {};\n\tconst opScopeId = cleanText(op.scope_id);\n\tconst payloadScopeId = cleanText(payload?.scope_id);\n\tconst visibility = cleanText(payload?.visibility ?? metadata.visibility)?.toLowerCase() ?? null;\n\tconst workspaceId = cleanText(payload?.workspace_id ?? metadata.workspace_id);\n\tconst workspaceKind =\n\t\tcleanText(payload?.workspace_kind ?? metadata.workspace_kind)?.toLowerCase() ?? null;\n\tconst actorId = cleanText(payload?.actor_id ?? metadata.actor_id);\n\tconst personalWorkspaceId = workspaceId?.startsWith(\"personal:\") ? workspaceId : null;\n\tconst hasPersonalSignal =\n\t\tvisibility === \"private\" ||\n\t\tvisibility === \"personal\" ||\n\t\tworkspaceKind === \"personal\" ||\n\t\tBoolean(personalWorkspaceId);\n\tconst actorScopeId = actorId && hasPersonalSignal ? `personal:${actorId}` : null;\n\tconst candidates = [opScopeId, payloadScopeId, personalWorkspaceId, actorScopeId].filter(\n\t\t(candidate): candidate is string => Boolean(candidate?.startsWith(\"personal:\")),\n\t);\n\tconst scopeId = candidates[0] ?? null;\n\tif (!scopeId) return { required: hasPersonalSignal, scopeId: null };\n\tif (candidates.some((candidate) => candidate !== scopeId)) {\n\t\treturn { required: true, scopeId: null };\n\t}\n\treturn { required: true, scopeId };\n}\n\nexport function replicationOpRequiresPersonalScopeAuthorization(\n\top: Pick<ReplicationOp, \"scope_id\">,\n\tpayload: Record<string, unknown> | null,\n): boolean {\n\treturn personalScopeAuthorizationRequirement(op, payload).required;\n}\n\nexport function peerCanSyncPrivateOpByPersonalScopeGrant(\n\tdb: Database,\n\top: Pick<ReplicationOp, \"scope_id\">,\n\tpayload: Record<string, unknown> | null,\n\tpeerDeviceId: string | null,\n): boolean {\n\tconst { scopeId } = personalScopeAuthorizationRequirement(op, payload);\n\tif (!scopeId) return false;\n\tconst actorId = scopeId.slice(\"personal:\".length);\n\treturn personalScopeGrantStatusForPeer(db, { peerDeviceId, actorId }).authorized;\n}\n\nfunction parsePayload(payloadJson: string | null): Record<string, unknown> | null {\n\tif (!payloadJson?.trim()) return null;\n\ttry {\n\t\tconst parsed = JSON.parse(payloadJson) as unknown;\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n\t\treturn parsed as Record<string, unknown>;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport interface FilterReplicationSkipped {\n\treason: \"scope_filter\" | \"visibility_filter\" | \"project_filter\";\n\top_id: string;\n\tcreated_at: string;\n\tentity_type: string;\n\tentity_id: string;\n\tskipped_count: number;\n\tproject?: string | null;\n\tscope_id?: string | null;\n\tvisibility?: string | null;\n}\n\nexport interface FilterReplicationOpsForSyncOptions {\n\tlocalDeviceId?: string | null;\n\tapplyScopeFilter?: boolean;\n\tsupportsReassignScope?: boolean;\n}\n\ninterface ExistingMemoryFilterContext {\n\tpayload: Record<string, unknown>;\n\tproject: string | null;\n\tscopeId: string | null;\n}\n\nfunction addSkipped(\n\tstate: { count: number; first: FilterReplicationSkipped | null },\n\top: ReplicationOp,\n\tskipped: Pick<FilterReplicationSkipped, \"reason\"> &\n\t\tPartial<Omit<FilterReplicationSkipped, \"reason\" | \"skipped_count\">>,\n): void {\n\tstate.count += 1;\n\tif (!state.first) {\n\t\tstate.first = {\n\t\t\t...skipped,\n\t\t\top_id: op.op_id,\n\t\t\tcreated_at: op.created_at,\n\t\t\tentity_type: op.entity_type,\n\t\t\tentity_id: op.entity_id,\n\t\t\tskipped_count: 0,\n\t\t};\n\t}\n}\n\nfunction metadataRecord(payload: Record<string, unknown> | null): Record<string, unknown> {\n\tconst metadata = payload?.metadata_json;\n\tif (!metadata || typeof metadata !== \"object\" || Array.isArray(metadata)) return {};\n\treturn metadata as Record<string, unknown>;\n}\n\nfunction payloadScopeId(payload: Record<string, unknown> | null): string | null {\n\tconst metadata = metadataRecord(payload);\n\treturn cleanText(payload?.scope_id ?? metadata.scope_id);\n}\n\nfunction payloadContradictsOutboundScope(\n\top: Pick<ReplicationOp, \"scope_id\">,\n\tpayload: Record<string, unknown> | null,\n): boolean {\n\tconst opScopeId = cleanText(op.scope_id);\n\tconst explicitPayloadScopeId = payloadScopeId(payload);\n\tif (explicitPayloadScopeId && explicitPayloadScopeId !== opScopeId) return true;\n\tif (!opScopeId) return explicitPayloadScopeId != null;\n\n\tconst personalRequirement = personalScopeAuthorizationRequirement(op, payload);\n\treturn Boolean(\n\t\tpersonalRequirement.required &&\n\t\t\tpersonalRequirement.scopeId &&\n\t\t\tpersonalRequirement.scopeId !== opScopeId,\n\t);\n}\n\nfunction existingMemoryFilterContext(\n\tdb: Database,\n\timportKey: string,\n): ExistingMemoryFilterContext | null {\n\tconst key = cleanText(importKey);\n\tif (!key) return null;\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT\n\t\t\t\tm.actor_id,\n\t\t\t\tm.metadata_json,\n\t\t\t\tm.scope_id,\n\t\t\t\tm.visibility,\n\t\t\t\tm.workspace_id,\n\t\t\t\tm.workspace_kind,\n\t\t\t\ts.project\n\t\t\t FROM memory_items m\n\t\t\t LEFT JOIN sessions s ON s.id = m.session_id\n\t\t\t WHERE m.import_key = ?\n\t\t\t LIMIT 1`,\n\t\t)\n\t\t.get(key) as\n\t\t| {\n\t\t\t\tactor_id: string | null;\n\t\t\t\tmetadata_json: string | null;\n\t\t\t\tproject: string | null;\n\t\t\t\tscope_id: string | null;\n\t\t\t\tvisibility: string | null;\n\t\t\t\tworkspace_id: string | null;\n\t\t\t\tworkspace_kind: string | null;\n\t\t }\n\t\t| undefined;\n\tif (!row) return null;\n\treturn {\n\t\tpayload: {\n\t\t\tactor_id: row.actor_id,\n\t\t\tmetadata_json: fromJson(row.metadata_json),\n\t\t\tvisibility: row.visibility,\n\t\t\tworkspace_id: row.workspace_id,\n\t\t\tworkspace_kind: row.workspace_kind,\n\t\t},\n\t\tproject: cleanText(row.project),\n\t\tscopeId: cleanText(row.scope_id),\n\t};\n}\n\nfunction outboundScopeAllowed(\n\tdb: Database,\n\top: ReplicationOp,\n\tpayload: Record<string, unknown> | null,\n\tpeerDeviceId: string | null,\n\tlocalDeviceId: string | null,\n): boolean {\n\tif (payloadContradictsOutboundScope(op, payload)) return false;\n\tconst scopeId = cleanText(op.scope_id);\n\tif (!scopeId) return true;\n\tif (scopeId === DEFAULT_SYNC_SCOPE_ID) return false;\n\tconst peerId = cleanText(peerDeviceId);\n\tif (!peerId) return false;\n\tconst peerAuth = getCachedScopeAuthorization(db, { deviceId: peerId, scopeId });\n\tif (!peerAuth.authorized || peerAuth.scope?.authority_type === \"local\") return false;\n\tconst localId = cleanText(localDeviceId);\n\tif (!localId) return true;\n\tconst localAuth = getCachedScopeAuthorization(db, { deviceId: localId, scopeId });\n\treturn localAuth.authorized && localAuth.scope?.authority_type !== \"local\";\n}\n\nfunction legacyDefaultReassignAllowed(\n\tdb: Database,\n\top: ReplicationOp,\n\tpeerDeviceId: string | null,\n): boolean {\n\tconst existing = existingMemoryFilterContext(db, op.entity_id);\n\tif (!existing) return false;\n\tif (\n\t\t(replicationOpRequiresPersonalScopeAuthorization(op, existing.payload) ||\n\t\t\t!syncVisibilityAllowed(existing.payload)) &&\n\t\t!peerCanSyncPrivateOpByPersonalScopeGrant(db, op, existing.payload, peerDeviceId)\n\t) {\n\t\treturn false;\n\t}\n\treturn syncProjectAllowed(db, existing.project, peerDeviceId);\n}\n\n/**\n * Filter replication ops for peer sync scopes.\n *\n * Returns ops that pass project/visibility rules, a cursor for the last\n * processed op (including skipped ops), and skipped metadata when filtering\n * removed one or more ops.\n */\nfunction existingDeleteRejection(\n\tdb: Database,\n\top: ReplicationOp,\n\tpeerDeviceId: string | null,\n\toptions: { applyScopeFilter: boolean },\n): Parameters<typeof addSkipped>[2] | null {\n\tconst existing = existingMemoryFilterContext(db, op.entity_id);\n\tif (!existing) return null;\n\tif (options.applyScopeFilter && existing.scopeId && existing.scopeId !== cleanText(op.scope_id)) {\n\t\treturn { reason: \"scope_filter\", scope_id: cleanText(op.scope_id) };\n\t}\n\tif (\n\t\t(replicationOpRequiresPersonalScopeAuthorization(op, existing.payload) ||\n\t\t\t!syncVisibilityAllowed(existing.payload)) &&\n\t\t!peerCanSyncPrivateOpByPersonalScopeGrant(db, op, existing.payload, peerDeviceId)\n\t) {\n\t\treturn {\n\t\t\treason: \"visibility_filter\",\n\t\t\tvisibility:\n\t\t\t\ttypeof existing.payload.visibility === \"string\"\n\t\t\t\t\t? String(existing.payload.visibility)\n\t\t\t\t\t: null,\n\t\t};\n\t}\n\tif (!syncProjectAllowed(db, existing.project, peerDeviceId))\n\t\treturn { reason: \"project_filter\", project: existing.project };\n\treturn null;\n}\n\nexport function filterReplicationOpsForSyncWithStatus(\n\tdb: Database,\n\tops: ReplicationOp[],\n\tpeerDeviceId: string | null,\n\toptions: FilterReplicationOpsForSyncOptions = {},\n): [ReplicationOp[], string | null, FilterReplicationSkipped | null] {\n\tconst allowed: ReplicationOp[] = [];\n\tlet nextCursor: string | null = null;\n\tconst skipped = { count: 0, first: null as FilterReplicationSkipped | null };\n\tconst applyScopeFilter = options.applyScopeFilter !== false;\n\tfor (const op of ops) {\n\t\tif (retirementBlocksMemoryOp(db, op)) {\n\t\t\taddSkipped(skipped, op, { reason: \"scope_filter\", scope_id: cleanText(op.scope_id) });\n\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\tcontinue;\n\t\t}\n\t\tif (op.entity_type === \"memory_item\") {\n\t\t\tconst payload = parsePayload(op.payload_json);\n\t\t\tif (op.op_type === REASSIGN_SCOPE_OP_TYPE && options.supportsReassignScope !== true) {\n\t\t\t\taddSkipped(skipped, op, {\n\t\t\t\t\treason: \"scope_filter\",\n\t\t\t\t\tscope_id: cleanText(op.scope_id),\n\t\t\t\t});\n\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (op.op_type === ACCESS_CLEANUP_OP_TYPE) {\n\t\t\t\tif (!accessCleanupTargetsPeer(op, peerDeviceId)) {\n\t\t\t\t\taddSkipped(skipped, op, {\n\t\t\t\t\t\treason: \"scope_filter\",\n\t\t\t\t\t\tscope_id: cleanText(payload?.cleanup_scope_id ?? op.scope_id),\n\t\t\t\t\t});\n\t\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tallowed.push(op);\n\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (op.op_type === REASSIGN_SCOPE_OP_TYPE) {\n\t\t\t\ttry {\n\t\t\t\t\tconst reassignment = parseReassignScopePayload(op);\n\t\t\t\t\tconst scopeAllowed =\n\t\t\t\t\t\t!applyScopeFilter ||\n\t\t\t\t\t\t(reassignment.side === \"old\" && reassignment.old_scope_id === DEFAULT_SYNC_SCOPE_ID\n\t\t\t\t\t\t\t? legacyDefaultReassignAllowed(db, op, peerDeviceId)\n\t\t\t\t\t\t\t: outboundScopeAllowed(db, op, payload, peerDeviceId, options.localDeviceId ?? null));\n\t\t\t\t\tif (!scopeAllowed) {\n\t\t\t\t\t\taddSkipped(skipped, op, {\n\t\t\t\t\t\t\treason: \"scope_filter\",\n\t\t\t\t\t\t\tscope_id: cleanText(op.scope_id),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (reassignment.side === \"old\") {\n\t\t\t\t\t\tallowed.push(op);\n\t\t\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\taddSkipped(skipped, op, {\n\t\t\t\t\t\treason: \"scope_filter\",\n\t\t\t\t\t\tscope_id: cleanText(op.scope_id),\n\t\t\t\t\t});\n\t\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst regularScopeId = cleanText(op.scope_id);\n\t\t\tif (!regularScopeId || regularScopeId === DEFAULT_SYNC_SCOPE_ID) {\n\t\t\t\taddSkipped(skipped, op, { reason: \"scope_filter\", scope_id: regularScopeId });\n\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tapplyScopeFilter &&\n\t\t\t\t!outboundScopeAllowed(db, op, payload, peerDeviceId, options.localDeviceId ?? null)\n\t\t\t) {\n\t\t\t\taddSkipped(skipped, op, { reason: \"scope_filter\", scope_id: cleanText(op.scope_id) });\n\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (op.op_type === \"delete\" && payload == null) {\n\t\t\t\tconst rejection = existingDeleteRejection(db, op, peerDeviceId, { applyScopeFilter });\n\t\t\t\tif (rejection) {\n\t\t\t\t\taddSkipped(skipped, op, rejection);\n\t\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\treplicationOpRequiresPersonalScopeAuthorization(op, payload) &&\n\t\t\t\t\t!peerCanSyncPrivateOpByPersonalScopeGrant(db, op, payload, peerDeviceId)\n\t\t\t\t) {\n\t\t\t\t\taddSkipped(skipped, op, { reason: \"visibility_filter\" });\n\t\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tallowed.push(op);\n\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\t(replicationOpRequiresPersonalScopeAuthorization(op, payload) ||\n\t\t\t\t\t!syncVisibilityAllowed(payload)) &&\n\t\t\t\t!peerCanSyncPrivateOpByPersonalScopeGrant(db, op, payload, peerDeviceId)\n\t\t\t) {\n\t\t\t\taddSkipped(skipped, op, {\n\t\t\t\t\treason: \"visibility_filter\",\n\t\t\t\t\tvisibility: typeof payload?.visibility === \"string\" ? String(payload.visibility) : null,\n\t\t\t\t});\n\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst project =\n\t\t\t\ttypeof payload?.project === \"string\" && payload.project.trim()\n\t\t\t\t\t? payload.project.trim()\n\t\t\t\t\t: null;\n\t\t\tif (!syncProjectAllowed(db, project, peerDeviceId)) {\n\t\t\t\taddSkipped(skipped, op, { reason: \"project_filter\", project });\n\t\t\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tallowed.push(op);\n\t\tnextCursor = computeCursor(op.created_at, op.op_id);\n\t}\n\n\tif (skipped.first) {\n\t\tskipped.first.skipped_count = skipped.count;\n\t}\n\n\treturn [allowed, nextCursor, skipped.first];\n}\n\nexport function filterReplicationOpsForSync(\n\tdb: Database,\n\tops: ReplicationOp[],\n\tpeerDeviceId: string | null,\n\toptions: FilterReplicationOpsForSyncOptions = {},\n): [ReplicationOp[], string | null] {\n\tconst [allowed, nextCursor] = filterReplicationOpsForSyncWithStatus(\n\t\tdb,\n\t\tops,\n\t\tpeerDeviceId,\n\t\toptions,\n\t);\n\treturn [allowed, nextCursor];\n}\n\n// Apply inbound replication ops\n\nfunction skipOwnOrRetiredMemoryOp(db: Database, op: ReplicationOp, localDeviceId: string): boolean {\n\tif (op.device_id === localDeviceId) return true;\n\treturn retirementBlocksMemoryOp(db, op);\n}\n\nfunction retirementPayloadContradictsScope(\n\top: ReplicationOp,\n\tscopeId: string,\n\tpayload: Record<string, unknown> | null,\n): boolean {\n\tconst scopes = [payload?.scope_id, metadataRecord(payload).scope_id];\n\tif (op.op_type === ACCESS_CLEANUP_OP_TYPE) {\n\t\tconst cleanupScope = cleanText(payload?.cleanup_scope_id ?? payload?.scope_id);\n\t\tif (!cleanupScope) return true;\n\t\tif (scopeId !== DEFAULT_SYNC_SCOPE_ID && scopeId !== cleanupScope) return true;\n\t\treturn scopes.some((value) => value != null && cleanText(value) !== cleanupScope);\n\t}\n\treturn scopes.some((value) => value != null && cleanText(value) !== scopeId);\n}\n\n/** History makes missing/contradictory scope unsafe even without optional membership validation. */\nfunction retirementBlocksMemoryOp(db: Database, op: ReplicationOp): boolean {\n\tif (op.entity_type !== \"memory_item\" || !hasMemoryScopeRetirement(db, op.entity_id)) return false;\n\tconst scopeId = cleanText(op.scope_id);\n\tif (!scopeId || isMemoryScopeRetired(db, op.entity_id, scopeId)) return true;\n\tconst payload = parsePayload(op.payload_json);\n\tif (op.payload_json != null && !payload) return true;\n\tif (retirementPayloadContradictsScope(op, scopeId, payload)) return true;\n\tif (op.op_type === ACCESS_CLEANUP_OP_TYPE) {\n\t\treturn isMemoryScopeRetired(db, op.entity_id, parseAccessCleanupPayload(op).cleanup_scope_id);\n\t}\n\tif (op.op_type !== REASSIGN_SCOPE_OP_TYPE) return false;\n\ttry {\n\t\tconst reassignment = parseReassignScopePayload(op);\n\t\treturn isMemoryScopeRetired(db, op.entity_id, reassignment.new_scope_id);\n\t} catch {\n\t\treturn true;\n\t}\n}\n\nexport interface ApplyResult {\n\tapplied: number;\n\tskipped: number;\n\trejected: number;\n\tconflicts: number;\n\terrors: string[];\n\trejections: InboundScopeRejection[];\n\tvectorWork: ReplicationVectorWork;\n}\n\nexport interface ReplicationVectorWork {\n\tupsertMemoryIds: number[];\n\tdeleteMemoryIds: number[];\n}\n\nexport type StalePeerReceivedRowReason =\n\t| \"authorization_unknown\"\n\t| \"missing_import_key\"\n\t| \"missing_origin_device\"\n\t| \"missing_scope\"\n\t| \"unverified_local_creation\";\n\nexport interface StalePeerReceivedRowDiagnostic {\n\tmemory_id: number;\n\timport_key: string | null;\n\torigin_device_id: string | null;\n\tscope_id: string | null;\n\treason: StalePeerReceivedRowReason;\n}\n\nexport interface ReconcileStalePeerReceivedRowsResult {\n\tchecked: number;\n\tdeleted: number;\n\tdeleted_memory_ids: number[];\n\tretained: number;\n\tambiguous: StalePeerReceivedRowDiagnostic[];\n}\n\nexport interface ReconcileStalePeerReceivedRowsOptions extends LocalCreationContext {\n\tlocalDeviceId: string;\n\tkeysDir?: string;\n\tmaxRows?: number | null;\n\tpeerDeviceId?: string | null;\n}\n\nexport type DiagnoseStalePeerReceivedRowsResult = Omit<\n\tReconcileStalePeerReceivedRowsResult,\n\t\"deleted\" | \"deleted_memory_ids\"\n> & {\n\twould_delete: number;\n\twould_delete_memory_ids: number[];\n};\n\ntype StalePeerCandidateAuthState = ReturnType<typeof getCachedScopeAuthorization>[\"state\"];\n\nfunction stalePeerCandidateIsDeletable(state: StalePeerCandidateAuthState): boolean {\n\treturn state === \"revoked\" || state === \"scope_inactive\" || state === \"stale_epoch\";\n}\n\nfunction stalePeerCandidateDiagnostic(input: {\n\timportKey: string | null;\n\tmemoryId: number;\n\toriginDeviceId: string | null;\n\treason: StalePeerReceivedRowReason;\n\tscopeId: string | null;\n}): StalePeerReceivedRowDiagnostic {\n\treturn {\n\t\tmemory_id: input.memoryId,\n\t\timport_key: input.importKey,\n\t\torigin_device_id: input.originDeviceId,\n\t\tscope_id: input.scopeId,\n\t\treason: input.reason,\n\t};\n}\n\nexport function reconcileStalePeerReceivedRows(\n\tdb: Database,\n\toptions: ReconcileStalePeerReceivedRowsOptions,\n): ReconcileStalePeerReceivedRowsResult {\n\treturn reconcileStalePeerReceivedRowsInternal(db, options, true);\n}\n\nexport function diagnoseStalePeerReceivedRows(\n\tdb: Database,\n\toptions: ReconcileStalePeerReceivedRowsOptions,\n): DiagnoseStalePeerReceivedRowsResult {\n\tconst result = reconcileStalePeerReceivedRowsInternal(db, options, false);\n\treturn {\n\t\tchecked: result.checked,\n\t\twould_delete: result.deleted,\n\t\twould_delete_memory_ids: result.deleted_memory_ids,\n\t\tretained: result.retained,\n\t\tambiguous: result.ambiguous,\n\t};\n}\n\nfunction clearRefsBeforeMemoryDeletion(db: Database, memoryId: number): void {\n\tsnapshotSessionExportKeysForMemoryIds(db, [memoryId]);\n\tclearMemoryRefs(db, memoryId);\n}\n\ninterface StalePeerReceivedRow {\n\tid: number;\n\timport_key: string | null;\n\torigin_device_id: string | null;\n\tscope_id: string | null;\n}\n\nfunction stalePeerReceivedRows(\n\tdb: Database,\n\tpeerDeviceId: string | null,\n\tmaxRows: number,\n): StalePeerReceivedRow[] {\n\treturn db\n\t\t.prepare(`SELECT id, import_key, origin_device_id, scope_id\n\t\tFROM memory_items WHERE active = 1 AND (? IS NULL OR origin_device_id = ?)\n\t\tORDER BY id LIMIT ?`)\n\t\t.all(peerDeviceId, peerDeviceId, maxRows) as StalePeerReceivedRow[];\n}\n\nfunction legacyLocalRetentionScope(db: Database, scopeId: string | null): boolean {\n\tconst scope = cleanText(scopeId);\n\tif (!scope || scope === DEFAULT_SYNC_SCOPE_ID || scope === LEGACY_SHARED_REVIEW_SCOPE_ID)\n\t\treturn true;\n\treturn (\n\t\tdb\n\t\t\t.prepare(`SELECT 1 FROM replication_scopes WHERE scope_id = ?\n\t\tAND authority_type IN ('local', 'manual', 'invite')`)\n\t\t\t.get(scope) !== undefined\n\t);\n}\n\nfunction retainOrDiagnoseLocalRow(\n\tdb: Database,\n\trow: StalePeerReceivedRow,\n\tlocalDeviceId: string,\n\tcreationSources: readonly string[],\n\tresult: ReconcileStalePeerReceivedRowsResult,\n): boolean {\n\tconst importKey = cleanText(row.import_key);\n\tconst origin = cleanText(row.origin_device_id);\n\tconst recorded = importKey !== null && hasRecordedLocalCreation(db, importKey);\n\tif (importKey && hasMatchingLocalCreation(db, importKey, creationSources)) {\n\t\tresult.retained += 1;\n\t\treturn true;\n\t}\n\t// Legacy labels retain old rows, but cannot override an unmatched creation record.\n\tif (!recorded && origin === localDeviceId && legacyLocalRetentionScope(db, row.scope_id)) {\n\t\tresult.retained += 1;\n\t\treturn true;\n\t}\n\tif (!recorded && origin !== localDeviceId && origin !== \"local\") return false;\n\t// Preserve uncertain originals; this diagnostic grants no read or write permission.\n\tresult.ambiguous.push(\n\t\tstalePeerCandidateDiagnostic({\n\t\t\tmemoryId: Number(row.id),\n\t\t\timportKey,\n\t\t\toriginDeviceId: origin,\n\t\t\tscopeId: cleanText(row.scope_id),\n\t\t\treason: \"unverified_local_creation\",\n\t\t}),\n\t);\n\treturn true;\n}\n\nfunction reconcileStalePeerReceivedRowsInternal(\n\tdb: Database,\n\toptions: ReconcileStalePeerReceivedRowsOptions,\n\tdeleteRows: boolean,\n): ReconcileStalePeerReceivedRowsResult {\n\tconst localDeviceId = cleanText(options.localDeviceId);\n\tif (!localDeviceId) throw new Error(\"localDeviceId must be a non-empty string\");\n\tconst peerDeviceId = cleanText(options.peerDeviceId);\n\tconst maxRows =\n\t\ttypeof options.maxRows === \"number\" && Number.isFinite(options.maxRows)\n\t\t\t? Math.max(0, Math.trunc(options.maxRows))\n\t\t\t: -1;\n\tconst rows = stalePeerReceivedRows(db, peerDeviceId, maxRows);\n\tconst result: ReconcileStalePeerReceivedRowsResult = {\n\t\tchecked: rows.length,\n\t\tdeleted: 0,\n\t\tdeleted_memory_ids: [],\n\t\tretained: 0,\n\t\tambiguous: [],\n\t};\n\tconst deleteMemory = deleteRows ? db.prepare(\"DELETE FROM memory_items WHERE id = ?\") : null;\n\tconst deleteCandidate = (\n\t\tmemoryId: number,\n\t\tcursor?: { originDeviceId: string; scopeId: string },\n\t): void => {\n\t\tif (deleteRows) {\n\t\t\tclearRefsBeforeMemoryDeletion(db, memoryId);\n\t\t\tdeleteMemory?.run(memoryId);\n\t\t\tif (cursor && cursor.scopeId !== DEFAULT_SYNC_SCOPE_ID) {\n\t\t\t\tclearReplicationCursorLastApplied(db, cursor.originDeviceId, cursor.scopeId);\n\t\t\t}\n\t\t}\n\t\tresult.deleted += 1;\n\t\tresult.deleted_memory_ids.push(memoryId);\n\t};\n\tconst creationSources = cleanupCreationSourceIds(db, localDeviceId, options);\n\tdb.transaction(() => {\n\t\t// Authorization decisions must not survive this synchronous cleanup transaction.\n\t\tconst authorizationByScope = new Map<string, CachedScopeAuthorizationResult>();\n\t\tfor (const row of rows) {\n\t\t\tconst memoryId = Number(row.id);\n\t\t\tconst importKey = cleanText(row.import_key);\n\t\t\tconst originDeviceId = cleanText(row.origin_device_id);\n\t\t\tconst scopeId = cleanText(row.scope_id);\n\t\t\tif (retainOrDiagnoseLocalRow(db, row, localDeviceId, creationSources, result)) continue;\n\t\t\tif (!originDeviceId) {\n\t\t\t\tresult.ambiguous.push(\n\t\t\t\t\tstalePeerCandidateDiagnostic({\n\t\t\t\t\t\timportKey,\n\t\t\t\t\t\tmemoryId,\n\t\t\t\t\t\toriginDeviceId,\n\t\t\t\t\t\treason: \"missing_origin_device\",\n\t\t\t\t\t\tscopeId,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!scopeId || scopeId === DEFAULT_SYNC_SCOPE_ID) {\n\t\t\t\tdeleteCandidate(memoryId);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!importKey) {\n\t\t\t\tresult.ambiguous.push(\n\t\t\t\t\tstalePeerCandidateDiagnostic({\n\t\t\t\t\t\timportKey,\n\t\t\t\t\t\tmemoryId,\n\t\t\t\t\t\toriginDeviceId,\n\t\t\t\t\t\treason: \"missing_import_key\",\n\t\t\t\t\t\tscopeId,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlet auth = authorizationByScope.get(scopeId);\n\t\t\tif (!auth) {\n\t\t\t\tauth = getCachedScopeAuthorization(db, { deviceId: localDeviceId, scopeId });\n\t\t\t\tauthorizationByScope.set(scopeId, auth);\n\t\t\t}\n\t\t\tif (auth.authorized) {\n\t\t\t\tresult.retained += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!auth.scope) {\n\t\t\t\tresult.ambiguous.push(\n\t\t\t\t\tstalePeerCandidateDiagnostic({\n\t\t\t\t\t\timportKey,\n\t\t\t\t\t\tmemoryId,\n\t\t\t\t\t\toriginDeviceId,\n\t\t\t\t\t\treason: \"authorization_unknown\",\n\t\t\t\t\t\tscopeId,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!auth.membership) {\n\t\t\t\tdeleteCandidate(memoryId, { originDeviceId, scopeId });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!stalePeerCandidateIsDeletable(auth.state)) {\n\t\t\t\tresult.ambiguous.push(\n\t\t\t\t\tstalePeerCandidateDiagnostic({\n\t\t\t\t\t\timportKey,\n\t\t\t\t\t\tmemoryId,\n\t\t\t\t\t\toriginDeviceId,\n\t\t\t\t\t\treason: \"authorization_unknown\",\n\t\t\t\t\t\tscopeId,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tdeleteCandidate(memoryId, { originDeviceId, scopeId });\n\t\t}\n\t})();\n\treturn result;\n}\n\nexport type InboundScopeRejectionReason =\n\t| \"missing_scope\"\n\t| \"sender_not_member\"\n\t| \"receiver_not_member\"\n\t| \"stale_epoch\"\n\t| \"scope_mismatch\";\n\nexport interface InboundScopeRejection {\n\top_id: string;\n\tentity_type: string;\n\tentity_id: string;\n\tscope_id: string | null;\n\tpeer_device_id: string | null;\n\treason: InboundScopeRejectionReason;\n}\n\nexport interface InboundScopeValidationOptions {\n\tpeerDeviceId?: string | null;\n\tenabled?: boolean;\n}\n\nexport interface ApplyReplicationOpsOptions extends LocalCreationContext {\n\t/** Authenticated transport peer, for durable applied-mutation accounting. */\n\tactivityPeerDeviceId?: string;\n\t/** Keep incoming requests from resolving failures owned by local cursor retries. */\n\tactivitySource?: SyncTransferObservationSource;\n\tactivityOptions?: { preserveError?: boolean };\n\tinboundScopeValidation?: InboundScopeValidationOptions | null;\n\tkeysDir?: string;\n}\n\nfunction cleanupCreationSourceIds(\n\tdb: Database,\n\tdeviceId: string,\n\toptions: LocalCreationContext & { keysDir?: string },\n): string[] {\n\treturn localCreationSourceIds(db, deviceId, {\n\t\t...options,\n\t\tloadExpectedPublicKey:\n\t\t\toptions.loadExpectedPublicKey ??\n\t\t\t(() =>\n\t\t\t\tloadRuntimeSigningPublicKey(db, {\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tkeysDir: options.keysDir ?? process.env.CODEMEM_KEYS_DIR?.trim(),\n\t\t\t\t}) ?? undefined),\n\t});\n}\n\ntype CachedScopeAuthorizationResult = ReturnType<typeof getCachedScopeAuthorization>;\n\nfunction inboundScopeRejection(\n\top: ReplicationOp,\n\treason: InboundScopeRejectionReason,\n\tpeerDeviceId: string | null,\n\tscopeId: string | null,\n): InboundScopeRejection {\n\treturn {\n\t\top_id: op.op_id,\n\t\tentity_type: op.entity_type,\n\t\tentity_id: op.entity_id,\n\t\tscope_id: scopeId,\n\t\tpeer_device_id: peerDeviceId,\n\t\treason,\n\t};\n}\n\nfunction normalizeInboundScopeId(value: unknown): string | null {\n\treturn cleanText(value);\n}\n\nfunction metadataObject(payload: Record<string, unknown> | null): Record<string, unknown> {\n\tconst metadata = payload?.metadata_json;\n\tif (!metadata || typeof metadata !== \"object\" || Array.isArray(metadata)) return {};\n\treturn metadata as Record<string, unknown>;\n}\n\nfunction payloadContradictsInboundScope(\n\topScopeId: string,\n\tpayload: Record<string, unknown> | null,\n): boolean {\n\tconst metadata = metadataObject(payload);\n\tconst payloadScopeId = cleanText(payload?.scope_id ?? metadata.scope_id);\n\tif (payloadScopeId && payloadScopeId !== opScopeId) return true;\n\n\tconst workspaceId = cleanText(payload?.workspace_id ?? metadata.workspace_id);\n\tif (workspaceId?.startsWith(\"personal:\") && workspaceId !== opScopeId) return true;\n\n\tconst workspaceKind = cleanText(\n\t\tpayload?.workspace_kind ?? metadata.workspace_kind,\n\t)?.toLowerCase();\n\tconst actorId = cleanText(payload?.actor_id ?? metadata.actor_id);\n\tif (workspaceKind === \"personal\" && actorId && `personal:${actorId}` !== opScopeId) {\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nfunction authorizationFailureReason(\n\tauth: CachedScopeAuthorizationResult,\n\tnotMemberReason: \"sender_not_member\" | \"receiver_not_member\",\n): InboundScopeRejectionReason | null {\n\tif (auth.scope?.authority_type === \"local\") return \"missing_scope\";\n\tif (auth.authorized) return null;\n\tif (\n\t\t!auth.scope ||\n\t\tauth.state === \"revoked\" ||\n\t\tauth.state === \"stale_epoch\" ||\n\t\tauth.state === \"scope_unknown\" ||\n\t\tauth.state === \"scope_inactive\"\n\t) {\n\t\treturn \"stale_epoch\";\n\t}\n\treturn notMemberReason;\n}\n\ntype LocalDefaultOldSideReassignmentValidation =\n\t| { ok: true; reassignment: ReassignScopePayload }\n\t| { ok: false; reason: \"scope_mismatch\" | \"sender_not_member\" };\n\nfunction validateLocalDefaultOldSideReassignment(\n\tdb: Database,\n\top: ReplicationOp,\n\tsenderDeviceId: string | null,\n): LocalDefaultOldSideReassignmentValidation {\n\tlet reassignment: ReassignScopePayload;\n\ttry {\n\t\treassignment = parseReassignScopePayload(op);\n\t} catch {\n\t\treturn { ok: false, reason: \"scope_mismatch\" };\n\t}\n\tif (reassignment.side !== \"old\" || reassignment.old_scope_id !== DEFAULT_SYNC_SCOPE_ID) {\n\t\treturn { ok: false, reason: \"scope_mismatch\" };\n\t}\n\tif (\n\t\t!senderDeviceId ||\n\t\tcleanText(op.device_id) !== senderDeviceId ||\n\t\tcleanText(op.clock_device_id) !== senderDeviceId\n\t) {\n\t\treturn { ok: false, reason: \"sender_not_member\" };\n\t}\n\tconst existing = db\n\t\t.prepare(\"SELECT origin_device_id FROM memory_items WHERE import_key = ?\")\n\t\t.get(op.entity_id) as { origin_device_id: string | null } | undefined;\n\tif (existing && cleanText(existing.origin_device_id) !== senderDeviceId) {\n\t\treturn { ok: false, reason: \"sender_not_member\" };\n\t}\n\treturn { ok: true, reassignment };\n}\n\nfunction validateInboundScopeOp(\n\tdb: Database,\n\top: ReplicationOp,\n\tlocalDeviceId: string,\n\toptions: InboundScopeValidationOptions,\n): InboundScopeRejection | null {\n\tconst peerDeviceId = cleanText(options.peerDeviceId) ?? cleanText(op.device_id);\n\tif (op.op_type === ACCESS_CLEANUP_OP_TYPE) {\n\t\tconst senderDeviceId = peerDeviceId ?? cleanText(op.clock_device_id);\n\t\tif (\n\t\t\t!senderDeviceId ||\n\t\t\tcleanText(op.device_id) !== senderDeviceId ||\n\t\t\tcleanText(op.clock_device_id) !== senderDeviceId\n\t\t) {\n\t\t\treturn inboundScopeRejection(op, \"sender_not_member\", peerDeviceId, null);\n\t\t}\n\t\treturn null;\n\t}\n\tconst senderDeviceId = peerDeviceId ?? cleanText(op.clock_device_id);\n\tconst receiverDeviceId = cleanText(localDeviceId);\n\tconst opScopeId = normalizeInboundScopeId(op.scope_id);\n\n\tif (!opScopeId) return inboundScopeRejection(op, \"missing_scope\", peerDeviceId, null);\n\tconst payload = parsePayload(op.payload_json);\n\tif (payloadContradictsInboundScope(opScopeId, payload)) {\n\t\treturn inboundScopeRejection(op, \"scope_mismatch\", peerDeviceId, opScopeId);\n\t}\n\n\tif (\n\t\t!senderDeviceId ||\n\t\tcleanText(op.device_id) !== senderDeviceId ||\n\t\tcleanText(op.clock_device_id) !== senderDeviceId\n\t) {\n\t\treturn inboundScopeRejection(op, \"sender_not_member\", peerDeviceId, opScopeId);\n\t}\n\tlet authorizationScopeId = opScopeId;\n\tlet requireReceiverMembership = true;\n\tlet allowLocalAuthorityRetraction = false;\n\tif (opScopeId === DEFAULT_SYNC_SCOPE_ID) {\n\t\tconst validation = validateLocalDefaultOldSideReassignment(db, op, senderDeviceId);\n\t\tif (!validation.ok) {\n\t\t\treturn inboundScopeRejection(op, validation.reason, peerDeviceId, opScopeId);\n\t\t}\n\t\tauthorizationScopeId = validation.reassignment.new_scope_id;\n\t\tallowLocalAuthorityRetraction = true;\n\t\t// This side only retracts sender-origin data previously delivered through\n\t\t// local-default. Prior recipients intentionally are not members of the new\n\t\t// boundary, and the apply path cannot create a new-scope row for them.\n\t\trequireReceiverMembership = false;\n\t}\n\n\tconst senderAuth = getCachedScopeAuthorization(db, {\n\t\tdeviceId: senderDeviceId,\n\t\tscopeId: authorizationScopeId,\n\t});\n\t// A validated old-side op only retracts a sender-owned local-default row;\n\t// it cannot create data in the destination scope. Permit that removal when\n\t// the receiver cannot know the sender's new device-local scope.\n\tconst senderFailure =\n\t\tallowLocalAuthorityRetraction &&\n\t\t(senderAuth.authorized || (senderAuth.state === \"not_authorized\" && !senderAuth.scope))\n\t\t\t? null\n\t\t\t: authorizationFailureReason(senderAuth, \"sender_not_member\");\n\tif (senderFailure) return inboundScopeRejection(op, senderFailure, peerDeviceId, opScopeId);\n\n\tif (requireReceiverMembership) {\n\t\tif (!receiverDeviceId) {\n\t\t\treturn inboundScopeRejection(op, \"receiver_not_member\", peerDeviceId, opScopeId);\n\t\t}\n\t\tconst receiverAuth = getCachedScopeAuthorization(db, {\n\t\t\tdeviceId: receiverDeviceId,\n\t\t\tscopeId: authorizationScopeId,\n\t\t});\n\t\tconst receiverFailure = authorizationFailureReason(receiverAuth, \"receiver_not_member\");\n\t\tif (receiverFailure) return inboundScopeRejection(op, receiverFailure, peerDeviceId, opScopeId);\n\t}\n\n\treturn null;\n}\n\nfunction validateInboundScopeBatch(\n\tdb: Database,\n\tops: ReplicationOp[],\n\tlocalDeviceId: string,\n\toptions: InboundScopeValidationOptions,\n): InboundScopeRejection[] {\n\tconst rejections: InboundScopeRejection[] = [];\n\tconst expectedPeerDeviceId = cleanText(options.peerDeviceId);\n\tfor (const op of ops) {\n\t\tif (!expectedPeerDeviceId && op.device_id === localDeviceId) continue;\n\t\tconst rejection = validateInboundScopeOp(db, op, localDeviceId, options);\n\t\tif (rejection) rejections.push(rejection);\n\t}\n\treturn rejections;\n}\n\nfunction validateInboundLocalOnlyBatch(\n\tdb: Database,\n\tops: ReplicationOp[],\n\toptions: InboundScopeValidationOptions,\n): InboundScopeRejection[] {\n\tconst peerDeviceId = cleanText(options.peerDeviceId);\n\tconst rejections: InboundScopeRejection[] = [];\n\tfor (const op of ops) {\n\t\tif (op.entity_type !== \"memory_item\" || op.op_type === ACCESS_CLEANUP_OP_TYPE) continue;\n\t\tconst scopeId = normalizeInboundScopeId(op.scope_id);\n\t\tif (!scopeId) {\n\t\t\trejections.push(inboundScopeRejection(op, \"missing_scope\", peerDeviceId, null));\n\t\t\tcontinue;\n\t\t}\n\t\tif (scopeId !== DEFAULT_SYNC_SCOPE_ID) {\n\t\t\tconst scope = db\n\t\t\t\t.prepare(\"SELECT authority_type FROM replication_scopes WHERE scope_id = ? LIMIT 1\")\n\t\t\t\t.get(scopeId) as { authority_type?: string | null } | undefined;\n\t\t\tif (scope?.authority_type === \"local\" || (!scope && options.enabled === false)) {\n\t\t\t\trejections.push(inboundScopeRejection(op, \"missing_scope\", peerDeviceId, scopeId));\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (op.op_type === REASSIGN_SCOPE_OP_TYPE) {\n\t\t\tconst validation = validateLocalDefaultOldSideReassignment(\n\t\t\t\tdb,\n\t\t\t\top,\n\t\t\t\tpeerDeviceId ?? cleanText(op.clock_device_id),\n\t\t\t);\n\t\t\tif (validation.ok) continue;\n\t\t\tif (validation.reason === \"sender_not_member\") {\n\t\t\t\trejections.push(inboundScopeRejection(op, validation.reason, peerDeviceId, scopeId));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\trejections.push(inboundScopeRejection(op, \"scope_mismatch\", peerDeviceId, scopeId));\n\t}\n\treturn rejections;\n}\n\nfunction ensureSyncScopeRejectionLogTable(db: Database): void {\n\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS sync_scope_rejections (\n\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\tpeer_device_id TEXT,\n\t\t\top_id TEXT NOT NULL,\n\t\t\tentity_type TEXT NOT NULL,\n\t\t\tentity_id TEXT NOT NULL,\n\t\t\tscope_id TEXT,\n\t\t\treason TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL\n\t\t);\n\t\tCREATE INDEX IF NOT EXISTS idx_sync_scope_rejections_peer_created\n\t\t\tON sync_scope_rejections(peer_device_id, created_at);\n\t\tCREATE INDEX IF NOT EXISTS idx_sync_scope_rejections_scope_created\n\t\t\tON sync_scope_rejections(scope_id, created_at);\n\t`);\n}\n\nfunction recordInboundScopeRejections(db: Database, rejections: InboundScopeRejection[]): void {\n\tif (rejections.length === 0) return;\n\tensureSyncScopeRejectionLogTable(db);\n\tconst now = new Date().toISOString();\n\tconst insert = db.prepare(\n\t\t`INSERT INTO sync_scope_rejections(\n\t\t\tpeer_device_id, op_id, entity_type, entity_id, scope_id, reason, created_at\n\t\t ) VALUES (?, ?, ?, ?, ?, ?, ?)`,\n\t);\n\tdb.transaction(() => {\n\t\tfor (const rejection of rejections) {\n\t\t\tinsert.run(\n\t\t\t\trejection.peer_device_id,\n\t\t\t\trejection.op_id,\n\t\t\t\trejection.entity_type,\n\t\t\t\trejection.entity_id,\n\t\t\t\trejection.scope_id,\n\t\t\t\trejection.reason,\n\t\t\t\tnow,\n\t\t\t);\n\t\t}\n\t})();\n}\n\nfunction emptyApplyResult(): ApplyResult {\n\treturn {\n\t\tapplied: 0,\n\t\tskipped: 0,\n\t\trejected: 0,\n\t\tconflicts: 0,\n\t\terrors: [],\n\t\trejections: [],\n\t\tvectorWork: { upsertMemoryIds: [], deleteMemoryIds: [] },\n\t};\n}\n\nexport function rejectInboundScopeFailures(\n\tdb: Database,\n\tops: ReplicationOp[],\n\tlocalDeviceId: string,\n\toptions: InboundScopeValidationOptions,\n): ApplyResult | null {\n\tconst localOnlyRejections = validateInboundLocalOnlyBatch(db, ops, options);\n\tconst rejections =\n\t\tlocalOnlyRejections.length > 0\n\t\t\t? localOnlyRejections\n\t\t\t: options.enabled === false\n\t\t\t\t? []\n\t\t\t\t: validateInboundScopeBatch(db, ops, localDeviceId, options);\n\tif (rejections.length === 0) return null;\n\tconst result = emptyApplyResult();\n\tresult.rejected = rejections.length;\n\tresult.rejections = rejections;\n\tresult.errors.push(\n\t\t...rejections.map((rejection) => `op ${rejection.op_id}: rejected — ${rejection.reason}`),\n\t);\n\ttry {\n\t\trecordInboundScopeRejections(db, rejections);\n\t} catch (err) {\n\t\tresult.errors.push(\n\t\t\t`scope rejection log failed: ${err instanceof Error ? err.message : String(err)}`,\n\t\t);\n\t}\n\treturn result;\n}\n\n/** Aggregate counts of recorded inbound-scope rejections per peer device. */\nexport interface InboundScopeRejectionPeerSummary {\n\tpeer_device_id: string | null;\n\ttotal: number;\n\tby_reason: Partial<Record<InboundScopeRejectionReason, number>>;\n\tlast_at: string | null;\n}\n\nexport interface InboundScopeRejectionSummaryOptions {\n\t/** ISO timestamp; rejections older than this are ignored. */\n\tsinceIso?: string;\n\t/** Optional: only summarize rejections recorded for this peer. */\n\tpeerDeviceId?: string | null;\n}\n\n/**\n * Read-only summary of recorded inbound-scope rejections grouped by peer.\n * Pure aggregate over the rejection log — never reads payloads (the log\n * does not store any). Used by the sync API to render reason-code\n * breakdowns without exposing op contents.\n */\nexport function summarizeInboundScopeRejections(\n\tdb: Database,\n\toptions: InboundScopeRejectionSummaryOptions = {},\n): InboundScopeRejectionPeerSummary[] {\n\tif (!syncScopeRejectionsTableExists(db)) return [];\n\tconst params: unknown[] = [];\n\tconst filters: string[] = [];\n\tif (options.sinceIso) {\n\t\tfilters.push(`created_at >= ?`);\n\t\tparams.push(options.sinceIso);\n\t}\n\tif (options.peerDeviceId !== undefined) {\n\t\tconst id = cleanText(options.peerDeviceId);\n\t\tif (id === null) {\n\t\t\tfilters.push(`peer_device_id IS NULL`);\n\t\t} else {\n\t\t\tfilters.push(`peer_device_id = ?`);\n\t\t\tparams.push(id);\n\t\t}\n\t}\n\tconst where = filters.length ? `WHERE ${filters.join(\" AND \")}` : \"\";\n\tconst rows = db\n\t\t.prepare(\n\t\t\t`SELECT peer_device_id, reason, COUNT(*) AS count, MAX(created_at) AS last_at\n\t\t\t FROM sync_scope_rejections\n\t\t\t ${where}\n\t\t\t GROUP BY peer_device_id, reason`,\n\t\t)\n\t\t.all(...params) as Array<{\n\t\tpeer_device_id: string | null;\n\t\treason: string;\n\t\tcount: number;\n\t\tlast_at: string | null;\n\t}>;\n\n\tconst summaries = new Map<string, InboundScopeRejectionPeerSummary>();\n\tfor (const row of rows) {\n\t\tconst key = row.peer_device_id ?? \"\";\n\t\tlet entry = summaries.get(key);\n\t\tif (!entry) {\n\t\t\tentry = {\n\t\t\t\tpeer_device_id: row.peer_device_id ?? null,\n\t\t\t\ttotal: 0,\n\t\t\t\tby_reason: {},\n\t\t\t\tlast_at: null,\n\t\t\t};\n\t\t\tsummaries.set(key, entry);\n\t\t}\n\t\tconst reason = row.reason as InboundScopeRejectionReason;\n\t\tconst count = Number(row.count ?? 0);\n\t\tentry.by_reason[reason] = (entry.by_reason[reason] ?? 0) + count;\n\t\tentry.total += count;\n\t\tif (row.last_at && (!entry.last_at || row.last_at > entry.last_at)) {\n\t\t\tentry.last_at = row.last_at;\n\t\t}\n\t}\n\treturn Array.from(summaries.values());\n}\n\nexport interface InboundScopeRejectionRecord extends InboundScopeRejection {\n\tid: number;\n\tcreated_at: string;\n}\n\nexport interface ListInboundScopeRejectionsOptions {\n\tpeerDeviceId?: string | null;\n\tsinceIso?: string;\n\tlimit?: number;\n}\n\n/**\n * List recently recorded inbound-scope rejections (newest first). Each row\n * is metadata only — op id, entity ref, scope id, reason, timestamp — and\n * never includes op payloads (the log does not store them).\n */\nexport function listInboundScopeRejections(\n\tdb: Database,\n\toptions: ListInboundScopeRejectionsOptions = {},\n): InboundScopeRejectionRecord[] {\n\tif (!syncScopeRejectionsTableExists(db)) return [];\n\tconst params: unknown[] = [];\n\tconst filters: string[] = [];\n\tif (options.sinceIso) {\n\t\tfilters.push(`created_at >= ?`);\n\t\tparams.push(options.sinceIso);\n\t}\n\tif (options.peerDeviceId !== undefined) {\n\t\tconst id = cleanText(options.peerDeviceId);\n\t\tif (id === null) {\n\t\t\tfilters.push(`peer_device_id IS NULL`);\n\t\t} else {\n\t\t\tfilters.push(`peer_device_id = ?`);\n\t\t\tparams.push(id);\n\t\t}\n\t}\n\tconst where = filters.length ? `WHERE ${filters.join(\" AND \")}` : \"\";\n\tconst limit = Math.max(1, Math.min(options.limit ?? 100, 500));\n\tconst rows = db\n\t\t.prepare(\n\t\t\t`SELECT id, peer_device_id, op_id, entity_type, entity_id, scope_id, reason, created_at\n\t\t\t FROM sync_scope_rejections\n\t\t\t ${where}\n\t\t\t ORDER BY created_at DESC, id DESC\n\t\t\t LIMIT ?`,\n\t\t)\n\t\t.all(...params, limit) as Array<{\n\t\tid: number;\n\t\tpeer_device_id: string | null;\n\t\top_id: string;\n\t\tentity_type: string;\n\t\tentity_id: string;\n\t\tscope_id: string | null;\n\t\treason: string;\n\t\tcreated_at: string;\n\t}>;\n\treturn rows.map((row) => ({\n\t\tid: Number(row.id),\n\t\tpeer_device_id: row.peer_device_id ?? null,\n\t\top_id: row.op_id,\n\t\tentity_type: row.entity_type,\n\t\tentity_id: row.entity_id,\n\t\tscope_id: row.scope_id ?? null,\n\t\treason: row.reason as InboundScopeRejectionReason,\n\t\tcreated_at: row.created_at,\n\t}));\n}\n\nfunction syncScopeRejectionsTableExists(db: Database): boolean {\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sync_scope_rejections' LIMIT 1`,\n\t\t)\n\t\t.get();\n\treturn Boolean(row);\n}\n\nconst LEGACY_IMPORT_KEY_OLD_RE = /^legacy:memory_item:(.+)$/;\n\n/**\n * Rewrite legacy import keys into globally unique, device-scoped keys.\n *\n * Older databases may contain keys like `legacy:memory_item:<id>`, which can\n * collide across peers. This rewrites them to\n * `legacy:<device_id>:memory_item:<id>`.\n */\nexport function migrateLegacyImportKeys(db: Database, limit = 2000): number {\n\tconst d = drizzle(db, { schema });\n\tconst deviceRow = d\n\t\t.select({ device_id: schema.syncDevice.device_id })\n\t\t.from(schema.syncDevice)\n\t\t.limit(1)\n\t\t.get();\n\tconst localDeviceId = String(deviceRow?.device_id ?? \"\").trim();\n\tif (!localDeviceId) return 0;\n\n\tconst rows = d\n\t\t.select({\n\t\t\tid: schema.memoryItems.id,\n\t\t\timport_key: schema.memoryItems.import_key,\n\t\t\tmetadata_json: schema.memoryItems.metadata_json,\n\t\t})\n\t\t.from(schema.memoryItems)\n\t\t.where(\n\t\t\tor(\n\t\t\t\tisNull(schema.memoryItems.import_key),\n\t\t\t\tsql`TRIM(${schema.memoryItems.import_key}) = ''`,\n\t\t\t\tlike(schema.memoryItems.import_key, \"legacy:memory_item:%\"),\n\t\t\t),\n\t\t)\n\t\t.orderBy(schema.memoryItems.id)\n\t\t.limit(limit)\n\t\t.all();\n\n\tif (rows.length === 0) return 0;\n\n\tlet updated = 0;\n\tfor (const row of rows) {\n\t\tconst memoryId = Number(row.id);\n\t\tconst current = String(row.import_key ?? \"\").trim();\n\t\tconst metadata = fromJson(row.metadata_json);\n\t\tconst clockDeviceId =\n\t\t\ttypeof metadata.clock_device_id === \"string\" ? metadata.clock_device_id.trim() : \"\";\n\n\t\tlet canonical = \"\";\n\t\tif (!current) {\n\t\t\tcanonical = `legacy:${localDeviceId}:memory_item:${memoryId}`;\n\t\t} else {\n\t\t\tconst match = current.match(LEGACY_IMPORT_KEY_OLD_RE);\n\t\t\tif (!match) continue;\n\t\t\tconst suffix = match[1] ?? \"\";\n\t\t\tconst origin = clockDeviceId && clockDeviceId !== \"local\" ? clockDeviceId : localDeviceId;\n\t\t\tcanonical = origin ? `legacy:${origin}:memory_item:${suffix}` : \"\";\n\t\t}\n\n\t\tif (!canonical || canonical === current) continue;\n\n\t\tconst existing = d\n\t\t\t.select({ id: schema.memoryItems.id })\n\t\t\t.from(schema.memoryItems)\n\t\t\t.where(eq(schema.memoryItems.import_key, canonical))\n\t\t\t.limit(1)\n\t\t\t.get();\n\t\tif (existing && Number(existing.id) !== memoryId) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tassignMemoryImportKey(db, memoryId, canonical);\n\t\tupdated++;\n\t}\n\n\treturn updated;\n}\n\nfunction assignMemoryImportKey(db: Database, memoryId: number, importKey: string): void {\n\tdb.transaction(() => {\n\t\tsnapshotSessionExportKeysForMemoryIds(db, [memoryId]);\n\t\tdb.prepare(\"UPDATE memory_items SET import_key = ? WHERE id = ?\").run(importKey, memoryId);\n\t}).immediate();\n}\n\n/**\n * Generate replication ops for rows that predate replication.\n *\n * Prioritizes delete/tombstone ops first, then active upserts, and only\n * generates ops when a matching op for the same entity/rev/op_type is missing.\n */\nexport function backfillReplicationOps(db: Database, limit = 200): number {\n\tif (limit <= 0) return 0;\n\n\tmigrateLegacyImportKeys(db, 2000);\n\n\tconst d = drizzle(db, { schema });\n\tconst deviceRow = d\n\t\t.select({ device_id: schema.syncDevice.device_id })\n\t\t.from(schema.syncDevice)\n\t\t.limit(1)\n\t\t.get();\n\tconst localDeviceId = String(deviceRow?.device_id ?? \"\").trim();\n\n\tconst deletedRows = d\n\t\t.select()\n\t\t.from(schema.memoryItems)\n\t\t.where(\n\t\t\tand(\n\t\t\t\tor(isNotNull(schema.memoryItems.deleted_at), eq(schema.memoryItems.active, 0)),\n\t\t\t\tsql`NOT EXISTS (\n\t\t\t\t\tSELECT 1\n\t\t\t\t\tFROM replication_ops ro\n\t\t\t\t\tWHERE ro.entity_type = 'memory_item'\n\t\t\t\t\t AND ro.entity_id = ${schema.memoryItems.import_key}\n\t\t\t\t\t AND ro.op_type = 'delete'\n\t\t\t\t\t AND ro.clock_rev = COALESCE(${schema.memoryItems.rev}, 0)\n\t\t\t\t)`,\n\t\t\t),\n\t\t)\n\t\t.orderBy(schema.memoryItems.updated_at)\n\t\t.limit(limit)\n\t\t.all();\n\n\tconst remaining = Math.max(0, limit - deletedRows.length);\n\tlet rows = deletedRows;\n\tif (remaining > 0) {\n\t\tconst upsertRows = d\n\t\t\t.select()\n\t\t\t.from(schema.memoryItems)\n\t\t\t.where(\n\t\t\t\tand(\n\t\t\t\t\tisNull(schema.memoryItems.deleted_at),\n\t\t\t\t\teq(schema.memoryItems.active, 1),\n\t\t\t\t\tsql`NOT EXISTS (\n\t\t\t\t\t\tSELECT 1\n\t\t\t\t\t\tFROM replication_ops ro\n\t\t\t\t\t\tWHERE ro.entity_type = 'memory_item'\n\t\t\t\t\t\t AND ro.entity_id = ${schema.memoryItems.import_key}\n\t\t\t\t\t\t AND ro.op_type = 'upsert'\n\t\t\t\t\t\t AND ro.clock_rev = COALESCE(${schema.memoryItems.rev}, 0)\n\t\t\t\t\t)`,\n\t\t\t\t),\n\t\t\t)\n\t\t\t.orderBy(schema.memoryItems.updated_at)\n\t\t\t.limit(remaining)\n\t\t\t.all();\n\t\trows = [...rows, ...upsertRows];\n\t}\n\n\tif (rows.length === 0) return 0;\n\n\tconst now = new Date().toISOString();\n\tlet inserted = 0;\n\n\tfor (const row of rows) {\n\t\tconst rowId = Number(row.id ?? 0);\n\t\tif (!rowId) continue;\n\n\t\tconst metadata =\n\t\t\ttypeof row.metadata_json === \"string\"\n\t\t\t\t? fromJson(row.metadata_json)\n\t\t\t\t: fromJsonNullableLike(row.metadata_json);\n\t\tconst metadataClockDeviceId =\n\t\t\ttypeof metadata.clock_device_id === \"string\" ? metadata.clock_device_id.trim() : \"\";\n\t\tconst originDeviceId =\n\t\t\tmetadataClockDeviceId && metadataClockDeviceId !== \"local\"\n\t\t\t\t? metadataClockDeviceId\n\t\t\t\t: localDeviceId;\n\n\t\tlet importKey = String(row.import_key ?? \"\").trim();\n\t\tif (!importKey) {\n\t\t\tif (!originDeviceId) continue;\n\t\t\timportKey = `legacy:${originDeviceId}:memory_item:${rowId}`;\n\t\t\tassignMemoryImportKey(db, rowId, importKey);\n\t\t}\n\n\t\tconst rev = Number(row.rev ?? 0);\n\t\tconst active = Number(row.active ?? 1);\n\t\tconst deletedAt = String(row.deleted_at ?? \"\").trim();\n\t\tconst opType: \"upsert\" | \"delete\" = deletedAt || active === 0 ? \"delete\" : \"upsert\";\n\t\tconst opId = `backfill:memory_item:${importKey}:${rev}:${opType}`;\n\n\t\tconst exists = d\n\t\t\t.select({ one: sql<number>`1` })\n\t\t\t.from(schema.replicationOps)\n\t\t\t.where(eq(schema.replicationOps.op_id, opId))\n\t\t\t.limit(1)\n\t\t\t.get();\n\t\tif (exists) continue;\n\n\t\tconst clockDeviceId = originDeviceId;\n\t\tif (!clockDeviceId) continue;\n\t\tconst scopeId = ensureMemoryScopeId(db, rowId);\n\t\tconst payload = buildPayloadFromMemoryRow({ ...row, scope_id: scopeId });\n\n\t\td.insert(schema.replicationOps)\n\t\t\t.values({\n\t\t\t\top_id: opId,\n\t\t\t\tentity_type: \"memory_item\",\n\t\t\t\tentity_id: importKey,\n\t\t\t\top_type: opType,\n\t\t\t\tpayload_json: toJson(payload),\n\t\t\t\tclock_rev: rev,\n\t\t\t\tclock_updated_at: String(row.updated_at ?? now),\n\t\t\t\tclock_device_id: clockDeviceId,\n\t\t\t\tdevice_id: clockDeviceId,\n\t\t\t\tcreated_at: now,\n\t\t\t\tscope_id: scopeId,\n\t\t\t})\n\t\t\t.onConflictDoNothing()\n\t\t\t.run();\n\n\t\tinserted++;\n\t}\n\n\treturn inserted;\n}\n\nfunction fromJsonNullableLike(value: unknown): Record<string, unknown> {\n\tif (typeof value === \"string\") return fromJson(value);\n\tif (value && typeof value === \"object\") return value as Record<string, unknown>;\n\treturn {};\n}\n\nfunction buildPayloadFromMemoryRow(row: MemoryItemRow): MemoryPayload {\n\tconst parseSqliteJson = (val: unknown): unknown => {\n\t\tif (typeof val !== \"string\") return val ?? null;\n\t\ttry {\n\t\t\treturn JSON.parse(val);\n\t\t} catch {\n\t\t\treturn val;\n\t\t}\n\t};\n\tconst metadataParsed = parseSqliteJson(row.metadata_json);\n\tconst metadataJson =\n\t\tmetadataParsed && typeof metadataParsed === \"object\" && !Array.isArray(metadataParsed)\n\t\t\t? (metadataParsed as Record<string, unknown>)\n\t\t\t: {};\n\n\treturn {\n\t\tsession_id: row.session_id ?? null,\n\t\tkind: row.kind ?? null,\n\t\ttitle: row.title ?? null,\n\t\tsubtitle: row.subtitle ?? null,\n\t\tbody_text: row.body_text ?? null,\n\t\tconfidence: row.confidence ?? null,\n\t\ttags_text: row.tags_text ?? null,\n\t\tactive: row.active ?? null,\n\t\tcreated_at: row.created_at ?? null,\n\t\tupdated_at: row.updated_at ?? null,\n\t\tmetadata_json: metadataJson,\n\t\tactor_id: row.actor_id ?? null,\n\t\tactor_display_name: row.actor_display_name ?? null,\n\t\tvisibility: row.visibility ?? null,\n\t\tworkspace_id: row.workspace_id ?? null,\n\t\tworkspace_kind: row.workspace_kind ?? null,\n\t\torigin_device_id: row.origin_device_id ?? null,\n\t\torigin_source: row.origin_source ?? null,\n\t\ttrust_state: row.trust_state ?? null,\n\t\tnarrative: row.narrative ?? null,\n\t\tfacts: parseSqliteJson(row.facts),\n\t\tconcepts: parseSqliteJson(row.concepts),\n\t\tfiles_read: parseSqliteJson(row.files_read),\n\t\tfiles_modified: parseSqliteJson(row.files_modified),\n\t\tuser_prompt_id: row.user_prompt_id ?? null,\n\t\tprompt_number: row.prompt_number ?? null,\n\t\tdeleted_at: row.deleted_at ?? null,\n\t\tscope_id: row.scope_id ?? null,\n\t\thas_deleted_at: row.deleted_at != null,\n\t\trev: row.rev ?? 0,\n\t\timport_key: row.import_key ?? null,\n\t\t// Denormalized project from memory_items so the outbound payload\n\t\t// carries it without a session join. Callers may still override with\n\t\t// sessions.project for legacy rows whose memory_items.project is null.\n\t\tproject: row.project ?? null,\n\t};\n}\n\n/**\n * Apply inbound replication ops from a remote peer.\n *\n * Runs all ops in a single transaction. For each op:\n * - Skips if device_id matches localDeviceId (don't re-apply own ops)\n * - Skips if op_id already exists (idempotent)\n * - For upsert: finds existing memory by import_key; if existing has a newer\n * clock, counts as conflict and skips; otherwise INSERT or UPDATE\n * - For delete: soft-deletes (active=0, deleted_at) by import_key\n * - Records the applied op in replication_ops\n */\nfunction rejectUnretiredScopeFailures(\n\tdb: Database,\n\tops: ReplicationOp[],\n\tlocalDeviceId: string,\n\toptions: InboundScopeValidationOptions,\n): ApplyResult | null {\n\tconst eligible = ops.filter((op) => !retirementBlocksMemoryOp(db, op));\n\tconst rejected = rejectInboundScopeFailures(db, eligible, localDeviceId, options);\n\tif (rejected) rejected.skipped += ops.length - eligible.length;\n\treturn rejected;\n}\n\nfunction skipOwnRetiredOrAppliedOp(\n\tdb: Database,\n\td: ReturnType<typeof drizzle>,\n\top: ReplicationOp,\n\tlocalDeviceId: string,\n): boolean {\n\tif (skipOwnOrRetiredMemoryOp(db, op, localDeviceId)) return true;\n\treturn (\n\t\td\n\t\t\t.select({ one: sql<number>`1` })\n\t\t\t.from(schema.replicationOps)\n\t\t\t.where(eq(schema.replicationOps.op_id, op.op_id))\n\t\t\t.get() !== undefined\n\t);\n}\n\nfunction rollbackReplicationOp(\n\tdb: Database,\n\tresult: ApplyResult,\n\tvectorWork: Map<number, \"upsert\" | \"delete\">,\n): void {\n\tdb.exec(\"ROLLBACK TO codemem_replication_op\");\n\tresult.applied = 0;\n\tresult.skipped = 0;\n\tresult.conflicts = 0;\n\tvectorWork.clear();\n}\n\nfunction finishReplicationOp(\n\tdb: Database,\n\tresult: ApplyResult,\n\teffects: {\n\t\tbatchResult: ApplyResult;\n\t\topVectorWork: Map<number, \"upsert\" | \"delete\">;\n\t\tupsertMemoryIds: Set<number>;\n\t\tdeleteMemoryIds: Set<number>;\n\t\tactivityPeer?: string;\n\t},\n\topId: string,\n): void {\n\trecordAppliedReceipt(db, effects.activityPeer, result.applied, opId);\n\tdb.exec(\"RELEASE codemem_replication_op\");\n\teffects.batchResult.applied += result.applied;\n\teffects.batchResult.skipped += result.skipped;\n\teffects.batchResult.conflicts += result.conflicts;\n\teffects.batchResult.errors.push(...result.errors);\n\tfor (const [memoryId, operation] of effects.opVectorWork) {\n\t\tif (operation === \"upsert\") {\n\t\t\teffects.deleteMemoryIds.delete(memoryId);\n\t\t\teffects.upsertMemoryIds.add(memoryId);\n\t\t} else {\n\t\t\teffects.upsertMemoryIds.delete(memoryId);\n\t\t\teffects.deleteMemoryIds.add(memoryId);\n\t\t}\n\t}\n}\n\nfunction recordAppliedReceipt(\n\tdb: Database,\n\tpeer: string | undefined,\n\tapplied: number,\n\topId: string,\n): void {\n\tif (peer && applied > 0) recordSyncTransferReceipts(db, peer, \"receive\", [opId]);\n}\n\nfunction applyAccessCleanupForLocalDevice(\n\tdb: Database,\n\td: ReturnType<typeof drizzle>,\n\top: ReplicationOp,\n\tcontext: {\n\t\tlocalDeviceId: string;\n\t\tqueueVectorDelete: (memoryId: number) => void;\n\t},\n): boolean {\n\tconst cleanup = parseAccessCleanupPayload(op);\n\tif (!cleanup.cleanup_scope_id) return false;\n\tconst existing = d\n\t\t.select({\n\t\t\tid: schema.memoryItems.id,\n\t\t\torigin_device_id: schema.memoryItems.origin_device_id,\n\t\t\tscope_id: schema.memoryItems.scope_id,\n\t\t})\n\t\t.from(schema.memoryItems)\n\t\t.where(eq(schema.memoryItems.import_key, op.entity_id))\n\t\t.limit(1)\n\t\t.get();\n\tif (!existing) return true;\n\tif (hasRecordedLocalCreation(db, op.entity_id)) return false;\n\tconst sourceDeviceId = cleanText(op.clock_device_id) ?? cleanText(op.device_id);\n\tconst originDeviceId = cleanText(existing.origin_device_id);\n\tif (!sourceDeviceId || !originDeviceId || originDeviceId !== sourceDeviceId) return false;\n\t// Local-looking labels preserve ambiguous data, never prove authorship.\n\tif (originDeviceId === context.localDeviceId || originDeviceId === \"local\") return false;\n\tif (cleanText(existing.scope_id) !== cleanup.cleanup_scope_id) return false;\n\tclearRefsBeforeMemoryDeletion(db, Number(existing.id));\n\td.delete(schema.memoryItems).where(eq(schema.memoryItems.id, existing.id)).run();\n\tcontext.queueVectorDelete(Number(existing.id));\n\treturn true;\n}\n\nexport function applyReplicationOps(\n\tdb: Database,\n\tops: ReplicationOp[],\n\tlocalDeviceId: string,\n\tscanner?: SecretScanner,\n\toptions: ApplyReplicationOpsOptions = {},\n): ApplyResult {\n\tconst peer = options.activityPeerDeviceId;\n\tif (!peer) return applyReplicationOpsInternal(db, ops, localDeviceId, scanner, options);\n\tensureSyncTransferActivitySchema(db);\n\ttry {\n\t\treturn db.transaction(() => {\n\t\t\tconst result = applyReplicationOpsInternal(db, ops, localDeviceId, scanner, {\n\t\t\t\t...options,\n\t\t\t\tactivityPeerDeviceId: peer,\n\t\t\t});\n\t\t\tlet errorCode: \"scope_rejected\" | \"apply_failed\" | undefined;\n\t\t\tif (result.rejected > 0) errorCode = \"scope_rejected\";\n\t\t\telse if (result.errors.length > 0) errorCode = \"apply_failed\";\n\t\t\trecordSyncTransferObservation(db, peer, \"receive\", {\n\t\t\t\t...options.activityOptions,\n\t\t\t\terrorCode,\n\t\t\t\tsource: options.activitySource,\n\t\t\t});\n\t\t\treturn result;\n\t\t})();\n\t} catch (error) {\n\t\trecordSyncTransferObservation(db, peer, \"receive\", {\n\t\t\terrorCode: \"apply_failed\",\n\t\t\tsource: options.activitySource,\n\t\t});\n\t\tthrow error;\n\t}\n}\n\nfunction applyReplicationOpsInternal(\n\tdb: Database,\n\tops: ReplicationOp[],\n\tlocalDeviceId: string,\n\tscanner: SecretScanner | undefined,\n\toptions: ApplyReplicationOpsOptions,\n): ApplyResult {\n\tconst d = drizzle(db, { schema });\n\t// Peer-shipped content goes through the same redaction policy as\n\t// locally-authored writes. Callers that maintain their own scanner\n\t// (typically a MemoryStore instance) should pass it so workspace-level\n\t// rule overrides apply uniformly. Otherwise fall back to defaults.\n\tconst activeScanner = scanner ?? new SecretScanner();\n\tconst result: ApplyResult = emptyApplyResult();\n\tconst rejected = rejectedInboundBatch(db, ops, localDeviceId, options);\n\tif (rejected) return rejected;\n\tconst upsertMemoryIds = new Set<number>();\n\tconst deleteMemoryIds = new Set<number>();\n\tconst opVectorWork = new Map<number, \"upsert\" | \"delete\">();\n\tconst queueVectorUpsert = (memoryId: number): void => {\n\t\tif (!Number.isInteger(memoryId) || memoryId <= 0) return;\n\t\topVectorWork.set(memoryId, \"upsert\");\n\t};\n\tconst queueVectorDelete = (memoryId: number): void => {\n\t\tif (!Number.isInteger(memoryId) || memoryId <= 0) return;\n\t\topVectorWork.set(memoryId, \"delete\");\n\t};\n\tconst applyAccessCleanupOp = (op: ReplicationOp): boolean =>\n\t\tapplyAccessCleanupForLocalDevice(db, d, op, { localDeviceId, queueVectorDelete });\n\n\tconst effects = {\n\t\tbatchResult: result,\n\t\topVectorWork,\n\t\tupsertMemoryIds,\n\t\tdeleteMemoryIds,\n\t\tactivityPeer: options.activityPeerDeviceId,\n\t};\n\tconst applyAll = db.transaction(() => {\n\t\tfor (const op of ops) {\n\t\t\tconst result = emptyApplyResult();\n\t\t\topVectorWork.clear();\n\t\t\t// Per-op failures must roll back content, provenance, refs, and op acknowledgement together.\n\t\t\tdb.exec(\"SAVEPOINT codemem_replication_op\");\n\t\t\ttry {\n\t\t\t\t// Skip own, retired, and already-applied ops.\n\t\t\t\tif (skipOwnRetiredOrAppliedOp(db, d, op, localDeviceId)) {\n\t\t\t\t\tresult.skipped++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst reassignment =\n\t\t\t\t\top.op_type === REASSIGN_SCOPE_OP_TYPE ? parseReassignScopePayload(op) : null;\n\t\t\t\tif (reassignment?.side === \"old\") {\n\t\t\t\t\tconst current = d\n\t\t\t\t\t\t.select({\n\t\t\t\t\t\t\tid: schema.memoryItems.id,\n\t\t\t\t\t\t\torigin_device_id: schema.memoryItems.origin_device_id,\n\t\t\t\t\t\t\trev: schema.memoryItems.rev,\n\t\t\t\t\t\t\tupdated_at: schema.memoryItems.updated_at,\n\t\t\t\t\t\t\tmetadata_json: schema.memoryItems.metadata_json,\n\t\t\t\t\t\t\tscope_id: schema.memoryItems.scope_id,\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.from(schema.memoryItems)\n\t\t\t\t\t\t.where(eq(schema.memoryItems.import_key, op.entity_id))\n\t\t\t\t\t\t.get();\n\t\t\t\t\tif (\n\t\t\t\t\t\t!current ||\n\t\t\t\t\t\t(cleanText(current.scope_id) ?? DEFAULT_SYNC_SCOPE_ID) !== reassignment.old_scope_id\n\t\t\t\t\t) {\n\t\t\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\t\t\tresult.skipped++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (reassignment.old_scope_id === DEFAULT_SYNC_SCOPE_ID) {\n\t\t\t\t\t\tconst senderDeviceId = cleanText(op.clock_device_id);\n\t\t\t\t\t\tconst originDeviceId = cleanText(current.origin_device_id);\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!senderDeviceId ||\n\t\t\t\t\t\t\tcleanText(op.device_id) !== senderDeviceId ||\n\t\t\t\t\t\t\t!originDeviceId ||\n\t\t\t\t\t\t\toriginDeviceId !== senderDeviceId ||\n\t\t\t\t\t\t\toriginDeviceId === localDeviceId\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthrow new Error(\"reassign_origin_mismatch\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst currentClock = clockTuple(\n\t\t\t\t\t\tcurrent.rev ?? 0,\n\t\t\t\t\t\tcurrent.updated_at ?? \"\",\n\t\t\t\t\t\tclockDeviceIdFromMetadataJson(current.metadata_json),\n\t\t\t\t\t);\n\t\t\t\t\tconst incomingClock = clockTuple(op.clock_rev, op.clock_updated_at, op.clock_device_id);\n\t\t\t\t\tif (!isNewerClock(incomingClock, currentClock)) {\n\t\t\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\t\t\tresult.conflicts++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst metadata = foreignRevisionMetadata(db, op, current.metadata_json);\n\t\t\t\t\tmetadata.last_scope_reassignment = reassignment;\n\t\t\t\t\td.update(schema.memoryItems)\n\t\t\t\t\t\t.set({\n\t\t\t\t\t\t\tactive: 0,\n\t\t\t\t\t\t\tdeleted_at: op.clock_updated_at,\n\t\t\t\t\t\t\trev: op.clock_rev,\n\t\t\t\t\t\t\tupdated_at: op.clock_updated_at,\n\t\t\t\t\t\t\tmetadata_json: toJson(metadata),\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.where(eq(schema.memoryItems.id, current.id))\n\t\t\t\t\t\t.run();\n\t\t\t\t\tqueueVectorDelete(Number(current.id));\n\t\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\t\tresult.applied++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (op.op_type === ACCESS_CLEANUP_OP_TYPE) {\n\t\t\t\t\tconst cleaned = applyAccessCleanupOp(op);\n\t\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\t\tif (cleaned) result.applied++;\n\t\t\t\t\telse result.skipped++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (op.op_type === \"upsert\" || reassignment?.side === \"new\") {\n\t\t\t\t\tconst importKey = op.entity_id;\n\t\t\t\t\tconst opScopeId =\n\t\t\t\t\t\ttypeof op.scope_id === \"string\" && op.scope_id.trim().length > 0\n\t\t\t\t\t\t\t? op.scope_id.trim()\n\t\t\t\t\t\t\t: null;\n\t\t\t\t\tconst memRow = d\n\t\t\t\t\t\t.select({\n\t\t\t\t\t\t\tid: schema.memoryItems.id,\n\t\t\t\t\t\t\trev: schema.memoryItems.rev,\n\t\t\t\t\t\t\tupdated_at: schema.memoryItems.updated_at,\n\t\t\t\t\t\t\ttitle: schema.memoryItems.title,\n\t\t\t\t\t\t\tbody_text: schema.memoryItems.body_text,\n\t\t\t\t\t\t\tactive: schema.memoryItems.active,\n\t\t\t\t\t\t\tdeleted_at: schema.memoryItems.deleted_at,\n\t\t\t\t\t\t\tmetadata_json: schema.memoryItems.metadata_json,\n\t\t\t\t\t\t\tscope_id: schema.memoryItems.scope_id,\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.from(schema.memoryItems)\n\t\t\t\t\t\t.where(eq(schema.memoryItems.import_key, importKey))\n\t\t\t\t\t\t.get();\n\n\t\t\t\t\tif (memRow) {\n\t\t\t\t\t\tconst existingClockDeviceId = clockDeviceIdFromMetadataJson(memRow.metadata_json);\n\t\t\t\t\t\tconst existingClock = clockTuple(\n\t\t\t\t\t\t\tmemRow.rev ?? 0,\n\t\t\t\t\t\t\tmemRow.updated_at ?? \"\",\n\t\t\t\t\t\t\texistingClockDeviceId,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst opClock = clockTuple(op.clock_rev, op.clock_updated_at, op.clock_device_id);\n\n\t\t\t\t\t\tconst sameReassignmentClock =\n\t\t\t\t\t\t\treassignment?.side === \"new\" &&\n\t\t\t\t\t\t\topClock[0] === existingClock[0] &&\n\t\t\t\t\t\t\topClock[1] === existingClock[1] &&\n\t\t\t\t\t\t\topClock[2] === existingClock[2] &&\n\t\t\t\t\t\t\t(cleanText(memRow.scope_id) ?? DEFAULT_SYNC_SCOPE_ID) === reassignment.old_scope_id;\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\treassignment &&\n\t\t\t\t\t\t\t![reassignment.old_scope_id, reassignment.new_scope_id].includes(\n\t\t\t\t\t\t\t\tcleanText(memRow.scope_id) ?? DEFAULT_SYNC_SCOPE_ID,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthrow new Error(\"reassign_existing_scope_mismatch\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!isNewerClock(opClock, existingClock) && !sameReassignmentClock) {\n\t\t\t\t\t\t\tresult.conflicts++;\n\t\t\t\t\t\t\t// Still record the op so we don't re-process it\n\t\t\t\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Update existing row from payload — skip if malformed\n\t\t\t\t\t\tconst payload = parseMemoryPayload(op, result.errors);\n\t\t\t\t\t\tif (!payload) {\n\t\t\t\t\t\t\t// A malformed payload can never be applied. Record the op so\n\t\t\t\t\t\t\t// it is acknowledged exactly once (not re-parsed and re-errored\n\t\t\t\t\t\t\t// every pass) and the inbound cursor can eventually advance\n\t\t\t\t\t\t\t// past it instead of stalling forever.\n\t\t\t\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\t\t\t\tresult.skipped++;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tredactMemoryFields(payload, activeScanner);\n\t\t\t\t\t\tconst metaObj = foreignRevisionMetadata(db, op, payload.metadata_json);\n\t\t\t\t\t\tconst nextTitle = resolveReplicatedTextUpdate(payload.title, memRow.title);\n\t\t\t\t\t\tconst nextBodyText = resolveReplicatedTextUpdate(payload.body_text, memRow.body_text);\n\t\t\t\t\t\tconst contentChanged =\n\t\t\t\t\t\t\tnextTitle !== (memRow.title ?? \"\") || nextBodyText !== (memRow.body_text ?? \"\");\n\t\t\t\t\t\tconst wasInactive = Number(memRow.active ?? 1) === 0 || memRow.deleted_at != null;\n\t\t\t\t\t\tconst nextActive =\n\t\t\t\t\t\t\tpayload.active != null ? Number(payload.active) : Number(memRow.active ?? 1);\n\t\t\t\t\t\tconst nextDeletedAt = payload.has_deleted_at\n\t\t\t\t\t\t\t? payload.deleted_at\n\t\t\t\t\t\t\t: (memRow.deleted_at ?? null);\n\t\t\t\t\t\tconst becomesActive = nextActive !== 0 && nextDeletedAt == null;\n\t\t\t\t\t\t// Keep `active` consistent with the tombstone: when the row stays\n\t\t\t\t\t\t// (or becomes) tombstoned, force active=0 so a field-omitting\n\t\t\t\t\t\t// upsert that carries active=1 cannot resurrect a deleted memory\n\t\t\t\t\t\t// (read paths filter on active=1).\n\t\t\t\t\t\tconst writtenActive = nextDeletedAt != null ? 0 : nextActive;\n\t\t\t\t\t\t// Base the vector decision on the FINAL persisted state, not the\n\t\t\t\t\t\t// raw payload: a row that stays (or becomes) tombstoned — active=0\n\t\t\t\t\t\t// or deleted_at set — must have its embeddings removed, not\n\t\t\t\t\t\t// re-upserted (the vector queue lets an upsert cancel a pending\n\t\t\t\t\t\t// delete, which would leave a deleted memory searchable).\n\t\t\t\t\t\tconst shouldDeleteVectors = nextDeletedAt != null || writtenActive === 0;\n\t\t\t\t\t\tconst shouldQueueVectorUpsert =\n\t\t\t\t\t\t\t!shouldDeleteVectors && (contentChanged || (wasInactive && becomesActive));\n\n\t\t\t\t\t\td.update(schema.memoryItems)\n\t\t\t\t\t\t\t.set({\n\t\t\t\t\t\t\t\tkind: sql`COALESCE(${payload.kind}, ${schema.memoryItems.kind})`,\n\t\t\t\t\t\t\t\ttitle: sql`COALESCE(${payload.title}, ${schema.memoryItems.title})`,\n\t\t\t\t\t\t\t\tsubtitle: payload.subtitle,\n\t\t\t\t\t\t\t\tbody_text: sql`COALESCE(${payload.body_text}, ${schema.memoryItems.body_text})`,\n\t\t\t\t\t\t\t\tconfidence: sql`COALESCE(${payload.confidence != null ? Number(payload.confidence) : null}, ${schema.memoryItems.confidence})`,\n\t\t\t\t\t\t\t\ttags_text: sql`COALESCE(NULLIF(TRIM(${payload.tags_text}), ''), ${schema.memoryItems.tags_text})`,\n\t\t\t\t\t\t\t\tactive: writtenActive,\n\t\t\t\t\t\t\t\tupdated_at: op.clock_updated_at,\n\t\t\t\t\t\t\t\tmetadata_json: toJson(metaObj),\n\t\t\t\t\t\t\t\trev: op.clock_rev,\n\t\t\t\t\t\t\t\t// Honor the wire intent flag: only clear/set the tombstone\n\t\t\t\t\t\t\t\t// when the payload actually carried `deleted_at`; otherwise\n\t\t\t\t\t\t\t\t// preserve the existing value (nextDeletedAt). Guards against\n\t\t\t\t\t\t\t\t// a field-omitting upsert resurrecting a tombstoned row.\n\t\t\t\t\t\t\t\tdeleted_at: nextDeletedAt,\n\t\t\t\t\t\t\t\tactor_id: sql`COALESCE(${payload.actor_id}, ${schema.memoryItems.actor_id})`,\n\t\t\t\t\t\t\t\tactor_display_name: sql`COALESCE(${payload.actor_display_name}, ${schema.memoryItems.actor_display_name})`,\n\t\t\t\t\t\t\t\tvisibility: sql`COALESCE(${payload.visibility}, ${schema.memoryItems.visibility})`,\n\t\t\t\t\t\t\t\tworkspace_id: sql`COALESCE(${payload.workspace_id}, ${schema.memoryItems.workspace_id})`,\n\t\t\t\t\t\t\t\tworkspace_kind: sql`COALESCE(${payload.workspace_kind}, ${schema.memoryItems.workspace_kind})`,\n\t\t\t\t\t\t\t\torigin_device_id: sql`COALESCE(${payload.origin_device_id}, ${schema.memoryItems.origin_device_id})`,\n\t\t\t\t\t\t\t\torigin_source: sql`COALESCE(${payload.origin_source}, ${schema.memoryItems.origin_source})`,\n\t\t\t\t\t\t\t\ttrust_state: sql`COALESCE(${payload.trust_state}, ${schema.memoryItems.trust_state})`,\n\t\t\t\t\t\t\t\tnarrative: payload.narrative,\n\t\t\t\t\t\t\t\tfacts: toJsonNullable(payload.facts),\n\t\t\t\t\t\t\t\tconcepts: toJsonNullable(payload.concepts),\n\t\t\t\t\t\t\t\tfiles_read: toJsonNullable(payload.files_read),\n\t\t\t\t\t\t\t\tfiles_modified: toJsonNullable(payload.files_modified),\n\t\t\t\t\t\t\t\tuser_prompt_id: payload.user_prompt_id,\n\t\t\t\t\t\t\t\tprompt_number: payload.prompt_number,\n\t\t\t\t\t\t\t\tscope_id: sql`COALESCE(${opScopeId}, ${schema.memoryItems.scope_id})`,\n\t\t\t\t\t\t\t\t// Backfill project on existing rows when the inbound\n\t\t\t\t\t\t\t\t// payload carries it; preserve the existing value when\n\t\t\t\t\t\t\t\t// the sender (older code) omitted the field.\n\t\t\t\t\t\t\t\tproject: sql`COALESCE(${typeof payload.project === \"string\" && payload.project.trim() ? payload.project.trim() : null}, ${schema.memoryItems.project})`,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.where(eq(schema.memoryItems.import_key, importKey))\n\t\t\t\t\t\t\t.run();\n\t\t\t\t\t\t// Re-populate junction tables with updated file/concept refs\n\t\t\t\t\t\tclearMemoryRefs(db, Number(memRow.id));\n\t\t\t\t\t\tpopulateMemoryRefs(\n\t\t\t\t\t\t\tdb,\n\t\t\t\t\t\t\tNumber(memRow.id),\n\t\t\t\t\t\t\tasStringArrayOrNull(payload.files_read),\n\t\t\t\t\t\t\tasStringArrayOrNull(payload.files_modified),\n\t\t\t\t\t\t\tasStringArrayOrNull(payload.concepts),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (shouldDeleteVectors) queueVectorDelete(Number(memRow.id));\n\t\t\t\t\t\telse if (shouldQueueVectorUpsert) queueVectorUpsert(Number(memRow.id));\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Insert new memory item — skip if malformed\n\t\t\t\t\t\tconst payload = parseMemoryPayload(op, result.errors);\n\t\t\t\t\t\tif (!payload) {\n\t\t\t\t\t\t\t// See the update branch: record malformed ops so they are\n\t\t\t\t\t\t\t// acknowledged once and never block inbound cursor progress.\n\t\t\t\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\t\t\t\tresult.skipped++;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tredactMemoryFields(payload, activeScanner);\n\t\t\t\t\t\tconst replicatedProject =\n\t\t\t\t\t\t\ttypeof payload.project === \"string\" && payload.project.trim()\n\t\t\t\t\t\t\t\t? payload.project.trim()\n\t\t\t\t\t\t\t\t: null;\n\t\t\t\t\t\tconst sessionId = ensureSessionForReplication(\n\t\t\t\t\t\t\td,\n\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\top.clock_updated_at,\n\t\t\t\t\t\t\treplicatedProject,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst metaObj = foreignRevisionMetadata(db, op, payload.metadata_json);\n\t\t\t\t\t\tconst insertedRows = d\n\t\t\t\t\t\t\t.insert(schema.memoryItems)\n\t\t\t\t\t\t\t.values({\n\t\t\t\t\t\t\t\tsession_id: sessionId,\n\t\t\t\t\t\t\t\tkind: payload.kind ?? \"discovery\",\n\t\t\t\t\t\t\t\ttitle: payload.title ?? \"\",\n\t\t\t\t\t\t\t\tsubtitle: payload.subtitle,\n\t\t\t\t\t\t\t\tbody_text: payload.body_text ?? \"\",\n\t\t\t\t\t\t\t\tconfidence: payload.confidence != null ? Number(payload.confidence) : 0.5,\n\t\t\t\t\t\t\t\ttags_text: resolveReplicatedTags(payload),\n\t\t\t\t\t\t\t\tactive: payload.active != null ? Number(payload.active) : 1,\n\t\t\t\t\t\t\t\tcreated_at: payload.created_at ?? op.clock_updated_at,\n\t\t\t\t\t\t\t\tupdated_at: op.clock_updated_at,\n\t\t\t\t\t\t\t\tmetadata_json: toJson(metaObj),\n\t\t\t\t\t\t\t\timport_key: importKey,\n\t\t\t\t\t\t\t\tdeleted_at: payload.deleted_at,\n\t\t\t\t\t\t\t\trev: op.clock_rev,\n\t\t\t\t\t\t\t\tactor_id: payload.actor_id,\n\t\t\t\t\t\t\t\tactor_display_name: payload.actor_display_name,\n\t\t\t\t\t\t\t\tvisibility: payload.visibility,\n\t\t\t\t\t\t\t\tworkspace_id: payload.workspace_id,\n\t\t\t\t\t\t\t\tworkspace_kind: payload.workspace_kind,\n\t\t\t\t\t\t\t\torigin_device_id: payload.origin_device_id,\n\t\t\t\t\t\t\t\torigin_source: payload.origin_source,\n\t\t\t\t\t\t\t\ttrust_state: payload.trust_state,\n\t\t\t\t\t\t\t\tnarrative: payload.narrative,\n\t\t\t\t\t\t\t\tfacts: toJsonNullable(payload.facts),\n\t\t\t\t\t\t\t\tconcepts: toJsonNullable(payload.concepts),\n\t\t\t\t\t\t\t\tfiles_read: toJsonNullable(payload.files_read),\n\t\t\t\t\t\t\t\tfiles_modified: toJsonNullable(payload.files_modified),\n\t\t\t\t\t\t\t\tuser_prompt_id: payload.user_prompt_id,\n\t\t\t\t\t\t\t\tprompt_number: payload.prompt_number,\n\t\t\t\t\t\t\t\tscope_id: opScopeId,\n\t\t\t\t\t\t\t\t// Persist replicated project name so the Projects read\n\t\t\t\t\t\t\t\t// model can surface this memory under its originating\n\t\t\t\t\t\t\t\t// project identity without joining through sessions.\n\t\t\t\t\t\t\t\tproject: replicatedProject,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.returning({ id: schema.memoryItems.id })\n\t\t\t\t\t\t\t.all();\n\t\t\t\t\t\tconst insertedId = Number(insertedRows[0]?.id ?? 0);\n\t\t\t\t\t\t// Populate junction tables for the new memory\n\t\t\t\t\t\tpopulateMemoryRefs(\n\t\t\t\t\t\t\tdb,\n\t\t\t\t\t\t\tinsertedId,\n\t\t\t\t\t\t\tasStringArrayOrNull(payload.files_read),\n\t\t\t\t\t\t\tasStringArrayOrNull(payload.files_modified),\n\t\t\t\t\t\t\tasStringArrayOrNull(payload.concepts),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (payload.deleted_at != null || Number(payload.active ?? 1) === 0) {\n\t\t\t\t\t\t\tqueueVectorDelete(insertedId);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tqueueVectorUpsert(insertedId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (op.op_type === \"delete\") {\n\t\t\t\t\tconst importKey = op.entity_id;\n\t\t\t\t\tconst opScopeId =\n\t\t\t\t\t\ttypeof op.scope_id === \"string\" && op.scope_id.trim().length > 0\n\t\t\t\t\t\t\t? op.scope_id.trim()\n\t\t\t\t\t\t\t: null;\n\t\t\t\t\tconst existingForDelete = d\n\t\t\t\t\t\t.select({\n\t\t\t\t\t\t\tid: schema.memoryItems.id,\n\t\t\t\t\t\t\trev: schema.memoryItems.rev,\n\t\t\t\t\t\t\tupdated_at: schema.memoryItems.updated_at,\n\t\t\t\t\t\t\tmetadata_json: schema.memoryItems.metadata_json,\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.from(schema.memoryItems)\n\t\t\t\t\t\t.where(eq(schema.memoryItems.import_key, importKey))\n\t\t\t\t\t\t.limit(1)\n\t\t\t\t\t\t.get();\n\n\t\t\t\t\tif (existingForDelete) {\n\t\t\t\t\t\t// Clock-compare: only delete if the incoming op is newer\n\t\t\t\t\t\tconst existingClock = clockTuple(\n\t\t\t\t\t\t\t// Match the upsert path's `rev ?? 0` so Lamport tie-breaks are\n\t\t\t\t\t\t\t// symmetric when an existing row has a NULL rev.\n\t\t\t\t\t\t\texistingForDelete.rev ?? 0,\n\t\t\t\t\t\t\texistingForDelete.updated_at ?? \"\",\n\t\t\t\t\t\t\tclockDeviceIdFromMetadataJson(existingForDelete.metadata_json),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst incomingClock = clockTuple(op.clock_rev, op.clock_updated_at, op.clock_device_id);\n\t\t\t\t\t\tif (!isNewerClock(incomingClock, existingClock)) {\n\t\t\t\t\t\t\tresult.conflicts++;\n\t\t\t\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst now = new Date().toISOString();\n\t\t\t\t\t\tconst deleteMetadata = foreignRevisionMetadata(db, op, existingForDelete.metadata_json);\n\t\t\t\t\t\td.update(schema.memoryItems)\n\t\t\t\t\t\t\t.set({\n\t\t\t\t\t\t\t\tactive: 0,\n\t\t\t\t\t\t\t\tdeleted_at: sql`COALESCE(${schema.memoryItems.deleted_at}, ${now})`,\n\t\t\t\t\t\t\t\trev: op.clock_rev,\n\t\t\t\t\t\t\t\tupdated_at: op.clock_updated_at,\n\t\t\t\t\t\t\t\tmetadata_json: toJson(deleteMetadata),\n\t\t\t\t\t\t\t\tscope_id: sql`COALESCE(${opScopeId}, ${schema.memoryItems.scope_id})`,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.where(eq(schema.memoryItems.id, existingForDelete.id))\n\t\t\t\t\t\t\t.run();\n\t\t\t\t\t\tqueueVectorDelete(Number(existingForDelete.id));\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// import_key not found: record the delete as a tombstone for\n\t\t\t\t\t\t// future resolution, but it mutated nothing — count it as\n\t\t\t\t\t\t// skipped rather than applied.\n\t\t\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\t\t\tresult.skipped++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tresult.skipped++;\n\t\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Record the applied op\n\t\t\t\tinsertReplicationOpRow(d, op);\n\t\t\t\tresult.applied++;\n\t\t\t} catch (err) {\n\t\t\t\trollbackReplicationOp(db, result, opVectorWork);\n\t\t\t\tresult.errors.push(`op ${op.op_id}: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\t} finally {\n\t\t\t\tfinishReplicationOp(db, result, effects, op.op_id);\n\t\t\t}\n\t\t}\n\t});\n\n\treturn completeAppliedReplicationOps(applyAll, result, upsertMemoryIds, deleteMemoryIds);\n}\n\nfunction completeAppliedReplicationOps(\n\tapplyAll: () => void,\n\tresult: ApplyResult,\n\tupsertMemoryIds: Set<number>,\n\tdeleteMemoryIds: Set<number>,\n): ApplyResult {\n\tapplyAll();\n\tresult.vectorWork = {\n\t\tupsertMemoryIds: [...upsertMemoryIds],\n\t\tdeleteMemoryIds: [...deleteMemoryIds],\n\t};\n\treturn result;\n}\n\nfunction rejectedInboundBatch(\n\tdb: Database,\n\tops: ReplicationOp[],\n\tlocalDeviceId: string,\n\toptions: ApplyReplicationOpsOptions,\n): ApplyResult | null {\n\tif (!options.inboundScopeValidation) return null;\n\treturn rejectUnretiredScopeFailures(db, ops, localDeviceId, options.inboundScopeValidation);\n}\n\n/** Apply authenticated inbound operations using the caller's scanner and scope policy. */\nexport function applyPeerReplicationOps(\n\tstore: { db: Database; scanner: SecretScanner },\n\tops: ReplicationOp[],\n\tlocalDeviceId: string,\n\toptions: ApplyReplicationOpsOptions & { peerDeviceId: string },\n): ApplyResult {\n\treturn applyReplicationOps(store.db, ops, localDeviceId, store.scanner, {\n\t\t...options,\n\t\tactivityPeerDeviceId: options.peerDeviceId,\n\t\tactivitySource: \"inbound\",\n\t});\n}\n\n/** Insert a replication op row into the replication_ops table (ignore on conflict). */\nfunction insertReplicationOpRow(d: ReturnType<typeof drizzle>, op: ReplicationOp): void {\n\td.insert(schema.replicationOps)\n\t\t.values({\n\t\t\top_id: op.op_id,\n\t\t\tentity_type: op.entity_type,\n\t\t\tentity_id: op.entity_id,\n\t\t\top_type: op.op_type,\n\t\t\tpayload_json: op.payload_json,\n\t\t\tclock_rev: op.clock_rev,\n\t\t\tclock_updated_at: op.clock_updated_at,\n\t\t\tclock_device_id: op.clock_device_id,\n\t\t\tdevice_id: op.device_id,\n\t\t\tcreated_at: op.created_at,\n\t\t\tscope_id: op.scope_id ?? null,\n\t\t})\n\t\t.onConflictDoNothing()\n\t\t.run();\n}\n\n/**\n * Ensure a session row exists for replication inserts.\n * Creates a minimal session if one doesn't exist yet.\n */\nfunction ensureSessionForReplication(\n\td: ReturnType<typeof drizzle>,\n\tsessionId: number | null,\n\tcreatedAt: string,\n\tproject?: string | null,\n): number {\n\tif (sessionId != null) {\n\t\tconst row = d\n\t\t\t.select({ id: schema.sessions.id })\n\t\t\t.from(schema.sessions)\n\t\t\t.where(eq(schema.sessions.id, sessionId))\n\t\t\t.get();\n\t\tif (row) return sessionId;\n\t}\n\t// Create a new session for replicated data, preserving the source project.\n\tconst now = createdAt || new Date().toISOString();\n\tconst rows = d\n\t\t.insert(schema.sessions)\n\t\t.values({\n\t\t\tstarted_at: now,\n\t\t\tproject: project ?? null,\n\t\t\tuser: \"sync\",\n\t\t\ttool_version: \"sync_replication\",\n\t\t\tmetadata_json: toJson({ source: \"sync\" }),\n\t\t})\n\t\t.returning({ id: schema.sessions.id })\n\t\t.all();\n\tconst id = rows[0]?.id;\n\tif (id == null) throw new Error(\"session insert returned no id\");\n\treturn id;\n}\n","import type { Database } from \"./db.js\";\nimport {\n\tgetMaintenanceJob,\n\ttype MaintenanceJobSnapshot,\n\ttype StartMaintenanceJobInput,\n\tstartMaintenanceJob,\n\tupdateMaintenanceJob,\n} from \"./maintenance-jobs.js\";\n\nexport const VECTOR_MODEL_MIGRATION_JOB = \"vector_model_migration\";\nexport const SYNC_INCREMENTAL_TRIGGER = \"sync_incremental\";\n\nexport class VectorMigrationJobGenerationError extends RangeError {}\n\nexport interface VectorBackfillWork {\n\tupsertMemoryIds: readonly number[];\n\tdeleteMemoryIds: readonly number[];\n}\n\nexport type VectorBackfillQueueMetadata = {\n\ttarget_model?: string | null;\n\trequested_model?: string | null;\n\trequested_revision?: string | null;\n\tremoved_stale_rows?: number;\n\tcleanup_pending?: boolean;\n\ttrigger?: string | null;\n\tpending_upsert_memory_ids?: number[];\n\tpending_delete_memory_ids?: number[];\n\tqueue_revision?: number;\n\tjob_generation?: number;\n\t/** Local repair may drain queued IDs without resuming a cancelled migration. */\n\tlocal_repair_preserves_migration_state?: boolean;\n};\n\n/** Replacement identity is allocated with the write, including inside an outer transaction. */\nexport function startVectorMigrationJob(\n\tdb: Database,\n\tinput: Omit<StartMaintenanceJobInput, \"kind\">,\n): MaintenanceJobSnapshot {\n\treturn db\n\t\t.transaction(() => {\n\t\t\tconst existingJob = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\t\tconst storedGeneration = existingJob?.metadata?.job_generation;\n\t\t\tconst generation = storedGeneration === undefined ? 0 : storedGeneration;\n\t\t\tif (\n\t\t\t\ttypeof generation !== \"number\" ||\n\t\t\t\t!Number.isSafeInteger(generation) ||\n\t\t\t\tgeneration < 0 ||\n\t\t\t\tgeneration === Number.MAX_SAFE_INTEGER\n\t\t\t) {\n\t\t\t\tthrow new VectorMigrationJobGenerationError(\n\t\t\t\t\t\"Vector migration job generation is invalid or exhausted\",\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn startMaintenanceJob(db, {\n\t\t\t\t...input,\n\t\t\t\tkind: VECTOR_MODEL_MIGRATION_JOB,\n\t\t\t\tmetadata: { ...input.metadata, job_generation: generation + 1 },\n\t\t\t});\n\t\t})\n\t\t.immediate();\n}\n\nfunction uniquePositiveIds(memoryIds: readonly number[]): number[] {\n\treturn [\n\t\t...new Set(memoryIds.filter((memoryId) => Number.isInteger(memoryId) && memoryId > 0)),\n\t].sort((a, b) => a - b);\n}\n\nexport function metadataMemoryIds(value: unknown): number[] {\n\tif (!Array.isArray(value)) return [];\n\treturn uniquePositiveIds(value.filter((item): item is number => typeof item === \"number\"));\n}\n\nexport function mergeQueuedSyncMemoryIds(\n\tmetadata: VectorBackfillQueueMetadata,\n\twork: VectorBackfillWork,\n): Pick<VectorBackfillQueueMetadata, \"pending_upsert_memory_ids\" | \"pending_delete_memory_ids\"> {\n\tconst pendingUpsertMemoryIds = new Set(metadataMemoryIds(metadata.pending_upsert_memory_ids));\n\tconst pendingDeleteMemoryIds = new Set(metadataMemoryIds(metadata.pending_delete_memory_ids));\n\n\tfor (const memoryId of uniquePositiveIds(work.deleteMemoryIds)) {\n\t\tpendingUpsertMemoryIds.delete(memoryId);\n\t\tpendingDeleteMemoryIds.add(memoryId);\n\t}\n\tfor (const memoryId of uniquePositiveIds(work.upsertMemoryIds)) {\n\t\tpendingDeleteMemoryIds.delete(memoryId);\n\t\tpendingUpsertMemoryIds.add(memoryId);\n\t}\n\n\treturn {\n\t\tpending_upsert_memory_ids: [...pendingUpsertMemoryIds],\n\t\tpending_delete_memory_ids: [...pendingDeleteMemoryIds],\n\t};\n}\n\nfunction retainedQueueMetadata(\n\tjob: MaintenanceJobSnapshot | null,\n\toptions: { resumeMigration?: boolean },\n): VectorBackfillQueueMetadata {\n\tconst metadata = (job?.metadata ?? {}) as VectorBackfillQueueMetadata;\n\tif (job?.status === \"cancelled\" && !options.resumeMigration) {\n\t\treturn metadata;\n\t}\n\tif (job && job.status !== \"completed\" && job.status !== \"cancelled\") return metadata;\n\tconst cleanupMetadata: VectorBackfillQueueMetadata = metadata.cleanup_pending\n\t\t? {\n\t\t\t\tcleanup_pending: true,\n\t\t\t\ttarget_model: metadata.target_model,\n\t\t\t\trequested_model: metadata.requested_model,\n\t\t\t\trequested_revision: metadata.requested_revision,\n\t\t\t\tremoved_stale_rows: metadata.removed_stale_rows,\n\t\t\t\tqueue_revision: metadata.queue_revision,\n\t\t\t}\n\t\t: {};\n\tif (job?.status === \"cancelled\" && metadata.local_repair_preserves_migration_state) {\n\t\t// Explicit sync starts fresh, but repair IDs accumulated during cancellation must survive.\n\t\treturn {\n\t\t\t...cleanupMetadata,\n\t\t\tpending_upsert_memory_ids: metadata.pending_upsert_memory_ids,\n\t\t\tpending_delete_memory_ids: metadata.pending_delete_memory_ids,\n\t\t\tqueue_revision: metadata.queue_revision,\n\t\t};\n\t}\n\treturn cleanupMetadata;\n}\n\n/** Persist intent on this connection; nested calls commit only with the outer transaction. */\nexport function queueVectorBackfill(\n\tdb: Database,\n\twork: VectorBackfillWork,\n\toptions: { resumeMigration?: boolean } = {},\n): void {\n\tconst queuedWork = mergeQueuedSyncMemoryIds({}, work);\n\tif (\n\t\t(queuedWork.pending_upsert_memory_ids?.length ?? 0) === 0 &&\n\t\t(queuedWork.pending_delete_memory_ids?.length ?? 0) === 0\n\t) {\n\t\treturn;\n\t}\n\n\tdb.transaction(() => {\n\t\tconst existingJob = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\tconst existingMetadata = retainedQueueMetadata(existingJob, options);\n\t\tconst metadata: VectorBackfillQueueMetadata = {\n\t\t\t...existingMetadata,\n\t\t\t...mergeQueuedSyncMemoryIds(existingMetadata, work),\n\t\t\tqueue_revision: Number(existingMetadata.queue_revision ?? 0) + 1,\n\t\t};\n\t\tif (\n\t\t\t!options.resumeMigration &&\n\t\t\t(existingJob?.status === \"failed\" || existingJob?.status === \"cancelled\")\n\t\t) {\n\t\t\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\t\tmetadata: {\n\t\t\t\t\t...metadata,\n\t\t\t\t\tlocal_repair_preserves_migration_state: existingJob.status === \"cancelled\" || undefined,\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\t// The worker uses this trigger to drain queued IDs before migration cutover.\n\t\tmetadata.trigger = existingMetadata.trigger ?? SYNC_INCREMENTAL_TRIGGER;\n\t\tmetadata.local_repair_preserves_migration_state = undefined;\n\t\tconst message = options.resumeMigration\n\t\t\t? \"Queued vector catch-up for incremental sync data\"\n\t\t\t: \"Queued vector catch-up for memories\";\n\t\tconst pendingWorkCount =\n\t\t\tmetadataMemoryIds(metadata.pending_upsert_memory_ids).length +\n\t\t\tmetadataMemoryIds(metadata.pending_delete_memory_ids).length;\n\n\t\tif (!existingJob || existingJob.status === \"completed\" || existingJob.status === \"cancelled\") {\n\t\t\tstartVectorMigrationJob(db, {\n\t\t\t\ttitle: \"Re-indexing memories\",\n\t\t\t\tstatus: \"pending\",\n\t\t\t\tmessage,\n\t\t\t\tprogressTotal: null,\n\t\t\t\tmetadata,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\tstatus: \"pending\",\n\t\t\tmessage,\n\t\t\tprogressCurrent:\n\t\t\t\texistingJob.status === \"failed\"\n\t\t\t\t\t? 0\n\t\t\t\t\t: Math.min(existingJob.progress.current, pendingWorkCount),\n\t\t\tprogressTotal: existingJob.progress.total,\n\t\t\tmetadata,\n\t\t});\n\t}).immediate();\n}\n","import type { Database } from \"better-sqlite3\";\nimport { readVectorCorpusFence, type VectorCorpusFence } from \"./vector-corpus-epoch.js\";\nimport { createVectorMetadataSnapshot } from \"./vector-metadata-snapshot.js\";\nimport {\n\tcountIncompleteActiveMemoryVectorCoverage,\n\tpruneObsoleteTargetVectorsFromCatalog,\n} from \"./vectors.js\";\n\ntype MutationFence = VectorCorpusFence & { dataVersion: number; totalChanges: number };\n\nfunction readFence(db: Database, phase: string): MutationFence {\n\treturn {\n\t\t...readVectorCorpusFence(db),\n\t\tdataVersion: Number(db.pragma(\"data_version\", { simple: true })),\n\t\ttotalChanges: Number(\n\t\t\tdb.prepare(`/* vector-cutover-${phase} */ SELECT total_changes()`).pluck().get(),\n\t\t),\n\t};\n}\n\ntype MetadataRow = {\n\trowid: number;\n\tmemory_id: number | null;\n\tmodel: string | null;\n\tcontent_hash: string | null;\n};\n\nfunction hasExactNumericIds(row: MetadataRow): boolean {\n\treturn (\n\t\tNumber.isSafeInteger(row.rowid) &&\n\t\t(row.memory_id === null || Number.isSafeInteger(row.memory_id))\n\t);\n}\n\nfunction compareCatalog(\n\tdb: Database,\n\tmetadata: Database,\n\tmodel: string,\n\texpectedCount: number,\n): string | null {\n\tconst deadline = performance.now() + 2000;\n\tconst find = metadata.prepare(\n\t\t\"SELECT memory_id, model, content_hash FROM vector_metadata WHERE rowid = ?\",\n\t);\n\tconst current = db\n\t\t.prepare(\n\t\t\t\"SELECT rowid, memory_id, model, content_hash FROM memory_vectors /* vector-cutover-exact-metadata */\",\n\t\t)\n\t\t.safeIntegers();\n\tlet count = 0;\n\tfor (const raw of current.iterate() as Iterable<\n\t\tOmit<MetadataRow, \"rowid\" | \"memory_id\"> & { rowid: bigint; memory_id: bigint | null }\n\t>) {\n\t\tif (performance.now() > deadline)\n\t\t\treturn \"Target metadata comparison exceeded 2 seconds; retrying\";\n\t\t// Read every row so a native step cannot spend the whole budget skipping\n\t\t// a long run of non-target rows before control returns to JavaScript.\n\t\tif (raw.model !== model) continue;\n\t\tconst row: MetadataRow = {\n\t\t\t...raw,\n\t\t\trowid: Number(raw.rowid),\n\t\t\tmemory_id: raw.memory_id === null ? null : Number(raw.memory_id),\n\t\t};\n\t\tif (!hasExactNumericIds(row))\n\t\t\treturn \"Target metadata IDs exceed the exact numeric range; retrying\";\n\t\tconst saved = find.get(row.rowid) as MetadataRow | undefined;\n\t\tif (\n\t\t\t!saved ||\n\t\t\tsaved.memory_id !== row.memory_id ||\n\t\t\tsaved.model !== row.model ||\n\t\t\tsaved.content_hash !== row.content_hash\n\t\t)\n\t\t\treturn \"Target vector metadata changed during validation; retrying\";\n\t\tcount++;\n\t}\n\tif (performance.now() > deadline)\n\t\treturn \"Target metadata comparison exceeded 2 seconds; retrying\";\n\t// Unique rowids + exact membership + cardinality proves equality in both directions.\n\tif (count !== expectedCount) return \"Target vector metadata changed during validation; retrying\";\n\treturn null;\n}\n\n/**\n * Keep the catalog alive through finalization; it is NOT a source TEMP table.\n * Blob/chunk_index-only writes cannot change hash coverage and are intentionally ignored.\n */\nexport type VectorCutoverValidation = {\n\tdeleted: number;\n\tuncovered: number;\n\tclose: () => void;\n\tretryReason: () => string | null;\n\tcorpusRetryReason: () => string | null;\n\tmetadataRetryReason: () => string | null;\n\tnoteOwnWrites: () => void;\n};\n\nexport function prepareVectorCutoverValidation(\n\tdb: Database,\n\tmodel: string,\n\toptions: { signal?: AbortSignal; phase?: \"cleanup-\"; pruneScope?: \"all\" | \"active-only\" } = {},\n): VectorCutoverValidation {\n\tconst phase = options.phase ?? \"\";\n\tconst before = readFence(db, `${phase}prune-start`);\n\tconst metadata = createVectorMetadataSnapshot(db, { model });\n\ttry {\n\t\tconst deleted = pruneObsoleteTargetVectorsFromCatalog(db, model, metadata, options);\n\t\tlet afterPrune = readFence(db, `${phase}prune-end`);\n\t\tconst uncovered = countIncompleteActiveMemoryVectorCoverage(db, model, { metadata });\n\t\tconst expectedCount = Number(\n\t\t\tmetadata.prepare(\"SELECT COUNT(*) FROM vector_metadata\").pluck().get(),\n\t\t);\n\t\tconst corpusRetryReason = (): string | null => {\n\t\t\tif (options.signal?.aborted) return \"Cutover paused during shutdown; retrying\";\n\t\t\tconst current = readFence(db, \"validation\");\n\t\t\tif (current.schemaVersion !== before.schemaVersion)\n\t\t\t\treturn \"Database schema changed during validation; retrying\";\n\t\t\tif (before.epoch !== null) {\n\t\t\t\tif (current.epoch !== before.epoch)\n\t\t\t\t\treturn `Memory changes arrived during ${phase}cutover validation; retrying`;\n\t\t\t} else if (\n\t\t\t\tbefore.dataVersion !== afterPrune.dataVersion ||\n\t\t\t\tcurrent.dataVersion !== afterPrune.dataVersion ||\n\t\t\t\tcurrent.totalChanges !== afterPrune.totalChanges\n\t\t\t) {\n\t\t\t\treturn `Memory changes arrived during ${phase}cutover validation; retrying`;\n\t\t\t}\n\t\t\treturn null;\n\t\t};\n\t\tconst metadataRetryReason = () => compareCatalog(db, metadata, model, expectedCount);\n\t\treturn {\n\t\t\tdeleted,\n\t\t\tuncovered,\n\t\t\tclose: () => metadata.close(),\n\t\t\t// Must be called under BEGIN IMMEDIATE. Body hashing already happened above.\n\t\t\tretryReason: () => corpusRetryReason() ?? metadataRetryReason(),\n\t\t\tcorpusRetryReason,\n\t\t\tmetadataRetryReason,\n\t\t\t// Only immediately after our synchronous delete/job writes, before yielding.\n\t\t\t// Keep the original data_version: other connections still invalidate fallback.\n\t\t\tnoteOwnWrites: () => {\n\t\t\t\tafterPrune = {\n\t\t\t\t\t...afterPrune,\n\t\t\t\t\ttotalChanges: Number(db.prepare(\"SELECT total_changes()\").pluck().get()),\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\tmetadata.close();\n\t\tthrow error;\n\t}\n}\n","import type { Database as SqliteDatabase } from \"better-sqlite3\";\nimport { connect, isEmbeddingDisabled, loadSqliteVec, resolveDbPath } from \"./db.js\";\nimport {\n\tDEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL,\n\ttype EmbeddingClient,\n\tgetEmbeddingClient,\n\tresolveEmbeddingClientVectorIdentityLabel,\n\ttryResolveEmbeddingVectorIdentityLabel,\n} from \"./embeddings.js\";\nimport {\n\tcompleteMaintenanceJob,\n\tfailMaintenanceJob,\n\tgetMaintenanceJob,\n\tisTransientSqliteBusy,\n\ttype MaintenanceJobSnapshot,\n\tupdateMaintenanceJob,\n} from \"./maintenance-jobs.js\";\nimport type { ReplicationVectorWork } from \"./sync-replication.js\";\nimport {\n\tmergeQueuedSyncMemoryIds,\n\tmetadataMemoryIds,\n\tqueueVectorBackfill,\n\tSYNC_INCREMENTAL_TRIGGER,\n\tstartVectorMigrationJob,\n\tVECTOR_MODEL_MIGRATION_JOB,\n\ttype VectorBackfillQueueMetadata,\n\tVectorMigrationJobGenerationError,\n} from \"./vector-backfill-queue.js\";\nimport { readVectorCorpusFence } from \"./vector-corpus-epoch.js\";\nimport {\n\tprepareVectorCutoverValidation,\n\ttype VectorCutoverValidation,\n} from \"./vector-cutover-validation.js\";\nimport { resolveVectorLayout } from \"./vector-layout.js\";\nimport { prepareVectorWrites } from \"./vector-writes.js\";\nimport {\n\tbackfillVectors,\n\tfindMemoryIdsWithCompleteActiveVectorCoverage,\n\tfindMemoryIdsWithCurrentTargetCoverage,\n\tpruneStaleCurrentModelVectors,\n} from \"./vectors.js\";\n\nexport { VECTOR_MODEL_MIGRATION_JOB } from \"./vector-backfill-queue.js\";\n\nconst LEGACY_DEFAULT_EMBEDDING_MODEL = \"Xenova/bge-small-en-v1.5\";\nconst SYNC_BOOTSTRAP_TRIGGER = \"sync_bootstrap\";\n\nexport interface VectorModelMigrationOptions {\n\tbatchSize?: number;\n\tintervalMs?: number;\n\tidleIntervalMs?: number;\n\t/**\n\t * Wall-clock budget for one tick. While work remains, the runner keeps\n\t * running batches on the same connection until this much time has passed.\n\t * Each batch still commits in its own short write transaction. 0 runs one\n\t * batch per tick.\n\t */\n\ttickBudgetMs?: number;\n\tdbPath?: string;\n\tsignal?: AbortSignal;\n}\n\n// Runner uses this cadence after a tick that detected no work. A live\n// migration or queued sync work switches back to intervalMs automatically.\nconst IDLE_INTERVAL_MS = 60_000;\n\n// Another connection held the write lock past busy_timeout. Retry soon with a\n// growing delay instead of treating lock contention as an idle database.\nconst BUSY_RETRY_BASE_MS = 5_000;\nconst BUSY_RETRY_MAX_MS = 30_000;\n// After this many locked ticks in a row (about 4 minutes), tell the UI why\n// catch-up is not moving.\nconst BUSY_TICKS_BEFORE_LOCK_NOTICE = 10;\nconst LOCK_WAIT_MESSAGE = \"Waiting for the database lock\";\n\nfunction busyRetryDelayMs(consecutiveBusyTicks: number): number {\n\tconst exponent = Math.max(0, consecutiveBusyTicks - 1);\n\treturn Math.min(BUSY_RETRY_MAX_MS, BUSY_RETRY_BASE_MS * 2 ** exponent);\n}\n\nfunction yieldToEventLoop(): Promise<void> {\n\treturn new Promise((resolve) => setImmediate(resolve));\n}\n\n// Module-level singleton so the queue writers can nudge the runner out of\n// its long idle cadence the moment new incremental/bootstrap work lands.\n// Assumes one active runner per process (the viewer serve loop), which\n// matches the current deployment model.\nlet activeRunner: VectorModelMigrationRunner | null = null;\n\ntype MemoryRow = { id: number; title: string | null; body_text: string | null };\n\ntype MigrationMetadata = VectorBackfillQueueMetadata & {\n\tsource_model?: string | null;\n\tlast_cursor_id?: number;\n\tprocessed_embeddable?: number;\n\tembeddable_total?: number;\n\tuncovered_target_memories?: number;\n\tstale_scan_exhausted?: boolean;\n\tstale_scan_exhausted_max_rowid?: number;\n\treconciliation_target_coverage_complete?: boolean;\n\tcutover_retry_count?: number;\n};\n\nfunction deleteVectorsForMemoryIds(db: SqliteDatabase, memoryIds: number[]): void {\n\tif (memoryIds.length === 0) return;\n\tconst write = prepareVectorWrites(db);\n\tdb.transaction(() => write({ deleteMemoryIds: memoryIds })).immediate();\n}\n\nfunction sameQueuedSyncWork(a: MigrationMetadata, b: MigrationMetadata): boolean {\n\treturn (\n\t\tNumber(a.queue_revision ?? 0) === Number(b.queue_revision ?? 0) &&\n\t\tJSON.stringify(metadataMemoryIds(a.pending_upsert_memory_ids)) ===\n\t\t\tJSON.stringify(metadataMemoryIds(b.pending_upsert_memory_ids)) &&\n\t\tJSON.stringify(metadataMemoryIds(a.pending_delete_memory_ids)) ===\n\t\t\tJSON.stringify(metadataMemoryIds(b.pending_delete_memory_ids))\n\t);\n}\n\nfunction buildDrainedQueuedSyncMetadata(options: {\n\tmetadata: MigrationMetadata;\n\tpendingUpsertMemoryIds: number[];\n\tbatchUpsertMemoryIds: number[];\n\tcoveredBatchUpsertMemoryIds: Set<number>;\n\tclient: EmbeddingClient;\n\ttargetModel: string;\n\tprunedRows: number;\n}): MigrationMetadata {\n\tconst targetChanged =\n\t\toptions.metadata.target_model != null && options.metadata.target_model !== options.targetModel;\n\tconst retainedMetadata: MigrationMetadata = targetChanged\n\t\t? {\n\t\t\t\ttrigger: options.metadata.trigger,\n\t\t\t\tpending_delete_memory_ids: options.metadata.pending_delete_memory_ids,\n\t\t\t\tpending_upsert_memory_ids: options.metadata.pending_upsert_memory_ids,\n\t\t\t\tjob_generation: options.metadata.job_generation,\n\t\t\t\tsource_model: null,\n\t\t\t\tlast_cursor_id: 0,\n\t\t\t\tprocessed_embeddable: 0,\n\t\t\t}\n\t\t: options.metadata;\n\tconst retainedBatchUpserts = options.batchUpsertMemoryIds.filter(\n\t\t(memoryId) => !options.coveredBatchUpsertMemoryIds.has(memoryId),\n\t);\n\treturn {\n\t\t...retainedMetadata,\n\t\ttarget_model: options.targetModel,\n\t\trequested_model: options.client.model,\n\t\trequested_revision:\n\t\t\toptions.client.identity?.requestedRevision ?? options.client.identity?.revision ?? null,\n\t\tremoved_stale_rows: Number(options.metadata.removed_stale_rows ?? 0) + options.prunedRows,\n\t\tpending_delete_memory_ids: [],\n\t\tpending_upsert_memory_ids: [\n\t\t\t...retainedBatchUpserts,\n\t\t\t...options.pendingUpsertMemoryIds.slice(options.batchUpsertMemoryIds.length),\n\t\t],\n\t};\n}\n\nfunction pendingQueuedSyncCount(metadata: MigrationMetadata): number {\n\treturn (\n\t\tmetadataMemoryIds(metadata.pending_delete_memory_ids).length +\n\t\tmetadataMemoryIds(metadata.pending_upsert_memory_ids).length\n\t);\n}\n\n/**\n * Incremental sync jobs with queued changes drain a batch and return before the\n * migration batch loop, so the pass never reaches cutover validation.\n */\nfunction drainsQueuedSyncBeforeCutover(metadata: MigrationMetadata): boolean {\n\treturn (\n\t\t(metadata.trigger ?? SYNC_INCREMENTAL_TRIGGER) === SYNC_INCREMENTAL_TRIGGER &&\n\t\tpendingQueuedSyncCount(metadata) > 0\n\t);\n}\n\nfunction shouldCompleteIncrementalSync(\n\tdb: SqliteDatabase,\n\tmetadata: MigrationMetadata,\n\ttargetModel: string,\n): boolean {\n\tif (pendingQueuedSyncCount(metadata) > 0) return false;\n\tif (hasSourceModelVectors(db, targetModel)) return false;\n\treturn (\n\t\t(metadata.trigger ?? SYNC_INCREMENTAL_TRIGGER) === SYNC_INCREMENTAL_TRIGGER &&\n\t\t!metadata.source_model &&\n\t\t!metadata.last_cursor_id &&\n\t\tmetadata.embeddable_total == null\n\t);\n}\n\nfunction writeQueuedSyncResult(\n\tdb: SqliteDatabase,\n\tjob: NonNullable<ReturnType<typeof getMaintenanceJob>>,\n\tmetadata: MigrationMetadata,\n\ttargetModel: string,\n): { completed: boolean; metadata: MigrationMetadata } {\n\tif (preservesCancelledMigration(job)) {\n\t\tconst preservedMetadata: MigrationMetadata = {\n\t\t\t...job.metadata,\n\t\t\tpending_upsert_memory_ids: metadata.pending_upsert_memory_ids,\n\t\t\tpending_delete_memory_ids: metadata.pending_delete_memory_ids,\n\t\t\tqueue_revision: metadata.queue_revision,\n\t\t};\n\t\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, { metadata: preservedMetadata });\n\t\treturn { completed: false, metadata: preservedMetadata };\n\t}\n\tconst remainingWorkCount = pendingQueuedSyncCount(metadata);\n\tif (shouldCompleteIncrementalSync(db, metadata, targetModel)) {\n\t\tcompleteMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\tmessage: \"Finished vector catch-up for incremental sync data\",\n\t\t\tprogressCurrent: 0,\n\t\t\tprogressTotal: null,\n\t\t\tmetadata,\n\t\t});\n\t\treturn { completed: true, metadata };\n\t}\n\n\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\tstatus: remainingWorkCount > 0 ? \"running\" : job.status,\n\t\tmessage:\n\t\t\tremainingWorkCount > 0\n\t\t\t\t? `Queued vector catch-up has ${remainingWorkCount} memory change(s) remaining`\n\t\t\t\t: job.message,\n\t\tprogressCurrent: 0,\n\t\tprogressTotal: null,\n\t\tmetadata,\n\t});\n\treturn { completed: false, metadata };\n}\n\ntype QueuedSyncResult = {\n\tcompleted: boolean;\n\tmetadata: MigrationMetadata;\n\tsuperseded?: boolean;\n\tjob?: MigrationJob;\n};\n\nfunction pruneCoveredRequeues(\n\tdb: SqliteDatabase,\n\tmetadata: MigrationMetadata,\n\tcovered: Set<number>,\n\ttargetModel: string,\n): number {\n\tconst memoryIds = metadataMemoryIds(metadata.pending_upsert_memory_ids).filter((id) =>\n\t\tcovered.has(id),\n\t);\n\treturn pruneStaleCurrentModelVectors(db, memoryIds, targetModel);\n}\n\nfunction mergeDrainedQueuedSyncMetadata(\n\tlatest: MigrationMetadata,\n\tdrained: MigrationMetadata,\n\tcovered: Set<number>,\n): MigrationMetadata {\n\tconst pendingUpserts = metadataMemoryIds(latest.pending_upsert_memory_ids).filter(\n\t\t(id) => !covered.has(id),\n\t);\n\treturn {\n\t\t...drained,\n\t\t...mergeQueuedSyncMemoryIds(\n\t\t\t{ ...latest, pending_upsert_memory_ids: pendingUpserts },\n\t\t\t{\n\t\t\t\tupsertMemoryIds: metadataMemoryIds(drained.pending_upsert_memory_ids),\n\t\t\t\tdeleteMemoryIds: metadataMemoryIds(drained.pending_delete_memory_ids),\n\t\t\t},\n\t\t),\n\t\tqueue_revision: latest.queue_revision,\n\t};\n}\n\nfunction finalizeQueuedSyncVectorWork(\n\tdb: SqliteDatabase,\n\toptions: {\n\t\tjob: NonNullable<ReturnType<typeof getMaintenanceJob>>;\n\t\tmetadata: MigrationMetadata;\n\t\tpendingUpsertMemoryIds: number[];\n\t\tbatchUpsertMemoryIds: number[];\n\t\tclient: EmbeddingClient;\n\t\ttargetModel: string;\n\t},\n): QueuedSyncResult {\n\treturn (\n\t\twithMigrationJobOwner(db, options.job, () => {\n\t\t\tlet prunedRows = pruneStaleCurrentModelVectors(\n\t\t\t\tdb,\n\t\t\t\toptions.batchUpsertMemoryIds,\n\t\t\t\toptions.targetModel,\n\t\t\t);\n\t\t\tconst latestJob = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\t\tif (!sameMigrationJob(options.job, latestJob)) {\n\t\t\t\treturn { completed: false, metadata: options.metadata, superseded: true };\n\t\t\t}\n\t\t\tconst coveredBatchUpsertMemoryIds = new Set(\n\t\t\t\tfindMemoryIdsWithCompleteActiveVectorCoverage(\n\t\t\t\t\tdb,\n\t\t\t\t\toptions.batchUpsertMemoryIds,\n\t\t\t\t\toptions.targetModel,\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst latestMetadata = (latestJob?.metadata ?? {}) as MigrationMetadata;\n\t\t\tconst queuedWorkChanged = !sameQueuedSyncWork(latestMetadata, options.metadata);\n\t\t\tif (queuedWorkChanged) {\n\t\t\t\tprunedRows += pruneCoveredRequeues(\n\t\t\t\t\tdb,\n\t\t\t\t\tlatestMetadata,\n\t\t\t\t\tcoveredBatchUpsertMemoryIds,\n\t\t\t\t\toptions.targetModel,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst drainedMetadata = buildDrainedQueuedSyncMetadata({\n\t\t\t\t...options,\n\t\t\t\tcoveredBatchUpsertMemoryIds,\n\t\t\t\tprunedRows,\n\t\t\t});\n\t\t\tlet nextMetadata = drainedMetadata;\n\t\t\tif (queuedWorkChanged) {\n\t\t\t\tnextMetadata = mergeDrainedQueuedSyncMetadata(\n\t\t\t\t\tlatestMetadata,\n\t\t\t\t\tdrainedMetadata,\n\t\t\t\t\tcoveredBatchUpsertMemoryIds,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst result = writeQueuedSyncResult(\n\t\t\t\tdb,\n\t\t\t\tlatestJob ?? options.job,\n\t\t\t\t{\n\t\t\t\t\t...nextMetadata,\n\t\t\t\t\tlocal_repair_preserves_migration_state:\n\t\t\t\t\t\tlatestMetadata.local_repair_preserves_migration_state,\n\t\t\t\t},\n\t\t\t\toptions.targetModel,\n\t\t\t);\n\t\t\treturn { ...result, job: getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB) };\n\t\t}) ?? { completed: false, metadata: options.metadata, superseded: true }\n\t);\n}\n\nexport function wakeActiveVectorMigrationRunner(): void {\n\tactiveRunner?.wake();\n}\n\nexport function queueVectorBackfillForIncrementalSync(\n\tdb: SqliteDatabase,\n\twork: ReplicationVectorWork,\n): void {\n\tconst queuedWork = mergeQueuedSyncMemoryIds({}, work);\n\tif (\n\t\t(queuedWork.pending_upsert_memory_ids?.length ?? 0) === 0 &&\n\t\t(queuedWork.pending_delete_memory_ids?.length ?? 0) === 0\n\t) {\n\t\treturn;\n\t}\n\n\tqueueVectorBackfill(db, work, { resumeMigration: true });\n\twakeActiveVectorMigrationRunner();\n}\n\nasync function runQueuedSyncVectorWork(\n\tdb: SqliteDatabase,\n\tjob: NonNullable<ReturnType<typeof getMaintenanceJob>>,\n\tclient: EmbeddingClient,\n\ttargetModel: string,\n\tbatchSize: number,\n\tsignal?: AbortSignal,\n): Promise<QueuedSyncResult> {\n\tconst metadata = (job.metadata ?? {}) as MigrationMetadata;\n\tconst pendingDeleteMemoryIds = metadataMemoryIds(metadata.pending_delete_memory_ids);\n\tconst pendingUpsertMemoryIds = metadataMemoryIds(metadata.pending_upsert_memory_ids);\n\tif (pendingDeleteMemoryIds.length === 0 && pendingUpsertMemoryIds.length === 0) {\n\t\treturn { completed: false, metadata };\n\t}\n\n\tconst ownsWork = withMigrationJobOwner(db, job, () => {\n\t\tdeleteVectorsForMemoryIds(db, pendingDeleteMemoryIds);\n\t\treturn true;\n\t});\n\tif (!ownsWork) return { completed: false, metadata, superseded: true };\n\tconst batchUpsertMemoryIds = pendingUpsertMemoryIds.slice(0, batchSize);\n\tif (batchUpsertMemoryIds.length > 0) {\n\t\tawait backfillVectors(db, { memoryIds: batchUpsertMemoryIds, signal, client });\n\t\t// If the abort fired mid-batch, backfillVectors may have only\n\t\t// processed a prefix. Skip the prune-and-drop bookkeeping so the\n\t\t// unprocessed IDs stay in pending_upsert_memory_ids for the next\n\t\t// tick to retry.\n\t\tif (signal?.aborted) {\n\t\t\treturn { completed: false, metadata };\n\t\t}\n\t}\n\treturn finalizeQueuedSyncVectorWork(db, {\n\t\tjob,\n\t\tmetadata,\n\t\tpendingUpsertMemoryIds,\n\t\tbatchUpsertMemoryIds,\n\t\tclient,\n\t\ttargetModel,\n\t});\n}\n\nexport function queueVectorBackfillForSyncBootstrap(\n\tdb: SqliteDatabase,\n\toptions: { embeddableTotal?: number | null } = {},\n): void {\n\tconst embeddableTotal =\n\t\ttypeof options.embeddableTotal === \"number\" && options.embeddableTotal >= 0\n\t\t\t? options.embeddableTotal\n\t\t\t: null;\n\tdb.transaction(() => {\n\t\tconst existingJob = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\tconst existingMetadata = (existingJob?.metadata ?? {}) as MigrationMetadata;\n\t\tconst metadata: MigrationMetadata = {\n\t\t\tlast_cursor_id: 0,\n\t\t\tprocessed_embeddable: 0,\n\t\t\ttrigger: SYNC_BOOTSTRAP_TRIGGER,\n\t\t\tpending_upsert_memory_ids: metadataMemoryIds(existingMetadata.pending_upsert_memory_ids),\n\t\t\tpending_delete_memory_ids: metadataMemoryIds(existingMetadata.pending_delete_memory_ids),\n\t\t\t// Bootstrap resets the scan, not the queued work. Retain its revision so\n\t\t\t// later enqueues cannot reuse a revision observed by an in-flight drain.\n\t\t\tqueue_revision: existingMetadata.queue_revision,\n\t\t};\n\t\tif (embeddableTotal != null) {\n\t\t\tmetadata.embeddable_total = embeddableTotal;\n\t\t}\n\t\tstartVectorMigrationJob(db, {\n\t\t\ttitle: \"Re-indexing memories\",\n\t\t\tstatus: \"pending\",\n\t\t\tmessage: \"Queued vector catch-up for synced bootstrap data\",\n\t\t\tprogressTotal: embeddableTotal,\n\t\t\tmetadata,\n\t\t});\n\t}).immediate();\n\twakeActiveVectorMigrationRunner();\n}\n\nfunction vectorModels(db: SqliteDatabase): Array<{ model: string; rows: number }> {\n\treturn db\n\t\t.prepare(\n\t\t\t\"SELECT model, COUNT(*) AS rows FROM memory_vectors GROUP BY model ORDER BY rows DESC, model ASC\",\n\t\t)\n\t\t.all() as Array<{ model: string; rows: number }>;\n}\n\ntype SourceModelScanResult = {\n\tfound: boolean;\n\t/** Last rowid the scan examined, or null when the legacy full-scan path ran. */\n\tscannedMaxRowId: number | null;\n};\n\nfunction exactVectorRowId(value: bigint): number | null {\n\tif (value < BigInt(Number.MIN_SAFE_INTEGER) || value > BigInt(Number.MAX_SAFE_INTEGER))\n\t\treturn null;\n\treturn Number(value);\n}\n\nfunction exactVectorRowIdPage(rows: { rowid: bigint }[]): { rowid: number }[] | null {\n\tconst exactRows: { rowid: number }[] = [];\n\tfor (const row of rows) {\n\t\tconst rowid = exactVectorRowId(row.rowid);\n\t\tif (rowid === null) return null;\n\t\texactRows.push({ rowid });\n\t}\n\treturn exactRows;\n}\n\nfunction scanForSourceModelVectorsAfter(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\tafterRowId: number,\n): SourceModelScanResult {\n\tif (!Number.isSafeInteger(afterRowId)) return { found: true, scannedMaxRowId: null };\n\tif (!hasMemoryVectorRowidsShadowTable(db)) {\n\t\tconst found = Boolean(\n\t\t\tdb.prepare(\"SELECT 1 FROM memory_vectors WHERE model != ? LIMIT 1\").pluck().get(targetModel),\n\t\t);\n\t\treturn { found, scannedMaxRowId: null };\n\t}\n\tconst selectRowIds = db\n\t\t.prepare(\n\t\t\t`SELECT rowid FROM ${vectorRowidsTable(db)} WHERE rowid > ? ORDER BY rowid ASC LIMIT ? /* vector-source-scan-rowids */`,\n\t\t)\n\t\t.safeIntegers();\n\tconst selectMetadata = db.prepare(\n\t\t\"SELECT memory_id, content_hash, model FROM memory_vectors WHERE rowid = ?\",\n\t);\n\tlet cursor = afterRowId;\n\twhile (true) {\n\t\tconst rows = exactVectorRowIdPage(selectRowIds.all(cursor, 250) as { rowid: bigint }[]);\n\t\t// An unsupported ID is unexamined work, not evidence of scan exhaustion.\n\t\tif (rows === null) return { found: true, scannedMaxRowId: null };\n\t\tif (rows.length === 0) return { found: false, scannedMaxRowId: cursor };\n\t\tfor (const row of rows) {\n\t\t\tconst metadata = selectMetadata.get(row.rowid) as { model: string } | undefined;\n\t\t\tif (metadata && metadata.model !== targetModel) {\n\t\t\t\treturn { found: true, scannedMaxRowId: null };\n\t\t\t}\n\t\t}\n\t\tcursor = rows.at(-1)?.rowid ?? cursor;\n\t}\n}\n\nfunction hasSourceModelVectorsAfter(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\tafterRowId: number,\n): boolean {\n\treturn scanForSourceModelVectorsAfter(db, targetModel, afterRowId).found;\n}\n\nfunction hasSourceModelVectors(db: SqliteDatabase, targetModel: string): boolean {\n\treturn hasSourceModelVectorsAfter(db, targetModel, 0);\n}\n\nfunction hasMemoryVectorRowidsShadowTable(db: SqliteDatabase): boolean {\n\tconst layout = resolveVectorLayout(db);\n\tif (layout.kind === \"absent\") return false;\n\tconst tables = db.prepare(\"PRAGMA table_list\").all() as Array<{ name: string }>;\n\treturn tables.some((table) => table.name === layout.rowidsName);\n}\n\nfunction vectorRowidsTable(\n\tdb: SqliteDatabase,\n): \"memory_vectors_rowids\" | \"memory_vectors_v1_rowids\" {\n\tconst layout = resolveVectorLayout(db);\n\tif (layout.kind === \"absent\") throw new Error(\"vector_table_required\");\n\treturn layout.rowidsName;\n}\n\nfunction readMaxMemoryVectorRowId(db: SqliteDatabase): number | null {\n\tif (!hasMemoryVectorRowidsShadowTable(db)) return null;\n\tconst row = db\n\t\t.prepare(`SELECT MAX(rowid) AS max_rowid FROM ${vectorRowidsTable(db)}`)\n\t\t.safeIntegers()\n\t\t.get() as { max_rowid: bigint | null } | undefined;\n\tif (row?.max_rowid == null) return 0;\n\treturn exactVectorRowId(row.max_rowid);\n}\n\nfunction checkCompletedStaleScan(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\tmetadata: MigrationMetadata,\n): { canReturn: boolean; metadata: MigrationMetadata } {\n\tif (metadata.cleanup_pending) return { canReturn: false, metadata };\n\tif (!metadata.stale_scan_exhausted) {\n\t\t// Jobs completed before the flag existed have no watermark. One clean\n\t\t// compatibility scan is unavoidable, but persist its result so upgraded\n\t\t// databases don't repeat it on every idle tick.\n\t\tconst scan = scanForSourceModelVectorsAfter(db, targetModel, 0);\n\t\tif (scan.found) return { canReturn: false, metadata };\n\t\tif (scan.scannedMaxRowId == null) return { canReturn: true, metadata };\n\t\tconst persisted = {\n\t\t\t...metadata,\n\t\t\tstale_scan_exhausted: true,\n\t\t\tstale_scan_exhausted_max_rowid: scan.scannedMaxRowId,\n\t\t};\n\t\treturn { canReturn: true, metadata: persisted };\n\t}\n\tconst exhaustedMaxRowId = metadata.stale_scan_exhausted_max_rowid;\n\tconst currentMaxRowId = readMaxMemoryVectorRowId(db);\n\tif (\n\t\ttypeof exhaustedMaxRowId === \"number\" &&\n\t\tNumber.isSafeInteger(exhaustedMaxRowId) &&\n\t\tcurrentMaxRowId != null &&\n\t\tcurrentMaxRowId <= exhaustedMaxRowId\n\t) {\n\t\treturn { canReturn: true, metadata };\n\t}\n\tif (\n\t\ttypeof exhaustedMaxRowId === \"number\" &&\n\t\tNumber.isSafeInteger(exhaustedMaxRowId) &&\n\t\tcurrentMaxRowId != null &&\n\t\t!hasSourceModelVectorsAfter(db, targetModel, exhaustedMaxRowId)\n\t) {\n\t\tconst refreshed = { ...metadata, stale_scan_exhausted_max_rowid: currentMaxRowId };\n\t\treturn { canReturn: true, metadata: refreshed };\n\t}\n\tconst invalidated = {\n\t\t...metadata,\n\t\tstale_scan_exhausted: undefined,\n\t\tstale_scan_exhausted_max_rowid: undefined,\n\t};\n\treturn { canReturn: false, metadata: invalidated };\n}\n\nfunction countEmbeddableActiveMemories(db: SqliteDatabase): number {\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT COUNT(*) AS c FROM memory_items\n\t\t\t WHERE active = 1\n\t\t\t AND TRIM(COALESCE(title, '') || COALESCE(body_text, '')) != ''`,\n\t\t)\n\t\t.get() as { c?: number } | undefined;\n\treturn Number(row?.c ?? 0);\n}\n\nfunction describeIncompleteTargetMemories(count: number): string {\n\treturn `${count} ${count === 1 ? \"memory\" : \"memories\"}`;\n}\n\nfunction selectNextMigrationBatch(\n\tdb: SqliteDatabase,\n\tafterId: number,\n\tbatchSize: number,\n): MemoryRow[] {\n\treturn db\n\t\t.prepare(\n\t\t\t`SELECT id, title, body_text\n\t\t\t FROM memory_items\n\t\t\t WHERE active = 1 AND id > ?\n\t\t\t ORDER BY id ASC\n\t\t\t LIMIT ?`,\n\t\t)\n\t\t.all(afterId, batchSize) as MemoryRow[];\n}\n\nfunction isEmbeddableMemory(row: MemoryRow): boolean {\n\treturn (\n\t\t`${row.title ?? \"\"}\n${row.body_text ?? \"\"}`.trim().length > 0\n\t);\n}\n\nfunction nextMigrationMetadata(\n\tjob: ReturnType<typeof getMaintenanceJob>,\n\tsourceModel: string | null,\n\ttargetModel: string,\n\trequestedModel: string,\n\trequestedRevision: string,\n\tembeddableTotal: number,\n\toptions: {\n\t\trestartFromBeginning?: boolean;\n\t\treconciliationTargetCoverageComplete?: boolean;\n\t} = {},\n): MigrationMetadata {\n\tconst metadata = (job?.metadata ?? {}) as MigrationMetadata;\n\tconst pendingUpsertMemoryIds = metadataMemoryIds(metadata.pending_upsert_memory_ids);\n\tconst pendingDeleteMemoryIds = metadataMemoryIds(metadata.pending_delete_memory_ids);\n\tconst pending_upsert_memory_ids =\n\t\tpendingUpsertMemoryIds.length > 0 ? pendingUpsertMemoryIds : undefined;\n\tconst pending_delete_memory_ids =\n\t\tpendingDeleteMemoryIds.length > 0 ? pendingDeleteMemoryIds : undefined;\n\tif (metadata.target_model !== targetModel || options.restartFromBeginning) {\n\t\treturn {\n\t\t\ttrigger: metadata.trigger,\n\t\t\treconciliation_target_coverage_complete:\n\t\t\t\toptions.reconciliationTargetCoverageComplete || undefined,\n\t\t\tpending_upsert_memory_ids,\n\t\t\tpending_delete_memory_ids,\n\t\t\tqueue_revision: metadata.queue_revision,\n\t\t\tjob_generation: metadata.job_generation,\n\t\t\tsource_model: sourceModel,\n\t\t\ttarget_model: targetModel,\n\t\t\trequested_model: requestedModel,\n\t\t\trequested_revision: requestedRevision,\n\t\t\tlast_cursor_id: 0,\n\t\t\tprocessed_embeddable: 0,\n\t\t\tembeddable_total: embeddableTotal,\n\t\t};\n\t}\n\treturn {\n\t\t...metadata,\n\t\tpending_upsert_memory_ids,\n\t\tpending_delete_memory_ids,\n\t\tsource_model: sourceModel ?? metadata.source_model ?? null,\n\t\ttarget_model: targetModel,\n\t\trequested_model: requestedModel,\n\t\trequested_revision: requestedRevision,\n\t\tlast_cursor_id: Number(metadata.last_cursor_id ?? 0),\n\t\tprocessed_embeddable: Number(metadata.processed_embeddable ?? 0),\n\t\tembeddable_total: Number(metadata.embeddable_total ?? embeddableTotal),\n\t\tremoved_stale_rows: metadata.removed_stale_rows,\n\t};\n}\n\ntype StaleDeleteOptions = {\n\tcleanupOwner?: { job: MigrationJob };\n\tcheckFence?: () => string | null;\n};\n\ntype CurrentStaleRow = { rowid: number; memoryId: number | null };\n\nfunction collectCurrentStaleRows(\n\tdb: SqliteDatabase,\n\trowIds: number[],\n\ttargetModel: string,\n\tsignal?: AbortSignal,\n): { rows: CurrentStaleRow[]; retainedFallback: boolean } {\n\tconst selectCurrent = db\n\t\t.prepare(\"SELECT memory_id, model FROM memory_vectors WHERE rowid = ?\")\n\t\t.safeIntegers();\n\tconst rows: CurrentStaleRow[] = [];\n\tif (rowIds.some((rowid) => !Number.isSafeInteger(rowid))) {\n\t\tthrow new RangeError(\"Vector metadata IDs exceed the exact numeric range\");\n\t}\n\tfor (const rowid of rowIds) {\n\t\tif (signal?.aborted) break;\n\t\tconst current = selectCurrent.get(rowid) as\n\t\t\t| { memory_id: bigint | null; model: string }\n\t\t\t| undefined;\n\t\tif (!current || current.model === targetModel) continue;\n\t\tconst memoryId = current.memory_id === null ? null : Number(current.memory_id);\n\t\tif (memoryId !== null && !Number.isSafeInteger(memoryId)) {\n\t\t\tthrow new RangeError(\"Vector metadata IDs exceed the exact numeric range\");\n\t\t}\n\t\trows.push({ rowid, memoryId });\n\t}\n\treturn { rows, retainedFallback: false };\n}\n\nfunction deleteCoveredStaleRows(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\trows: CurrentStaleRow[],\n\tsignal?: AbortSignal,\n): { deleted: number; retainedFallback: boolean } {\n\tconst coverage = findMemoryIdsWithCurrentTargetCoverage(\n\t\tdb,\n\t\trows.flatMap((row) => (row.memoryId === null ? [] : [row.memoryId])),\n\t\ttargetModel,\n\t);\n\tconst rowIds: number[] = [];\n\tlet retainedFallback = false;\n\tfor (const row of rows) {\n\t\tif (signal?.aborted) break;\n\t\tif (row.memoryId !== null && !coverage.has(row.memoryId)) {\n\t\t\tretainedFallback = true;\n\t\t\tcontinue;\n\t\t}\n\t\trowIds.push(row.rowid);\n\t}\n\tconst { deleted } = prepareVectorWrites(db)({ deleteRowIds: rowIds, signal });\n\treturn { deleted, retainedFallback };\n}\n\nfunction deleteCheckedStaleRows(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\trowIds: number[],\n\tsignal?: AbortSignal,\n\toptions: StaleDeleteOptions = {},\n): { deleted: number; retainedFallback: boolean } {\n\treturn db\n\t\t.transaction(() => {\n\t\t\tif (options.cleanupOwner && !isCurrentCleanupJob(db, targetModel, options.cleanupOwner))\n\t\t\t\treturn { deleted: 0, retainedFallback: false };\n\t\t\tif (options.checkFence?.()) return { deleted: 0, retainedFallback: true };\n\t\t\tconst current = collectCurrentStaleRows(db, rowIds, targetModel, signal);\n\t\t\tif (signal?.aborted) return { deleted: 0, retainedFallback: current.retainedFallback };\n\t\t\tconst result = deleteCoveredStaleRows(db, targetModel, current.rows, signal);\n\t\t\treturn {\n\t\t\t\tdeleted: result.deleted,\n\t\t\t\tretainedFallback: current.retainedFallback || result.retainedFallback,\n\t\t\t};\n\t\t})\n\t\t.immediate();\n}\n\nfunction appendStaleRowIds(\n\tdb: SqliteDatabase,\n\trows: { rowid: number }[],\n\ttargetModel: string,\n\tstaleRowIds: number[],\n): number {\n\tconst selectMetadata = db.prepare(\n\t\t\"SELECT memory_id, content_hash, model FROM memory_vectors WHERE rowid = ?\",\n\t);\n\tlet cursor = 0;\n\tfor (const row of rows) {\n\t\tconst metadata = selectMetadata.get(row.rowid) as { model: string } | undefined;\n\t\tif (metadata && metadata.model !== targetModel) staleRowIds.push(row.rowid);\n\t\tcursor = row.rowid;\n\t\tif (staleRowIds.length === 250) break;\n\t}\n\treturn cursor;\n}\n\nfunction scanStaleModelVectorRows(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\tsignal?: AbortSignal,\n): {\n\trowIds: number[];\n\texhausted: boolean;\n\tscannedMaxRowId: number | null;\n} {\n\tconst batchSize = 250;\n\tif (!hasMemoryVectorRowidsShadowTable(db)) {\n\t\tconst rawRows = db\n\t\t\t.prepare(\"SELECT rowid FROM memory_vectors WHERE model != ? ORDER BY rowid ASC LIMIT ?\")\n\t\t\t.safeIntegers()\n\t\t\t.all(targetModel, batchSize) as { rowid: bigint }[];\n\t\tconst rows = exactVectorRowIdPage(rawRows);\n\t\tif (rows === null) throw new RangeError(\"Vector metadata IDs exceed the exact numeric range\");\n\t\treturn {\n\t\t\trowIds: rows.map((row) => row.rowid),\n\t\t\texhausted: rows.length < batchSize,\n\t\t\tscannedMaxRowId: null,\n\t\t};\n\t}\n\n\tconst selectRowIds = db\n\t\t.prepare(\n\t\t\t`SELECT rowid FROM ${vectorRowidsTable(db)} WHERE rowid > ? ORDER BY rowid ASC LIMIT ? /* vector-stale-scan-rowids */`,\n\t\t)\n\t\t.safeIntegers();\n\tconst staleRowIds: number[] = [];\n\tlet afterRowId = 0;\n\tlet exhausted = false;\n\twhile (staleRowIds.length < batchSize && !signal?.aborted) {\n\t\tconst rows = exactVectorRowIdPage(\n\t\t\tselectRowIds.all(afterRowId, batchSize) as { rowid: bigint }[],\n\t\t);\n\t\t// Fail through the runner instead of repeatedly rescanning an unsafe page.\n\t\tif (rows === null) throw new RangeError(\"Vector metadata IDs exceed the exact numeric range\");\n\t\tif (rows.length === 0) {\n\t\t\texhausted = true;\n\t\t\tbreak;\n\t\t}\n\t\tafterRowId = appendStaleRowIds(db, rows, targetModel, staleRowIds);\n\t\tconst lastRowId = rows.at(-1)?.rowid;\n\t\tif (rows.length < batchSize && afterRowId === lastRowId) exhausted = true;\n\t}\n\t// The watermark is the last rowid this scan actually examined. Rows inserted\n\t// above it by a concurrent writer were never inspected and must be re-checked\n\t// on the next pass, so it must not be read from MAX(rowid) after the fact.\n\tconst scannedMaxRowId = exhausted ? afterRowId : null;\n\treturn { rowIds: staleRowIds, exhausted, scannedMaxRowId };\n}\n\nfunction deleteStaleModelVectors(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\tsignal?: AbortSignal,\n\toptions: StaleDeleteOptions = {},\n): { deleted: number; exhausted: boolean; scannedMaxRowId: number | null } {\n\tif (signal?.aborted) return { deleted: 0, exhausted: false, scannedMaxRowId: null };\n\tconst scan = scanStaleModelVectorRows(db, targetModel, signal);\n\tif (signal?.aborted) return { deleted: 0, exhausted: false, scannedMaxRowId: null };\n\t// Stop after one bounded batch so the event loop can deliver shutdown before\n\t// the next migration pass. Deleted rows are the durable cleanup cursor.\n\tconst result = deleteCheckedStaleRows(db, targetModel, scan.rowIds, signal, options);\n\treturn {\n\t\tdeleted: result.deleted,\n\t\texhausted: scan.exhausted && !result.retainedFallback && !signal?.aborted,\n\t\tscannedMaxRowId: scan.scannedMaxRowId,\n\t};\n}\n\nfunction isCurrentCleanupJob(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\texpectedOwner?: { job: MigrationJob },\n): boolean {\n\tconst job = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\tconst metadata = (job?.metadata ?? {}) as MigrationMetadata;\n\treturn (\n\t\tjob?.status === \"completed\" &&\n\t\tmetadata.target_model === targetModel &&\n\t\tpendingQueuedSyncCount(metadata) === 0 &&\n\t\t(expectedOwner === undefined || JSON.stringify(job) === JSON.stringify(expectedOwner.job))\n\t);\n}\n\nfunction cleanupStaleModels(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n): { removed: number; exhausted: boolean; scannedMaxRowId: number | null } {\n\tconst cleanup = deleteStaleModelVectors(db, targetModel);\n\t// Also prune obsolete rows within the target model: coverage is a subset\n\t// check, so a memory can be \"covered\" while retaining target rows for content\n\t// that no longer exists (interrupted migration, or an edit/redaction without\n\t// vector maintenance). Leaving them lets MIN-distance recall surface stale\n\t// content after the migration reports success.\n\t// The detached catalog supports pruning under the owner's write transaction\n\t// without changing temp_store on the source connection.\n\tconst validation = prepareVectorCutoverValidation(db, targetModel);\n\ttry {\n\t\treturn {\n\t\t\tremoved: cleanup.deleted + validation.deleted,\n\t\t\texhausted: cleanup.exhausted,\n\t\t\tscannedMaxRowId: cleanup.scannedMaxRowId,\n\t\t};\n\t} finally {\n\t\tvalidation.close();\n\t}\n}\n\ntype MigrationJob = ReturnType<typeof getMaintenanceJob>;\ntype MigrationPassOwner = { job: MigrationJob; failureHandled: boolean };\n\nfunction hasInFlightMigrationJob(job: MigrationJob): boolean {\n\treturn job?.status === \"running\" || job?.status === \"pending\" || job?.status === \"failed\";\n}\n\nfunction isActiveMigrationJob(job: MigrationJob): boolean {\n\treturn job?.status === \"running\" || job?.status === \"pending\";\n}\n\nfunction sameMigrationJob(original: MigrationJob, latest: MigrationJob): boolean {\n\tif (!original || !latest) return original === latest;\n\tconst before = original.metadata ?? {};\n\tconst after = latest.metadata ?? {};\n\treturn (\n\t\t(before.job_generation ?? 0) === (after.job_generation ?? 0) &&\n\t\toriginal.started_at === latest.started_at &&\n\t\t(original.status === \"cancelled\") === (latest.status === \"cancelled\") &&\n\t\tbefore.target_model === after.target_model &&\n\t\tbefore.requested_model === after.requested_model &&\n\t\tbefore.requested_revision === after.requested_revision\n\t);\n}\n\n/** Queue revisions may change within one job without invalidating its owner. */\nfunction withMigrationJobOwner<T>(\n\tdb: SqliteDatabase,\n\towner: MigrationJob,\n\twrite: (latest: MigrationJob) => T,\n): T | undefined {\n\treturn db\n\t\t.transaction(() => {\n\t\t\tconst latest = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\t\tif (!sameMigrationJob(owner, latest)) return undefined;\n\t\t\treturn write(latest);\n\t\t})\n\t\t.immediate();\n}\n\ntype CutoverProgress = {\n\tmetadata: MigrationMetadata;\n\tprogressCurrent: number;\n\tprogressTotal: number;\n};\n\nfunction sameCutoverJob(\n\toriginal: MigrationJob,\n\tlatest: MigrationJob,\n\ttargetModel: string,\n): boolean {\n\tif (\n\t\t!original ||\n\t\t!latest ||\n\t\t!sameMigrationJob(original, latest) ||\n\t\tlatest.status === \"cancelled\" ||\n\t\tlatest.started_at !== original.started_at\n\t)\n\t\treturn false;\n\tconst before = (original.metadata ?? {}) as MigrationMetadata;\n\tconst after = (latest.metadata ?? {}) as MigrationMetadata;\n\treturn (\n\t\tafter.target_model === before.target_model &&\n\t\tafter.requested_model === before.requested_model &&\n\t\tafter.requested_revision === before.requested_revision &&\n\t\t(after.target_model == null || after.target_model === targetModel)\n\t);\n}\n\nfunction completeCoveredSyncJob(\n\tdb: SqliteDatabase,\n\towner: MigrationJob,\n\ttargetModel: string,\n\trequestMetadata: MigrationMetadata,\n): boolean {\n\treturn (\n\t\twithMigrationJobOwner(db, owner, (latest) => {\n\t\t\tconst uncovered = db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT COUNT(*) AS c FROM memory_items\n\t\t\t WHERE active = 1\n\t\t\t AND id NOT IN (SELECT DISTINCT memory_id FROM memory_vectors WHERE model = ?)`,\n\t\t\t\t)\n\t\t\t\t.get(targetModel) as { c?: number } | undefined;\n\t\t\tif (Number(uncovered?.c ?? 0) > 0) return false;\n\t\t\tconst indexedTotal = countEmbeddableActiveMemories(db);\n\t\t\tcompleteMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\t\tmessage: \"Finished re-indexing memories\",\n\t\t\t\tprogressCurrent: indexedTotal,\n\t\t\t\tprogressTotal: indexedTotal,\n\t\t\t\tmetadata: {\n\t\t\t\t\t...latest?.metadata,\n\t\t\t\t\t...requestMetadata,\n\t\t\t\t\tsource_model: null,\n\t\t\t\t\ttarget_model: targetModel,\n\t\t\t\t\tprocessed_embeddable: indexedTotal,\n\t\t\t\t\tembeddable_total: indexedTotal,\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn true;\n\t\t}) !== false\n\t);\n}\n\nfunction completeEmptySourceMigration(\n\tdb: SqliteDatabase,\n\towner: MigrationJob,\n\ttargetModel: string,\n\tsourceModel: string,\n\trequestMetadata: MigrationMetadata,\n): void {\n\twithMigrationJobOwner(db, owner, (latest) => {\n\t\tif (countEmbeddableActiveMemories(db) > 0) return;\n\t\tconst cleanup = cleanupStaleModels(db, targetModel);\n\t\tconst staleScanExhausted = cleanup.exhausted && cleanup.scannedMaxRowId != null;\n\t\tconst job = startVectorMigrationJob(db, {\n\t\t\ttitle: \"Re-indexing memories\",\n\t\t\tmessage:\n\t\t\t\tcleanup.removed > 0\n\t\t\t\t\t? `Removed ${cleanup.removed} stale vector rows`\n\t\t\t\t\t: \"No embeddable memories to re-index\",\n\t\t\tprogressTotal: 0,\n\t\t\tmetadata: {\n\t\t\t\t...requestMetadata,\n\t\t\t\t...mergeQueuedSyncMemoryIds(latest?.metadata ?? {}, {\n\t\t\t\t\tupsertMemoryIds: [],\n\t\t\t\t\tdeleteMemoryIds: [],\n\t\t\t\t}),\n\t\t\t\tqueue_revision: latest?.metadata?.queue_revision,\n\t\t\t\tsource_model: sourceModel,\n\t\t\t\ttarget_model: targetModel,\n\t\t\t\tremoved_stale_rows: cleanup.removed,\n\t\t\t\tcleanup_pending: !cleanup.exhausted,\n\t\t\t\tstale_scan_exhausted: staleScanExhausted || undefined,\n\t\t\t\tstale_scan_exhausted_max_rowid: staleScanExhausted\n\t\t\t\t\t? (cleanup.scannedMaxRowId ?? undefined)\n\t\t\t\t\t: undefined,\n\t\t\t},\n\t\t});\n\t\tcompleteMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\tprogressCurrent: 0,\n\t\t\tprogressTotal: 0,\n\t\t\tmetadata: job.metadata,\n\t\t});\n\t});\n}\n\nfunction writeCutoverFailure(\n\tdb: SqliteDatabase,\n\tprogress: CutoverProgress,\n\tuncovered: number,\n): void {\n\tfailMaintenanceJob(\n\t\tdb,\n\t\tVECTOR_MODEL_MIGRATION_JOB,\n\t\t`Target vector coverage is incomplete for ${describeIncompleteTargetMemories(uncovered)}`,\n\t\t{\n\t\t\tmessage: \"Vector re-indexing stopped before cutover; existing valid vectors remain available\",\n\t\t\tmetadata: {\n\t\t\t\t...progress.metadata,\n\t\t\t\treconciliation_target_coverage_complete: undefined,\n\t\t\t\tlast_cursor_id: 0,\n\t\t\t\tprocessed_embeddable: 0,\n\t\t\t\tcutover_retry_count: 0,\n\t\t\t\tuncovered_target_memories: uncovered,\n\t\t\t},\n\t\t},\n\t);\n}\n\nfunction writeValidatedCutover(\n\tdb: SqliteDatabase,\n\tprogress: CutoverProgress,\n\tvalidation: VectorCutoverValidation,\n\tshouldStop?: () => boolean,\n): MigrationJob {\n\tconst retryReason = validation.retryReason();\n\tif (retryReason || shouldStop?.()) {\n\t\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\t...progress,\n\t\t\tstatus: \"running\",\n\t\t\tmessage: retryReason ?? \"Cutover paused during shutdown; retrying\",\n\t\t\tmetadata: {\n\t\t\t\t...progress.metadata,\n\t\t\t\tcutover_retry_count: Number(progress.metadata.cutover_retry_count ?? 0) + 1,\n\t\t\t},\n\t\t});\n\t\treturn null;\n\t}\n\tif (validation.uncovered > 0) {\n\t\twriteCutoverFailure(db, progress, validation.uncovered);\n\t\treturn null;\n\t}\n\treturn completeMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t...progress,\n\t\tmessage: \"Finished re-indexing; removing stale vectors\",\n\t\tmetadata: {\n\t\t\t...progress.metadata,\n\t\t\tcleanup_pending: true,\n\t\t\tstale_scan_exhausted: undefined,\n\t\t\tstale_scan_exhausted_max_rowid: undefined,\n\t\t\tcutover_retry_count: 0,\n\t\t\tuncovered_target_memories: undefined,\n\t\t},\n\t});\n}\n\nfunction commitMigrationCutover(\n\tdb: SqliteDatabase,\n\toptions: {\n\t\toriginalJob: MigrationJob;\n\t\ttargetModel: string;\n\t\tprogress: CutoverProgress;\n\t\tvalidation: VectorCutoverValidation;\n\t\tshouldStop?: () => boolean;\n\t},\n): (CutoverProgress & { cleanupJob: NonNullable<MigrationJob> }) | null {\n\treturn db\n\t\t.transaction(() => {\n\t\t\tconst latest = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\t\tif (!sameCutoverJob(options.originalJob, latest, options.targetModel)) return null;\n\t\t\tconst latestMetadata = (latest?.metadata ?? {}) as MigrationMetadata;\n\t\t\tconst sameQueue = sameQueuedSyncWork(latestMetadata, options.progress.metadata);\n\t\t\tif (sameQueue && JSON.stringify(latest) !== JSON.stringify(options.originalJob)) return null;\n\t\t\tconst progress: CutoverProgress = {\n\t\t\t\t...options.progress,\n\t\t\t\tmetadata: {\n\t\t\t\t\t...(sameQueue ? options.progress.metadata : latestMetadata),\n\t\t\t\t\tlast_cursor_id: options.progress.metadata.last_cursor_id,\n\t\t\t\t\tprocessed_embeddable: options.progress.progressCurrent,\n\t\t\t\t\tembeddable_total: options.progress.progressTotal,\n\t\t\t\t\tremoved_stale_rows:\n\t\t\t\t\t\tMath.max(\n\t\t\t\t\t\t\tNumber(latestMetadata.removed_stale_rows ?? 0),\n\t\t\t\t\t\t\tNumber(options.progress.metadata.removed_stale_rows ?? 0),\n\t\t\t\t\t\t) + options.validation.deleted,\n\t\t\t\t},\n\t\t\t};\n\t\t\tif (!sameQueue || pendingQueuedSyncCount(latestMetadata) > 0) {\n\t\t\t\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\t\t\t...progress,\n\t\t\t\t\tstatus: \"running\",\n\t\t\t\t\tmessage: \"Draining vector changes queued before cutover\",\n\t\t\t\t});\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst cleanupJob = writeValidatedCutover(\n\t\t\t\tdb,\n\t\t\t\tprogress,\n\t\t\t\toptions.validation,\n\t\t\t\toptions.shouldStop,\n\t\t\t);\n\t\t\treturn cleanupJob ? { ...progress, cleanupJob } : null;\n\t\t})\n\t\t.immediate();\n}\n\nasync function finalizeMigrationCutover(\n\tdb: SqliteDatabase,\n\towner: { job: MigrationJob },\n\ttargetModel: string,\n\tmetadata: MigrationMetadata,\n\tlastCursorId: number,\n\tprocessedEmbeddable: number,\n\tembeddableTotal: number,\n\tsignal?: AbortSignal,\n\tshouldStop?: () => boolean,\n): Promise<void> {\n\tconst originalJob = owner.job;\n\tconst validation = prepareVectorCutoverValidation(db, targetModel, { signal });\n\ttry {\n\t\tconst committed = commitMigrationCutover(db, {\n\t\t\toriginalJob,\n\t\t\ttargetModel,\n\t\t\tvalidation,\n\t\t\tshouldStop,\n\t\t\tprogress: {\n\t\t\t\tmetadata: { ...metadata, last_cursor_id: lastCursorId },\n\t\t\t\tprogressCurrent: processedEmbeddable,\n\t\t\t\tprogressTotal: embeddableTotal,\n\t\t\t},\n\t\t});\n\t\tif (!committed) return;\n\t\towner.job = committed.cleanupJob;\n\t\tvalidation.noteOwnWrites();\n\t\tawait drainStaleModelVectors(db, targetModel, {\n\t\t\texpectedJob: committed.cleanupJob,\n\t\t\tvalidation,\n\t\t\tpreviouslyRemoved: Number(committed.metadata.removed_stale_rows ?? 0),\n\t\t\tprunedTargetRows: 0,\n\t\t\tsignal,\n\t\t\tshouldStop,\n\t\t});\n\t} finally {\n\t\tvalidation.close();\n\t}\n}\n\nfunction detectSourceModel(db: SqliteDatabase, targetModel: string): string | null {\n\tconst rows = vectorModels(db).filter((row) => row.model !== targetModel);\n\treturn rows[0]?.model ?? null;\n}\n\nfunction mergedRemovedRows(\n\tlatestMetadata: MigrationMetadata,\n\tpreviouslyRemoved: number,\n\tnewlyRemoved: number,\n): number {\n\treturn Math.max(Number(latestMetadata.removed_stale_rows ?? 0), previouslyRemoved) + newlyRemoved;\n}\n\nfunction deferCompletedCleanup(\n\tdb: SqliteDatabase,\n\texpectedCleanup: { job: MigrationJob; targetModel: string },\n\tpreviouslyRemoved: number,\n\tprunedTargetRows: number,\n\tmessage: string,\n): void {\n\tdb.transaction(() => {\n\t\tif (!isCurrentCleanupJob(db, expectedCleanup.targetModel)) return;\n\t\tconst latestJob = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\t// The unlocked fence/shutdown check may have raced a replacement job or\n\t\t// queued work. Only the exact cleanup job we checked may be deferred.\n\t\tif (JSON.stringify(latestJob) !== JSON.stringify(expectedCleanup.job)) return;\n\t\tconst latestMetadata = (latestJob?.metadata ?? {}) as MigrationMetadata;\n\t\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\tstatus: \"completed\",\n\t\t\tmessage,\n\t\t\tmetadata: {\n\t\t\t\t...latestMetadata,\n\t\t\t\tremoved_stale_rows: mergedRemovedRows(latestMetadata, previouslyRemoved, prunedTargetRows),\n\t\t\t\tcleanup_pending: true,\n\t\t\t\tstale_scan_exhausted: undefined,\n\t\t\t\tstale_scan_exhausted_max_rowid: undefined,\n\t\t\t\treconciliation_target_coverage_complete: undefined,\n\t\t\t},\n\t\t});\n\t}).immediate();\n}\n\nfunction restartMigrationForIncompleteCoverage(\n\tdb: SqliteDatabase,\n\tpreviouslyRemoved: number,\n\tprunedTargetRows: number,\n\tuncovered: number,\n): void {\n\tdb.transaction(() => {\n\t\tconst latestJob = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\tconst latestMetadata = (latestJob?.metadata ?? {}) as MigrationMetadata;\n\t\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\tstatus: \"pending\",\n\t\t\tmessage: \"Target coverage changed before cleanup; rebuilding missing vectors\",\n\t\t\tprogressCurrent: 0,\n\t\t\tprogressTotal: null,\n\t\t\tmetadata: {\n\t\t\t\t...latestMetadata,\n\t\t\t\tcleanup_pending: false,\n\t\t\t\tstale_scan_exhausted: undefined,\n\t\t\t\tstale_scan_exhausted_max_rowid: undefined,\n\t\t\t\treconciliation_target_coverage_complete: undefined,\n\t\t\t\tsource_model: null,\n\t\t\t\tlast_cursor_id: 0,\n\t\t\t\tprocessed_embeddable: 0,\n\t\t\t\tembeddable_total: undefined,\n\t\t\t\tremoved_stale_rows: mergedRemovedRows(latestMetadata, previouslyRemoved, prunedTargetRows),\n\t\t\t\tuncovered_target_memories: uncovered,\n\t\t\t},\n\t\t});\n\t}).immediate();\n}\n\nfunction cleanupResultMessage(options: {\n\tcompleted: boolean;\n\tremoved: number;\n\tretryReason: string | null;\n\tcleanup: { exhausted: boolean; deleted: number };\n}): string {\n\tif (options.completed)\n\t\treturn options.removed > 0\n\t\t\t? `Finished re-indexing and removed ${options.removed} stale vector rows`\n\t\t\t: \"Finished re-indexing memories\";\n\tif (!options.cleanup.exhausted && options.cleanup.deleted === 0)\n\t\treturn \"Memory changes arrived during cleanup; retrying\";\n\treturn options.retryReason ?? \"Finished re-indexing; removing stale vectors\";\n}\n\nfunction recordResumedCleanupResult(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\toptions: {\n\t\texpectedJob: MigrationJob;\n\t\tcleanup: { deleted: number; exhausted: boolean; scannedMaxRowId: number | null };\n\t\tvalidation: VectorCutoverValidation;\n\t\tpreviouslyRemoved: number;\n\t\tprunedTargetRows: number;\n\t},\n): { completed: boolean; job: NonNullable<MigrationJob> } | null {\n\treturn db\n\t\t.transaction(() => {\n\t\t\tif (!isCurrentCleanupJob(db, targetModel, { job: options.expectedJob })) return null;\n\t\t\tconst latestJob = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\t\tconst latestMetadata = (latestJob?.metadata ?? {}) as MigrationMetadata;\n\t\t\tconst newlyRemoved = options.prunedTargetRows + options.cleanup.deleted;\n\t\t\tconst removed = mergedRemovedRows(latestMetadata, options.previouslyRemoved, newlyRemoved);\n\t\t\tconst retryReason =\n\t\t\t\toptions.validation.corpusRetryReason() ??\n\t\t\t\t(options.cleanup.exhausted ? options.validation.metadataRetryReason() : null);\n\t\t\tconst cleanupCompleted = options.cleanup.exhausted && !retryReason;\n\t\t\tconst exhaustedMaxRowId = cleanupCompleted ? options.cleanup.scannedMaxRowId : null;\n\t\t\tconst message = cleanupResultMessage({\n\t\t\t\tcompleted: cleanupCompleted,\n\t\t\t\tremoved,\n\t\t\t\tretryReason,\n\t\t\t\tcleanup: options.cleanup,\n\t\t\t});\n\t\t\tconst job = updateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\t\tstatus: \"completed\",\n\t\t\t\tmessage,\n\t\t\t\tmetadata: {\n\t\t\t\t\t...latestMetadata,\n\t\t\t\t\tremoved_stale_rows: removed,\n\t\t\t\t\tcleanup_pending: !cleanupCompleted,\n\t\t\t\t\tstale_scan_exhausted: cleanupCompleted || undefined,\n\t\t\t\t\tstale_scan_exhausted_max_rowid: exhaustedMaxRowId ?? undefined,\n\t\t\t\t\treconciliation_target_coverage_complete: undefined,\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn job ? { completed: cleanupCompleted, job } : null;\n\t\t})\n\t\t.immediate();\n}\n\nasync function yieldToCleanupInterrupts(): Promise<void> {\n\tawait new Promise<void>((resolve) => setImmediate(resolve));\n}\n\nfunction cleanupShouldPause(options: {\n\tsignal?: AbortSignal;\n\tshouldStop?: () => boolean;\n}): boolean {\n\tif (options.signal?.aborted) return true;\n\treturn options.shouldStop?.() === true;\n}\n\nasync function drainStaleModelVectors(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\toptions: {\n\t\texpectedJob: MigrationJob;\n\t\tvalidation: VectorCutoverValidation;\n\t\tpreviouslyRemoved: number;\n\t\tprunedTargetRows: number;\n\t\tsignal?: AbortSignal;\n\t\tshouldStop?: () => boolean;\n\t},\n): Promise<boolean> {\n\tlet prunedTargetRows = options.prunedTargetRows;\n\tlet expectedJob = options.expectedJob;\n\twhile (true) {\n\t\tconst cleanupJob = expectedJob;\n\t\tif (!isCurrentCleanupJob(db, targetModel, { job: cleanupJob })) return false;\n\t\tconst reason = options.validation.corpusRetryReason();\n\t\tif (reason) {\n\t\t\tdeferCompletedCleanup(\n\t\t\t\tdb,\n\t\t\t\t{ job: cleanupJob, targetModel },\n\t\t\t\toptions.previouslyRemoved,\n\t\t\t\tprunedTargetRows,\n\t\t\t\t\"Memory changes arrived during cleanup; retrying\",\n\t\t\t);\n\t\t\treturn false;\n\t\t}\n\t\tif (cleanupShouldPause(options)) {\n\t\t\tdeferCompletedCleanup(\n\t\t\t\tdb,\n\t\t\t\t{ job: cleanupJob, targetModel },\n\t\t\t\toptions.previouslyRemoved,\n\t\t\t\tprunedTargetRows,\n\t\t\t\t\"Cleanup paused during shutdown; retrying\",\n\t\t\t);\n\t\t\treturn false;\n\t\t}\n\t\tconst cleanup = deleteStaleModelVectors(db, targetModel, options.signal, {\n\t\t\tcleanupOwner: { job: cleanupJob },\n\t\t\tcheckFence: options.validation.corpusRetryReason,\n\t\t});\n\t\toptions.validation.noteOwnWrites();\n\t\tconst recorded = recordResumedCleanupResult(db, targetModel, {\n\t\t\texpectedJob: cleanupJob,\n\t\t\tcleanup,\n\t\t\tvalidation: options.validation,\n\t\t\tpreviouslyRemoved: options.previouslyRemoved,\n\t\t\tprunedTargetRows,\n\t\t});\n\t\toptions.validation.noteOwnWrites();\n\t\tif (!recorded) return false;\n\t\texpectedJob = recorded.job;\n\t\tif (recorded.completed) return true;\n\t\tif (cleanupShouldPause(options)) return false;\n\t\tif (cleanup.deleted === 0) return false;\n\t\tprunedTargetRows = 0;\n\t\tawait yieldToCleanupInterrupts();\n\t}\n}\n\ntype CompletedCleanupPassResult = {\n\tcontinueMigration: boolean;\n\trestartFromBeginning: boolean;\n\tstaleScanExhausted: boolean;\n\tvalidatedTargetCoverageComplete: boolean;\n};\n\nfunction acceptCompletedCleanupValidation(\n\tdb: SqliteDatabase,\n\toptions: {\n\t\toriginalJob: MigrationJob;\n\t\ttargetModel: string;\n\t\tvalidation: VectorCutoverValidation;\n\t\tpreviouslyRemoved: number;\n\t\tshouldStop?: () => boolean;\n\t},\n): boolean {\n\treturn db\n\t\t.transaction(() => {\n\t\t\tif (!isCurrentCleanupJob(db, options.targetModel, { job: options.originalJob })) return false;\n\t\t\tconst reason = options.validation.retryReason();\n\t\t\tif (reason || options.shouldStop?.()) {\n\t\t\t\tdeferCompletedCleanup(\n\t\t\t\t\tdb,\n\t\t\t\t\t{ job: options.originalJob, targetModel: options.targetModel },\n\t\t\t\t\toptions.previouslyRemoved,\n\t\t\t\t\toptions.validation.deleted,\n\t\t\t\t\treason ?? \"Cleanup paused during shutdown; retrying\",\n\t\t\t\t);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (options.validation.uncovered > 0) {\n\t\t\t\trestartMigrationForIncompleteCoverage(\n\t\t\t\t\tdb,\n\t\t\t\t\toptions.previouslyRemoved,\n\t\t\t\t\toptions.validation.deleted,\n\t\t\t\t\toptions.validation.uncovered,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn true;\n\t\t})\n\t\t.immediate();\n}\n\nfunction readCompletedScanFence(db: SqliteDatabase): string {\n\treturn JSON.stringify({\n\t\t...readVectorCorpusFence(db),\n\t\tdataVersion: Number(db.pragma(\"data_version\", { simple: true })),\n\t\ttotalChanges: Number(db.prepare(\"SELECT total_changes()\").pluck().get()),\n\t});\n}\n\nfunction prepareCompletedCleanupOwner(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\texpectedJob: MigrationJob,\n) {\n\tif (!isCurrentCleanupJob(db, targetModel, { job: expectedJob })) return null;\n\tconst metadata = (expectedJob?.metadata ?? {}) as MigrationMetadata;\n\tconst before = readCompletedScanFence(db);\n\t// Compatibility scans may walk the entire index; do not reserve the writer here.\n\tconst staleScan = checkCompletedStaleScan(db, targetModel, metadata);\n\treturn db\n\t\t.transaction(() => {\n\t\t\tif (!isCurrentCleanupJob(db, targetModel, { job: expectedJob })) return null;\n\t\t\tif (readCompletedScanFence(db) !== before) return null;\n\t\t\tif (staleScan.metadata !== metadata) {\n\t\t\t\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, { metadata: staleScan.metadata });\n\t\t\t}\n\t\t\tif (staleScan.canReturn) return null;\n\t\t\t// Keep the checked owner, including any watermark invalidation, across validation.\n\t\t\treturn {\n\t\t\t\tmetadata: staleScan.metadata,\n\t\t\t\tjob: getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB),\n\t\t\t};\n\t\t})\n\t\t.immediate();\n}\n\nasync function finishCompletedCleanupPass(\n\tdb: SqliteDatabase,\n\ttargetModel: string,\n\tmetadata: MigrationMetadata,\n\toriginalJob: MigrationJob,\n\tsignal?: AbortSignal,\n\tshouldStop?: () => boolean,\n): Promise<CompletedCleanupPassResult> {\n\tconst stop: CompletedCleanupPassResult = {\n\t\tcontinueMigration: false,\n\t\trestartFromBeginning: false,\n\t\tstaleScanExhausted: false,\n\t\tvalidatedTargetCoverageComplete: false,\n\t};\n\tif (signal?.aborted) return stop;\n\n\tconst previouslyRemoved = Number(metadata.removed_stale_rows ?? 0);\n\tconst validation = prepareVectorCutoverValidation(db, targetModel, { signal, phase: \"cleanup-\" });\n\tconst prunedTargetRows = validation.deleted;\n\tlet accepted: boolean;\n\ttry {\n\t\taccepted = acceptCompletedCleanupValidation(db, {\n\t\t\toriginalJob,\n\t\t\ttargetModel,\n\t\t\tvalidation,\n\t\t\tpreviouslyRemoved,\n\t\t\tshouldStop,\n\t\t});\n\t\tif (!accepted) return stop;\n\t\tif (validation.uncovered > 0) {\n\t\t\treturn {\n\t\t\t\tcontinueMigration: true,\n\t\t\t\trestartFromBeginning: false,\n\t\t\t\tstaleScanExhausted: false,\n\t\t\t\tvalidatedTargetCoverageComplete: false,\n\t\t\t};\n\t\t}\n\t\tif (!metadata.cleanup_pending) {\n\t\t\treturn {\n\t\t\t\tcontinueMigration: true,\n\t\t\t\trestartFromBeginning: true,\n\t\t\t\tstaleScanExhausted: metadata.stale_scan_exhausted === true,\n\t\t\t\tvalidatedTargetCoverageComplete: false,\n\t\t\t};\n\t\t}\n\n\t\tconst cleanupCompleted = await drainStaleModelVectors(db, targetModel, {\n\t\t\texpectedJob: originalJob,\n\t\t\tvalidation,\n\t\t\tpreviouslyRemoved,\n\t\t\tprunedTargetRows,\n\t\t\tsignal,\n\t\t\tshouldStop,\n\t\t});\n\t\tif (!cleanupCompleted) return stop;\n\t\treturn {\n\t\t\tcontinueMigration: true,\n\t\t\trestartFromBeginning: true,\n\t\t\tstaleScanExhausted: true,\n\t\t\t// Cleanup yields between batches. Per-row deletes remain safe, but a\n\t\t\t// whole-corpus proof cannot be carried across those yields.\n\t\t\tvalidatedTargetCoverageComplete: false,\n\t\t};\n\t} finally {\n\t\tvalidation.close();\n\t}\n}\n\nfunction resolveMigrationStartMessage(\n\tsourceModel: string | null,\n\ttargetModel: string,\n\ttargetDisplay: string,\n): string {\n\tconst servesCompatibleLegacySource =\n\t\tsourceModel === LEGACY_DEFAULT_EMBEDDING_MODEL &&\n\t\ttargetModel === DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL;\n\tif (servesCompatibleLegacySource) {\n\t\treturn `Building ${targetDisplay} vectors while semantic search continues on the compatible legacy index`;\n\t}\n\tif (sourceModel) {\n\t\treturn `Building ${targetDisplay} vectors while semantic search uses FTS-only`;\n\t}\n\treturn `Building ${targetDisplay} vectors`;\n}\n\nfunction preservesCancelledMigration(job: MaintenanceJobSnapshot | null): boolean {\n\treturn (\n\t\tjob?.status === \"cancelled\" && job.metadata?.local_repair_preserves_migration_state === true\n\t);\n}\n\nfunction prepareMigrationJob(db: SqliteDatabase, job: MigrationJob): MigrationJob | undefined {\n\tif (!job || job.status === \"cancelled\" || !job.metadata?.local_repair_preserves_migration_state) {\n\t\treturn job;\n\t}\n\t// Failed jobs retry automatically. Only cancelled jobs keep the local-repair-only policy.\n\treturn db\n\t\t.transaction(() => {\n\t\t\tconst latestJob = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\t\tif (!sameMigrationJob(job, latestJob)) return undefined;\n\t\t\treturn updateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\t\tmetadata: { ...latestJob?.metadata, local_repair_preserves_migration_state: undefined },\n\t\t\t});\n\t\t})\n\t\t.immediate();\n}\n\nasync function resolveMigrationClient(\n\tdb: SqliteDatabase,\n\texistingJob: MaintenanceJobSnapshot | null,\n): Promise<EmbeddingClient | null> {\n\tconst isInFlightJob = isActiveMigrationJob(existingJob);\n\tif (isEmbeddingDisabled()) {\n\t\tif (isInFlightJob) {\n\t\t\twithMigrationJobOwner(db, existingJob, () =>\n\t\t\t\tfailMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, \"Embeddings are disabled\", {\n\t\t\t\t\tmessage: \"Vector re-indexing is waiting for embeddings to be enabled\",\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t...(existingJob?.metadata ?? {}),\n\t\t\t\t\t\treconciliation_target_coverage_complete: undefined,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\treturn null;\n\t}\n\tconst client = await getEmbeddingClient();\n\tif (!client) {\n\t\tif (isInFlightJob) {\n\t\t\twithMigrationJobOwner(db, existingJob, () =>\n\t\t\t\tfailMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, \"Embedding client unavailable\", {\n\t\t\t\t\tmessage: \"Vector re-indexing is waiting for the embedding client\",\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t...(existingJob?.metadata ?? {}),\n\t\t\t\t\t\treconciliation_target_coverage_complete: undefined,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\treturn null;\n\t}\n\treturn client;\n}\n\nasync function drainLocalRepairsWithoutResumingCancelledMigration(\n\tdb: SqliteDatabase,\n\tjob: MaintenanceJobSnapshot | null,\n\toptions: { batchSize?: number; signal?: AbortSignal },\n): Promise<boolean> {\n\tif (!job || !preservesCancelledMigration(job)) return false;\n\tif (pendingQueuedSyncCount(job.metadata ?? {}) === 0) return true;\n\tconst client = await resolveMigrationClient(db, job);\n\tif (!client) return true;\n\tawait runQueuedSyncVectorWork(\n\t\tdb,\n\t\tjob,\n\t\tclient,\n\t\tresolveEmbeddingClientVectorIdentityLabel(client),\n\t\tMath.max(1, options.batchSize ?? 50),\n\t\toptions.signal,\n\t);\n\treturn true;\n}\n\nexport async function runVectorMigrationPass(\n\tdb: SqliteDatabase,\n\toptions: { batchSize?: number; signal?: AbortSignal; shouldStop?: () => boolean } = {},\n): Promise<void> {\n\tawait runTrackedVectorMigrationPass(db, options, { job: null, failureHandled: false });\n}\n\nasync function runTrackedVectorMigrationPass(\n\tdb: SqliteDatabase,\n\toptions: { batchSize?: number; signal?: AbortSignal; shouldStop?: () => boolean },\n\towner: MigrationPassOwner,\n): Promise<void> {\n\towner.failureHandled = false;\n\ttry {\n\t\towner.job = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\tconst preparedJob = prepareMigrationJob(db, owner.job);\n\t\tif (preparedJob === undefined) return;\n\t\towner.job = preparedJob;\n\t\tawait runOwnedVectorMigrationPass(db, options, owner);\n\t} catch (error) {\n\t\trecordOwnedMigrationFailure(db, error, owner);\n\t\tthrow error;\n\t}\n}\n\nfunction recordOwnedMigrationFailure(\n\tdb: SqliteDatabase,\n\terror: unknown,\n\towner: MigrationPassOwner,\n): void {\n\towner.failureHandled = true;\n\t// Allocation failures leave the previous job intact, including its error.\n\tif (error instanceof VectorMigrationJobGenerationError || isTransientSqliteBusy(error)) return;\n\ttry {\n\t\trecordFailedMigrationJob(db, error, owner.job);\n\t} catch (writeError) {\n\t\tif (isTransientSqliteBusy(writeError)) {\n\t\t\tconsole.warn(\"Vector migration runner failed\", error);\n\t\t\tthrow writeError;\n\t\t}\n\t\tconsole.warn(\"Vector migration runner could not record its failure\", writeError);\n\t}\n}\n\nasync function runOwnedVectorMigrationPass(\n\tdb: SqliteDatabase,\n\toptions: { batchSize?: number; signal?: AbortSignal; shouldStop?: () => boolean },\n\towner: { job: MigrationJob },\n): Promise<void> {\n\tlet existingJob = owner.job;\n\tif (await drainLocalRepairsWithoutResumingCancelledMigration(db, existingJob, options)) return;\n\tconst client = await resolveMigrationClient(db, existingJob);\n\tif (!client) return;\n\tif (!withMigrationJobOwner(db, existingJob, () => true)) return;\n\tif (existingJob?.status === \"cancelled\") return;\n\tconst targetModel = resolveEmbeddingClientVectorIdentityLabel(client);\n\tconst requestedModel = client.model;\n\tconst requestedRevision = client.identity?.requestedRevision ?? client.identity?.revision;\n\tif (!requestedRevision) {\n\t\tthrow new TypeError(\"Embedding runtime identity is required to migrate persisted vectors\");\n\t}\n\tconst requestMetadata = {\n\t\trequested_model: requestedModel,\n\t\trequested_revision: requestedRevision,\n\t};\n\tconst targetDisplay = client.identity?.revision\n\t\t? `${client.model}@${client.identity.revision.slice(0, 12)}`\n\t\t: client.model;\n\tconst effectiveBatchSize = Math.max(1, options.batchSize ?? 50);\n\tconst existingMetadata = (existingJob?.metadata ?? {}) as MigrationMetadata;\n\tconst queuedSyncWorkCount =\n\t\tmetadataMemoryIds(existingMetadata.pending_upsert_memory_ids).length +\n\t\tmetadataMemoryIds(existingMetadata.pending_delete_memory_ids).length;\n\tlet restartCompletedMigration = false;\n\tlet reconciliationTargetCoverageComplete = false;\n\tconst completedMetadata = existingMetadata;\n\tif (\n\t\texistingJob?.status === \"completed\" &&\n\t\tcompletedMetadata.target_model === targetModel &&\n\t\tqueuedSyncWorkCount === 0\n\t) {\n\t\tconst cleanupOwner = prepareCompletedCleanupOwner(db, targetModel, existingJob);\n\t\tif (!cleanupOwner) return;\n\t\tconst cleanupResult = await finishCompletedCleanupPass(\n\t\t\tdb,\n\t\t\ttargetModel,\n\t\t\tcleanupOwner.metadata,\n\t\t\tcleanupOwner.job,\n\t\t\toptions.signal,\n\t\t\toptions.shouldStop,\n\t\t);\n\t\tif (\n\t\t\t!cleanupResult.continueMigration ||\n\t\t\toptions.signal?.aborted ||\n\t\t\t(cleanupResult.restartFromBeginning &&\n\t\t\t\t(cleanupResult.staleScanExhausted || !hasSourceModelVectors(db, targetModel)))\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\trestartCompletedMigration = cleanupResult.restartFromBeginning;\n\t\treconciliationTargetCoverageComplete = cleanupResult.validatedTargetCoverageComplete;\n\t\tconst refreshed = withMigrationJobOwner(db, existingJob, (latest) => latest);\n\t\tif (!refreshed) return;\n\t\texistingJob = refreshed;\n\t\towner.job = existingJob;\n\t}\n\tif (existingJob) {\n\t\tconst queuedSyncWork = await runQueuedSyncVectorWork(\n\t\t\tdb,\n\t\t\texistingJob,\n\t\t\tclient,\n\t\t\ttargetModel,\n\t\t\teffectiveBatchSize,\n\t\t\toptions.signal,\n\t\t);\n\t\tif (queuedSyncWork.completed || queuedSyncWork.superseded || options.signal?.aborted) {\n\t\t\treturn;\n\t\t}\n\t\tif (drainsQueuedSyncBeforeCutover(queuedSyncWork.metadata)) {\n\t\t\treturn;\n\t\t}\n\t\towner.job = queuedSyncWork.job ?? existingJob;\n\t\tconst refreshed = withMigrationJobOwner(db, owner.job, (latest) => latest);\n\t\tif (!refreshed) return;\n\t\texistingJob = refreshed;\n\t\towner.job = existingJob;\n\t}\n\tconst sourceModel = detectSourceModel(db, targetModel);\n\tconst hasInFlightJob = hasInFlightMigrationJob(existingJob);\n\t// An incremental job may finish when its queue drains. Full scans must\n\t// still visit every memory so backfillVectors can repair partial chunks.\n\tconst existingMeta = (existingJob?.metadata ?? {}) as MigrationMetadata;\n\tconst existingJobTrigger = existingMeta.trigger;\n\t// Bootstrap is a fresh corpus scan. An old row for each ID does not prove\n\t// current chunk coverage, especially for edits below the previous cursor.\n\tconst fromSyncTrigger = existingJobTrigger === SYNC_INCREMENTAL_TRIGGER;\n\tconst hasKnownIncompleteCoverage = Number(existingMeta.uncovered_target_memories ?? 0) > 0;\n\tif (!sourceModel && fromSyncTrigger && hasInFlightJob && !hasKnownIncompleteCoverage) {\n\t\tif (completeCoveredSyncJob(db, existingJob, targetModel, requestMetadata)) return;\n\t}\n\t// Use cached embeddable_total from an in-progress job to avoid a full table scan per tick.\n\t// Only recompute when starting a fresh migration or when the job is terminal.\n\tconst isResumingJob = isActiveMigrationJob(existingJob);\n\tconst embeddableTotal =\n\t\tisResumingJob && existingMeta.target_model === targetModel && existingMeta.embeddable_total\n\t\t\t? Number(existingMeta.embeddable_total)\n\t\t\t: countEmbeddableActiveMemories(db);\n\tif (embeddableTotal <= 0 && hasInFlightJob && !sourceModel) {\n\t\twithMigrationJobOwner(db, existingJob, () =>\n\t\t\tcompleteMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\t\tmessage: \"No embeddable memories to re-index\",\n\t\t\t\tprogressCurrent: 0,\n\t\t\t\tprogressTotal: 0,\n\t\t\t\tmetadata: {\n\t\t\t\t\t...existingMeta,\n\t\t\t\t\t...requestMetadata,\n\t\t\t\t\tlast_cursor_id: 0,\n\t\t\t\t\tprocessed_embeddable: 0,\n\t\t\t\t\tembeddable_total: 0,\n\t\t\t\t},\n\t\t\t}),\n\t\t);\n\t\treturn;\n\t}\n\tif (sourceModel && embeddableTotal <= 0) {\n\t\tcompleteEmptySourceMigration(db, existingJob, targetModel, sourceModel, requestMetadata);\n\t\treturn;\n\t}\n\n\tconst job = existingJob;\n\tlet metadata = nextMigrationMetadata(\n\t\tjob,\n\t\tsourceModel,\n\t\ttargetModel,\n\t\trequestedModel,\n\t\trequestedRevision,\n\t\tembeddableTotal,\n\t\t{\n\t\t\trestartFromBeginning: restartCompletedMigration,\n\t\t\treconciliationTargetCoverageComplete,\n\t\t},\n\t);\n\tif (!job || job.status === \"completed\" || job.status === \"failed\") {\n\t\tconst started = withMigrationJobOwner(db, job, (latest) =>\n\t\t\tstartVectorMigrationJob(db, {\n\t\t\t\ttitle: \"Re-indexing memories\",\n\t\t\t\tmessage: resolveMigrationStartMessage(sourceModel, targetModel, targetDisplay),\n\t\t\t\tprogressTotal: embeddableTotal,\n\t\t\t\tmetadata: {\n\t\t\t\t\t...metadata,\n\t\t\t\t\t...mergeQueuedSyncMemoryIds(latest?.metadata ?? {}, {\n\t\t\t\t\t\tupsertMemoryIds: [],\n\t\t\t\t\t\tdeleteMemoryIds: [],\n\t\t\t\t\t}),\n\t\t\t\t\tqueue_revision: latest?.metadata?.queue_revision,\n\t\t\t\t},\n\t\t\t}),\n\t\t);\n\t\tif (!started) return;\n\t\towner.job = started;\n\t\tmetadata = started.metadata as MigrationMetadata;\n\t}\n\n\tconst batchRows = selectNextMigrationBatch(db, metadata.last_cursor_id ?? 0, effectiveBatchSize);\n\tconst batchIds = batchRows.map((row) => row.id);\n\tconst embeddableInBatch = batchRows.filter(isEmbeddableMemory).length;\n\tconst lastCursorId = batchRows.at(-1)?.id ?? metadata.last_cursor_id ?? 0;\n\tconst processedEmbeddable = Math.min(\n\t\tembeddableTotal,\n\t\t(metadata.processed_embeddable ?? 0) + embeddableInBatch,\n\t);\n\n\tif (batchIds.length > 0) {\n\t\tawait backfillVectors(db, { memoryIds: batchIds, signal: options.signal, client });\n\t\t// If the signal fired mid-batch, backfillVectors may have processed\n\t\t// only a prefix of batchRows. Don't advance the cursor or mark the\n\t\t// job completed in that case — the next tick after restart needs to\n\t\t// re-process this batch from the same cursor to cover any rows the\n\t\t// abort skipped. Leave the metadata untouched.\n\t\tif (options.signal?.aborted) return;\n\t\tconst prunedCoveredRows = withMigrationJobOwner(db, owner.job, () =>\n\t\t\tpruneStaleCurrentModelVectors(db, batchIds, targetModel),\n\t\t);\n\t\tif (prunedCoveredRows === undefined) return;\n\t\tconst metadataAfterPrune: MigrationMetadata = {\n\t\t\t...metadata,\n\t\t\tremoved_stale_rows: Number(metadata.removed_stale_rows ?? 0) + prunedCoveredRows,\n\t\t};\n\t\tif (batchRows.length < effectiveBatchSize) {\n\t\t\tawait finalizeMigrationCutover(\n\t\t\t\tdb,\n\t\t\t\towner,\n\t\t\t\ttargetModel,\n\t\t\t\tmetadataAfterPrune,\n\t\t\t\tlastCursorId,\n\t\t\t\tprocessedEmbeddable,\n\t\t\t\tembeddableTotal,\n\t\t\t\toptions.signal,\n\t\t\t\toptions.shouldStop,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tdb.transaction(() => {\n\t\t\tconst latestJob = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\t\tif (!sameMigrationJob(owner.job, latestJob)) return;\n\t\t\tconst latestMetadata = (latestJob?.metadata ?? {}) as MigrationMetadata;\n\t\t\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, {\n\t\t\t\tstatus: \"running\",\n\t\t\t\tmessage: `Re-indexed ${processedEmbeddable} of ${embeddableTotal} memories with ${targetDisplay}`,\n\t\t\t\tprogressCurrent: processedEmbeddable,\n\t\t\t\tprogressTotal: embeddableTotal,\n\t\t\t\tmetadata: {\n\t\t\t\t\t...(sameQueuedSyncWork(latestMetadata, metadata) ? metadataAfterPrune : latestMetadata),\n\t\t\t\t\tremoved_stale_rows:\n\t\t\t\t\t\tNumber(latestMetadata.removed_stale_rows ?? metadata.removed_stale_rows ?? 0) +\n\t\t\t\t\t\tprunedCoveredRows,\n\t\t\t\t\tlast_cursor_id: lastCursorId,\n\t\t\t\t\tprocessed_embeddable: processedEmbeddable,\n\t\t\t\t\tembeddable_total: embeddableTotal,\n\t\t\t\t},\n\t\t\t});\n\t\t}).immediate();\n\t\treturn;\n\t}\n\n\tif (metadata.last_cursor_id && metadata.last_cursor_id > 0) {\n\t\tawait finalizeMigrationCutover(\n\t\t\tdb,\n\t\t\towner,\n\t\t\ttargetModel,\n\t\t\tmetadata,\n\t\t\tmetadata.last_cursor_id,\n\t\t\tembeddableTotal,\n\t\t\tembeddableTotal,\n\t\t\toptions.signal,\n\t\t\toptions.shouldStop,\n\t\t);\n\t}\n}\n\nfunction recordFailedMigrationJob(db: SqliteDatabase, error: unknown, owner: MigrationJob): void {\n\twithMigrationJobOwner(db, owner, (job) => {\n\t\tif (!job || job.status === \"cancelled\") return;\n\t\tconst metadata = job.metadata ?? {};\n\t\tfailMaintenanceJob(\n\t\t\tdb,\n\t\t\tVECTOR_MODEL_MIGRATION_JOB,\n\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t{ metadata: { ...metadata, reconciliation_target_coverage_complete: undefined } },\n\t\t);\n\t});\n}\n\n/**\n * Returns false only when the lock blocked the write, so the caller can try\n * again later. A job that is no longer in flight keeps its own message.\n */\nfunction writeLockWaitNotice(db: SqliteDatabase): boolean {\n\ttry {\n\t\tdb.transaction(() => {\n\t\t\tconst job = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\t\tif (job?.status !== \"running\" && job?.status !== \"pending\") return;\n\t\t\tupdateMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB, { message: LOCK_WAIT_MESSAGE });\n\t\t}).immediate();\n\t\treturn true;\n\t} catch (error) {\n\t\tif (isTransientSqliteBusy(error)) return false;\n\t\tthrow error;\n\t}\n}\n\nexport class VectorModelMigrationRunner {\n\tprivate readonly dbPath: string;\n\tprivate readonly signal?: AbortSignal;\n\tprivate readonly batchSize: number;\n\tprivate readonly intervalMs: number;\n\tprivate readonly idleIntervalMs: number;\n\tprivate readonly tickBudgetMs: number;\n\tprivate active = false;\n\tprivate timer: ReturnType<typeof setTimeout> | null = null;\n\tprivate currentRun: Promise<void> | null = null;\n\tprivate lastTickWasIdle = false;\n\tprivate consecutiveBusyTicks = 0;\n\tprivate lockNoticeWritten = false;\n\n\tconstructor(options: VectorModelMigrationOptions = {}) {\n\t\tthis.dbPath = resolveDbPath(options.dbPath);\n\t\tthis.signal = options.signal;\n\t\tthis.batchSize = Math.max(1, options.batchSize ?? 50);\n\t\tthis.intervalMs = Math.max(1000, options.intervalMs ?? 5000);\n\t\tthis.idleIntervalMs = Math.max(1000, options.idleIntervalMs ?? IDLE_INTERVAL_MS);\n\t\tthis.tickBudgetMs = Math.max(0, options.tickBudgetMs ?? 0);\n\t}\n\n\tstart(): void {\n\t\tif (this.active) return;\n\t\tthis.active = true;\n\t\tthis.lastTickWasIdle = false;\n\t\tactiveRunner = this;\n\t\tthis.schedule(100);\n\t}\n\n\tasync stop(): Promise<void> {\n\t\tthis.active = false;\n\t\tif (activeRunner === this) activeRunner = null;\n\t\tif (this.timer) {\n\t\t\tclearTimeout(this.timer);\n\t\t\tthis.timer = null;\n\t\t}\n\t\tif (this.currentRun) await this.currentRun;\n\t}\n\n\t/**\n\t * Pulls the runner out of its idle cadence and schedules an immediate\n\t * tick. Queue writers (sync bootstrap / incremental replication) call\n\t * this through {@link wakeActiveVectorMigrationRunner} so freshly\n\t * replicated memories don't sit unembedded for the full idle interval.\n\t */\n\twake(): void {\n\t\tif (!this.active) return;\n\t\tthis.lastTickWasIdle = false;\n\t\tif (this.timer) {\n\t\t\tclearTimeout(this.timer);\n\t\t\tthis.timer = null;\n\t\t\tthis.schedule(100);\n\t\t}\n\t}\n\n\tprivate schedule(delayMs: number): void {\n\t\tif (!this.active || this.signal?.aborted) return;\n\t\tthis.timer = setTimeout(() => {\n\t\t\tthis.timer = null;\n\t\t\tthis.currentRun = this.runOnce()\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tconsole.error(\"Vector migration runner tick failed:\", err);\n\t\t\t\t})\n\t\t\t\t.finally(() => {\n\t\t\t\t\tthis.currentRun = null;\n\t\t\t\t\tthis.schedule(this.nextDelayMs());\n\t\t\t\t});\n\t\t}, delayMs);\n\t\tif (typeof this.timer === \"object\" && \"unref\" in this.timer) this.timer.unref();\n\t}\n\n\tprivate nextDelayMs(): number {\n\t\tif (this.consecutiveBusyTicks > 0) return busyRetryDelayMs(this.consecutiveBusyTicks);\n\t\treturn this.lastTickWasIdle ? this.idleIntervalMs : this.intervalMs;\n\t}\n\n\tprivate async runOnce(): Promise<void> {\n\t\tif (!this.active || this.signal?.aborted) return;\n\t\tlet db: SqliteDatabase | null = null;\n\t\tlet owner: MigrationPassOwner | null = null;\n\t\ttry {\n\t\t\tdb = connect(this.dbPath) as SqliteDatabase;\n\t\t\towner = { job: getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB), failureHandled: false };\n\t\t\tloadSqliteVec(db);\n\t\t\tthis.lastTickWasIdle = await this.runPassesWithinBudget(db, owner);\n\t\t\tthis.consecutiveBusyTicks = 0;\n\t\t\tthis.lockNoticeWritten = false;\n\t\t} catch (error) {\n\t\t\tthis.handleOwnedTickFailure(db, error, owner);\n\t\t} finally {\n\t\t\tdb?.close();\n\t\t}\n\t}\n\n\t/**\n\t * Runs passes on one connection until the job goes idle, the runner stops,\n\t * or the tick budget is spent, and returns whether the last pass left the\n\t * job idle. Every pass commits its own short write transactions, and\n\t * inference runs outside them, so a longer tick does not lengthen any single\n\t * write transaction. It does run more of them per minute.\n\t */\n\tprivate async runPassesWithinBudget(\n\t\tdb: SqliteDatabase,\n\t\towner: MigrationPassOwner,\n\t): Promise<boolean> {\n\t\tconst deadline = Date.now() + this.tickBudgetMs;\n\t\twhile (true) {\n\t\t\tawait runTrackedVectorMigrationPass(\n\t\t\t\tdb,\n\t\t\t\t{\n\t\t\t\t\tbatchSize: this.batchSize,\n\t\t\t\t\tsignal: this.signal,\n\t\t\t\t\tshouldStop: () => !this.active,\n\t\t\t\t},\n\t\t\t\towner,\n\t\t\t);\n\t\t\towner.failureHandled = false;\n\t\t\towner.job = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\t\tconst idle = this.computeIdle(db);\n\t\t\tif (idle || !this.active || this.signal?.aborted || Date.now() >= deadline) return idle;\n\t\t\t// No transaction is open here. Let shutdown and timers run between batches.\n\t\t\tawait yieldToEventLoop();\n\t\t}\n\t}\n\n\tprivate handleOwnedTickFailure(\n\t\tdb: SqliteDatabase | null,\n\t\terror: unknown,\n\t\towner: MigrationPassOwner | null,\n\t): void {\n\t\ttry {\n\t\t\tif (db && owner && !owner.failureHandled) recordOwnedMigrationFailure(db, error, owner);\n\t\t} catch (writeError) {\n\t\t\tthis.handleTickFailure(db, writeError);\n\t\t\treturn;\n\t\t}\n\t\tthis.handleTickFailure(db, error);\n\t}\n\n\tprivate handleTickFailure(db: SqliteDatabase | null, error: unknown): void {\n\t\tif (isTransientSqliteBusy(error)) {\n\t\t\tthis.recordBusyTick(db, error);\n\t\t\treturn;\n\t\t}\n\t\tthis.consecutiveBusyTicks = 0;\n\t\tthis.lockNoticeWritten = false;\n\t\t// Treat exceptions as idle — a thrown tick is not going to unthrow\n\t\t// at 5s cadence. The failMaintenanceJob record captures the error;\n\t\t// the next tick at IDLE_INTERVAL_MS will retry.\n\t\tthis.lastTickWasIdle = true;\n\t\tconsole.warn(\"Vector migration runner failed\", error);\n\t}\n\n\t/**\n\t * Lock contention is transient, so the job keeps its status instead of\n\t * showing a failure, and the next tick runs well before the idle interval.\n\t */\n\tprivate recordBusyTick(db: SqliteDatabase | null, error: unknown): void {\n\t\tthis.consecutiveBusyTicks += 1;\n\t\tconst retrySeconds = busyRetryDelayMs(this.consecutiveBusyTicks) / 1000;\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconsole.warn(\n\t\t\t`Vector migration runner found the database locked (${message}); retrying in ${retrySeconds}s`,\n\t\t);\n\t\tthis.noteLongLockWait(db);\n\t}\n\n\t/**\n\t * Best effort, once per locked streak: the write itself needs the lock, so an\n\t * attempt blocked by the lock is retried on the next locked tick.\n\t */\n\tprivate noteLongLockWait(db: SqliteDatabase | null): void {\n\t\tif (!db || this.lockNoticeWritten) return;\n\t\tif (this.consecutiveBusyTicks < BUSY_TICKS_BEFORE_LOCK_NOTICE) return;\n\t\ttry {\n\t\t\tthis.lockNoticeWritten = writeLockWaitNotice(db);\n\t\t} catch (error) {\n\t\t\tconsole.warn(\"Vector migration runner could not record the lock wait\", error);\n\t\t\tthis.lockNoticeWritten = true;\n\t\t}\n\t}\n\n\tprivate computeIdle(db: SqliteDatabase): boolean {\n\t\t// Embeddings disabled → the pass returns immediately with no work\n\t\t// possible. Polling fast adds nothing.\n\t\tif (isEmbeddingDisabled()) return true;\n\t\tconst job = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB);\n\t\tif (job) {\n\t\t\t// Local repairs drain without resuming cancelled migrations.\n\t\t\t// Failed jobs retain their existing automatic retry behavior.\n\t\t\tconst meta = (job.metadata ?? {}) as MigrationMetadata;\n\t\t\tif (job.status === \"running\" || job.status === \"pending\") {\n\t\t\t\t// A cutover retry slows the runner because each retry re-runs full\n\t\t\t\t// validation scans. Queued incremental work drains before cutover,\n\t\t\t\t// so a retry count left over from an earlier attempt must not slow it.\n\t\t\t\tif (drainsQueuedSyncBeforeCutover(meta)) return false;\n\t\t\t\treturn Number(meta.cutover_retry_count ?? 0) > 0;\n\t\t\t}\n\t\t\tconst queued =\n\t\t\t\tmetadataMemoryIds(meta.pending_upsert_memory_ids).length +\n\t\t\t\tmetadataMemoryIds(meta.pending_delete_memory_ids).length;\n\t\t\tif (queued > 0) return false;\n\t\t\t// A completed job with cleanup still owed (bounded stale batch not yet\n\t\t\t// exhausted, or a deferred cleanup pass) is known work, not a quiet\n\t\t\t// database. Keep it on the active cadence so it finishes promptly.\n\t\t\treturn !meta.cleanup_pending || preservesCancelledMigration(job);\n\t\t}\n\t\t// No job row yet. Peek coverage directly to tell whether the first\n\t\t// tick on a fresh DB genuinely had nothing to do.\n\t\tconst targetModel = tryResolveEmbeddingVectorIdentityLabel();\n\t\tif (!targetModel) return true;\n\t\ttry {\n\t\t\tconst uncovered = db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT COUNT(*) AS c FROM memory_items\n\t\t\t\t\t WHERE active = 1\n\t\t\t\t\t AND TRIM(COALESCE(title, '') || COALESCE(body_text, '')) != ''\n\t\t\t\t\t AND id NOT IN (SELECT DISTINCT memory_id FROM memory_vectors WHERE model = ?)`,\n\t\t\t\t)\n\t\t\t\t.get(targetModel) as { c?: number } | undefined;\n\t\t\tif (Number(uncovered?.c ?? 0) > 0) return false;\n\t\t\treturn detectSourceModel(db, targetModel) === null;\n\t\t} catch (error) {\n\t\t\t// Don't silently tick fast forever on a query failure; log so it\n\t\t\t// shows up in dogfood logs. Conservatively treat as non-idle so\n\t\t\t// the next tick tries again at full cadence.\n\t\t\tconsole.warn(\"Vector migration runner idle peek failed\", error);\n\t\t\treturn false;\n\t\t}\n\t}\n}\n","import { realpathSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { posix } from \"node:path\";\n\nexport function normalizePortablePath(value: string): string {\n\tconst normalized = posix.normalize(value.replaceAll(\"\\\\\", \"/\"));\n\treturn normalized === \"/\" ? normalized : normalized.replace(/\\/+$/, \"\");\n}\n\nexport function comparablePortablePath(value: string): string {\n\treturn /^[A-Za-z]:\\//.test(value) ? value.toLowerCase() : value;\n}\n\nexport function resolveComparablePath(value: string): string {\n\ttry {\n\t\treturn comparablePortablePath(normalizePortablePath(realpathSync(value)));\n\t} catch {\n\t\treturn comparablePortablePath(normalizePortablePath(value));\n\t}\n}\n\nexport function normalizeInstallEntryPath(entryPath: string): string {\n\tif (!entryPath) return \"\";\n\ttry {\n\t\treturn normalizePortablePath(realpathSync(entryPath));\n\t} catch {\n\t\treturn normalizePortablePath(entryPath);\n\t}\n}\n\nfunction configuredMiseDataDirectories(env: Record<string, string | undefined>): string[] {\n\tconst explicitDataDirectory = env.MISE_DATA_DIR?.trim();\n\tif (explicitDataDirectory) return [explicitDataDirectory];\n\n\tconst candidates: string[] = [];\n\tconst xdgDataHome = env.XDG_DATA_HOME?.trim();\n\tif (xdgDataHome) return [posix.join(xdgDataHome, \"mise\")];\n\tconst localAppData = env.LOCALAPPDATA?.trim();\n\tif (localAppData) return [posix.join(localAppData, \"mise\")];\n\tconst home = env.HOME?.trim() || env.USERPROFILE?.trim() || homedir();\n\tif (home) candidates.push(posix.join(home, \".local/share/mise\"));\n\treturn candidates;\n}\n\nfunction versionUnderMiseDataDirectory(entryPath: string, dataDirectory: string): string | null {\n\tconst installPrefix = `${posix.join(\n\t\tresolveComparablePath(dataDirectory),\n\t\t\"installs/npm-codemem\",\n\t)}/`;\n\tif (!entryPath.startsWith(installPrefix)) return null;\n\tconst versionAndPath = entryPath.slice(installPrefix.length);\n\tconst separatorIndex = versionAndPath.indexOf(\"/\");\n\treturn separatorIndex > 0 ? versionAndPath.slice(0, separatorIndex) : null;\n}\n\nexport function miseInstallVersionFromPath(\n\tentryPath: string,\n\tenv: Record<string, string | undefined>,\n): string | null {\n\tconst comparableEntryPath = comparablePortablePath(normalizeInstallEntryPath(entryPath));\n\tfor (const dataDirectory of configuredMiseDataDirectories(env)) {\n\t\tconst version = versionUnderMiseDataDirectory(comparableEntryPath, dataDirectory);\n\t\tif (version) return version;\n\t}\n\tconst defaultMatch = /\\/mise\\/installs\\/npm-codemem\\/([^/]+)\\//.exec(comparableEntryPath);\n\tif (defaultMatch?.[1] !== undefined) return defaultMatch[1];\n\treturn null;\n}\n","import { randomUUID } from \"node:crypto\";\nimport { mkdir, open, readFile, rename, unlink } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { codememHomeDir } from \"./home.js\";\nimport {\n\tmiseInstallVersionFromPath,\n\tnormalizeInstallEntryPath,\n\tresolveComparablePath,\n} from \"./mise-install-path.js\";\n\nexport { resolveComparablePath };\n\nconst REGISTRY_URL_PREFIX = \"https://registry.npmjs.org/codemem/\";\nconst REQUEST_TIMEOUT_MS = 2_000;\nconst CACHE_MAX_AGE_MS = 6 * 60 * 60 * 1_000;\nconst FAILURE_RETRY_DELAY_MS = 15 * 60 * 1_000;\nconst MAX_RESPONSE_BYTES = 16 * 1_024;\nconst MAX_VERSION_LENGTH = 128;\nconst MAX_RUNNER_SOURCE_LENGTH = 4_096;\nconst RELEASE_CACHE_SCHEMA_VERSION = 2;\nconst AUTO_UPDATE_DELAY_MS = 24 * 60 * 60 * 1_000;\nconst SEMVER =\n\t/^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$/;\n\nexport type InstallKind =\n\t| \"npm-global\"\n\t| \"pnpm-global\"\n\t| \"mise\"\n\t| \"npx\"\n\t| \"docker\"\n\t| \"repo-dev\"\n\t| \"pinned\"\n\t| \"unknown\";\nexport type ReleaseChannel = \"alpha\" | \"beta\" | \"rc\" | \"latest\";\n\nconst KNOWN_INSTALL_KINDS: readonly InstallKind[] = [\n\t\"npm-global\",\n\t\"pnpm-global\",\n\t\"mise\",\n\t\"npx\",\n\t\"docker\",\n\t\"repo-dev\",\n\t\"pinned\",\n\t\"unknown\",\n];\n\nexport interface UpdateStatus {\n\tcurrent_version: string;\n\tchannel: ReleaseChannel | null;\n\tlatest_version: string | null;\n\tupdate_available: boolean;\n\tfirst_seen_at: string | null;\n\tchecked_at: string | null;\n\tstale: boolean;\n\tinstall_kind: InstallKind;\n\tauto_update_eligible: boolean;\n\trecommended_action: string;\n\terror: string | null;\n}\n\nexport function isExplicitUpdateInstallEligible(status: UpdateStatus): boolean {\n\tif (status.install_kind === \"npm-global\") return status.auto_update_eligible;\n\treturn (\n\t\t(status.install_kind === \"mise\" || status.install_kind === \"pnpm-global\") &&\n\t\tstatus.update_available &&\n\t\t!status.stale &&\n\t\tstatus.error === null\n\t);\n}\n\ninterface ReleaseCacheRecord {\n\tschema_version: typeof RELEASE_CACHE_SCHEMA_VERSION;\n\tchannel: ReleaseChannel;\n\tlatest_version: string;\n\tchecked_at: string;\n\tfirst_seen_at: string;\n}\n\nexport interface ReleaseCacheIo {\n\treadCache: () => Promise<string | null>;\n\twriteCacheAtomic: (contents: string) => Promise<void>;\n}\n\nexport interface InstallDetectionInput {\n\tentryPath: string;\n\tenv?: Record<string, string | undefined>;\n}\n\nexport interface ReleaseDiscoveryDependencies {\n\tfetch: (url: string, init?: RequestInit) => Promise<Response>;\n\tnow: () => Date;\n\treadCache: () => Promise<string | null>;\n\twriteCacheAtomic: (contents: string) => Promise<void>;\n\ttimeoutSignal: (milliseconds: number) => AbortSignal;\n}\n\nexport interface ReleaseCheckOptions {\n\tcurrentVersion: string;\n\tinstallKind: InstallKind;\n\trefresh?: boolean;\n}\n\nexport interface ReleaseDiscovery {\n\tcheck(options: ReleaseCheckOptions): Promise<UpdateStatus>;\n}\n\ninterface ReleaseResolution {\n\trecord: ReleaseCacheRecord | null;\n\tstale: boolean;\n\terror: string | null;\n}\n\ninterface ParsedSemver {\n\tcore: [number, number, number];\n\tprerelease: string[];\n}\n\ninterface ReleaseDiscoveryState {\n\tinFlight: Map<ReleaseChannel, Promise<ReleaseResolution>>;\n\tmemoryResolutions: Map<ReleaseChannel, { resolution: ReleaseResolution; resolvedAtMs: number }>;\n}\n\nfunction parseSemver(value: unknown): ParsedSemver | null {\n\tif (typeof value !== \"string\" || value.length === 0 || value.length > MAX_VERSION_LENGTH) {\n\t\treturn null;\n\t}\n\tconst match = SEMVER.exec(value);\n\tif (!match) return null;\n\tconst parts = match.slice(1, 4).map(Number);\n\tif (!parts.every(Number.isSafeInteger)) return null;\n\tconst prerelease = match[4]?.split(\".\") ?? [];\n\tif (prerelease.some((identifier) => /^\\d+$/.test(identifier) && /^0\\d/.test(identifier))) {\n\t\treturn null;\n\t}\n\treturn { core: parts as [number, number, number], prerelease };\n}\n\nexport function releaseChannelForVersion(value: unknown): ReleaseChannel | null {\n\tconst parsed = parseSemver(value);\n\tif (!parsed) return null;\n\tif (parsed.prerelease.length === 0) return \"latest\";\n\tconst channel = parsed.prerelease[0];\n\treturn channel === \"alpha\" || channel === \"beta\" || channel === \"rc\" ? channel : null;\n}\n\nexport function isReleaseVersionForChannel(\n\tvalue: unknown,\n\tchannel: ReleaseChannel,\n): value is string {\n\treturn releaseChannelForVersion(value) === channel;\n}\n\nexport function isStableReleaseVersion(value: unknown): value is string {\n\treturn releaseChannelForVersion(value) === \"latest\";\n}\n\nfunction comparePrereleaseIdentifier(left: string | undefined, right: string | undefined): number {\n\tif (left === undefined) return right === undefined ? 0 : -1;\n\tif (right === undefined) return 1;\n\tif (left === right) return 0;\n\tconst leftNumeric = /^\\d+$/.test(left);\n\tconst rightNumeric = /^\\d+$/.test(right);\n\tif (leftNumeric && rightNumeric && left.length !== right.length) {\n\t\treturn Math.sign(left.length - right.length);\n\t}\n\tif (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1;\n\treturn left < right ? -1 : 1;\n}\n\nfunction comparePrerelease(left: string[], right: string[]): number {\n\tif (left.length === 0) return right.length === 0 ? 0 : 1;\n\tif (right.length === 0) return -1;\n\tfor (let index = 0; index < Math.max(left.length, right.length); index += 1) {\n\t\tconst comparison = comparePrereleaseIdentifier(left[index], right[index]);\n\t\tif (comparison !== 0) return comparison;\n\t}\n\treturn 0;\n}\n\nfunction compareSemver(left: string, right: string): number | null {\n\tconst leftVersion = parseSemver(left);\n\tconst rightVersion = parseSemver(right);\n\tif (!leftVersion || !rightVersion) return null;\n\tfor (const index of [0, 1, 2] as const) {\n\t\tconst difference = leftVersion.core[index] - rightVersion.core[index];\n\t\tif (difference !== 0) return Math.sign(difference);\n\t}\n\treturn comparePrerelease(leftVersion.prerelease, rightVersion.prerelease);\n}\n\nfunction parseIsoTimestamp(value: unknown): string | null {\n\tif (typeof value !== \"string\") return null;\n\tconst timestamp = new Date(value);\n\treturn Number.isFinite(timestamp.getTime()) && timestamp.toISOString() === value ? value : null;\n}\n\nfunction parseCache(\n\tcontents: string | null,\n\tnow: Date,\n\tchannel: ReleaseChannel,\n): ReleaseCacheRecord | null {\n\tif (contents === null) return null;\n\ttry {\n\t\tconst value: unknown = JSON.parse(contents);\n\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\t\tconst candidate = value as Record<string, unknown>;\n\t\tconst isLegacyStableCache = candidate.schema_version === 1 && channel === \"latest\";\n\t\tif (!isLegacyStableCache && candidate.schema_version !== RELEASE_CACHE_SCHEMA_VERSION)\n\t\t\treturn null;\n\t\tconst cachedChannel = isLegacyStableCache ? \"latest\" : candidate.channel;\n\t\tif (cachedChannel !== channel) return null;\n\t\tconst latestVersion =\n\t\t\ttypeof candidate.latest_version === \"string\" &&\n\t\t\tisReleaseVersionForChannel(candidate.latest_version, channel)\n\t\t\t\t? candidate.latest_version\n\t\t\t\t: null;\n\t\tconst checkedAt = parseIsoTimestamp(candidate.checked_at);\n\t\tconst firstSeenAt = parseIsoTimestamp(candidate.first_seen_at);\n\t\tif (!latestVersion || !checkedAt || !firstSeenAt) return null;\n\t\tconst checkedTime = Date.parse(checkedAt);\n\t\tconst firstSeenTime = Date.parse(firstSeenAt);\n\t\tif (checkedTime > now.getTime() || firstSeenTime > checkedTime) return null;\n\t\treturn {\n\t\t\tschema_version: RELEASE_CACHE_SCHEMA_VERSION,\n\t\t\tchannel,\n\t\t\tlatest_version: latestVersion,\n\t\t\tchecked_at: checkedAt,\n\t\t\tfirst_seen_at: firstSeenAt,\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction isFresh(record: ReleaseCacheRecord, now: Date): boolean {\n\treturn now.getTime() - Date.parse(record.checked_at) < CACHE_MAX_AGE_MS;\n}\n\nfunction errorMessage(error: unknown): string {\n\tif (error instanceof Error && (error.name === \"AbortError\" || error.name === \"TimeoutError\")) {\n\t\treturn \"registry request timed out\";\n\t}\n\treturn error instanceof Error && error.message ? error.message : \"release discovery failed\";\n}\n\nasync function readBoundedResponseBody(response: Response): Promise<string> {\n\tconst contentLength = response.headers.get(\"content-length\");\n\tif (contentLength !== null) {\n\t\tif (!/^\\d+$/.test(contentLength)) {\n\t\t\tawait response.body?.cancel();\n\t\t\tthrow new Error(\"invalid registry response: invalid Content-Length\");\n\t\t}\n\t\tconst declaredBytes = Number(contentLength);\n\t\tif (!Number.isSafeInteger(declaredBytes) || declaredBytes > MAX_RESPONSE_BYTES) {\n\t\t\tawait response.body?.cancel();\n\t\t\tthrow new Error(\"invalid registry response: payload too large\");\n\t\t}\n\t}\n\tif (!response.body) throw new Error(\"invalid registry response: missing body\");\n\n\tconst reader = response.body.getReader();\n\tconst chunks: Uint8Array[] = [];\n\tlet receivedBytes = 0;\n\ttry {\n\t\twhile (true) {\n\t\t\tconst result = await reader.read();\n\t\t\tif (result.done) break;\n\t\t\treceivedBytes += result.value.byteLength;\n\t\t\tif (receivedBytes > MAX_RESPONSE_BYTES) {\n\t\t\t\tawait reader.cancel();\n\t\t\t\tthrow new Error(\"invalid registry response: payload too large\");\n\t\t\t}\n\t\t\tchunks.push(result.value);\n\t\t}\n\t} finally {\n\t\treader.releaseLock();\n\t}\n\n\tconst body = new Uint8Array(receivedBytes);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tbody.set(chunk, offset);\n\t\toffset += chunk.byteLength;\n\t}\n\ttry {\n\t\treturn new TextDecoder(\"utf-8\", { fatal: true }).decode(body);\n\t} catch {\n\t\tthrow new Error(\"invalid registry response payload\");\n\t}\n}\n\nasync function fetchLatestVersion(\n\tdeps: ReleaseDiscoveryDependencies,\n\tchannel: ReleaseChannel,\n): Promise<string> {\n\tconst registryUrl = `${REGISTRY_URL_PREFIX}${channel}`;\n\tconst response = await deps.fetch(registryUrl, {\n\t\theaders: { accept: \"application/json\" },\n\t\tredirect: \"error\",\n\t\tsignal: deps.timeoutSignal(REQUEST_TIMEOUT_MS),\n\t});\n\tif (!response.ok) {\n\t\tawait response.body?.cancel();\n\t\tthrow new Error(`registry request failed with status ${response.status}`);\n\t}\n\tif (response.url) {\n\t\tconst finalUrl = new URL(response.url);\n\t\tif (finalUrl.href !== registryUrl) {\n\t\t\tawait response.body?.cancel();\n\t\t\tthrow new Error(\"invalid registry response URL\");\n\t\t}\n\t}\n\tconst body = await readBoundedResponseBody(response);\n\tlet payload: unknown;\n\ttry {\n\t\tpayload = JSON.parse(body);\n\t} catch {\n\t\tthrow new Error(\"invalid registry response payload\");\n\t}\n\tif (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n\t\tthrow new Error(\"invalid registry response payload\");\n\t}\n\tconst version = (payload as Record<string, unknown>).version;\n\tif (typeof version !== \"string\" || !isReleaseVersionForChannel(version, channel)) {\n\t\tthrow new Error(\"invalid registry version\");\n\t}\n\treturn version;\n}\n\nfunction recommendedAction(\n\tinstallKind: InstallKind,\n\tcurrentVersion: string,\n\tlatestVersion: string | null,\n\tupdateAvailable: boolean,\n\tchannel: ReleaseChannel | null,\n): string {\n\tif (installKind === \"repo-dev\") {\n\t\treturn \"Package-release updates do not apply to repository source. Run git pull, pnpm install, and pnpm build in the codemem repository.\";\n\t}\n\tif (!channel || !isReleaseVersionForChannel(currentVersion, channel)) {\n\t\treturn \"Verify the current codemem version and try again.\";\n\t}\n\tif (!latestVersion) return \"Check network access and try again.\";\n\tif (!updateAvailable) {\n\t\tconst releaseLabel = channel === \"latest\" ? \"stable\" : channel;\n\t\treturn `No action required; codemem is on the latest ${releaseLabel} release.`;\n\t}\n\tswitch (installKind) {\n\t\tcase \"npm-global\":\n\t\t\treturn `${process.platform === \"linux\" ? \"env ONNXRUNTIME_NODE_INSTALL=skip \" : \"\"}npm install -g codemem@${latestVersion}`;\n\t\tcase \"pnpm-global\":\n\t\t\treturn `${process.platform === \"linux\" ? \"env ONNXRUNTIME_NODE_INSTALL=skip \" : \"\"}pnpm add -g codemem@${latestVersion} @codemem/embeddings@${latestVersion}`;\n\t\tcase \"mise\":\n\t\t\treturn process.platform === \"linux\"\n\t\t\t\t? `env ONNXRUNTIME_NODE_INSTALL=skip mise use -g npm:codemem@${latestVersion}`\n\t\t\t\t: `mise use -g npm:codemem@${latestVersion}`;\n\t\tcase \"npx\":\n\t\t\treturn `Update your launcher to request codemem@${latestVersion} and @codemem/embeddings@${latestVersion} together.`;\n\t\tcase \"docker\":\n\t\t\treturn `Set CODEMEM_VERSION=${latestVersion}, then run CODEMEM_VERSION=${latestVersion} docker compose build --pull and docker compose up -d.`;\n\t\tcase \"pinned\":\n\t\t\treturn `Update the pinned codemem version to ${latestVersion}, then restart codemem.`;\n\t\tdefault:\n\t\t\treturn `Update codemem to ${latestVersion} using your installation method.`;\n\t}\n}\n\nfunction hasNewerPackageRelease(\n\tinstallKind: InstallKind,\n\tcurrentVersion: string,\n\tlatestVersion: string | null,\n): boolean {\n\tif (installKind === \"repo-dev\" || latestVersion === null) return false;\n\tconst comparison = compareSemver(latestVersion, currentVersion);\n\treturn comparison !== null && comparison > 0;\n}\n\nfunction toStatus(\n\tresolution: ReleaseResolution,\n\toptions: ReleaseCheckOptions,\n\tchannel: ReleaseChannel | null,\n): UpdateStatus {\n\tconst latestVersion = resolution.record?.latest_version ?? null;\n\tconst updateAvailable = hasNewerPackageRelease(\n\t\toptions.installKind,\n\t\toptions.currentVersion,\n\t\tlatestVersion,\n\t);\n\treturn {\n\t\tcurrent_version: options.currentVersion,\n\t\tchannel,\n\t\tlatest_version: latestVersion,\n\t\tupdate_available: updateAvailable,\n\t\tfirst_seen_at: resolution.record?.first_seen_at ?? null,\n\t\tchecked_at: resolution.record?.checked_at ?? null,\n\t\tstale: resolution.stale,\n\t\tinstall_kind: options.installKind,\n\t\tauto_update_eligible:\n\t\t\toptions.installKind === \"npm-global\" &&\n\t\t\tupdateAvailable &&\n\t\t\t!resolution.stale &&\n\t\t\tresolution.error === null &&\n\t\t\tresolution.record !== null &&\n\t\t\tDate.parse(resolution.record.checked_at) - Date.parse(resolution.record.first_seen_at) >=\n\t\t\t\tAUTO_UPDATE_DELAY_MS,\n\t\trecommended_action: recommendedAction(\n\t\t\toptions.installKind,\n\t\t\toptions.currentVersion,\n\t\t\tlatestVersion,\n\t\t\tupdateAvailable,\n\t\t\tchannel,\n\t\t),\n\t\terror: resolution.error,\n\t};\n}\n\nfunction canReuseMemoryResolution(\n\tstate: ReleaseDiscoveryState,\n\tchannel: ReleaseChannel,\n\tnow: Date,\n): boolean {\n\tconst memoryResolution = state.memoryResolutions.get(channel);\n\tif (!memoryResolution) return false;\n\tconst ageMs = Math.max(0, now.getTime() - memoryResolution.resolvedAtMs);\n\tconst { resolution } = memoryResolution;\n\tif (resolution.record && !resolution.stale && isFresh(resolution.record, now)) return true;\n\treturn resolution.error !== null && ageMs < FAILURE_RETRY_DELAY_MS;\n}\n\nasync function refreshRelease(\n\tdeps: ReleaseDiscoveryDependencies,\n\tcached: ReleaseCacheRecord | null,\n\tnow: Date,\n\tchannel: ReleaseChannel,\n): Promise<ReleaseResolution> {\n\ttry {\n\t\tconst latestVersion = await fetchLatestVersion(deps, channel);\n\t\tconst timestamp = now.toISOString();\n\t\tconst record: ReleaseCacheRecord = {\n\t\t\tschema_version: RELEASE_CACHE_SCHEMA_VERSION,\n\t\t\tchannel,\n\t\t\tlatest_version: latestVersion,\n\t\t\tchecked_at: timestamp,\n\t\t\tfirst_seen_at: cached?.latest_version === latestVersion ? cached.first_seen_at : timestamp,\n\t\t};\n\t\ttry {\n\t\t\tawait deps.writeCacheAtomic(JSON.stringify(record));\n\t\t\treturn { record, stale: false, error: null };\n\t\t} catch (error) {\n\t\t\treturn { record, stale: false, error: `cache write failed: ${errorMessage(error)}` };\n\t\t}\n\t} catch (error) {\n\t\treturn { record: cached, stale: cached !== null, error: errorMessage(error) };\n\t}\n}\n\nfunction withCacheReadError(\n\tresolution: ReleaseResolution,\n\tcacheReadError: string | null,\n): ReleaseResolution {\n\treturn cacheReadError && !resolution.error\n\t\t? { ...resolution, error: cacheReadError }\n\t\t: resolution;\n}\n\nasync function readReleaseCache(\n\tdeps: ReleaseDiscoveryDependencies,\n\tnow: Date,\n\tchannel: ReleaseChannel,\n): Promise<{ cached: ReleaseCacheRecord | null; error: string | null }> {\n\ttry {\n\t\treturn { cached: parseCache(await deps.readCache(), now, channel), error: null };\n\t} catch (error) {\n\t\treturn { cached: null, error: `cache read failed: ${errorMessage(error)}` };\n\t}\n}\n\nasync function checkRelease(\n\tdeps: ReleaseDiscoveryDependencies,\n\tstate: ReleaseDiscoveryState,\n\toptions: ReleaseCheckOptions,\n): Promise<UpdateStatus> {\n\tconst now = deps.now();\n\tconst channel = releaseChannelForVersion(options.currentVersion);\n\tif (!channel) {\n\t\treturn toStatus(\n\t\t\t{ record: null, stale: false, error: \"unsupported installed release channel\" },\n\t\t\toptions,\n\t\t\tnull,\n\t\t);\n\t}\n\tconst cache = await readReleaseCache(deps, now, channel);\n\tif (!options.refresh && cache.cached && isFresh(cache.cached, now)) {\n\t\treturn toStatus({ record: cache.cached, stale: false, error: null }, options, channel);\n\t}\n\tconst memoryResolution = state.memoryResolutions.get(channel);\n\tif (!options.refresh && memoryResolution && canReuseMemoryResolution(state, channel, now)) {\n\t\treturn toStatus(withCacheReadError(memoryResolution.resolution, cache.error), options, channel);\n\t}\n\tlet request = state.inFlight.get(channel);\n\tif (!request) {\n\t\trequest = refreshRelease(deps, cache.cached, now, channel).finally(() => {\n\t\t\tstate.inFlight.delete(channel);\n\t\t});\n\t\tstate.inFlight.set(channel, request);\n\t}\n\tconst resolution = await request;\n\tstate.memoryResolutions.set(channel, { resolution, resolvedAtMs: deps.now().getTime() });\n\treturn toStatus(withCacheReadError(resolution, cache.error), options, channel);\n}\n\nexport function createReleaseDiscovery(deps: ReleaseDiscoveryDependencies): ReleaseDiscovery {\n\tconst state: ReleaseDiscoveryState = {\n\t\tinFlight: new Map(),\n\t\tmemoryResolutions: new Map(),\n\t};\n\treturn { check: (options) => checkRelease(deps, state, options) };\n}\n\nfunction defaultCachePath(): string {\n\treturn join(codememHomeDir(), \".codemem\", \"release-discovery.json\");\n}\n\nexport function createReleaseCacheIo(cachePath: string): ReleaseCacheIo {\n\tconst directory = dirname(cachePath);\n\treturn {\n\t\tasync readCache(): Promise<string | null> {\n\t\t\ttry {\n\t\t\t\treturn await readFile(cachePath, \"utf8\");\n\t\t\t} catch (error) {\n\t\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\tasync writeCacheAtomic(contents: string): Promise<void> {\n\t\t\tawait mkdir(directory, { recursive: true, mode: 0o700 });\n\t\t\tconst temporaryPath = join(\n\t\t\t\tdirectory,\n\t\t\t\t`.release-discovery.${process.pid}.${randomUUID()}.tmp`,\n\t\t\t);\n\t\t\tlet handle: Awaited<ReturnType<typeof open>> | null = null;\n\t\t\ttry {\n\t\t\t\thandle = await open(temporaryPath, \"wx\", 0o600);\n\t\t\t\tawait handle.writeFile(contents, \"utf8\");\n\t\t\t\tawait handle.sync();\n\t\t\t\tawait handle.close();\n\t\t\t\thandle = null;\n\t\t\t\tawait rename(temporaryPath, cachePath);\n\t\t\t} catch (error) {\n\t\t\t\tawait handle?.close().catch(() => undefined);\n\t\t\t\tawait unlink(temporaryPath).catch(() => undefined);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t};\n}\n\nfunction isPinnedSource(source: string): boolean {\n\tif (!source || source.length > MAX_RUNNER_SOURCE_LENGTH) return false;\n\tconst containsWhitespace = (value: string): boolean => {\n\t\tfor (const character of value) {\n\t\t\tif (character.trim() === \"\") return true;\n\t\t}\n\t\treturn false;\n\t};\n\tconst normalized = source.toLowerCase();\n\tif (normalized.startsWith(\"codemem@\")) {\n\t\tconst requested = source.slice(\"codemem@\".length);\n\t\treturn (\n\t\t\trequested.length > 0 &&\n\t\t\t!containsWhitespace(requested) &&\n\t\t\t![\"latest\", \"next\", \"*\"].includes(requested.toLowerCase())\n\t\t);\n\t}\n\tif (!source.startsWith(\"git+\") && !source.includes(\".git\")) return false;\n\tconst queryIndex = source.indexOf(\"?\");\n\tconst fragmentIndex = source.indexOf(\"#\");\n\tconst boundaryIndexes = [queryIndex, fragmentIndex].filter((index) => index >= 0);\n\tconst boundary = boundaryIndexes.length > 0 ? Math.min(...boundaryIndexes) : source.length;\n\tconst withoutQuery = source.slice(0, boundary);\n\tconst gitRefIndex = withoutQuery.toLowerCase().lastIndexOf(\".git@\");\n\tconst gitRef = gitRefIndex >= 0 ? withoutQuery.slice(gitRefIndex + \".git@\".length) : \"\";\n\tif (gitRef.length > 0 && !gitRef.includes(\"/\") && !containsWhitespace(gitRef)) return true;\n\tconst fragment = fragmentIndex >= 0 ? source.slice(fragmentIndex + 1) : \"\";\n\treturn fragment.length > 0 && !containsWhitespace(fragment);\n}\n\nfunction miseInstallKindForPath(\n\tentryPath: string,\n\tenv: Record<string, string | undefined>,\n): \"mise\" | \"unknown\" | null {\n\tconst version = miseInstallVersionFromPath(entryPath, env);\n\tif (version === null) return null;\n\treturn parseSemver(version) === null ? \"unknown\" : \"mise\";\n}\n\nfunction narrowedInstallKind(\n\tentryPath: string,\n\texplicit: string,\n\tenv: Record<string, string | undefined>,\n): InstallKind | null {\n\tif (!explicit) return null;\n\tif (!KNOWN_INSTALL_KINDS.includes(explicit as InstallKind)) return \"unknown\";\n\tif (explicit === \"mise\" && miseInstallKindForPath(entryPath, env) !== \"mise\") return \"unknown\";\n\tif ([\"docker\", \"repo-dev\", \"pinned\", \"unknown\"].includes(explicit)) {\n\t\treturn explicit as InstallKind;\n\t}\n\treturn null;\n}\n\nfunction runnerInstallKind(runner: string): InstallKind | null {\n\treturn runner === \"node\" || runner === \"uv\" ? \"repo-dev\" : null;\n}\n\nfunction pnpmVirtualStoreVersion(packagePath: string): string | null {\n\tconst match =\n\t\t/^\\.pnpm\\/codemem@([^/_]+)(?:_[^/]+)?\\/node_modules\\/codemem\\/dist\\/index\\.js$/i.exec(\n\t\t\tpackagePath,\n\t\t);\n\treturn match?.[1] && parseSemver(match[1]) !== null ? match[1] : null;\n}\n\nfunction pnpmGlobalRelativePath(\n\tentryPath: string,\n\tenv: Record<string, string | undefined>,\n): string | null {\n\tconst pnpmHome = env.PNPM_HOME?.trim();\n\tif (pnpmHome) {\n\t\tconst prefix = `${resolveComparablePath(pnpmHome)}/global/`;\n\t\treturn entryPath.startsWith(prefix) ? entryPath.slice(prefix.length) : null;\n\t}\n\tconst marker = \"/pnpm/global/\";\n\tconst markerIndex = entryPath.indexOf(marker);\n\treturn markerIndex >= 0 ? entryPath.slice(markerIndex + marker.length) : null;\n}\n\nfunction isPnpmGlobalEntryPath(\n\tentryPath: string,\n\tenv: Record<string, string | undefined>,\n): boolean {\n\tconst relativePath = pnpmGlobalRelativePath(entryPath, env);\n\tif (!relativePath) return false;\n\tconst layout = /^(?:[1-9]\\d*\\/|v[1-9]\\d*\\/[^/]+\\/node_modules\\/)/i.exec(relativePath);\n\tif (!layout) return false;\n\treturn pnpmVirtualStoreVersion(relativePath.slice(layout[0].length)) !== null;\n}\n\nfunction isPnpmDlxEntryPath(entryPath: string): boolean {\n\tconst match =\n\t\t/\\/(?:pnpm\\/dlx\\/[^/]+\\/[^/]+|\\.pnpm\\/dlx\\/[^/]+)\\/node_modules\\/(\\.pnpm\\/codemem@.+)$/i.exec(\n\t\t\tentryPath,\n\t\t);\n\treturn match?.[1] !== undefined && pnpmVirtualStoreVersion(match[1]) !== null;\n}\n\nfunction installKindForEntryPath(\n\tentryPath: string,\n\tenv: Record<string, string | undefined>,\n): InstallKind {\n\tconst miseInstallKind = miseInstallKindForPath(entryPath, env);\n\tif (miseInstallKind) return miseInstallKind;\n\tif (/\\/_npx\\//.test(entryPath) || isPnpmDlxEntryPath(entryPath)) return \"npx\";\n\tif (/\\/installs\\/npm-codemem\\/[^/]+\\//.test(entryPath)) return \"unknown\";\n\tif (isPnpmGlobalEntryPath(resolveComparablePath(entryPath), env)) return \"pnpm-global\";\n\tif (/\\/lib\\/node_modules\\/codemem\\/dist\\/index\\.js$/.test(entryPath)) return \"npm-global\";\n\tif (/\\/AppData\\/Roaming\\/npm\\/node_modules\\/codemem\\/dist\\/index\\.js$/i.test(entryPath)) {\n\t\treturn \"npm-global\";\n\t}\n\treturn \"unknown\";\n}\n\nexport function detectInstallKind(input: InstallDetectionInput): InstallKind {\n\tconst env = input.env ?? {};\n\tconst source = env.CODEMEM_RUNNER_FROM?.trim() ?? \"\";\n\tif (isPinnedSource(source)) return \"pinned\";\n\n\tconst entryPath = normalizeInstallEntryPath(input.entryPath);\n\tif (/\\/packages\\/cli\\/src\\/index\\.ts$/.test(entryPath)) return \"repo-dev\";\n\n\tconst explicit = env.CODEMEM_INSTALL_KIND?.trim().toLowerCase();\n\tconst narrowedKind = narrowedInstallKind(entryPath, explicit ?? \"\", env);\n\tif (narrowedKind) return narrowedKind;\n\n\tconst runner = env.CODEMEM_RUNNER?.trim().toLowerCase();\n\treturn runnerInstallKind(runner ?? \"\") ?? installKindForEntryPath(entryPath, env);\n}\n\nconst defaultReleaseDiscovery = createReleaseDiscovery({\n\tfetch: (url, init) => fetch(url, init),\n\tnow: () => new Date(),\n\treadCache: () => createReleaseCacheIo(defaultCachePath()).readCache(),\n\twriteCacheAtomic: (contents) =>\n\t\tcreateReleaseCacheIo(defaultCachePath()).writeCacheAtomic(contents),\n\ttimeoutSignal: (milliseconds) => AbortSignal.timeout(milliseconds),\n});\n\nexport interface GetUpdateStatusOptions {\n\tcurrentVersion: string;\n\tinstallKind?: InstallKind;\n\trefresh?: boolean;\n}\n\nexport function getUpdateStatus(options: GetUpdateStatusOptions): Promise<UpdateStatus> {\n\treturn defaultReleaseDiscovery.check({\n\t\tcurrentVersion: options.currentVersion,\n\t\tinstallKind: options.installKind ?? \"unknown\",\n\t\trefresh: options.refresh,\n\t});\n}\n","/**\n * Sync bootstrap: client-side snapshot consumer for re-bootstrapping\n * shared memories from a peer when the incremental op log is no longer\n * sufficient (generation mismatch, stale cursor beyond retained floor).\n *\n * The bootstrap protocol:\n * 1. Fetch paginated snapshot pages from GET /v1/snapshot\n * 2. Collect all canonical shared memory items (including tombstones)\n * 3. In a single transaction: wipe local synced memories for the requested\n * scope, apply snapshot, update replication cursor to baseline_cursor,\n * bump generation\n */\n\nimport { and, eq, inArray, isNotNull, isNull, ne, or, sql } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport type { ApiSyncMemorySnapshotPageResponse } from \"./api-types.js\";\nimport type { Database } from \"./db.js\";\nimport { toJson } from \"./db.js\";\nimport { recordForeignMemoryRevision } from \"./memory-creation-provenance.js\";\nimport { retirementAllowsSnapshot } from \"./memory-retirement-snapshot-guard.js\";\nimport * as schema from \"./schema.js\";\nimport { redactMemoryFields, SecretScanner } from \"./secret-scanner.js\";\nimport { snapshotSessionExportKeysForMemoryIds } from \"./session-export-identity-mutation.js\";\nimport { buildAuthHeaders, buildDirectPeerAuthHeaders } from \"./sync-auth.js\";\nimport { SYNC_BOOTSTRAP_CWD_PREFIX } from \"./sync-bootstrap-constants.js\";\nimport { LOCAL_SYNC_CAPABILITY, SYNC_CAPABILITY_HEADER } from \"./sync-capability.js\";\nimport { type RequestJsonExecutor, requestJson } from \"./sync-http-client.js\";\nimport {\n\tclearReplicationCursorLastApplied,\n\tclockDeviceIdFromMetadataJson,\n\tDEFAULT_SYNC_SCOPE_ID,\n\tisNewerClock,\n\tSCOPED_NULL_BASELINE_BOOTSTRAP_CURSOR_MARKER,\n\tsetReplicationCursor,\n\tsetSyncResetState,\n} from \"./sync-replication.js\";\nimport {\n\trecordSyncTransferObservation,\n\trecordSyncTransferReceipts,\n} from \"./sync-transfer-activity.js\";\nimport type { SyncMemorySnapshotItem, SyncResetRequired } from \"./types.js\";\nimport { queueVectorBackfillForSyncBootstrap } from \"./vector-migration.js\";\n\nexport { SYNC_BOOTSTRAP_CWD_PREFIX } from \"./sync-bootstrap-constants.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface BootstrapResult {\n\tok: boolean;\n\tapplied: number;\n\tdeleted: number;\n\terror?: string;\n}\n\nexport interface BootstrapApplicationOptions {\n\tactivityOptions?: { preserveError?: boolean };\n\tcursorPolicy?: \"preserve\";\n}\n\ninterface ExistingSnapshotRow {\n\tid: number;\n\trev: number | null;\n\tupdated_at: string;\n\tmetadata_json: string | null;\n}\n\nexport interface BootstrapOptions {\n\trequestExecutor?: RequestJsonExecutor;\n\t/** Source-only snapshots require recipient-bound transport and additive application. */\n\tsourceDeviceId?: string;\n\tkeysDir?: string;\n\tdbPath?: string;\n\tbootstrapGrantId?: string;\n\t/** Direct peer identity used to add recipient-bound v3 auth headers. */\n\trecipientId?: string;\n\t/** Max items per page request. Defaults to 200. */\n\tpageSize?: number;\n\t/** Timeout per HTTP request in seconds. Defaults to 10. */\n\ttimeoutS?: number;\n\t/** Safety cap on total snapshot items. Defaults to 100,000. */\n\tmaxItems?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Snapshot page fetcher\n// ---------------------------------------------------------------------------\n\ntype SnapshotPageResponse = ApiSyncMemorySnapshotPageResponse;\n\nfunction checkedSnapshotBoundary(\n\tpage: SnapshotPageResponse & { source_device_id?: unknown },\n\texpected: SyncResetRequired,\n\tsourceDeviceId?: string,\n) {\n\tif (sourceDeviceId && page.source_device_id !== sourceDeviceId)\n\t\tthrow new Error(\"retirement_snapshot_source_required\");\n\tif (\n\t\tpage.generation !== expected.generation ||\n\t\tpage.snapshot_id !== expected.snapshot_id ||\n\t\tpage.baseline_cursor !== expected.baseline_cursor\n\t)\n\t\tthrow new Error(\"snapshot_boundary_mismatch\");\n\treturn {\n\t\tgeneration: page.generation,\n\t\tsnapshot_id: page.snapshot_id,\n\t\tbaseline_cursor: page.baseline_cursor,\n\t};\n}\n\nfunction snapshotPageParams(\n\tresetInfo: SyncResetRequired,\n\tpageSize: number,\n\tpageToken: string | null,\n\tsourceDeviceId?: string,\n) {\n\tconst params = new URLSearchParams({\n\t\tgeneration: String(resetInfo.generation),\n\t\tsnapshot_id: resetInfo.snapshot_id,\n\t\tlimit: String(pageSize),\n\t});\n\tif (sourceDeviceId) params.set(\"source_device_id\", sourceDeviceId);\n\tif (resetInfo.baseline_cursor) params.set(\"baseline_cursor\", resetInfo.baseline_cursor);\n\tif (resetInfo.scope_id) params.set(\"scope_id\", resetInfo.scope_id);\n\tif (pageToken) params.set(\"page_token\", pageToken);\n\treturn params;\n}\n\nfunction checkedSnapshotSource(options?: BootstrapOptions): string | undefined {\n\tconst source = options?.sourceDeviceId;\n\tif (source !== undefined && (!source || source !== options?.recipientId?.trim()))\n\t\tthrow new Error(\"retirement_snapshot_source_required\");\n\treturn source;\n}\n\nfunction snapshotRequestExecutor(options?: BootstrapOptions): RequestJsonExecutor {\n\treturn options?.requestExecutor ?? requestJson;\n}\n\n/**\n * Fetch all snapshot pages from a peer's /v1/snapshot endpoint.\n * Returns the full list of items and the boundary metadata.\n */\nexport async function fetchAllSnapshotPages(\n\tbaseUrl: string,\n\tresetInfo: SyncResetRequired,\n\tdeviceId: string,\n\toptions?: BootstrapOptions,\n): Promise<{\n\titems: SyncMemorySnapshotItem[];\n\tgeneration: number;\n\tsnapshot_id: string;\n\tbaseline_cursor: string | null;\n}> {\n\tconst pageSize = options?.pageSize ?? 200;\n\tconst timeoutS = options?.timeoutS ?? 10;\n\tconst requestExecutor = snapshotRequestExecutor(options);\n\tconst keysDir = options?.keysDir;\n\tconst dbPath = options?.dbPath;\n\tconst bootstrapGrantId = options?.bootstrapGrantId?.trim() || undefined;\n\tconst recipientId = options?.recipientId?.trim() || undefined;\n\tconst maxItems = options?.maxItems ?? 100_000;\n\tconst sourceDeviceId = checkedSnapshotSource(options);\n\n\tconst allItems: SyncMemorySnapshotItem[] = [];\n\tlet pageToken: string | null = null;\n\tlet boundary: { generation: number; snapshot_id: string; baseline_cursor: string | null } | null =\n\t\tnull;\n\n\tfor (;;) {\n\t\tconst params = snapshotPageParams(resetInfo, pageSize, pageToken, sourceDeviceId);\n\n\t\tconst url = `${baseUrl}/v1/snapshot?${params.toString()}`;\n\t\tconst authOptions = {\n\t\t\tdeviceId,\n\t\t\tmethod: \"GET\",\n\t\t\turl,\n\t\t\tbodyBytes: Buffer.alloc(0),\n\t\t\tbootstrapGrantId,\n\t\t\tkeysDir,\n\t\t\tdbPath,\n\t\t};\n\t\tconst headers = {\n\t\t\t// Public callers that omit a recipient retain the legacy v2 wire contract. All\n\t\t\t// in-repo direct-peer callers provide recipientId and therefore emit v3.\n\t\t\t...(recipientId === undefined\n\t\t\t\t? buildAuthHeaders(authOptions)\n\t\t\t\t: buildDirectPeerAuthHeaders({ ...authOptions, recipientId })),\n\t\t\t[SYNC_CAPABILITY_HEADER]: LOCAL_SYNC_CAPABILITY,\n\t\t};\n\n\t\tconst [status, payload] = await requestExecutor(\"GET\", url, { headers, timeoutS });\n\t\tif (status !== 200 || !payload) {\n\t\t\tconst error = payload?.error ? String(payload.error) : \"\";\n\t\t\tconst reason = payload?.reason ? String(payload.reason) : \"\";\n\t\t\tconst detail = error ? (reason ? `${error}:${reason}` : error) : `status ${status}`;\n\t\t\tthrow new Error(`snapshot fetch failed: ${detail}`);\n\t\t}\n\n\t\tconst page = payload as unknown as SnapshotPageResponse;\n\t\tif (!Array.isArray(page.items) || page.generation == null) {\n\t\t\tthrow new Error(\"invalid snapshot response shape\");\n\t\t}\n\n\t\tboundary = checkedSnapshotBoundary(page, resetInfo, sourceDeviceId);\n\t\tallItems.push(...page.items);\n\n\t\tif (allItems.length > maxItems) {\n\t\t\tthrow new Error(\n\t\t\t\t`snapshot too large: ${allItems.length} items exceeds safety limit of ${maxItems}`,\n\t\t\t);\n\t\t}\n\n\t\tif (!page.has_more || !page.next_page_token) {\n\t\t\tbreak;\n\t\t}\n\t\tpageToken = page.next_page_token;\n\t}\n\n\tif (!boundary) {\n\t\tthrow new Error(\"no snapshot pages returned\");\n\t}\n\n\treturn { items: allItems, ...boundary };\n}\n\n// ---------------------------------------------------------------------------\n// Local application\n// ---------------------------------------------------------------------------\n\n/**\n * Parse a snapshot item's payload_json into memory fields.\n * Returns null if the payload is malformed.\n */\nfunction parseSnapshotPayload(item: SyncMemorySnapshotItem): Record<string, unknown> | null {\n\tif (!item.payload_json) return null;\n\ttry {\n\t\tconst parsed = JSON.parse(item.payload_json);\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return null;\n\t\treturn parsed as Record<string, unknown>;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction isEmbeddableSnapshotPayload(payload: Record<string, unknown>): boolean {\n\tconst title = typeof payload.title === \"string\" ? payload.title : \"\";\n\tconst bodyText = typeof payload.body_text === \"string\" ? payload.body_text : \"\";\n\treturn `${title}\\n${bodyText}`.trim().length > 0;\n}\n\nfunction retirementSnapshotItems(\n\tdb: Database,\n\titems: SyncMemorySnapshotItem[],\n\tscope: string | null,\n): SyncMemorySnapshotItem[] {\n\treturn items.filter((item) => {\n\t\tconst payload = parseSnapshotPayload(item);\n\t\treturn payload && retirementAllowsSnapshot(db, item.entity_id, payload, scope);\n\t});\n}\n\nfunction normalizeBootstrapScopeId(scopeId: unknown): string | null {\n\tif (typeof scopeId !== \"string\") return null;\n\tconst trimmed = scopeId.trim();\n\treturn trimmed.length > 0 ? trimmed : null;\n}\n\nfunction snapshotPayloadScopeId(\n\tpayload: Record<string, unknown>,\n\tbootstrapScopeId: string | null,\n): string | null {\n\tif (bootstrapScopeId) return bootstrapScopeId;\n\treturn normalizeBootstrapScopeId(payload.scope_id);\n}\n\nfunction validateSnapshotScopes(\n\titems: SyncMemorySnapshotItem[],\n\tbootstrapScopeId: string | null,\n): void {\n\tif (bootstrapScopeId === DEFAULT_SYNC_SCOPE_ID) throw new Error(\"scope_mismatch\");\n\tfor (const item of items) {\n\t\tconst payload = parseSnapshotPayload(item);\n\t\tif (!payload) continue;\n\t\tconst payloadScopeId = normalizeBootstrapScopeId(payload.scope_id);\n\t\tif (!bootstrapScopeId) throw new Error(\"scope_mismatch\");\n\t\tif (payloadScopeId && payloadScopeId !== bootstrapScopeId) {\n\t\t\tthrow new Error(\"scope_mismatch\");\n\t\t}\n\t}\n}\n\nconst bootstrapSessionCache = new Map<string, number>();\n\nfunction ensureSessionForBootstrap(\n\td: ReturnType<typeof drizzle>,\n\tupdatedAt: string,\n\tproject?: string | null,\n): number {\n\tconst projectKey = project ?? \"__none__\";\n\tconst cached = bootstrapSessionCache.get(projectKey);\n\tif (cached != null) return cached;\n\n\tconst cwd = project ? `${SYNC_BOOTSTRAP_CWD_PREFIX}:${project}` : SYNC_BOOTSTRAP_CWD_PREFIX;\n\tconst existing = d\n\t\t.select({ id: schema.sessions.id })\n\t\t.from(schema.sessions)\n\t\t.where(eq(schema.sessions.cwd, cwd))\n\t\t.limit(1)\n\t\t.get();\n\tif (existing) {\n\t\tbootstrapSessionCache.set(projectKey, existing.id);\n\t\treturn existing.id;\n\t}\n\n\tconst rows = d\n\t\t.insert(schema.sessions)\n\t\t.values({\n\t\t\tstarted_at: updatedAt,\n\t\t\tcwd,\n\t\t\tproject: project ?? null,\n\t\t\tuser: \"sync\",\n\t\t\ttool_version: \"bootstrap\",\n\t\t})\n\t\t.returning({ id: schema.sessions.id })\n\t\t.all();\n\tconst id = rows[0]?.id ?? 0;\n\tbootstrapSessionCache.set(projectKey, id);\n\treturn id;\n}\n\nfunction shouldReplaceExistingSnapshotRows(\n\texistingRows: ExistingSnapshotRow[],\n\titem: SyncMemorySnapshotItem,\n): boolean {\n\tif (existingRows.length === 0) return true;\n\t// Mirror the canonical last-writer-wins clock used by incremental\n\t// replication: rev → updated_at → clock_device_id. Without the device-id\n\t// tie-break, an exact rev+timestamp tie that the snapshot should win would\n\t// be skipped here while the scoped cursor/baseline still advances, leaving\n\t// the stale local row with no later pull to correct it.\n\tconst candidate: [number, string, string] = [\n\t\titem.clock_rev,\n\t\titem.clock_updated_at,\n\t\titem.clock_device_id,\n\t];\n\treturn existingRows.every((row) =>\n\t\tisNewerClock(candidate, [\n\t\t\ttypeof row.rev === \"number\" ? row.rev : 0,\n\t\t\trow.updated_at,\n\t\t\tclockDeviceIdFromMetadataJson(row.metadata_json),\n\t\t]),\n\t);\n}\n\nfunction insertSnapshotItem(\n\td: ReturnType<typeof drizzle>,\n\titem: SyncMemorySnapshotItem,\n\tbootstrapScopeId: string | null,\n\tactiveScanner: SecretScanner,\n): { applied: boolean; embeddable: boolean } {\n\tconst payload = parseSnapshotPayload(item);\n\tif (!payload) return { applied: false, embeddable: false };\n\tredactMemoryFields(payload, activeScanner);\n\tconst scopeId = snapshotPayloadScopeId(payload, bootstrapScopeId);\n\tconst project =\n\t\ttypeof payload.project === \"string\" && payload.project.trim() ? payload.project.trim() : null;\n\tconst sessionId = ensureSessionForBootstrap(d, new Date().toISOString(), project);\n\n\tconst metaRaw = payload.metadata_json;\n\tconst meta =\n\t\tmetaRaw && typeof metaRaw === \"object\" && !Array.isArray(metaRaw)\n\t\t\t? (metaRaw as Record<string, unknown>)\n\t\t\t: {};\n\tmeta.clock_device_id = item.clock_device_id;\n\n\tconst isDeleted = item.op_type === \"delete\";\n\n\td.insert(schema.memoryItems)\n\t\t.values({\n\t\t\tsession_id: sessionId,\n\t\t\tkind: typeof payload.kind === \"string\" ? payload.kind : \"discovery\",\n\t\t\ttitle: typeof payload.title === \"string\" ? payload.title : \"\",\n\t\t\tsubtitle: typeof payload.subtitle === \"string\" ? payload.subtitle : null,\n\t\t\tbody_text: typeof payload.body_text === \"string\" ? payload.body_text : \"\",\n\t\t\tconfidence: typeof payload.confidence === \"number\" ? payload.confidence : 0.5,\n\t\t\ttags_text: typeof payload.tags_text === \"string\" ? payload.tags_text : \"\",\n\t\t\tactive: isDeleted ? 0 : 1,\n\t\t\tcreated_at:\n\t\t\t\ttypeof payload.created_at === \"string\" ? payload.created_at : item.clock_updated_at,\n\t\t\tupdated_at: item.clock_updated_at,\n\t\t\tmetadata_json: toJson(meta),\n\t\t\timport_key: item.entity_id,\n\t\t\tdeleted_at: isDeleted ? item.clock_updated_at : null,\n\t\t\trev: item.clock_rev,\n\t\t\tactor_id: typeof payload.actor_id === \"string\" ? payload.actor_id : null,\n\t\t\tactor_display_name:\n\t\t\t\ttypeof payload.actor_display_name === \"string\" ? payload.actor_display_name : null,\n\t\t\tvisibility: typeof payload.visibility === \"string\" ? payload.visibility : \"shared\",\n\t\t\tworkspace_id:\n\t\t\t\ttypeof payload.workspace_id === \"string\" ? payload.workspace_id : \"shared:default\",\n\t\t\tworkspace_kind:\n\t\t\t\ttypeof payload.workspace_kind === \"string\" ? payload.workspace_kind : \"shared\",\n\t\t\torigin_device_id:\n\t\t\t\ttypeof payload.origin_device_id === \"string\"\n\t\t\t\t\t? payload.origin_device_id\n\t\t\t\t\t: item.clock_device_id,\n\t\t\torigin_source: typeof payload.origin_source === \"string\" ? payload.origin_source : null,\n\t\t\ttrust_state: typeof payload.trust_state === \"string\" ? payload.trust_state : \"trusted\",\n\t\t\tnarrative: typeof payload.narrative === \"string\" ? payload.narrative : null,\n\t\t\tfacts: Array.isArray(payload.facts) ? JSON.stringify(payload.facts) : null,\n\t\t\tconcepts: Array.isArray(payload.concepts) ? JSON.stringify(payload.concepts) : null,\n\t\t\tfiles_read: Array.isArray(payload.files_read) ? JSON.stringify(payload.files_read) : null,\n\t\t\tfiles_modified: Array.isArray(payload.files_modified)\n\t\t\t\t? JSON.stringify(payload.files_modified)\n\t\t\t\t: null,\n\t\t\tuser_prompt_id: typeof payload.user_prompt_id === \"number\" ? payload.user_prompt_id : null,\n\t\t\tprompt_number: typeof payload.prompt_number === \"number\" ? payload.prompt_number : null,\n\t\t\tscope_id: scopeId,\n\t\t\t// Persist the originating project name from the snapshot so the\n\t\t\t// Projects read model can surface this memory under its real\n\t\t\t// project identity on this receiver.\n\t\t\tproject,\n\t\t})\n\t\t.run();\n\n\treturn { applied: true, embeddable: !isDeleted && isEmbeddableSnapshotPayload(payload) };\n}\n\nfunction clearScopedAckedCursor(db: Database, peerDeviceId: string, scopeId: string): void {\n\tdrizzle(db, { schema })\n\t\t.update(schema.replicationCursorsV2)\n\t\t.set({ last_acked_cursor: null, updated_at: new Date().toISOString() })\n\t\t.where(\n\t\t\tand(\n\t\t\t\teq(schema.replicationCursorsV2.peer_device_id, peerDeviceId),\n\t\t\t\teq(schema.replicationCursorsV2.scope_id, scopeId),\n\t\t\t),\n\t\t)\n\t\t.run();\n}\n\n/**\n * Apply a bootstrap snapshot to the local database, atomically replacing\n * synced memories in the requested scope with the snapshot contents.\n *\n * This runs in a single IMMEDIATE transaction:\n * 1. For an explicit scope, delete local shared-visibility memory_items in\n * that scope (preserving private and other-scope rows). Unscoped bootstrap\n * is non-destructive because its serving lane contains no regular rows.\n * 2. Insert all snapshot items (upsert handles tombstones via active/deleted_at)\n * 3. Update the replication cursor to baseline_cursor\n * 4. Bump the local generation + snapshot_id to match the peer\n */\nexport function applyBootstrapSnapshot(\n\tdb: Database,\n\tpeerDeviceId: string,\n\titems: SyncMemorySnapshotItem[],\n\tresetInfo: SyncResetRequired,\n\tscanner?: SecretScanner,\n\toptions?: BootstrapApplicationOptions,\n): BootstrapResult {\n\tconst result = newBootstrapResult();\n\t// Bootstrap items are peer-authored content. Run them through the same\n\t// scanner as locally-authored writes; without this, a single bootstrap\n\t// from a misbehaving peer could re-populate the local store with secrets\n\t// the peer emitted before they ran scanner-aware versions.\n\tconst activeScanner = scanner ?? new SecretScanner();\n\tconst bootstrapScopeId = normalizeBootstrapScopeId(resetInfo.scope_id);\n\tvalidateSnapshotScopes(items, bootstrapScopeId);\n\n\tdb.transaction(() => {\n\t\tconst d = drizzle(db, { schema });\n\t\tlet embeddableApplied = 0;\n\n\t\t// 1. Delete local sync-eligible memories only for an explicit bootstrap scope.\n\t\t// - Only memories with import_key (i.e. previously synced) are deleted.\n\t\t// - Bootstrap for one Sharing domain must not wipe rows from another.\n\t\t// - Only explicitly private memories are preserved; NULL visibility is\n\t\t// treated as sync-eligible (matching syncVisibilityAllowed semantics)\n\t\t// to avoid leaving stale rows that could create duplicate import_keys.\n\t\t// - The dirty-local gate in sync-pass ensures we only reach here when\n\t\t// no unsynced shared changes exist.\n\t\tif (bootstrapScopeId) {\n\t\t\tresult.deleted = deleteSyncedMemoriesInScope(db, bootstrapScopeId);\n\t\t}\n\n\t\t// 2. Insert snapshot items, grouping by project.\n\t\tbootstrapSessionCache.clear();\n\n\t\tfor (const item of retirementSnapshotItems(db, items, bootstrapScopeId)) {\n\t\t\tconst inserted = insertSnapshotItem(d, item, bootstrapScopeId, activeScanner);\n\t\t\tif (!inserted.applied) continue;\n\t\t\trecordForeignMemoryRevision(db, item.entity_id, \"bootstrap\");\n\t\t\tif (inserted.embeddable) embeddableApplied++;\n\t\t\tresult.applied++;\n\t\t\trecordSnapshotReceipt(db, peerDeviceId, item, bootstrapScopeId);\n\t\t}\n\n\t\t// 3. Update replication cursor to baseline_cursor. For scoped null-baseline\n\t\t// snapshots, baseline_cursor can be null; store a hidden marker in the\n\t\t// scoped cursor row so status can distinguish \"this peer/scope bootstrap\n\t\t// completed without a cursor boundary\" from \"this scope was never attempted\".\n\t\tif (resetInfo.baseline_cursor || resetInfo.scope_id) {\n\t\t\tif (resetInfo.scope_id && !resetInfo.baseline_cursor) {\n\t\t\t\tclearReplicationCursorLastApplied(db, peerDeviceId, resetInfo.scope_id);\n\t\t\t}\n\t\t\tif (resetInfo.scope_id && resetInfo.baseline_cursor) {\n\t\t\t\tclearScopedAckedCursor(db, peerDeviceId, resetInfo.scope_id);\n\t\t\t}\n\t\t\tsetReplicationCursor(\n\t\t\t\tdb,\n\t\t\t\tpeerDeviceId,\n\t\t\t\t{\n\t\t\t\t\tlastApplied: resetInfo.baseline_cursor,\n\t\t\t\t\tlastAcked: resetInfo.baseline_cursor\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: SCOPED_NULL_BASELINE_BOOTSTRAP_CURSOR_MARKER,\n\t\t\t\t},\n\t\t\t\tresetInfo.scope_id,\n\t\t\t);\n\t\t}\n\n\t\t// 4. Bump local generation + snapshot_id to match the peer.\n\t\tsetSyncResetState(\n\t\t\tdb,\n\t\t\t{\n\t\t\t\tgeneration: resetInfo.generation,\n\t\t\t\tsnapshot_id: resetInfo.snapshot_id,\n\t\t\t\tbaseline_cursor: resetInfo.baseline_cursor,\n\t\t\t},\n\t\t\tresetInfo.scope_id,\n\t\t);\n\n\t\tqueueVectorBackfillForSyncBootstrap(db, { embeddableTotal: embeddableApplied });\n\n\t\tfinishSnapshotActivity(db, peerDeviceId, result, options);\n\t}).immediate();\n\n\treturn result;\n}\n\nfunction deleteSyncedMemoriesInScope(db: Database, scopeId: string): number {\n\tconst d = drizzle(db, { schema });\n\tconst deletePredicate = and(\n\t\tisNotNull(schema.memoryItems.import_key),\n\t\teq(schema.memoryItems.scope_id, scopeId),\n\t\tne(sql`COALESCE(${schema.memoryItems.visibility}, '')`, \"private\"),\n\t);\n\tconst affectedRows = d\n\t\t.select({ id: schema.memoryItems.id })\n\t\t.from(schema.memoryItems)\n\t\t.where(deletePredicate)\n\t\t.all();\n\tsnapshotSessionExportKeysForMemoryIds(\n\t\tdb,\n\t\taffectedRows.map((row) => row.id),\n\t);\n\treturn d.delete(schema.memoryItems).where(deletePredicate).run().changes;\n}\n\nfunction advanceMergedSnapshotBoundary(\n\tdb: Database,\n\tpeerDeviceId: string,\n\tresetInfo: SyncResetRequired,\n\toptions?: BootstrapApplicationOptions,\n): void {\n\tif (options?.cursorPolicy === \"preserve\") return;\n\tif (resetInfo.baseline_cursor || resetInfo.scope_id) {\n\t\tif (resetInfo.scope_id && !resetInfo.baseline_cursor)\n\t\t\tclearReplicationCursorLastApplied(db, peerDeviceId, resetInfo.scope_id);\n\t\tif (resetInfo.scope_id && resetInfo.baseline_cursor)\n\t\t\tclearScopedAckedCursor(db, peerDeviceId, resetInfo.scope_id);\n\t\tsetReplicationCursor(\n\t\t\tdb,\n\t\t\tpeerDeviceId,\n\t\t\t{\n\t\t\t\tlastApplied: resetInfo.baseline_cursor,\n\t\t\t\tlastAcked: resetInfo.baseline_cursor\n\t\t\t\t\t? undefined\n\t\t\t\t\t: SCOPED_NULL_BASELINE_BOOTSTRAP_CURSOR_MARKER,\n\t\t\t},\n\t\t\tresetInfo.scope_id,\n\t\t);\n\t}\n\tsetSyncResetState(\n\t\tdb,\n\t\t{\n\t\t\tgeneration: resetInfo.generation,\n\t\t\tsnapshot_id: resetInfo.snapshot_id,\n\t\t\tbaseline_cursor: resetInfo.baseline_cursor,\n\t\t},\n\t\tresetInfo.scope_id,\n\t);\n}\n\n/**\n * Additively merge a peer snapshot into an already-populated scope.\n *\n * Unlike `applyBootstrapSnapshot`, this does not delete local imported rows that\n * are absent from the peer snapshot. It only inserts missing snapshot entities\n * or replaces stale copies of the same snapshot entity. Use this when a scoped\n * peer has no cursor yet but the receiver already has rows in that scope from\n * another source, making destructive bootstrap unsafe.\n * Source subsets must preserve the whole-scope cursor and reset boundary.\n */\nexport function mergeBootstrapSnapshot(\n\tdb: Database,\n\tpeerDeviceId: string,\n\titems: SyncMemorySnapshotItem[],\n\tresetInfo: SyncResetRequired,\n\tscanner?: SecretScanner,\n\toptions?: BootstrapApplicationOptions,\n): BootstrapResult {\n\tconst result = newBootstrapResult();\n\tconst activeScanner = scanner ?? new SecretScanner();\n\tconst bootstrapScopeId = normalizeBootstrapScopeId(resetInfo.scope_id);\n\tvalidateSnapshotScopes(items, bootstrapScopeId);\n\tconst mergeScopePredicate = bootstrapScopeId\n\t\t? eq(schema.memoryItems.scope_id, bootstrapScopeId)\n\t\t: or(\n\t\t\t\tisNull(schema.memoryItems.scope_id),\n\t\t\t\teq(schema.memoryItems.scope_id, DEFAULT_SYNC_SCOPE_ID),\n\t\t\t);\n\n\tdb.transaction(() => {\n\t\tconst d = drizzle(db, { schema });\n\t\tlet embeddableApplied = 0;\n\t\tbootstrapSessionCache.clear();\n\n\t\tfor (const item of retirementSnapshotItems(db, items, bootstrapScopeId)) {\n\t\t\tif (!parseSnapshotPayload(item)) continue;\n\t\t\tconst existingRows = d\n\t\t\t\t.select({\n\t\t\t\t\tid: schema.memoryItems.id,\n\t\t\t\t\trev: schema.memoryItems.rev,\n\t\t\t\t\tupdated_at: schema.memoryItems.updated_at,\n\t\t\t\t\tmetadata_json: schema.memoryItems.metadata_json,\n\t\t\t\t})\n\t\t\t\t.from(schema.memoryItems)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(schema.memoryItems.import_key, item.entity_id),\n\t\t\t\t\t\tmergeScopePredicate,\n\t\t\t\t\t\tne(sql`COALESCE(${schema.memoryItems.visibility}, '')`, \"private\"),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.all();\n\n\t\t\tif (!shouldReplaceExistingSnapshotRows(existingRows, item)) continue;\n\n\t\t\tconst existingIds = existingRows.map((row) => row.id);\n\t\t\tif (existingIds.length > 0) {\n\t\t\t\tsnapshotSessionExportKeysForMemoryIds(db, existingIds);\n\t\t\t\tconst deleteResult = d\n\t\t\t\t\t.delete(schema.memoryItems)\n\t\t\t\t\t.where(inArray(schema.memoryItems.id, existingIds))\n\t\t\t\t\t.run();\n\t\t\t\tresult.deleted += deleteResult.changes;\n\t\t\t}\n\n\t\t\tconst inserted = insertSnapshotItem(d, item, bootstrapScopeId, activeScanner);\n\t\t\tif (!inserted.applied) continue;\n\t\t\trecordForeignMemoryRevision(db, item.entity_id, \"bootstrap\");\n\t\t\tif (inserted.embeddable) embeddableApplied++;\n\t\t\tresult.applied++;\n\t\t\trecordSnapshotReceipt(db, peerDeviceId, item, bootstrapScopeId);\n\t\t}\n\n\t\tadvanceMergedSnapshotBoundary(db, peerDeviceId, resetInfo, options);\n\n\t\tqueueVectorBackfillForSyncBootstrap(db, { embeddableTotal: embeddableApplied });\n\t\tfinishSnapshotActivity(db, peerDeviceId, result, options);\n\t}).immediate();\n\n\treturn result;\n}\n\nfunction recordSnapshotReceipt(\n\tdb: Database,\n\tpeerDeviceId: string,\n\titem: SyncMemorySnapshotItem,\n\tscopeId: string | null,\n): void {\n\tconst id = JSON.stringify([\n\t\tscopeId,\n\t\titem.entity_id,\n\t\titem.op_type,\n\t\titem.clock_rev,\n\t\titem.clock_updated_at,\n\t\titem.clock_device_id,\n\t]);\n\trecordSyncTransferReceipts(db, peerDeviceId, \"receive\", [id], { kind: \"snapshot\" });\n}\n\nfunction finishSnapshotActivity(\n\tdb: Database,\n\tpeerDeviceId: string,\n\tresult: BootstrapResult,\n\toptions?: BootstrapApplicationOptions,\n): void {\n\trecordSyncTransferObservation(db, peerDeviceId, \"receive\", options?.activityOptions);\n\tresult.ok = true;\n}\n\nfunction newBootstrapResult(): BootstrapResult {\n\treturn { ok: false, applied: 0, deleted: 0 };\n}\n","/**\n * Peer discovery and address management for the codemem sync system.\n *\n * Handles address normalization, deduplication, peer address storage,\n * and cross-platform mDNS advertise/discover via `bonjour-service`.\n */\n\nimport { createRequire } from \"node:module\";\nimport { eq } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport {\n\tformatHostPort,\n\tmergeAddresses,\n\tmergeCoordinatorPeerAddresses,\n\tnormalizeAddress,\n} from \"./address-utils.js\";\nimport { readCoordinatorSyncConfig } from \"./coordinator-sync-config.js\";\nimport {\n\ttype Database,\n\tensureSyncAttemptFailureCategoryColumn,\n\tensureSyncAttemptTransportColumn,\n} from \"./db.js\";\nimport * as schema from \"./schema.js\";\nimport type { SyncAttemptFailureCategory } from \"./sync-pass.js\";\nimport { loadManualPeerAddresses, loadPeerAddresses } from \"./sync-peer-addresses.js\";\n\nconst requireFromHere = createRequire(import.meta.url);\n\n// Re-export for consumers that import from sync-discovery\nexport {\n\taddressDedupeKey,\n\tformatHostPort,\n\tmergeAddresses,\n\tnormalizeAddress,\n} from \"./address-utils.js\";\nexport { loadPeerAddresses, updatePeerAddresses } from \"./sync-peer-addresses.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nexport const DEFAULT_SERVICE_TYPE = \"_codemem._tcp.local.\";\n\n// ---------------------------------------------------------------------------\n// Address selection\n// ---------------------------------------------------------------------------\n\n/**\n * Select addresses to dial, preferring mDNS-discovered addresses.\n *\n * mDNS addresses come first, then stored addresses (deduplicated).\n */\nexport function selectDialAddresses(options: { stored: string[]; mdns: string[] }): string[] {\n\tif (options.mdns.length === 0) {\n\t\treturn mergeAddresses(options.stored, []);\n\t}\n\treturn mergeAddresses(options.mdns, options.stored);\n}\n\n// ---------------------------------------------------------------------------\n// Peer address storage (DB)\n// ---------------------------------------------------------------------------\n\n/**\n * Record a sync attempt in the sync_attempts table and update peer status.\n */\nexport function recordSyncAttempt(\n\tdb: Database,\n\tpeerDeviceId: string,\n\toptions: {\n\t\tok: boolean;\n\t\topsIn?: number;\n\t\topsOut?: number;\n\t\terror?: string;\n\t\tfailureCategory?: SyncAttemptFailureCategory;\n\t\ttransport?: \"direct\" | \"relay\";\n\t},\n): void {\n\t// Exported for direct callers whose connect() skips the additive schema pass.\n\tensureSyncAttemptFailureCategoryColumn(db);\n\tensureSyncAttemptTransportColumn(db);\n\tconst d = drizzle(db, { schema });\n\tconst now = new Date().toISOString();\n\td.insert(schema.syncAttempts)\n\t\t.values({\n\t\t\tpeer_device_id: peerDeviceId,\n\t\t\tstarted_at: now,\n\t\t\tfinished_at: now,\n\t\t\tok: options.ok ? 1 : 0,\n\t\t\tops_in: options.opsIn ?? 0,\n\t\t\tops_out: options.opsOut ?? 0,\n\t\t\terror: options.error ?? null,\n\t\t\tfailure_category: options.ok ? null : (options.failureCategory ?? \"other\"),\n\t\t\ttransport: options.transport ?? null,\n\t\t})\n\t\t.run();\n\n\tif (options.ok) {\n\t\td.update(schema.syncPeers)\n\t\t\t.set({ last_sync_at: now, last_error: null })\n\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t.run();\n\t} else {\n\t\td.update(schema.syncPeers)\n\t\t\t.set({ last_error: options.error ?? null })\n\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t.run();\n\t}\n}\n\n/**\n * Record a successful sync and promote the working address to the front.\n *\n * Returns the reordered address list.\n */\nexport function recordPeerSuccess(\n\tdb: Database,\n\tpeerDeviceId: string,\n\taddress: string | null,\n): string[] {\n\tconst normalized = normalizeAddress(address ?? \"\");\n\tconst now = new Date().toISOString();\n\tconst promote = db.transaction((deviceId: string, promotedAddress: string, syncedAt: string) => {\n\t\tconst addresses = loadPeerAddresses(db, deviceId);\n\t\tconst remaining = promotedAddress\n\t\t\t? addresses.filter((item) => normalizeAddress(item) !== promotedAddress)\n\t\t\t: addresses;\n\t\tconst manual = loadManualPeerAddresses(db, deviceId) ?? addresses;\n\t\tconst ordered = mergeCoordinatorPeerAddresses(\n\t\t\t[],\n\t\t\tpromotedAddress ? [promotedAddress, ...remaining] : addresses,\n\t\t\tmanual,\n\t\t\t{\n\t\t\t\trequiredFreshAddresses: promotedAddress ? 1 : 0,\n\t\t\t\tsuccessfulAddress: promotedAddress || undefined,\n\t\t\t},\n\t\t);\n\t\tconst d = drizzle(db, { schema });\n\t\td.update(schema.syncPeers)\n\t\t\t.set({\n\t\t\t\taddresses_json: JSON.stringify(ordered),\n\t\t\t\tmanual_addresses_json: JSON.stringify(manual),\n\t\t\t\t...(promotedAddress ? { last_success_address: promotedAddress } : {}),\n\t\t\t\tlast_sync_at: syncedAt,\n\t\t\t\tlast_seen_at: syncedAt,\n\t\t\t\tlast_error: null,\n\t\t\t})\n\t\t\t.where(eq(schema.syncPeers.peer_device_id, deviceId))\n\t\t\t.run();\n\t\treturn ordered;\n\t});\n\treturn promote.immediate(peerDeviceId, normalized, now);\n}\n\n// ---------------------------------------------------------------------------\n// Project filters\n// ---------------------------------------------------------------------------\n\n/**\n * Set per-peer project include/exclude filters.\n *\n * Pass null for both to clear the override (inherit global config).\n */\nexport function setPeerProjectFilter(\n\tdb: Database,\n\tpeerDeviceId: string,\n\toptions: {\n\t\tinclude: string[] | null;\n\t\texclude: string[] | null;\n\t},\n): void {\n\tconst includeJson = options.include === null ? null : JSON.stringify(options.include);\n\tconst excludeJson = options.exclude === null ? null : JSON.stringify(options.exclude);\n\tconst d = drizzle(db, { schema });\n\td.update(schema.syncPeers)\n\t\t.set({ projects_include_json: includeJson, projects_exclude_json: excludeJson })\n\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t.run();\n}\n\n/**\n * Set the claimed_local_actor flag for a peer.\n */\nexport function setPeerLocalActorClaim(db: Database, peerDeviceId: string, claimed: boolean): void {\n\tconst d = drizzle(db, { schema });\n\td.update(schema.syncPeers)\n\t\t.set({ claimed_local_actor: claimed ? 1 : 0 })\n\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t.run();\n}\n\n// ---------------------------------------------------------------------------\n// mDNS peer discovery (cross-platform via bonjour-service)\n// ---------------------------------------------------------------------------\n\nexport interface MdnsEntry {\n\tname?: string;\n\thost?: string;\n\tport?: number;\n\taddress?: Uint8Array | string;\n\tproperties?: Record<string, string | Uint8Array>;\n}\n\nexport function normalizeMdnsTxtProperties(\n\ttxt: Record<string, unknown>,\n): Record<string, string | Uint8Array> {\n\tconst properties: Record<string, string | Uint8Array> = {};\n\tfor (const [key, value] of Object.entries(txt)) {\n\t\tproperties[key] = value instanceof Uint8Array ? value : String(value);\n\t}\n\treturn properties;\n}\n\nconst MDNS_SERVICE_TYPE = \"codemem\"; // advertises as _codemem._tcp.local.\n\n/**\n * Returns true when mDNS discovery should be active on this device.\n *\n * Reads the merged codemem config (so the Settings UI toggle is\n * authoritative) with an env-var override (`CODEMEM_SYNC_MDNS`) for\n * one-off runs. Previously env-only, which silently ignored the UI\n * toggle.\n */\nexport function mdnsEnabled(): boolean {\n\tconst envValue = process.env.CODEMEM_SYNC_MDNS;\n\tif (envValue) return envValue === \"1\" || envValue.toLowerCase() === \"true\";\n\ttry {\n\t\treturn readCoordinatorSyncConfig().syncMdns;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// Lazy-import `bonjour-service` so users who disable embeddings or run\n// in environments where the multicast socket can't bind don't pay the\n// startup cost. Returns null when the module isn't available.\ninterface BonjourLike {\n\tpublish: (opts: { name: string; type: string; port: number; txt?: Record<string, string> }) => {\n\t\tstop: (cb?: () => void) => void;\n\t};\n\tfind: (\n\t\topts: { type: string },\n\t\tonUp?: (svc: {\n\t\t\tname: string;\n\t\t\thost?: string;\n\t\t\tfqdn?: string;\n\t\t\tport: number;\n\t\t\taddresses?: string[];\n\t\t\ttxt?: Record<string, string>;\n\t\t}) => void,\n\t) => { stop: () => void };\n\tdestroy: () => void;\n}\n\ntype BonjourCtor = new (\n\topts?: Record<string, unknown>,\n\terrorCallback?: (err: Error) => void,\n) => BonjourLike;\n\nfunction loadBonjour(): BonjourLike | null {\n\ttry {\n\t\tconst mod = requireFromHere(\"bonjour-service\") as {\n\t\t\tBonjour?: BonjourCtor;\n\t\t\tdefault?: BonjourCtor;\n\t\t};\n\t\tconst Ctor = mod.Bonjour ?? mod.default;\n\t\tif (!Ctor) return null;\n\t\t// Pass an error callback so mDNS runtime errors (bind failures on\n\t\t// restricted containers, interface churn, multicast blocked) stay\n\t\t// contained instead of propagating as uncaught exceptions and\n\t\t// taking down the sync/viewer process. Degrades to no-op on error.\n\t\treturn new Ctor(undefined, (err: Error) => {\n\t\t\tconsole.warn(\"[codemem] mDNS runtime error (non-fatal):\", err?.message ?? err);\n\t\t});\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n// Shared Bonjour instance: advertise + discover reuse a single multicast\n// socket, refcounted across callers. This avoids churn where each call would\n// otherwise spin up a fresh bind-release cycle and race its own publish/find\n// against destroy(). The instance is lazily created on first acquire and torn\n// down when the last caller releases.\nlet sharedInstance: BonjourLike | null = null;\nlet sharedRefcount = 0;\n\nfunction acquireBonjour(): BonjourLike | null {\n\tif (sharedInstance) {\n\t\tsharedRefcount += 1;\n\t\treturn sharedInstance;\n\t}\n\tconst instance = loadBonjour();\n\tif (!instance) return null;\n\tsharedInstance = instance;\n\tsharedRefcount = 1;\n\treturn sharedInstance;\n}\n\nfunction releaseBonjour(): void {\n\tif (!sharedInstance) return;\n\tsharedRefcount = Math.max(0, sharedRefcount - 1);\n\tif (sharedRefcount > 0) return;\n\tconst instance = sharedInstance;\n\tsharedInstance = null;\n\ttry {\n\t\tinstance.destroy();\n\t} catch {\n\t\t// best effort\n\t}\n}\n\n/**\n * Internal: reset shared instance state. Exposed for tests only.\n */\nexport function __resetMdnsForTests(): void {\n\tif (sharedInstance) {\n\t\ttry {\n\t\t\tsharedInstance.destroy();\n\t\t} catch {\n\t\t\t// best effort\n\t\t}\n\t}\n\tsharedInstance = null;\n\tsharedRefcount = 0;\n}\n\n/**\n * Advertise this device as a codemem sync peer via mDNS.\n *\n * Returns a closer that tears down the advertisement. No-op when mDNS\n * is disabled, when `bonjour-service` failed to load, or when the\n * multicast socket cannot bind.\n */\nexport function advertiseMdns(deviceId: string, port: number): { close(): void } {\n\tif (!mdnsEnabled()) return { close() {} };\n\tif (!deviceId || !port || !Number.isFinite(port)) return { close() {} };\n\n\tconst bonjour = acquireBonjour();\n\tif (!bonjour) return { close() {} };\n\n\tlet advertisement: { stop: (cb?: () => void) => void } | null = null;\n\ttry {\n\t\tadvertisement = bonjour.publish({\n\t\t\tname: `codemem-${deviceId.slice(0, 12)}`,\n\t\t\ttype: MDNS_SERVICE_TYPE,\n\t\t\tport,\n\t\t\ttxt: { device_id: deviceId },\n\t\t});\n\t} catch {\n\t\treleaseBonjour();\n\t\treturn { close() {} };\n\t}\n\n\tlet closed = false;\n\treturn {\n\t\tclose() {\n\t\t\tif (closed) return;\n\t\t\tclosed = true;\n\t\t\tconst release = () => releaseBonjour();\n\t\t\ttry {\n\t\t\t\t// Wait for publish to acknowledge the stop before releasing the\n\t\t\t\t// shared instance so the unpublish actually reaches the wire.\n\t\t\t\tadvertisement?.stop(() => release());\n\t\t\t} catch {\n\t\t\t\trelease();\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Discover codemem sync peers via mDNS. Blocks up to `timeoutMs` (default\n * 1500) collecting `_codemem._tcp.local.` responders, then returns the\n * entries it saw. No-op / empty array when mDNS is disabled or the\n * module couldn't load.\n */\nexport async function discoverPeersViaMdns(timeoutMs = 1500): Promise<MdnsEntry[]> {\n\tif (!mdnsEnabled()) return [];\n\n\tconst bonjour = acquireBonjour();\n\tif (!bonjour) return [];\n\n\tconst found: MdnsEntry[] = [];\n\tconst seen = new Set<string>();\n\t// Ignore late `onUp` callbacks that fire after the timeout elapses — the\n\t// browser's `stop()` is best-effort and can race in-flight dispatches.\n\tlet acceptingResults = true;\n\tlet browser: { stop: () => void } | null = null;\n\ttry {\n\t\tbrowser = bonjour.find({ type: MDNS_SERVICE_TYPE }, (svc) => {\n\t\t\tif (!acceptingResults) return;\n\t\t\tconst key = `${svc.name}|${svc.host ?? svc.fqdn ?? \"\"}|${svc.port}`;\n\t\t\tif (seen.has(key)) return;\n\t\t\tseen.add(key);\n\t\t\tconst addresses = Array.isArray(svc.addresses) ? svc.addresses : [];\n\t\t\tconst resolvedAddress =\n\t\t\t\taddresses.find((addr) => addr && /^[\\d.]+$/.test(addr)) ??\n\t\t\t\taddresses.find((addr) => typeof addr === \"string\" && addr.trim().length > 0);\n\t\t\tconst rawTxt = svc.txt ?? {};\n\t\t\tfound.push({\n\t\t\t\tname: svc.name,\n\t\t\t\thost: (svc.host || svc.fqdn || \"\").replace(/\\.$/, \"\"),\n\t\t\t\tport: svc.port,\n\t\t\t\taddress: resolvedAddress,\n\t\t\t\tproperties: normalizeMdnsTxtProperties(rawTxt),\n\t\t\t});\n\t\t});\n\t\tawait new Promise<void>((resolve) => setTimeout(resolve, Math.max(100, timeoutMs)));\n\t} finally {\n\t\tacceptingResults = false;\n\t\ttry {\n\t\t\tbrowser?.stop();\n\t\t} catch {\n\t\t\t// best effort\n\t\t}\n\t\treleaseBonjour();\n\t}\n\treturn found;\n}\n\n/**\n * Extract addresses for a specific peer from mDNS discovery entries.\n */\nexport function mdnsAddressesForPeer(peerDeviceId: string, entries: MdnsEntry[]): string[] {\n\tconst addresses: string[] = [];\n\tfor (const entry of entries) {\n\t\tconst props = entry.properties ?? {};\n\t\tlet deviceId: string | Uint8Array | undefined =\n\t\t\tprops.device_id ??\n\t\t\t((props as Record<string, unknown>).device_id as string | Uint8Array | undefined);\n\t\tif (deviceId == null) continue;\n\t\tif (deviceId instanceof Uint8Array) {\n\t\t\tdeviceId = new TextDecoder().decode(deviceId);\n\t\t}\n\t\tif (deviceId !== peerDeviceId) continue;\n\n\t\tconst port = entry.port ?? 0;\n\t\tif (!port) continue;\n\n\t\t// Prefer entry.address (resolved IP) over entry.host (service name).\n\t\t// mDNS responses often carry a service-name host (e.g. _codemem._tcp.local)\n\t\t// that isn't directly dialable, but include the usable IP in address.\n\t\tconst address = (entry as Record<string, unknown>).address as string | undefined;\n\t\tconst host = entry.host ?? \"\";\n\t\tconst dialHost = address && !address.includes(\".local\") ? address : host;\n\t\tif (dialHost && !dialHost.includes(\"_tcp.local\") && !dialHost.includes(\"_udp.local\")) {\n\t\t\tconst normalized = normalizeAddress(formatHostPort(dialHost, port));\n\t\t\tif (normalized) addresses.push(normalized);\n\t\t}\n\t}\n\treturn addresses;\n}\n","import type { Database } from \"./db.js\";\n\nexport interface SyncChannelBoundary {\n\tgeneration: number;\n\tsnapshot_id: string;\n\tbaseline_cursor: string | null;\n}\n\nexport interface SyncChannelProgress extends SyncChannelBoundary {\n\tlast_acked_cursor: string | null;\n}\n\ninterface ProgressTarget {\n\tpeerDeviceId: string;\n\tscopeId: string;\n\tboundary: SyncChannelBoundary;\n}\n\n// Installed only by the opt-in channel pass, after explicit scope authorization.\nfunction ensureSyncChannelProgress(db: Database): void {\n\tdb.exec(`CREATE TABLE IF NOT EXISTS sync_channel_progress (\n\t\tpeer_device_id TEXT NOT NULL,\n\t\tscope_id TEXT NOT NULL,\n\t\tgeneration INTEGER NOT NULL,\n\t\tsnapshot_id TEXT NOT NULL,\n\t\tbaseline_cursor TEXT,\n\t\tlast_acked_cursor TEXT,\n\t\tPRIMARY KEY (peer_device_id, scope_id)\n\t)`);\n}\n\nexport function getSyncChannelProgress(\n\tdb: Database,\n\tpeerDeviceId: string,\n\tscopeId: string,\n): SyncChannelProgress | null {\n\tensureSyncChannelProgress(db);\n\treturn (\n\t\t(db\n\t\t\t.prepare(`SELECT generation, snapshot_id, baseline_cursor, last_acked_cursor\n\t\tFROM sync_channel_progress WHERE peer_device_id = ? AND scope_id = ?`)\n\t\t\t.get(peerDeviceId, scopeId) as SyncChannelProgress | undefined) ?? null\n\t);\n}\n\nexport function clearSyncChannelProgress(\n\tdb: Database,\n\tpeerDeviceId: string,\n\tscopeId: string,\n): void {\n\tensureSyncChannelProgress(db);\n\tdb.prepare(\"DELETE FROM sync_channel_progress WHERE peer_device_id = ? AND scope_id = ?\").run(\n\t\tpeerDeviceId,\n\t\tscopeId,\n\t);\n}\n\nexport function hasCompletedSyncChannelBoundary(\n\tprogress: SyncChannelProgress | null,\n\tboundary: SyncChannelBoundary,\n): boolean {\n\treturn (\n\t\tprogress !== null &&\n\t\tprogress.generation === boundary.generation &&\n\t\tprogress.snapshot_id === boundary.snapshot_id &&\n\t\tprogress.baseline_cursor === boundary.baseline_cursor\n\t);\n}\n\n/** Save only after durable pull success. A changed peer boundary invalidates its outbound ACK. */\nexport function saveSyncChannelCompletedBoundary(db: Database, target: ProgressTarget): void {\n\tensureSyncChannelProgress(db);\n\tconst { peerDeviceId, scopeId, boundary } = target;\n\tdb.prepare(`INSERT INTO sync_channel_progress\n\t\t(peer_device_id, scope_id, generation, snapshot_id, baseline_cursor, last_acked_cursor)\n\t\tVALUES (?, ?, ?, ?, ?, NULL)\n\t\tON CONFLICT (peer_device_id, scope_id) DO UPDATE SET\n\t\tlast_acked_cursor = CASE WHEN generation = excluded.generation\n\t\t\tAND snapshot_id = excluded.snapshot_id AND baseline_cursor IS excluded.baseline_cursor\n\t\t\tTHEN last_acked_cursor ELSE NULL END,\n\t\tgeneration = excluded.generation, snapshot_id = excluded.snapshot_id,\n\t\tbaseline_cursor = excluded.baseline_cursor`).run(\n\t\tpeerDeviceId,\n\t\tscopeId,\n\t\tboundary.generation,\n\t\tboundary.snapshot_id,\n\t\tboundary.baseline_cursor,\n\t);\n}\n\n/** Bind ACK to the completed pull boundary, including when another pass changed it meanwhile. */\nexport function saveSyncChannelOutboundAck(\n\tdb: Database,\n\ttarget: ProgressTarget & { cursor: string },\n): void {\n\tconst { peerDeviceId, scopeId, boundary, cursor } = target;\n\tconst result = db\n\t\t.prepare(`UPDATE sync_channel_progress SET last_acked_cursor = ?\n\t\tWHERE peer_device_id = ? AND scope_id = ? AND generation = ? AND snapshot_id = ?\n\t\tAND baseline_cursor IS ? AND (last_acked_cursor IS NULL OR last_acked_cursor <= ?)`)\n\t\t.run(\n\t\t\tcursor,\n\t\t\tpeerDeviceId,\n\t\t\tscopeId,\n\t\t\tboundary.generation,\n\t\t\tboundary.snapshot_id,\n\t\t\tboundary.baseline_cursor,\n\t\t\tcursor,\n\t\t);\n\tif (result.changes !== 1) throw new Error(\"channel progress changed\");\n}\n","import type { SyncFailureCategory } from \"./sync-pass.js\";\n\nexport type RecordedSyncFailureCategory = SyncFailureCategory | \"compatibility\";\n\n// Checked in order; the first matching phrase decides the category.\nconst SYNC_FAILURE_PHRASES: Array<[SyncFailureCategory, string[]]> = [\n\t[\"trust\", [\"fingerprint mismatch\", \"peer not pinned\"]],\n\t[\"scope\", [\"scope_rejected\", \"scope rejected\", \"missing_scope\", \"stale_epoch\", \"scope_inactive\"]],\n\t[\n\t\t\"connectivity\",\n\t\t[\n\t\t\t\"no dialable peer addresses\",\n\t\t\t\"fetch failed\",\n\t\t\t\"connection refused\",\n\t\t\t\"network\",\n\t\t\t\"timeout\",\n\t\t\t\"503\",\n\t\t\t\"502\",\n\t\t\t\"504\",\n\t\t\t\"peer status failed\",\n\t\t\t\"peer ops fetch failed\",\n\t\t\t\"snapshot fetch failed\",\n\t\t],\n\t],\n];\n\nexport function categorizeSyncFailure(error: string | undefined): SyncFailureCategory {\n\tconst lower = String(error ?? \"\").toLowerCase();\n\tif (!lower) return \"other\";\n\tif (lower.includes(\"401\") && lower.includes(\"unauthorized\")) return \"trust\";\n\tconst match = SYNC_FAILURE_PHRASES.find(([, phrases]) =>\n\t\tphrases.some((phrase) => lower.includes(phrase)),\n\t);\n\treturn match?.[0] ?? \"other\";\n}\n\n// Aggregated per-Space and inbound-apply errors embed arbitrary Space IDs and\n// nested error text whose delimiters are ambiguous, and the runtime category\n// for them is not persisted. Report them as `other` rather than guess.\nconst AGGREGATE_PREFIXES = [\"scoped sync incomplete:\", \"inbound apply incomplete\"];\n\n// The sync pass writes these phrases only after the peer returned an HTTP\n// response (status/error formats vary); transport failures are recorded as raw\n// fetch errors instead. A response is a reachability problem only when a\n// gateway or unavailable status says so.\nconst ANSWERED_RESPONSE_PHRASES = [\n\t\"peer status failed\",\n\t\"peer ops fetch failed\",\n\t\"peer ops push failed\",\n\t\"snapshot fetch failed\",\n];\n// JSON error bodies can drop the status (for example `snapshot fetch failed:\n// sync_auth_store_busy` from a 503), so also match stable busy codes.\nconst UNREACHABLE_STATUS_PATTERN = /\\b50[234]\\b|sync_auth_store_busy/;\n\n// Peer addresses can contain any word (for example `http://authbox.local`).\n// Drop whitespace-separated tokens that contain a URL scheme separator; a\n// linear token scan avoids backtracking on untrusted input.\nfunction withoutPeerAddresses(text: string): string {\n\treturn text\n\t\t.split(/\\s+/)\n\t\t.filter((token) => !token.includes(\"://\"))\n\t\t.join(\" \");\n}\n\n/**\n * Classify an error string persisted in `sync_attempts`, using the same\n * categories the sync pass assigns at runtime. Returns `other` whenever the\n * stored text cannot be classified unambiguously.\n */\nexport function classifyRecordedSyncFailure(\n\terror: string | null | undefined,\n): RecordedSyncFailureCategory {\n\tconst text = String(error ?? \"\").trim();\n\tif (!text) return \"other\";\n\tif (AGGREGATE_PREFIXES.some((prefix) => text.toLowerCase().startsWith(prefix))) return \"other\";\n\tconst withoutAddresses = withoutPeerAddresses(text);\n\tconst lower = withoutAddresses.toLowerCase();\n\tif (lower.includes(\"protocol mismatch\")) return \"compatibility\";\n\tconst category = categorizeSyncFailure(withoutAddresses);\n\tconst peerAnswered = ANSWERED_RESPONSE_PHRASES.some((phrase) => lower.includes(phrase));\n\tif (category === \"connectivity\" && peerAnswered && !UNREACHABLE_STATUS_PATTERN.test(lower)) {\n\t\treturn \"other\";\n\t}\n\treturn category;\n}\n\nconst STORED_CATEGORY_PRIORITY: RecordedSyncFailureCategory[] = [\n\t\"trust\",\n\t\"scope\",\n\t\"compatibility\",\n\t\"connectivity\",\n];\n\n/**\n * Category persisted for a failed multi-address attempt. Each address error is\n * classified on its own, without the address, so peer URLs and delimiter text\n * inside an error cannot change the result. The most actionable category wins\n * when addresses disagree.\n */\nexport function storedAddressFailureCategory(\n\taddressErrors: Array<{ address: string; error: string }>,\n\tfallbackError: string,\n): RecordedSyncFailureCategory {\n\tif (addressErrors.length === 0) return categorizeSyncFailure(fallbackError);\n\tconst categories = new Set(addressErrors.map((item) => classifyRecordedSyncFailure(item.error)));\n\treturn STORED_CATEGORY_PRIORITY.find((category) => categories.has(category)) ?? \"other\";\n}\n","/**\n * Sync pass orchestrator: coordinates a single sync exchange with a peer device.\n *\n * Handles the pull→apply→push cycle for replication ops, with address\n * fallback, fingerprint verification, and cursor tracking.\n * Ported from codemem/sync/sync_pass.py.\n */\n\nimport { and, desc, eq, gt, or } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport { MAX_PEER_ADDRESSES, mergeAddresses } from \"./address-utils.js\";\nimport type { Database } from \"./db.js\";\nimport { ensureAdditiveSchemaCompatibility, ensureSyncAttemptTransportColumn } from \"./db.js\";\nimport type { RelayFailureReason } from \"./relay-failure-reason.js\";\nimport { isStableReleaseVersion } from \"./release-discovery.js\";\nimport * as schema from \"./schema.js\";\nimport type { SecretScanner } from \"./secret-scanner.js\";\nimport { buildDirectPeerAuthHeaders } from \"./sync-auth.js\";\nimport {\n\tapplyBootstrapSnapshot,\n\tfetchAllSnapshotPages,\n\tmergeBootstrapSnapshot,\n} from \"./sync-bootstrap.js\";\nimport {\n\tLOCAL_SYNC_CAPABILITY,\n\tLOCAL_SYNC_FEATURES,\n\tnegotiateSyncCapability,\n\tnormalizeSyncCapability,\n\tnormalizeSyncFeatures,\n\tSYNC_AUTHORIZATION_REFRESH_HEADER,\n\tSYNC_CAPABILITY_HEADER,\n\tSYNC_FEATURES_HEADER,\n\ttype SyncCapability,\n\tsupportsSyncFeature,\n} from \"./sync-capability.js\";\nimport {\n\tgetSyncChannelProgress,\n\thasCompletedSyncChannelBoundary,\n} from \"./sync-channel-progress.js\";\nimport { recordPeerSuccess } from \"./sync-discovery.js\";\nimport {\n\tcategorizeSyncFailure,\n\tstoredAddressFailureCategory,\n} from \"./sync-failure-classification.js\";\nimport { buildBaseUrl, type RequestJsonExecutor, requestJson } from \"./sync-http-client.js\";\nimport { ensureDeviceIdentity } from \"./sync-identity.js\";\nimport {\n\tapplyReplicationOps,\n\tbackfillReplicationOps,\n\tchunkOpsBySize,\n\tclearReplicationCursorLastApplied,\n\textractReplicationOps,\n\ttype FilterReplicationSkipped,\n\tfilterReplicationOpsForSyncWithStatus,\n\tgetReplicationCursor,\n\thasUnsyncedSharedMemoryChanges,\n\tmigrateLegacyImportKeys,\n\treconcileStalePeerReceivedRows,\n\tSCOPED_NULL_BASELINE_BOOTSTRAP_CURSOR_MARKER,\n\tsetReplicationCursor,\n} from \"./sync-replication.js\";\nimport {\n\trecordSyncTransferObservation,\n\trecordSyncTransferReceipts,\n\ttype SyncTransferErrorCode,\n} from \"./sync-transfer-activity.js\";\nimport type { ReplicationOp, SyncMemorySnapshotItem, SyncResetRequired } from \"./types.js\";\nimport { queueVectorBackfillForIncrementalSync } from \"./vector-migration.js\";\nimport { bestEffortMaintainVectorsForSyncFallback } from \"./vectors.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/** Default max body size for sync POST requests (1 MiB). */\nconst MAX_SYNC_BODY_BYTES = 1_048_576;\n\n/**\n * One-shot warning latch so sync-apply paths log a single line per process if\n * a caller forgot to thread the scanner through. Workspace-level rule overrides\n * silently fail to apply to peer-shipped content otherwise.\n */\nlet syncOnceScannerWarned = false;\n\n/**\n * Default op fetch/push limit per round.\n *\n * The server caps this at 1000 per request (see viewer-server /v1/ops).\n * Callers can override via SyncPassOptions.limit; the sync daemon resolves\n * it from the sync_ops_limit config key / CODEMEM_SYNC_OPS_LIMIT env var.\n */\nconst DEFAULT_LIMIT = 500;\n\n/** Elevated page size for initial bootstrap of never-synced peers. */\nconst BOOTSTRAP_PAGE_SIZE = 2000;\n\n/**\n * Per-page snapshot fetch timeout for bootstrap / scoped merge recovery.\n * Larger than the default incremental timeout because snapshot pages can be\n * substantially bigger and slower to assemble on the serving peer.\n */\nconst BOOTSTRAP_REQUEST_TIMEOUT_S = 60;\n\n// Initiated windows share one observation. Only the final receive result resolves errors.\nconst RECEIVE_WINDOW_OPTIONS = { activityOptions: { preserveError: true } };\n\n/** Current sync protocol version expected from peers. */\nconst EXPECTED_SYNC_PROTOCOL_VERSION = \"2\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type SyncFailureCategory = \"trust\" | \"scope\" | \"connectivity\" | \"other\";\n\n/**\n * Category persisted on `sync_attempts.failure_category`. Wider than the\n * runtime `SyncFailureCategory` so stored diagnostics can tell protocol\n * mismatches apart without changing callers that switch on the runtime type.\n */\nexport type SyncAttemptFailureCategory = SyncFailureCategory | \"compatibility\";\n\nexport interface SyncResult {\n\tok: boolean;\n\ttransport?: \"direct\" | \"traversal\" | \"relay\" | \"wait\";\n\t/** Why a `wait` result skipped relay on purpose. The direct attempt record stands alone. */\n\trelaySkipped?: \"relay_peer_unsupported\" | \"relay_backoff\";\n\terror?: string;\n\tfailureCategory?: SyncFailureCategory;\n\treceiveFailureCode?: SyncTransferErrorCode;\n\taddress?: string;\n\topsIn: number;\n\topsOut: number;\n\topsSkipped?: number;\n\tskippedOut?: FilterReplicationSkipped | null;\n\taddressErrors: Array<{ address: string; error: string }>;\n\tresetRequired?: SyncResetRequired;\n\t/**\n\t * Per-Space sync outcomes when both peers negotiate the `scoped` sync\n\t * capability. Each entry covers a non-default scope returned by the peer's\n\t * `authorized_scopes` advertisement. Unset for legacy / `aware` peers; in\n\t * that case the top-level `opsIn` / `opsOut` describe the only sync pass\n\t * that ran (default scope).\n\t *\n\t * Top-level `opsIn` / `opsOut` aggregate the default-scope pass plus every\n\t * scoped pass, so existing callers stay correct without per-scope\n\t * awareness. A failure in a single scope sets the entry's `ok=false` but\n\t * does not block other scopes, and does not affect the default-scope\n\t * outcome. The top-level `ok` is true only when every per-scope result is\n\t * `ok`, matching the design's \"all-or-nothing\" report.\n\t */\n\tperScopeResults?: SyncScopeResult[];\n}\n\n/**\n * Outcome of a single per-Space sync pass within a larger `syncOnce` exchange.\n *\n * Lives alongside `SyncResult` rather than nested into it because each scope\n * has its own cursor / reset state and can fail independently. Aggregating the\n * per-scope counts into `SyncResult.opsIn` / `opsOut` preserves backward\n * compatibility for callers that only need totals.\n */\nexport interface SyncScopeResult {\n\tscope_id: string;\n\tlabel?: string;\n\tok: boolean;\n\tfailureCategory?: SyncFailureCategory;\n\treceiveFailureCode?: SyncTransferErrorCode;\n\topsIn: number;\n\topsOut: number;\n\terror?: string;\n\t/** First local relay route failure for a relay channel pass. Never sent to peers. */\n\trelayFailureReason?: RelayFailureReason;\n\tresetRequired?: SyncResetRequired;\n\t/**\n\t * True when the pass began with an empty cursor and no local rows in the\n\t * scope, triggering a `/v1/snapshot` bootstrap. False for incremental\n\t * `/v1/ops` passes. Useful for diagnostics and UI progress reporting.\n\t */\n\tbootstrapped: boolean;\n}\n\nexport interface SyncPassOptions {\n\trequestExecutor?: RequestJsonExecutor;\n\t/** @internal A selected pass defers address-level diagnostics to its final result. */\n\tattemptRecorder?: typeof recordSyncAttempt;\n\t/** @internal Transport selection records exhausted connection probes only after fallback. */\n\tdeferConnectionFailure?: boolean;\n\treachability?: import(\"./sync-reachability-pass.js\").SyncReachabilityOptions;\n\tlimit?: number;\n\tkeysDir?: string;\n\tdbPath?: string;\n\trefreshAuthorization?: boolean;\n\t/**\n\t * Secret scanner used to redact peer-shipped content on apply. Callers that\n\t * own a `MemoryStore` should pass `store.scanner` so workspace-level rule\n\t * overrides apply uniformly to local writes and sync-receive. Omitting it\n\t * falls back to default rules only and prints a one-time warning.\n\t */\n\tscanner?: SecretScanner;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Check if a cursor candidate advances beyond the current position.\n *\n * Cursors are `timestamp|op_id` strings that sort lexicographically.\n */\nexport function cursorAdvances(current: string | null, candidate: string | null): boolean {\n\tif (!candidate) return false;\n\tif (!candidate.includes(\"|\")) return false;\n\tif (!current) return true;\n\treturn candidate > current;\n}\n\n/**\n * Extract an error detail string from a JSON response payload.\n */\nfunction errorDetail(payload: Record<string, unknown> | null): string | null {\n\tif (!payload) return null;\n\tconst error = payload.error;\n\tconst reason = payload.reason;\n\tif (typeof error === \"string\" && typeof reason === \"string\") {\n\t\treturn `${error}:${reason}`;\n\t}\n\tif (typeof error === \"string\") return error;\n\treturn null;\n}\n\n/**\n * Summarize address errors into a single error string.\n */\nfunction summarizeAddressErrors(\n\taddressErrors: Array<{ address: string; error: string }>,\n): string | null {\n\tif (addressErrors.length === 0) return null;\n\tconst parts = addressErrors.map((item) => `${item.address}: ${item.error}`);\n\treturn `all addresses failed | ${parts.join(\" || \")}`;\n}\n\nfunction asOptionalCursor(value: unknown): string | null {\n\tif (typeof value !== \"string\") return null;\n\tconst trimmed = value.trim();\n\treturn trimmed.length > 0 ? trimmed : null;\n}\n\nfunction parsePeerResetBoundary(payload: Record<string, unknown> | null): {\n\tscope_id: string | null;\n\tgeneration: number;\n\tsnapshot_id: string;\n\tbaseline_cursor: string | null;\n\tretained_floor_cursor: string | null;\n} | null {\n\tconst raw = payload?.sync_reset;\n\tif (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return null;\n\tconst boundary = raw as Record<string, unknown>;\n\tif (!Number.isFinite(boundary.generation)) return null;\n\tif (typeof boundary.snapshot_id !== \"string\" || boundary.snapshot_id.trim().length === 0) {\n\t\treturn null;\n\t}\n\tconst baseline = asOptionalCursor(boundary.baseline_cursor);\n\treturn {\n\t\tscope_id: asOptionalCursor(boundary.scope_id),\n\t\tgeneration: Number(boundary.generation),\n\t\tsnapshot_id: boundary.snapshot_id.trim(),\n\t\tbaseline_cursor: baseline,\n\t\tretained_floor_cursor: asOptionalCursor(boundary.retained_floor_cursor),\n\t};\n}\n\nfunction isValidIncrementalOpsResponse(payload: Record<string, unknown> | null): payload is {\n\treset_required: false;\n\tgeneration: number;\n\tsnapshot_id: string;\n\tbaseline_cursor: string | null;\n\tretained_floor_cursor: string | null;\n\tops: unknown[];\n\tnext_cursor: string | null;\n\tskipped: number;\n} {\n\tif (payload?.reset_required !== false) return false;\n\tif (!Number.isFinite(payload.generation)) return false;\n\tif (typeof payload.snapshot_id !== \"string\" || payload.snapshot_id.trim().length === 0)\n\t\treturn false;\n\tif (!(payload.baseline_cursor == null || typeof payload.baseline_cursor === \"string\"))\n\t\treturn false;\n\tif (\n\t\t!(payload.retained_floor_cursor == null || typeof payload.retained_floor_cursor === \"string\")\n\t) {\n\t\treturn false;\n\t}\n\tif (!Array.isArray(payload.ops)) return false;\n\tif (!(payload.next_cursor == null || typeof payload.next_cursor === \"string\")) return false;\n\tif (!Number.isFinite(payload.skipped)) return false;\n\treturn true;\n}\n\ninterface SyncCapabilityDiagnostics {\n\tlocal: SyncCapability;\n\tpeer: SyncCapability;\n\tnegotiated: SyncCapability;\n}\n\nfunction capabilityDiagnostics(peerCapability: unknown): SyncCapabilityDiagnostics {\n\tconst peer = normalizeSyncCapability(peerCapability);\n\treturn {\n\t\tlocal: LOCAL_SYNC_CAPABILITY,\n\t\tpeer,\n\t\tnegotiated: negotiateSyncCapability(LOCAL_SYNC_CAPABILITY, peer),\n\t};\n}\n\nfunction capabilityHeader(): Record<string, string> {\n\t// Diagnostic advertisement only. This unsigned GET header can opt an\n\t// authenticated paired peer into scoped metadata enumeration, but never into\n\t// scoped data access; receivers must still authorize every scoped request.\n\treturn {\n\t\t[SYNC_CAPABILITY_HEADER]: LOCAL_SYNC_CAPABILITY,\n\t\t[SYNC_FEATURES_HEADER]: LOCAL_SYNC_FEATURES.join(\",\"),\n\t};\n}\n\nfunction defaultCapabilityDiagnostics(): SyncCapabilityDiagnostics {\n\treturn capabilityDiagnostics(\"unsupported\");\n}\n\nfunction persistPeerRuntimeVersion(\n\tdb: Database,\n\tpeerDeviceId: string,\n\tstatusPayload: Record<string, unknown>,\n): void {\n\tconst matchingDevice = statusPayload.device_id === peerDeviceId;\n\tconst runtimeVersion =\n\t\tmatchingDevice && isStableReleaseVersion(statusPayload.runtime_version)\n\t\t\t? statusPayload.runtime_version\n\t\t\t: null;\n\t// A status reply without the field is an older peer: store an empty list, which\n\t// is a known answer, so relay fallback can tell \"no relay\" from \"never seen\".\n\tconst features = matchingDevice\n\t\t? JSON.stringify(normalizeSyncFeatures(statusPayload.sync_features))\n\t\t: null;\n\ttry {\n\t\tdb.prepare(\n\t\t\t`UPDATE sync_peers\n\t\t\t SET runtime_version = ?, runtime_version_observed_at = ?,\n\t\t\t sync_features_json = COALESCE(?, sync_features_json),\n\t\t\t sync_features_observed_at = COALESCE(?, sync_features_observed_at)\n\t\t\t WHERE peer_device_id = ?`,\n\t\t).run(\n\t\t\truntimeVersion,\n\t\t\truntimeVersion ? new Date().toISOString() : null,\n\t\t\tfeatures,\n\t\t\tfeatures === null ? null : new Date().toISOString(),\n\t\t\tpeerDeviceId,\n\t\t);\n\t} catch {\n\t\t// Informational metadata must never affect sync availability or trust.\n\t}\n}\n\nasync function reconcilePeerRowsBeforeExchange(\n\tdb: Database,\n\toptions: { localDeviceId: string; peerDeviceId: string; keysDir?: string },\n): Promise<void> {\n\tconst reconciliation = reconcileStalePeerReceivedRows(db, options);\n\tif (reconciliation.deleted_memory_ids.length === 0) return;\n\tconst vectorWork = {\n\t\tupsertMemoryIds: [],\n\t\tdeleteMemoryIds: reconciliation.deleted_memory_ids,\n\t};\n\ttry {\n\t\tqueueVectorBackfillForIncrementalSync(db, vectorWork);\n\t} catch (queueError) {\n\t\tconst fallback = await bestEffortMaintainVectorsForSyncFallback(db, vectorWork);\n\t\tif (fallback.errors.length > 0) {\n\t\t\tconst queueDetail = queueError instanceof Error ? queueError.message : String(queueError);\n\t\t\tthrow new Error(\n\t\t\t\t`peer recovery vector cleanup failed: ${queueDetail}; fallback failed: ${fallback.errors.join(\"; \")}`,\n\t\t\t);\n\t\t}\n\t}\n}\n\nfunction reconcileReceivedRowsForExchange(\n\tdb: Database,\n\toptions: { deviceId: string; peerDeviceId: string; keysDir?: string },\n): ReturnType<typeof reconcileStalePeerReceivedRows> {\n\treturn reconcileStalePeerReceivedRows(db, {\n\t\tlocalDeviceId: options.deviceId,\n\t\tpeerDeviceId: options.peerDeviceId,\n\t\tkeysDir: options.keysDir,\n\t});\n}\n\n/**\n * Record a sync attempt in the sync_attempts table.\n */\nexport function recordSyncAttempt(\n\tdb: Database,\n\tpeerDeviceId: string,\n\toptions: {\n\t\tok: boolean;\n\t\topsIn?: number;\n\t\topsOut?: number;\n\t\terror?: string;\n\t\tfailureCategory?: SyncAttemptFailureCategory;\n\t\tcapabilities?: SyncCapabilityDiagnostics;\n\t\ttransport?: SyncResult[\"transport\"];\n\t},\n): void {\n\tensureSyncAttemptTransportColumn(db);\n\tconst d = drizzle(db, { schema });\n\tconst now = new Date().toISOString();\n\tconst capabilities = options.capabilities ?? defaultCapabilityDiagnostics();\n\td.insert(schema.syncAttempts)\n\t\t.values({\n\t\t\tpeer_device_id: peerDeviceId,\n\t\t\tstarted_at: now,\n\t\t\tfinished_at: now,\n\t\t\tok: options.ok ? 1 : 0,\n\t\t\tops_in: options.opsIn ?? 0,\n\t\t\tops_out: options.opsOut ?? 0,\n\t\t\terror: options.error ?? null,\n\t\t\tlocal_sync_capability: capabilities.local,\n\t\t\tpeer_sync_capability: capabilities.peer,\n\t\t\tnegotiated_sync_capability: capabilities.negotiated,\n\t\t\tfailure_category: options.ok ? null : (options.failureCategory ?? \"other\"),\n\t\t\ttransport:\n\t\t\t\toptions.transport === \"direct\" || options.transport === \"relay\" ? options.transport : null,\n\t\t})\n\t\t.run();\n}\n\n/**\n * Load outbound replication ops for the local device since a cursor.\n *\n * Returns `[ops, nextCursor]`. The cursor is `created_at|op_id`.\n */\nfunction loadLocalOpsSince(\n\tdb: Database,\n\tcursor: string | null,\n\tdeviceId: string,\n\tlimit: number,\n): [ReplicationOp[], string | null] {\n\tconst d = drizzle(db, { schema });\n\tconst { replicationOps: ops } = schema;\n\tlet rows: ReplicationOp[];\n\tif (cursor) {\n\t\tconst sepIdx = cursor.indexOf(\"|\");\n\t\tconst cursorTs = sepIdx >= 0 ? cursor.slice(0, sepIdx) : cursor;\n\t\tconst cursorOpId = sepIdx >= 0 ? cursor.slice(sepIdx + 1) : \"\";\n\t\trows = d\n\t\t\t.select()\n\t\t\t.from(ops)\n\t\t\t.where(\n\t\t\t\tand(\n\t\t\t\t\teq(ops.device_id, deviceId),\n\t\t\t\t\tor(\n\t\t\t\t\t\tgt(ops.created_at, cursorTs),\n\t\t\t\t\t\tand(eq(ops.created_at, cursorTs), gt(ops.op_id, cursorOpId)),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t)\n\t\t\t.orderBy(ops.created_at, ops.op_id)\n\t\t\t.limit(limit)\n\t\t\t.all() as ReplicationOp[];\n\t} else {\n\t\trows = d\n\t\t\t.select()\n\t\t\t.from(ops)\n\t\t\t.where(eq(ops.device_id, deviceId))\n\t\t\t.orderBy(ops.created_at, ops.op_id)\n\t\t\t.limit(limit)\n\t\t\t.all() as ReplicationOp[];\n\t}\n\n\tif (rows.length === 0) return [[], null];\n\tconst last = rows.at(-1);\n\tif (!last) return [[], null];\n\tconst nextCursor = `${last.created_at}|${last.op_id}`;\n\treturn [rows, nextCursor];\n}\n\n// ---------------------------------------------------------------------------\n// Push ops\n// ---------------------------------------------------------------------------\n\n/**\n * Push ops to a peer endpoint with auth headers.\n *\n * On 413 (too large), splits the batch in half and retries recursively.\n */\nconst MAX_PUSH_SPLIT_DEPTH = 8;\n\nfunction hasPeerApplyErrors(payload: Record<string, unknown>): boolean {\n\tif (Object.hasOwn(payload, \"error\")) {\n\t\tconst error = payload.error;\n\t\tif (error != null) return true;\n\t}\n\t// Legacy peers may omit errors. A present field must explicitly report no failures.\n\tif (!Object.hasOwn(payload, \"errors\")) return false;\n\tconst errors = payload.errors;\n\treturn !Array.isArray(errors) || errors.length > 0;\n}\n\nasync function pushOps(\n\tpostUrl: string,\n\tdeviceId: string,\n\trecipientId: string,\n\tops: ReplicationOp[],\n\trequestExecutor: RequestJsonExecutor,\n\tonAcknowledged: (ops: ReplicationOp[]) => void,\n\tkeysDir?: string,\n\tdbPath?: string,\n\tdepth = 0,\n): Promise<void> {\n\tconst body = {\n\t\tops,\n\t\tsync_capability: LOCAL_SYNC_CAPABILITY,\n\t\tsync_features: LOCAL_SYNC_FEATURES,\n\t};\n\tconst bodyBytes = Buffer.from(JSON.stringify(body), \"utf-8\");\n\tconst headers = {\n\t\t...buildDirectPeerAuthHeaders({\n\t\t\tdeviceId,\n\t\t\trecipientId,\n\t\t\tmethod: \"POST\",\n\t\t\turl: postUrl,\n\t\t\tbodyBytes,\n\t\t\tkeysDir,\n\t\t\tdbPath,\n\t\t}),\n\t\t...capabilityHeader(),\n\t};\n\tconst [status, payload] = await requestExecutor(\"POST\", postUrl, {\n\t\theaders,\n\t\tbody,\n\t\tbodyBytes,\n\t});\n\n\tif (status === 200 && payload != null) {\n\t\tif (hasPeerApplyErrors(payload)) {\n\t\t\tthrow new Error(\"peer ops push failed (200: peer reported apply errors)\");\n\t\t}\n\t\tonAcknowledged(ops);\n\t\treturn;\n\t}\n\n\tconst detail = errorDetail(payload);\n\tif (\n\t\tstatus === 413 &&\n\t\tops.length > 1 &&\n\t\tdepth < MAX_PUSH_SPLIT_DEPTH &&\n\t\t(detail === \"payload_too_large\" || detail === \"too_many_ops\")\n\t) {\n\t\tconst mid = Math.floor(ops.length / 2);\n\t\tfor (const batch of [ops.slice(0, mid), ops.slice(mid)]) {\n\t\t\tawait pushOps(\n\t\t\t\tpostUrl,\n\t\t\t\tdeviceId,\n\t\t\t\trecipientId,\n\t\t\t\tbatch,\n\t\t\t\trequestExecutor,\n\t\t\t\tonAcknowledged,\n\t\t\t\tkeysDir,\n\t\t\t\tdbPath,\n\t\t\t\tdepth + 1,\n\t\t\t);\n\t\t}\n\t\treturn;\n\t}\n\n\tconst suffix = detail ? ` (${status}: ${detail})` : ` (${status})`;\n\tthrow new Error(`peer ops push failed${suffix}`);\n}\n\n// ---------------------------------------------------------------------------\n// Per-scope sync helpers (scoped capability path)\n// ---------------------------------------------------------------------------\n\n/**\n * Wire shape of a single entry in the `authorized_scopes` array returned by\n * `/v1/status` when both peers negotiate the `scoped` capability.\n */\ninterface PeerAuthorizedScope {\n\tscope_id: string;\n\tlabel?: string;\n\tauthority_type?: string;\n\tmembership_epoch?: number;\n\tsync_reset: {\n\t\tscope_id: string | null;\n\t\tgeneration: number;\n\t\tsnapshot_id: string;\n\t\tbaseline_cursor: string | null;\n\t\tretained_floor_cursor: string | null;\n\t};\n\t/** The peer's pull cursor for this device's ops in the scope, when it reports one. */\n\tapplied_cursor: string | null;\n}\n\n/** A reported `created_at|op_id` pull cursor, or null when absent or malformed. */\nfunction asAppliedCursor(value: unknown): string | null {\n\tconst cursor = asOptionalCursor(value);\n\tif (!cursor) return null;\n\t// Both parts must be present: a bare separator would sort after every real cursor.\n\tconst separator = cursor.indexOf(\"|\");\n\treturn separator > 0 && separator < cursor.length - 1 ? cursor : null;\n}\n\n/**\n * Parse and validate a peer's `authorized_scopes` advertisement.\n *\n * Returns an empty array (not null) for any malformed value so the per-scope\n * loop is a safe no-op for legacy peers that don't emit the field. Each\n * accepted entry must carry a non-empty `scope_id` and a complete\n * `sync_reset` boundary; partially-formed entries are dropped silently rather\n * than failing the whole pass.\n */\nfunction parseAuthorizedScopes(value: unknown): PeerAuthorizedScope[] {\n\tif (!Array.isArray(value)) return [];\n\tconst entries: PeerAuthorizedScope[] = [];\n\tfor (const raw of value) {\n\t\tif (!raw || typeof raw !== \"object\") continue;\n\t\tconst record = raw as Record<string, unknown>;\n\t\tconst scopeId = typeof record.scope_id === \"string\" ? record.scope_id.trim() : \"\";\n\t\tif (!scopeId) continue;\n\t\tconst reset = record.sync_reset;\n\t\tif (!reset || typeof reset !== \"object\") continue;\n\t\tconst resetRecord = reset as Record<string, unknown>;\n\t\tconst generation = Number(resetRecord.generation);\n\t\tif (!Number.isFinite(generation)) continue;\n\t\tconst snapshotId =\n\t\t\ttypeof resetRecord.snapshot_id === \"string\" ? resetRecord.snapshot_id.trim() : \"\";\n\t\tif (!snapshotId) continue;\n\t\tentries.push({\n\t\t\tscope_id: scopeId,\n\t\t\tapplied_cursor: asAppliedCursor(record.applied_cursor),\n\t\t\tlabel: typeof record.label === \"string\" ? record.label : undefined,\n\t\t\tauthority_type: typeof record.authority_type === \"string\" ? record.authority_type : undefined,\n\t\t\tmembership_epoch:\n\t\t\t\ttypeof record.membership_epoch === \"number\" ? record.membership_epoch : undefined,\n\t\t\tsync_reset: {\n\t\t\t\tscope_id: typeof resetRecord.scope_id === \"string\" ? resetRecord.scope_id : null,\n\t\t\t\tgeneration,\n\t\t\t\tsnapshot_id: snapshotId,\n\t\t\t\tbaseline_cursor: asOptionalCursor(resetRecord.baseline_cursor),\n\t\t\t\tretained_floor_cursor: asOptionalCursor(resetRecord.retained_floor_cursor),\n\t\t\t},\n\t\t});\n\t}\n\treturn entries;\n}\n\n/**\n * True when the local DB has any memory_items belonging to the given scope.\n * Used to decide between bootstrap (no local rows) and incremental (some local\n * rows) on first pull for a scope. Matches the predicate\n * `loadMemorySnapshotPageForPeer` uses for snapshot eligibility.\n */\nfunction hasLocalRowsInScope(db: Database, scopeId: string): boolean {\n\tconst row = db\n\t\t.prepare(\"SELECT 1 FROM memory_items WHERE import_key IS NOT NULL AND scope_id = ? LIMIT 1\")\n\t\t.get(scopeId) as { 1: number } | undefined;\n\treturn row !== undefined;\n}\n\nfunction scopedSnapshotAccessFailure(\n\tdb: Database,\n\toptions: { scopeId: string; peerDeviceId: string; localDeviceId: string },\n): SyncResetRequired[\"reason\"] | null {\n\tconst scope = db\n\t\t.prepare(\n\t\t\t`SELECT authority_type, status, membership_epoch\n\t\t\t FROM replication_scopes\n\t\t\t WHERE scope_id = ?`,\n\t\t)\n\t\t.get(options.scopeId) as\n\t\t| { authority_type: string | null; status: string | null; membership_epoch: number | null }\n\t\t| undefined;\n\tif (!scope) return \"missing_scope\";\n\tif (scope.status !== \"active\") return \"scope_inactive\";\n\tif (scope.authority_type === \"local\") return \"missing_scope\";\n\n\tconst requiredEpoch = Number(scope.membership_epoch ?? 0);\n\tfor (const deviceId of [options.localDeviceId, options.peerDeviceId]) {\n\t\tconst membership = db\n\t\t\t.prepare(\n\t\t\t\t`SELECT status, membership_epoch\n\t\t\t\t FROM scope_memberships\n\t\t\t\t WHERE scope_id = ? AND device_id = ?`,\n\t\t\t)\n\t\t\t.get(options.scopeId, deviceId) as\n\t\t\t| { status: string | null; membership_epoch: number | null }\n\t\t\t| undefined;\n\t\tif (!membership) return \"missing_scope\";\n\t\tif (membership.status !== \"active\") return \"scope_inactive\";\n\t\tif (Number(membership.membership_epoch ?? 0) < requiredEpoch) return \"stale_epoch\";\n\t}\n\n\treturn null;\n}\n\nfunction scopedSnapshotAccessDeniedResult(\n\tbaseUrl: string,\n\tresetInfo: SyncResetRequired,\n\treason: SyncResetRequired[\"reason\"],\n): SyncResult {\n\treturn {\n\t\tok: false,\n\t\taddress: baseUrl,\n\t\terror: `reset_required:${reason}`,\n\t\tfailureCategory: scopeResetFailureCategory(reason),\n\t\topsIn: 0,\n\t\topsOut: 0,\n\t\taddressErrors: [],\n\t\tresetRequired: { ...resetInfo, reason },\n\t};\n}\n\nfunction scopeFailureCategory(error: string | undefined): SyncFailureCategory {\n\treturn categorizeSyncFailure(error);\n}\n\nfunction scopeResetFailureCategory(reason: SyncResetRequired[\"reason\"]): SyncFailureCategory {\n\tswitch (reason) {\n\t\tcase \"missing_scope\":\n\t\tcase \"scope_inactive\":\n\t\tcase \"stale_epoch\":\n\t\t\treturn \"scope\";\n\t\tcase \"boundary_mismatch\":\n\t\tcase \"generation_mismatch\":\n\t\tcase \"initial_bootstrap\":\n\t\tcase \"stale_cursor\":\n\t\tcase \"unsupported_scope\":\n\t\t\treturn \"other\";\n\t}\n\treturn \"other\";\n}\n\nfunction aggregateScopeFailureCategory(\n\tresults: SyncScopeResult[],\n): SyncFailureCategory | undefined {\n\tconst failed = results.filter((result) => !result.ok);\n\tif (failed.length === 0) return undefined;\n\tconst categories = new Set(\n\t\tfailed.map((result) => result.failureCategory ?? scopeFailureCategory(result.error)),\n\t);\n\treturn categories.size === 1 ? Array.from(categories)[0] : \"other\";\n}\n\n/**\n * Run the per-Space iteration after a successful default-scope sync.\n *\n * Returns the per-scope outcomes plus the aggregate inbound op count so the\n * caller can update its top-level `SyncResult`. Failures inside individual\n * scopes are reported in the returned array; the function itself never\n * throws.\n */\nasync function runScopedSync(\n\tdb: Database,\n\trequestExecutor: RequestJsonExecutor,\n\toptions: {\n\t\tpeerDeviceId: string;\n\t\tbaseUrl: string;\n\t\tdeviceId: string;\n\t\tstatusPayload: Record<string, unknown>;\n\t\tkeysDir?: string;\n\t\tdbPath?: string;\n\t\tscanner?: SecretScanner;\n\t\tlimit: number;\n\t},\n): Promise<{ results: SyncScopeResult[]; totalOpsIn: number }> {\n\tconst authorizedScopes = parseAuthorizedScopes(options.statusPayload.authorized_scopes);\n\tif (authorizedScopes.length === 0) {\n\t\treturn { results: [], totalOpsIn: 0 };\n\t}\n\tconst results: SyncScopeResult[] = [];\n\tlet totalOpsIn = 0;\n\tfor (const scope of authorizedScopes) {\n\t\tconst scopeResult = await syncOneScope(db, {\n\t\t\tpeerDeviceId: options.peerDeviceId,\n\t\t\tbaseUrl: options.baseUrl,\n\t\t\tdeviceId: options.deviceId,\n\t\t\trequestExecutor,\n\t\t\tscope,\n\t\t\tkeysDir: options.keysDir,\n\t\t\tdbPath: options.dbPath,\n\t\t\tscanner: options.scanner,\n\t\t\tlimit: options.limit,\n\t\t});\n\t\tresults.push(scopeResult);\n\t\tif (!scopeResult.ok)\n\t\t\trecordSyncTransferObservation(db, options.peerDeviceId, \"receive\", {\n\t\t\t\terrorCode: scopeReceiveFailure(scopeResult),\n\t\t\t});\n\t\tif (scopeResult.ok) totalOpsIn += scopeResult.opsIn;\n\t}\n\treturn { results, totalOpsIn };\n}\n\nfunction scopeReceiveFailure(result: SyncScopeResult): SyncTransferErrorCode {\n\tif (result.receiveFailureCode) return result.receiveFailureCode;\n\treturn result.failureCategory === \"scope\" ? \"scope_rejected\" : \"exchange_failed\";\n}\n\n// A successful sibling window cannot resolve another scope's failed apply.\nfunction aggregateReceiveFailure(\n\tresults: SyncScopeResult[],\n\toptions: { applyErrors?: readonly string[] } = {},\n): SyncTransferErrorCode | undefined {\n\tconst failures = results.filter((result) => !result.ok).map(scopeReceiveFailure);\n\tif ((options.applyErrors?.length ?? 0) > 0 || failures.includes(\"apply_failed\"))\n\t\treturn \"apply_failed\";\n\tif (failures.includes(\"scope_rejected\")) return \"scope_rejected\";\n\tif (failures.length > 0) return \"exchange_failed\";\n\treturn undefined;\n}\n\nfunction applyReceiveFailure(errors: readonly string[]): \"apply_failed\" | undefined {\n\treturn errors.length > 0 ? \"apply_failed\" : undefined;\n}\n\nfunction mergedReceiveVectorWork(\n\twork: ReturnType<typeof applyReplicationOps>[\"vectorWork\"],\n\tdeletedMemoryIds: number[],\n) {\n\treturn {\n\t\tupsertMemoryIds: work.upsertMemoryIds,\n\t\tdeleteMemoryIds: [...work.deleteMemoryIds, ...deletedMemoryIds],\n\t};\n}\n\nfunction mergeScopeSnapshot(\n\tdb: Database,\n\tpeerDeviceId: string,\n\titems: SyncMemorySnapshotItem[],\n\tresetInfo: SyncResetRequired,\n\tscanner: SecretScanner | undefined,\n) {\n\treturn mergeBootstrapSnapshot(\n\t\tdb,\n\t\tpeerDeviceId,\n\t\titems,\n\t\tresetInfo,\n\t\tscanner,\n\t\tRECEIVE_WINDOW_OPTIONS,\n\t);\n}\n\nfunction applyScopeSnapshot(\n\tdb: Database,\n\tpeerDeviceId: string,\n\titems: SyncMemorySnapshotItem[],\n\tresetInfo: SyncResetRequired,\n\tscanner: SecretScanner | undefined,\n) {\n\treturn applyBootstrapSnapshot(\n\t\tdb,\n\t\tpeerDeviceId,\n\t\titems,\n\t\tresetInfo,\n\t\tscanner,\n\t\tRECEIVE_WINDOW_OPTIONS,\n\t);\n}\n\ninterface ScopedPeerPullOptions {\n\tpeerDeviceId: string;\n\tbaseUrl: string;\n\tdeviceId: string;\n\tscope: PeerAuthorizedScope;\n\trequestExecutor: RequestJsonExecutor;\n\tkeysDir?: string;\n\tdbPath?: string;\n\tscanner?: SecretScanner;\n\tlimit: number;\n\t/** Explicit per-peer completion overrides the legacy marker, including on boundary changes. */\n\tcompletedNullBaseline?: boolean;\n\tsourceDeviceId?: string;\n\tvalidateCurrentAuthorization?: () => void;\n\t/** Must finish synchronously before the inbound cursor can be cleared. */\n\tinvalidateCompletedBoundary?: () => void;\n}\n\nfunction resetScopedPullProgress(db: Database, options: ScopedPeerPullOptions): void {\n\t// Dropping completion first prevents an interrupted reset from skipping recovery.\n\toptions.invalidateCompletedBoundary?.();\n\tclearReplicationCursorLastApplied(db, options.peerDeviceId, options.scope.scope_id);\n}\n\nfunction scopedNullBaselineIsCurrent(options: {\n\tmarker: boolean;\n\tcompleted?: boolean;\n\tbaseline: string | null;\n}): boolean {\n\treturn (options.completed ?? options.marker) && options.baseline == null;\n}\n\nfunction scopedBootstrapOptions(options: ScopedPeerPullOptions) {\n\treturn {\n\t\trequestExecutor: options.requestExecutor,\n\t\tkeysDir: options.keysDir,\n\t\tdbPath: options.dbPath,\n\t\trecipientId: options.peerDeviceId,\n\t\tpageSize: BOOTSTRAP_PAGE_SIZE,\n\t\ttimeoutS: BOOTSTRAP_REQUEST_TIMEOUT_S,\n\t\tsourceDeviceId: options.sourceDeviceId,\n\t};\n}\n\n/**\n * Sync a single Sharing-domain scope with a peer. Caller is responsible for\n * having already authenticated against the peer (via legacy default-scope\n * sync) and having an `authorized_scopes` entry from `/v1/status`.\n *\n * Branches on per-scope cursor state:\n * - `bootstrapped=true`: no cursor and no local rows in this scope → fetch\n * the full snapshot page-by-page via `/v1/snapshot?scope_id=X` and apply\n * atomically via `applyBootstrapSnapshot`.\n * - `bootstrapped=false`: pull `/v1/ops?scope_id=X&since=<cursor>` and apply\n * through the normal `applyReplicationOps` path.\n *\n * Outbound ops are NOT pushed per-scope here. The default-scope outbound push\n * that ran in `syncOnce` already streams ops with their per-op `scope_id`\n * metadata intact, and the peer's outbound filter (`outboundScopeAllowed`)\n * applies the same membership gate per row. Re-pushing per scope would be a\n * waste; the receiver's per-scope pull on the next pass picks up anything it\n * missed.\n */\nasync function syncOneScope(\n\tdb: Database,\n\toptions: ScopedPeerPullOptions,\n): Promise<SyncScopeResult> {\n\tconst { peerDeviceId, baseUrl, deviceId, scope, keysDir, dbPath, scanner, limit } = options;\n\tconst bootstrapOptions = scopedBootstrapOptions(options);\n\tconst scopeId = scope.scope_id;\n\tconst [lastApplied, lastAcked] = getReplicationCursor(db, peerDeviceId, scopeId);\n\tconst hasNullBaselineBootstrapMarker = lastAcked === SCOPED_NULL_BASELINE_BOOTSTRAP_CURSOR_MARKER;\n\tconst nullBaselineBootstrapStillCurrent = scopedNullBaselineIsCurrent({\n\t\tmarker: hasNullBaselineBootstrapMarker,\n\t\tcompleted: options.completedNullBaseline,\n\t\tbaseline: scope.sync_reset.baseline_cursor,\n\t});\n\tconst localRowsPresent = hasLocalRowsInScope(db, scopeId);\n\tconst shouldMergeRecoverScope =\n\t\tlastApplied == null && localRowsPresent && !nullBaselineBootstrapStillCurrent;\n\tconst shouldBootstrapEmptyScope =\n\t\tlastApplied == null && !localRowsPresent && !nullBaselineBootstrapStillCurrent;\n\tif (shouldMergeRecoverScope || shouldBootstrapEmptyScope) {\n\t\tconst accessFailure = scopedSnapshotAccessFailure(db, {\n\t\t\tscopeId,\n\t\t\tpeerDeviceId,\n\t\t\tlocalDeviceId: deviceId,\n\t\t});\n\t\tif (accessFailure) {\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: false,\n\t\t\t\tfailureCategory: scopeResetFailureCategory(accessFailure),\n\t\t\t\topsIn: 0,\n\t\t\t\topsOut: 0,\n\t\t\t\terror: `reset_required:${accessFailure}`,\n\t\t\t\tresetRequired: {\n\t\t\t\t\treset_required: true,\n\t\t\t\t\treason: accessFailure,\n\t\t\t\t\tscope_id: scopeId,\n\t\t\t\t\tgeneration: scope.sync_reset.generation,\n\t\t\t\t\tsnapshot_id: scope.sync_reset.snapshot_id,\n\t\t\t\t\tbaseline_cursor: scope.sync_reset.baseline_cursor,\n\t\t\t\t\tretained_floor_cursor: scope.sync_reset.retained_floor_cursor,\n\t\t\t\t},\n\t\t\t\tbootstrapped: false,\n\t\t\t};\n\t\t}\n\t}\n\n\t// If this peer/scope has no cursor but the receiver already has rows in the\n\t// scope, a destructive bootstrap is unsafe and incremental from an empty\n\t// cursor can be a permanent no-op on peers that only retain snapshot state.\n\t// Recover additively by merging the advertised scoped snapshot: missing or\n\t// stale copies of the same snapshot entity are applied, but rows absent from\n\t// the peer snapshot are preserved.\n\tif (shouldMergeRecoverScope) {\n\t\ttry {\n\t\t\tconst resetInfo: SyncResetRequired = {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tgeneration: scope.sync_reset.generation,\n\t\t\t\tsnapshot_id: scope.sync_reset.snapshot_id,\n\t\t\t\tbaseline_cursor: scope.sync_reset.baseline_cursor,\n\t\t\t\tretained_floor_cursor: scope.sync_reset.retained_floor_cursor,\n\t\t\t\treset_required: true,\n\t\t\t\treason: \"initial_bootstrap\" as SyncResetRequired[\"reason\"],\n\t\t\t};\n\t\t\tconst { items } = await fetchAllSnapshotPages(baseUrl, resetInfo, deviceId, bootstrapOptions);\n\t\t\toptions.validateCurrentAuthorization?.();\n\t\t\tconst mergeResult = mergeScopeSnapshot(db, peerDeviceId, items, resetInfo, scanner);\n\t\t\tif (!mergeResult.ok) {\n\t\t\t\tconst error = \"scoped merge bootstrap apply failed\";\n\t\t\t\treturn {\n\t\t\t\t\tscope_id: scopeId,\n\t\t\t\t\tlabel: scope.label,\n\t\t\t\t\tok: false,\n\t\t\t\t\tfailureCategory: \"other\",\n\t\t\t\t\topsIn: 0,\n\t\t\t\t\topsOut: 0,\n\t\t\t\t\terror,\n\t\t\t\t\tbootstrapped: true,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: true,\n\t\t\t\topsIn: mergeResult.applied,\n\t\t\t\topsOut: 0,\n\t\t\t\tbootstrapped: true,\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tconst detail = err instanceof Error ? err.message.trim() || err.constructor.name : \"unknown\";\n\t\t\tconst error = `scoped merge bootstrap failed: ${detail}`;\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: false,\n\t\t\t\tfailureCategory: scopeFailureCategory(error),\n\t\t\t\topsIn: 0,\n\t\t\t\topsOut: 0,\n\t\t\t\terror,\n\t\t\t\tbootstrapped: true,\n\t\t\t};\n\t\t}\n\t}\n\n\t// Bootstrap when this device has never pulled the scope and has no local\n\t// rows. Populated scopes without a peer cursor are handled by the additive\n\t// merge-recovery branch above so this destructive bootstrap path stays safe.\n\tif (shouldBootstrapEmptyScope) {\n\t\ttry {\n\t\t\tconst resetInfo: SyncResetRequired = {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tgeneration: scope.sync_reset.generation,\n\t\t\t\tsnapshot_id: scope.sync_reset.snapshot_id,\n\t\t\t\tbaseline_cursor: scope.sync_reset.baseline_cursor,\n\t\t\t\tretained_floor_cursor: scope.sync_reset.retained_floor_cursor,\n\t\t\t\treset_required: true,\n\t\t\t\treason: \"initial_bootstrap\" as SyncResetRequired[\"reason\"],\n\t\t\t};\n\t\t\tconst { items } = await fetchAllSnapshotPages(baseUrl, resetInfo, deviceId, bootstrapOptions);\n\t\t\toptions.validateCurrentAuthorization?.();\n\t\t\t// TOCTOU re-check: another process (CLI write, plugin, concurrent\n\t\t\t// sync pass) could have created shared memories in this scope while\n\t\t\t// the snapshot was downloading. applyBootstrapSnapshot wipes all\n\t\t\t// shared rows for the scope before inserting the snapshot, so\n\t\t\t// proceeding would clobber those writes. Mirror the same guard the\n\t\t\t// default-scope auto-bootstrap path already enforces in syncOnce\n\t\t\t// (see \"needs_attention:shared_memories_appeared_during_bootstrap\").\n\t\t\tif (hasLocalRowsInScope(db, scopeId)) {\n\t\t\t\tconst error = \"needs_attention:shared_memories_appeared_during_bootstrap\";\n\t\t\t\treturn {\n\t\t\t\t\tscope_id: scopeId,\n\t\t\t\t\tlabel: scope.label,\n\t\t\t\t\tok: false,\n\t\t\t\t\tfailureCategory: \"other\",\n\t\t\t\t\topsIn: 0,\n\t\t\t\t\topsOut: 0,\n\t\t\t\t\terror,\n\t\t\t\t\tbootstrapped: true,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst bootstrapResult = applyScopeSnapshot(db, peerDeviceId, items, resetInfo, scanner);\n\t\t\tif (!bootstrapResult.ok) {\n\t\t\t\tconst error = \"bootstrap apply failed\";\n\t\t\t\treturn {\n\t\t\t\t\tscope_id: scopeId,\n\t\t\t\t\tlabel: scope.label,\n\t\t\t\t\tok: false,\n\t\t\t\t\tfailureCategory: \"other\",\n\t\t\t\t\topsIn: 0,\n\t\t\t\t\topsOut: 0,\n\t\t\t\t\terror,\n\t\t\t\t\tbootstrapped: true,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: true,\n\t\t\t\topsIn: bootstrapResult.applied,\n\t\t\t\topsOut: 0,\n\t\t\t\tbootstrapped: true,\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tconst detail = err instanceof Error ? err.message.trim() || err.constructor.name : \"unknown\";\n\t\t\tconst error = `scoped bootstrap failed: ${detail}`;\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: false,\n\t\t\t\tfailureCategory: scopeFailureCategory(error),\n\t\t\t\topsIn: 0,\n\t\t\t\topsOut: 0,\n\t\t\t\terror,\n\t\t\t\tbootstrapped: true,\n\t\t\t};\n\t\t}\n\t}\n\n\t// Incremental: pull /v1/ops?scope_id=X&since=<lastApplied>.\n\ttry {\n\t\tconst queryParams = new URLSearchParams({\n\t\t\tscope_id: scopeId,\n\t\t\tsince: lastApplied ?? \"\",\n\t\t\tlimit: String(limit),\n\t\t\tgeneration: String(scope.sync_reset.generation),\n\t\t\tsnapshot_id: scope.sync_reset.snapshot_id,\n\t\t});\n\t\tif (scope.sync_reset.baseline_cursor) {\n\t\t\tqueryParams.set(\"baseline_cursor\", scope.sync_reset.baseline_cursor);\n\t\t}\n\t\tconst url = `${baseUrl}/v1/ops?${queryParams.toString()}`;\n\t\tconst headers = {\n\t\t\t...buildDirectPeerAuthHeaders({\n\t\t\t\tdeviceId,\n\t\t\t\trecipientId: peerDeviceId,\n\t\t\t\tmethod: \"GET\",\n\t\t\t\turl,\n\t\t\t\tbodyBytes: Buffer.alloc(0),\n\t\t\t\tkeysDir,\n\t\t\t\tdbPath,\n\t\t\t}),\n\t\t\t...capabilityHeader(),\n\t\t};\n\t\tconst [status, payload] = await options.requestExecutor(\"GET\", url, { headers });\n\t\toptions.validateCurrentAuthorization?.();\n\n\t\tif (status === 409 && payload?.reset_required === true) {\n\t\t\t// Per-scope reset requested. Clear the stale scoped cursor so the\n\t\t\t// next pass picks a fresh bootstrap path instead of replaying the\n\t\t\t// same invalid boundary forever. We deliberately do not auto-bootstrap from here\n\t\t\t// to avoid surprising state changes mid-loop; the default-scope\n\t\t\t// auto-bootstrap path remains the canonical recovery mechanism.\n\t\t\tresetScopedPullProgress(db, options);\n\t\t\tconst reason = ((): SyncResetRequired[\"reason\"] => {\n\t\t\t\tswitch (payload.reason) {\n\t\t\t\t\tcase \"generation_mismatch\":\n\t\t\t\t\tcase \"boundary_mismatch\":\n\t\t\t\t\tcase \"missing_scope\":\n\t\t\t\t\tcase \"scope_inactive\":\n\t\t\t\t\tcase \"stale_epoch\":\n\t\t\t\t\tcase \"unsupported_scope\":\n\t\t\t\t\t\treturn payload.reason;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn \"stale_cursor\";\n\t\t\t\t}\n\t\t\t})();\n\t\t\tconst error = `reset_required:${reason}`;\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: false,\n\t\t\t\tfailureCategory: scopeResetFailureCategory(reason),\n\t\t\t\topsIn: 0,\n\t\t\t\topsOut: 0,\n\t\t\t\terror,\n\t\t\t\tresetRequired: {\n\t\t\t\t\treset_required: true,\n\t\t\t\t\treason,\n\t\t\t\t\tscope_id: typeof payload.scope_id === \"string\" ? payload.scope_id : scopeId,\n\t\t\t\t\tgeneration: Number(payload.generation ?? scope.sync_reset.generation),\n\t\t\t\t\tsnapshot_id: String(payload.snapshot_id ?? scope.sync_reset.snapshot_id),\n\t\t\t\t\tbaseline_cursor:\n\t\t\t\t\t\ttypeof payload.baseline_cursor === \"string\" ? payload.baseline_cursor.trim() : null,\n\t\t\t\t\tretained_floor_cursor:\n\t\t\t\t\t\ttypeof payload.retained_floor_cursor === \"string\"\n\t\t\t\t\t\t\t? payload.retained_floor_cursor.trim()\n\t\t\t\t\t\t\t: null,\n\t\t\t\t},\n\t\t\t\tbootstrapped: false,\n\t\t\t};\n\t\t}\n\n\t\tif (status !== 200 || payload == null) {\n\t\t\tconst detail = errorDetail(payload);\n\t\t\tconst suffix = detail ? ` (${status}: ${detail})` : ` (${status})`;\n\t\t\tconst error = `peer scoped ops fetch failed${suffix}`;\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: false,\n\t\t\t\tfailureCategory: scopeFailureCategory(error),\n\t\t\t\topsIn: 0,\n\t\t\t\topsOut: 0,\n\t\t\t\terror,\n\t\t\t\tbootstrapped: false,\n\t\t\t};\n\t\t}\n\n\t\tif (!isValidIncrementalOpsResponse(payload)) {\n\t\t\tconst error = \"invalid scoped ops response\";\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: false,\n\t\t\t\tfailureCategory: \"other\",\n\t\t\t\topsIn: 0,\n\t\t\t\topsOut: 0,\n\t\t\t\terror,\n\t\t\t\tbootstrapped: false,\n\t\t\t};\n\t\t}\n\n\t\tconst ops = extractReplicationOps(payload);\n\t\tconst mismatched = ops.find(\n\t\t\t(op) => op.device_id !== peerDeviceId || op.clock_device_id !== peerDeviceId,\n\t\t);\n\t\tif (mismatched) {\n\t\t\tconst error = `inbound op device mismatch:${mismatched.op_id}`;\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: false,\n\t\t\t\tfailureCategory: \"other\",\n\t\t\t\topsIn: 0,\n\t\t\t\topsOut: 0,\n\t\t\t\terror,\n\t\t\t\tbootstrapped: false,\n\t\t\t};\n\t\t}\n\n\t\tconst applyOptions = scopedInboundOptions(peerDeviceId, keysDir);\n\t\tconst applied = applyReplicationOps(db, ops, deviceId, scanner, applyOptions);\n\t\tif (applied.rejected > 0) {\n\t\t\tconst reason = applied.rejections[0]?.reason ?? \"scope_rejected\";\n\t\t\tconst error = `inbound scope rejected:${reason}`;\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: false,\n\t\t\t\tfailureCategory: \"scope\",\n\t\t\t\topsIn: 0,\n\t\t\t\topsOut: 0,\n\t\t\t\terror,\n\t\t\t\tbootstrapped: false,\n\t\t\t};\n\t\t}\n\n\t\tconst reconciliation = reconcileReceivedRowsForExchange(db, options);\n\t\tconst vectorWork = mergedReceiveVectorWork(\n\t\t\tapplied.vectorWork,\n\t\t\treconciliation.deleted_memory_ids,\n\t\t);\n\t\ttry {\n\t\t\tqueueVectorBackfillForIncrementalSync(db, vectorWork);\n\t\t} catch (queueErr) {\n\t\t\tconst fallback = await bestEffortMaintainVectorsForSyncFallback(db, vectorWork);\n\t\t\tif (fallback.errors.length > 0) {\n\t\t\t\tconst error = `vector catch-up failed: ${queueErr instanceof Error ? queueErr.message : String(queueErr)}; fallback failed: ${fallback.errors.join(\"; \")}`;\n\t\t\t\treturn {\n\t\t\t\t\tscope_id: scopeId,\n\t\t\t\t\tlabel: scope.label,\n\t\t\t\t\tok: false,\n\t\t\t\t\tfailureCategory: \"other\",\n\t\t\t\t\treceiveFailureCode: applyReceiveFailure(applied.errors),\n\t\t\t\t\topsIn: 0,\n\t\t\t\t\topsOut: 0,\n\t\t\t\t\terror,\n\t\t\t\t\tbootstrapped: false,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\toptions.validateCurrentAuthorization?.();\n\t\tconst inboundCursorCandidate = asOptionalCursor(payload.next_cursor);\n\t\t// Never advance the inbound cursor past a pass that had apply errors: a\n\t\t// failed op that was not durably recorded would otherwise be skipped\n\t\t// forever (silent data loss). Holding the cursor retries it next pass.\n\t\t// Do NOT \"fix\" a persistent stall by recording throwing ops — that\n\t\t// reintroduces the silent data loss this guards against.\n\t\tif (applied.errors.length > 0) {\n\t\t\tprocess.stderr.write(\n\t\t\t\t`[codemem] sync: holding inbound cursor for scope ${scopeId} — ${applied.errors.length} op(s) failed to apply and will be retried\\n`,\n\t\t\t);\n\t\t}\n\t\tif (applied.errors.length === 0 && cursorAdvances(lastApplied, inboundCursorCandidate)) {\n\t\t\tsetReplicationCursor(db, peerDeviceId, { lastApplied: inboundCursorCandidate }, scopeId);\n\t\t}\n\n\t\tif (applied.errors.length > 0) {\n\t\t\t// Cursor was held (apply errors) — inbound replication for this scope\n\t\t\t// is incomplete and stalled on this window. Report failure so a\n\t\t\t// persistent stall surfaces instead of looking like a healthy sync.\n\t\t\treturn {\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tlabel: scope.label,\n\t\t\t\tok: false,\n\t\t\t\tfailureCategory: \"other\",\n\t\t\t\topsIn: applied.applied,\n\t\t\t\treceiveFailureCode: \"apply_failed\",\n\t\t\t\topsOut: 0,\n\t\t\t\terror: `inbound apply incomplete: ${applied.errors.length} op(s) failed; cursor held for retry`,\n\t\t\t\tbootstrapped: hasNullBaselineBootstrapMarker,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tscope_id: scopeId,\n\t\t\tlabel: scope.label,\n\t\t\tok: true,\n\t\t\topsIn: applied.applied,\n\t\t\topsOut: 0,\n\t\t\tbootstrapped: hasNullBaselineBootstrapMarker,\n\t\t};\n\t} catch (err) {\n\t\tconst detail = err instanceof Error ? err.message.trim() || err.constructor.name : \"unknown\";\n\t\tconst error = `scoped incremental failed: ${detail}`;\n\t\treturn {\n\t\t\tscope_id: scopeId,\n\t\t\tlabel: scope.label,\n\t\t\tok: false,\n\t\t\tfailureCategory: scopeFailureCategory(error),\n\t\t\topsIn: 0,\n\t\t\topsOut: 0,\n\t\t\terror,\n\t\t\tbootstrapped: false,\n\t\t};\n\t}\n}\n\n// Internal transport entrypoint. The caller authenticates one selected scope first.\nexport { syncOneScope as syncScopedPeerPull };\n\n// ---------------------------------------------------------------------------\n// Preflight\n// ---------------------------------------------------------------------------\n\n/** Run migration + replication backfill preflight. */\nexport function syncPassPreflight(db: Database): void {\n\tensureAdditiveSchemaCompatibility(db);\n\tmigrateLegacyImportKeys(db, 2000);\n\tbackfillReplicationOps(db, 200);\n}\n\ntype PeerResetBoundary = NonNullable<ReturnType<typeof parsePeerResetBoundary>>;\n\nfunction scopedInboundOptions(peerDeviceId: string, keysDir: string | undefined) {\n\treturn {\n\t\t...RECEIVE_WINDOW_OPTIONS,\n\t\tactivityPeerDeviceId: peerDeviceId,\n\t\tinboundScopeValidation: { peerDeviceId },\n\t\tkeysDir,\n\t};\n}\n\ninterface SyncExchangeContext {\n\trequestExecutor: RequestJsonExecutor;\n\trecordAttempt: typeof recordSyncAttempt;\n\tdeferConnectionFailure: boolean;\n\tdb: Database;\n\tpeerDeviceId: string;\n\tdeviceId: string;\n\tpinnedFingerprint: string;\n\tpendingBootstrapGrantId: string | undefined;\n\tlimit: number;\n\tkeysDir: string | undefined;\n\tdbPath: string | undefined;\n\tscanner: SecretScanner | undefined;\n\trefreshAuthorization: boolean;\n}\n\ninterface SyncCursorState {\n\tlastApplied: string | null;\n\tlastAcked: string | null;\n}\n\ninterface NegotiatedPeerExchange {\n\tbaseUrl: string;\n\tstatusPayload: Record<string, unknown>;\n\tresetBoundary: PeerResetBoundary;\n\tcapabilities: SyncCapabilityDiagnostics;\n}\n\nclass PeerProtocolMismatchError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"PeerProtocolMismatchError\";\n\t}\n}\n\nclass PeerNegotiationError extends Error {\n\treadonly capabilities: SyncCapabilityDiagnostics;\n\treadonly protocolMismatch: boolean;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tcapabilities: SyncCapabilityDiagnostics,\n\t\toptions: { protocolMismatch: boolean },\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"PeerNegotiationError\";\n\t\tthis.capabilities = capabilities;\n\t\tthis.protocolMismatch = options.protocolMismatch;\n\t}\n}\n\nasync function negotiatePeerExchange(\n\tcontext: SyncExchangeContext,\n\tbaseUrl: string,\n): Promise<NegotiatedPeerExchange> {\n\tconst statusUrl = `${baseUrl}/v1/status`;\n\tconst statusHeaders = {\n\t\t...buildDirectPeerAuthHeaders({\n\t\t\tdeviceId: context.deviceId,\n\t\t\trecipientId: context.peerDeviceId,\n\t\t\tmethod: \"GET\",\n\t\t\turl: statusUrl,\n\t\t\tbodyBytes: Buffer.alloc(0),\n\t\t\tkeysDir: context.keysDir,\n\t\t\tdbPath: context.dbPath,\n\t\t\tbootstrapGrantId: context.pendingBootstrapGrantId,\n\t\t}),\n\t\t...capabilityHeader(),\n\t\t...(context.refreshAuthorization ? { [SYNC_AUTHORIZATION_REFRESH_HEADER]: \"1\" } : {}),\n\t};\n\tconst [statusCode, statusPayload] = await context.requestExecutor(\"GET\", statusUrl, {\n\t\theaders: statusHeaders,\n\t});\n\tif (statusCode !== 200 || !statusPayload) {\n\t\tconst detail = errorDetail(statusPayload);\n\t\tconst suffix = detail ? ` (${statusCode}: ${detail})` : ` (${statusCode})`;\n\t\tthrow new Error(`peer status failed${suffix}`);\n\t}\n\tif (statusPayload.fingerprint !== context.pinnedFingerprint) {\n\t\tthrow new Error(\"peer fingerprint mismatch\");\n\t}\n\tpersistPeerRuntimeVersion(context.db, context.peerDeviceId, statusPayload);\n\tconst capabilities = capabilityDiagnostics(statusPayload.sync_capability);\n\ttry {\n\t\tif (String(statusPayload.protocol_version ?? \"\") !== EXPECTED_SYNC_PROTOCOL_VERSION) {\n\t\t\tthrow new PeerProtocolMismatchError(\n\t\t\t\t`peer protocol mismatch (expected ${EXPECTED_SYNC_PROTOCOL_VERSION}, got ${String(statusPayload.protocol_version ?? \"missing\")})`,\n\t\t\t);\n\t\t}\n\t\tconst resetBoundary = parsePeerResetBoundary(statusPayload);\n\t\tif (!resetBoundary) throw new Error(\"peer status missing sync_reset boundary\");\n\t\tawait reconcilePeerRowsBeforeExchange(context.db, {\n\t\t\tlocalDeviceId: context.deviceId,\n\t\t\tpeerDeviceId: context.peerDeviceId,\n\t\t\tkeysDir: context.keysDir,\n\t\t});\n\t\tif (context.pendingBootstrapGrantId) {\n\t\t\tcontext.db\n\t\t\t\t.prepare(`UPDATE sync_peers SET pending_bootstrap_grant_id = NULL\n\t\t\t\t\tWHERE peer_device_id = ? AND pending_bootstrap_grant_id = ?`)\n\t\t\t\t.run(context.peerDeviceId, context.pendingBootstrapGrantId);\n\t\t}\n\t\treturn { baseUrl, statusPayload, resetBoundary, capabilities };\n\t} catch (error) {\n\t\tconst message =\n\t\t\terror instanceof Error ? error.message.trim() || error.constructor.name : \"unknown\";\n\t\tthrow new PeerNegotiationError(message, capabilities, {\n\t\t\tprotocolMismatch: error instanceof PeerProtocolMismatchError,\n\t\t});\n\t}\n}\n\nfunction sharedMemoryCount(db: Database): number {\n\treturn Number(\n\t\t(\n\t\t\tdb.prepare(\"SELECT count(*) as n FROM memory_items WHERE import_key IS NOT NULL\").get() as {\n\t\t\t\tn: number;\n\t\t\t}\n\t\t)?.n ?? 0,\n\t);\n}\n\nfunction snapshotAccessDenied(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n\treset: SyncResetRequired,\n): SyncResult | null {\n\tif (!reset.scope_id) return null;\n\tconst failure = scopedSnapshotAccessFailure(context.db, {\n\t\tscopeId: reset.scope_id,\n\t\tpeerDeviceId: context.peerDeviceId,\n\t\tlocalDeviceId: context.deviceId,\n\t});\n\tif (!failure) return null;\n\tconst result = scopedSnapshotAccessDeniedResult(peer.baseUrl, reset, failure);\n\tcontext.recordAttempt(context.db, context.peerDeviceId, {\n\t\tok: false,\n\t\terror: `reset_required:${failure}`,\n\t\tfailureCategory: result.failureCategory,\n\t\tcapabilities: peer.capabilities,\n\t});\n\treturn result;\n}\n\ntype SnapshotItems = Awaited<ReturnType<typeof fetchAllSnapshotPages>>[\"items\"];\n\nasync function finishInitialBootstrap(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n\tresetInfo: SyncResetRequired,\n\titems: SnapshotItems,\n): Promise<SyncResult> {\n\tconst bootstrap = applyBootstrapSnapshot(\n\t\tcontext.db,\n\t\tcontext.peerDeviceId,\n\t\titems,\n\t\tresetInfo,\n\t\tcontext.scanner,\n\t\tRECEIVE_WINDOW_OPTIONS,\n\t);\n\tif (!bootstrap.ok) throw new Error(\"initial bootstrap apply failed\");\n\tconst scoped =\n\t\tpeer.capabilities.negotiated === \"scoped\"\n\t\t\t? await runScopedSync(context.db, context.requestExecutor, {\n\t\t\t\t\tpeerDeviceId: context.peerDeviceId,\n\t\t\t\t\tbaseUrl: peer.baseUrl,\n\t\t\t\t\tdeviceId: context.deviceId,\n\t\t\t\t\tstatusPayload: peer.statusPayload,\n\t\t\t\t\tkeysDir: context.keysDir,\n\t\t\t\t\tdbPath: context.dbPath,\n\t\t\t\t\tscanner: context.scanner,\n\t\t\t\t\tlimit: context.limit,\n\t\t\t\t})\n\t\t\t: { results: [], totalOpsIn: 0 };\n\tconst ok = scoped.results.every((result) => result.ok);\n\tconst error = ok\n\t\t? undefined\n\t\t: `scoped sync incomplete: ${scoped.results\n\t\t\t\t.filter((result) => !result.ok)\n\t\t\t\t.map((result) => `${result.scope_id}=${result.error ?? \"unknown\"}`)\n\t\t\t\t.join(\"; \")}`;\n\tconst failureCategory = aggregateScopeFailureCategory(scoped.results);\n\trecordPeerSuccess(context.db, context.peerDeviceId, peer.baseUrl);\n\tcontext.recordAttempt(context.db, context.peerDeviceId, {\n\t\tok,\n\t\topsIn: bootstrap.applied + scoped.totalOpsIn,\n\t\topsOut: 0,\n\t\tcapabilities: peer.capabilities,\n\t\terror,\n\t\tfailureCategory,\n\t});\n\treturn {\n\t\tok,\n\t\taddress: peer.baseUrl,\n\t\tfailureCategory,\n\t\topsIn: bootstrap.applied + scoped.totalOpsIn,\n\t\topsOut: 0,\n\t\taddressErrors: [],\n\t\treceiveFailureCode: aggregateReceiveFailure(scoped.results),\n\t\tperScopeResults: scoped.results.length > 0 ? scoped.results : undefined,\n\t};\n}\n\nasync function performInitialBootstrap(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n): Promise<SyncResult> {\n\tconst resetInfo = {\n\t\tscope_id: peer.resetBoundary.scope_id,\n\t\tgeneration: peer.resetBoundary.generation,\n\t\tsnapshot_id: peer.resetBoundary.snapshot_id,\n\t\tbaseline_cursor: peer.resetBoundary.baseline_cursor ?? null,\n\t\tretained_floor_cursor: peer.resetBoundary.retained_floor_cursor ?? null,\n\t\treset_required: true as const,\n\t\treason: \"initial_bootstrap\" as const,\n\t};\n\tconst accessDenied = snapshotAccessDenied(context, peer, resetInfo);\n\tif (accessDenied) return accessDenied;\n\tconst { items } = await fetchAllSnapshotPages(peer.baseUrl, resetInfo, context.deviceId, {\n\t\trequestExecutor: context.requestExecutor,\n\t\tkeysDir: context.keysDir,\n\t\tdbPath: context.dbPath,\n\t\trecipientId: context.peerDeviceId,\n\t\tpageSize: BOOTSTRAP_PAGE_SIZE,\n\t\ttimeoutS: BOOTSTRAP_REQUEST_TIMEOUT_S,\n\t});\n\tconst postFetchSharedCount = sharedMemoryCount(context.db);\n\tif (postFetchSharedCount > 0) {\n\t\tcontext.recordAttempt(context.db, context.peerDeviceId, {\n\t\t\tok: false,\n\t\t\terror: \"needs_attention:shared_memories_appeared_during_bootstrap\",\n\t\t\tfailureCategory: \"other\",\n\t\t\tcapabilities: peer.capabilities,\n\t\t});\n\t\treturn {\n\t\t\tok: false,\n\t\t\taddress: peer.baseUrl,\n\t\t\terror: `needs attention: ${postFetchSharedCount} shared memory change(s) appeared during initial bootstrap fetch`,\n\t\t\tfailureCategory: \"other\",\n\t\t\topsIn: 0,\n\t\t\topsOut: 0,\n\t\t\taddressErrors: [],\n\t\t};\n\t}\n\treturn finishInitialBootstrap(context, peer, resetInfo, items);\n}\n\nasync function tryInitialBootstrap(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n\tcursors: SyncCursorState,\n): Promise<SyncResult | null> {\n\tif (cursors.lastApplied !== null || cursors.lastAcked !== null) return null;\n\tif (sharedMemoryCount(context.db) !== 0) return null;\n\ttry {\n\t\treturn await performInitialBootstrap(context, peer);\n\t} catch (error) {\n\t\tconst detail = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(`initial bootstrap failed: ${detail}`);\n\t}\n}\n\nfunction resetRequiredFromPayload(payload: Record<string, unknown>): SyncResetRequired {\n\tconst reason =\n\t\tpayload.reason === \"generation_mismatch\" ||\n\t\tpayload.reason === \"boundary_mismatch\" ||\n\t\tpayload.reason === \"missing_scope\" ||\n\t\tpayload.reason === \"unsupported_scope\"\n\t\t\t? payload.reason\n\t\t\t: \"stale_cursor\";\n\treturn {\n\t\treset_required: true,\n\t\treason,\n\t\tscope_id: typeof payload.scope_id === \"string\" ? payload.scope_id : null,\n\t\tgeneration: Number(payload.generation ?? 1),\n\t\tsnapshot_id: String(payload.snapshot_id ?? \"\"),\n\t\tbaseline_cursor: asOptionalCursor(payload.baseline_cursor),\n\t\tretained_floor_cursor: asOptionalCursor(payload.retained_floor_cursor),\n\t};\n}\n\nfunction resetBlockedResult(\n\tbaseUrl: string,\n\tcount: number,\n\tresetRequired: SyncResetRequired,\n\twhen: \"before\" | \"during\",\n): SyncResult {\n\tconst timing = when === \"during\" ? \" appeared during bootstrap fetch\" : \" block automatic reset\";\n\treturn {\n\t\tok: false,\n\t\taddress: baseUrl,\n\t\terror: `needs attention: ${count} unsynced shared memory change(s)${timing}`,\n\t\tfailureCategory: \"other\",\n\t\topsIn: 0,\n\t\topsOut: 0,\n\t\taddressErrors: [],\n\t\tresetRequired,\n\t};\n}\n\nfunction failedResetBootstrap(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n\tresetRequired: SyncResetRequired,\n\terror: unknown,\n): SyncResult {\n\tconst detail = error instanceof Error ? error.message : String(error);\n\tcontext.recordAttempt(context.db, context.peerDeviceId, {\n\t\tok: false,\n\t\terror: `bootstrap_failed:${detail}`,\n\t\tfailureCategory: \"other\",\n\t\tcapabilities: peer.capabilities,\n\t});\n\treturn {\n\t\tok: false,\n\t\taddress: peer.baseUrl,\n\t\terror: `bootstrap failed: ${detail}`,\n\t\tfailureCategory: \"other\",\n\t\topsIn: 0,\n\t\topsOut: 0,\n\t\taddressErrors: [],\n\t\tresetRequired,\n\t};\n}\n\nasync function performResetBootstrap(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n\tresetRequired: SyncResetRequired,\n): Promise<SyncResult> {\n\tconst dirtyLocal = hasUnsyncedSharedMemoryChanges(context.db);\n\tif (dirtyLocal.dirty) {\n\t\tcontext.recordAttempt(context.db, context.peerDeviceId, {\n\t\t\tok: false,\n\t\t\terror: `needs_attention:local_unsynced_shared_memory:${dirtyLocal.count}`,\n\t\t\tfailureCategory: \"other\",\n\t\t\tcapabilities: peer.capabilities,\n\t\t});\n\t\treturn resetBlockedResult(peer.baseUrl, dirtyLocal.count, resetRequired, \"before\");\n\t}\n\ttry {\n\t\tconst accessDenied = snapshotAccessDenied(context, peer, resetRequired);\n\t\tif (accessDenied) return accessDenied;\n\t\tconst { items } = await fetchAllSnapshotPages(peer.baseUrl, resetRequired, context.deviceId, {\n\t\t\trequestExecutor: context.requestExecutor,\n\t\t\tkeysDir: context.keysDir,\n\t\t\tdbPath: context.dbPath,\n\t\t\trecipientId: context.peerDeviceId,\n\t\t\ttimeoutS: BOOTSTRAP_REQUEST_TIMEOUT_S,\n\t\t});\n\t\tconst dirtyAfterFetch = hasUnsyncedSharedMemoryChanges(context.db);\n\t\tif (dirtyAfterFetch.dirty) {\n\t\t\tcontext.recordAttempt(context.db, context.peerDeviceId, {\n\t\t\t\tok: false,\n\t\t\t\terror: `needs_attention:local_unsynced_shared_memory:${dirtyAfterFetch.count}`,\n\t\t\t\tfailureCategory: \"other\",\n\t\t\t\tcapabilities: peer.capabilities,\n\t\t\t});\n\t\t\treturn resetBlockedResult(peer.baseUrl, dirtyAfterFetch.count, resetRequired, \"during\");\n\t\t}\n\t\tconst bootstrapResult = applyBootstrapSnapshot(\n\t\t\tcontext.db,\n\t\t\tcontext.peerDeviceId,\n\t\t\titems,\n\t\t\tresetRequired,\n\t\t\tcontext.scanner,\n\t\t\tRECEIVE_WINDOW_OPTIONS,\n\t\t);\n\t\tif (!bootstrapResult.ok) throw new Error(\"bootstrap apply failed\");\n\t\trecordPeerSuccess(context.db, context.peerDeviceId, peer.baseUrl);\n\t\tcontext.recordAttempt(context.db, context.peerDeviceId, {\n\t\t\tok: true,\n\t\t\topsIn: bootstrapResult.applied,\n\t\t\topsOut: 0,\n\t\t\tcapabilities: peer.capabilities,\n\t\t});\n\t\treturn {\n\t\t\tok: true,\n\t\t\taddress: peer.baseUrl,\n\t\t\topsIn: bootstrapResult.applied,\n\t\t\topsOut: 0,\n\t\t\taddressErrors: [],\n\t\t};\n\t} catch (error) {\n\t\treturn failedResetBootstrap(context, peer, resetRequired, error);\n\t}\n}\n\ninterface PulledDefaultOps {\n\tkind: \"ops\";\n\tpayload: Record<string, unknown>;\n\tops: ReplicationOp[];\n}\n\ninterface PulledResetResult {\n\tkind: \"result\";\n\tresult: SyncResult;\n}\n\nasync function pullDefaultScope(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n\tlastApplied: string | null,\n): Promise<PulledDefaultOps | PulledResetResult> {\n\tconst queryParams = new URLSearchParams({\n\t\tsince: lastApplied ?? \"\",\n\t\tlimit: String(context.limit),\n\t\tgeneration: String(peer.resetBoundary.generation),\n\t\tsnapshot_id: peer.resetBoundary.snapshot_id,\n\t});\n\tif (peer.resetBoundary.baseline_cursor) {\n\t\tqueryParams.set(\"baseline_cursor\", peer.resetBoundary.baseline_cursor);\n\t}\n\tconst getUrl = `${peer.baseUrl}/v1/ops?${queryParams.toString()}`;\n\tconst getHeaders = {\n\t\t...buildDirectPeerAuthHeaders({\n\t\t\tdeviceId: context.deviceId,\n\t\t\trecipientId: context.peerDeviceId,\n\t\t\tmethod: \"GET\",\n\t\t\turl: getUrl,\n\t\t\tbodyBytes: Buffer.alloc(0),\n\t\t\tkeysDir: context.keysDir,\n\t\t\tdbPath: context.dbPath,\n\t\t}),\n\t\t...capabilityHeader(),\n\t};\n\tconst [status, payload] = await context.requestExecutor(\"GET\", getUrl, { headers: getHeaders });\n\tif (status === 409 && payload?.reset_required === true) {\n\t\treturn {\n\t\t\tkind: \"result\",\n\t\t\tresult: await performResetBootstrap(context, peer, resetRequiredFromPayload(payload)),\n\t\t};\n\t}\n\tif (status !== 200 || payload == null) {\n\t\tconst detail = errorDetail(payload);\n\t\tconst suffix = detail ? ` (${status}: ${detail})` : ` (${status})`;\n\t\tthrow new Error(`peer ops fetch failed${suffix}`);\n\t}\n\tif (!isValidIncrementalOpsResponse(payload)) throw new Error(\"invalid ops response\");\n\tconst ops = extractReplicationOps(payload);\n\tconst mismatchedOp = ops.find(\n\t\t(op) => op.device_id !== context.peerDeviceId || op.clock_device_id !== context.peerDeviceId,\n\t);\n\tif (mismatchedOp) throw new Error(`inbound op device mismatch:${mismatchedOp.op_id}`);\n\treturn { kind: \"ops\", payload, ops };\n}\n\ntype AppliedReplicationOps = ReturnType<typeof applyReplicationOps>;\n\nasync function applyPulledDefaultOps(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n\tpulled: PulledDefaultOps,\n\tlastApplied: string | null,\n): Promise<{ applied: AppliedReplicationOps; lastApplied: string | null }> {\n\tconst inboundScopeValidation =\n\t\tpeer.capabilities.negotiated === \"unsupported\"\n\t\t\t? { peerDeviceId: context.peerDeviceId, enabled: false }\n\t\t\t: { peerDeviceId: context.peerDeviceId };\n\tconst applied = applyReplicationOps(context.db, pulled.ops, context.deviceId, context.scanner, {\n\t\t...RECEIVE_WINDOW_OPTIONS,\n\t\tactivityPeerDeviceId: context.peerDeviceId,\n\t\tinboundScopeValidation,\n\t\tkeysDir: context.keysDir,\n\t});\n\tif (applied.rejected > 0) {\n\t\tconst firstReason = applied.rejections[0]?.reason ?? \"scope_rejected\";\n\t\tthrow new Error(`inbound scope rejected:${firstReason}`);\n\t}\n\tconst reconciliation = reconcileStalePeerReceivedRows(context.db, {\n\t\tlocalDeviceId: context.deviceId,\n\t\tpeerDeviceId: context.peerDeviceId,\n\t\tkeysDir: context.keysDir,\n\t});\n\tconst vectorWork = {\n\t\tupsertMemoryIds: applied.vectorWork.upsertMemoryIds,\n\t\tdeleteMemoryIds: [...applied.vectorWork.deleteMemoryIds, ...reconciliation.deleted_memory_ids],\n\t};\n\ttry {\n\t\tqueueVectorBackfillForIncrementalSync(context.db, vectorWork);\n\t} catch (queueError) {\n\t\tconst fallback = await bestEffortMaintainVectorsForSyncFallback(context.db, vectorWork);\n\t\tif (fallback.errors.length > 0) {\n\t\t\tconst details = fallback.errors.join(\"; \");\n\t\t\tthrow new Error(\n\t\t\t\t`vector catch-up queue failed: ${queueError instanceof Error ? queueError.message : String(queueError)}; fallback failed: ${details}`,\n\t\t\t);\n\t\t}\n\t}\n\tconst inboundCursor = asOptionalCursor(pulled.payload.next_cursor);\n\tif (applied.errors.length > 0) {\n\t\tprocess.stderr.write(\n\t\t\t`[codemem] sync: holding inbound cursor for peer ${context.peerDeviceId} — ${applied.errors.length} op(s) failed to apply and will be retried\\n`,\n\t\t);\n\t}\n\tif (applied.errors.length !== 0 || !cursorAdvances(lastApplied, inboundCursor)) {\n\t\treturn { applied, lastApplied };\n\t}\n\tsetReplicationCursor(context.db, context.peerDeviceId, { lastApplied: inboundCursor });\n\treturn { applied, lastApplied: inboundCursor };\n}\n\n/**\n * Drop scoped ops the peer already holds, so a path switch does not resend them.\n *\n * The relay channel acknowledges per scope in `sync_channel_progress`, while\n * this legacy push tracks one interleaved cursor. A scope's position is the\n * later of the channel ACK, when its boundary still matches the peer's current\n * one, and the pull cursor the peer reports in status. Ops at or before that\n * position were already applied there. Legacy peers report no scopes, so\n * nothing is dropped for them.\n */\nfunction withoutOpsPeerAlreadyHolds(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n\tops: ReplicationOp[],\n): ReplicationOp[] {\n\tconst held = new Map<string, string>();\n\tfor (const scope of parseAuthorizedScopes(peer.statusPayload.authorized_scopes)) {\n\t\tconst progress = getSyncChannelProgress(context.db, context.peerDeviceId, scope.scope_id);\n\t\tconst acked = hasCompletedSyncChannelBoundary(progress, scope.sync_reset)\n\t\t\t? (progress?.last_acked_cursor ?? null)\n\t\t\t: null;\n\t\tconst position = [acked, scope.applied_cursor]\n\t\t\t.filter((cursor): cursor is string => cursor !== null)\n\t\t\t.sort()\n\t\t\t.at(-1);\n\t\tif (position) held.set(scope.scope_id, position);\n\t}\n\tif (held.size === 0) return ops;\n\treturn ops.filter((op) => {\n\t\tconst position = op.scope_id ? held.get(op.scope_id) : undefined;\n\t\treturn position === undefined || `${op.created_at}|${op.op_id}` > position;\n\t});\n}\n\ninterface PushedDefaultOps {\n\toutboundOps: ReplicationOp[];\n\tskippedOutbound: FilterReplicationSkipped | null | undefined;\n\topsSkipped: number;\n\tlastAcked: string | null;\n}\n\nasync function pushDefaultScope(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n\tlastAcked: string | null,\n): Promise<PushedDefaultOps> {\n\tconst [outboundWindow, outboundCursor] = loadLocalOpsSince(\n\t\tcontext.db,\n\t\tlastAcked,\n\t\tcontext.deviceId,\n\t\tcontext.limit,\n\t);\n\tconst [allowedOps, filteredOutboundCursor, skippedOutbound] =\n\t\tfilterReplicationOpsForSyncWithStatus(context.db, outboundWindow, context.peerDeviceId, {\n\t\t\tlocalDeviceId: context.deviceId,\n\t\t\tsupportsReassignScope: supportsSyncFeature(\n\t\t\t\tpeer.statusPayload.sync_features,\n\t\t\t\t\"reassign_scope\",\n\t\t\t),\n\t\t});\n\tconst outboundOps = withoutOpsPeerAlreadyHolds(context, peer, allowedOps);\n\tconst postUrl = `${peer.baseUrl}/v1/ops`;\n\t// An idle sender still verifies the signed POST path without claiming any transfer.\n\tconst batches = outboundOps.length > 0 ? chunkOpsBySize(outboundOps, MAX_SYNC_BODY_BYTES) : [[]];\n\tfor (const batch of batches) {\n\t\tawait pushOps(\n\t\t\tpostUrl,\n\t\t\tcontext.deviceId,\n\t\t\tcontext.peerDeviceId,\n\t\t\tbatch,\n\t\t\tcontext.requestExecutor,\n\t\t\t(acknowledged) => {\n\t\t\t\tcontext.db.transaction(() => {\n\t\t\t\t\trecordSyncTransferReceipts(\n\t\t\t\t\t\tcontext.db,\n\t\t\t\t\t\tcontext.peerDeviceId,\n\t\t\t\t\t\t\"send\",\n\t\t\t\t\t\tacknowledged.map((op) => op.op_id),\n\t\t\t\t\t);\n\t\t\t\t\trecordSyncTransferObservation(context.db, context.peerDeviceId, \"send\");\n\t\t\t\t})();\n\t\t\t},\n\t\t\tcontext.keysDir,\n\t\t\tcontext.dbPath,\n\t\t);\n\t}\n\tconst ackCursor = filteredOutboundCursor ?? outboundCursor;\n\tlet nextLastAcked = lastAcked;\n\tif (ackCursor && cursorAdvances(lastAcked, ackCursor)) {\n\t\tsetReplicationCursor(context.db, context.peerDeviceId, { lastAcked: ackCursor });\n\t\tnextLastAcked = ackCursor;\n\t}\n\treturn {\n\t\toutboundOps,\n\t\tskippedOutbound,\n\t\topsSkipped: skippedOutbound?.skipped_count ?? 0,\n\t\tlastAcked: nextLastAcked,\n\t};\n}\n\nfunction incrementalReceiveErrors(\n\tapplyErrors: readonly string[],\n\tscopes: SyncScopeResult[],\n): string[] {\n\tconst errors: string[] = [];\n\tif (applyErrors.length > 0) {\n\t\terrors.push(\n\t\t\t`inbound apply incomplete: ${applyErrors.length} op(s) failed; cursor held for retry`,\n\t\t);\n\t}\n\tconst failedScopes = scopes.filter((result) => !result.ok);\n\tif (failedScopes.length > 0) {\n\t\terrors.push(\n\t\t\t`scoped sync incomplete: ${failedScopes\n\t\t\t\t.map((result) => `${result.scope_id}=${result.error ?? \"unknown\"}`)\n\t\t\t\t.join(\"; \")}`,\n\t\t);\n\t}\n\treturn errors;\n}\n\nasync function finishIncrementalExchange(\n\tcontext: SyncExchangeContext,\n\tpeer: NegotiatedPeerExchange,\n\tapplied: AppliedReplicationOps,\n\tpushed: PushedDefaultOps,\n): Promise<SyncResult> {\n\tconst scoped =\n\t\tpeer.capabilities.negotiated === \"scoped\"\n\t\t\t? await runScopedSync(context.db, context.requestExecutor, {\n\t\t\t\t\tpeerDeviceId: context.peerDeviceId,\n\t\t\t\t\tbaseUrl: peer.baseUrl,\n\t\t\t\t\tdeviceId: context.deviceId,\n\t\t\t\t\tstatusPayload: peer.statusPayload,\n\t\t\t\t\tkeysDir: context.keysDir,\n\t\t\t\t\tdbPath: context.dbPath,\n\t\t\t\t\tscanner: context.scanner,\n\t\t\t\t\tlimit: context.limit,\n\t\t\t\t})\n\t\t\t: { results: [], totalOpsIn: 0 };\n\tconst allScopesOk = scoped.results.every((result) => result.ok);\n\tconst inboundIncomplete = applied.errors.length > 0;\n\tconst errors = incrementalReceiveErrors(applied.errors, scoped.results);\n\tconst ok = allScopesOk && !inboundIncomplete;\n\tconst error = errors.length > 0 ? errors.join(\"; \") : undefined;\n\tconst failureCategory = inboundIncomplete\n\t\t? \"other\"\n\t\t: aggregateScopeFailureCategory(scoped.results);\n\tif (!inboundIncomplete) recordPeerSuccess(context.db, context.peerDeviceId, peer.baseUrl);\n\tcontext.recordAttempt(context.db, context.peerDeviceId, {\n\t\tok,\n\t\topsIn: applied.applied + scoped.totalOpsIn,\n\t\topsOut: pushed.outboundOps.length,\n\t\tcapabilities: peer.capabilities,\n\t\terror,\n\t\tfailureCategory,\n\t});\n\treturn {\n\t\tok,\n\t\taddress: peer.baseUrl,\n\t\terror,\n\t\tfailureCategory,\n\t\topsIn: applied.applied + scoped.totalOpsIn,\n\t\topsOut: pushed.outboundOps.length,\n\t\topsSkipped: pushed.opsSkipped,\n\t\tskippedOut: pushed.skippedOutbound ?? null,\n\t\taddressErrors: [],\n\t\treceiveFailureCode: aggregateReceiveFailure(scoped.results, { applyErrors: applied.errors }),\n\t\tperScopeResults: scoped.results.length > 0 ? scoped.results : undefined,\n\t};\n}\n\ntype SyncAddressOutcome =\n\t| { kind: \"success\"; result: SyncResult }\n\t| {\n\t\t\tkind: \"failure\";\n\t\t\terror: unknown;\n\t\t\tcapabilities: SyncCapabilityDiagnostics | undefined;\n\t\t\tnegotiationFailed?: boolean;\n\t };\n\nfunction recordReceiveResult<\n\tT extends {\n\t\tok: boolean;\n\t\tfailureCategory?: SyncFailureCategory;\n\t\treceiveFailureCode?: SyncTransferErrorCode;\n\t},\n>(context: SyncExchangeContext, result: T, options: { preserveError?: boolean } = {}): T {\n\tlet errorCode: SyncTransferErrorCode | undefined;\n\tif (!result.ok) {\n\t\terrorCode =\n\t\t\tresult.receiveFailureCode ??\n\t\t\t(result.failureCategory === \"scope\" ? \"scope_rejected\" : \"exchange_failed\");\n\t}\n\trecordSyncTransferObservation(context.db, context.peerDeviceId, \"receive\", {\n\t\t...options,\n\t\terrorCode,\n\t});\n\treturn result;\n}\n\nasync function syncAddress(\n\tcontext: SyncExchangeContext,\n\tbaseUrl: string,\n\tcursors: SyncCursorState,\n): Promise<SyncAddressOutcome> {\n\tlet peer: NegotiatedPeerExchange;\n\ttry {\n\t\tpeer = await negotiatePeerExchange(context, baseUrl);\n\t} catch (error) {\n\t\treturn {\n\t\t\tkind: \"failure\",\n\t\t\terror,\n\t\t\tcapabilities: error instanceof PeerNegotiationError ? error.capabilities : undefined,\n\t\t\tnegotiationFailed: true,\n\t\t};\n\t}\n\tlet direction: \"send\" | \"receive\" = \"receive\";\n\ttry {\n\t\tconst bootstrap = await tryInitialBootstrap(context, peer, cursors);\n\t\tif (bootstrap) {\n\t\t\trecordReceiveResult(context, bootstrap);\n\t\t\treturn { kind: \"success\", result: bootstrap };\n\t\t}\n\t\tconst pulled = await pullDefaultScope(context, peer, cursors.lastApplied);\n\t\tif (pulled.kind === \"result\") {\n\t\t\t// Reset recovery checks only the default scope, not the remaining receive scopes.\n\t\t\trecordReceiveResult(context, pulled.result, RECEIVE_WINDOW_OPTIONS.activityOptions);\n\t\t\treturn { kind: \"success\", result: pulled.result };\n\t\t}\n\t\tconst applied = await applyPulledDefaultOps(context, peer, pulled, cursors.lastApplied);\n\t\tcursors.lastApplied = applied.lastApplied;\n\t\tdirection = \"send\";\n\t\tconst pushed = await pushDefaultScope(context, peer, cursors.lastAcked);\n\t\tcursors.lastAcked = pushed.lastAcked;\n\t\tdirection = \"receive\";\n\t\treturn {\n\t\t\tkind: \"success\",\n\t\t\tresult: recordReceiveResult(\n\t\t\t\tcontext,\n\t\t\t\tawait finishIncrementalExchange(context, peer, applied.applied, pushed),\n\t\t\t),\n\t\t};\n\t} catch (error) {\n\t\trecordSyncTransferObservation(context.db, context.peerDeviceId, direction, {\n\t\t\terrorCode: \"exchange_failed\",\n\t\t});\n\t\treturn { kind: \"failure\", error, capabilities: peer.capabilities };\n\t}\n}\n\nfunction warnMissingSyncScanner(scanner: SecretScanner | undefined): void {\n\tif (scanner || syncOnceScannerWarned) return;\n\tsyncOnceScannerWarned = true;\n\tprocess.stderr.write(\n\t\t\"[codemem] sync apply running without explicit scanner — workspace-level secret rules will not apply to inbound peer content\\n\",\n\t);\n}\n\nfunction peerPin(\n\tdb: Database,\n\tpeerDeviceId: string,\n): { pinnedFingerprint: string; pendingBootstrapGrantId: string | undefined } {\n\tconst d = drizzle(db, { schema });\n\tconst row = d\n\t\t.select({\n\t\t\tpinned_fingerprint: schema.syncPeers.pinned_fingerprint,\n\t\t\tpending_bootstrap_grant_id: schema.syncPeers.pending_bootstrap_grant_id,\n\t\t})\n\t\t.from(schema.syncPeers)\n\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t.get();\n\treturn {\n\t\tpinnedFingerprint: row?.pinned_fingerprint ?? \"\",\n\t\tpendingBootstrapGrantId: row?.pending_bootstrap_grant_id?.trim() || undefined,\n\t};\n}\n\nfunction unavailableIdentityResult(\n\tdb: Database,\n\tpeerDeviceId: string,\n\terror: unknown,\n\trecordAttempt = recordSyncAttempt,\n): SyncResult {\n\tconst detail =\n\t\terror instanceof Error ? error.message.trim() || error.constructor.name : \"unknown\";\n\tconst message = `device identity unavailable: ${detail}`;\n\trecordAttempt(db, peerDeviceId, { ok: false, error: message, failureCategory: \"other\" });\n\treturn {\n\t\tok: false,\n\t\terror: message,\n\t\tfailureCategory: \"other\",\n\t\topsIn: 0,\n\t\topsOut: 0,\n\t\taddressErrors: [],\n\t};\n}\n\ntype PreparedSyncExchange =\n\t| { kind: \"ready\"; context: SyncExchangeContext; cursors: SyncCursorState }\n\t| { kind: \"result\"; result: SyncResult };\n\nfunction prepareSyncExchange(\n\tdb: Database,\n\tpeerDeviceId: string,\n\toptions: SyncPassOptions | undefined,\n): PreparedSyncExchange {\n\tensureAdditiveSchemaCompatibility(db);\n\twarnMissingSyncScanner(options?.scanner);\n\tconst { pinnedFingerprint, pendingBootstrapGrantId } = peerPin(db, peerDeviceId);\n\tif (!pinnedFingerprint) {\n\t\treturn {\n\t\t\tkind: \"result\",\n\t\t\tresult: {\n\t\t\t\tok: false,\n\t\t\t\terror: \"peer not pinned\",\n\t\t\t\tfailureCategory: \"trust\",\n\t\t\t\topsIn: 0,\n\t\t\t\topsOut: 0,\n\t\t\t\taddressErrors: [],\n\t\t\t},\n\t\t};\n\t}\n\tlet deviceId: string;\n\ttry {\n\t\t[deviceId] = ensureDeviceIdentity(db, { keysDir: options?.keysDir });\n\t} catch (error) {\n\t\treturn {\n\t\t\tkind: \"result\",\n\t\t\tresult: unavailableIdentityResult(db, peerDeviceId, error, options?.attemptRecorder),\n\t\t};\n\t}\n\tconst [lastApplied, lastAcked] = getReplicationCursor(db, peerDeviceId);\n\treturn {\n\t\tkind: \"ready\",\n\t\tcontext: {\n\t\t\trequestExecutor: options?.requestExecutor ?? requestJson,\n\t\t\trecordAttempt: (attemptDb, peerId, attempt) => {\n\t\t\t\tconst record = options?.attemptRecorder ?? recordSyncAttempt;\n\t\t\t\t// This exchange dials a peer directly. Relay selection happens outside syncOnce.\n\t\t\t\trecord(attemptDb, peerId, { ...attempt, transport: \"direct\" });\n\t\t\t},\n\t\t\tdeferConnectionFailure: options?.deferConnectionFailure ?? false,\n\t\t\tdb,\n\t\t\tpeerDeviceId,\n\t\t\tdeviceId,\n\t\t\tpinnedFingerprint,\n\t\t\tpendingBootstrapGrantId,\n\t\t\tlimit: options?.limit ?? DEFAULT_LIMIT,\n\t\t\tkeysDir: options?.keysDir,\n\t\t\tdbPath: options?.dbPath,\n\t\t\tscanner: options?.scanner,\n\t\t\trefreshAuthorization: options?.refreshAuthorization ?? false,\n\t\t},\n\t\tcursors: { lastApplied, lastAcked },\n\t};\n}\n\nfunction failedAddressResult(\n\tdb: Database,\n\tpeerDeviceId: string,\n\taddressErrors: Array<{ address: string; error: string }>,\n\tattemptedAny: boolean,\n\tcapabilities: SyncCapabilityDiagnostics | undefined,\n\toptions: { protocolMismatch: boolean; recordAttempt: typeof recordSyncAttempt },\n): SyncResult {\n\tlet error = summarizeAddressErrors(addressErrors);\n\tif (!attemptedAny) error = \"no dialable peer addresses\";\n\tif (!error) error = \"sync failed without diagnostic detail\";\n\tconst failureCategory = categorizeSyncFailure(error);\n\toptions.recordAttempt(db, peerDeviceId, {\n\t\tok: false,\n\t\terror,\n\t\tfailureCategory: options.protocolMismatch\n\t\t\t? \"compatibility\"\n\t\t\t: storedAddressFailureCategory(addressErrors, error),\n\t\tcapabilities,\n\t});\n\treturn {\n\t\tok: false,\n\t\terror,\n\t\tfailureCategory,\n\t\topsIn: 0,\n\t\topsOut: 0,\n\t\taddressErrors,\n\t};\n}\n\nasync function tryPeerAddresses(\n\tcontext: SyncExchangeContext,\n\tcursors: SyncCursorState,\n\taddresses: string[],\n): Promise<SyncResult> {\n\tconst addressErrors: Array<{ address: string; error: string }> = [];\n\tlet attemptedAny = false;\n\tlet negotiated = false;\n\tlet capabilities: SyncCapabilityDiagnostics | undefined;\n\t// A protocol mismatch is only reported after the pinned fingerprint\n\t// matched, so the peer was reachable and trusted but incompatible.\n\tlet protocolMismatch = false;\n\tconst boundedAddresses = mergeAddresses(addresses, [], {\n\t\tmaxAddresses: MAX_PEER_ADDRESSES,\n\t});\n\tfor (const address of boundedAddresses) {\n\t\tconst baseUrl = buildBaseUrl(address);\n\t\tif (!baseUrl) continue;\n\t\tattemptedAny = true;\n\t\tconst exchange = await syncAddress(context, baseUrl, cursors);\n\t\tif (exchange.kind === \"success\") return exchange.result;\n\t\tif (!exchange.negotiationFailed) negotiated = true;\n\t\tif (exchange.capabilities) capabilities = exchange.capabilities;\n\t\tif (exchange.error instanceof PeerNegotiationError && exchange.error.protocolMismatch) {\n\t\t\tprotocolMismatch = true;\n\t\t}\n\t\tconst detail =\n\t\t\texchange.error instanceof Error\n\t\t\t\t? exchange.error.message.trim() || exchange.error.constructor.name\n\t\t\t\t: \"unknown\";\n\t\taddressErrors.push({ address: baseUrl, error: detail });\n\t}\n\tconst result = failedAddressResult(\n\t\tcontext.db,\n\t\tcontext.peerDeviceId,\n\t\taddressErrors,\n\t\tattemptedAny,\n\t\tcapabilities,\n\t\t{ protocolMismatch, recordAttempt: context.recordAttempt },\n\t);\n\treturn recordExhaustedConnectionFailure(context, result, { attemptedAny, negotiated });\n}\n\nfunction recordExhaustedConnectionFailure(\n\tcontext: SyncExchangeContext,\n\tresult: SyncResult,\n\toptions: { attemptedAny: boolean; negotiated: boolean },\n): SyncResult {\n\tif (!options.attemptedAny || options.negotiated) return result;\n\tresult.receiveFailureCode = \"exchange_failed\";\n\tif (!context.deferConnectionFailure) {\n\t\trecordSyncTransferObservation(context.db, context.peerDeviceId, \"receive\", {\n\t\t\terrorCode: \"exchange_failed\",\n\t\t});\n\t}\n\treturn result;\n}\n\n// ---------------------------------------------------------------------------\n// Main sync loop\n// ---------------------------------------------------------------------------\n\n/**\n * Execute a single sync exchange with a peer across the given addresses.\n *\n * Tries each address in order. On first success, returns immediately.\n * On all failures, collects address-level errors and returns them.\n */\nexport async function syncOnce(\n\tdb: Database,\n\tpeerDeviceId: string,\n\taddresses: string[],\n\toptions?: SyncPassOptions,\n): Promise<SyncResult> {\n\tconst prepared = prepareSyncExchange(db, peerDeviceId, options);\n\tif (prepared.kind === \"result\") return prepared.result;\n\treturn tryPeerAddresses(prepared.context, prepared.cursors, addresses);\n}\n\n// ---------------------------------------------------------------------------\n// Connectivity backoff (for daemon use)\n// ---------------------------------------------------------------------------\n\n/** Connectivity error patterns indicating peer is offline. */\nconst CONNECTIVITY_ERROR_PATTERNS = [\n\t\"no route to host\",\n\t\"connection refused\",\n\t\"network is unreachable\",\n\t\"timed out\",\n\t\"name or service not known\",\n\t\"nodename nor servname provided\",\n\t\"errno 65\",\n\t\"errno 61\",\n\t\"errno 60\",\n\t\"errno 111\",\n] as const;\n\nconst PEER_BACKOFF_BASE_S = 120;\nconst PEER_BACKOFF_MAX_S = 1800;\n\n/** Check if an error string indicates a network connectivity failure. */\nexport function isConnectivityError(error: string | null): boolean {\n\tif (!error) return false;\n\tconst lower = error.toLowerCase();\n\treturn CONNECTIVITY_ERROR_PATTERNS.some((pattern) => lower.includes(pattern));\n}\n\n/** Count consecutive recent failures that are connectivity errors. */\nexport function consecutiveConnectivityFailures(\n\tdb: Database,\n\tpeerDeviceId: string,\n\tlimit = 10,\n): number {\n\tconst d = drizzle(db, { schema });\n\tconst rows = d\n\t\t.select({ ok: schema.syncAttempts.ok, error: schema.syncAttempts.error })\n\t\t.from(schema.syncAttempts)\n\t\t.where(eq(schema.syncAttempts.peer_device_id, peerDeviceId))\n\t\t.orderBy(desc(schema.syncAttempts.started_at))\n\t\t.limit(limit)\n\t\t.all();\n\n\tlet count = 0;\n\tfor (const row of rows) {\n\t\tif (row.ok) break;\n\t\tif (isConnectivityError(row.error)) {\n\t\t\tcount++;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn count;\n}\n\n/** Calculate backoff duration with jitter to avoid thundering herd. */\nexport function peerBackoffSeconds(consecutiveFailures: number): number {\n\tif (consecutiveFailures <= 1) return 0;\n\tconst exponent = Math.min(consecutiveFailures - 1, 8);\n\tconst base = Math.min(PEER_BACKOFF_BASE_S * 2 ** (exponent - 1), PEER_BACKOFF_MAX_S);\n\t// Add 50% jitter: base * [0.5, 1.0)\n\treturn base * (0.5 + Math.random() * 0.5);\n}\n\n/** Check if a peer should be skipped due to repeated connectivity failures. */\nexport function shouldSkipOfflinePeer(db: Database, peerDeviceId: string): boolean {\n\tconst failures = consecutiveConnectivityFailures(db, peerDeviceId);\n\tif (failures < 2) return false;\n\tconst backoffS = peerBackoffSeconds(failures);\n\tif (backoffS <= 0) return false;\n\n\tconst d = drizzle(db, { schema });\n\tconst row = d\n\t\t.select({ started_at: schema.syncAttempts.started_at })\n\t\t.from(schema.syncAttempts)\n\t\t.where(eq(schema.syncAttempts.peer_device_id, peerDeviceId))\n\t\t.orderBy(desc(schema.syncAttempts.started_at))\n\t\t.limit(1)\n\t\t.get();\n\n\tif (!row?.started_at) return false;\n\ttry {\n\t\tconst lastAttempt = new Date(row.started_at).getTime();\n\t\tconst now = Date.now();\n\t\tconst elapsedS = (now - lastAttempt) / 1000;\n\t\treturn elapsedS < backoffS;\n\t} catch {\n\t\treturn false;\n\t}\n}\n","import { type ClientRequest, type IncomingMessage, request } from \"node:http\";\nimport { performance } from \"node:perf_hooks\";\nimport type { Duplex } from \"node:stream\";\nimport { finished } from \"node:stream/promises\";\nimport { adoptPeerHttpConnection, PeerHttpLifetime } from \"./peer-http-client-lifecycle.js\";\nimport { preparePeerHttpRequest, readPeerHttpBodyLength } from \"./peer-http-headers.js\";\nimport { PeerHttpExchangeError } from \"./peer-http-policy.js\";\nimport { PeerHttpWireAudit } from \"./peer-http-wire-audit.js\";\nimport { RelayNoiseDuplex } from \"./relay-noise-stream.js\";\nimport type { RequestJsonExecutor } from \"./sync-http-client.js\";\n\nexport interface OwnedPeerHttpConnection {\n\treadonly duplex: Duplex;\n\t/** Resolves only after clean underlying raw I/O AND resource disposal. */\n\treadonly completion: Promise<void>;\n\t/** Idempotently owns the entire channel and settles within the cleanup grace. */\n\tdispose(error: Error): Promise<void>;\n}\n\nexport interface PeerHttpConnectionFactory {\n\topen(options: { signal: AbortSignal; deadlineMs: number }): Promise<OwnedPeerHttpConnection>;\n}\n\ntype Owner = ReturnType<typeof adoptPeerHttpConnection>;\ntype ValidOwner = Extract<Owner, { valid: true }>;\ntype Prepared = ReturnType<typeof preparePeerHttpRequest>;\n\nfunction requireFreshConnection(duplex: Duplex): void {\n\tif (\n\t\t!(duplex instanceof RelayNoiseDuplex) ||\n\t\tduplex.destroyed ||\n\t\tduplex.errored ||\n\t\tduplex.readableEnded ||\n\t\tduplex.writableEnded ||\n\t\tduplex.readableLength !== 0 ||\n\t\tduplex.writableLength !== 0 ||\n\t\tduplex.readableFlowing === true\n\t)\n\t\tthrow new PeerHttpExchangeError(\"transport\");\n}\n\nfunction decodeResponse(bytes: Buffer): Record<string, unknown> | null {\n\tif (bytes.length === 0) return null;\n\ttry {\n\t\tconst value: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n\t\tif (typeof value === \"object\" && value !== null && !Array.isArray(value))\n\t\t\treturn value as Record<string, unknown>;\n\t\treturn { error: \"unexpected_json_type\" };\n\t} catch {\n\t\treturn { error: \"non_json_response\" };\n\t}\n}\n\nfunction receiveResponse(\n\tresponse: IncomingMessage,\n\taudit: PeerHttpWireAudit,\n\tlifetime: PeerHttpLifetime,\n\tmaxBodyBytes: number,\n) {\n\treturn new Promise<{ status: number; bytes: Buffer }>((resolve, reject) => {\n\t\tresponse.once(\"error\", () => reject(lifetime.fail(\"transport\")));\n\t\tresponse.once(\"aborted\", () => reject(lifetime.fail(\"framing\")));\n\t\ttry {\n\t\t\tconst status = response.statusCode;\n\t\t\tif (response.httpVersion !== \"1.1\" || status === undefined || status < 200 || status > 599)\n\t\t\t\tthrow new PeerHttpExchangeError(\"framing\");\n\t\t\tconst length = readPeerHttpBodyLength(response.rawHeaders, {\n\t\t\t\tdirection: \"response\",\n\t\t\t\tmaxBodyBytes,\n\t\t\t});\n\t\t\taudit.expectBodyBytes(length);\n\t\t\tconst bytes = Buffer.alloc(length);\n\t\t\tlet received = 0;\n\t\t\tresponse.on(\"data\", (chunk: Buffer) => {\n\t\t\t\tif (!Buffer.isBuffer(chunk) || received + chunk.length > length) {\n\t\t\t\t\treject(lifetime.fail(\"framing\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tchunk.copy(bytes, received);\n\t\t\t\treceived += chunk.length;\n\t\t\t});\n\t\t\tresponse.once(\"end\", () => {\n\t\t\t\tif (!response.complete || received !== length || response.rawTrailers.length !== 0)\n\t\t\t\t\treject(lifetime.fail(\"framing\"));\n\t\t\t\telse resolve({ status, bytes });\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst code = error instanceof PeerHttpExchangeError ? error.code : \"framing\";\n\t\t\treject(lifetime.fail(code));\n\t\t}\n\t});\n}\n\nasync function writeRequest(\n\treq: ClientRequest,\n\tbody: Buffer,\n\tlifetime: PeerHttpLifetime,\n): Promise<void> {\n\tfor (let offset = 0; offset < body.length; offset += 16384) {\n\t\tlet drained = false;\n\t\tlet written = false;\n\t\tlet resume = (): void => {};\n\t\tconst onDrain = (): void => {\n\t\t\tdrained = true;\n\t\t\tresume();\n\t\t};\n\t\ttry {\n\t\t\tawait lifetime.wait(\n\t\t\t\tnew Promise<void>((resolve, reject) => {\n\t\t\t\t\tresume = () => {\n\t\t\t\t\t\tif (drained && written) resolve();\n\t\t\t\t\t};\n\t\t\t\t\treq.once(\"drain\", onDrain);\n\t\t\t\t\tdrained = req.write(body.subarray(offset, offset + 16384), (error) => {\n\t\t\t\t\t\tif (error) reject(lifetime.fail(\"transport\"));\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\twritten = true;\n\t\t\t\t\t\t\tresume();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tresume();\n\t\t\t\t}),\n\t\t\t);\n\t\t} finally {\n\t\t\treq.off(\"drain\", onDrain);\n\t\t}\n\t}\n\tawait lifetime.wait(new Promise<void>((resolve) => req.end(resolve)));\n}\n\nfunction observePlaintext(duplex: Duplex, lifetime: PeerHttpLifetime) {\n\t// Native headers classify a declared excess before the audit binds the validated length.\n\tconst audit = new PeerHttpWireAudit({ direction: \"response\" });\n\tconst eof = Promise.withResolvers<void>();\n\tvoid eof.promise.catch(() => {});\n\tconst data = (chunk: unknown): void => {\n\t\ttry {\n\t\t\taudit.observe(chunk);\n\t\t} catch {\n\t\t\tlifetime.fail(\"framing\");\n\t\t}\n\t};\n\tconst end = (): void => {\n\t\ttry {\n\t\t\taudit.finish();\n\t\t\teof.resolve();\n\t\t} catch {\n\t\t\teof.reject(lifetime.fail(\"framing\"));\n\t\t}\n\t};\n\tconst error = (): void => {\n\t\tlifetime.fail(\"transport\");\n\t};\n\tduplex.on(\"data\", data);\n\tduplex.once(\"end\", end);\n\tduplex.on(\"error\", error);\n\treturn {\n\t\taudit,\n\t\teof: eof.promise,\n\t\tremove: () => {\n\t\t\tduplex.off(\"data\", data);\n\t\t\tduplex.off(\"end\", end);\n\t\t\tduplex.off(\"error\", error);\n\t\t},\n\t};\n}\n\nfunction startRequest(\n\tduplex: Duplex,\n\tprepared: Prepared,\n\taudit: PeerHttpWireAudit,\n\tlifetime: PeerHttpLifetime,\n) {\n\tconst response = Promise.withResolvers<{ status: number; bytes: Buffer }>();\n\tvoid response.promise.catch(() => {});\n\tconst req = request(\n\t\t{\n\t\t\tmethod: prepared.method,\n\t\t\thostname: prepared.hostname,\n\t\t\tpath: prepared.path,\n\t\t\theaders: prepared.headers,\n\t\t\tsetHost: false,\n\t\t\tmaxHeaderSize: 16384,\n\t\t\tcreateConnection: () => duplex,\n\t\t\tlookup: () => {\n\t\t\t\tthrow new PeerHttpExchangeError(\"transport\");\n\t\t\t},\n\t\t\tsignal: lifetime.controller.signal,\n\t\t},\n\t\t(incoming) => {\n\t\t\tvoid receiveResponse(incoming, audit, lifetime, prepared.maxResponseBytes).then((result) => {\n\t\t\t\ttry {\n\t\t\t\t\tduplex.end();\n\t\t\t\t\tresponse.resolve(result);\n\t\t\t\t} catch {\n\t\t\t\t\tresponse.reject(lifetime.fail(\"transport\"));\n\t\t\t\t}\n\t\t\t}, response.reject);\n\t\t},\n\t);\n\t// Preserve every field for policy validation. The independent byte cap still applies.\n\treq.maxHeadersCount = 0;\n\treq.once(\"socket\", () => duplex.resume());\n\treq.on(\"error\", () => lifetime.fail(\"transport\"));\n\tfor (const event of [\"information\", \"continue\", \"upgrade\", \"connect\"])\n\t\treq.on(event, () => lifetime.fail(\"framing\"));\n\treturn { req, response: response.promise };\n}\n\nasync function exchange(owner: ValidOwner, prepared: Prepared, lifetime: PeerHttpLifetime) {\n\trequireFreshConnection(owner.duplex);\n\t// Node installs its parser on the next tick. Resume only after its socket event.\n\towner.duplex.pause();\n\tconst observer = observePlaintext(owner.duplex, lifetime);\n\tconst plaintextCompletion = finished(owner.duplex, { cleanup: true });\n\tvoid plaintextCompletion.catch(() => {});\n\ttry {\n\t\tconst { req, response } = startRequest(owner.duplex, prepared, observer.audit, lifetime);\n\t\tconst [result] = await lifetime.wait(\n\t\t\tPromise.all([\n\t\t\t\tresponse,\n\t\t\t\tobserver.eof,\n\t\t\t\tplaintextCompletion,\n\t\t\t\towner.completion,\n\t\t\t\twriteRequest(req, prepared.body, lifetime),\n\t\t\t]),\n\t\t);\n\t\tlifetime.check();\n\t\tconst payload = decodeResponse(result.bytes);\n\t\tlifetime.check();\n\t\treturn [result.status, payload] as [number, Record<string, unknown> | null];\n\t} finally {\n\t\tobserver.remove();\n\t}\n}\n\ninterface ExecutorOptions {\n\tfactory: PeerHttpConnectionFactory;\n\tsignal?: AbortSignal;\n\tdeadlineMs?: number;\n}\n\nfunction captureExecutorOptions(options: ExecutorOptions) {\n\ttry {\n\t\tconst { factory, signal, deadlineMs } = options;\n\t\tconst open = factory.open.bind(factory);\n\t\tif (\n\t\t\t(deadlineMs !== undefined && !Number.isFinite(deadlineMs)) ||\n\t\t\t(signal !== undefined && !(signal instanceof AbortSignal))\n\t\t)\n\t\t\tthrow new Error();\n\t\treturn { open, signal, deadlineMs };\n\t} catch {\n\t\tthrow new PeerHttpExchangeError(\"framing\");\n\t}\n}\n\n/** Inert injected executor. One fresh owned Noise connection per call, with no retry or fallback. */\nexport function createPeerHttpExecutor(options: ExecutorOptions): RequestJsonExecutor {\n\tconst { open, signal, deadlineMs } = captureExecutorOptions(options);\n\treturn async (method, url, requestOptions = {}) => {\n\t\tconst startedAt = performance.now();\n\t\tconst prepared = preparePeerHttpRequest(method, url, requestOptions);\n\t\tconst deadline = Math.min(startedAt + prepared.lifetimeMs, deadlineMs ?? Infinity);\n\t\tconst lifetime = new PeerHttpLifetime(deadline, signal);\n\t\tlet owner: Owner | undefined;\n\t\ttry {\n\t\t\tlifetime.check();\n\t\t\tconst opening = Promise.resolve(\n\t\t\t\topen({ signal: lifetime.controller.signal, deadlineMs: deadline }),\n\t\t\t).then((connection) => {\n\t\t\t\towner = adoptPeerHttpConnection(connection);\n\t\t\t\tif (owner.valid) void owner.completion.catch(() => lifetime.fail(\"transport\"));\n\t\t\t\tif (lifetime.failed) void owner.dispose(lifetime.fail(\"transport\")).catch(() => {});\n\t\t\t\treturn owner;\n\t\t\t});\n\t\t\tconst acquired = await lifetime.wait(opening);\n\t\t\tif (!acquired.valid) throw lifetime.fail(\"transport\");\n\t\t\treturn await exchange(acquired, prepared, lifetime);\n\t\t} catch {\n\t\t\tconst failure = lifetime.fail(\"transport\");\n\t\t\tif (owner) await owner.dispose(failure);\n\t\t\tthrow failure;\n\t\t} finally {\n\t\t\tlifetime.close();\n\t\t}\n\t};\n}\n","import { and, eq } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport type { Database } from \"./db.js\";\nimport * as schema from \"./schema.js\";\nimport {\n\ttype CachedScopeAuthorization,\n\tgetEffectiveCachedScopeAuthorization,\n} from \"./scope-membership-cache.js\";\nimport { isScopedSyncCapability, type SyncCapability } from \"./sync-capability.js\";\nimport {\n\tDEFAULT_SYNC_SCOPE_ID,\n\tgetReplicationCursor,\n\tgetSyncResetState,\n\tSCOPED_NULL_BASELINE_BOOTSTRAP_CURSOR_MARKER,\n} from \"./sync-replication.js\";\n\nexport const SYNC_SCOPE_QUERY_PARAM = \"scope_id\";\n\n// An absent signing key must not turn into an unbound managed-cache lookup.\nfunction scopeSigningKey(publicKey: string | null | undefined): string {\n\treturn publicKey ?? \"\";\n}\n\nexport type SyncScopeRequestMode = \"legacy\" | \"scoped\";\nexport type SyncScopeResetReason =\n\t| \"missing_scope\"\n\t| \"unsupported_scope\"\n\t| \"stale_epoch\"\n\t| \"scope_inactive\";\n\nexport interface SyncScopeRequestOk {\n\tok: true;\n\tmode: SyncScopeRequestMode;\n\tscope_id: string | null;\n}\n\nexport interface SyncScopeRequestError {\n\tok: false;\n\treason: SyncScopeResetReason;\n}\n\nexport type SyncScopeRequest = SyncScopeRequestOk | SyncScopeRequestError;\n\nexport interface SyncResetBoundaryShape {\n\tgeneration: number;\n\tsnapshot_id: string;\n\tbaseline_cursor: string | null;\n\tretained_floor_cursor: string | null;\n}\n\n/**\n * Parse a sync scope request and validate it against caller authorization.\n *\n * Legacy callers (`negotiatedCapability !== \"scoped\"`) MUST NOT pass a\n * scope_id; doing so is rejected as `unsupported_scope` so the wire format\n * stays predictable when the lower-ranked side cannot interpret per-scope\n * responses anyway.\n *\n * Scoped callers (`negotiatedCapability === \"scoped\"`) may pass a scope_id.\n * The server verifies both the local device and the calling peer are active,\n * current-epoch members of the requested scope before accepting. Failed\n * authorization maps to wire\n * reasons that the client can act on:\n * - `missing_scope`: scope unknown, inactive, or caller is not a member.\n * - `stale_epoch`: caller membership exists but epoch is behind authority.\n * - `scope_inactive`: scope membership was revoked or scope is closed.\n *\n * Callers that pass no scope_id continue to be served via the legacy default\n * scope path regardless of capability.\n */\nexport function parseSyncScopeRequest(\n\tvalue: unknown,\n\tprovided: boolean,\n\tcontext?: {\n\t\tdb?: Database;\n\t\tlocalDeviceId?: string | null;\n\t\tlocalSigningPublicKey?: string | null;\n\t\tnegotiatedCapability?: SyncCapability;\n\t\tpeerDeviceId?: string | null;\n\t\tauthenticatedPeerSigningKey?: string | null;\n\t},\n): SyncScopeRequest {\n\tif (!provided) {\n\t\treturn { ok: true, mode: \"legacy\", scope_id: null };\n\t}\n\n\tconst scopeId = typeof value === \"string\" ? value.trim() : \"\";\n\tif (!scopeId) {\n\t\treturn { ok: false, reason: \"missing_scope\" };\n\t}\n\n\tconst negotiated = context?.negotiatedCapability;\n\tif (!negotiated || !isScopedSyncCapability(negotiated)) {\n\t\t// Caller is on the legacy default-scope wire format. Refuse the\n\t\t// scope_id rather than silently downgrading: the response shape\n\t\t// will not carry the per-scope boundary the caller expects.\n\t\treturn { ok: false, reason: \"unsupported_scope\" };\n\t}\n\n\tconst db = context.db;\n\tconst localDeviceId = context.localDeviceId?.trim();\n\tconst peerDeviceId = context.peerDeviceId?.trim();\n\tif (!db || !localDeviceId || !peerDeviceId) {\n\t\t// Caller advertised scoped capability but the route did not thread\n\t\t// the authentication context through. Fail closed.\n\t\treturn { ok: false, reason: \"missing_scope\" };\n\t}\n\n\tconst localAuthorization = getEffectiveCachedScopeAuthorization(db, {\n\t\tdeviceId: localDeviceId,\n\t\tscopeId,\n\t\texpectedPublicKey: context.localSigningPublicKey ?? \"\",\n\t});\n\tconst localErrorReason = scopeAuthorizationFailureReason(localAuthorization);\n\tif (localErrorReason) {\n\t\treturn { ok: false, reason: localErrorReason };\n\t}\n\n\tconst authorization = getEffectiveCachedScopeAuthorization(db, {\n\t\tdeviceId: peerDeviceId,\n\t\tscopeId,\n\t\texpectedPublicKey: context.authenticatedPeerSigningKey ?? \"\",\n\t});\n\tconst errorReason = scopeAuthorizationFailureReason(authorization);\n\tif (errorReason) {\n\t\treturn { ok: false, reason: errorReason };\n\t}\n\n\treturn { ok: true, mode: \"scoped\", scope_id: scopeId };\n}\n\n/**\n * Map a cached scope authorization result to a wire reset reason, or null\n * when the caller is fully authorized for the scope.\n */\nexport function scopeAuthorizationFailureReason(\n\tauthorization: CachedScopeAuthorization,\n): SyncScopeResetReason | null {\n\tif (authorization.scope?.authority_type === \"local\") return \"missing_scope\";\n\tif (authorization.authorized) return null;\n\n\tswitch (authorization.state) {\n\t\tcase \"stale_epoch\":\n\t\t\treturn \"stale_epoch\";\n\t\tcase \"revoked\":\n\t\tcase \"scope_inactive\":\n\t\t\treturn \"scope_inactive\";\n\t\tdefault:\n\t\t\treturn \"missing_scope\";\n\t}\n}\n\nexport function addSyncScopeToBoundary<T extends SyncResetBoundaryShape>(\n\tboundary: T,\n\tscopeId: string | null,\n): T & { scope_id: string | null } {\n\treturn { ...boundary, scope_id: scopeId };\n}\n\nexport function syncScopeResetRequiredPayload(\n\tboundary: SyncResetBoundaryShape,\n\treason: SyncScopeResetReason,\n\tsyncCapability: SyncCapability,\n\tscopeId?: string | null,\n): SyncResetBoundaryShape & {\n\terror: \"reset_required\";\n\treset_required: true;\n\tsync_capability: SyncCapability;\n\treason: SyncScopeResetReason;\n\tscope_id: string | null;\n} {\n\treturn {\n\t\terror: \"reset_required\",\n\t\treset_required: true,\n\t\tsync_capability: syncCapability,\n\t\treason,\n\t\t...addSyncScopeToBoundary(boundary, scopeId ?? null),\n\t};\n}\n\n/**\n * Authorized-scope entry advertised on /v1/status when both peers negotiate\n * the `scoped` capability. Each entry carries the per-scope reset boundary\n * (`sync_reset_state_v2` row) so the client can immediately request that\n * scope's snapshot or incremental ops without an extra round trip.\n */\nexport interface AuthorizedScopeEntry {\n\tscope_id: string;\n\tlabel: string;\n\tauthority_type: string;\n\tmembership_epoch: number;\n\tsync_reset: SyncResetBoundaryShape & { scope_id: string | null };\n\t/**\n\t * The `created_at|op_id` cursor of the last op this device applied from the\n\t * calling peer in this Space, or null. Only the authenticated peer's own\n\t * cursor is reported. A peer that pushes can start after it.\n\t */\n\tapplied_cursor?: string | null;\n}\n\n/**\n * Enumerate scopes the calling peer is authorized to sync with the local\n * device, suitable for advertising on /v1/status under scoped capability.\n *\n * Inclusion rule: a scope is returned when\n * - it exists in `replication_scopes` with status `active`, and\n * - both the local device and the peer device have active membership rows\n * in `scope_memberships`, and\n * - the scope's `authority_type` is not `local`.\n *\n * The legacy `local-default` scope is intentionally excluded. Scoped peers\n * still run the legacy default-scope path alongside per-scope sync to handle\n * pre-Spaces data, so listing it here would duplicate work and require new\n * code paths in the loaders to emit \"explicit\" default-scope rows.\n *\n * The returned `sync_reset` value is the per-scope boundary; calling\n * `getSyncResetState(db, scope_id)` lazily creates a row if one does not\n * exist yet so first-time scopes get a stable generation/snapshot_id.\n */\nexport function listAuthorizedScopesForPeer(\n\tdb: Database,\n\toptions: {\n\t\tlocalDeviceId: string;\n\t\tpeerDeviceId: string;\n\t\tlocalSigningPublicKey?: string | null;\n\t\tauthenticatedPeerSigningKey?: string | null;\n\t\tscopeId?: string;\n\t},\n): AuthorizedScopeEntry[] {\n\tconst memberships = listAuthorizedScopeMembershipsForPeer(db, options).filter(\n\t\t(scope) => options.scopeId === undefined || scope.scope_id === options.scopeId,\n\t);\n\treturn memberships.map((scope) => {\n\t\tconst reset = getSyncResetState(db, scope.scope_id);\n\t\tconst [appliedCursor] = getReplicationCursor(db, options.peerDeviceId, scope.scope_id);\n\t\treturn {\n\t\t\t...scope,\n\t\t\tapplied_cursor: appliedCursor,\n\t\t\tsync_reset: {\n\t\t\t\tscope_id: scope.scope_id,\n\t\t\t\tgeneration: reset.generation,\n\t\t\t\tsnapshot_id: reset.snapshot_id,\n\t\t\t\tbaseline_cursor: reset.baseline_cursor,\n\t\t\t\tretained_floor_cursor: reset.retained_floor_cursor,\n\t\t\t},\n\t\t};\n\t});\n}\n\n// Diagnostics need membership and cursor reads, not creation of reset boundaries.\nfunction listAuthorizedScopeMembershipsForPeer(\n\tdb: Database,\n\toptions: Parameters<typeof listAuthorizedScopesForPeer>[1],\n): Omit<AuthorizedScopeEntry, \"sync_reset\">[] {\n\tconst localDeviceId = options.localDeviceId.trim();\n\tconst peerDeviceId = options.peerDeviceId.trim();\n\tif (!localDeviceId || !peerDeviceId || localDeviceId === peerDeviceId) {\n\t\treturn [];\n\t}\n\n\tconst d = drizzle(db, { schema });\n\tconst localMemberships = d\n\t\t.select({\n\t\t\tscope_id: schema.scopeMemberships.scope_id,\n\t\t\tmembership_epoch: schema.scopeMemberships.membership_epoch,\n\t\t})\n\t\t.from(schema.scopeMemberships)\n\t\t.where(\n\t\t\tand(\n\t\t\t\teq(schema.scopeMemberships.device_id, localDeviceId),\n\t\t\t\teq(schema.scopeMemberships.status, \"active\"),\n\t\t\t),\n\t\t)\n\t\t.all();\n\n\tif (localMemberships.length === 0) return [];\n\n\tconst entries: Omit<AuthorizedScopeEntry, \"sync_reset\">[] = [];\n\tfor (const local of localMemberships) {\n\t\tif (!local.scope_id || local.scope_id === DEFAULT_SYNC_SCOPE_ID) continue;\n\t\tconst localAuth = getEffectiveCachedScopeAuthorization(db, {\n\t\t\tdeviceId: localDeviceId,\n\t\t\tscopeId: local.scope_id,\n\t\t\texpectedPublicKey: scopeSigningKey(options.localSigningPublicKey),\n\t\t});\n\t\tif (!localAuth.authorized || localAuth.scope?.authority_type === \"local\") continue;\n\n\t\t// Peer must also be an active member of the same scope, at the same\n\t\t// or higher membership_epoch as the local row, before we advertise.\n\t\tconst peerAuth = getEffectiveCachedScopeAuthorization(db, {\n\t\t\tdeviceId: peerDeviceId,\n\t\t\tscopeId: local.scope_id,\n\t\t\texpectedPublicKey: scopeSigningKey(options.authenticatedPeerSigningKey),\n\t\t});\n\t\tif (!peerAuth.authorized || !peerAuth.scope || peerAuth.scope.status !== \"active\") continue;\n\n\t\tentries.push({\n\t\t\tscope_id: local.scope_id,\n\t\t\tlabel: peerAuth.scope.label,\n\t\t\tauthority_type: peerAuth.scope.authority_type,\n\t\t\tmembership_epoch: Number(peerAuth.scope.membership_epoch ?? local.membership_epoch ?? 0),\n\t\t});\n\t}\n\n\tentries.sort((a, b) => a.scope_id.localeCompare(b.scope_id));\n\treturn entries;\n}\n\n/**\n * Per-Space sync state for a given peer, suitable for both the CLI status\n * display and the `/api/sync/status` / `/api/sync/peers` viewer payload.\n *\n * Renders the intersection of local + peer scope memberships against the\n * per-scope cursor state stored in `replication_cursors_v2`. Consumers use\n * this surface to show \"synced / pending\" per Space instead of the legacy\n * peer-level `last_sync=ok`, which is the diagnostic gap that hid the\n * codemem-ruu6 regression while ~18k scoped rows silently failed to\n * replicate.\n *\n * Returns an empty array when local device identity has not yet been\n * initialized or when there is no membership overlap.\n */\nexport interface PerPeerScopeSyncEntry {\n\tscope_id: string;\n\tlabel: string;\n\tauthority_type: string;\n\tmembership_epoch: number;\n\tlast_applied_cursor: string | null;\n\tlast_acked_cursor: string | null;\n\tbootstrapped: boolean;\n}\n\nexport function listPerPeerScopeSyncState(\n\tdb: Database,\n\toptions: {\n\t\tlocalDeviceId: string | null;\n\t\tpeerDeviceId: string;\n\t\tlocalSigningPublicKey?: string | null;\n\t\tauthenticatedPeerSigningKey?: string | null;\n\t},\n): PerPeerScopeSyncEntry[] {\n\tconst localDeviceId = options.localDeviceId?.trim() ?? \"\";\n\tconst peerDeviceId = options.peerDeviceId.trim();\n\tif (!localDeviceId || !peerDeviceId) return [];\n\tconst scopes = listAuthorizedScopeMembershipsForPeer(db, {\n\t\t...options,\n\t\tlocalDeviceId,\n\t\tpeerDeviceId,\n\t});\n\tconst readCursor = db.prepare(\n\t\t`SELECT last_applied_cursor, last_acked_cursor FROM replication_cursors_v2\n\t\t WHERE peer_device_id = ? AND scope_id = ?`,\n\t);\n\treturn scopes.map((scope) => {\n\t\tconst cursor = readCursor.get(peerDeviceId, scope.scope_id) as\n\t\t\t| { last_applied_cursor: string | null; last_acked_cursor: string | null }\n\t\t\t| undefined;\n\t\tconst lastApplied = cursor?.last_applied_cursor ?? null;\n\t\tconst lastAcked = cursor?.last_acked_cursor ?? null;\n\t\tconst hasNullBaselineBootstrapMarker =\n\t\t\tlastAcked === SCOPED_NULL_BASELINE_BOOTSTRAP_CURSOR_MARKER;\n\t\treturn {\n\t\t\tscope_id: scope.scope_id,\n\t\t\tlabel: scope.label,\n\t\t\tauthority_type: scope.authority_type,\n\t\t\tmembership_epoch: scope.membership_epoch,\n\t\t\tlast_applied_cursor: lastApplied,\n\t\t\tlast_acked_cursor: hasNullBaselineBootstrapMarker ? null : lastAcked,\n\t\t\tbootstrapped: lastApplied != null || hasNullBaselineBootstrapMarker,\n\t\t};\n\t});\n}\n","import { performance } from \"node:perf_hooks\";\nimport type { Database } from \"./db.js\";\nimport { createPeerHttpExecutor, type PeerHttpConnectionFactory } from \"./peer-http-client.js\";\nimport { adoptPeerHttpConnection } from \"./peer-http-client-lifecycle.js\";\nimport { parseRelayEd25519PublicKey } from \"./relay-ed25519.js\";\nimport type { RelayFailureReason } from \"./relay-failure-reason.js\";\nimport { readAuthenticatedRelayNoisePeerPin } from \"./relay-noise.js\";\nimport type { SecretScanner } from \"./secret-scanner.js\";\nimport { buildDirectPeerAuthHeaders } from \"./sync-auth.js\";\nimport {\n\tLOCAL_SYNC_FEATURES,\n\tSYNC_CAPABILITY_HEADER,\n\tSYNC_FEATURES_HEADER,\n\tsupportsSyncFeature,\n} from \"./sync-capability.js\";\nimport {\n\tclearSyncChannelProgress,\n\tgetSyncChannelProgress,\n\thasCompletedSyncChannelBoundary,\n\ttype SyncChannelBoundary,\n\tsaveSyncChannelCompletedBoundary,\n\tsaveSyncChannelOutboundAck,\n} from \"./sync-channel-progress.js\";\nimport type { RequestJsonExecutor } from \"./sync-http-client.js\";\nimport { ensureDeviceIdentity, fingerprintPublicKey } from \"./sync-identity.js\";\nimport { type SyncScopeResult, syncScopedPeerPull } from \"./sync-pass.js\";\nimport { filterReplicationOpsForSyncWithStatus } from \"./sync-replication.js\";\nimport { parseSyncScopeRequest } from \"./sync-scope-protocol.js\";\nimport {\n\trecordSyncTransferObservation,\n\trecordSyncTransferReceipts,\n} from \"./sync-transfer-activity.js\";\nimport type { ReplicationOp } from \"./types.js\";\n\nconst MAX_BODY_BYTES = 1_048_576;\nexport interface ScopedChannelSyncOptions {\n\tdb: Database;\n\tpeerDeviceId: string;\n\tscopeId: string;\n\tlogicalOrigin: string;\n\t/** Relay factories report their first route failure, which the result records locally. */\n\tfactory: PeerHttpConnectionFactory & { failureReason?: () => RelayFailureReason | undefined };\n\tkeysDir?: string;\n\tdbPath?: string;\n\tscanner?: SecretScanner;\n\tlimit?: number;\n\tsignal?: AbortSignal;\n\tdeadlineMs?: number;\n}\ntype Identity = { device_id: string; public_key: string; fingerprint: string };\ntype Peer = { public_key: string; pinned_fingerprint: string };\ntype Scope = Parameters<typeof syncScopedPeerPull>[1][\"scope\"];\ntype Context = ReturnType<typeof captureContext>;\n\nfunction canonicalKey(key: string): string {\n\treturn `ssh-ed25519 ${Buffer.from(parseRelayEd25519PublicKey(key).wireKey).toString(\"base64\")}`;\n}\n\nfunction currentIdentity(db: Database): Identity {\n\tconst row = db\n\t\t.prepare(\"SELECT device_id, public_key, fingerprint FROM sync_device LIMIT 1\")\n\t\t.get() as Identity | undefined;\n\tif (!row?.device_id || fingerprintPublicKey(row.public_key) !== row.fingerprint)\n\t\tthrow new Error(\"channel identity invalid\");\n\tcanonicalKey(row.public_key);\n\treturn row;\n}\n\nfunction currentPeer(db: Database, peerDeviceId: string): Peer {\n\tconst row = db\n\t\t.prepare(\"SELECT public_key, pinned_fingerprint FROM sync_peers WHERE peer_device_id = ?\")\n\t\t.get(peerDeviceId) as Peer | undefined;\n\tif (\n\t\t!row?.public_key ||\n\t\t!row.pinned_fingerprint ||\n\t\tfingerprintPublicKey(row.public_key) !== row.pinned_fingerprint\n\t)\n\t\tthrow new Error(\"channel peer trust invalid\");\n\tcanonicalKey(row.public_key);\n\treturn row;\n}\n\nfunction captureContext(input: ScopedChannelSyncOptions) {\n\tconst passDeadline = performance.now() + 60_000;\n\tconst options = { ...input };\n\tconst origin = new URL(options.logicalOrigin);\n\tif (![\"http:\", \"https:\"].includes(origin.protocol) || origin.origin !== options.logicalOrigin)\n\t\tthrow new Error(\"channel origin invalid\");\n\tif (!options.scopeId || options.scopeId.trim() !== options.scopeId)\n\t\tthrow new Error(\"channel scope invalid\");\n\tif (options.limit !== undefined && (!Number.isInteger(options.limit) || options.limit < 1))\n\t\tthrow new Error(\"channel limit invalid\");\n\tif (options.deadlineMs !== undefined && !Number.isFinite(options.deadlineMs))\n\t\tthrow new Error(\"channel deadline invalid\");\n\tensureDeviceIdentity(options.db, { keysDir: options.keysDir });\n\treturn {\n\t\t...options,\n\t\tdeadlineMs: Math.min(options.deadlineMs ?? passDeadline, passDeadline),\n\t\tlimit: Math.min(options.limit ?? 500, 1000),\n\t\tlocal: currentIdentity(options.db),\n\t\tpeer: currentPeer(options.db, options.peerDeviceId),\n\t\topen: options.factory.open.bind(options.factory),\n\t};\n}\n\nfunction checkAuthorization(context: Context): void {\n\tconst local = currentIdentity(context.db);\n\tconst peer = currentPeer(context.db, context.peerDeviceId);\n\tif (\n\t\tlocal.device_id !== context.local.device_id ||\n\t\tlocal.public_key !== context.local.public_key ||\n\t\tpeer.public_key !== context.peer.public_key ||\n\t\tpeer.pinned_fingerprint !== context.peer.pinned_fingerprint\n\t)\n\t\tthrow new Error(\"channel trust changed\");\n\tconst admission = parseSyncScopeRequest(context.scopeId, true, {\n\t\tdb: context.db,\n\t\tlocalDeviceId: local.device_id,\n\t\tlocalSigningPublicKey: local.public_key,\n\t\tpeerDeviceId: context.peerDeviceId,\n\t\tauthenticatedPeerSigningKey: peer.public_key,\n\t\tnegotiatedCapability: \"scoped\",\n\t});\n\tif (!admission.ok) throw new Error(\"channel scope authorization denied\");\n}\n\nfunction validatePullPayload(context: Context, url: URL, payload: Record<string, unknown>): void {\n\tif (payload.scope_id !== context.scopeId) throw new Error(\"channel response scope invalid\");\n\tif (url.pathname === \"/v1/ops\") {\n\t\tif (!Array.isArray(payload.ops)) throw new Error(\"channel ops invalid\");\n\t\tfor (const raw of payload.ops) {\n\t\t\tconst op = raw as Partial<ReplicationOp> | null;\n\t\t\tif (\n\t\t\t\t!op ||\n\t\t\t\top.scope_id !== context.scopeId ||\n\t\t\t\top.device_id !== context.peerDeviceId ||\n\t\t\t\top.clock_device_id !== context.peerDeviceId\n\t\t\t)\n\t\t\t\tthrow new Error(\"channel op source or scope invalid\");\n\t\t}\n\t}\n\tif (url.pathname === \"/v1/snapshot\" && !Array.isArray(payload.items))\n\t\tthrow new Error(\"channel snapshot invalid\");\n}\n\nfunction channelExecutor(context: Context): RequestJsonExecutor {\n\tconst execute = createPeerHttpExecutor({\n\t\tsignal: context.signal,\n\t\tdeadlineMs: context.deadlineMs,\n\t\tfactory: {\n\t\t\topen: async (options) => {\n\t\t\t\tcheckAuthorization(context);\n\t\t\t\tconst connection = await context.open(options);\n\t\t\t\tconst owned = adoptPeerHttpConnection(connection);\n\t\t\t\ttry {\n\t\t\t\t\tcheckAuthorization(context);\n\t\t\t\t\tif (\n\t\t\t\t\t\t!owned.valid ||\n\t\t\t\t\t\treadAuthenticatedRelayNoisePeerPin(owned.duplex) !==\n\t\t\t\t\t\t\tcanonicalKey(context.peer.public_key)\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow new Error(\"channel peer pin mismatch\");\n\t\t\t\t\treturn owned;\n\t\t\t\t} catch {\n\t\t\t\t\tawait owned.dispose(new Error(\"channel trust invalid\"));\n\t\t\t\t\tthrow new Error(\"channel trust invalid\");\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t});\n\treturn async (method, target, options = {}) => {\n\t\tcheckAuthorization(context);\n\t\tconst url = new URL(target);\n\t\tif (url.origin !== context.logicalOrigin) throw new Error(\"channel target invalid\");\n\t\tconst response = await execute(method, target, options);\n\t\tcheckAuthorization(context);\n\t\tconst [status, payload] = response;\n\t\tif (method === \"GET\" && url.pathname !== \"/v1/status\" && status === 200 && payload)\n\t\t\tvalidatePullPayload(context, url, payload);\n\t\tif (status >= 400 && status !== 409 && status !== 413)\n\t\t\tthrow new Error(\"channel request failed\");\n\t\treturn response;\n\t};\n}\n\nfunction signedHeaders(context: Context, method: string, url: string, bodyBytes: Buffer) {\n\treturn {\n\t\t...buildDirectPeerAuthHeaders({\n\t\t\tdeviceId: context.local.device_id,\n\t\t\trecipientId: context.peerDeviceId,\n\t\t\tmethod,\n\t\t\turl,\n\t\t\tbodyBytes,\n\t\t\tkeysDir: context.keysDir,\n\t\t\tdbPath: context.dbPath,\n\t\t}),\n\t\t[SYNC_CAPABILITY_HEADER]: \"scoped\",\n\t\t[SYNC_FEATURES_HEADER]: LOCAL_SYNC_FEATURES.join(\",\"),\n\t};\n}\n\nfunction checkedBoundary(value: unknown, scopeId: string): Scope[\"sync_reset\"] {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value))\n\t\tthrow new Error(\"channel status invalid\");\n\tconst b = value as Scope[\"sync_reset\"];\n\tif (\n\t\tb.scope_id !== scopeId ||\n\t\t!Number.isSafeInteger(b.generation) ||\n\t\tb.generation < 1 ||\n\t\ttypeof b.snapshot_id !== \"string\" ||\n\t\t!b.snapshot_id.trim() ||\n\t\t!(b.baseline_cursor === null || typeof b.baseline_cursor === \"string\") ||\n\t\t!(b.retained_floor_cursor === null || typeof b.retained_floor_cursor === \"string\")\n\t)\n\t\tthrow new Error(\"channel status invalid\");\n\treturn b;\n}\n\nasync function fetchStatus(context: Context, execute: RequestJsonExecutor) {\n\tconst url = `${context.logicalOrigin}/v1/status?${new URLSearchParams({ scope_id: context.scopeId })}`;\n\tconst [status, payload] = await execute(\"GET\", url, {\n\t\theaders: signedHeaders(context, \"GET\", url, Buffer.alloc(0)),\n\t});\n\tif (\n\t\tstatus !== 200 ||\n\t\t!payload ||\n\t\tpayload.device_id !== context.peerDeviceId ||\n\t\tpayload.fingerprint !== context.peer.pinned_fingerprint ||\n\t\tString(payload.protocol_version) !== \"2\" ||\n\t\tpayload.sync_capability !== \"scoped\" ||\n\t\t!Array.isArray(payload.authorized_scopes) ||\n\t\tpayload.authorized_scopes.length !== 1\n\t)\n\t\tthrow new Error(\"channel status invalid\");\n\tconst scope = payload.authorized_scopes[0] as Scope | null;\n\tif (!scope || scope.scope_id !== context.scopeId) throw new Error(\"channel status invalid\");\n\tconst boundary = checkedBoundary(scope.sync_reset, context.scopeId);\n\tconst top = checkedBoundary(payload.sync_reset, context.scopeId);\n\tfor (const key of [\n\t\t\"generation\",\n\t\t\"snapshot_id\",\n\t\t\"baseline_cursor\",\n\t\t\"retained_floor_cursor\",\n\t] as const)\n\t\tif (top[key] !== boundary[key]) throw new Error(\"channel status invalid\");\n\treturn { scope, features: payload.sync_features, appliedCursor: appliedCursor(scope) };\n}\n\n/** The peer's pull cursor for this device, when it reports one in the right shape. */\nfunction appliedCursor(scope: Scope): string | null {\n\tconst value = (scope as { applied_cursor?: unknown }).applied_cursor;\n\tif (typeof value !== \"string\") return null;\n\tconst trimmed = value.trim();\n\tconst separator = trimmed.indexOf(\"|\");\n\treturn separator > 0 && separator < trimmed.length - 1 ? trimmed : null;\n}\n\n/** Cursors order by `created_at` text, then op ID, the same order the push window uses. */\nfunction laterCursor(a: string | null, b: string | null): string | null {\n\tif (!a) return b;\n\tif (!b) return a;\n\tconst [aTime, aOp] = [a.slice(0, a.indexOf(\"|\")), a.slice(a.indexOf(\"|\") + 1)];\n\tconst [bTime, bOp] = [b.slice(0, b.indexOf(\"|\")), b.slice(b.indexOf(\"|\") + 1)];\n\tif (aTime !== bTime) return aTime > bTime ? a : b;\n\treturn aOp >= bOp ? a : b;\n}\n\nfunction loadOutbound(\n\tcontext: Context,\n\tboundary: SyncChannelBoundary,\n\tappliedByPeer: string | null,\n): ReplicationOp[] {\n\tconst progress = getSyncChannelProgress(context.db, context.peerDeviceId, context.scopeId);\n\tif (!hasCompletedSyncChannelBoundary(progress, boundary))\n\t\tthrow new Error(\"channel progress changed\");\n\t// The peer may already hold ops this channel never sent, for example from\n\t// direct sync before relay. Start after whichever position is later.\n\tconst cursor = laterCursor(progress?.last_acked_cursor ?? null, appliedByPeer);\n\tconst separator = cursor?.indexOf(\"|\") ?? -1;\n\tconst timestamp = cursor?.slice(0, separator) ?? \"\";\n\tconst opId = cursor?.slice(separator + 1) ?? \"\";\n\treturn context.db\n\t\t.prepare(`SELECT * FROM replication_ops WHERE device_id = ? AND scope_id = ?\n\t\tAND (? IS NULL OR created_at > ? OR (created_at = ? AND op_id > ?))\n\t\tORDER BY created_at, op_id LIMIT ?`)\n\t\t.all(\n\t\t\tcontext.local.device_id,\n\t\t\tcontext.scopeId,\n\t\t\tcursor,\n\t\t\ttimestamp,\n\t\t\ttimestamp,\n\t\t\topId,\n\t\t\tcontext.limit,\n\t\t) as ReplicationOp[];\n}\n\nfunction pushBody(scopeId: string, ops: ReplicationOp[]): Buffer {\n\treturn Buffer.from(\n\t\tJSON.stringify({\n\t\t\tscope_id: scopeId,\n\t\t\tops,\n\t\t\tsync_capability: \"scoped\",\n\t\t\tsync_features: LOCAL_SYNC_FEATURES,\n\t\t}),\n\t);\n}\n\nfunction planBatches(scopeId: string, ops: ReplicationOp[]): ReplicationOp[][] {\n\tif (ops.length === 0) return [];\n\tif (pushBody(scopeId, ops).length <= MAX_BODY_BYTES) return [ops];\n\tif (ops.length === 1) throw new Error(\"channel operation too large\");\n\tconst middle = Math.floor(ops.length / 2);\n\treturn [\n\t\t...planBatches(scopeId, ops.slice(0, middle)),\n\t\t...planBatches(scopeId, ops.slice(middle)),\n\t];\n}\n\nfunction checkPushReply(payload: Record<string, unknown> | null, scopeId: string): void {\n\tif (\n\t\t!payload ||\n\t\tpayload.scope_id !== scopeId ||\n\t\tpayload.error != null ||\n\t\t(payload.errors !== undefined &&\n\t\t\t(!Array.isArray(payload.errors) || payload.errors.length !== 0)) ||\n\t\t(payload.rejected !== undefined && payload.rejected !== 0) ||\n\t\t(payload.rejections !== undefined &&\n\t\t\t(!Array.isArray(payload.rejections) || payload.rejections.length !== 0))\n\t)\n\t\tthrow new Error(\"channel push rejected\");\n}\n\nasync function pushBatch(\n\tcontext: Context,\n\texecute: RequestJsonExecutor,\n\tops: ReplicationOp[],\n): Promise<void> {\n\tconst url = `${context.logicalOrigin}/v1/ops`;\n\tconst bodyBytes = pushBody(context.scopeId, ops);\n\tconst [status, payload] = await execute(\"POST\", url, {\n\t\tbodyBytes,\n\t\theaders: signedHeaders(context, \"POST\", url, bodyBytes),\n\t});\n\tif (\n\t\tstatus === 413 &&\n\t\t(payload?.error === \"payload_too_large\" || payload?.error === \"too_many_ops\") &&\n\t\tops.length > 1\n\t) {\n\t\tconst middle = Math.floor(ops.length / 2);\n\t\tawait pushBatch(context, execute, ops.slice(0, middle));\n\t\tawait pushBatch(context, execute, ops.slice(middle));\n\t\treturn;\n\t}\n\tif (status !== 200) throw new Error(\"channel push failed\");\n\tcheckPushReply(payload, context.scopeId);\n\tcheckAuthorization(context);\n\tcontext.db.transaction(() => {\n\t\trecordSyncTransferReceipts(\n\t\t\tcontext.db,\n\t\t\tcontext.peerDeviceId,\n\t\t\t\"send\",\n\t\t\tops.map((op) => op.op_id),\n\t\t);\n\t\trecordSyncTransferObservation(context.db, context.peerDeviceId, \"send\");\n\t})();\n}\n\nasync function pushOutbound(\n\tcontext: Context,\n\texecute: RequestJsonExecutor,\n\tfeatures: unknown,\n\tboundary: SyncChannelBoundary,\n\tappliedByPeer: string | null,\n): Promise<number> {\n\tcheckAuthorization(context);\n\tconst window = loadOutbound(context, boundary, appliedByPeer);\n\tconst [ops, cursor] = filterReplicationOpsForSyncWithStatus(\n\t\tcontext.db,\n\t\twindow,\n\t\tcontext.peerDeviceId,\n\t\t{\n\t\t\tlocalDeviceId: context.local.device_id,\n\t\t\tsupportsReassignScope: supportsSyncFeature(features, \"reassign_scope\"),\n\t\t},\n\t);\n\tconst save = (acked: string) =>\n\t\tsaveSyncChannelOutboundAck(context.db, {\n\t\t\tpeerDeviceId: context.peerDeviceId,\n\t\t\tscopeId: context.scopeId,\n\t\t\tboundary,\n\t\t\tcursor: acked,\n\t\t});\n\t// Each confirmed batch saves its own ACK, so a pass that runs out of time keeps\n\t// what the peer already applied instead of resending the whole window next pass.\n\tfor (const batch of planBatches(context.scopeId, ops)) {\n\t\tawait pushBatch(context, execute, batch);\n\t\tcheckAuthorization(context);\n\t\tconst last = batch.at(-1);\n\t\tif (last) save(`${last.created_at}|${last.op_id}`);\n\t}\n\tcheckAuthorization(context);\n\t// The window cursor also covers ops filtered out after the last one sent. An\n\t// empty window means the peer's reported position already covers everything.\n\tconst saved = getSyncChannelProgress(context.db, context.peerDeviceId, context.scopeId);\n\tconst reached = laterCursor(laterCursor(cursor, appliedByPeer), saved?.last_acked_cursor ?? null);\n\t// A peer whose reported position is behind the saved ACK changes nothing.\n\tif (reached && reached !== saved?.last_acked_cursor) save(reached);\n\treturn ops.length;\n}\n\n/** Appends the factory's first relay reason, if any, to the existing generic local error. */\nfunction failedResult(\n\tresult: SyncScopeResult,\n\tfactory: ScopedChannelSyncOptions[\"factory\"],\n\terror: string,\n): SyncScopeResult {\n\tconst reason = factory.failureReason?.();\n\tif (!reason) return { ...result, ok: false, error };\n\treturn { ...result, ok: false, error: `${error}: ${reason}`, relayFailureReason: reason };\n}\n\nfunction failedPullResult(\n\toptions: ScopedChannelSyncOptions,\n\tresult: SyncScopeResult,\n): SyncScopeResult {\n\tconst errorCode =\n\t\tresult.receiveFailureCode ??\n\t\t(result.failureCategory === \"scope\" ? \"scope_rejected\" : \"exchange_failed\");\n\trecordSyncTransferObservation(options.db, options.peerDeviceId, \"receive\", { errorCode });\n\treturn failedResult(result, options.factory, \"channel pull failed\");\n}\n\n/** Internal, opt-in scoped exchange. Never discovers addresses or refreshes authorization. */\nexport async function syncScopedChannelOnce(\n\toptions: ScopedChannelSyncOptions,\n): Promise<SyncScopeResult> {\n\tlet sending = false;\n\tlet result: SyncScopeResult = {\n\t\tscope_id: options.scopeId,\n\t\tok: false,\n\t\topsIn: 0,\n\t\topsOut: 0,\n\t\tbootstrapped: false,\n\t};\n\ttry {\n\t\tconst context = captureContext(options);\n\t\tcheckAuthorization(context);\n\t\tconst execute = channelExecutor(context);\n\t\tconst status = await fetchStatus(context, execute);\n\t\tcheckAuthorization(context);\n\t\tconst progress = getSyncChannelProgress(context.db, context.peerDeviceId, context.scopeId);\n\t\tresult = await syncScopedPeerPull(context.db, {\n\t\t\tpeerDeviceId: context.peerDeviceId,\n\t\t\tbaseUrl: context.logicalOrigin,\n\t\t\tdeviceId: context.local.device_id,\n\t\t\tscope: status.scope,\n\t\t\trequestExecutor: execute,\n\t\t\tkeysDir: context.keysDir,\n\t\t\tdbPath: context.dbPath,\n\t\t\tscanner: context.scanner,\n\t\t\tlimit: context.limit,\n\t\t\tcompletedNullBaseline: hasCompletedSyncChannelBoundary(progress, status.scope.sync_reset),\n\t\t\tsourceDeviceId: context.peerDeviceId,\n\t\t\tvalidateCurrentAuthorization: () => checkAuthorization(context),\n\t\t\tinvalidateCompletedBoundary: () =>\n\t\t\t\tclearSyncChannelProgress(context.db, context.peerDeviceId, context.scopeId),\n\t\t});\n\t\tif (!result.ok) return failedPullResult(options, result);\n\t\t// One Space per pass proves the receive path works, but other scopes stay unretried.\n\t\trecordSyncTransferObservation(context.db, context.peerDeviceId, \"receive\", {\n\t\t\tpreserveScopedError: true,\n\t\t});\n\t\tcheckAuthorization(context);\n\t\tsaveSyncChannelCompletedBoundary(context.db, {\n\t\t\tpeerDeviceId: context.peerDeviceId,\n\t\t\tscopeId: context.scopeId,\n\t\t\tboundary: status.scope.sync_reset,\n\t\t});\n\t\tsending = true;\n\t\tconst opsOut = await pushOutbound(\n\t\t\tcontext,\n\t\t\texecute,\n\t\t\tstatus.features,\n\t\t\tstatus.scope.sync_reset,\n\t\t\tstatus.appliedCursor,\n\t\t);\n\t\treturn { ...result, opsOut };\n\t} catch {\n\t\trecordSyncTransferObservation(options.db, options.peerDeviceId, sending ? \"send\" : \"receive\", {\n\t\t\terrorCode: \"exchange_failed\",\n\t\t});\n\t\treturn failedResult(result, options.factory, \"scoped channel exchange failed\");\n\t}\n}\n","import { performance } from \"node:perf_hooks\";\nimport type { Database } from \"./db.js\";\nimport { isRelayPeerClient, type RelayPeerClient } from \"./relay-peer-client.js\";\nimport { isStableReleaseVersion } from \"./release-discovery.js\";\nimport { supportsSyncFeature } from \"./sync-capability.js\";\nimport { syncScopedChannelOnce } from \"./sync-channel-pass.js\";\nimport { type RequestJsonExecutor, requestJson } from \"./sync-http-client.js\";\nimport {\n\ttype SyncPassOptions,\n\ttype SyncResult,\n\ttype SyncScopeResult,\n\tsyncOnce,\n} from \"./sync-pass.js\";\nimport { recordSyncTransferObservation } from \"./sync-transfer-activity.js\";\n\nexport interface SyncReachabilityOptions {\n\t/** One explicitly authorized Space for relay fallback. Direct sync retains its existing scope behavior. */\n\treadonly scopeId: string;\n\treadonly logicalOrigin: string;\n\treadonly relay?: RelayPeerClient;\n\treadonly signal?: AbortSignal;\n\treadonly deadlineMs?: number;\n}\n\nexport type SyncReachabilityMaintenance = Pick<\n\tSyncReachabilityOptions,\n\t\"relay\" | \"signal\" | \"deadlineMs\"\n>;\n\n/**\n * Per-peer reachability for the sync daemon. The caller owns every relay\n * client's lifecycle and must close the clients during shutdown.\n */\nexport interface SyncPeerReachabilityResolver {\n\t/** This tick's relay route for one peer, or undefined for direct-only sync. */\n\tforPeer(db: Database, peerDeviceId: string): SyncReachabilityOptions | undefined;\n\t/** Relay clients whose registration the daemon maintains once per tick. */\n\tclients(): readonly RelayPeerClient[];\n\t/** Cancels maintenance and every pass this resolver selects. */\n\treadonly signal?: AbortSignal;\n}\n\n/** Reuses the existing reconciliation tick. Maintenance failure never blocks direct sync. */\nexport async function maintainSyncReachability(\n\toptions: SyncReachabilityMaintenance,\n): Promise<void> {\n\tif (!isRelayPeerClient(options.relay)) return;\n\ttry {\n\t\tawait options.relay.maintainRegistration(\n\t\t\toptions.signal ?? new AbortController().signal,\n\t\t\tMath.min(options.deadlineMs ?? Infinity, performance.now() + 3000),\n\t\t);\n\t} catch {\n\t\t// A later selected relay attempt reports failure through the normal pass result.\n\t}\n}\n\nconst activePeers = new WeakMap<Database, Set<string>>();\nconst activeRelayPeers = new WeakMap<RelayPeerClient, Set<string>>();\nconst NETWORK_CODES = new Set([\n\t\"ECONNREFUSED\",\n\t\"ECONNRESET\",\n\t\"ENETUNREACH\",\n\t\"EHOSTUNREACH\",\n\t\"ENOTFOUND\",\n\t\"EAI_AGAIN\",\n\t\"ETIMEDOUT\",\n\t\"UND_ERR_CONNECT_TIMEOUT\",\n\t\"UND_ERR_HEADERS_TIMEOUT\",\n\t\"UND_ERR_SOCKET\",\n]);\n\nfunction networkFailure(error: unknown): boolean {\n\tif (!error || typeof error !== \"object\") return false;\n\tconst value = error as { name?: string; code?: string; cause?: unknown };\n\tif (value.name === \"TimeoutError\" || (value.code && NETWORK_CODES.has(value.code))) return true;\n\tif (!value.cause || typeof value.cause !== \"object\") return false;\n\tconst cause = value.cause as { code?: string };\n\treturn cause.code !== undefined && NETWORK_CODES.has(cause.code);\n}\n\nfunction failure(transport: \"direct\" | \"wait\", error: string): SyncResult {\n\treturn {\n\t\tok: false,\n\t\ttransport,\n\t\terror,\n\t\tfailureCategory: \"other\",\n\t\topsIn: 0,\n\t\topsOut: 0,\n\t\taddressErrors: [],\n\t};\n}\n\nfunction requireActive(signal: AbortSignal, deadline: number): void {\n\tif (signal.aborted || performance.now() >= deadline)\n\t\tthrow new Error(\"Sync pass cancelled or expired\");\n}\n\nclass DirectPass {\n\tcommittedOrigin: string | null = null;\n\tterminal = false;\n\tattempts = 0;\n\tprivate readonly probeDeadline: number;\n\tconstructor(\n\t\tprivate readonly execute: RequestJsonExecutor,\n\t\tprivate readonly fingerprint: string,\n\t\tprivate readonly signal: AbortSignal,\n\t\tprivate readonly deadline: number,\n\t\tprivate readonly directDeadline: number,\n\t) {\n\t\tthis.probeDeadline = Math.min(deadline, performance.now() + 10_000);\n\t}\n\n\tprivate requestOrigin(method: string, url: string): string {\n\t\trequireActive(this.signal, this.committedOrigin === null ? this.deadline : this.directDeadline);\n\t\tconst origin = new URL(url).origin;\n\t\tif (this.terminal || (this.committedOrigin !== null && this.committedOrigin !== origin))\n\t\t\tthrow new Error(\"Sync transport is already committed\");\n\t\tif (\n\t\t\tthis.committedOrigin === null &&\n\t\t\t(method !== \"GET\" || !new URL(url).pathname.endsWith(\"/v1/status\"))\n\t\t) {\n\t\t\tthis.terminal = true;\n\t\t\tthrow new Error(\"Sync status is required before application requests\");\n\t\t}\n\t\treturn origin;\n\t}\n\n\treadonly request: RequestJsonExecutor = async (method, url, options = {}) => {\n\t\tconst origin = this.requestOrigin(method, url);\n\t\ttry {\n\t\t\tconst remaining =\n\t\t\t\t(this.committedOrigin === null ? this.probeDeadline : this.directDeadline) -\n\t\t\t\tperformance.now();\n\t\t\tif (remaining <= 0)\n\t\t\t\tthrow new DOMException(\"Direct reachability deadline expired\", \"TimeoutError\");\n\t\t\tthis.attempts++;\n\t\t\tconst response = await this.execute(method, url, {\n\t\t\t\t...options,\n\t\t\t\tredirect: \"error\",\n\t\t\t\tsignal: this.signal,\n\t\t\t\ttimeoutS: Math.min(options.timeoutS ?? 3, remaining / 1000),\n\t\t\t});\n\t\t\trequireActive(\n\t\t\t\tthis.signal,\n\t\t\t\tthis.committedOrigin === null ? this.deadline : this.directDeadline,\n\t\t\t);\n\t\t\tif (this.committedOrigin === null) {\n\t\t\t\tif (response[0] === 200 && response[1]?.fingerprint === this.fingerprint)\n\t\t\t\t\tthis.committedOrigin = origin;\n\t\t\t\telse this.terminal = true;\n\t\t\t}\n\t\t\treturn response;\n\t\t} catch (error) {\n\t\t\tif (this.committedOrigin !== null || this.signal.aborted || !networkFailure(error))\n\t\t\t\tthis.terminal = true;\n\t\t\tthrow error;\n\t\t}\n\t};\n}\n\nasync function selectedPass(\n\tdb: Database,\n\tpeerDeviceId: string,\n\taddresses: string[],\n\toptions: SyncPassOptions,\n\treachability: SyncReachabilityOptions,\n): Promise<SyncResult> {\n\tconst deadline = Math.min(reachability.deadlineMs ?? Infinity, performance.now() + 60_000);\n\tconst signal = reachability.signal ?? new AbortController().signal;\n\tif (\n\t\t(reachability.deadlineMs !== undefined && !Number.isFinite(reachability.deadlineMs)) ||\n\t\t!Number.isFinite(deadline) ||\n\t\t!reachability.scopeId.trim()\n\t)\n\t\treturn failure(\"wait\", \"Invalid sync pass configuration\");\n\trequireActive(signal, deadline);\n\tconst peer = db\n\t\t.prepare(\"SELECT pinned_fingerprint, public_key FROM sync_peers WHERE peer_device_id = ?\")\n\t\t.get(peerDeviceId) as { pinned_fingerprint: string; public_key: string } | undefined;\n\tif (!peer?.pinned_fingerprint)\n\t\treturn { ...failure(\"direct\", \"Peer is not pinned\"), failureCategory: \"trust\" };\n\tconst direct = new DirectPass(\n\t\toptions.requestExecutor ?? requestJson,\n\t\tpeer.pinned_fingerprint,\n\t\tsignal,\n\t\tdeadline,\n\t\treachability.deadlineMs ?? Infinity,\n\t);\n\tconst result = await syncOnce(db, peerDeviceId, addresses, {\n\t\t...options,\n\t\trequestExecutor: direct.request,\n\t\tattemptRecorder: options.attemptRecorder ?? (() => {}),\n\t\tdeferConnectionFailure: true,\n\t});\n\tif (result.ok || direct.committedOrigin !== null || direct.terminal)\n\t\treturn { ...result, transport: \"direct\" };\n\tif (direct.attempts === 0 && result.error !== \"no dialable peer addresses\")\n\t\treturn { ...result, transport: \"direct\" };\n\t// The traversal engine has no approved runtime capability. No RTC networking starts here.\n\tif (!reachability.relay) return { ...result, transport: \"wait\" };\n\tif (!isRelayPeerClient(reachability.relay))\n\t\treturn {\n\t\t\t...failure(\"wait\", \"Relay transport is unavailable\"),\n\t\t\treceiveFailureCode: result.receiveFailureCode,\n\t\t};\n\trequireActive(signal, deadline);\n\treturn relayPass(db, peerDeviceId, peer.public_key, options, reachability, signal, result);\n}\n\nasync function relayPass(\n\tdb: Database,\n\tpeerDeviceId: string,\n\tpeerPublicKey: string,\n\toptions: SyncPassOptions,\n\treachability: SyncReachabilityOptions,\n\tsignal: AbortSignal,\n\tdirect: SyncResult,\n): Promise<SyncResult> {\n\tif (!isRelayPeerClient(reachability.relay))\n\t\treturn {\n\t\t\t...failure(\"wait\", \"Relay transport is unavailable\"),\n\t\t\treceiveFailureCode: direct.receiveFailureCode,\n\t\t};\n\t// A skipped relay is a wait, so the pass records only the direct attempt, as it\n\t// does when no relay is configured.\n\tconst skip = relaySkipReason(db, peerDeviceId);\n\tif (skip) return { ...direct, transport: \"wait\", relaySkipped: skip };\n\tconst scoped = await syncScopedChannelOnce({\n\t\tdb,\n\t\tpeerDeviceId,\n\t\tscopeId: reachability.scopeId,\n\t\tlogicalOrigin: reachability.logicalOrigin,\n\t\tfactory: reachability.relay.factory(peerDeviceId, peerPublicKey),\n\t\tkeysDir: options.keysDir,\n\t\tdbPath: options.dbPath,\n\t\tscanner: options.scanner,\n\t\tlimit: options.limit,\n\t\tsignal,\n\t\t// Direct attempts to unreachable addresses can use most of the pass deadline.\n\t\t// Relay gets its own lifetime, bounded only by an explicit caller deadline.\n\t\tdeadlineMs: reachability.deadlineMs,\n\t});\n\trecordRelayOutcome(db, peerDeviceId, scoped);\n\treturn relayResult(scoped, direct);\n}\n\nconst RELAY_REJECTION_BACKOFF_MS = [2, 4, 8, 16, 30].map((minutes) => minutes * 60_000);\n/** A \"no relay client\" observation is trusted this long; after that the rejection back-off applies. */\nconst RELAY_UNSUPPORTED_TTL_MS = 24 * 60 * 60_000;\n\n/**\n * Why relay is not tried for this peer right now, or null to try it.\n *\n * A peer that last advertised `relay_aware` without `relay` over direct sync runs\n * no relay client, so the realm has no route for it. That observation expires after\n * a day, because the peer may turn relay on while direct sync is unavailable. A peer\n * without `relay_aware` may still relay on an early build, unless a recent stable\n * version identifies it as pre-0.48. Unknown or expired versions remain eligible.\n * A peer that recently\n * sent REJECTED is retried on a growing schedule, since REJECTED carries no\n * reason and most often means the peer is offline or not on relay.\n */\nfunction relaySkipReason(db: Database, peerDeviceId: string): SyncResult[\"relaySkipped\"] | null {\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT sync_features_json, sync_features_observed_at, relay_retry_after,\n\t\t\truntime_version, runtime_version_observed_at\n\t\t\tFROM sync_peers WHERE peer_device_id = ?`,\n\t\t)\n\t\t.get(peerDeviceId) as\n\t\t| {\n\t\t\t\tsync_features_json: string | null;\n\t\t\t\tsync_features_observed_at: string | null;\n\t\t\t\trelay_retry_after: string | null;\n\t\t\t\truntime_version: string | null;\n\t\t\t\truntime_version_observed_at: string | null;\n\t\t }\n\t\t| undefined;\n\tif (!row) return null;\n\tconst features = row.sync_features_json === null ? null : parseJson(row.sync_features_json);\n\tconst observedAt = Date.parse(row.sync_features_observed_at ?? \"\");\n\tconst age = Date.now() - observedAt;\n\tif (\n\t\tfeatures !== null &&\n\t\tage >= 0 &&\n\t\tage < RELAY_UNSUPPORTED_TTL_MS &&\n\t\tsupportsSyncFeature(features, \"relay_aware\") &&\n\t\t!supportsSyncFeature(features, \"relay\")\n\t)\n\t\treturn \"relay_peer_unsupported\";\n\tif (!supportsSyncFeature(features, \"relay\") && recentlyObservedLegacyPeer(row))\n\t\treturn \"relay_peer_unsupported\";\n\tif (row.relay_retry_after && row.relay_retry_after > new Date().toISOString())\n\t\treturn \"relay_backoff\";\n\treturn null;\n}\n\nfunction recentlyObservedLegacyPeer(peer: {\n\truntime_version: string | null;\n\truntime_version_observed_at: string | null;\n}): boolean {\n\tif (!isStableReleaseVersion(peer.runtime_version)) return false;\n\tconst age = Date.now() - Date.parse(peer.runtime_version_observed_at ?? \"\");\n\tif (!(age >= 0 && age < RELAY_UNSUPPORTED_TTL_MS)) return false;\n\tconst parts = peer.runtime_version.split(\".\");\n\treturn Number(parts[0]) === 0 && Number(parts[1]) < 48;\n}\n\nfunction parseJson(text: string): unknown {\n\ttry {\n\t\treturn JSON.parse(text);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction recordRelayOutcome(db: Database, peerDeviceId: string, result: SyncScopeResult): void {\n\tconst now = new Date().toISOString();\n\tif (result.ok) {\n\t\tdb.prepare(\n\t\t\t`UPDATE sync_peers SET last_sync_at = ?, last_seen_at = ?, last_error = NULL,\n\t\t\trelay_retry_after = NULL, relay_rejections = 0 WHERE peer_device_id = ?`,\n\t\t).run(now, now, peerDeviceId);\n\t\treturn;\n\t}\n\tif (result.relayFailureReason !== \"relay_rejected\") return;\n\tconst rejections =\n\t\t((\n\t\t\tdb\n\t\t\t\t.prepare(\"SELECT relay_rejections FROM sync_peers WHERE peer_device_id = ?\")\n\t\t\t\t.get(peerDeviceId) as { relay_rejections: number } | undefined\n\t\t)?.relay_rejections ?? 0) + 1;\n\tconst backoff =\n\t\tRELAY_REJECTION_BACKOFF_MS[Math.min(rejections, RELAY_REJECTION_BACKOFF_MS.length) - 1];\n\tdb.prepare(\n\t\t\"UPDATE sync_peers SET relay_retry_after = ?, relay_rejections = ? WHERE peer_device_id = ?\",\n\t).run(new Date(Date.now() + (backoff ?? 0)).toISOString(), rejections, peerDeviceId);\n}\n\nfunction relayResult(scoped: SyncScopeResult, direct: SyncResult): SyncResult {\n\treturn {\n\t\tok: scoped.ok,\n\t\ttransport: \"relay\",\n\t\topsIn: scoped.opsIn,\n\t\topsOut: scoped.opsOut,\n\t\terror: scoped.error,\n\t\tfailureCategory: scoped.failureCategory,\n\t\tresetRequired: scoped.resetRequired,\n\t\tperScopeResults: [scoped],\n\t\taddressErrors: direct.addressErrors,\n\t};\n}\n\n/** Opt-in direct → approved traversal when available → relay → wait. Never changes paths after status. */\nexport async function runReachableSyncPass(\n\tdb: Database,\n\tpeerDeviceId: string,\n\taddresses: string[],\n\toptions: SyncPassOptions,\n): Promise<SyncResult> {\n\tconst reachability = options.reachability;\n\tif (!reachability) return syncOnce(db, peerDeviceId, addresses, options);\n\tlet active = activePeers.get(db);\n\tif (!active) {\n\t\tactive = new Set();\n\t\tactivePeers.set(db, active);\n\t}\n\tlet relayActive: Set<string> | undefined;\n\tif (isRelayPeerClient(reachability.relay)) {\n\t\trelayActive = activeRelayPeers.get(reachability.relay);\n\t\tif (!relayActive) {\n\t\t\trelayActive = new Set();\n\t\t\tactiveRelayPeers.set(reachability.relay, relayActive);\n\t\t}\n\t}\n\tif (active.has(peerDeviceId) || relayActive?.has(peerDeviceId))\n\t\treturn failure(\"wait\", \"Peer sync is already in progress\");\n\t// Manual and daemon passes can share a relay client through separate DB handles.\n\t// Acquire both before direct work so fallback never competes with an admitted pass.\n\tactive.add(peerDeviceId);\n\trelayActive?.add(peerDeviceId);\n\ttry {\n\t\tconst result = await selectedPass(db, peerDeviceId, addresses, options, reachability);\n\t\tif (!result.ok && result.transport !== \"relay\" && result.receiveFailureCode) {\n\t\t\trecordSyncTransferObservation(db, peerDeviceId, \"receive\", {\n\t\t\t\terrorCode: result.receiveFailureCode,\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t} catch {\n\t\treturn failure(\"wait\", \"Sync pass cancelled or failed\");\n\t} finally {\n\t\tactive.delete(peerDeviceId);\n\t\trelayActive?.delete(peerDeviceId);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA6DA,IAAM,KACL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