@remnic/core 9.69.103 → 9.69.104
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/access-admin-ops-surface.js +10 -10
- package/dist/access-authorization-probe.js +11 -11
- package/dist/access-boundary.js +10 -10
- package/dist/access-cli.js +30 -30
- package/dist/access-extraction-force-flush.js +10 -10
- package/dist/access-http-briefing.js +11 -11
- package/dist/access-http-query.js +10 -10
- package/dist/access-http.js +23 -23
- package/dist/access-identity-continuity-surface.js +10 -10
- package/dist/access-lcm-surface.js +10 -10
- package/dist/access-mcp.js +17 -17
- package/dist/access-namespace-preflight.js +10 -10
- package/dist/access-observe-write-category.js +7 -7
- package/dist/access-observe-write-surface.js +10 -10
- package/dist/access-offline-manifest.js +6 -6
- package/dist/access-operations-batch.js +11 -11
- package/dist/access-operations.js +16 -16
- package/dist/access-recall-concurrency.js +10 -10
- package/dist/access-recall-response.js +10 -10
- package/dist/access-recall-surface.js +10 -10
- package/dist/access-schema.js +6 -6
- package/dist/access-service.js +10 -10
- package/dist/access-surface-catalog.js +12 -12
- package/dist/active-recall.js +6 -6
- package/dist/{chunk-47LTKAGL.js → chunk-2COXDQ6C.js} +21 -6
- package/dist/chunk-2COXDQ6C.js.map +1 -0
- package/dist/{chunk-KN4GNQH7.js → chunk-2TCNEJ36.js} +4 -4
- package/dist/{chunk-5FHH4NJR.js → chunk-5R4YPRAR.js} +17 -4
- package/dist/chunk-5R4YPRAR.js.map +1 -0
- package/dist/{chunk-ANPRNTPT.js → chunk-63LFM77Z.js} +15 -2
- package/dist/chunk-63LFM77Z.js.map +1 -0
- package/dist/{chunk-JHZOY4CJ.js → chunk-6WRHNA4I.js} +7 -7
- package/dist/{chunk-HTXTVY64.js → chunk-7NBUE5VY.js} +2 -2
- package/dist/{chunk-4QHWRWCF.js → chunk-7YQR6XHY.js} +8 -8
- package/dist/{chunk-2JJD7GIW.js → chunk-ATFFWIKL.js} +2 -2
- package/dist/{chunk-2GSO4FEC.js → chunk-AU43D3IT.js} +3 -3
- package/dist/{chunk-OC6ATPIP.js → chunk-CGBE3N7T.js} +2 -2
- package/dist/{chunk-NN62MUZA.js → chunk-DB6XFMOF.js} +3 -3
- package/dist/{chunk-5GKRQBPQ.js → chunk-FYX2LXIX.js} +2 -2
- package/dist/{chunk-6RWPKWCZ.js → chunk-GZ2KV2RO.js} +3 -3
- package/dist/{chunk-D4MXH276.js → chunk-JC7QQ2DJ.js} +2 -2
- package/dist/{chunk-GWWHV7F3.js → chunk-KFHEZJQZ.js} +2 -2
- package/dist/{chunk-B44TVSEI.js → chunk-KV7LFOPF.js} +2 -2
- package/dist/{chunk-L6BUCPGI.js → chunk-LHDSCWDK.js} +11 -11
- package/dist/{chunk-5PEBJUYD.js → chunk-MZOQ26LH.js} +2 -2
- package/dist/{chunk-NBYSCXOY.js → chunk-OFGTRDWX.js} +2 -2
- package/dist/{chunk-26DJ7FG6.js → chunk-PZ2QQULY.js} +2 -2
- package/dist/{chunk-LP4UW5WI.js → chunk-QAIVTLL2.js} +2 -2
- package/dist/{chunk-HYFVZJLX.js → chunk-QUNCLKHM.js} +2 -2
- package/dist/{chunk-Q3LWW7WS.js → chunk-QX3K3INR.js} +2 -2
- package/dist/{chunk-K5ABKRXK.js → chunk-SFDBLCZV.js} +7 -7
- package/dist/{chunk-XM32D6YZ.js → chunk-STQC2FYQ.js} +4 -4
- package/dist/{chunk-PNZAFABF.js → chunk-TXTRHF3B.js} +2 -2
- package/dist/{chunk-SOVRTUD3.js → chunk-VDVHIRCK.js} +2 -2
- package/dist/{chunk-D42DLA4D.js → chunk-WR66CTVU.js} +3 -3
- package/dist/{chunk-UCPGOUDZ.js → chunk-Y57GJDG5.js} +108 -3
- package/dist/chunk-Y57GJDG5.js.map +1 -0
- package/dist/{chunk-NIGZ3LE7.js → chunk-YI6XIFQV.js} +2 -2
- package/dist/cli.js +27 -27
- package/dist/config.js +6 -6
- package/dist/deep-recall-http-glue.js +7 -7
- package/dist/embedding-fallback.d.ts +2 -1
- package/dist/embedding-fallback.d.ts.map +1 -1
- package/dist/embedding-fallback.js +2 -2
- package/dist/embedding-index-storage.d.ts +28 -1
- package/dist/embedding-index-storage.d.ts.map +1 -1
- package/dist/embedding-index-storage.js +1 -1
- package/dist/external-wiki-access.js +11 -11
- package/dist/index.js +30 -30
- package/dist/memory-browse-operations.js +11 -11
- package/dist/offline-sync-changeset-generations.js +4 -4
- package/dist/offline-sync-embedding-generation.js +3 -3
- package/dist/offline-sync-exclude-globs.d.ts +8 -0
- package/dist/offline-sync-exclude-globs.d.ts.map +1 -1
- package/dist/offline-sync-exclude-globs.js +3 -1
- package/dist/offline-sync-snapshot-stream.js +6 -6
- package/dist/offline-sync.d.ts.map +1 -1
- package/dist/offline-sync.js +5 -5
- package/dist/operator-toolkit.js +7 -7
- package/dist/orchestrator.js +30 -30
- package/dist/recall-navigation-operations.js +11 -11
- package/dist/recall-navigation.js +10 -10
- package/dist/resume-bundles.js +7 -7
- package/dist/support-passport/index.js +13 -13
- package/package.json +2 -2
- package/src/embedding-fallback-cross-process.test.ts +533 -0
- package/src/embedding-fallback.ts +19 -7
- package/src/embedding-index-storage.test.ts +482 -2
- package/src/embedding-index-storage.ts +131 -2
- package/src/offline-sync-exclude-globs.ts +23 -0
- package/src/offline-sync.test.ts +325 -0
- package/src/offline-sync.ts +17 -1
- package/dist/chunk-47LTKAGL.js.map +0 -1
- package/dist/chunk-5FHH4NJR.js.map +0 -1
- package/dist/chunk-ANPRNTPT.js.map +0 -1
- package/dist/chunk-UCPGOUDZ.js.map +0 -1
- /package/dist/{chunk-KN4GNQH7.js.map → chunk-2TCNEJ36.js.map} +0 -0
- /package/dist/{chunk-JHZOY4CJ.js.map → chunk-6WRHNA4I.js.map} +0 -0
- /package/dist/{chunk-HTXTVY64.js.map → chunk-7NBUE5VY.js.map} +0 -0
- /package/dist/{chunk-4QHWRWCF.js.map → chunk-7YQR6XHY.js.map} +0 -0
- /package/dist/{chunk-2JJD7GIW.js.map → chunk-ATFFWIKL.js.map} +0 -0
- /package/dist/{chunk-2GSO4FEC.js.map → chunk-AU43D3IT.js.map} +0 -0
- /package/dist/{chunk-OC6ATPIP.js.map → chunk-CGBE3N7T.js.map} +0 -0
- /package/dist/{chunk-NN62MUZA.js.map → chunk-DB6XFMOF.js.map} +0 -0
- /package/dist/{chunk-5GKRQBPQ.js.map → chunk-FYX2LXIX.js.map} +0 -0
- /package/dist/{chunk-6RWPKWCZ.js.map → chunk-GZ2KV2RO.js.map} +0 -0
- /package/dist/{chunk-D4MXH276.js.map → chunk-JC7QQ2DJ.js.map} +0 -0
- /package/dist/{chunk-GWWHV7F3.js.map → chunk-KFHEZJQZ.js.map} +0 -0
- /package/dist/{chunk-B44TVSEI.js.map → chunk-KV7LFOPF.js.map} +0 -0
- /package/dist/{chunk-L6BUCPGI.js.map → chunk-LHDSCWDK.js.map} +0 -0
- /package/dist/{chunk-5PEBJUYD.js.map → chunk-MZOQ26LH.js.map} +0 -0
- /package/dist/{chunk-NBYSCXOY.js.map → chunk-OFGTRDWX.js.map} +0 -0
- /package/dist/{chunk-26DJ7FG6.js.map → chunk-PZ2QQULY.js.map} +0 -0
- /package/dist/{chunk-LP4UW5WI.js.map → chunk-QAIVTLL2.js.map} +0 -0
- /package/dist/{chunk-HYFVZJLX.js.map → chunk-QUNCLKHM.js.map} +0 -0
- /package/dist/{chunk-Q3LWW7WS.js.map → chunk-QX3K3INR.js.map} +0 -0
- /package/dist/{chunk-K5ABKRXK.js.map → chunk-SFDBLCZV.js.map} +0 -0
- /package/dist/{chunk-XM32D6YZ.js.map → chunk-STQC2FYQ.js.map} +0 -0
- /package/dist/{chunk-PNZAFABF.js.map → chunk-TXTRHF3B.js.map} +0 -0
- /package/dist/{chunk-SOVRTUD3.js.map → chunk-VDVHIRCK.js.map} +0 -0
- /package/dist/{chunk-D42DLA4D.js.map → chunk-WR66CTVU.js.map} +0 -0
- /package/dist/{chunk-NIGZ3LE7.js.map → chunk-YI6XIFQV.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/embedding-fallback.ts"],"sourcesContent":["import path from \"node:path\";\nimport { log } from \"./logger.js\";\nimport {\n resolveMemoryLifecycleCapabilities,\n resolveLocalLlmCapabilities,\n} from \"./capabilities.js\";\nimport { readEnvVar } from \"./runtime/env.js\";\nimport type { PluginConfig } from \"./types.js\";\nimport { resolvePipelineProcessingCapabilities } from \"./capabilities.js\";\nimport {\n getHostEmbeddingProvider,\n type HostEmbeddingProvider,\n normalizeHostEmbeddingVector,\n} from \"./host-embedding-provider.js\";\nimport {\n EmbeddingIndexFileStore,\n EmbeddingIndexStorageError,\n type EmbeddingIndexEntry,\n type EmbeddingIndexFile,\n type EmbeddingIndexIdentity,\n type EmbeddingProviderType,\n EmbeddingIndexStoreIo,\n} from \"./embedding-index-storage.js\";\nexport {\n EmbeddingIndexCapacityError,\n EmbeddingIndexStorageError,\n} from \"./embedding-index-storage.js\";\nexport type {\n EmbeddingIndexStatusFile,\n EmbeddingIndexWriteFailure,\n} from \"./embedding-index-storage.js\";\ntype ProviderConfig = {\n type: EmbeddingProviderType;\n model: string;\n endpoint?: string;\n headers?: Record<string, string>;\n hostProvider?: HostEmbeddingProvider;\n};\n\ntype EmbeddingResult = {\n provider: ProviderConfig;\n vector: number[];\n};\n\ntype EmbeddingIndexComparable =\n | EmbeddingIndexIdentity\n | Pick<ProviderConfig, \"type\" | \"model\">;\n\nconst DEFAULT_OPENAI_MODEL = \"text-embedding-3-small\";\n\n/**\n * Thrown by `EmbeddingFallback.search()` (via `embed()`) when the embedding\n * backend is effectively unavailable on the lookup path — either because the\n * HTTP fetch exceeded its deadline OR because the endpoint returned a non-2xx\n * status code. Callers that need to distinguish a backend outage from \"no\n * candidates\" can `instanceof`-check against this class.\n *\n * Round 9 fix (Finding UZqB): previously a timeout returned null from embed(),\n * which caused search() to return [] silently. decideSemanticDedup then\n * classified the result as no_candidates instead of backend_unavailable, so\n * the per-batch batchBackendUnavailable short-circuit never activated and\n * batches of N facts each paid a full timeout roundtrip.\n *\n * Round 10 fix (Findings Ui1J + Ui1L): search() now only re-throws this error\n * when the caller explicitly passes `{ throwOnTimeout: true }`. Without that\n * flag search() catches it and returns [] instead, preserving fail-open\n * semantics for recall-path callers (searchEmbeddingFallback) that have no\n * try/catch. Only the semantic-dedup path (semanticDedupLookup) passes the\n * flag so it can still reach decideSemanticDedup's backend_unavailable branch.\n *\n * Round 11 fix (Finding Ur_J): `embed()` now also throws this error from the\n * lookup path when the HTTP response is non-2xx (e.g. 429, 500, 503). Without\n * this, repeated 5xx outages would each return null → [] → no_candidates and\n * subsequent facts in the same batch would all pay full roundtrips instead of\n * tripping the per-batch backend_unavailable short-circuit.\n *\n * The class name is kept for backward compatibility — `EmbeddingTimeoutError`\n * now signals \"lookup backend unavailable\" rather than strictly \"timed out\".\n */\nimport {\n assertEmbeddingGenerationLockHeld,\n embeddingGenerationLockPath,\n EmbeddingGenerationLockUnavailableError,\n withEmbeddingGenerationLock,\n type EmbeddingGenerationLockSection,\n} from \"./embedding-generation-lock.js\";\n\nexport class EmbeddingTimeoutError extends Error {\n override readonly name = \"EmbeddingTimeoutError\" as const;\n constructor(message: string) {\n super(message);\n }\n}\n\nexport class EmbeddingProviderUnavailableError extends Error {\n override readonly name = \"EmbeddingProviderUnavailableError\" as const;\n constructor(message: string) {\n super(message);\n }\n}\n\nfunction isLookupBackendUnavailableError(err: unknown): boolean {\n return (\n err instanceof EmbeddingTimeoutError ||\n err instanceof EmbeddingProviderUnavailableError\n );\n}\n\n/**\n * Maximum time to wait for an embedding HTTP request on the LOOKUP/query\n * path before giving up.\n *\n * The write-time semantic dedup guard in orchestrator.persistExtraction()\n * blocks each candidate fact on an embedding lookup. If the embedding\n * endpoint hangs (degraded OpenAI, stalled local gateway, DNS timeout),\n * extraction would otherwise stall indefinitely — a single bad backend\n * could freeze the entire persist loop. Bounding the fetch here ensures\n * the decision path fails open (returns null) within a predictable window\n * and writes proceed as non-duplicates.\n *\n * Tests can override via REMNIC_EMBEDDING_FETCH_TIMEOUT_MS so they don't\n * have to wait the full default on hung-fetch assertions.\n *\n * Related: joshuaswarren/remnic#373, PR #399 P1/P2 review.\n */\nconst DEFAULT_EMBEDDING_LOOKUP_TIMEOUT_MS = 5000;\n\n/**\n * Maximum time to wait for an embedding HTTP request on the INDEX path.\n *\n * Indexing runs asynchronously after a memory has already been persisted\n * to disk. It does not block extraction or writes — it only updates the\n * embedding index used by later semantic dedup lookups. A slow local\n * CPU-backed embedding model can legitimately take tens of seconds per\n * call, so applying the short lookup timeout here silently dropped index\n * updates and caused later dedup lookups to miss recently persisted\n * memories. Use a much larger budget on this path.\n *\n * Tests can override via REMNIC_EMBEDDING_INDEX_TIMEOUT_MS.\n */\nconst DEFAULT_EMBEDDING_INDEX_TIMEOUT_MS = 120_000;\n\nfunction resolveEmbeddingLookupTimeoutMs(): number {\n const raw = readEnvVar(\"REMNIC_EMBEDDING_FETCH_TIMEOUT_MS\");\n if (raw) {\n const parsed = Number(raw);\n if (Number.isFinite(parsed) && parsed > 0) {\n return Math.floor(parsed);\n }\n }\n return DEFAULT_EMBEDDING_LOOKUP_TIMEOUT_MS;\n}\n\nfunction resolveEmbeddingIndexTimeoutMs(): number {\n const raw = readEnvVar(\"REMNIC_EMBEDDING_INDEX_TIMEOUT_MS\");\n if (raw) {\n const parsed = Number(raw);\n if (Number.isFinite(parsed) && parsed > 0) {\n return Math.floor(parsed);\n }\n }\n return DEFAULT_EMBEDDING_INDEX_TIMEOUT_MS;\n}\n\n/**\n * Options for the low-level embed() call.\n *\n * `mode` selects the timeout profile:\n * - \"lookup\" (default): bounded by the short lookup budget; fails open fast.\n * - \"index\": bounded by a much longer budget so slow backends can still\n * index newly persisted memories.\n */\nexport type EmbedMode = \"lookup\" | \"index\";\n\nexport class EmbeddingFallback {\n private readonly store: EmbeddingIndexFileStore;\n private loaded: EmbeddingIndexFile | null = null;\n /** True when the cached index came from a published generation. */\n private loadedFromDisk = false;\n private identityProbe: { stamp: string; identity: EmbeddingIndexIdentity | null } | null = null;\n private mutationQueue: Promise<void> = Promise.resolve();\n\n /** The canonical state dir scoping this fallback's generation mutation lock. */\n private readonly generationStateDir: string;\n private readonly generationLockPath: string;\n private lockSection: EmbeddingGenerationLockSection | null = null;\n\n constructor(private readonly config: PluginConfig, storeIo?: EmbeddingIndexStoreIo) {\n const stateDir = path.join(config.memoryDir, \"state\");\n this.generationStateDir = stateDir;\n this.generationLockPath = embeddingGenerationLockPath(stateDir);\n this.store = new EmbeddingIndexFileStore(\n path.join(stateDir, \"embeddings.json\"),\n path.join(stateDir, \"embeddings\"),\n path.join(stateDir, \"embedding-fallback-status.json\"),\n storeIo,\n );\n }\n\n async isAvailable(): Promise<boolean> {\n return (await this.resolveProvider()) !== null;\n }\n\n /**\n * Embed an array of texts and return their embedding vectors.\n *\n * This is the public batch-embed interface used by semantic chunking\n * (Finding 1, PR #420 post-merge). Texts are grouped into batches of\n * `embeddingBatchSize` (from `semanticChunkingConfig`, default 32) and\n * each batch is dispatched concurrently via `Promise.all()`. This\n * preserves the semantic intent of `embeddingBatchSize` — without batching,\n * every text incurred a sequential HTTP round-trip, making the batch size\n * config ineffective. (PR #439 post-merge Finding 2.)\n *\n * If the provider is unavailable or any single embedding fails, the method\n * throws so the caller can fall back to recursive chunking.\n */\n async embedTexts(texts: string[]): Promise<number[][]> {\n const provider = await this.resolveProvider();\n if (!provider) {\n throw new Error(\"Embedding provider is not available\");\n }\n\n const batchSize = Math.max(\n 1,\n this.config.semanticChunkingConfig?.embeddingBatchSize ?? 32,\n );\n\n const vectors: number[][] = [];\n for (let i = 0; i < texts.length; i += batchSize) {\n const batch = texts.slice(i, i + batchSize);\n const batchResults = await Promise.all(\n batch.map((text) => this.embed(text, provider, { mode: \"lookup\" })),\n );\n for (const vec of batchResults) {\n if (!vec) {\n throw new Error(\"Embedding returned null for input text\");\n }\n vectors.push(vec);\n }\n }\n return vectors;\n }\n\n /**\n * Nearest-neighbor search against the embedding index.\n *\n * @param query The query string to embed and search for.\n * @param limit Max number of hits to return.\n * @param options Optional filters.\n * - `pathPrefix` Restrict candidates to entries whose indexed `path`\n * starts with this prefix (relative to `memoryDir`).\n * Used by the semantic dedup guard to scope lookups\n * to the target namespace so a high-similarity hit\n * from a different namespace can't suppress a write\n * in the target namespace. Default: no filter.\n * - `pathExcludePrefixes`\n * Exclude any entry whose indexed `path` starts with\n * any of these prefixes. Used for the default\n * namespace case: when the default namespace lives at\n * `memoryDir` root (legacy layout) we still want to\n * exclude `namespaces/<other>/…` entries.\n */\n async search(\n query: string,\n limit: number,\n options: {\n pathPrefix?: string;\n pathExcludePrefixes?: readonly string[];\n /**\n * When true, an `EmbeddingTimeoutError` from the embedding backend is\n * re-thrown to the caller. Use this on the semantic-dedup path so\n * `decideSemanticDedup`'s catch block can classify the result as\n * `reason=\"backend_unavailable\"` and activate the per-batch\n * short-circuit.\n *\n * When false (the default), a timeout is caught here and search()\n * returns [] instead — preserving fail-open semantics for the recall\n * path (`searchEmbeddingFallback`) which has no surrounding try/catch.\n * Without this gate a timed-out embedding request on the recall path\n * would propagate as an unhandled rejection and abort recall entirely.\n * (Round 10 fix, Findings Ui1J + Ui1L.)\n */\n throwOnTimeout?: boolean;\n } = {},\n ): Promise<Array<{ id: string; score: number; path: string }>> {\n const provider = await this.resolveProvider();\n if (!provider) return [];\n\n let queryResult = await this.embedForSearch(query, provider, options);\n if (!queryResult) return [];\n // Effective query embedding: swapped to the disk index's provider\n // below when the on-disk generation has a different identity. `let` so\n // the swap reassigns; TS narrowing bound for control flow.\n let active = queryResult;\n\n // Recall fails OPEN on index read failures (corrupt/oversized/mixed\n // generations, unreadable shard dirs): return [] without caching so a\n // later mutation still revalidates and fails closed (issue #3146).\n try {\n const diskIdentity = await this.readIndexIdentityFromDisk();\n if (diskIdentity && !sameIndexIdentity(diskIdentity, queryResult.provider)) {\n // The provider swap needs a NETWORK embed: run it OUTSIDE the\n // generation lock, then re-verify the identity under the lock below.\n const diskProvider = await this.resolveFallbackProviderForIndexIdentity(diskIdentity);\n if (diskProvider) {\n const diskQueryResult = await this.embedForSearch(query, diskProvider, options);\n if (diskQueryResult && sameIndexIdentity(diskIdentity, diskQueryResult.provider)) {\n active = diskQueryResult;\n } else {\n log.debug(\n `embedding fallback search skipped: preserved ${diskIdentity.provider}/${diskIdentity.model} index is unavailable for lookup`,\n );\n return [];\n }\n } else {\n log.debug(\n `embedding fallback search skipped: query provider ${queryResult.provider.type}/${queryResult.provider.model} does not match existing ${diskIdentity.provider}/${diskIdentity.model} index`,\n );\n return [];\n }\n }\n\n // Cold load only (cache miss): the complete shard enumeration + read\n // happens under the generation mutation lock so a concurrent swap can\n // never leave a cached SUBSET of the generation (codex\n // PRRT_kwDORJXyws6mZ72p). Warm cached searches stay lock-free.\n let index: EmbeddingIndexFile;\n try {\n index = await this.loadIndexUnderGenerationLock(active.provider);\n } catch (err) {\n if (err instanceof EmbeddingGenerationLockUnavailableError) {\n // Existing read diagnostic, recorded once per failed load; recall\n // itself fails open.\n await this.store.recordIndexStatusForLoad(\n `generation mutation lock unavailable: ${err instanceof Error ? err.message : String(err)}`,\n );\n return [];\n }\n throw err;\n }\n const ids = Object.keys(index.entries);\n if (ids.length === 0) return [];\n\n const includePrefix = normalizePathPrefix(options.pathPrefix);\n const excludePrefixes = (options.pathExcludePrefixes ?? [])\n .map((p) => normalizePathPrefix(p))\n .filter((p): p is string => typeof p === \"string\");\n\n const scored = ids\n .map((id) => {\n const entry = index.entries[id];\n return {\n id,\n path: entry.path,\n score: cosineSimilarity(active.vector, entry.vector),\n };\n })\n .filter((r) => {\n if (!Number.isFinite(r.score)) return false;\n const normalized = normalizeEntryPath(r.path);\n if (includePrefix !== undefined && !normalized.startsWith(includePrefix)) {\n return false;\n }\n for (const excl of excludePrefixes) {\n if (normalized.startsWith(excl)) return false;\n }\n return true;\n })\n .sort((a, b) => b.score - a.score)\n .slice(0, Math.max(1, limit));\n\n return scored;\n } catch (err) {\n if (err instanceof EmbeddingIndexStorageError) {\n log.debug(\n `embedding fallback index unreadable on recall path, failing open: ${err instanceof Error ? err.message : String(err)}`,\n );\n return [];\n }\n throw err;\n }\n }\n\n async indexFile(memoryId: string, content: string, filePath: string): Promise<void> {\n const provider = await this.resolveProvider();\n if (!provider) return;\n // Indexing is not on the write-critical path: a newly persisted memory\n // has already been written to disk by the time we reach this call. Use\n // the long \"index\" timeout so slow local embedding backends can still\n // add the entry to the index. Previously this used the short lookup\n // budget and silently dropped updates, leaving later dedup lookups\n // blind to the memory. Related: PR #399 P2.\n const result = await this.embedWithEffectiveProvider(content, provider, {\n mode: \"index\",\n });\n if (!result) return;\n\n await this.enqueueIndexMutation(memoryId, async () => {\n try {\n const existing = await this.readIndexIdentityFromDisk();\n if (\n existing &&\n !sameIndexIdentity(existing, result.provider) &&\n !canReplaceIndexIdentity(existing, result.provider)\n ) {\n log.debug(\n `embedding fallback index update skipped: ${result.provider.type}/${result.provider.model} would replace existing ${existing.provider}/${existing.model} index`,\n );\n return;\n }\n const index = await this.loadIndex(result.provider);\n const relPath = toMemoryRelativePath(this.config.memoryDir, filePath);\n index.entries[memoryId] = {\n vector: result.vector,\n path: relPath,\n };\n await this.saveIndex(index, { touchedIds: [memoryId], memoryId });\n } catch (err) {\n await this.store.recordIndexWriteOutcome(err, memoryId);\n throw err;\n }\n await this.store.recordIndexWriteOutcome(null, memoryId);\n });\n }\n\n async removeFromIndex(memoryId: string): Promise<void> {\n const provider = await this.resolveProvider();\n if (!provider) return;\n\n await this.enqueueIndexMutation(memoryId, async () => {\n const providers = [provider];\n const diskIdentity = await this.readIndexIdentityFromDisk();\n if (\n diskIdentity &&\n !providers.some((entry) => sameIndexIdentity(entry, diskIdentity))\n ) {\n providers.push(providerFromIndexIdentity(diskIdentity));\n }\n if (provider.type === \"host\") {\n const fallbackProvider = await this.resolveProvider({ includeHost: false });\n if (\n fallbackProvider &&\n !providers.some((entry) => sameIndexIdentity(entry, fallbackProvider))\n ) {\n providers.push(fallbackProvider);\n }\n }\n\n let saved = false;\n for (const indexProvider of providers) {\n try {\n const index = await this.loadIndex(indexProvider);\n if (!index.entries[memoryId]) continue;\n delete index.entries[memoryId];\n await this.saveIndex(index, { touchedIds: [memoryId], memoryId });\n saved = true;\n } catch (err) {\n await this.store.recordIndexWriteOutcome(err, memoryId);\n throw err;\n }\n }\n // A no-op removal (id absent from every candidate index) performs no\n // save: it must NOT clear a recorded persistence failure, or the\n // operator console would report an unresolved failure as fixed\n // without any demonstration that storage is writable (round 6).\n if (saved) await this.store.recordIndexWriteOutcome(null, memoryId);\n });\n }\n\n private enqueueIndexMutation<T>(memoryId: string | undefined, mutation: () => Promise<T>): Promise<T> {\n const run = this.mutationQueue\n .catch(() => undefined)\n .then(() =>\n withEmbeddingGenerationLock(this.generationStateDir, async (section) => {\n this.lockSection = section;\n try {\n // A peer process may have persisted while this process did not\n // hold the generation lock: drop any cached index so the\n // mutation loads the real disk state (codex P1).\n this.loaded = null;\n this.loadedFromDisk = false;\n // Recover an interrupted replacement BEFORE the mutation's identity\n // probes and existence checks: a deletion no-op must not skip\n // persistence while the published generation sits in the rename-gap\n // backup, and insertions must load the restored vectors rather than\n // a fresh empty index (issue #3148, codex round 3).\n let recovered = false;\n try {\n recovered = await this.store.recoverIfInterrupted(this.generationFence());\n } catch (err) {\n // Record the recovery failure durably BEFORE rejecting the\n // mutation: the write-outcome try below is never reached.\n await this.store.recordIndexWriteOutcome(err).catch(() => undefined);\n throw err;\n }\n if (recovered) {\n this.loaded = null;\n this.loadedFromDisk = false;\n }\n return await mutation();\n } finally {\n this.lockSection = null;\n }\n }).catch(async (err) => {\n // A lock ACQUISITION failure never reaches the mutation closure's\n // own write-outcome recording. Route it through the existing\n // durable diagnostic exactly once (codex PRRT_kwDORJXyws6mZ8qS);\n // in-lock failures were already recorded by the closure.\n if (err instanceof EmbeddingGenerationLockUnavailableError) {\n await this.store.recordIndexWriteOutcome(err, memoryId).catch(() => undefined);\n }\n throw err;\n }));\n this.mutationQueue = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n }\n\n private async resolveProvider(\n options: { includeHost?: boolean } = {},\n ): Promise<ProviderConfig | null> {\n if (!resolveMemoryLifecycleCapabilities(this.config).embeddingFallback) return null;\n\n if (\n options.includeHost !== false &&\n resolvePipelineProcessingCapabilities(this.config).hostEmbeddingProvider !== false\n ) {\n const hostProvider = getHostEmbeddingProvider(this.config.memoryDir);\n if (hostProvider) {\n return {\n type: \"host\",\n model: hostProvider.model || hostProvider.id,\n hostProvider,\n };\n }\n }\n\n const preferred = this.config.embeddingFallbackProvider;\n const providers = preferred === \"auto\" ? [\"openai\", \"local\"] : [preferred];\n\n for (const p of providers) {\n if (p === \"openai\") {\n const provider = this.createOpenAiProvider();\n if (provider) return provider;\n }\n\n if (p === \"local\") {\n const provider = this.createLocalProvider();\n if (provider) return provider;\n }\n }\n\n return null;\n }\n\n private async resolveFallbackProviderForIndexIdentity(\n identity: EmbeddingIndexIdentity,\n ): Promise<ProviderConfig | null> {\n if (identity.provider === \"openai\") {\n const provider = this.createOpenAiProvider();\n return provider && sameIndexIdentity(provider, identity) ? provider : null;\n }\n if (identity.provider === \"local\") {\n const provider = this.createLocalProvider();\n return provider && sameIndexIdentity(provider, identity) ? provider : null;\n }\n return null;\n }\n\n private createOpenAiProvider(): ProviderConfig | null {\n if (!this.config.openaiApiKey) return null;\n const baseUrl = this.config.openaiBaseUrl ?? \"https://api.openai.com/v1\";\n return {\n type: \"openai\",\n model: DEFAULT_OPENAI_MODEL,\n endpoint: `${baseUrl.replace(/\\/$/, \"\")}/embeddings`,\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.config.openaiApiKey}`,\n },\n };\n }\n\n private createLocalProvider(): ProviderConfig | null {\n if (!resolveLocalLlmCapabilities(this.config).localLlm || !this.config.localLlmUrl) return null;\n const base = this.config.localLlmUrl.replace(/\\/$/, \"\");\n const endpoint = /\\/v1$/i.test(base) ? `${base}/embeddings` : `${base}/v1/embeddings`;\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...(this.config.localLlmHeaders ?? {}),\n };\n if (this.config.localLlmApiKey && this.config.localLlmAuthHeader !== false) {\n headers.Authorization = `Bearer ${this.config.localLlmApiKey}`;\n }\n return {\n type: \"local\",\n model:\n this.config.embeddingFallbackModel ||\n this.config.localLlmModel ||\n DEFAULT_OPENAI_MODEL,\n endpoint,\n headers,\n };\n }\n\n private async embedForSearch(\n query: string,\n provider: ProviderConfig,\n options: { throwOnTimeout?: boolean } = {},\n ): Promise<EmbeddingResult | null> {\n try {\n return await this.embedWithEffectiveProvider(query, provider, {\n mode: \"lookup\",\n });\n } catch (err) {\n if (isLookupBackendUnavailableError(err)) {\n if (options.throwOnTimeout) {\n throw err;\n }\n // Fail-open: recall-path callers get an empty result rather than an\n // unhandled rejection that would abort recall entirely.\n log.debug(\"embedding fallback search: backend unavailable on lookup, returning [] (throwOnTimeout=false)\");\n return null;\n }\n throw err;\n }\n }\n\n private async embed(\n input: string,\n provider: ProviderConfig,\n options: { mode?: EmbedMode } = {},\n ): Promise<number[] | null> {\n const result = await this.embedWithEffectiveProvider(input, provider, options);\n return result?.vector ?? null;\n }\n\n private async embedWithEffectiveProvider(\n input: string,\n provider: ProviderConfig,\n options: { mode?: EmbedMode } = {},\n ): Promise<EmbeddingResult | null> {\n // Bound the fetch so a hung embedding endpoint cannot stall callers.\n // The lookup path uses a short budget (see DEFAULT_EMBEDDING_LOOKUP_TIMEOUT_MS\n // docblock) so semantic dedup fails open fast. The index path uses a\n // much longer budget because slow local backends (CPU embedding models)\n // otherwise drop index updates and blind later dedup lookups. See\n // DEFAULT_EMBEDDING_INDEX_TIMEOUT_MS docblock and PR #399 P2 review.\n const mode: EmbedMode = options.mode ?? \"lookup\";\n const timeoutMs =\n mode === \"index\"\n ? resolveEmbeddingIndexTimeoutMs()\n : resolveEmbeddingLookupTimeoutMs();\n if (provider.type === \"host\") {\n const vector = await this.embedWithHostProvider(input, provider, mode, timeoutMs);\n if (vector) return { provider, vector };\n const fallbackProvider = await this.resolveProvider({ includeHost: false });\n if (!fallbackProvider) {\n if (mode === \"lookup\") {\n throw new EmbeddingProviderUnavailableError(\n `host embedding provider unavailable (${provider.hostProvider?.id ?? provider.model})`,\n );\n }\n return null;\n }\n return this.embedWithEffectiveProvider(input, fallbackProvider, options);\n }\n if (!provider.endpoint || !provider.headers) return null;\n try {\n const res = await fetch(provider.endpoint, {\n method: \"POST\",\n headers: provider.headers,\n body: JSON.stringify({\n model: provider.model,\n input: input.slice(0, 8000),\n encoding_format: \"float\",\n }),\n signal: AbortSignal.timeout(timeoutMs),\n });\n if (!res.ok) {\n log.debug(`embedding fallback request failed: ${provider.type} ${res.status}`);\n // Round 11 fix (Finding Ur_J): on the LOOKUP path, a non-2xx response\n // means the embedding backend is effectively unavailable. Throw the\n // tagged error so search() (when called with throwOnTimeout) propagates\n // to decideSemanticDedup's backend_unavailable branch, activating the\n // per-batch short-circuit. Without this, repeated 429/5xx responses\n // would silently return [] for every fact in the batch.\n //\n // On the INDEX path a non-2xx is non-fatal (the memory is already\n // persisted; index update can be skipped) — return null there.\n if (mode === \"lookup\") {\n throw new EmbeddingTimeoutError(\n `embedding backend returned ${res.status} (${provider.type})`,\n );\n }\n return null;\n }\n const payload = (await res.json()) as any;\n const vector = payload?.data?.[0]?.embedding;\n if (!Array.isArray(vector)) return null;\n const normalized = vector\n .map((n: unknown) => Number(n))\n .filter((n: number) => Number.isFinite(n));\n return normalized.length > 0 ? { provider, vector: normalized } : null;\n } catch (err) {\n // Round 11 (Finding Ur_J): the !res.ok branch above throws\n // EmbeddingTimeoutError directly. Re-throw it here so the catch does\n // not swallow our own intentional signal back into a null return.\n if (isLookupBackendUnavailableError(err)) {\n throw err;\n }\n // AbortSignal.timeout throws a DOMException with name \"TimeoutError\";\n // surface at warn level so operators can distinguish slow backends from\n // generic errors.\n const isTimeout =\n err instanceof Error &&\n (err.name === \"TimeoutError\" || err.name === \"AbortError\");\n if (isTimeout) {\n log.warn(\n `embedding fallback fetch timed out after ${timeoutMs}ms (${provider.type}, mode=${mode})`,\n );\n // Round 9 fix (Finding UZqB): on the LOOKUP path a timeout means the\n // embedding backend is effectively unavailable — re-throw so that\n // search() propagates the error to semanticDedupLookup, which lets it\n // reach decideSemanticDedup's catch block and return\n // reason=\"backend_unavailable\". Without this, search() would silently\n // return [] and the per-batch batchBackendUnavailable flag would never\n // flip, causing subsequent facts in the same batch to each pay a full\n // timeout roundtrip (N × timeout instead of 1 × timeout).\n //\n // On the INDEX path a timeout is not fatal (the memory is already\n // persisted; index update can be skipped) — return null there so\n // indexFile() stays non-blocking.\n if (mode === \"lookup\") {\n throw new EmbeddingTimeoutError(\n `embedding backend timed out after ${timeoutMs}ms (${provider.type})`,\n );\n }\n } else {\n // Round 12 fix (PR #399 thread PRRT_kwDORJXyws56U6Gi): non-timeout\n // transport failures (ECONNREFUSED, DNS errors, TLS failures) are just\n // as fatal as timeouts on the LOOKUP path — the embedding backend is\n // effectively unreachable. Throw EmbeddingTimeoutError so that\n // search() (when called with throwOnTimeout:true) propagates the error\n // to decideSemanticDedup's backend_unavailable branch, activating the\n // per-batch short-circuit. Without this, each fact in the batch would\n // pay a full ECONNREFUSED roundtrip and return null → [] → no_candidates,\n // preventing batchBackendUnavailable from ever being set.\n //\n // On the INDEX path a transport failure is non-fatal — the memory is\n // already persisted; index update can be safely skipped.\n if (mode === \"lookup\") {\n log.warn(\n `embedding fallback transport error on lookup path (${provider.type}): ${err}`,\n );\n throw new EmbeddingTimeoutError(\n `embedding backend transport failure (${provider.type}): ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n log.debug(`embedding fallback error: ${err}`);\n }\n return null;\n }\n }\n\n private async embedWithHostProvider(\n input: string,\n provider: ProviderConfig,\n mode: EmbedMode,\n timeoutMs: number,\n ): Promise<number[] | null> {\n const hostProvider = provider.hostProvider;\n if (!hostProvider) return null;\n try {\n const vector = await hostProvider.embed(input.slice(0, 8000), {\n signal: AbortSignal.timeout(timeoutMs),\n inputType: mode === \"lookup\" ? \"query\" : \"document\",\n });\n return normalizeHostEmbeddingVector(vector);\n } catch (err) {\n log.debug(`host embedding provider error: ${hostProvider.id}: ${err}`);\n return null;\n }\n }\n\n /**\n * Load the authoritative generation for `provider`. STRICT: an unreadable,\n * malformed, foreign-shaped, or mixed-identity index throws\n * EmbeddingIndexStorageError instead of ever returning a partial view —\n * recall catches it at its boundary and fails open uncached; mutations\n * propagate it and fail closed. This.loaded is only ever assigned a fully\n * validated generation.\n */\n /**\n * A fence the store calls immediately before destructive writes: reasserts\n * THIS section's lock ownership after potentially long serialization.\n * Fail closed when no section is held — persisting unsynchronized would\n * reintroduce the lost-update race.\n */\n private generationFence(): () => Promise<void> {\n const section = this.lockSection;\n if (!section) {\n return async () => {\n throw new EmbeddingIndexStorageError(\n \"embedding index mutation attempted outside the generation lock; refusing to publish\",\n );\n };\n }\n return () => assertEmbeddingGenerationLockHeld(this.generationLockPath, section);\n }\n\n /**\n * Cache-warm path: a normal search serves the in-memory index WITHOUT the\n * lock (pre-existing staleness semantics: a peer swap between searches is\n * refreshed by the next cold load). On a cache miss the COMPLETE load runs\n * under the generation mutation lock so the enumeration + shard reads see\n * exactly one generation. The identity is re-checked under the lock on the\n * cold path; the caller has already performed any provider-swap embed\n * outside the lock.\n */\n private async loadIndexUnderGenerationLock(provider: ProviderConfig): Promise<EmbeddingIndexFile> {\n if (this.loaded && this.loadedFromDisk) return this.loaded;\n return await withEmbeddingGenerationLock(this.generationStateDir, async () => {\n // Another in-process consumer may have warmed the cache while this\n // call waited on the lock.\n if (this.loaded && this.loadedFromDisk) return this.loaded;\n // Re-check the on-disk identity UNDER the lock: a peer swap during the\n // caller's embed means the cold load must fail open, never serve a\n // mixed generation (codex PRRT_kwDORJXyws6mZ72p).\n const diskIdentity = await this.store.identityFromDisk();\n if (diskIdentity && !sameIndexIdentity(diskIdentity, provider)) {\n throw new EmbeddingIndexStorageError(\n `embedding index identity swapped to ${diskIdentity.provider}/${diskIdentity.model} during the cold load; failing open`,\n );\n }\n return await this.loadIndex(provider);\n });\n }\n\n private async loadIndex(provider: ProviderConfig): Promise<EmbeddingIndexFile> {\n if (this.loaded && this.loaded.provider === provider.type && this.loaded.model === provider.model) {\n return this.loaded;\n }\n\n const merged: Record<string, EmbeddingIndexEntry> = {};\n let diskIdentity: EmbeddingIndexIdentity | null = null;\n\n const layout = await this.store.detectLayout();\n if (layout === \"sharded\") {\n // Published generation: shards are the ONLY authoritative state. A\n // legacy embeddings.json left over by a crash between the atomic\n // publish and its recovery rename is never merged (single-generation\n // rule, issue #3146).\n diskIdentity = await this.store.readShardGenerationInto(merged);\n } else if (layout === \"legacy\") {\n const read = await this.store.readLegacy();\n if (read.outcome === \"ok\") {\n diskIdentity = { provider: read.file.provider, model: read.file.model };\n Object.assign(merged, read.file.entries);\n } else if (read.outcome === \"unreadable\") {\n await this.store.recordIndexStatusForLoad(read.reason);\n throw new EmbeddingIndexStorageError(\n `refusing to continue from an unreadable embedding index at ${this.store.legacyPath}: ${read.reason}`,\n );\n } else if (read.outcome === \"foreign\") {\n // Valid JSON but not an index we recognize (wrong version/shape).\n // Overwriting it would destroy unknown data, so mutation fails\n // closed; the file stays in place for recovery.\n await this.store.recordIndexStatusForLoad(\"unrecognized index format\");\n throw new EmbeddingIndexStorageError(\n `refusing to continue from a malformed embedding index at ${this.store.legacyPath} (unrecognized format); file preserved in place`,\n );\n }\n // absent falls through to a fresh index; a readable legacy index with\n // a different provider identity keeps the existing replace semantics\n // (gated by canReplaceIndexIdentity at the mutation sites).\n }\n\n if (diskIdentity && diskIdentity.provider === provider.type && diskIdentity.model === provider.model) {\n this.loaded = {\n version: 1,\n provider: provider.type,\n model: provider.model,\n entries: merged,\n };\n this.loadedFromDisk = true;\n return this.loaded;\n }\n\n this.loaded = {\n version: 1,\n provider: provider.type,\n model: provider.model,\n entries: {},\n };\n this.loadedFromDisk = false;\n return this.loaded;\n }\n\n private async readIndexIdentityFromDisk(): Promise<EmbeddingIndexIdentity | null> {\n const stamp = await this.store.identityStamp();\n if (this.loaded) {\n if (this.identityProbe?.stamp === stamp) {\n return { provider: this.loaded.provider, model: this.loaded.model };\n }\n this.loaded = null;\n this.loadedFromDisk = false;\n }\n if (this.identityProbe?.stamp === stamp) {\n return this.identityProbe.identity;\n }\n const identity = await this.store.identityFromDisk();\n this.identityProbe = { stamp, identity };\n return identity;\n }\n\n /**\n * Persist the index through the file store. On any failure the in-memory\n * cache is invalidated: entries mutated in the cached map must never be\n * mistaken for durable state by a retry or a later search.\n */\n private async saveIndex(\n index: EmbeddingIndexFile,\n opts: { touchedIds?: readonly string[]; memoryId?: string } = {},\n ): Promise<void> {\n try {\n await this.store.persist(index, { ...opts, fence: this.generationFence() });\n } catch (err) {\n this.loaded = null;\n this.loadedFromDisk = false;\n throw err;\n }\n this.loaded = index;\n this.loadedFromDisk = true;\n this.identityProbe = {\n stamp: await this.store.identityStamp(),\n identity: { provider: index.provider, model: index.model },\n };\n }\n}\n\nfunction toMemoryRelativePath(memoryDir: string, filePath: string): string {\n if (!path.isAbsolute(filePath)) return filePath;\n const rel = path.relative(memoryDir, filePath);\n return rel.startsWith(\"..\") ? filePath : rel;\n}\n\n/**\n * Normalize an index entry path to forward-slashes for stable prefix\n * comparison. Entries are stored as `path.relative(memoryDir, …)` output,\n * which on Windows uses back-slashes. Normalize both sides so prefix\n * matching is OS-independent.\n *\n * Also strip a leading `./` so this helper's output is symmetric with\n * `normalizePathPrefix` below. `toMemoryRelativePath` is a pass-through for\n * non-absolute filePath inputs, so an index entry could legitimately carry a\n * stored path like `\"./namespaces/alpha/facts/f.md\"`. Without this strip, a\n * caller-supplied prefix `\"./namespaces/alpha\"` (which `normalizePathPrefix`\n * rewrites to `\"namespaces/alpha/\"`) would silently miss that entry and\n * namespace-scoped dedup would either let a near-duplicate through or fail\n * to exclude a cross-namespace hit.\n */\nfunction normalizeEntryPath(p: string): string {\n let out = p.replace(/\\\\/g, \"/\");\n if (out.startsWith(\"./\")) out = out.slice(2);\n return out;\n}\n\n/**\n * Normalize a caller-supplied path prefix:\n * - Return `undefined` for nullish/empty input (no filter).\n * - Replace back-slashes with forward-slashes.\n * - Strip a leading `./`.\n * - Ensure a trailing `/` so `\"namespaces/a\"` doesn't accidentally match\n * `\"namespaces/another/…\"`.\n */\nfunction normalizePathPrefix(prefix: string | undefined): string | undefined {\n if (prefix === undefined || prefix === null) return undefined;\n let p = String(prefix).replace(/\\\\/g, \"/\");\n if (p.startsWith(\"./\")) p = p.slice(2);\n if (p.length === 0) return undefined;\n if (!p.endsWith(\"/\")) p = `${p}/`;\n return p;\n}\n\nfunction sameIndexIdentity(\n left: EmbeddingIndexComparable,\n right: EmbeddingIndexComparable,\n): boolean {\n return indexIdentityProvider(left) === indexIdentityProvider(right) && left.model === right.model;\n}\n\nfunction indexIdentityProvider(identity: EmbeddingIndexComparable): EmbeddingProviderType {\n return \"provider\" in identity ? identity.provider : identity.type;\n}\n\nfunction canReplaceIndexIdentity(\n existing: EmbeddingIndexIdentity,\n replacement: Pick<ProviderConfig, \"type\" | \"model\">,\n): boolean {\n return existing.provider === \"host\" && !sameIndexIdentity(existing, replacement);\n}\n\nfunction providerFromIndexIdentity(identity: EmbeddingIndexIdentity): ProviderConfig {\n return {\n type: identity.provider,\n model: identity.model,\n };\n}\n\nfunction cosineSimilarity(a: number[], b: number[]): number {\n const n = Math.min(a.length, b.length);\n if (n === 0) return 0;\n let dot = 0;\n let normA = 0;\n let normB = 0;\n for (let i = 0; i < n; i++) {\n const av = a[i] ?? 0;\n const bv = b[i] ?? 0;\n dot += av * bv;\n normA += av * av;\n normB += bv * bv;\n }\n const denom = Math.sqrt(normA) * Math.sqrt(normB);\n if (denom === 0) return 0;\n return dot / denom;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,UAAU;AAgDjB,IAAM,uBAAuB;AAuCtB,IAAM,wBAAN,cAAoC,MAAM;AAAA,EAC7B,OAAO;AAAA,EACzB,YAAY,S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AAiB,GAAa,GAAqB;AAC1D,QAAM,IAAI,KAAK,IAAI,EAAE,QAAQ,EAAE,MAAM;AACrC,MAAI,MAAM,EAAG,QAAO;AACpB,MAAI,MAAM;AACV,MAAI,QAAQ;AACZ,MAAI,QAAQ;AACZ,WAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,UAAM,KAAK,EAAE,CAAC,KAAK;AACnB,UAAM,KAAK,EAAE,CAAC,KAAK;AACnB,WAAO,KAAK;AACZ,aAAS,KAAK;AACd,aAAS,KAAK;AAAA,EAChB;AACA,QAAM,QAAQ,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,KAAK;AAChD,MAAI,UAAU,EAAG,QAAO;AACxB,SAAO,MAAM;AACf;","names":[]}
|
|
@@ -2,14 +2,14 @@ import {
|
|
|
2
2
|
OFFLINE_SYNC_SNAPSHOT_FORMAT,
|
|
3
3
|
filterOfflineSyncDeletionRevisions,
|
|
4
4
|
iterateOfflineSyncSnapshotFileRecords
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-5R4YPRAR.js";
|
|
6
6
|
import {
|
|
7
7
|
computeOmittedEmbeddingGenerationPaths,
|
|
8
8
|
embeddingGenerationMembership
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-GZ2KV2RO.js";
|
|
10
10
|
import {
|
|
11
11
|
matchesOfflineSyncDefaultExclude
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-63LFM77Z.js";
|
|
13
13
|
|
|
14
14
|
// src/offline-sync-snapshot-stream.ts
|
|
15
15
|
import { createHash } from "crypto";
|
|
@@ -61,4 +61,4 @@ async function buildEmbeddingAwareSnapshotStream(options) {
|
|
|
61
61
|
export {
|
|
62
62
|
buildEmbeddingAwareSnapshotStream
|
|
63
63
|
};
|
|
64
|
-
//# sourceMappingURL=chunk-
|
|
64
|
+
//# sourceMappingURL=chunk-2TCNEJ36.js.map
|
|
@@ -23,7 +23,7 @@ import {
|
|
|
23
23
|
import {
|
|
24
24
|
applyChangesetEmbeddingGenerations,
|
|
25
25
|
normalizeChangesetGenerations
|
|
26
|
-
} from "./chunk-
|
|
26
|
+
} from "./chunk-DB6XFMOF.js";
|
|
27
27
|
import {
|
|
28
28
|
applyIncomingEmbeddingGenerations,
|
|
29
29
|
assertEmbeddingGenerationStillIncluded,
|
|
@@ -32,10 +32,11 @@ import {
|
|
|
32
32
|
embeddingGenerationMembership,
|
|
33
33
|
isEmbeddingGenerationDirPath,
|
|
34
34
|
isPathInOmittedEmbeddingGeneration
|
|
35
|
-
} from "./chunk-
|
|
35
|
+
} from "./chunk-GZ2KV2RO.js";
|
|
36
36
|
import {
|
|
37
|
+
isEmbeddingGenerationMarkerPath,
|
|
37
38
|
matchesOfflineSyncDefaultExclude
|
|
38
|
-
} from "./chunk-
|
|
39
|
+
} from "./chunk-63LFM77Z.js";
|
|
39
40
|
import {
|
|
40
41
|
isCanonicalRuntimeStatePath,
|
|
41
42
|
shouldDeleteAbsentIncomingOfflineRuntimeFile,
|
|
@@ -1050,6 +1051,11 @@ async function applyOfflineSyncSnapshot(options) {
|
|
|
1050
1051
|
continue;
|
|
1051
1052
|
}
|
|
1052
1053
|
if (incoming) {
|
|
1054
|
+
if (isEmbeddingGenerationMarkerPath(relPath)) {
|
|
1055
|
+
nextBase.delete(relPath);
|
|
1056
|
+
skipped += 1;
|
|
1057
|
+
continue;
|
|
1058
|
+
}
|
|
1053
1059
|
if (currentEntry?.sha256 === incoming.sha256) {
|
|
1054
1060
|
if (await setSafeFileMtime(root, relPath, incoming.mtimeMs)) {
|
|
1055
1061
|
nextBase.set(relPath, toFileState(incoming));
|
|
@@ -1238,6 +1244,10 @@ async function applyOfflineSyncChangeset(options) {
|
|
|
1238
1244
|
for (const change of changeset.changes) {
|
|
1239
1245
|
if (generationRouting.conflictedPaths.has(change.path)) continue;
|
|
1240
1246
|
if (generationRouting.transactionHandled.has(change.path)) continue;
|
|
1247
|
+
if (isEmbeddingGenerationMarkerPath(change.path)) {
|
|
1248
|
+
skipped += 1;
|
|
1249
|
+
continue;
|
|
1250
|
+
}
|
|
1241
1251
|
const currentEntry = currentMap.get(change.path);
|
|
1242
1252
|
if (change.type === "upsert") {
|
|
1243
1253
|
if (currentEntry?.sha256 === change.file.sha256) {
|
|
@@ -1466,6 +1476,9 @@ async function applyOfflineSyncFileContentChunk(options) {
|
|
|
1466
1476
|
if (shouldExcludeRelPath(relPath, includeTranscripts)) {
|
|
1467
1477
|
throw new Error(`offline sync file content path is excluded: ${relPath}`);
|
|
1468
1478
|
}
|
|
1479
|
+
if (isEmbeddingGenerationMarkerPath(relPath)) {
|
|
1480
|
+
throw new Error(`offline sync file content path is node-local: ${relPath}`);
|
|
1481
|
+
}
|
|
1469
1482
|
const sha256 = assertSha256(options.sha256, "sha256");
|
|
1470
1483
|
const bytes = assertNonNegativeInteger(options.bytes, "bytes");
|
|
1471
1484
|
const mtimeMs = assertOfflineSyncMtimeMs(options.mtimeMs, "mtimeMs");
|
|
@@ -1774,4 +1787,4 @@ export {
|
|
|
1774
1787
|
normalizeOfflineSyncState,
|
|
1775
1788
|
fileStatesFromSnapshot
|
|
1776
1789
|
};
|
|
1777
|
-
//# sourceMappingURL=chunk-
|
|
1790
|
+
//# sourceMappingURL=chunk-5R4YPRAR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/offline-sync.ts"],"sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport {\n lstat,\n mkdir,\n open,\n readdir,\n readFile,\n rename,\n rm,\n stat,\n unlink,\n utimes,\n writeFile,\n} from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n DEFAULT_TRANSFER_EXCLUDE_DIRS,\n} from \"./transfer/exclusions.js\";\nimport {\n prepareSafeArchiveRoot,\n resolveSafeArchiveTarget,\n sha256Bytes,\n validateArchiveRelativePath,\n type SafeArchiveRoot,\n} from \"./transfer/fs-utils.js\";\nimport { parseFlexibleIsoTimestamp } from \"./utils/iso-timestamp.js\";\nimport { EmbeddingIndexStorageError } from \"./embedding-index-storage.js\";\nimport { isEmbeddingGenerationMarkerPath, matchesOfflineSyncDefaultExclude } from \"./offline-sync-exclude-globs.js\";\nimport {\n applyIncomingEmbeddingGenerations,\n assertEmbeddingGenerationStillIncluded,\n computeOmittedEmbeddingGenerationPaths,\n divergedEmbeddingGenerationDeferrals,\n embeddingGenerationMembership,\n isEmbeddingGenerationDirPath,\n isPathInOmittedEmbeddingGeneration,\n} from \"./offline-sync-embedding-generation.js\";\nimport {\n applyChangesetEmbeddingGenerations,\n normalizeChangesetGenerations,\n type OfflineSyncChangesetGeneration,\n} from \"./offline-sync-changeset-generations.js\";\nimport { withEmbeddingGenerationLock, withEmbeddingGenerationLockIter } from \"./embedding-generation-lock.js\";\nimport {\n isCanonicalRuntimeStatePath,\n shouldDeleteAbsentIncomingOfflineRuntimeFile,\n shouldPreferIncomingOfflineRuntimeFile,\n} from \"./offline-sync-runtime-state.js\";\nexport { shouldPreferIncomingOfflineRuntimeFile } from \"./offline-sync-runtime-state.js\";\nexport { computeOmittedEmbeddingGenerationPaths } from \"./offline-sync-embedding-generation.js\";\nexport type { OfflineSyncChangesetGeneration } from \"./offline-sync-changeset-generations.js\";\nexport {\n compileOfflineSyncExcludeGlobs,\n globToRegExp,\n parseOfflineSyncExcludes,\n} from \"./offline-sync-exclude-globs.js\";\nimport {\n isEncryptedOfflineSyncFile,\n readPlainOfflineSyncFileChunk,\n sha256OfflineSyncFile,\n shouldExcludeOfflineSyncFile,\n type OfflineSyncExcludeFile,\n type OfflineSyncFileTarget,\n plainFileDigest,\n SYNC_INTERNAL_DIR,\n setSafeFileMtime,\n assertNonNegativeFinite,\n assertOfflineSyncMtimeMs,\n OFFLINE_SYNC_FAST_BASE_MTIME_TOLERANCE_MS,\n} from \"./offline-sync-file-io.js\";\nimport { CENSUS_MAX_MTIME_MS, isSha256Hex } from \"./census-validation.js\";\nimport {\n cleanupOfflineUpload,\n digestOfflineUploadStagingContent,\n pruneOfflineUploadStaging,\n writeOfflineUploadChunk,\n writeSafeFileFromUpload,\n hashText,\n type OfflineUploadStaging,\n} from \"./offline-sync-upload-staging.js\";\nexport type { OfflineSyncExcludeFile, OfflineSyncFileTarget } from \"./offline-sync-file-io.js\";\n\nexport const OFFLINE_SYNC_SNAPSHOT_FORMAT = \"remnic.offline-sync.snapshot.v1\";\nexport const OFFLINE_SYNC_CHANGESET_FORMAT = \"remnic.offline-sync.changeset.v1\";\nexport const OFFLINE_SYNC_STATE_VERSION = 1;\nexport const OFFLINE_SYNC_FILE_CONTENT_MAX_CHUNK_BYTES = 64 * 1024 * 1024;\nexport const OFFLINE_SYNC_FILE_CONTENT_TRANSFER_CHUNK_BYTES = 8 * 1024 * 1024;\nexport const OFFLINE_SYNC_APPLY_MAX_BODY_BYTES = 16 * 1024 * 1024;\nexport const OFFLINE_SYNC_SNAPSHOT_BASE_MAX_BODY_BYTES = 64 * 1024 * 1024;\nexport const OFFLINE_SYNC_MAX_MTIME_MS = CENSUS_MAX_MTIME_MS;\n\nexport interface OfflineSyncFileState {\n path: string;\n sha256: string;\n /** Byte length of the transferable content, after any readFile hook such as secure-store decryption. */\n bytes: number;\n mtimeMs: number;\n}\n\nexport interface OfflineSyncFileRecord extends OfflineSyncFileState {\n contentBase64?: string;\n}\n\nexport interface OfflineSyncFileDigest {\n sha256: string;\n bytes: number;\n}\n\nexport interface OfflineSyncDeletionRevision {\n path: string;\n mtimeMs: number;\n}\n\nexport interface OfflineSyncSnapshot {\n format: typeof OFFLINE_SYNC_SNAPSHOT_FORMAT;\n schemaVersion: 1;\n createdAt: string;\n sourceId: string;\n includeTranscripts: boolean;\n files: OfflineSyncFileRecord[];\n deletions?: OfflineSyncDeletionRevision[];\n /**\n * Embedding generation dirs whose on-disk members were ALL omitted from\n * `files` because a push filter excluded at least one member (PR #3148\n * round 4). Their absence here is NOT a delete instruction: a receiver\n * keeps its local copy and its base entries until the generation is\n * pushed unfiltered or genuinely deleted with deletion metadata.\n */\n omittedEmbeddingGenerationDirs?: string[];\n}\n\nexport type OfflineSyncChange =\n | {\n type: \"upsert\";\n path: string;\n baseSha256?: string;\n file: OfflineSyncFileRecord & { contentBase64: string };\n }\n | {\n type: \"delete\";\n path: string;\n baseSha256: string;\n mtimeMs?: number;\n };\n\nexport interface OfflineSyncChangeset {\n format: typeof OFFLINE_SYNC_CHANGESET_FORMAT;\n schemaVersion: 1;\n createdAt: string;\n sourceId: string;\n includeTranscripts: boolean;\n changes: OfflineSyncChange[];\n /**\n * Complete post-change membership of every embedding generation the\n * changeset touches (issue #3150). Absent on legacy senders: receivers\n * defer manifest-less shard upserts as conflicts instead of publishing a\n * mixed generation.\n */\n embeddingGenerations?: OfflineSyncChangesetGeneration[];\n}\n\nexport interface OfflineSyncState {\n version: typeof OFFLINE_SYNC_STATE_VERSION;\n remoteId: string;\n namespace?: string;\n includeTranscripts: boolean;\n lastSyncedAt: string;\n baseFiles: OfflineSyncFileState[];\n}\n\nexport interface OfflineSyncConflict {\n path: string;\n reason:\n | \"both_modified\"\n | \"local_deleted_remote_modified\"\n | \"local_modified_remote_deleted\"\n | \"remote_exists_for_local_create\"\n | \"remote_changed_for_local_update\"\n | \"remote_deleted_for_local_update\"\n | \"remote_changed_for_local_delete\"\n // Changeset generation deferrals (#3150): the receiver refused a whole\n // embedding generation; surfaced as conflicts so the push side never\n // checkpoints it as applied.\n | \"embedding_generation_diverged\"\n | \"embedding_generation_manifest_required\";\n baseSha256?: string;\n localSha256?: string;\n incomingSha256?: string;\n conflictPath?: string;\n}\n\nexport interface OfflineSyncApplySnapshotResult {\n upserted: number;\n deleted: number;\n skipped: number;\n pendingLocal: number;\n conflicts: OfflineSyncConflict[];\n nextBaseFiles: OfflineSyncFileState[];\n}\n\nexport interface OfflineSyncApplyChangesetResult {\n appliedUpserts: number;\n appliedDeletes: number;\n skipped: number;\n conflicts: OfflineSyncConflict[];\n currentFiles: OfflineSyncFileState[];\n currentFilesComplete?: boolean;\n}\n\nexport interface OfflineSyncChangesetSummary {\n upserts: number;\n deletes: number;\n total: number;\n}\n\nexport interface OfflineSyncFileDeleteTarget extends OfflineSyncFileTarget {\n mtimeMs?: number;\n}\n\nexport type OfflineSyncRecordDeletionRevision = (\n target: OfflineSyncFileDeleteTarget & { mtimeMs: number },\n) => Promise<void>;\n\nexport interface OfflineSyncFileWriteTarget extends OfflineSyncFileTarget {\n content: Buffer;\n}\n\nexport interface OfflineSyncFileWriteChunksTarget extends OfflineSyncFileTarget {\n chunks: AsyncIterable<Buffer>;\n}\n\nexport interface OfflineSyncFileStagingWriteTarget extends OfflineSyncFileWriteTarget {\n /**\n * ABSOLUTE final path whose canonical AAD the staged ciphertext binds\n * (secure-store deployments): the offline-sync embedding generation\n * transaction stages under a staging dir and publishes by rename, so the\n * ciphertext must decrypt at the FINAL path. The AAD derives through the\n * same filePathAad logic as ordinary reads (platform-consistent).\n */\n finalAadFilePath?: string;\n}\n\nexport interface OfflineSyncFileStagingReadTarget extends OfflineSyncFileTarget {\n /** See {@link OfflineSyncFileStagingWriteTarget.finalAadFilePath}. */\n finalAadFilePath?: string;\n}\n\nexport interface OfflineSyncFileContentChunk extends Omit<OfflineSyncFileState, \"sha256\"> {\n sha256?: string;\n offset: number;\n chunkBytes: number;\n content: Buffer;\n}\n\nexport interface OfflineSyncApplyFileContentChunkResult {\n path: string;\n sha256: string;\n bytes: number;\n mtimeMs: number;\n offset: number;\n chunkBytes: number;\n done: boolean;\n applied: boolean;\n skipped: boolean;\n conflict?: OfflineSyncConflict;\n currentFile?: OfflineSyncFileState;\n}\n\ninterface OfflineSyncFileRecordOptions {\n root: SafeArchiveRoot;\n relPath: string;\n filePath: string;\n includeContent: boolean;\n readFile?: (target: OfflineSyncFileTarget) => Promise<Buffer>;\n readFileDigest?: (target: OfflineSyncFileTarget) => Promise<OfflineSyncFileDigest>;\n signal?: AbortSignal;\n}\n\nconst OFFLINE_SYNC_FAST_BASE_CTIME_TOLERANCE_MS = 1;\nconst EXCLUDED_FILE_NAMES = new Set([\n \".sync-state.json\",\n]);\n\nconst EXCLUDED_FILE_PREFIXES = [\n \".remnic-sync.\",\n \".remnic-sync-state.\",\n];\n\n/**\n * Convert a tiny subset of glob syntax (`*`, `**`, `?`, literal text) into a\n * regular expression anchored at the start and end of the input. The matcher\n * is intentionally narrow — it is only used for operator-supplied\n * `offlineSyncExcludes` entries, not for full shell-style globbing.\n * `*` and `?` match within a single path segment. `**` is cross-segment\n * wherever it appears: a `star-star-slash` prefix (leading or embedded)\n * matches zero or more whole segments, and a trailing `dir/star-star`\n * matches everything under `dir/` at any depth.\n */\n\n\nfunction sha256Buffer(buffer: Buffer): { sha256: string; bytes: number } {\n return sha256Bytes(buffer);\n}\n\nfunction throwIfOfflineSyncAborted(signal: AbortSignal | undefined): void {\n if (!signal?.aborted) return;\n throw new Error(\"offline sync request aborted\");\n}\n\nfunction compareByPath<T extends { path: string }>(left: T, right: T): number {\n return left.path.localeCompare(right.path);\n}\n\nfunction assertSha256(value: unknown, field: string): string {\n if (!isSha256Hex(value)) {\n throw new Error(`${field} must be a 64-character sha256 hex string`);\n }\n return value.toLowerCase();\n}\n\nfunction assertNonNegativeInteger(value: unknown, field: string): number {\n if (\n typeof value !== \"number\" ||\n !Number.isFinite(value) ||\n !Number.isInteger(value) ||\n value < 0\n ) {\n throw new Error(`${field} must be a non-negative integer`);\n }\n return value;\n}\n\n\n\nfunction assertBoolean(value: unknown, field: string): boolean {\n if (typeof value !== \"boolean\") {\n throw new Error(`${field} must be a boolean`);\n }\n return value;\n}\n\nfunction normalizeSourceId(value: unknown, field: string): string {\n if (typeof value !== \"string\" || value.trim().length === 0 || value.length > 512) {\n throw new Error(`${field} must be a non-empty string no longer than 512 characters`);\n }\n return value.trim();\n}\n\nfunction normalizeFileState(input: unknown, fieldPrefix: string): OfflineSyncFileState {\n if (!input || typeof input !== \"object\" || Array.isArray(input)) {\n throw new Error(`${fieldPrefix} must be an object`);\n }\n const obj = input as Record<string, unknown>;\n const relPath = normalizeRelativePath(obj.path, `${fieldPrefix}.path`);\n return {\n path: relPath,\n sha256: assertSha256(obj.sha256, `${fieldPrefix}.sha256`),\n bytes: assertNonNegativeInteger(obj.bytes, `${fieldPrefix}.bytes`),\n mtimeMs: assertOfflineSyncMtimeMs(obj.mtimeMs, `${fieldPrefix}.mtimeMs`),\n };\n}\n\nfunction normalizeFileRecord(\n input: unknown,\n fieldPrefix: string,\n requireContent: boolean,\n): OfflineSyncFileRecord {\n const state = normalizeFileState(input, fieldPrefix);\n const obj = input as Record<string, unknown>;\n const contentBase64 = obj.contentBase64;\n if (requireContent && typeof contentBase64 !== \"string\") {\n throw new Error(`${fieldPrefix}.contentBase64 is required`);\n }\n if (contentBase64 !== undefined && typeof contentBase64 !== \"string\") {\n throw new Error(`${fieldPrefix}.contentBase64 must be a base64 string`);\n }\n return {\n ...state,\n ...(contentBase64 !== undefined ? { contentBase64 } : {}),\n };\n}\n\nfunction normalizeFileStates(input: readonly unknown[] | undefined): OfflineSyncFileState[] {\n if (!input) return [];\n if (!Array.isArray(input)) {\n throw new Error(\"baseFiles must be an array\");\n }\n return input.map((entry, index) => normalizeFileState(entry, `baseFiles[${index}]`));\n}\n\nfunction normalizeDeletionRevisions(\n input: unknown,\n fieldPrefix: string,\n): OfflineSyncDeletionRevision[] | undefined {\n if (input === undefined) return undefined;\n if (!Array.isArray(input)) {\n throw new Error(`${fieldPrefix} must be an array`);\n }\n const deletions = input.map((entry, index): OfflineSyncDeletionRevision => {\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) {\n throw new Error(`${fieldPrefix}[${index}] must be an object`);\n }\n const obj = entry as Record<string, unknown>;\n return {\n path: normalizeRelativePath(obj.path, `${fieldPrefix}[${index}].path`),\n mtimeMs: assertOfflineSyncMtimeMs(obj.mtimeMs, `${fieldPrefix}[${index}].mtimeMs`),\n };\n });\n assertUniquePaths(deletions, fieldPrefix);\n return deletions.sort(compareByPath);\n}\n\nfunction snapshotBuilderDeletions(options: {\n deletions?: readonly OfflineSyncDeletionRevision[];\n files: readonly OfflineSyncFileState[];\n paths?: readonly string[];\n includeTranscripts: boolean;\n excludeNodeLocalState?: boolean;\n userExcludeRegexps?: readonly RegExp[];\n /** Generation dirs omitted by the push enumeration (PR #3148): revisions\n * for ANY member — including already-absent ones — are suppressed, so a\n * filtered generation can never be announced as deleted. */\n omittedGenerationDirs?: ReadonlySet<string>;\n}): OfflineSyncDeletionRevision[] | undefined {\n const deletions = normalizeDeletionRevisions(options.deletions, \"deletions\");\n if (deletions === undefined) return undefined;\n if (deletions.length === 0) return deletions;\n const presentPaths = new Set(options.files.map((file) => file.path.toLowerCase()));\n const scopedPaths = options.paths\n ? new Set(options.paths.map((relPath) => relPath.toLowerCase()))\n : undefined;\n return deletions.filter((deletion) =>\n (scopedPaths === undefined || scopedPaths.has(deletion.path.toLowerCase())) &&\n !presentPaths.has(deletion.path.toLowerCase()) &&\n !isDeletionInOmittedGeneration(deletion.path, options.omittedGenerationDirs) &&\n !(options.excludeNodeLocalState === false\n ? shouldExcludeRelPath(deletion.path, options.includeTranscripts)\n : shouldExcludePushRelPath(\n deletion.path,\n options.includeTranscripts,\n options.userExcludeRegexps,\n )));\n}\n\nfunction isDeletionInOmittedGeneration(\n relPath: string,\n omittedGenerationDirs: ReadonlySet<string> | undefined,\n): boolean {\n if (!omittedGenerationDirs || omittedGenerationDirs.size === 0) return false;\n const membership = embeddingGenerationMembership(relPath);\n return membership !== null && omittedGenerationDirs.has(membership.shardDir);\n}\n\nexport async function filterOfflineSyncDeletionRevisions(options: {\n root: string;\n deletions: readonly OfflineSyncDeletionRevision[];\n includeTranscripts?: boolean;\n userExcludeRegexps?: readonly RegExp[];\n excludeFile?: OfflineSyncExcludeFile;\n}): Promise<OfflineSyncDeletionRevision[]> {\n const deletions = normalizeDeletionRevisions(options.deletions, \"deletions\");\n if (deletions === undefined) throw new Error(\"deletions must be an array\");\n if (deletions.length === 0) return deletions;\n const root = await prepareSafeArchiveRoot(\n path.resolve(options.root),\n \"filterOfflineSyncDeletionRevisions\",\n \"root\",\n );\n const includeTranscripts = options.includeTranscripts !== false;\n const omission = await computeOmittedEmbeddingGenerationPaths({\n rootAbs: root.abs,\n userExcludeRegexps: options.userExcludeRegexps,\n excludeFile: options.excludeFile,\n isExcludedRelPath: (relPath) =>\n shouldExcludePushRelPath(relPath, includeTranscripts, options.userExcludeRegexps),\n });\n const omittedDirs = new Set(omission.omittedDirs);\n const filtered: OfflineSyncDeletionRevision[] = [];\n for (const deletion of deletions) {\n if (\n shouldExcludePushRelPath(deletion.path, includeTranscripts, options.userExcludeRegexps) ||\n isDeletionInOmittedGeneration(deletion.path, omittedDirs)\n ) {\n continue;\n }\n const filePath = path.join(root.abs, ...deletion.path.split(\"/\"));\n const present = await lstat(filePath).then(\n () => true,\n (error: unknown) => {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return false;\n throw error;\n },\n );\n if (!present) filtered.push(deletion);\n }\n return filtered;\n}\n\nexport function normalizeOfflineSyncSnapshot(\n input: unknown,\n options: { requireContent?: boolean } = {},\n): OfflineSyncSnapshot {\n if (!input || typeof input !== \"object\" || Array.isArray(input)) {\n throw new Error(\"offline sync snapshot must be an object\");\n }\n const obj = input as Record<string, unknown>;\n if (obj.format !== OFFLINE_SYNC_SNAPSHOT_FORMAT) {\n throw new Error(`offline sync snapshot format must be ${OFFLINE_SYNC_SNAPSHOT_FORMAT}`);\n }\n if (obj.schemaVersion !== 1) {\n throw new Error(\"offline sync snapshot schemaVersion must be 1\");\n }\n const createdAt = normalizeIsoString(obj.createdAt, \"createdAt\");\n const sourceId = normalizeSourceId(obj.sourceId, \"sourceId\");\n const includeTranscripts = assertBoolean(obj.includeTranscripts, \"includeTranscripts\");\n if (!Array.isArray(obj.files)) {\n throw new Error(\"offline sync snapshot files must be an array\");\n }\n const files = obj.files\n .map((entry, index) =>\n normalizeFileRecord(entry, `files[${index}]`, options.requireContent === true))\n .filter((file) => !shouldIgnoreIncomingRuntimePath(file.path))\n .sort(compareByPath);\n const deletions = normalizeDeletionRevisions(obj.deletions, \"deletions\")\n ?.filter((deletion) => !shouldIgnoreIncomingRuntimePath(deletion.path));\n const entries = deletions && deletions.length > 0 ? [...files, ...deletions] : files;\n assertUniquePaths(entries, \"offline sync snapshot\");\n if (!includeTranscripts) {\n const transcriptPath = entries\n .find((entry) => entry.path.split(\"/\")[0] === \"transcripts\")?.path;\n if (transcriptPath) {\n throw new Error(\n `offline sync snapshot includeTranscripts is false but contains transcript path: ${transcriptPath}`,\n );\n }\n }\n const excludedPath = entries\n .find((entry) => shouldExcludeRelPath(entry.path, true))?.path;\n if (excludedPath) {\n throw new Error(`offline sync snapshot contains excluded path: ${excludedPath}`);\n }\n let omittedEmbeddingGenerationDirs: string[] | undefined;\n if (obj.omittedEmbeddingGenerationDirs !== undefined) {\n if (!Array.isArray(obj.omittedEmbeddingGenerationDirs)) {\n throw new Error(\"offline sync snapshot omittedEmbeddingGenerationDirs must be an array\");\n }\n const seenDirs = new Set<string>();\n for (const [index, entry] of obj.omittedEmbeddingGenerationDirs.entries()) {\n if (\n typeof entry !== \"string\" ||\n !isEmbeddingGenerationDirPath(entry) ||\n seenDirs.has(entry)\n ) {\n throw new Error(\n `omittedEmbeddingGenerationDirs[${index}] must be a unique canonical embeddings generation dir`,\n );\n }\n seenDirs.add(entry);\n }\n omittedEmbeddingGenerationDirs = [...seenDirs].sort((left, right) => left.localeCompare(right));\n }\n return {\n format: OFFLINE_SYNC_SNAPSHOT_FORMAT,\n schemaVersion: 1,\n createdAt,\n sourceId,\n includeTranscripts,\n files,\n ...(deletions === undefined ? {} : { deletions }),\n ...(omittedEmbeddingGenerationDirs === undefined ? {} : { omittedEmbeddingGenerationDirs }),\n };\n}\n\nexport function normalizeOfflineSyncChangeset(\n input: unknown,\n): OfflineSyncChangeset {\n if (!input || typeof input !== \"object\" || Array.isArray(input)) {\n throw new Error(\"offline sync changeset must be an object\");\n }\n const obj = input as Record<string, unknown>;\n if (obj.format !== OFFLINE_SYNC_CHANGESET_FORMAT) {\n throw new Error(`offline sync changeset format must be ${OFFLINE_SYNC_CHANGESET_FORMAT}`);\n }\n if (obj.schemaVersion !== 1) {\n throw new Error(\"offline sync changeset schemaVersion must be 1\");\n }\n const createdAt = normalizeIsoString(obj.createdAt, \"createdAt\");\n const sourceId = normalizeSourceId(obj.sourceId, \"sourceId\");\n const includeTranscripts = assertBoolean(obj.includeTranscripts, \"includeTranscripts\");\n if (!Array.isArray(obj.changes)) {\n throw new Error(\"offline sync changeset changes must be an array\");\n }\n const changes = obj.changes.map((entry, index): OfflineSyncChange => {\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) {\n throw new Error(`changes[${index}] must be an object`);\n }\n const change = entry as Record<string, unknown>;\n const type = change.type;\n const relPath = normalizeRelativePath(change.path, `changes[${index}].path`);\n if (type === \"upsert\") {\n const file = normalizeFileRecord(\n change.file,\n `changes[${index}].file`,\n true,\n ) as OfflineSyncFileRecord & { contentBase64: string };\n if (file.path !== relPath) {\n throw new Error(`changes[${index}].file.path must match changes[${index}].path`);\n }\n const baseSha256 =\n change.baseSha256 === undefined\n ? undefined\n : assertSha256(change.baseSha256, `changes[${index}].baseSha256`);\n return {\n type: \"upsert\",\n path: relPath,\n ...(baseSha256 ? { baseSha256 } : {}),\n file,\n };\n }\n if (type === \"delete\") {\n const mtimeMs = change.mtimeMs === undefined\n ? undefined\n : assertOfflineSyncMtimeMs(change.mtimeMs, `changes[${index}].mtimeMs`);\n return {\n type: \"delete\",\n path: relPath,\n baseSha256: assertSha256(change.baseSha256, `changes[${index}].baseSha256`),\n ...(mtimeMs === undefined ? {} : { mtimeMs }),\n };\n }\n throw new Error(`changes[${index}].type must be \"upsert\" or \"delete\"`);\n }).filter((change) => !shouldIgnoreIncomingRuntimePath(change.path));\n assertUniquePaths(changes, \"offline sync changeset\");\n if (!includeTranscripts) {\n const transcriptPath = changes.find((change) => change.path.split(\"/\")[0] === \"transcripts\")?.path;\n if (transcriptPath) {\n throw new Error(\n `offline sync changeset includeTranscripts is false but contains transcript path: ${transcriptPath}`,\n );\n }\n }\n const excludedPath = changes.find((change) => shouldExcludeRelPath(change.path, true))?.path;\n if (excludedPath) {\n throw new Error(`offline sync changeset contains excluded path: ${excludedPath}`);\n }\n const embeddingGenerations = normalizeChangesetGenerations(obj.embeddingGenerations, changes);\n return {\n format: OFFLINE_SYNC_CHANGESET_FORMAT,\n schemaVersion: 1,\n createdAt,\n sourceId,\n includeTranscripts,\n changes: changes.sort(compareByPath),\n ...(embeddingGenerations === undefined ? {} : { embeddingGenerations }),\n };\n}\n\nfunction normalizeIsoString(input: unknown, field: string): string {\n if (typeof input !== \"string\" || input.trim().length === 0) {\n throw new Error(`${field} must be an ISO timestamp string`);\n }\n const parsed = parseFlexibleIsoTimestamp(input.trim());\n if (parsed === null) {\n throw new Error(`${field} must be a parseable ISO timestamp`);\n }\n return new Date(parsed).toISOString();\n}\n\nfunction normalizeRelativePath(input: unknown, field: string): string {\n if (typeof input !== \"string\") {\n throw new Error(`${field} must be a POSIX relative path string`);\n }\n return validateArchiveRelativePath(input, field);\n}\n\nfunction assertUniquePaths(entries: readonly { path: string }[], context: string): void {\n const seen = new Set<string>();\n for (const entry of entries) {\n const key = entry.path.toLowerCase();\n if (seen.has(key)) {\n throw new Error(`${context} contains duplicate path: ${entry.path}`);\n }\n seen.add(key);\n }\n}\n\nexport function isInternalRemnicStatePath(relPosix: string): boolean {\n const normalized = relPosix.includes(\"\\\\\") ? relPosix.replaceAll(\"\\\\\", \"/\") : relPosix;\n return normalized === \".remnic\"\n || normalized.startsWith(\".remnic/\")\n || normalized.endsWith(\"/.remnic\")\n || normalized.includes(\"/.remnic/\");\n}\n\nfunction shouldExcludeRelPath(relPosix: string, includeTranscripts: boolean): boolean {\n if (isInternalRemnicStatePath(relPosix)) return true;\n const parts = relPosix.split(\"/\");\n if (parts.some((part) => DEFAULT_TRANSFER_EXCLUDE_DIRS.has(part))) return true;\n if (parts.some((part) => part === SYNC_INTERNAL_DIR)) return true;\n if (!includeTranscripts && parts[0] === \"transcripts\") return true;\n const basename = parts[parts.length - 1] ?? \"\";\n if (isCanonicalRuntimeStatePath(parts) && basename.includes(\".tmp-\")) return true;\n if (EXCLUDED_FILE_NAMES.has(basename)) return true;\n if (EXCLUDED_FILE_PREFIXES.some((prefix) => basename.startsWith(prefix))) return true;\n return false;\n}\n\n/**\n * Push-side variant of `shouldExcludeRelPath` for issue #1786. Combines the\n * legacy structural exclude (private dirs, sync internal, tmp runtime state,\n * excluded file names/prefixes) with the new push-only exclusion layers:\n * - the `state/*.sqlite`, `state/index_tags.json`, etc. defaults that\n * describe node-local runtime state each node rebuilds from synced\n * records, and\n * - operator-supplied `offlineSyncExcludes` regexps.\n *\n * Used ONLY by push-side enumeration/validation paths. Apply-side callers\n * must use the legacy `shouldExcludeRelPath` so a remote snapshot containing\n * `state/lcm.sqlite` can still be accepted on first sync -- the remote's\n * view is authoritative for that file until the local LCM is bootstrapped.\n */\nfunction shouldExcludePushRelPath(\n relPosix: string,\n includeTranscripts: boolean,\n userExcludeRegexps?: readonly RegExp[],\n): boolean {\n if (shouldExcludeRelPath(relPosix, includeTranscripts)) return true;\n // Issue #1786: node-local runtime state (live sqlite, derived indexes,\n // per-node governance run logs) is rebuilt by each node, never synced.\n if (matchesOfflineSyncDefaultExclude(relPosix)) return true;\n if (userExcludeRegexps && userExcludeRegexps.some((re) => re.test(relPosix))) return true;\n return false;\n}\n\n// Precompiled once at module load — this check sits on the hot\n// enumeration path for every walked file (Kilo review, PR #1793).\n\n\n/**\n * Compile operator-supplied `offlineSyncExcludes` glob strings into a\n * pre-validated array of regular expressions. Empty input is allowed and\n * returns an empty list. Throws on any invalid entry — callers should treat\n * a thrown error as a fatal configuration mistake and refuse to start the\n * sync run rather than silently dropping the bad entry.\n */\n\nfunction shouldIgnoreIncomingRuntimePath(relPosix: string): boolean {\n if (isInternalRemnicStatePath(relPosix)) return true;\n const parts = relPosix.split(\"/\");\n const basename = parts[parts.length - 1] ?? \"\";\n return isCanonicalRuntimeStatePath(parts) && basename.includes(\".tmp-\");\n}\n\nfunction filterBaseFilesForMode(\n files: readonly OfflineSyncFileState[],\n includeTranscripts: boolean,\n): OfflineSyncFileState[] {\n return files.filter((file) => !shouldExcludeRelPath(file.path, includeTranscripts));\n}\n\nfunction canReuseFastBaseFileState(\n baseEntry: OfflineSyncFileState,\n st: { size: number; mtimeMs: number; ctimeMs: number },\n baseCapturedAtMs: number | null,\n): boolean {\n if (baseEntry.bytes !== st.size) return false;\n if (Math.abs(baseEntry.mtimeMs - st.mtimeMs) > OFFLINE_SYNC_FAST_BASE_MTIME_TOLERANCE_MS) {\n return false;\n }\n if (baseCapturedAtMs === null) return false;\n // Node reports stat times as fractional milliseconds while Date snapshots are\n // whole milliseconds, so allow only a tiny precision window around capture.\n return st.ctimeMs - baseCapturedAtMs <= OFFLINE_SYNC_FAST_BASE_CTIME_TOLERANCE_MS;\n}\n\nasync function canReuseFastBaseFileStateFromDisk(\n baseEntry: OfflineSyncFileState,\n st: { size: number; mtimeMs: number; ctimeMs: number },\n baseCapturedAtMs: number | null,\n): Promise<boolean> {\n return canReuseFastBaseFileState(baseEntry, st, baseCapturedAtMs);\n}\n\nasync function readOfflineSyncFileRecord(\n options: OfflineSyncFileRecordOptions,\n): Promise<OfflineSyncFileRecord> {\n throwIfOfflineSyncAborted(options.signal);\n const relPath = validateArchiveRelativePath(options.relPath, \"offlineSyncFile.path\");\n let content: Buffer | null = null;\n let digest: OfflineSyncFileDigest;\n if (options.includeContent) {\n content = options.readFile\n ? await options.readFile({ root: options.root.abs, path: relPath, filePath: options.filePath })\n : await readFile(options.filePath);\n throwIfOfflineSyncAborted(options.signal);\n digest = sha256Buffer(content);\n } else if (options.readFileDigest) {\n digest = await options.readFileDigest({ root: options.root.abs, path: relPath, filePath: options.filePath });\n throwIfOfflineSyncAborted(options.signal);\n } else if (options.readFile) {\n content = await options.readFile({ root: options.root.abs, path: relPath, filePath: options.filePath });\n throwIfOfflineSyncAborted(options.signal);\n digest = sha256Buffer(content);\n content = null;\n } else {\n digest = await sha256OfflineSyncFile(options.filePath, options.signal);\n }\n throwIfOfflineSyncAborted(options.signal);\n const st = await stat(options.filePath);\n return {\n path: relPath,\n sha256: digest.sha256,\n bytes: digest.bytes,\n mtimeMs: st.mtimeMs,\n ...(content ? { contentBase64: content.toString(\"base64\") } : {}),\n };\n}\n\nexport async function* iterateOfflineSyncSnapshotFileRecords(options: {\n root: string;\n includeContent?: boolean;\n includeTranscripts?: boolean;\n readFile?: (target: OfflineSyncFileTarget) => Promise<Buffer>;\n readFileDigest?: (target: OfflineSyncFileTarget) => Promise<OfflineSyncFileDigest>;\n excludeFile?: OfflineSyncExcludeFile;\n userExcludeRegexps?: readonly RegExp[];\n /**\n * Precomputed whole-generation omission set (PR #3148 round 4): paths the\n * walk must skip because their embedding generation lost ANY member to a\n * push filter. When omitted and push excludes are active, the set is\n * computed here so streaming census consumers get the same semantics.\n */\n skipEmbeddingGenerationPaths?: ReadonlySet<string>;\n /**\n * When false, enumeration uses only the legacy structural excludes —\n * the apply/pull-side view of local files. Push-side callers keep the\n * default (true): built-in node-local state excludes + user excludes.\n * (Cursor review on PR #1793: apply-side local enumeration must see\n * files like state/lcm.sqlite or merges misclassify them.)\n */\n excludeNodeLocalState?: boolean;\n signal?: AbortSignal;\n}): AsyncIterable<OfflineSyncFileRecord> {\n throwIfOfflineSyncAborted(options.signal);\n const rootAbs = path.resolve(options.root);\n const root = await prepareSafeArchiveRoot(rootAbs, \"iterateOfflineSyncSnapshotFileRecords\", \"root\");\n const includeTranscripts = options.includeTranscripts !== false;\n const pushExcludes = options.excludeNodeLocalState !== false;\n const skipGenerationPaths = options.skipEmbeddingGenerationPaths ??\n (pushExcludes\n ? (await computeOmittedEmbeddingGenerationPaths({\n rootAbs: root.abs,\n userExcludeRegexps: options.userExcludeRegexps,\n excludeFile: options.excludeFile,\n isExcludedRelPath: (relPath) =>\n shouldExcludePushRelPath(relPath, includeTranscripts, options.userExcludeRegexps),\n })).omittedPaths\n : undefined);\n\n async function* walk(dirAbs: string, includeContent = options.includeContent === true): AsyncIterable<OfflineSyncFileRecord> {\n throwIfOfflineSyncAborted(options.signal);\n let entries = await readdir(dirAbs, { withFileTypes: true });\n entries = entries.sort((left, right) => left.name.localeCompare(right.name));\n for (const entry of entries) {\n const abs = path.join(dirAbs, entry.name);\n const relPosix = path.relative(root.abs, abs).split(path.sep).join(\"/\");\n if (\n options.excludeNodeLocalState === false\n ? shouldExcludeRelPath(relPosix, includeTranscripts)\n : shouldExcludePushRelPath(relPosix, includeTranscripts, options.userExcludeRegexps)\n ) continue;\n if (skipGenerationPaths?.has(relPosix)) continue;\n if (entry.isSymbolicLink()) continue;\n if (entry.isDirectory()) {\n if (isEmbeddingGenerationDirPath(relPosix)) {\n yield* withEmbeddingGenerationLockIter(path.dirname(abs), (content) => walk(abs, content), includeContent,\n () => assertEmbeddingGenerationStillIncluded(root.abs, relPosix, options.excludeFile,\n (rel) => shouldExcludePushRelPath(rel, includeTranscripts, options.userExcludeRegexps),\n []));\n continue;\n }\n yield* walk(abs, includeContent);\n continue;\n }\n if (!entry.isFile()) continue;\n if (await shouldExcludeOfflineSyncFile(options.excludeFile, {\n root: root.abs,\n path: relPosix,\n filePath: abs,\n })) continue;\n yield await readOfflineSyncFileRecord({\n root,\n relPath: relPosix,\n filePath: abs,\n includeContent,\n readFile: options.readFile,\n readFileDigest: options.readFileDigest,\n signal: options.signal,\n });\n }\n }\n\n yield* walk(root.abs);\n}\n\nexport async function buildOfflineSyncSnapshot(options: {\n root: string;\n sourceId: string;\n includeContent?: boolean;\n deletions?: readonly OfflineSyncDeletionRevision[];\n includeTranscripts?: boolean;\n now?: Date;\n readFile?: (target: OfflineSyncFileTarget) => Promise<Buffer>;\n readFileDigest?: (target: OfflineSyncFileTarget) => Promise<OfflineSyncFileDigest>;\n excludeFile?: OfflineSyncExcludeFile;\n userExcludeRegexps?: readonly RegExp[];\n /**\n * When false, enumeration uses only the legacy structural excludes —\n * the apply/pull-side view of local files. Push-side callers keep the\n * default (true): built-in node-local state excludes + user excludes.\n * (Cursor review on PR #1793: apply-side local enumeration must see\n * files like state/lcm.sqlite or merges misclassify them.)\n */\n excludeNodeLocalState?: boolean;\n signal?: AbortSignal;\n}): Promise<OfflineSyncSnapshot> {\n throwIfOfflineSyncAborted(options.signal);\n const includeTranscripts = options.includeTranscripts !== false;\n const pushExcludes = options.excludeNodeLocalState !== false;\n const normalizedDeletions = normalizeDeletionRevisions(options.deletions, \"deletions\");\n const omission = pushExcludes\n ? await computeOmittedEmbeddingGenerationPaths({\n rootAbs: path.resolve(options.root),\n userExcludeRegexps: options.userExcludeRegexps,\n excludeFile: options.excludeFile,\n tombstonedPaths: (normalizedDeletions ?? []).map((deletion) => deletion.path),\n isExcludedRelPath: (relPath) =>\n shouldExcludePushRelPath(relPath, includeTranscripts, options.userExcludeRegexps),\n })\n : undefined;\n const files: OfflineSyncFileRecord[] = [];\n for await (const file of iterateOfflineSyncSnapshotFileRecords({\n ...options,\n skipEmbeddingGenerationPaths: omission?.omittedPaths,\n })) files.push(file);\n throwIfOfflineSyncAborted(options.signal);\n\n const sortedFiles = files.sort(compareByPath);\n const deletions = snapshotBuilderDeletions({\n deletions: options.deletions,\n files: sortedFiles,\n includeTranscripts,\n excludeNodeLocalState: options.excludeNodeLocalState,\n userExcludeRegexps: options.userExcludeRegexps,\n omittedGenerationDirs: omission && omission.omittedDirs.length > 0\n ? new Set(omission.omittedDirs)\n : undefined,\n });\n return {\n format: OFFLINE_SYNC_SNAPSHOT_FORMAT,\n schemaVersion: 1,\n createdAt: (options.now ?? new Date()).toISOString(),\n sourceId: normalizeSourceId(options.sourceId, \"sourceId\"),\n includeTranscripts,\n files: sortedFiles,\n ...(deletions === undefined ? {} : { deletions }),\n ...(omission && omission.omittedDirs.length > 0\n ? { omittedEmbeddingGenerationDirs: omission.omittedDirs }\n : {}),\n };\n}\n\nexport async function buildOfflineSyncSnapshotFromBase(options: {\n root: string;\n sourceId: string;\n baseFiles?: readonly OfflineSyncFileState[];\n deletions?: readonly OfflineSyncDeletionRevision[];\n baseCapturedAt?: Date;\n includeContent?: boolean;\n includeTranscripts?: boolean;\n now?: Date;\n readFile?: (target: OfflineSyncFileTarget) => Promise<Buffer>;\n readFileDigest?: (target: OfflineSyncFileTarget) => Promise<OfflineSyncFileDigest>;\n excludeFile?: OfflineSyncExcludeFile;\n userExcludeRegexps?: readonly RegExp[];\n /**\n * When false, enumeration uses only the legacy structural excludes —\n * the apply/pull-side view of local files. Push-side callers keep the\n * default (true): built-in node-local state excludes + user excludes.\n * (Cursor review on PR #1793: apply-side local enumeration must see\n * files like state/lcm.sqlite or merges misclassify them.)\n */\n excludeNodeLocalState?: boolean;\n signal?: AbortSignal;\n}): Promise<OfflineSyncSnapshot> {\n throwIfOfflineSyncAborted(options.signal);\n const rootAbs = path.resolve(options.root);\n const root = await prepareSafeArchiveRoot(rootAbs, \"buildOfflineSyncSnapshotFromBase\", \"root\");\n const includeTranscripts = options.includeTranscripts !== false;\n const base = byPath(filterBaseFilesForMode(\n normalizeFileStates(options.baseFiles),\n includeTranscripts,\n ));\n const rawBaseCapturedAtMs = options.baseCapturedAt?.getTime();\n const baseCapturedAtMs = rawBaseCapturedAtMs !== undefined && Number.isFinite(rawBaseCapturedAtMs)\n ? rawBaseCapturedAtMs\n : null;\n const pushExcludes = options.excludeNodeLocalState !== false;\n const normalizedDeletions = normalizeDeletionRevisions(options.deletions, \"deletions\");\n const omission = pushExcludes\n ? await computeOmittedEmbeddingGenerationPaths({\n rootAbs: root.abs,\n userExcludeRegexps: options.userExcludeRegexps,\n excludeFile: options.excludeFile,\n tombstonedPaths: (normalizedDeletions ?? []).map((deletion) => deletion.path),\n isExcludedRelPath: (relPath) =>\n shouldExcludePushRelPath(relPath, includeTranscripts, options.userExcludeRegexps),\n })\n : undefined;\n const files: OfflineSyncFileRecord[] = [];\n\n async function walk(dirAbs: string): Promise<void> {\n throwIfOfflineSyncAborted(options.signal);\n let entries = await readdir(dirAbs, { withFileTypes: true });\n entries = entries.sort((left, right) => left.name.localeCompare(right.name));\n for (const entry of entries) {\n throwIfOfflineSyncAborted(options.signal);\n const abs = path.join(dirAbs, entry.name);\n const relPosix = path.relative(root.abs, abs).split(path.sep).join(\"/\");\n if (\n options.excludeNodeLocalState === false\n ? shouldExcludeRelPath(relPosix, includeTranscripts)\n : shouldExcludePushRelPath(relPosix, includeTranscripts, options.userExcludeRegexps)\n ) continue;\n if (omission?.omittedPaths.has(relPosix)) continue;\n if (entry.isSymbolicLink()) continue;\n if (entry.isDirectory()) {\n if (isEmbeddingGenerationDirPath(relPosix)) {\n await withEmbeddingGenerationLock(path.dirname(abs), async () => {\n await assertEmbeddingGenerationStillIncluded(root.abs, relPosix, options.excludeFile,\n (rel) => shouldExcludePushRelPath(rel, includeTranscripts, options.userExcludeRegexps),\n (normalizedDeletions ?? []).map((deletion) => deletion.path));\n await walk(abs);\n });\n continue;\n }\n await walk(abs);\n continue;\n }\n if (!entry.isFile()) continue;\n if (await shouldExcludeOfflineSyncFile(options.excludeFile, {\n root: root.abs,\n path: relPosix,\n filePath: abs,\n })) continue;\n const st = await stat(abs);\n const baseEntry = base.get(relPosix);\n if (\n options.includeContent !== true &&\n baseEntry &&\n baseCapturedAtMs !== null &&\n await canReuseFastBaseFileStateFromDisk(baseEntry, st, baseCapturedAtMs)\n ) {\n files.push(baseEntry);\n continue;\n }\n files.push(await readOfflineSyncFileRecord({\n root,\n relPath: relPosix,\n filePath: abs,\n includeContent: options.includeContent === true,\n readFile: options.readFile,\n readFileDigest: options.readFileDigest,\n signal: options.signal,\n }));\n }\n }\n\n await walk(root.abs);\n throwIfOfflineSyncAborted(options.signal);\n\n const sortedFiles = files.sort(compareByPath);\n const deletions = snapshotBuilderDeletions({\n deletions: options.deletions,\n files: sortedFiles,\n includeTranscripts,\n excludeNodeLocalState: options.excludeNodeLocalState,\n userExcludeRegexps: options.userExcludeRegexps,\n omittedGenerationDirs: omission && omission.omittedDirs.length > 0\n ? new Set(omission.omittedDirs)\n : undefined,\n });\n return {\n format: OFFLINE_SYNC_SNAPSHOT_FORMAT,\n schemaVersion: 1,\n createdAt: (options.now ?? new Date()).toISOString(),\n sourceId: normalizeSourceId(options.sourceId, \"sourceId\"),\n includeTranscripts,\n files: sortedFiles,\n ...(deletions === undefined ? {} : { deletions }),\n ...(omission && omission.omittedDirs.length > 0\n ? { omittedEmbeddingGenerationDirs: omission.omittedDirs }\n : {}),\n };\n}\n\nexport async function buildOfflineSyncSnapshotForPaths(options: {\n root: string;\n sourceId: string;\n paths: readonly string[];\n deletions?: readonly OfflineSyncDeletionRevision[];\n includeContent?: boolean;\n includeTranscripts?: boolean;\n now?: Date;\n readFile?: (target: OfflineSyncFileTarget) => Promise<Buffer>;\n readFileDigest?: (target: OfflineSyncFileTarget) => Promise<OfflineSyncFileDigest>;\n excludeFile?: OfflineSyncExcludeFile;\n userExcludeRegexps?: readonly RegExp[];\n /**\n * When false, enumeration uses only the legacy structural excludes —\n * the apply/pull-side view of local files. Push-side callers keep the\n * default (true): built-in node-local state excludes + user excludes.\n * (Cursor review on PR #1793: apply-side local enumeration must see\n * files like state/lcm.sqlite or merges misclassify them.)\n */\n excludeNodeLocalState?: boolean;\n signal?: AbortSignal;\n}): Promise<OfflineSyncSnapshot> {\n throwIfOfflineSyncAborted(options.signal);\n const rootAbs = path.resolve(options.root);\n const root = await prepareSafeArchiveRoot(rootAbs, \"buildOfflineSyncSnapshotForPaths\", \"root\");\n const includeTranscripts = options.includeTranscripts !== false;\n const files: OfflineSyncFileRecord[] = [];\n const seen = new Set<string>();\n\n for (const rawPath of options.paths) {\n throwIfOfflineSyncAborted(options.signal);\n const relPath = normalizeRelativePath(rawPath, \"paths[]\");\n if (seen.has(relPath)) continue;\n seen.add(relPath);\n if (\n options.excludeNodeLocalState === false\n ? shouldExcludeRelPath(relPath, includeTranscripts)\n : shouldExcludePushRelPath(relPath, includeTranscripts, options.userExcludeRegexps)\n ) {\n throw new Error(`offline sync snapshot path is excluded: ${relPath}`);\n }\n const filePath = await resolveSafeArchiveTarget(root, relPath);\n const st = await lstat(filePath).catch((error: unknown) => {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw error;\n });\n if (!st || st.isSymbolicLink() || !st.isFile()) continue;\n if (await shouldExcludeOfflineSyncFile(options.excludeFile, {\n root: root.abs,\n path: relPath,\n filePath,\n })) {\n throw new Error(`offline sync snapshot path is excluded: ${relPath}`);\n }\n files.push(await readOfflineSyncFileRecord({\n root,\n relPath,\n filePath,\n includeContent: options.includeContent === true,\n readFile: options.readFile,\n readFileDigest: options.readFileDigest,\n signal: options.signal,\n }));\n }\n throwIfOfflineSyncAborted(options.signal);\n\n const sortedFiles = files.sort(compareByPath);\n const deletions = snapshotBuilderDeletions({\n deletions: options.deletions,\n files: sortedFiles,\n paths: [...seen],\n includeTranscripts,\n excludeNodeLocalState: options.excludeNodeLocalState,\n userExcludeRegexps: options.userExcludeRegexps,\n });\n return {\n format: OFFLINE_SYNC_SNAPSHOT_FORMAT,\n schemaVersion: 1,\n createdAt: (options.now ?? new Date()).toISOString(),\n sourceId: normalizeSourceId(options.sourceId, \"sourceId\"),\n includeTranscripts,\n files: sortedFiles,\n ...(deletions === undefined ? {} : { deletions }),\n };\n}\n\nexport async function readOfflineSyncFileContentChunk(options: {\n root: string;\n path: string;\n offset?: number;\n length?: number;\n includeTranscripts?: boolean;\n readFile?: (target: OfflineSyncFileTarget) => Promise<Buffer>;\n excludeFile?: OfflineSyncExcludeFile;\n userExcludeRegexps?: readonly RegExp[];\n /**\n * When false, enumeration uses only the legacy structural excludes —\n * the apply/pull-side view of local files. Push-side callers keep the\n * default (true): built-in node-local state excludes + user excludes.\n * (Cursor review on PR #1793: apply-side local enumeration must see\n * files like state/lcm.sqlite or merges misclassify them.)\n */\n excludeNodeLocalState?: boolean;\n}): Promise<OfflineSyncFileContentChunk> {\n const rootAbs = path.resolve(options.root);\n const root = await prepareSafeArchiveRoot(rootAbs, \"readOfflineSyncFileContentChunk\", \"root\");\n const includeTranscripts = options.includeTranscripts !== false;\n const relPath = normalizeRelativePath(options.path, \"path\");\n if (\n options.excludeNodeLocalState === false\n ? shouldExcludeRelPath(relPath, includeTranscripts)\n : shouldExcludePushRelPath(relPath, includeTranscripts, options.userExcludeRegexps)\n ) {\n throw new Error(`offline sync file content path is excluded: ${relPath}`);\n }\n const offset = options.offset === undefined\n ? 0\n : assertNonNegativeInteger(options.offset, \"offset\");\n const requestedLength = options.length === undefined\n ? OFFLINE_SYNC_FILE_CONTENT_MAX_CHUNK_BYTES\n : assertNonNegativeInteger(options.length, \"length\");\n if (requestedLength < 1 || requestedLength > OFFLINE_SYNC_FILE_CONTENT_MAX_CHUNK_BYTES) {\n throw new Error(\n `length must be an integer from 1 to ${OFFLINE_SYNC_FILE_CONTENT_MAX_CHUNK_BYTES}`,\n );\n }\n const filePath = await resolveSafeArchiveTarget(root, relPath);\n const st = await lstat(filePath).catch((error: unknown) => {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw error;\n });\n if (!st || st.isSymbolicLink() || !st.isFile()) {\n throw new Error(`offline sync file content path not found: ${relPath}`);\n }\n if (await shouldExcludeOfflineSyncFile(options.excludeFile, {\n root: root.abs,\n path: relPath,\n filePath,\n })) {\n throw new Error(`offline sync file content path is excluded: ${relPath}`);\n }\n const encrypted = await isEncryptedOfflineSyncFile(filePath);\n if (!encrypted) {\n if (offset > st.size) {\n throw new Error(`offset must be <= file size for ${relPath}`);\n }\n // Plain files need the whole-file sha256 for the response contract\n // (x-remnic-file-sha256; peer transports reject chunks without it), but\n // must stay memory-bounded for large files: the digest is computed by a\n // streamed hash pass (never buffering the file) and cached by\n // (path, bytes, mtimeMs) so per-chunk requests after the first are O(1).\n const chunk = await readPlainOfflineSyncFileChunk({\n filePath,\n offset,\n length: requestedLength,\n bytes: st.size,\n });\n const digest = await plainFileDigest(filePath);\n return {\n path: relPath,\n sha256: digest,\n bytes: st.size,\n mtimeMs: st.mtimeMs,\n offset,\n chunkBytes: chunk.length,\n content: chunk,\n };\n }\n if (!options.readFile) {\n throw new Error(`offline sync file content requires a secure-store read hook: ${relPath}`);\n }\n const content = await options.readFile({ root: root.abs, path: relPath, filePath });\n if (offset > content.length) {\n throw new Error(`offset must be <= file size for ${relPath}`);\n }\n const digest = sha256Buffer(content);\n const end = Math.min(content.length, offset + requestedLength);\n const chunk = content.subarray(offset, end);\n return {\n path: relPath,\n sha256: digest.sha256,\n bytes: digest.bytes,\n mtimeMs: st.mtimeMs,\n offset,\n chunkBytes: chunk.length,\n content: Buffer.from(chunk),\n };\n}\n\nexport async function buildOfflineSyncChangeset(options: {\n root: string;\n sourceId: string;\n baseFiles?: readonly OfflineSyncFileState[];\n deletions?: readonly OfflineSyncDeletionRevision[];\n baseCapturedAt?: Date;\n excludePaths?: readonly string[];\n includeTranscripts?: boolean;\n now?: Date;\n userExcludeRegexps?: readonly RegExp[];\n /**\n * When false, enumeration uses only the legacy structural excludes —\n * the apply/pull-side view of local files. Push-side callers keep the\n * default (true): built-in node-local state excludes + user excludes.\n * (Cursor review on PR #1793: apply-side local enumeration must see\n * files like state/lcm.sqlite or merges misclassify them.)\n */\n excludeNodeLocalState?: boolean;\n readFile?: (target: OfflineSyncFileTarget) => Promise<Buffer>;\n readFileDigest?: (target: OfflineSyncFileTarget) => Promise<OfflineSyncFileDigest>;\n}): Promise<OfflineSyncChangeset> {\n const includeTranscripts = options.includeTranscripts !== false;\n const current = await buildOfflineSyncSnapshotFromBase({\n root: options.root,\n sourceId: options.sourceId,\n baseFiles: options.baseFiles,\n deletions: options.deletions,\n baseCapturedAt: options.baseCapturedAt,\n includeContent: false,\n includeTranscripts,\n now: options.now,\n userExcludeRegexps: options.userExcludeRegexps,\n readFile: options.readFile,\n readFileDigest: options.readFileDigest,\n });\n return buildOfflineSyncChangesetFromSnapshot({\n root: options.root,\n sourceId: options.sourceId,\n baseFiles: options.baseFiles,\n currentFiles: current.files,\n deletions: current.deletions,\n excludePaths: options.excludePaths,\n includeTranscripts,\n now: options.now,\n userExcludeRegexps: options.userExcludeRegexps,\n readFile: options.readFile,\n });\n}\n\nexport async function buildOfflineSyncChangesetFromSnapshot(options: {\n root: string;\n sourceId: string;\n currentFiles: readonly OfflineSyncFileState[];\n baseFiles?: readonly OfflineSyncFileState[];\n deletions?: readonly OfflineSyncDeletionRevision[];\n excludePaths?: readonly string[];\n includeTranscripts?: boolean;\n now?: Date;\n userExcludeRegexps?: readonly RegExp[];\n /**\n * When false, enumeration uses only the legacy structural excludes —\n * the apply/pull-side view of local files. Push-side callers keep the\n * default (true): built-in node-local state excludes + user excludes.\n * (Cursor review on PR #1793: apply-side local enumeration must see\n * files like state/lcm.sqlite or merges misclassify them.)\n */\n excludeNodeLocalState?: boolean;\n readFile?: (target: OfflineSyncFileTarget) => Promise<Buffer>;\n}): Promise<OfflineSyncChangeset> {\n const includeTranscripts = options.includeTranscripts !== false;\n const excludedPaths = new Set(\n (options.excludePaths ?? []).map((relPath) => normalizeRelativePath(relPath, \"excludePaths[]\")),\n );\n const base = byPath(filterBaseFilesForMode(\n normalizeFileStates(options.baseFiles),\n includeTranscripts,\n ));\n const currentMap = byPath(filterBaseFilesForMode(\n normalizeFileStates(options.currentFiles),\n includeTranscripts,\n ));\n const deletions = normalizeDeletionRevisions(options.deletions, \"deletions\");\n const deletionMtimeByPath = deletions === undefined\n ? undefined\n : new Map(deletions.map((deletion) => [deletion.path, deletion.mtimeMs] as const));\n const changes: OfflineSyncChange[] = [];\n\n for (const relPath of unionPaths(base, currentMap)) {\n if (excludedPaths.has(relPath)) continue;\n // Issue #1786: node-local runtime state must never appear in a push-side\n // changeset — each node rebuilds it from synced records.\n if (shouldExcludePushRelPath(relPath, includeTranscripts, options.userExcludeRegexps)) continue;\n // Runtime state is remote-authoritative in offline sync: local edits and\n // deletes are not pushed; the pull phase restores or removes these files\n // from the remote snapshot.\n if (shouldPreferIncomingOfflineRuntimeFile(relPath)) continue;\n const baseEntry = base.get(relPath);\n const currentEntry = currentMap.get(relPath);\n if (currentEntry && currentEntry.sha256 !== baseEntry?.sha256) {\n const file = await buildOfflineSyncSnapshotForPaths({\n root: options.root,\n sourceId: options.sourceId,\n paths: [relPath],\n includeContent: true,\n includeTranscripts,\n now: options.now,\n userExcludeRegexps: options.userExcludeRegexps,\n readFile: options.readFile,\n });\n const record = file.files[0];\n if (!record || typeof record.contentBase64 !== \"string\" || record.sha256 !== currentEntry.sha256) {\n throw new Error(`offline sync file changed while building changeset: ${relPath}`);\n }\n changes.push({\n type: \"upsert\",\n path: relPath,\n ...(baseEntry ? { baseSha256: baseEntry.sha256 } : {}),\n file: record as OfflineSyncFileRecord & { contentBase64: string },\n });\n continue;\n }\n if (!currentEntry && baseEntry) {\n const mtimeMs = deletionMtimeByPath?.get(relPath);\n changes.push({\n type: \"delete\",\n path: relPath,\n baseSha256: baseEntry.sha256,\n ...(mtimeMs === undefined ? {} : { mtimeMs }),\n });\n }\n }\n\n return {\n format: OFFLINE_SYNC_CHANGESET_FORMAT,\n schemaVersion: 1,\n createdAt: (options.now ?? new Date()).toISOString(),\n sourceId: normalizeSourceId(options.sourceId, \"sourceId\"),\n includeTranscripts,\n changes: changes.sort(compareByPath),\n };\n}\n\nexport function summarizeOfflineSyncChangeset(\n changeset: OfflineSyncChangeset,\n): OfflineSyncChangesetSummary {\n const upserts = changeset.changes.filter((change) => change.type === \"upsert\").length;\n const deletes = changeset.changes.filter((change) => change.type === \"delete\").length;\n return {\n upserts,\n deletes,\n total: changeset.changes.length,\n };\n}\n\nexport async function summarizeOfflineSyncPendingChanges(options: {\n root: string;\n sourceId: string;\n baseFiles?: readonly OfflineSyncFileState[];\n baseCapturedAt?: Date;\n includeTranscripts?: boolean;\n now?: Date;\n userExcludeRegexps?: readonly RegExp[];\n /**\n * When false, enumeration uses only the legacy structural excludes —\n * the apply/pull-side view of local files. Push-side callers keep the\n * default (true): built-in node-local state excludes + user excludes.\n * (Cursor review on PR #1793: apply-side local enumeration must see\n * files like state/lcm.sqlite or merges misclassify them.)\n */\n excludeNodeLocalState?: boolean;\n readFile?: (target: OfflineSyncFileTarget) => Promise<Buffer>;\n readFileDigest?: (target: OfflineSyncFileTarget) => Promise<OfflineSyncFileDigest>;\n}): Promise<OfflineSyncChangesetSummary> {\n const includeTranscripts = options.includeTranscripts !== false;\n const current = await buildOfflineSyncSnapshotFromBase({\n root: options.root,\n sourceId: options.sourceId,\n baseFiles: options.baseFiles,\n baseCapturedAt: options.baseCapturedAt,\n includeContent: false,\n includeTranscripts,\n now: options.now,\n userExcludeRegexps: options.userExcludeRegexps,\n readFile: options.readFile,\n readFileDigest: options.readFileDigest,\n });\n return summarizeOfflineSyncPendingFiles({\n baseFiles: options.baseFiles,\n currentFiles: current.files,\n includeTranscripts,\n userExcludeRegexps: options.userExcludeRegexps,\n });\n}\n\nexport function summarizeOfflineSyncPendingFiles(options: {\n baseFiles?: readonly OfflineSyncFileState[];\n currentFiles: readonly OfflineSyncFileState[];\n includeTranscripts?: boolean;\n userExcludeRegexps?: readonly RegExp[];\n /**\n * When false, enumeration uses only the legacy structural excludes —\n * the apply/pull-side view of local files. Push-side callers keep the\n * default (true): built-in node-local state excludes + user excludes.\n * (Cursor review on PR #1793: apply-side local enumeration must see\n * files like state/lcm.sqlite or merges misclassify them.)\n */\n excludeNodeLocalState?: boolean;\n}): OfflineSyncChangesetSummary {\n const includeTranscripts = options.includeTranscripts !== false;\n const base = byPath(filterBaseFilesForMode(\n normalizeFileStates(options.baseFiles),\n includeTranscripts,\n ));\n const currentMap = byPath(filterBaseFilesForMode(\n normalizeFileStates(options.currentFiles),\n includeTranscripts,\n ));\n let upserts = 0;\n let deletes = 0;\n for (const relPath of unionPaths(base, currentMap)) {\n if (shouldPreferIncomingOfflineRuntimeFile(relPath)) continue;\n if (shouldExcludePushRelPath(relPath, includeTranscripts, options.userExcludeRegexps)) continue;\n const baseEntry = base.get(relPath);\n const currentEntry = currentMap.get(relPath);\n if (currentEntry && currentEntry.sha256 !== baseEntry?.sha256) {\n upserts += 1;\n continue;\n }\n if (!currentEntry && baseEntry) {\n deletes += 1;\n }\n }\n\n return {\n upserts,\n deletes,\n total: upserts + deletes,\n };\n}\n\nexport async function applyOfflineSyncSnapshot(options: {\n root: string;\n snapshot: unknown;\n baseFiles?: readonly OfflineSyncFileState[];\n currentFiles?: readonly OfflineSyncFileState[];\n deferredPaths?: readonly string[];\n allowMissingConflictContent?: boolean;\n /**\n * Explicit INCOMING content source for snapshot records without inline\n * `contentBase64` (oversized generation members the client fetched\n * chunk-wise into a private staging root). Consulted only for such\n * records; return null to keep the metadata-only behavior (the local\n * file must hash-match the record). Returned buffers are digest-verified\n * against the incoming record before anything is published.\n */\n readIncomingFile?: (target: { path: string; sha256: string; bytes: number }) => Promise<Buffer | null>;\n writeConflictCopies?: boolean;\n readFile?: (target: OfflineSyncFileTarget) => Promise<Buffer>;\n readFileDigest?: (target: OfflineSyncFileTarget) => Promise<OfflineSyncFileDigest>;\n writeFile?: (target: OfflineSyncFileWriteTarget) => Promise<void>;\n writeStagingFile?: (target: OfflineSyncFileStagingWriteTarget) => Promise<void>;\n readStagingFile?: (target: OfflineSyncFileStagingReadTarget) => Promise<Buffer>;\n deleteFile?: (target: OfflineSyncFileDeleteTarget) => Promise<void>;\n recordDeletionRevision?: OfflineSyncRecordDeletionRevision;\n}): Promise<OfflineSyncApplySnapshotResult> {\n const snapshot = normalizeOfflineSyncSnapshot(options.snapshot);\n const baseMap = byPath(filterBaseFilesForMode(\n normalizeFileStates(options.baseFiles),\n snapshot.includeTranscripts,\n ));\n const incomingMap = byPath(snapshot.files);\n const deletionMtimeByPath = snapshot.deletions === undefined\n ? undefined\n : new Map(snapshot.deletions.map((deletion) => [deletion.path, deletion.mtimeMs] as const));\n const incomingBuffers = await verifyRecordContents(snapshot.files, \"offline sync snapshot\", {\n requireContent: false,\n readIncomingFile: options.readIncomingFile,\n });\n const root = await ensureSyncRoot(options.root, \"applyOfflineSyncSnapshot\");\n const currentFiles = options.currentFiles\n ? filterBaseFilesForMode(normalizeFileStates(options.currentFiles), snapshot.includeTranscripts).sort(compareByPath)\n : (await buildOfflineSyncSnapshot({\n root: root.abs,\n sourceId: \"local\",\n includeContent: false,\n includeTranscripts: snapshot.includeTranscripts,\n readFile: options.readFile,\n readFileDigest: options.readFileDigest,\n excludeNodeLocalState: false,\n })).files;\n const currentMap = byPath(currentFiles);\n const deferredPaths = new Set([...(options.deferredPaths ?? []),\n ...divergedEmbeddingGenerationDeferrals({\n incomingFiles: snapshot.files, baseFiles: [...baseMap.values()], currentFiles,\n }),\n ]);\n const omittedGenerationDirs = new Set(snapshot.omittedEmbeddingGenerationDirs ?? []);\n if (deletionMtimeByPath && options.recordDeletionRevision) {\n for (const [relPath, mtimeMs] of deletionMtimeByPath) {\n if (\n currentMap.has(relPath) ||\n deferredPaths.has(relPath) ||\n (omittedGenerationDirs.size > 0 &&\n isPathInOmittedEmbeddingGeneration(relPath, omittedGenerationDirs)) ||\n matchesOfflineSyncDefaultExclude(relPath)\n ) {\n continue;\n }\n await options.recordDeletionRevision({\n root: root.abs,\n path: relPath,\n filePath: await resolveSafeArchiveTarget(root, relPath),\n mtimeMs,\n });\n }\n }\n const nextBase = new Map(baseMap);\n const conflicts: OfflineSyncConflict[] = [];\n let upserted = 0;\n let deleted = 0;\n let skipped = 0;\n let pendingLocal = 0;\n const conflictIncomingBuffer = (relPath: string): Buffer | undefined => {\n if (options.writeConflictCopies === false) return undefined;\n const buffer = incomingBuffers.get(relPath);\n if (buffer || options.allowMissingConflictContent === true) return buffer;\n return requiredBuffer(incomingBuffers, relPath);\n };\n\n // Embedding generations travel and replace as ONE unit (issue #3148):\n // atomic replacement, cross-layout marker conversion, whole-generation\n // removal on tombstones — all extracted to the generation module (issue\n // #3150) so the changeset path can share it without growing this file.\n const { transactionResults, deferredGenerationDirs } = await applyIncomingEmbeddingGenerations({\n root,\n incomingMap,\n incomingBuffers,\n baseMap,\n currentMap,\n deferredPaths,\n omittedGenerationDirs,\n deletionMtimeByPath,\n io: {\n readFile: options.readFile,\n writeStagingFile: options.writeStagingFile,\n readStagingFile: options.readStagingFile,\n deleteFile: options.deleteFile,\n },\n customIoPresent: Boolean(options.writeFile || options.readFile || options.readFileDigest || options.deleteFile),\n now: Date.now(),\n });\n\n const transactionHandled = new Set<string>();\n let generationUpserted = 0;\n let generationDeleted = 0;\n for (const result of transactionResults) {\n if (result.deferredLocalDivergence) {\n for (const relPath of result.handledPaths) deferredPaths.add(relPath);\n deferredGenerationDirs.add(result.shardDirRel);\n continue;\n }\n generationUpserted += result.upserted;\n generationDeleted += result.deleted;\n for (const relPath of result.handledPaths) transactionHandled.add(relPath);\n // Record converted shard paths directly; they may not be in any input map.\n for (const [relPath, state] of result.writtenStates) {\n nextBase.set(relPath, state);\n transactionHandled.add(relPath);\n }\n for (const relPath of result.removedPaths) {\n nextBase.delete(relPath);\n transactionHandled.add(relPath);\n }\n }\n\n for (const relPath of unionPaths(baseMap, incomingMap, currentMap)) {\n const base = baseMap.get(relPath);\n const incoming = incomingMap.get(relPath);\n const currentEntry = currentMap.get(relPath);\n\n if (deferredPaths.has(relPath)) {\n if (base) nextBase.set(relPath, base);\n else nextBase.delete(relPath);\n skipped += 1;\n continue;\n }\n\n // The generation transaction already published or removed this path and\n // applied its nextBase bookkeeping above; nothing left to do.\n if (transactionHandled.has(relPath)) continue;\n\n // A deferral anywhere in a generation defers the WHOLE generation: no\n // partial replacement in either direction, local files and base entries\n // stay exactly as they are.\n const membership = embeddingGenerationMembership(relPath);\n if (membership && deferredGenerationDirs.has(membership.shardDir)) {\n if (base) nextBase.set(relPath, base);\n else nextBase.delete(relPath);\n skipped += 1;\n continue;\n }\n\n if (incoming) {\n // The generation marker (PR #3176) is node-local on BOTH sides: an\n // incoming copy — old or hostile — never overwrites the local file\n // and never enters the base set. Other default excludes stay\n // apply-accepted (#1786: first-sync LCM sqlite bootstrapping).\n if (isEmbeddingGenerationMarkerPath(relPath)) {\n nextBase.delete(relPath);\n skipped += 1;\n continue;\n }\n if (currentEntry?.sha256 === incoming.sha256) {\n if (await setSafeFileMtime(root, relPath, incoming.mtimeMs)) {\n nextBase.set(relPath, toFileState(incoming));\n } else {\n if (base) nextBase.set(relPath, base);\n else nextBase.delete(relPath);\n pendingLocal += 1;\n }\n skipped += 1;\n continue;\n }\n // Remote unchanged from the shared base while the local file drifted:\n // keep the local copy (no content is needed to make that decision).\n // Members of a replaced generation never reach this branch — the\n // generation transaction or the deferral guard handled them above.\n if (\n shouldPreferIncomingOfflineRuntimeFile(relPath) &&\n currentEntry && base && incoming.sha256 === base.sha256\n ) {\n nextBase.set(relPath, base);\n skipped += 1;\n continue;\n }\n if (shouldPreferIncomingOfflineRuntimeFile(relPath)) {\n await writeSafeFile(root, relPath, requiredBuffer(incomingBuffers, relPath), options.writeFile, incoming.mtimeMs);\n nextBase.set(relPath, toFileState(incoming));\n upserted += 1;\n continue;\n }\n if (!currentEntry && base && incoming.sha256 === base.sha256) {\n nextBase.set(relPath, base);\n pendingLocal += 1;\n skipped += 1;\n continue;\n }\n if (!currentEntry && base && incoming.sha256 !== base.sha256) {\n conflicts.push(await recordConflict({\n root,\n relPath,\n reason: \"local_deleted_remote_modified\",\n baseSha256: base.sha256,\n incomingSha256: incoming.sha256,\n incomingBuffer: conflictIncomingBuffer(relPath),\n writeConflictCopies: options.writeConflictCopies !== false,\n sourceId: snapshot.sourceId,\n writeFile: options.writeFile,\n }));\n nextBase.set(relPath, base);\n continue;\n }\n if (!currentEntry && !base) {\n await writeSafeFile(root, relPath, requiredBuffer(incomingBuffers, relPath), options.writeFile, incoming.mtimeMs);\n nextBase.set(relPath, toFileState(incoming));\n upserted += 1;\n continue;\n }\n if (base && currentEntry && currentEntry.sha256 === base.sha256) {\n await writeSafeFile(root, relPath, requiredBuffer(incomingBuffers, relPath), options.writeFile, incoming.mtimeMs);\n nextBase.set(relPath, toFileState(incoming));\n upserted += 1;\n continue;\n }\n if (base && incoming.sha256 === base.sha256) {\n nextBase.set(relPath, base);\n pendingLocal += 1;\n skipped += 1;\n continue;\n }\n conflicts.push(await recordConflict({\n root,\n relPath,\n reason: base ? \"both_modified\" : \"remote_exists_for_local_create\",\n baseSha256: base?.sha256,\n localSha256: currentEntry?.sha256,\n incomingSha256: incoming.sha256,\n incomingBuffer: conflictIncomingBuffer(relPath),\n writeConflictCopies: options.writeConflictCopies !== false,\n sourceId: snapshot.sourceId,\n writeFile: options.writeFile,\n }));\n if (base) nextBase.set(relPath, base);\n continue;\n }\n\n // Node-local runtime state (#1786): a push-filtered remote snapshot\n // never carries these paths, so their absence is NOT a delete\n // instruction. Drop any stale base entry (pre-#1786 state files still\n // carry them) and leave the local file untouched — deleting a live\n // sqlite WAL/SHM here would corrupt the local LCM store.\n if (matchesOfflineSyncDefaultExclude(relPath)) {\n nextBase.delete(relPath);\n skipped += 1;\n continue;\n }\n if (!currentEntry) {\n nextBase.delete(relPath);\n skipped += 1;\n continue;\n }\n if (\n shouldPreferIncomingOfflineRuntimeFile(relPath) &&\n membership !== null && omittedGenerationDirs.has(membership.shardDir)\n ) {\n // The push omitted this whole generation because a filter excluded at\n // least one member (snapshot.omittedEmbeddingGenerationDirs): absence\n // is NOT a deletion — keep the local generation and its base entries\n // until it is pushed unfiltered or deleted with deletion metadata.\n pendingLocal += 1;\n skipped += 1;\n continue;\n }\n if (\n shouldPreferIncomingOfflineRuntimeFile(relPath) &&\n (base || shouldDeleteAbsentIncomingOfflineRuntimeFile(relPath))\n ) {\n await deleteSafeFile(\n root,\n relPath,\n options.deleteFile,\n deletionMtimeByPath?.get(relPath),\n );\n nextBase.delete(relPath);\n deleted += 1;\n continue;\n }\n if (shouldPreferIncomingOfflineRuntimeFile(relPath)) {\n pendingLocal += 1;\n skipped += 1;\n continue;\n }\n if (base && currentEntry.sha256 === base.sha256) {\n await deleteSafeFile(\n root,\n relPath,\n options.deleteFile,\n deletionMtimeByPath?.get(relPath),\n );\n nextBase.delete(relPath);\n deleted += 1;\n continue;\n }\n if (base) {\n conflicts.push({\n path: relPath,\n reason: \"local_modified_remote_deleted\",\n baseSha256: base.sha256,\n localSha256: currentEntry.sha256,\n });\n nextBase.set(relPath, base);\n continue;\n }\n pendingLocal += 1;\n skipped += 1;\n }\n\n return {\n upserted: upserted + generationUpserted,\n deleted: deleted + generationDeleted,\n skipped,\n pendingLocal,\n conflicts,\n nextBaseFiles: [...nextBase.values()].sort(compareByPath),\n };\n}\n\nexport async function applyOfflineSyncChangeset(options: {\n root: string;\n changeset: unknown;\n currentFiles?: readonly OfflineSyncFileState[];\n returnCurrentFiles?: boolean;\n writeConflictCopies?: boolean;\n readFile?: (target: OfflineSyncFileTarget) => Promise<Buffer>;\n readFileDigest?: (target: OfflineSyncFileTarget) => Promise<OfflineSyncFileDigest>;\n writeFile?: (target: OfflineSyncFileWriteTarget) => Promise<void>;\n writeStagingFile?: (target: OfflineSyncFileStagingWriteTarget) => Promise<void>;\n readStagingFile?: (target: OfflineSyncFileStagingReadTarget) => Promise<Buffer>;\n deleteFile?: (target: OfflineSyncFileDeleteTarget) => Promise<void>;\n recordDeletionRevision?: OfflineSyncRecordDeletionRevision;\n}): Promise<OfflineSyncApplyChangesetResult> {\n let changeset: OfflineSyncChangeset;\n try {\n changeset = normalizeOfflineSyncChangeset(options.changeset);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(\n message.startsWith(\"offline sync\")\n ? message\n : `offline sync changeset invalid: ${message}`,\n );\n }\n const root = await ensureSyncRoot(options.root, \"applyOfflineSyncChangeset\");\n const records = changeset.changes\n .filter((change): change is Extract<OfflineSyncChange, { type: \"upsert\" }> => change.type === \"upsert\")\n .map((change) => change.file);\n const incomingBuffers = await verifyRecordContents(records, \"offline sync changeset\");\n const currentFiles = options.currentFiles\n ? filterBaseFilesForMode(normalizeFileStates(options.currentFiles), changeset.includeTranscripts).sort(compareByPath)\n : (await buildOfflineSyncSnapshotForPaths({\n root: root.abs,\n sourceId: \"local\",\n paths: changeset.changes.map((change) => change.path),\n includeContent: false,\n includeTranscripts: changeset.includeTranscripts,\n readFile: options.readFile,\n readFileDigest: options.readFileDigest,\n excludeNodeLocalState: false,\n })).files;\n const currentMap = byPath(currentFiles);\n const conflicts: OfflineSyncConflict[] = [];\n let appliedUpserts = 0;\n let appliedDeletes = 0;\n let skipped = 0;\n\n // Embedding generations apply as ONE unit through the shared locked\n // transaction (issue #3150). Deferred generations surface as conflicts so\n // the push side never checkpoints them as applied.\n const generationRouting = await applyChangesetEmbeddingGenerations({\n root,\n changeset,\n incomingBuffers,\n currentMap,\n io: {\n readFile: options.readFile,\n writeStagingFile: options.writeStagingFile,\n readStagingFile: options.readStagingFile,\n deleteFile: options.deleteFile,\n },\n customIoPresent: Boolean(options.writeFile || options.readFile || options.readFileDigest || options.deleteFile),\n now: Date.now(),\n });\n appliedUpserts += generationRouting.appliedUpserts;\n appliedDeletes += generationRouting.appliedDeletes;\n conflicts.push(...generationRouting.conflicts);\n\n for (const change of changeset.changes) {\n if (generationRouting.conflictedPaths.has(change.path)) continue;\n if (generationRouting.transactionHandled.has(change.path)) continue;\n if (isEmbeddingGenerationMarkerPath(change.path)) {\n skipped += 1;\n continue;\n }\n const currentEntry = currentMap.get(change.path);\n if (change.type === \"upsert\") {\n if (currentEntry?.sha256 === change.file.sha256) {\n if (await setSafeFileMtime(root, change.path, change.file.mtimeMs)) {\n skipped += 1;\n } else {\n await writeSafeFile(root, change.path, requiredBuffer(incomingBuffers, change.path), options.writeFile, change.file.mtimeMs);\n currentMap.set(change.path, toFileState(change.file));\n appliedUpserts += 1;\n }\n continue;\n }\n if (!change.baseSha256) {\n if (!currentEntry) {\n await writeSafeFile(root, change.path, requiredBuffer(incomingBuffers, change.path), options.writeFile, change.file.mtimeMs);\n currentMap.set(change.path, toFileState(change.file));\n appliedUpserts += 1;\n continue;\n }\n conflicts.push(await recordConflict({\n root,\n relPath: change.path,\n reason: \"remote_exists_for_local_create\",\n localSha256: currentEntry.sha256,\n incomingSha256: change.file.sha256,\n incomingBuffer: incomingBuffers.get(change.path),\n writeConflictCopies: options.writeConflictCopies !== false,\n sourceId: changeset.sourceId,\n writeFile: options.writeFile,\n }));\n continue;\n }\n if (currentEntry?.sha256 === change.baseSha256) {\n await writeSafeFile(root, change.path, requiredBuffer(incomingBuffers, change.path), options.writeFile, change.file.mtimeMs);\n currentMap.set(change.path, toFileState(change.file));\n appliedUpserts += 1;\n continue;\n }\n conflicts.push(await recordConflict({\n root,\n relPath: change.path,\n reason: currentEntry ? \"remote_changed_for_local_update\" : \"remote_deleted_for_local_update\",\n baseSha256: change.baseSha256,\n localSha256: currentEntry?.sha256,\n incomingSha256: change.file.sha256,\n incomingBuffer: incomingBuffers.get(change.path),\n writeConflictCopies: options.writeConflictCopies !== false,\n sourceId: changeset.sourceId,\n writeFile: options.writeFile,\n }));\n continue;\n }\n\n if (!currentEntry) {\n if (change.mtimeMs !== undefined && options.recordDeletionRevision) {\n await options.recordDeletionRevision({\n root: root.abs,\n path: change.path,\n filePath: await resolveSafeArchiveTarget(root, change.path),\n mtimeMs: change.mtimeMs,\n });\n }\n skipped += 1;\n continue;\n }\n if (currentEntry.sha256 === change.baseSha256) {\n await deleteSafeFile(root, change.path, options.deleteFile, change.mtimeMs);\n currentMap.delete(change.path);\n appliedDeletes += 1;\n continue;\n }\n conflicts.push({\n path: change.path,\n reason: \"remote_changed_for_local_delete\",\n baseSha256: change.baseSha256,\n localSha256: currentEntry.sha256,\n });\n }\n\n // Generation transactions bypassed the per-file loop; fold their published\n // and removed members into the partial result map (returnCurrentFiles ===\n // false consumers) so it reflects the post-apply generation exactly.\n for (const [relPath, state] of generationRouting.writtenStates) currentMap.set(relPath, state);\n for (const relPath of generationRouting.removedPaths) currentMap.delete(relPath);\n\n return {\n appliedUpserts,\n appliedDeletes,\n skipped,\n conflicts,\n currentFiles: options.returnCurrentFiles === false\n ? [...currentMap.values()].sort(compareByPath)\n : (await buildOfflineSyncSnapshot({\n root: root.abs,\n sourceId: \"local\",\n includeContent: false,\n includeTranscripts: changeset.includeTranscripts,\n readFile: options.readFile,\n readFileDigest: options.readFileDigest,\n excludeNodeLocalState: false,\n })).files,\n ...(options.returnCurrentFiles === false ? { currentFilesComplete: false } : {}),\n };\n}\n\nasync function verifyRecordContents(\n records: readonly OfflineSyncFileRecord[],\n context: string,\n options: {\n requireContent?: boolean;\n readIncomingFile?: (target: { path: string; sha256: string; bytes: number }) => Promise<Buffer | null>;\n } = {},\n): Promise<Map<string, Buffer>> {\n const buffers = new Map<string, Buffer>();\n for (const record of records) {\n if (typeof record.contentBase64 !== \"string\") {\n if (options.readIncomingFile) {\n // Explicit INCOMING content source for records whose bytes travel\n // out-of-band (chunked fetch into the client's private staging\n // root). Never the local current-state file: the buffer is\n // digest-verified against the incoming record before anything is\n // published. null keeps the metadata-only behavior below.\n const incoming = await options.readIncomingFile({\n path: record.path,\n sha256: record.sha256,\n bytes: record.bytes,\n });\n if (incoming) {\n const digest = sha256Buffer(incoming);\n if (digest.sha256 !== record.sha256 || digest.bytes !== record.bytes) {\n throw new Error(`${context}: incoming content checksum mismatch for ${record.path}`);\n }\n buffers.set(record.path, incoming);\n continue;\n }\n }\n if (options.requireContent === false) continue;\n throw new Error(`${context}: contentBase64 is required for ${record.path}`);\n }\n const buffer = Buffer.from(record.contentBase64, \"base64\");\n const digest = sha256Buffer(buffer);\n if (digest.sha256 !== record.sha256 || digest.bytes !== record.bytes) {\n throw new Error(\n `${context}: content checksum mismatch for ${record.path}`,\n );\n }\n buffers.set(record.path, buffer);\n }\n return buffers;\n}\n\nfunction requiredBuffer(buffers: Map<string, Buffer>, relPath: string): Buffer {\n const buffer = buffers.get(relPath);\n if (!buffer) {\n throw new Error(`missing decoded content for ${relPath}`);\n }\n return buffer;\n}\n\nasync function ensureSyncRoot(rootPath: string, errorPrefix: string): Promise<SafeArchiveRoot> {\n const rootAbs = path.resolve(rootPath);\n await mkdir(rootAbs, { recursive: true });\n return prepareSafeArchiveRoot(rootAbs, errorPrefix, \"root\");\n}\n\nfunction byPath<T extends OfflineSyncFileState>(files: readonly T[]): Map<string, T> {\n const out = new Map<string, T>();\n for (const file of files) {\n out.set(validateArchiveRelativePath(file.path, \"offlineSync\"), file);\n }\n return out;\n}\n\nfunction unionPaths(...maps: Array<Map<string, unknown>>): string[] {\n const paths = new Set<string>();\n for (const map of maps) {\n for (const key of map.keys()) paths.add(key);\n }\n return [...paths].sort();\n}\n\nfunction toFileState(file: OfflineSyncFileState): OfflineSyncFileState {\n return {\n path: file.path,\n sha256: file.sha256,\n bytes: file.bytes,\n mtimeMs: file.mtimeMs,\n };\n}\n\nasync function writeSafeFile(\n root: SafeArchiveRoot,\n relPath: string,\n content: Buffer,\n writeFileHook?: (target: OfflineSyncFileWriteTarget) => Promise<void>,\n mtimeMs?: number,\n): Promise<void> {\n const target = await resolveSafeArchiveTarget(root, relPath);\n if (writeFileHook) {\n await writeFileHook({ root: root.abs, path: relPath, filePath: target, content });\n await setSafeFileMtime(root, relPath, mtimeMs);\n return;\n }\n await mkdir(path.dirname(target), { recursive: true });\n const tmp = path.join(\n path.dirname(target),\n `.remnic-sync.${process.pid}.${randomUUID()}.tmp`,\n );\n await writeFile(tmp, content);\n try {\n const targetStat = await lstat(target).catch((error: unknown) => {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw error;\n });\n if (targetStat?.isSymbolicLink()) {\n throw new Error(`offline sync target is a symlink: ${relPath}`);\n }\n await rename(tmp, target);\n await setSafeFileMtime(root, relPath, mtimeMs);\n } catch (error) {\n await unlink(tmp).catch(() => {});\n throw error;\n }\n}\n\n\n/**\n * Read the local file digest for a single relative path without applying\n * push-side exclude rules. Used by apply-side helpers that need to check\n * the current local state of a path that the push-side exclude would\n * reject (e.g. `state/lcm.sqlite`). Returns `null` if the file does not\n * exist, is not a regular file, or is a symlink.\n */\nasync function readLocalFileState(options: {\n rootAbs: string;\n relPath: string;\n readFile?: (target: OfflineSyncFileTarget) => Promise<Buffer>;\n readFileDigest?: (target: OfflineSyncFileTarget) => Promise<OfflineSyncFileDigest>;\n signal?: AbortSignal;\n}): Promise<OfflineSyncFileState | null> {\n const filePath = await resolveSafeArchiveTarget(\n await prepareSafeArchiveRoot(options.rootAbs, \"readLocalFileState\", \"rootAbs\"),\n options.relPath,\n );\n const st = await lstat(filePath).catch((error: unknown) => {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw error;\n });\n if (!st || st.isSymbolicLink() || !st.isFile()) return null;\n throwIfOfflineSyncAborted(options.signal);\n let digest: OfflineSyncFileDigest;\n if (options.readFileDigest) {\n digest = await options.readFileDigest({ root: options.rootAbs, path: options.relPath, filePath });\n } else if (options.readFile) {\n const content = await options.readFile({ root: options.rootAbs, path: options.relPath, filePath });\n digest = sha256Buffer(content);\n } else {\n digest = await sha256OfflineSyncFile(filePath, options.signal);\n }\n throwIfOfflineSyncAborted(options.signal);\n return {\n path: options.relPath,\n sha256: digest.sha256,\n bytes: digest.bytes,\n mtimeMs: st.mtimeMs,\n };\n}\n\nexport async function applyOfflineSyncFileContentChunk(options: {\n root: string;\n sourceId: string;\n path: string;\n sha256: string;\n bytes: number;\n mtimeMs: number;\n offset?: number;\n content: Buffer;\n baseSha256?: string;\n includeTranscripts?: boolean;\n readFile?: (target: OfflineSyncFileTarget) => Promise<Buffer>;\n readFileDigest?: (target: OfflineSyncFileTarget) => Promise<OfflineSyncFileDigest>;\n writeFile?: (target: OfflineSyncFileWriteTarget) => Promise<void>;\n writeStagingFile?: (target: OfflineSyncFileStagingWriteTarget) => Promise<void>;\n writeFileChunks?: (target: OfflineSyncFileWriteChunksTarget) => Promise<void>;\n}): Promise<OfflineSyncApplyFileContentChunkResult> {\n const root = await ensureSyncRoot(options.root, \"applyOfflineSyncFileContentChunk\");\n const sourceId = normalizeSourceId(options.sourceId, \"sourceId\");\n const relPath = normalizeRelativePath(options.path, \"path\");\n const includeTranscripts = options.includeTranscripts !== false;\n if (shouldExcludeRelPath(relPath, includeTranscripts)) {\n throw new Error(`offline sync file content path is excluded: ${relPath}`);\n }\n if (isEmbeddingGenerationMarkerPath(relPath)) {\n throw new Error(`offline sync file content path is node-local: ${relPath}`);\n }\n const sha256 = assertSha256(options.sha256, \"sha256\");\n const bytes = assertNonNegativeInteger(options.bytes, \"bytes\");\n const mtimeMs = assertOfflineSyncMtimeMs(options.mtimeMs, \"mtimeMs\");\n const offset = options.offset === undefined\n ? 0\n : assertNonNegativeInteger(options.offset, \"offset\");\n const baseSha256 = options.baseSha256 === undefined\n ? undefined\n : assertSha256(options.baseSha256, \"baseSha256\");\n const preferIncomingRuntimeFile = shouldPreferIncomingOfflineRuntimeFile(relPath);\n if (!Buffer.isBuffer(options.content)) {\n throw new Error(\"content must be a Buffer\");\n }\n if (options.content.length > OFFLINE_SYNC_FILE_CONTENT_MAX_CHUNK_BYTES) {\n throw new Error(\n `content chunk must be ${OFFLINE_SYNC_FILE_CONTENT_MAX_CHUNK_BYTES} bytes or fewer`,\n );\n }\n if (bytes > 0 && options.content.length === 0) {\n throw new Error(\"content chunk must be non-empty before EOF\");\n }\n if (offset > bytes || offset + options.content.length > bytes) {\n throw new Error(`content chunk range exceeds declared file size for ${relPath}`);\n }\n if (options.writeFile && !options.writeFileChunks) {\n throw new Error(\"offline sync upload storage hooks require writeFileChunks\");\n }\n if (options.writeFile && !options.writeStagingFile) {\n throw new Error(\"offline sync upload storage hooks require writeStagingFile\");\n }\n const baseResult = {\n path: relPath,\n sha256,\n bytes,\n mtimeMs,\n offset,\n chunkBytes: options.content.length,\n done: offset + options.content.length === bytes,\n };\n const currentFileConflict = async (\n currentFile: OfflineSyncFileState | undefined,\n ): Promise<{ conflict: OfflineSyncConflict; currentFile?: OfflineSyncFileState } | null> => {\n if (!baseSha256 && currentFile && !preferIncomingRuntimeFile) {\n const conflict = await recordConflict({\n root,\n relPath,\n reason: \"remote_exists_for_local_create\",\n localSha256: currentFile.sha256,\n incomingSha256: sha256,\n writeConflictCopies: false,\n sourceId,\n writeFile: options.writeFile,\n });\n return {\n conflict,\n currentFile,\n };\n }\n if (baseSha256 && currentFile?.sha256 !== baseSha256 && !preferIncomingRuntimeFile) {\n const conflict = await recordConflict({\n root,\n relPath,\n reason: currentFile ? \"remote_changed_for_local_update\" : \"remote_deleted_for_local_update\",\n baseSha256,\n localSha256: currentFile?.sha256,\n incomingSha256: sha256,\n writeConflictCopies: false,\n sourceId,\n writeFile: options.writeFile,\n });\n return {\n conflict,\n ...(currentFile ? { currentFile } : {}),\n };\n }\n return null;\n };\n if (offset === 0) {\n await pruneOfflineUploadStaging(root);\n const currentFile = await readLocalFileState({\n rootAbs: root.abs,\n relPath,\n readFile: options.readFile,\n readFileDigest: options.readFileDigest,\n });\n if (currentFile && currentFile.sha256 === sha256) {\n await setSafeFileMtime(root, relPath, mtimeMs);\n return {\n ...baseResult,\n done: true,\n chunkBytes: 0,\n applied: false,\n skipped: true,\n currentFile: toFileState(currentFile),\n };\n }\n const conflictResult = await currentFileConflict(currentFile ? toFileState(currentFile) : undefined);\n if (conflictResult) {\n return {\n ...baseResult,\n done: true,\n chunkBytes: 0,\n applied: false,\n skipped: false,\n ...conflictResult,\n };\n }\n }\n\n const upload = await writeOfflineUploadChunk({\n root,\n sourceId,\n relPath,\n sha256,\n bytes,\n offset,\n content: options.content,\n readFile: options.readFile,\n writeFile: options.writeFile,\n writeStagingFile: options.writeStagingFile,\n });\n const done = baseResult.done;\n if (!done) {\n return {\n ...baseResult,\n applied: false,\n skipped: false,\n };\n }\n\n const digest = await digestOfflineUploadStagingContent({\n root,\n upload,\n readFile: options.readFile,\n });\n if (digest.sha256 !== sha256 || digest.bytes !== bytes) {\n await cleanupOfflineUpload(upload).catch(() => {});\n throw new Error(`offline sync upload checksum mismatch for ${relPath}`);\n }\n\n const currentFile = await readLocalFileState({\n rootAbs: root.abs,\n relPath,\n readFile: options.readFile,\n readFileDigest: options.readFileDigest,\n });\n const uploadedState: OfflineSyncFileState = {\n path: relPath,\n sha256,\n bytes,\n mtimeMs,\n };\n\n try {\n if (currentFile && currentFile.sha256 === sha256) {\n await setSafeFileMtime(root, relPath, mtimeMs);\n return {\n ...baseResult,\n applied: false,\n skipped: true,\n currentFile: uploadedState,\n };\n }\n\n const conflictResult = await currentFileConflict(currentFile ? toFileState(currentFile) : undefined);\n if (conflictResult) {\n return {\n ...baseResult,\n applied: false,\n skipped: false,\n ...conflictResult,\n };\n }\n\n await writeSafeFileFromUpload(root, relPath, upload, options.readFile, options.writeFileChunks, mtimeMs);\n return {\n ...baseResult,\n applied: true,\n skipped: false,\n currentFile: uploadedState,\n };\n } finally {\n await cleanupOfflineUpload(upload).catch(() => {});\n }\n}\n\n\nasync function deleteSafeFile(\n root: SafeArchiveRoot,\n relPath: string,\n deleteFile?: (target: OfflineSyncFileDeleteTarget) => Promise<void>,\n mtimeMs?: number,\n): Promise<void> {\n const target = await resolveSafeArchiveTarget(root, relPath);\n if (deleteFile) {\n await deleteFile({\n root: root.abs,\n path: relPath,\n filePath: target,\n ...(mtimeMs === undefined ? {} : { mtimeMs }),\n });\n return;\n }\n await unlink(target).catch((error: unknown) => {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return;\n throw error;\n });\n}\n\nasync function recordConflict(options: {\n root: SafeArchiveRoot;\n relPath: string;\n reason: OfflineSyncConflict[\"reason\"];\n baseSha256?: string;\n localSha256?: string;\n incomingSha256?: string;\n incomingBuffer?: Buffer;\n writeConflictCopies: boolean;\n sourceId: string;\n writeFile?: (target: OfflineSyncFileWriteTarget) => Promise<void>;\n}): Promise<OfflineSyncConflict> {\n let conflictPath: string | undefined;\n if (options.writeConflictCopies && options.incomingBuffer) {\n const sourceHash = hashText(options.sourceId).slice(0, 12);\n const stamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n conflictPath = `${SYNC_INTERNAL_DIR}/conflicts/${stamp}-${sourceHash}/${options.relPath}`;\n await writeSafeFile(options.root, conflictPath, options.incomingBuffer, options.writeFile);\n }\n return {\n path: options.relPath,\n reason: options.reason,\n baseSha256: options.baseSha256,\n localSha256: options.localSha256,\n incomingSha256: options.incomingSha256,\n ...(conflictPath ? { conflictPath } : {}),\n };\n}\n\nexport function defaultOfflineSyncStatePath(\n memoryDir: string,\n remoteId: string,\n namespace?: string,\n): string {\n const key = hashText(`${remoteId}\\0${namespace ?? \"\"}`).slice(0, 16);\n return path.join(path.resolve(memoryDir), SYNC_INTERNAL_DIR, \"state\", `${key}.json`);\n}\n\nexport async function readOfflineSyncState(\n statePath: string,\n): Promise<OfflineSyncState | null> {\n let raw: string;\n try {\n raw = await readFile(path.resolve(statePath), \"utf-8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw error;\n }\n const parsed = JSON.parse(raw) as unknown;\n return normalizeOfflineSyncState(parsed);\n}\n\nexport async function writeOfflineSyncState(\n statePath: string,\n state: OfflineSyncState,\n): Promise<void> {\n const normalized = normalizeOfflineSyncState(state);\n const target = path.resolve(statePath);\n await mkdir(path.dirname(target), { recursive: true });\n const tmp = path.join(\n path.dirname(target),\n `.remnic-sync-state.${process.pid}.${randomUUID()}.tmp`,\n );\n await writeFile(tmp, JSON.stringify(normalized, null, 2) + \"\\n\", \"utf-8\");\n try {\n await rename(tmp, target);\n } catch (error) {\n await unlink(tmp).catch(() => {});\n throw error;\n }\n}\n\nexport function offlineSyncStateFromSnapshot(options: {\n remoteId: string;\n namespace?: string;\n snapshot: OfflineSyncSnapshot;\n baseFiles?: readonly OfflineSyncFileState[];\n}): OfflineSyncState {\n const snapshot = normalizeOfflineSyncSnapshot(options.snapshot);\n return normalizeOfflineSyncState({\n version: OFFLINE_SYNC_STATE_VERSION,\n remoteId: options.remoteId,\n namespace: options.namespace,\n includeTranscripts: snapshot.includeTranscripts,\n lastSyncedAt: new Date().toISOString(),\n baseFiles: options.baseFiles ?? snapshot.files.map(toFileState),\n });\n}\n\nexport function normalizeOfflineSyncState(input: unknown): OfflineSyncState {\n if (!input || typeof input !== \"object\" || Array.isArray(input)) {\n throw new Error(\"offline sync state must be an object\");\n }\n const obj = input as Record<string, unknown>;\n if (obj.version !== OFFLINE_SYNC_STATE_VERSION) {\n throw new Error(`offline sync state version must be ${OFFLINE_SYNC_STATE_VERSION}`);\n }\n const namespace =\n typeof obj.namespace === \"string\" && obj.namespace.trim().length > 0\n ? obj.namespace.trim()\n : undefined;\n const baseFiles = normalizeFileStates(obj.baseFiles as readonly unknown[] | undefined)\n .sort(compareByPath);\n assertUniquePaths(baseFiles, \"offline sync state\");\n return {\n version: OFFLINE_SYNC_STATE_VERSION,\n remoteId: normalizeSourceId(obj.remoteId, \"remoteId\"),\n ...(namespace ? { namespace } : {}),\n includeTranscripts: assertBoolean(obj.includeTranscripts, \"includeTranscripts\"),\n lastSyncedAt: normalizeIsoString(obj.lastSyncedAt, \"lastSyncedAt\"),\n baseFiles,\n };\n}\n\nexport function fileStatesFromSnapshot(snapshot: OfflineSyncSnapshot): OfflineSyncFileState[] {\n return normalizeOfflineSyncSnapshot(snapshot).files.map(toFileState).sort(compareByPath);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAqB,kBAAkB;AACvC;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EAEA;AAAA,OACK;AACP,OAAO,UAAU;AAoEV,IAAM,+BAA+B;AACrC,IAAM,gCAAgC;AACtC,IAAM,6BAA6B;AACnC,IAAM,4CAA4C,KAAK,OAAO;AAC9D,IAAM,iDAAiD,IAAI,OAAO;AAClE,IAAM,oCAAoC,KAAK,OAAO;AACtD,IAAM,4CAA4C,KAAK,OAAO;AAC9D,IAAM,4BAA4B;AA6LzC,IAAM,4CAA4C;AAClD,IAAM,sBAAsB,oBAAI,IAAI;AAAA,EAClC;AACF,CAAC;AAED,IAAM,yBAAyB;AAAA,EAC7B;AAAA,EACA;AACF;AAcA,SAAS,aAAa,QAAmD;AACvE,SAAO,YAAY,MAAM;AAC3B;A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_EXCLUDE_GLOBS = [
|
|
|
52
52
|
"**/state/embeddings.json.pre-migration.tmp-*",
|
|
53
53
|
"**/namespaces/*/state/embeddings.pre-replace.tmp/**",
|
|
54
54
|
"**/namespaces/*/state/embeddings.staging.tmp-*/**",
|
|
55
|
-
"**/namespaces/*/state/embeddings.json.pre-migration.tmp-*"
|
|
55
|
+
"**/namespaces/*/state/embeddings.json.pre-migration.tmp-*",
|
|
56
|
+
// The warm-cache generation marker (PR #3176) is node-local coherence
|
|
57
|
+
// state: a synced copy — worse, a captured `in-flight` value — would make
|
|
58
|
+
// the receiving node's stamp probes unique forever and force a full index
|
|
59
|
+
// reload on every search. Exclude on both sides: never snapshotted, and
|
|
60
|
+
// an incoming (old or hostile) marker never overwrites or deletes the
|
|
61
|
+
// local one.
|
|
62
|
+
"**/state/embeddings.generation",
|
|
63
|
+
"**/namespaces/*/state/embeddings.generation"
|
|
56
64
|
];
|
|
57
65
|
var DEFAULT_OFFLINE_SYNC_EXCLUDE_REGEXPS = DEFAULT_OFFLINE_SYNC_EXCLUDE_GLOBS.map((glob) => globToRegExp(glob));
|
|
66
|
+
function isEmbeddingGenerationMarkerPath(relPosix) {
|
|
67
|
+
const normalized = relPosix.includes("\\") ? relPosix.replaceAll("\\", "/") : relPosix;
|
|
68
|
+
return /(?:^|\/)state\/embeddings\.generation$/i.test(normalized);
|
|
69
|
+
}
|
|
58
70
|
function matchesOfflineSyncDefaultExclude(relPosix) {
|
|
59
71
|
for (const regexp of DEFAULT_OFFLINE_SYNC_EXCLUDE_REGEXPS) {
|
|
60
72
|
if (regexp.test(relPosix)) return true;
|
|
@@ -129,9 +141,10 @@ function parseOfflineSyncExcludes(raw) {
|
|
|
129
141
|
export {
|
|
130
142
|
OFFLINE_DECRYPT_STAGING_DIR_PREFIX,
|
|
131
143
|
DEFAULT_OFFLINE_SYNC_EXCLUDE_GLOBS,
|
|
144
|
+
isEmbeddingGenerationMarkerPath,
|
|
132
145
|
matchesOfflineSyncDefaultExclude,
|
|
133
146
|
globToRegExp,
|
|
134
147
|
compileOfflineSyncExcludeGlobs,
|
|
135
148
|
parseOfflineSyncExcludes
|
|
136
149
|
};
|
|
137
|
-
//# sourceMappingURL=chunk-
|
|
150
|
+
//# sourceMappingURL=chunk-63LFM77Z.js.map
|