@remnic/core 9.3.733 → 9.3.734
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-boundary.d.ts +10 -10
- package/dist/access-boundary.js +9 -9
- package/dist/access-cli.js +25 -23
- package/dist/access-cli.js.map +1 -1
- package/dist/access-http.d.ts +10 -10
- package/dist/access-http.js +14 -14
- package/dist/access-mcp.d.ts +10 -10
- package/dist/access-mcp.js +13 -13
- package/dist/access-operations-batch.js +11 -11
- package/dist/access-operations.d.ts +10 -10
- package/dist/access-operations.js +12 -12
- package/dist/{access-service-Byoe3HsT.d.ts → access-service-rjFfmfKB.d.ts} +4 -4
- package/dist/access-service.d.ts +10 -10
- package/dist/access-service.js +8 -8
- package/dist/access-surface-catalog.d.ts +10 -10
- package/dist/action-confidence.d.ts +1 -1
- package/dist/active-memory-bridge.d.ts +1 -1
- package/dist/active-memory-bridge.js +3 -2
- package/dist/active-recall.d.ts +1 -1
- package/dist/behavior-learner.d.ts +1 -1
- package/dist/behavior-signals.d.ts +1 -1
- package/dist/bootstrap.d.ts +9 -9
- package/dist/briefing.d.ts +1 -1
- package/dist/buffer-surprise-report.d.ts +1 -1
- package/dist/buffer.d.ts +1 -1
- package/dist/calibration.d.ts +1 -1
- package/dist/capabilities.d.ts +97 -2
- package/dist/capabilities.js +11 -3
- package/dist/{catalog-DM1nk7cM.d.ts → catalog-DHYXzM4-.d.ts} +2 -2
- package/dist/causal-behavior.d.ts +1 -1
- package/dist/causal-consolidation.d.ts +1 -1
- package/dist/causal-trajectory-graph.d.ts +1 -1
- package/dist/{chunk-24D66MMN.js → chunk-2L5RTVMO.js} +7 -4
- package/dist/chunk-2L5RTVMO.js.map +1 -0
- package/dist/{chunk-KQYGNGON.js → chunk-3QETM5NG.js} +6 -3
- package/dist/chunk-3QETM5NG.js.map +1 -0
- package/dist/{chunk-ZQUAVZNG.js → chunk-54RCE5Z3.js} +7 -4
- package/dist/chunk-54RCE5Z3.js.map +1 -0
- package/dist/{chunk-NOU77OHX.js → chunk-5DIKZKOD.js} +2 -2
- package/dist/{chunk-CGPHMNL4.js → chunk-5OYHJIJN.js} +10 -6
- package/dist/chunk-5OYHJIJN.js.map +1 -0
- package/dist/{chunk-LUCARK4W.js → chunk-6U7TES2M.js} +29 -28
- package/dist/chunk-6U7TES2M.js.map +1 -0
- package/dist/{chunk-FFUCCKPN.js → chunk-7FPJFCXL.js} +10 -7
- package/dist/chunk-7FPJFCXL.js.map +1 -0
- package/dist/{chunk-PMAQRUN4.js → chunk-CILX2XW7.js} +5 -2
- package/dist/chunk-CILX2XW7.js.map +1 -0
- package/dist/{chunk-ZVHRSR2R.js → chunk-ET5HXSQL.js} +6 -3
- package/dist/chunk-ET5HXSQL.js.map +1 -0
- package/dist/{chunk-KSJCXXOU.js → chunk-FAGERSH2.js} +6 -3
- package/dist/chunk-FAGERSH2.js.map +1 -0
- package/dist/{chunk-FYWUNVFZ.js → chunk-IDIXGGDN.js} +6 -6
- package/dist/{chunk-CX77GNMB.js → chunk-IWMGBNXY.js} +6 -3
- package/dist/chunk-IWMGBNXY.js.map +1 -0
- package/dist/{chunk-GGL34GCW.js → chunk-IZLTOS5L.js} +7 -4
- package/dist/chunk-IZLTOS5L.js.map +1 -0
- package/dist/{chunk-HHNSLPX7.js → chunk-K7PAILHO.js} +10 -9
- package/dist/chunk-K7PAILHO.js.map +1 -0
- package/dist/{chunk-UZYLX7M6.js → chunk-LV32K4OP.js} +9 -6
- package/dist/chunk-LV32K4OP.js.map +1 -0
- package/dist/{chunk-HJWQJUKQ.js → chunk-NDYQIN6C.js} +3 -3
- package/dist/{chunk-DKT3X5C3.js → chunk-PEF2XOIV.js} +7 -4
- package/dist/chunk-PEF2XOIV.js.map +1 -0
- package/dist/{chunk-646B5ERJ.js → chunk-PKO5NJ65.js} +51 -48
- package/dist/chunk-PKO5NJ65.js.map +1 -0
- package/dist/{chunk-QZHF4BWN.js → chunk-Q5LGXWNG.js} +6 -6
- package/dist/{chunk-ESF7TRYJ.js → chunk-SHJGBAIW.js} +37 -2
- package/dist/{chunk-ESF7TRYJ.js.map → chunk-SHJGBAIW.js.map} +1 -1
- package/dist/{chunk-O4ZIBPIW.js → chunk-T7CGPTFU.js} +3 -3
- package/dist/{chunk-PLBIPT6I.js → chunk-TJSQHO4Q.js} +7 -4
- package/dist/chunk-TJSQHO4Q.js.map +1 -0
- package/dist/{chunk-6TUWSUUD.js → chunk-UF3N7IRP.js} +26 -24
- package/dist/chunk-UF3N7IRP.js.map +1 -0
- package/dist/{chunk-P3VJCTVE.js → chunk-UH3NYOHN.js} +4 -3
- package/dist/chunk-UH3NYOHN.js.map +1 -0
- package/dist/{chunk-J6BH2OBA.js → chunk-UK6U5C3N.js} +8 -5
- package/dist/chunk-UK6U5C3N.js.map +1 -0
- package/dist/{chunk-OTQE66IX.js → chunk-V5OVSGB6.js} +6 -3
- package/dist/chunk-V5OVSGB6.js.map +1 -0
- package/dist/{chunk-H3MB3F62.js → chunk-WHQ2JB35.js} +4 -3
- package/dist/chunk-WHQ2JB35.js.map +1 -0
- package/dist/{chunk-NIZQH6AU.js → chunk-WTTVFSCO.js} +8 -7
- package/dist/chunk-WTTVFSCO.js.map +1 -0
- package/dist/{chunk-OUITHS6V.js → chunk-Z7J3OAPR.js} +357 -325
- package/dist/chunk-Z7J3OAPR.js.map +1 -0
- package/dist/{cli-Dt-tuiYH.d.ts → cli-XVpmSoQs.d.ts} +3 -3
- package/dist/cli.d.ts +11 -11
- package/dist/cli.js +20 -20
- package/dist/compounding/engine.d.ts +3 -2
- package/dist/compounding/engine.js +2 -1
- package/dist/compounding/preference-consolidator.d.ts +1 -1
- package/dist/compression-optimizer.d.ts +1 -1
- package/dist/config.d.ts +1 -1
- package/dist/connectors/codex-materialize-runner.d.ts +1 -1
- package/dist/connectors/codex-materialize.d.ts +1 -1
- package/dist/connectors/index.d.ts +1 -1
- package/dist/consolidation-provenance-check.d.ts +1 -1
- package/dist/consolidation-undo.d.ts +1 -1
- package/dist/contradiction/index.d.ts +2 -2
- package/dist/contradiction/index.js +2 -1
- package/dist/{contradiction-scan-HWGEOUDS.js → contradiction-scan-OUHMCUBT.js} +3 -2
- package/dist/conversation-index/backend.d.ts +1 -1
- package/dist/conversation-index/chunker.d.ts +1 -1
- package/dist/conversation-index/faiss-adapter.d.ts +1 -1
- package/dist/conversation-index/indexer.d.ts +1 -1
- package/dist/conversation-index/search.d.ts +1 -1
- package/dist/day-summary.d.ts +1 -1
- package/dist/delinearize.d.ts +1 -1
- package/dist/direct-answer-wiring.d.ts +1 -1
- package/dist/direct-answer.d.ts +1 -1
- package/dist/embedding-fallback.d.ts +1 -1
- package/dist/embedding-fallback.js +2 -2
- package/dist/enrichment/index.d.ts +1 -1
- package/dist/entity-retrieval.d.ts +1 -1
- package/dist/entity-retrieval.js +2 -1
- package/dist/entity-schema.d.ts +1 -1
- package/dist/explicit-capture.d.ts +9 -9
- package/dist/explicit-capture.js +2 -1
- package/dist/extraction-faithfulness.d.ts +1 -1
- package/dist/extraction-judge-telemetry.d.ts +1 -1
- package/dist/extraction-judge-training.d.ts +1 -1
- package/dist/extraction-judge.d.ts +1 -1
- package/dist/extraction.d.ts +1 -1
- package/dist/extraction.js +3 -3
- package/dist/fallback-llm.d.ts +1 -1
- package/dist/{first-start-migration-OOR57AYR.js → first-start-migration-W4U6XDKI.js} +7 -6
- package/dist/first-start-migration-W4U6XDKI.js.map +1 -0
- package/dist/graph-dashboard-diff.d.ts +1 -1
- package/dist/graph-dashboard-key.d.ts +1 -1
- package/dist/graph-dashboard-parser.d.ts +1 -1
- package/dist/graph-edge-reinforcement.d.ts +1 -1
- package/dist/graph-snapshot.d.ts +1 -1
- package/dist/graph.d.ts +1 -1
- package/dist/identity-continuity.d.ts +1 -1
- package/dist/importance.d.ts +1 -1
- package/dist/index.d.ts +12 -12
- package/dist/index.js +43 -43
- package/dist/intent.d.ts +1 -1
- package/dist/lcm/engine.d.ts +1 -1
- package/dist/lcm/index.d.ts +1 -1
- package/dist/lcm/tools.d.ts +1 -1
- package/dist/lifecycle.d.ts +1 -1
- package/dist/live-connectors-runner.d.ts +1 -1
- package/dist/local-llm.d.ts +1 -1
- package/dist/local-llm.js +2 -1
- package/dist/local-model-endpoint.d.ts +1 -1
- package/dist/maintenance/memory-governance.d.ts +1 -1
- package/dist/mcp-memory-inspector-app.d.ts +10 -10
- package/dist/memory-action-policy.d.ts +1 -1
- package/dist/memory-cache.d.ts +1 -1
- package/dist/memory-lifecycle-ledger-utils.d.ts +1 -1
- package/dist/memory-projection-store.d.ts +1 -1
- package/dist/memory-provenance.d.ts +1 -1
- package/dist/memory-worth-outcomes.d.ts +1 -1
- package/dist/models-json.d.ts +1 -1
- package/dist/namespaces/migrate.d.ts +2 -2
- package/dist/namespaces/migrate.js +6 -6
- package/dist/namespaces/principal.d.ts +1 -1
- package/dist/namespaces/principal.js +2 -1
- package/dist/namespaces/search.d.ts +1 -1
- package/dist/namespaces/search.js +4 -4
- package/dist/namespaces/storage.d.ts +2 -2
- package/dist/namespaces/storage.js +2 -1
- package/dist/native-knowledge.d.ts +1 -1
- package/dist/operator-toolkit.d.ts +1 -1
- package/dist/operator-toolkit.js +11 -11
- package/dist/orchestration/compression-guideline-coordinator.d.ts +1 -1
- package/dist/orchestration/maintenance.d.ts +2 -2
- package/dist/orchestration/maintenance.js +6 -5
- package/dist/{orchestrator-B4KjaOtY.d.ts → orchestrator-BXi-gadS.d.ts} +66 -5
- package/dist/orchestrator.d.ts +5 -5
- package/dist/orchestrator.js +20 -18
- package/dist/patterns-cli.d.ts +1 -1
- package/dist/policy-runtime.d.ts +1 -1
- package/dist/provenance.d.ts +1 -1
- package/dist/qmd-recall-cache.d.ts +1 -1
- package/dist/qmd.d.ts +1 -1
- package/dist/recall-disclosure-escalation.d.ts +1 -1
- package/dist/recall-explain-renderer.d.ts +1 -1
- package/dist/recall-planner-llm.d.ts +1 -1
- package/dist/recall-state.d.ts +1 -1
- package/dist/recall-tag-filter.d.ts +1 -1
- package/dist/recall-xray-cli.d.ts +1 -1
- package/dist/recall-xray-renderer.d.ts +1 -1
- package/dist/recall-xray.d.ts +1 -1
- package/dist/resolve-auth-token.d.ts +1 -1
- package/dist/retrieval-agents.d.ts +1 -1
- package/dist/retrieval-tiers.d.ts +1 -1
- package/dist/routing/engine.d.ts +1 -1
- package/dist/routing/store.d.ts +1 -1
- package/dist/schemas.d.ts +22 -22
- package/dist/search/embed-helper.d.ts +1 -1
- package/dist/search/embed-helper.js +2 -2
- package/dist/search/factory.d.ts +1 -1
- package/dist/search/factory.js +3 -3
- package/dist/search/index.d.ts +1 -1
- package/dist/search/index.js +3 -3
- package/dist/search/lancedb-backend.d.ts +1 -1
- package/dist/search/meilisearch-backend.d.ts +1 -1
- package/dist/search/noop-backend.d.ts +1 -1
- package/dist/search/orama-backend.d.ts +1 -1
- package/dist/search/port.d.ts +1 -1
- package/dist/search/remote-backend.d.ts +1 -1
- package/dist/{semantic-SLAa_prH.d.ts → semantic-DJR8_DMQ.d.ts} +1 -1
- package/dist/{semantic-consolidation-CstTvHPo.d.ts → semantic-consolidation-DeL5grLx.d.ts} +1 -1
- package/dist/semantic-consolidation.d.ts +2 -2
- package/dist/semantic-rule-verifier.d.ts +1 -1
- package/dist/session-observer-bands.d.ts +1 -1
- package/dist/session-observer-state.d.ts +1 -1
- package/dist/shared-context/manager.d.ts +1 -1
- package/dist/signal.d.ts +1 -1
- package/dist/storage.d.ts +1 -1
- package/dist/summarizer.d.ts +1 -1
- package/dist/summarizer.js +3 -2
- package/dist/summary-snapshot.d.ts +1 -1
- package/dist/temporal-supersession.d.ts +1 -1
- package/dist/temporal-validity.d.ts +1 -1
- package/dist/threading.d.ts +1 -1
- package/dist/tier-migration.d.ts +1 -1
- package/dist/tier-routing.d.ts +1 -1
- package/dist/{tier-stats-3LYQ3VV5.js → tier-stats-LSM35HZY.js} +5 -2
- package/dist/tier-stats-LSM35HZY.js.map +1 -0
- package/dist/topics.d.ts +1 -1
- package/dist/transcript.d.ts +1 -1
- package/dist/transfer/types.d.ts +12 -12
- package/dist/trust-score-stage.d.ts +1 -1
- package/dist/trust-score.d.ts +1 -1
- package/dist/{types-VkxElCHR.d.ts → types-CpFz51Pv.d.ts} +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/utility-runtime.d.ts +1 -1
- package/package.json +2 -2
- package/src/access-service.ts +42 -37
- package/src/active-memory-bridge.ts +2 -1
- package/src/admin/admin-surfaces.ts +2 -1
- package/src/capabilities.test.ts +178 -0
- package/src/capabilities.ts +197 -0
- package/src/cli.ts +13 -9
- package/src/compounding/engine.ts +4 -3
- package/src/contradiction/contradiction-scan.ts +4 -3
- package/src/embedding-fallback.ts +5 -2
- package/src/entity-retrieval.ts +3 -2
- package/src/explicit-capture.ts +2 -1
- package/src/extraction.ts +6 -3
- package/src/local-llm.ts +4 -3
- package/src/maintenance/first-start-migration.ts +6 -3
- package/src/maintenance/namespace-maintenance-fanout.ts +2 -1
- package/src/maintenance/namespace-planner.ts +4 -3
- package/src/maintenance/tier-stats.ts +2 -1
- package/src/namespaces/catalog.ts +2 -1
- package/src/namespaces/migrate.ts +2 -1
- package/src/namespaces/principal.ts +6 -5
- package/src/namespaces/scope-profiles.ts +2 -1
- package/src/namespaces/search.ts +2 -1
- package/src/namespaces/storage.ts +4 -3
- package/src/operator-toolkit.ts +19 -18
- package/src/orchestration/maintenance.ts +8 -4
- package/src/orchestration/semantic-consolidation-coordinator.ts +454 -0
- package/src/orchestration/tier-migration-coordinator.ts +5 -4
- package/src/orchestrator.ts +78 -417
- package/src/scopes/scope-plan.ts +3 -2
- package/src/search/embed-helper.ts +5 -2
- package/src/search/factory.ts +9 -6
- package/src/summarizer.ts +3 -2
- package/dist/chunk-24D66MMN.js.map +0 -1
- package/dist/chunk-646B5ERJ.js.map +0 -1
- package/dist/chunk-6TUWSUUD.js.map +0 -1
- package/dist/chunk-CGPHMNL4.js.map +0 -1
- package/dist/chunk-CX77GNMB.js.map +0 -1
- package/dist/chunk-DKT3X5C3.js.map +0 -1
- package/dist/chunk-FFUCCKPN.js.map +0 -1
- package/dist/chunk-GGL34GCW.js.map +0 -1
- package/dist/chunk-H3MB3F62.js.map +0 -1
- package/dist/chunk-HHNSLPX7.js.map +0 -1
- package/dist/chunk-J6BH2OBA.js.map +0 -1
- package/dist/chunk-KQYGNGON.js.map +0 -1
- package/dist/chunk-KSJCXXOU.js.map +0 -1
- package/dist/chunk-LUCARK4W.js.map +0 -1
- package/dist/chunk-NIZQH6AU.js.map +0 -1
- package/dist/chunk-OTQE66IX.js.map +0 -1
- package/dist/chunk-OUITHS6V.js.map +0 -1
- package/dist/chunk-P3VJCTVE.js.map +0 -1
- package/dist/chunk-PLBIPT6I.js.map +0 -1
- package/dist/chunk-PMAQRUN4.js.map +0 -1
- package/dist/chunk-UZYLX7M6.js.map +0 -1
- package/dist/chunk-ZQUAVZNG.js.map +0 -1
- package/dist/chunk-ZVHRSR2R.js.map +0 -1
- package/dist/first-start-migration-OOR57AYR.js.map +0 -1
- package/dist/tier-stats-3LYQ3VV5.js.map +0 -1
- /package/dist/{chunk-NOU77OHX.js.map → chunk-5DIKZKOD.js.map} +0 -0
- /package/dist/{chunk-FYWUNVFZ.js.map → chunk-IDIXGGDN.js.map} +0 -0
- /package/dist/{chunk-HJWQJUKQ.js.map → chunk-NDYQIN6C.js.map} +0 -0
- /package/dist/{chunk-QZHF4BWN.js.map → chunk-Q5LGXWNG.js.map} +0 -0
- /package/dist/{chunk-O4ZIBPIW.js.map → chunk-T7CGPTFU.js.map} +0 -0
- /package/dist/{contradiction-scan-HWGEOUDS.js.map → contradiction-scan-OUHMCUBT.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/embedding-fallback.ts"],"sourcesContent":["import path from \"node:path\";\nimport { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { log } from \"./logger.js\";\nimport { resolveMemoryLifecycleCapabilities } from \"./capabilities.js\";\nimport { readEnvVar } from \"./runtime/env.js\";\nimport type { PluginConfig } from \"./types.js\";\nimport {\n getHostEmbeddingProvider,\n type HostEmbeddingProvider,\n normalizeHostEmbeddingVector,\n} from \"./host-embedding-provider.js\";\n\ntype EmbeddingProviderType = \"openai\" | \"local\" | \"host\";\n\ntype ProviderConfig = {\n type: EmbeddingProviderType;\n model: string;\n endpoint?: string;\n headers?: Record<string, string>;\n hostProvider?: HostEmbeddingProvider;\n};\n\ntype EmbeddingIndexEntry = {\n vector: number[];\n path: string;\n};\n\ntype EmbeddingResult = {\n provider: ProviderConfig;\n vector: number[];\n};\n\ntype EmbeddingIndexFile = {\n version: 1;\n provider: EmbeddingProviderType;\n model: string;\n entries: Record<string, EmbeddingIndexEntry>;\n};\n\ntype EmbeddingIndexIdentity = Pick<EmbeddingIndexFile, \"provider\" | \"model\">;\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 */\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 indexPath: string;\n private loaded: EmbeddingIndexFile | null = null;\n private mutationQueue: Promise<void> = Promise.resolve();\n\n constructor(private readonly config: PluginConfig) {\n this.indexPath = path.join(config.memoryDir, \"state\", \"embeddings.json\");\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\n const diskIdentity = await this.readIndexIdentityFromDisk();\n if (diskIdentity && !sameIndexIdentity(diskIdentity, queryResult.provider)) {\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 queryResult = 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 const index = await this.loadIndex(queryResult.provider);\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(queryResult.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 }\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(async () => {\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);\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(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 for (const indexProvider of providers) {\n const index = await this.loadIndex(indexProvider);\n if (!index.entries[memoryId]) continue;\n delete index.entries[memoryId];\n await this.saveIndex(index);\n }\n });\n }\n\n private enqueueIndexMutation<T>(mutation: () => Promise<T>): Promise<T> {\n const run = this.mutationQueue.catch(() => undefined).then(mutation);\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 this.config.hostEmbeddingProviderEnabled !== 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 (!this.config.localLlmEnabled || !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 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 try {\n const raw = await readFile(this.indexPath, \"utf-8\");\n const parsed = JSON.parse(raw) as EmbeddingIndexFile;\n if (\n parsed &&\n parsed.version === 1 &&\n parsed.provider === provider.type &&\n parsed.model === provider.model &&\n parsed.entries &&\n typeof parsed.entries === \"object\"\n ) {\n this.loaded = {\n version: 1,\n provider: provider.type,\n model: provider.model,\n entries: parsed.entries,\n };\n return this.loaded;\n }\n } catch {\n // ignore and create a new index\n }\n\n this.loaded = {\n version: 1,\n provider: provider.type,\n model: provider.model,\n entries: {},\n };\n return this.loaded;\n }\n\n private async readIndexIdentityFromDisk(): Promise<EmbeddingIndexIdentity | null> {\n try {\n const raw = await readFile(this.indexPath, \"utf-8\");\n const parsed = JSON.parse(raw) as Partial<EmbeddingIndexFile> | null;\n if (\n parsed &&\n parsed.version === 1 &&\n (parsed.provider === \"openai\" ||\n parsed.provider === \"local\" ||\n parsed.provider === \"host\") &&\n typeof parsed.model === \"string\" &&\n parsed.model.length > 0\n ) {\n return {\n provider: parsed.provider,\n model: parsed.model,\n };\n }\n } catch {\n // Missing or invalid indexes are treated as absent; loadIndex() owns\n // creating a fresh file when it is safe to write.\n }\n return null;\n }\n\n private async saveIndex(index: EmbeddingIndexFile): Promise<void> {\n const dir = path.dirname(this.indexPath);\n await mkdir(dir, { recursive: true });\n const tempPath = path.join(\n dir,\n `.embeddings.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,\n );\n try {\n await writeFile(tempPath, JSON.stringify(index), \"utf-8\");\n await rename(tempPath, this.indexPath);\n } catch (err) {\n await rm(tempPath, { force: true }).catch(() => undefined);\n throw err;\n }\n this.loaded = index;\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;AACjB,SAAS,OAAO,UAAU,QAAQ,IAAI,iBAAiB;AA2CvD,IAAM,uBAAuB;AA+BtB,IAAM,wBAAN,cAAoC,MAAM;AAAA,EAC7B,OAAO;AAAA,EACzB,YAAY,SAAiB;AAC3B,UAAM,OAAO;AAAA,EACf;AACF;AAEO,IAAM,oCAAN,cAAgD,MAAM;AAAA,EACzC,OAAO;AAAA,EACzB,YAAY,SAAiB;AAC3B,UAAM,OAAO;AAAA,EACf;AACF;AAEA,SAAS,gCAAgC,KAAuB;AAC9D,SACE,eAAe,yBACf,eAAe;AAEnB;AAmBA,IAAM,sCAAsC;AAe5C,IAAM,qCAAqC;AAE3C,SAAS,kCAA0C;AACjD,QAAM,MAAM,WAAW,mCAAmC;AAC1D,MAAI,KAAK;AACP,UAAM,SAAS,OAAO,GAAG;AACzB,QAAI,OAAO,SAAS,MAAM,KAAK,SAAS,GAAG;AACzC,aAAO,KAAK,MAAM,MAAM;AAAA,IAC1B;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,iCAAyC;AAChD,QAAM,MAAM,WAAW,mCAAmC;AAC1D,MAAI,KAAK;AACP,UAAM,SAAS,OAAO,GAAG;AACzB,QAAI,OAAO,SAAS,MAAM,KAAK,SAAS,GAAG;AACzC,aAAO,KAAK,MAAM,MAAM;AAAA,IAC1B;AAAA,EACF;AACA,SAAO;AACT;AAYO,IAAM,oBAAN,MAAwB;AAAA,EAK7B,YAA6B,QAAsB;AAAtB;AAC3B,SAAK,YAAY,KAAK,KAAK,OAAO,WAAW,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C,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":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/contradiction/contradiction-judge.ts","../src/contradiction/contradiction-scan.ts"],"sourcesContent":["/**\n * Contradiction Judge — LLM-as-judge for semantic contradiction detection (issue #520).\n *\n * Pairs semantically-similar memories and classifies their relationship.\n * Reuses the extraction-judge adapter pattern but with a contradiction-specific\n * prompt and verdict taxonomy.\n *\n * Design constraints:\n * - Default verdict on any failure is \"needs-user\" (rule 48: least-privileged default).\n * - Never auto-resolve; all verdicts enter the review queue.\n * - Content-hash caching avoids redundant LLM calls across runs.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { log } from \"../logger.js\";\nimport type { PluginConfig } from \"../types.js\";\nimport type { LocalLlmClient } from \"../local-llm.js\";\nimport type { FallbackLlmClient } from \"../fallback-llm.js\";\nimport { extractJsonCandidates } from \"../json-extract.js\";\n\n// ── Types ──────────────────────────────────────────────────────────────────────\n\nexport type ContradictionVerdict =\n | \"contradicts\"\n | \"independent\"\n | \"duplicates\"\n | \"needs-user\";\n\nexport interface ContradictionJudgeInput {\n /** Memory ID of the first fact. */\n memoryIdA: string;\n /** Memory ID of the second fact. */\n memoryIdB: string;\n /** Content text of the first fact. */\n textA: string;\n /** Content text of the second fact. */\n textB: string;\n /** Category of the first fact (optional context). */\n categoryA?: string;\n /** Category of the second fact (optional context). */\n categoryB?: string;\n}\n\nexport interface ContradictionJudgeResult {\n /** Memory IDs of the pair. */\n memoryIdA: string;\n memoryIdB: string;\n /** Verdict from the judge. */\n verdict: ContradictionVerdict;\n /** Human-readable rationale. */\n rationale: string;\n /** Confidence in [0, 1]. */\n confidence: number;\n}\n\nexport interface ContradictionJudgeBatchResult {\n /** Results keyed by pair key (\"idA:idB\"). */\n results: Map<string, ContradictionJudgeResult>;\n /** Number served from cache. */\n cached: number;\n /** Number produced by LLM call. */\n judged: number;\n /** Total wall-clock time in ms. */\n elapsed: number;\n}\n\n// ── Prompt ─────────────────────────────────────────────────────────────────────\n\nconst CONTRADICTION_JUDGE_PROMPT = `You are a memory contradiction classifier. You will receive pairs of stored memories and must classify their semantic relationship.\n\nFor each pair, respond with a JSON array where each element has:\n- \"pairKey\": the pairKey provided in the input\n- \"verdict\": one of \"contradicts\", \"independent\", \"duplicates\", \"needs-user\"\n- \"rationale\": one sentence explaining why\n- \"confidence\": number between 0 and 1\n\nVERDICT DEFINITIONS:\n- \"contradicts\": The two memories make claims that cannot both be true. One must be wrong or outdated.\n- \"duplicates\": The two memories convey essentially the same information (near-paraphrase).\n- \"independent\": The memories are topically similar but do not conflict or duplicate.\n- \"needs-user\": Cannot determine with sufficient confidence; requires human review.\n\nIMPORTANT:\n- Be conservative. When in doubt, prefer \"needs-user\" over a wrong classification.\n- Two memories about the same entity/topic are NOT necessarily contradictory.\n- Temporal changes (\"Joshua uses pnpm\" vs \"Joshua switched to npm\") ARE contradictions.\n- Different aspects of the same entity (\"Joshua uses pnpm\" vs \"Joshua works on Remnic\") are \"independent\".`;\n\n// ── Cache ──────────────────────────────────────────────────────────────────────\n\n/** Module-level fallback cache — only used when caller does not supply one. */\nlet defaultVerdictCache: Map<string, ContradictionJudgeResult> = new Map();\nconst CACHE_MAX = 10_000;\n\nfunction pairKey(idA: string, idB: string): string {\n const sorted = [idA, idB].sort();\n return `${sorted[0]}:${sorted[1]}`;\n}\n\nfunction contentHash(a: ContradictionJudgeInput): string {\n // Sort each side pair to be order-independent (matching pairKey behavior)\n const sides = [\n { text: a.textA.trim(), category: (a.categoryA ?? \"\").trim() },\n { text: a.textB.trim(), category: (a.categoryB ?? \"\").trim() },\n ].sort((left, right) => {\n const leftKey = JSON.stringify(left);\n const rightKey = JSON.stringify(right);\n return leftKey.localeCompare(rightKey);\n });\n const normalized = JSON.stringify(sides);\n return createHash(\"sha256\").update(normalized).digest(\"hex\").slice(0, 16);\n}\n\nexport function createVerdictCache(): Map<string, ContradictionJudgeResult> {\n return new Map();\n}\n\nexport function clearVerdictCache(): void {\n defaultVerdictCache.clear();\n}\n\nexport function verdictCacheSize(): number {\n return defaultVerdictCache.size;\n}\n\n// ── Public API ──────────────────────────────────────────────────────────────────\n\n/**\n * Judge a batch of memory pairs for contradiction.\n *\n * Uses content-hash caching to skip pairs already judged in a prior run.\n * On any LLM failure, all unresolved pairs default to \"needs-user\".\n */\nexport async function judgeContradictionPairs(\n pairs: ContradictionJudgeInput[],\n config: PluginConfig,\n localLlm: LocalLlmClient | null,\n fallbackLlm: FallbackLlmClient | null,\n cache?: Map<string, ContradictionJudgeResult>,\n): Promise<ContradictionJudgeBatchResult> {\n const startTime = Date.now();\n const results = new Map<string, ContradictionJudgeResult>();\n const activeCache = cache ?? defaultVerdictCache;\n let cached = 0;\n let judged = 0;\n\n // Partition into cached vs needs-judging\n const toJudge: ContradictionJudgeInput[] = [];\n for (const pair of pairs) {\n const key = pairKey(pair.memoryIdA, pair.memoryIdB);\n const hash = contentHash(pair);\n const cachedResult = activeCache.get(hash);\n if (cachedResult) {\n results.set(key, { ...cachedResult, memoryIdA: pair.memoryIdA, memoryIdB: pair.memoryIdB });\n cached++;\n } else {\n toJudge.push(pair);\n }\n }\n\n if (toJudge.length === 0) {\n return { results, cached, judged, elapsed: Date.now() - startTime };\n }\n\n // Build the prompt with all pairs\n const pairDescriptions = toJudge.map((p, i) => {\n const pk = pairKey(p.memoryIdA, p.memoryIdB);\n const catA = p.categoryA ? ` [${p.categoryA}]` : \"\";\n const catB = p.categoryB ? ` [${p.categoryB}]` : \"\";\n return `Pair ${i + 1} (pairKey: \"${pk}\"):${catA} \"${p.textA}\"${catB} \"${p.textB}\"`;\n });\n\n const userMessage = `Classify these ${toJudge.length} memory pair(s):\\n\\n${pairDescriptions.join(\"\\n\\n\")}`;\n\n // Try LLM call\n let llmResponse: string | null = null;\n\n if (localLlm) {\n try {\n llmResponse = await callLlm(localLlm, config, userMessage);\n } catch (err) {\n log.warn(\"[contradiction-judge] local LLM call failed: %s\", err instanceof Error ? err.message : err);\n }\n }\n\n if (!llmResponse && fallbackLlm) {\n try {\n llmResponse = await callLlm(fallbackLlm, config, userMessage);\n } catch (err) {\n log.warn(\"[contradiction-judge] fallback LLM call failed: %s\", err instanceof Error ? err.message : err);\n }\n }\n\n // Parse response or default to needs-user\n if (llmResponse) {\n const candidates = extractJsonCandidates(llmResponse);\n const parsed = parseJudgeResponse(candidates, toJudge);\n\n for (const result of parsed) {\n const key = pairKey(result.memoryIdA, result.memoryIdB);\n results.set(key, result);\n\n // Update cache\n const input = toJudge.find(\n (p) => pairKey(p.memoryIdA, p.memoryIdB) === key,\n );\n if (input) {\n const hash = contentHash(input);\n if (activeCache.size >= CACHE_MAX) {\n const firstKey = activeCache.keys().next().value;\n if (firstKey !== undefined) activeCache.delete(firstKey);\n }\n activeCache.set(hash, result);\n }\n judged++;\n }\n } else {\n // All unresolved → needs-user (rule 48)\n for (const pair of toJudge) {\n const key = pairKey(pair.memoryIdA, pair.memoryIdB);\n const result: ContradictionJudgeResult = {\n memoryIdA: pair.memoryIdA,\n memoryIdB: pair.memoryIdB,\n verdict: \"needs-user\",\n rationale: \"LLM call failed; requires manual review\",\n confidence: 0,\n };\n results.set(key, result);\n judged++;\n }\n }\n\n return { results, cached, judged, elapsed: Date.now() - startTime };\n}\n\n// ── Internals ──────────────────────────────────────────────────────────────────\n\nasync function callLlm(\n client: LocalLlmClient | FallbackLlmClient,\n config: PluginConfig,\n userMessage: string,\n): Promise<string> {\n const messages: Array<{ role: \"user\" | \"assistant\" | \"system\"; content: string }> = [\n { role: \"system\", content: CONTRADICTION_JUDGE_PROMPT },\n { role: \"user\", content: userMessage },\n ];\n if (\"chatCompletion\" in client && typeof client.chatCompletion === \"function\") {\n const result = await client.chatCompletion(messages, {\n temperature: 0.1,\n maxTokens: 4096,\n operation: \"contradiction-judge\",\n });\n return result?.content ?? \"\";\n }\n // FallbackLlmClient — try OpenAI-compatible chat completions\n if (\"complete\" in client && typeof (client as Record<string, unknown>).complete === \"function\") {\n const result = await (client as { complete: (msg: Array<{ role: string; content: string }>) => Promise<{ content: string }> }).complete(messages);\n return result.content ?? \"\";\n }\n return \"\";\n}\n\nfunction parseJudgeResponse(\n candidates: string[],\n inputs: ContradictionJudgeInput[],\n): ContradictionJudgeResult[] {\n const VALID_VERDICTS: ContradictionVerdict[] = [\"contradicts\", \"independent\", \"duplicates\", \"needs-user\"];\n let conservativeFallback: ContradictionJudgeResult[] | null = null;\n\n for (const candidate of candidates) {\n try {\n const parsed = JSON.parse(candidate);\n const items = Array.isArray(parsed) ? parsed : [parsed];\n const results: ContradictionJudgeResult[] = [];\n const matchedKeys = new Set<string>();\n\n for (const item of items) {\n if (!item || typeof item !== \"object\") continue;\n\n const verdict = typeof item.verdict === \"string\" && VALID_VERDICTS.includes(item.verdict as ContradictionVerdict)\n ? (item.verdict as ContradictionVerdict)\n : \"needs-user\";\n\n const pairKeyVal = typeof item.pairKey === \"string\" && item.pairKey.length > 0\n ? item.pairKey\n : null;\n const input = pairKeyVal\n ? inputs.find((p) => pairKey(p.memoryIdA, p.memoryIdB) === pairKeyVal)\n : null;\n\n if (!input) continue;\n\n matchedKeys.add(pairKey(input.memoryIdA, input.memoryIdB));\n\n const confidence = typeof item.confidence === \"number\"\n ? Math.min(1, Math.max(0, item.confidence))\n : 0.5;\n\n results.push({\n memoryIdA: input.memoryIdA,\n memoryIdB: input.memoryIdB,\n verdict,\n rationale: typeof item.rationale === \"string\" ? item.rationale : \"No rationale provided\",\n confidence,\n });\n }\n\n // Backfill any inputs the LLM omitted with needs-user\n for (const inp of inputs) {\n const key = pairKey(inp.memoryIdA, inp.memoryIdB);\n if (!matchedKeys.has(key)) {\n results.push({\n memoryIdA: inp.memoryIdA,\n memoryIdB: inp.memoryIdB,\n verdict: \"needs-user\",\n rationale: \"LLM response omitted this pair\",\n confidence: 0,\n });\n }\n }\n\n if (matchedKeys.size > 0) return results;\n if (results.length > 0 && conservativeFallback === null) {\n conservativeFallback = results;\n }\n } catch {\n continue;\n }\n }\n\n if (conservativeFallback !== null) return conservativeFallback;\n\n // All parse attempts failed → needs-user for every input\n return inputs.map((p) => ({\n memoryIdA: p.memoryIdA,\n memoryIdB: p.memoryIdB,\n verdict: \"needs-user\" as ContradictionVerdict,\n rationale: \"Failed to parse judge response\",\n confidence: 0,\n }));\n}\n\nexport { pairKey as _pairKey, contentHash as _contentHash };\n","/**\n * Contradiction Scan — pair generator + scan driver (issue #520).\n *\n * Nightly cron that pairs semantically-similar active memories within\n * the same namespace, sends candidate pairs to the LLM-as-judge\n * contradiction classifier, and drops contradicting pairs into a\n * review queue for user resolution.\n *\n * Pair generation (cheap pre-filter):\n * 1. Find candidate peers via embedding cosine >= similarityFloor.\n * 2. Restrict to pairs sharing at least one entityRef OR overlapping\n * topic tokens >= topicOverlapFloor.\n * 3. Skip pairs already judged independent/both-valid within cooldown.\n * 4. Cap per-run work at maxPairsPerRun.\n */\n\nimport type { StorageManager } from \"../storage.js\";\nimport type { PluginConfig, MemoryFile, MemoryStatus } from \"../types.js\";\nimport type { SemanticDedupLookup } from \"../dedup/semantic.js\";\nimport { log } from \"../logger.js\";\nimport { judgeContradictionPairs, type ContradictionJudgeInput } from \"./contradiction-judge.js\";\nimport {\n writePairs,\n readPair,\n isCoolingDown,\n memoryHashesChanged,\n computeMemoryContentHash,\n computePairId,\n migrateUnscopedPairsToNamespace,\n type ContradictionPair,\n} from \"./contradiction-review.js\";\nimport type { LocalLlmClient } from \"../local-llm.js\";\nimport type { FallbackLlmClient } from \"../fallback-llm.js\";\n\n// ── Types ──────────────────────────────────────────────────────────────────────\n\n/** The set of statuses that represent \"live\" memories eligible for scanning. */\nexport const ACTIVE_STATUSES: Set<MemoryStatus> = new Set([\"active\"]);\n\n/** High-value taxonomy buckets to scan. */\nconst SCAN_CATEGORIES = new Set([\n \"decision\",\n \"principle\",\n \"rule\",\n \"entity\",\n \"fact\",\n \"preference\",\n]);\n\nexport interface ScanResult {\n /** Total active memories scanned. */\n scanned: number;\n /** Candidate pairs generated by the pre-filter. */\n candidates: number;\n /** Pairs sent to judge. */\n judged: number;\n /** Pairs written to review queue. */\n queued: number;\n /** Pairs skipped due to cooldown. */\n cooledDown: number;\n /** Total wall-clock time in ms. */\n elapsedMs: number;\n}\n\nexport interface ScanStorageResolution {\n storage: StorageManager;\n namespace?: string;\n}\n\nexport interface ScanDependencies {\n storage: StorageManager;\n config: PluginConfig;\n memoryDir: string;\n /** Pre-built embedding lookup. When provided, used as-is for Strategy 3. */\n embeddingLookup?: SemanticDedupLookup;\n /**\n * Factory to build a namespace-scoped embedding lookup.\n * When provided, takes precedence over `embeddingLookup`.\n * The scan driver passes its own `storage` so the lookup queries the correct index.\n */\n embeddingLookupFactory?: (storage: StorageManager) => SemanticDedupLookup | undefined;\n /** Resolver for namespace-scoped storage. Required for scans when namespaces are enabled. */\n storageForNamespace?: (\n namespace: string | undefined,\n ) => StorageManager | ScanStorageResolution | Promise<StorageManager | ScanStorageResolution>;\n localLlm: LocalLlmClient | null;\n fallbackLlm: FallbackLlmClient | null;\n namespace?: string;\n}\n\n// ── Main scan driver ───────────────────────────────────────────────────────────\n\n/**\n * Run a contradiction scan over the memory corpus.\n *\n * This is the entry point called by the nightly cron and by the CLI.\n */\nexport async function runContradictionScan(deps: ScanDependencies): Promise<ScanResult> {\n const startTime = Date.now();\n const { config, memoryDir, embeddingLookup, embeddingLookupFactory, localLlm, fallbackLlm } = deps;\n const requestedNamespace = normalizeScanNamespace(deps.namespace);\n const scanConfig = config.contradictionScan;\n\n if (!scanConfig.enabled) {\n log.info(\"[contradiction-scan] disabled by config\");\n return { scanned: 0, candidates: 0, judged: 0, queued: 0, cooledDown: 0, elapsedMs: 0 };\n }\n\n const { storage: scanStorage, namespace } = await resolveScanStorage(deps, requestedNamespace);\n if (config.namespacesEnabled && namespace !== undefined && isDefaultNamespaceScan(config, requestedNamespace, namespace)) {\n const migrated = migrateUnscopedPairsToNamespace(memoryDir, namespace, { cooldownDays: scanConfig.cooldownDays });\n if (migrated > 0) {\n log.info(\"[contradiction-scan] migrated %d legacy unscoped review pairs to namespace %s\", migrated, namespace);\n }\n }\n\n // Prefer the factory (which uses the scan's own storage for correct namespace scoping)\n // over a pre-built lookup (which may use default-namespace storage).\n const scopedEmbeddingLookup = embeddingLookupFactory\n ? embeddingLookupFactory(scanStorage)\n : embeddingLookup;\n\n // 1. Load active memories in scan categories\n const memories = await loadEligibleMemories(scanStorage);\n log.info(\"[contradiction-scan] loaded %d eligible memories\", memories.length);\n\n if (memories.length < 2) {\n return { scanned: memories.length, candidates: 0, judged: 0, queued: 0, cooledDown: 0, elapsedMs: Date.now() - startTime };\n }\n\n // 2. Prepare exact existing-pair lookup for cooldown checking.\n // Pair IDs are deterministic, so lookup the candidate's file directly instead\n // of paging through the review queue and risking a bounded-list miss.\n const existingPairCache = new Map<string, ContradictionPair | undefined>();\n const getExistingPair = (pairId: string): ContradictionPair | undefined => {\n if (!existingPairCache.has(pairId)) {\n existingPairCache.set(pairId, readPair(memoryDir, pairId) ?? undefined);\n }\n return existingPairCache.get(pairId);\n };\n\n // 3. Generate candidate pairs\n const candidates = await generatePairs(memories, getExistingPair, scanConfig, namespace, scopedEmbeddingLookup);\n const cooledDown = candidates.skipped;\n log.info(\"[contradiction-scan] generated %d candidates (%d cooled down)\", candidates.pairs.length, cooledDown);\n\n if (candidates.pairs.length === 0) {\n return {\n scanned: memories.length,\n candidates: 0,\n judged: 0,\n queued: 0,\n cooledDown,\n elapsedMs: Date.now() - startTime,\n };\n }\n\n // 4. Build judge inputs. Candidate generation already preserves strategy\n // priority and caps work at maxPairsPerRun.\n const judgeInputs: ContradictionJudgeInput[] = candidates.pairs.map((pair) => ({\n memoryIdA: pair.idA,\n memoryIdB: pair.idB,\n textA: pair.textA,\n textB: pair.textB,\n categoryA: pair.categoryA,\n categoryB: pair.categoryB,\n }));\n\n // 6. Send to judge (per-scan cache avoids module-level singleton leak)\n const scanCache = new Map<string, import(\"./contradiction-judge.js\").ContradictionJudgeResult>();\n const judgeResult = await judgeContradictionPairs(judgeInputs, config, localLlm, fallbackLlm, scanCache);\n log.info(\"[contradiction-scan] judge completed: %d judged, %d cached in %dms\", judgeResult.judged, judgeResult.cached, judgeResult.elapsed);\n\n // 7. Write to review queue\n const queueEntries: Array<Omit<ContradictionPair, \"pairId\"> & { memoryIds: [string, string] }> = [];\n const currentMemoryHashes = memoryContentHashMap(memories);\n for (const [key, result] of judgeResult.results) {\n queueEntries.push({\n memoryIds: [result.memoryIdA, result.memoryIdB],\n verdict: result.verdict,\n rationale: result.rationale,\n confidence: result.confidence,\n detectedAt: new Date().toISOString(),\n // Set lastReviewedAt for non-actionable verdicts so cooldown prevents re-judging\n lastReviewedAt: result.verdict === \"independent\" ? new Date().toISOString() : undefined,\n memoryContentHashes: pairMemoryContentHashes(result.memoryIdA, result.memoryIdB, currentMemoryHashes),\n namespace,\n });\n }\n\n const written = writePairs(memoryDir, queueEntries, { cooldownDays: scanConfig.cooldownDays });\n const elapsed = Date.now() - startTime;\n log.info(\"[contradiction-scan] complete: %d queued in %dms\", written.length, elapsed);\n\n return {\n scanned: memories.length,\n candidates: candidates.pairs.length,\n judged: judgeResult.judged,\n queued: written.length,\n cooledDown,\n elapsedMs: elapsed,\n };\n}\n\n// ── Pair generation ────────────────────────────────────────────────────────────\n\ninterface CandidatePair {\n idA: string;\n idB: string;\n textA: string;\n textB: string;\n categoryA?: string;\n categoryB?: string;\n}\n\ninterface PairGenResult {\n pairs: CandidatePair[];\n skipped: number;\n}\n\nasync function generatePairs(\n memories: MemoryFile[],\n getExistingPair: (pairId: string) => ContradictionPair | undefined,\n scanConfig: PluginConfig[\"contradictionScan\"],\n namespace: string | undefined,\n embeddingLookup?: SemanticDedupLookup,\n): Promise<PairGenResult> {\n const pairs: CandidatePair[] = [];\n let skipped = 0;\n const seen = new Set<string>();\n const maxPairs = Math.max(0, Math.floor(scanConfig.maxPairsPerRun));\n if (maxPairs === 0) return { pairs, skipped };\n\n const orderedMemories = [...memories].sort(compareMemoryId);\n const currentMemoryHashes = memoryContentHashMap(orderedMemories);\n\n const pushCandidate = (pair: CandidatePair): void => {\n if (pairs.length < maxPairs) pairs.push(pair);\n };\n\n const hasCapacity = (): boolean => pairs.length < maxPairs;\n const isSkippedByCooldown = (existing: ContradictionPair | undefined): boolean => {\n if (!existing || !isCoolingDown(existing, scanConfig.cooldownDays)) return false;\n return !memoryHashesChanged(\"\", existing, (memoryId) => currentMemoryHashes.get(memoryId) ?? null);\n };\n\n // Build index by entityRef for fast lookup\n const byEntity = new Map<string, MemoryFile[]>();\n for (const mem of orderedMemories) {\n const entity = mem.frontmatter.entityRef;\n if (entity) {\n const existing = byEntity.get(entity) ?? [];\n existing.push(mem);\n byEntity.set(entity, existing);\n }\n }\n\n // Strategy 1: Entity-ref based pairing (high precision)\n entityPairs:\n for (const entity of [...byEntity.keys()].sort()) {\n const group = byEntity.get(entity) ?? [];\n if (group.length < 2) continue;\n for (let i = 0; i < group.length; i++) {\n for (let j = i + 1; j < group.length; j++) {\n if (!hasCapacity()) break entityPairs;\n const a = group[i];\n const b = group[j];\n const pairId = computePairId(a.frontmatter.id!, b.frontmatter.id!, namespace);\n\n if (seen.has(pairId)) continue;\n seen.add(pairId);\n\n // Check cooldown\n const existing = getExistingPair(pairId);\n if (isSkippedByCooldown(existing)) {\n skipped++;\n continue;\n }\n\n pushCandidate({\n idA: a.frontmatter.id!,\n idB: b.frontmatter.id!,\n textA: a.content,\n textB: b.content,\n categoryA: a.frontmatter.category as string | undefined,\n categoryB: b.frontmatter.category as string | undefined,\n });\n }\n }\n }\n\n // Strategy 2: Tag/topic overlap for memories without a shared entityRef\n topicPairs:\n for (let i = 0; i < orderedMemories.length; i++) {\n for (let j = i + 1; j < orderedMemories.length; j++) {\n if (!hasCapacity()) break topicPairs;\n const a = orderedMemories[i];\n const b = orderedMemories[j];\n if (shareEntityRef(a, b)) continue;\n const overlap = jaccardOverlap(\n (a.frontmatter.tags as string[]) ?? [],\n (b.frontmatter.tags as string[]) ?? [],\n );\n\n if (overlap < scanConfig.topicOverlapFloor) continue;\n\n const pairId = computePairId(a.frontmatter.id!, b.frontmatter.id!, namespace);\n if (seen.has(pairId)) continue;\n seen.add(pairId);\n\n const existing = getExistingPair(pairId);\n if (isSkippedByCooldown(existing)) {\n skipped++;\n continue;\n }\n\n pushCandidate({\n idA: a.frontmatter.id!,\n idB: b.frontmatter.id!,\n textA: a.content,\n textB: b.content,\n categoryA: a.frontmatter.category as string | undefined,\n categoryB: b.frontmatter.category as string | undefined,\n });\n }\n }\n\n // Strategy 3: Embedding cosine similarity (enforces similarityFloor config)\n if (embeddingLookup && hasCapacity()) {\n const memoryById = new Map(orderedMemories.map((m) => [m.frontmatter.id!, m]));\n embeddingPairs:\n for (const mem of orderedMemories) {\n if (!hasCapacity()) break;\n const id = mem.frontmatter.id!;\n try {\n const hits = (await embeddingLookup(mem.content, 20)).sort((a, b) =>\n b.score - a.score || a.id.localeCompare(b.id),\n );\n for (const hit of hits) {\n if (!hasCapacity()) break embeddingPairs;\n if (hit.score < scanConfig.similarityFloor) continue;\n if (hit.id === id) continue;\n const peer = memoryById.get(hit.id);\n if (!peer) continue;\n\n const pairId = computePairId(id, hit.id, namespace);\n if (seen.has(pairId)) continue;\n seen.add(pairId);\n\n const existing = getExistingPair(pairId);\n if (isSkippedByCooldown(existing)) {\n skipped++;\n continue;\n }\n\n pushCandidate({\n idA: id,\n idB: hit.id,\n textA: mem.content,\n textB: peer.content,\n categoryA: mem.frontmatter.category as string | undefined,\n categoryB: peer.frontmatter.category as string | undefined,\n });\n }\n } catch {\n // Embedding backend unavailable — skip, entity-ref/tag strategies already covered\n }\n }\n }\n\n return { pairs, skipped };\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────────────\n\nfunction normalizeScanNamespace(namespace: string | undefined): string | undefined {\n const trimmed = namespace?.trim();\n return trimmed ? trimmed : undefined;\n}\n\nasync function resolveScanStorage(\n deps: ScanDependencies,\n namespace: string | undefined,\n): Promise<ScanStorageResolution> {\n if (!deps.config.namespacesEnabled) {\n const defaultNamespace = normalizeScanNamespace(deps.config.defaultNamespace);\n if (namespace && namespace !== defaultNamespace) {\n throw new Error(`unsupported namespace: ${namespace}`);\n }\n return { storage: deps.storage, namespace: undefined };\n }\n\n if (deps.storageForNamespace) {\n const resolved = await deps.storageForNamespace(namespace);\n if (isScanStorageResolution(resolved)) {\n return {\n storage: resolved.storage,\n namespace: normalizeScanNamespace(resolved.namespace) ?? fallbackResolvedNamespace(deps, namespace),\n };\n }\n if (!isStorageManagerLike(resolved)) {\n throw new Error(\"storageForNamespace must return a StorageManager or { storage: StorageManager, namespace?: string }\");\n }\n return {\n storage: resolved,\n namespace: fallbackResolvedNamespace(deps, namespace),\n };\n }\n\n throw new Error(\n \"contradiction scans require storageForNamespace when namespaces are enabled so callers can enforce namespace access\",\n );\n}\n\nfunction isScanStorageResolution(value: StorageManager | ScanStorageResolution): value is ScanStorageResolution {\n if (isStorageManagerLike(value)) return false;\n if (typeof value !== \"object\" || value === null) return false;\n const candidate = value as { storage?: unknown };\n return isStorageManagerLike(candidate.storage);\n}\n\nfunction isStorageManagerLike(value: unknown): value is StorageManager {\n if (typeof value !== \"object\" || value === null) return false;\n const candidate = value as { readAllMemories?: unknown };\n return typeof candidate.readAllMemories === \"function\";\n}\n\nfunction fallbackResolvedNamespace(deps: ScanDependencies, namespace: string | undefined): string | undefined {\n if (namespace) return namespace;\n return deps.config.namespacesEnabled ? deps.config.defaultNamespace : undefined;\n}\n\nfunction isDefaultNamespaceScan(\n config: PluginConfig,\n requestedNamespace: string | undefined,\n resolvedNamespace: string,\n): boolean {\n if (requestedNamespace === undefined) return true;\n return requestedNamespace === config.defaultNamespace || resolvedNamespace === config.defaultNamespace;\n}\n\nasync function loadEligibleMemories(storage: StorageManager): Promise<MemoryFile[]> {\n let all: MemoryFile[];\n try {\n all = await storage.readAllMemories();\n } catch {\n return [];\n }\n\n return all.filter((mem) => {\n const fm = mem.frontmatter;\n // Only active memories (rule 53: explicit ACTIVE_STATUSES set)\n const status = (fm.status as MemoryStatus) ?? \"active\";\n if (!ACTIVE_STATUSES.has(status)) return false;\n\n // Only scan high-value categories\n const category = fm.category as string | undefined;\n if (category && !SCAN_CATEGORIES.has(category)) return false;\n\n // Must have content\n if (!mem.content || mem.content.trim().length === 0) return false;\n\n // Must have an ID\n if (!fm.id) return false;\n\n return true;\n });\n}\n\nfunction jaccardOverlap(a: string[], b: string[]): number {\n if (a.length === 0 && b.length === 0) return 0;\n const setA = new Set(a.map((t) => t.toLowerCase()));\n const setB = new Set(b.map((t) => t.toLowerCase()));\n let intersection = 0;\n for (const item of setA) {\n if (setB.has(item)) intersection++;\n }\n const union = setA.size + setB.size - intersection;\n return union === 0 ? 0 : intersection / union;\n}\n\nfunction shareEntityRef(a: MemoryFile, b: MemoryFile): boolean {\n const entityA = a.frontmatter.entityRef?.trim();\n const entityB = b.frontmatter.entityRef?.trim();\n return Boolean(entityA && entityB && entityA === entityB);\n}\n\nfunction compareMemoryId(a: MemoryFile, b: MemoryFile): number {\n return (a.frontmatter.id ?? \"\").localeCompare(b.frontmatter.id ?? \"\");\n}\n\nfunction memoryContentHashMap(memories: MemoryFile[]): Map<string, string> {\n const hashes = new Map<string, string>();\n for (const memory of memories) {\n const id = memory.frontmatter.id;\n if (!id) continue;\n hashes.set(id, computeMemoryContentHash(memory.content, memory.frontmatter.category as string | undefined));\n }\n return hashes;\n}\n\nfunction pairMemoryContentHashes(\n memoryIdA: string,\n memoryIdB: string,\n currentMemoryHashes: Map<string, string>,\n): Record<string, string> | undefined {\n const hashA = currentMemoryHashes.get(memoryIdA);\n const hashB = currentMemoryHashes.get(memoryIdB);\n if (!hashA || !hashB) return undefined;\n return {\n [memoryIdA]: hashA,\n [memoryIdB]: hashB,\n };\n}\n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,QAAM,QAAQ,oBAAoB,IAAI,SAAS;AAC/C,QAAM,QAAQ,oBAAoB,IAAI,SAAS;AAC/C,MAAI,CAAC,SAAS,CAAC,MAAO,QAAO;AAC7B,SAAO;AAAA,IACL,CAAC,SAAS,GAAG;AAAA,IACb,CAAC,SAAS,GAAG;AAAA,EACf;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/explicit-capture.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { Orchestrator } from \"./orchestrator.js\";\nimport { isSafeRouteNamespace } from \"./routing/engine.js\";\nimport { sanitizeMemoryContent } from \"./sanitize.js\";\nimport { ContentHashIndex } from \"./storage.js\";\nimport type { CaptureMode, MemoryCategory, MemoryLifecycleEvent, PluginConfig } from \"./types.js\";\n\nexport type ExplicitCaptureInput = {\n content: string;\n category?: string;\n confidence?: number;\n namespace?: string;\n tags?: string[];\n entityRef?: string;\n ttl?: string;\n sourceReason?: string;\n};\n\nexport type ValidExplicitCapture = {\n content: string;\n category: MemoryCategory;\n confidence: number;\n namespace?: string;\n tags: string[];\n entityRef?: string;\n expiresAt?: string;\n sourceReason?: string;\n /**\n * When true, `namespace` was already resolved AND authorized by the caller\n * (the access service's `resolveCodingScopedWriteNamespace`, which auth-checks\n * the base and derives a session-owned `project-*` overlay). The persist /\n * queue layer then routes to it directly instead of re-validating against the\n * static policy allow-list — which would otherwise reject legitimately-derived\n * dynamic project namespaces (#1434). Callers that do NOT pre-authorize the\n * namespace must leave this unset so the allow-list guard still applies.\n */\n namespacePreResolved?: boolean;\n};\n\nexport type ExplicitCaptureSource = \"memory_store\" | \"memory_capture\" | \"suggestion_submit\" | \"inline\";\ntype ExplicitCaptureValidationMode = \"legacy_tool\" | \"strict_explicit\";\n\n// Bounded body {0,100000} instead of an unbounded lazy *? so scanning for the\n// closing tag cannot backtrack polynomially on unterminated <memory_note>\n// markup in hostile turn text (CodeQL js/polynomial-redos). 100 000 chars far\n// exceeds any real inline note, so matching is behavior-preserving; the outer\n// \\s* groups were also dropped (body absorbs whitespace; captures are trimmed).\nconst INLINE_NOTE_RE = /<memory_note>([\\s\\S]{0,100000}?)<\\/memory_note>/gi;\nconst INLINE_NOTE_MARKUP_RE = /<memory_note>[\\s\\S]{0,100000}?<\\/memory_note>/i;\nconst INLINE_ALLOWED_CATEGORIES = new Set<MemoryCategory>([\n \"fact\",\n \"preference\",\n \"correction\",\n \"entity\",\n \"decision\",\n \"relationship\",\n \"principle\",\n \"commitment\",\n \"moment\",\n \"skill\",\n \"rule\",\n \"procedure\",\n \"reasoning_trace\",\n]);\n\nconst SECRET_PATTERNS: RegExp[] = [\n /\\bsk-[A-Za-z0-9]{16,}\\b/,\n /\\bAKIA[0-9A-Z]{16}\\b/,\n /\\bBearer\\s+[A-Za-z0-9._-]{16,}\\b/i,\n /\\b(?:api[_-]?key|secret|token|password|passwd)\\s*[:=]\\s*[^\\s]{8,}\\b/i,\n /\\b(?:authorization)\\s*:\\s*[^\\s]{8,}\\b/i,\n];\nconst SECRET_REDACTION_PATTERNS: Array<{ pattern: RegExp; replacement: string }> = [\n { pattern: /\\bsk-[A-Za-z0-9]{16,}\\b/g, replacement: \"[redacted openai key]\" },\n { pattern: /\\bAKIA[0-9A-Z]{16}\\b/g, replacement: \"[redacted aws key]\" },\n { pattern: /\\bBearer\\s+[A-Za-z0-9._-]{16,}\\b/gi, replacement: \"Bearer [redacted token]\" },\n {\n pattern: /\\b(?:api[_-]?key|secret|token|password|passwd)\\s*[:=]\\s*[^\\s]{8,}\\b/gi,\n replacement: \"[redacted credential]\",\n },\n {\n pattern: /\\b(?:authorization)\\s*:\\s*[^\\s]{8,}\\b/gi,\n replacement: \"authorization: [redacted credential]\",\n },\n];\nconst EXPLICIT_CAPTURE_REVIEW_TAGS = [\"explicit-capture\", \"queued-review\"];\n\nfunction explicitCaptureActor(source: ExplicitCaptureSource): string {\n switch (source) {\n case \"inline\":\n return \"inline.memory_note\";\n case \"memory_store\":\n return \"tool.memory_store\";\n case \"suggestion_submit\":\n return \"tool.suggestion_submit\";\n default:\n return \"tool.memory_capture\";\n }\n}\n\nfunction asTrimmed(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction normalizeCaptureContent(value: string): string {\n return value\n .toLowerCase()\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\nfunction redactSecrets(value: string): string {\n let redacted = value;\n for (const { pattern, replacement } of SECRET_REDACTION_PATTERNS) {\n redacted = redacted.replace(pattern, replacement);\n }\n return redacted;\n}\n\nfunction containsSecretLikeValue(value: string): boolean {\n return SECRET_PATTERNS.some((pattern) => pattern.test(value));\n}\n\nfunction assertNoSecretLikeMetadata(field: string, value: string | undefined): void {\n const trimmed = asTrimmed(value);\n if (trimmed && containsSecretLikeValue(trimmed)) {\n throw new Error(`${field} appears to contain a secret or credential`);\n }\n}\n\nfunction assertNoSecretLikeMetadataList(field: string, values: string[] | undefined): void {\n for (const value of values ?? []) {\n assertNoSecretLikeMetadata(field, value);\n }\n}\n\nfunction sanitizeReviewText(value: string | undefined, fallback: string): string {\n const redacted = redactSecrets(asTrimmed(value) ?? fallback);\n const sanitized = sanitizeMemoryContent(redacted);\n const safe = sanitized.text.trim();\n return safe.length > 0 ? safe : fallback;\n}\n\nfunction sanitizeReviewMetadata(value: string | undefined): string | undefined {\n const trimmed = asTrimmed(value);\n if (!trimmed) return undefined;\n return sanitizeReviewText(trimmed, \"[redacted]\");\n}\n\nfunction sanitizeReviewTags(tags: string[] | undefined): string[] {\n return Array.from(new Set((tags ?? [])\n .map((tag) => sanitizeReviewMetadata(tag))\n .filter((tag): tag is string => typeof tag === \"string\" && tag.length > 0)));\n}\n\nfunction normalizeExplicitCaptureError(error: unknown): string {\n if (error instanceof Error && error.message.trim().length > 0) return error.message.trim();\n const rendered = String(error).trim();\n return rendered.length > 0 ? rendered : \"explicit capture failed\";\n}\n\nfunction resolveExplicitCaptureReviewNamespace(\n orchestrator: Orchestrator,\n namespace: string | undefined,\n): string | undefined {\n const normalized = asTrimmed(namespace);\n if (!normalized) return undefined;\n return resolveExplicitCaptureNamespace(orchestrator, normalized);\n}\n\nfunction resolveExplicitCaptureNamespace(\n orchestrator: Orchestrator,\n namespace: string | undefined,\n): string | undefined {\n const normalized = asTrimmed(namespace);\n if (!normalized) return undefined;\n if (!orchestrator.config.namespacesEnabled) {\n if (normalized !== orchestrator.config.defaultNamespace) {\n throw new Error(`unsupported namespace: ${normalized}`);\n }\n return normalized;\n }\n const allowed = new Set([\n orchestrator.config.defaultNamespace,\n orchestrator.config.sharedNamespace,\n ...orchestrator.config.namespacePolicies.map((policy) => policy.name),\n ].map((value) => value.trim()).filter(Boolean));\n if (!allowed.has(normalized)) {\n throw new Error(`unsupported namespace: ${normalized}`);\n }\n return normalized;\n}\n\nfunction parseExplicitCaptureTtl(ttl: string | undefined): string | undefined {\n const raw = asTrimmed(ttl);\n if (!raw) return undefined;\n\n const absoluteMs = Date.parse(raw);\n if (Number.isFinite(absoluteMs)) {\n return new Date(absoluteMs).toISOString();\n }\n\n const relative = raw.match(/^(\\d+)\\s*([mhdw])$/i);\n if (!relative) {\n throw new Error(\"ttl must be an ISO-8601 timestamp or relative duration like 30m, 12h, 7d, or 2w\");\n }\n\n const amount = Number.parseInt(relative[1] ?? \"\", 10);\n const unit = (relative[2] ?? \"\").toLowerCase();\n if (!Number.isFinite(amount) || amount <= 0) {\n throw new Error(\"ttl duration must be a positive integer\");\n }\n\n const multiplier =\n unit === \"m\" ? 60_000\n : unit === \"h\" ? 60 * 60_000\n : unit === \"d\" ? 24 * 60 * 60_000\n : 7 * 24 * 60 * 60_000;\n return new Date(Date.now() + amount * multiplier).toISOString();\n}\n\nfunction parseInlineConfidence(value: string): number {\n const trimmed = value.trim();\n if (!/^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i.test(trimmed)) {\n return Number.NaN;\n }\n const parsed = Number(trimmed);\n return Number.isFinite(parsed) ? parsed : Number.NaN;\n}\n\nfunction parseInlineNote(block: string): ExplicitCaptureInput | null {\n const lines = block.replace(/\\r/g, \"\").split(\"\\n\");\n const note: Partial<ExplicitCaptureInput> = {};\n let idx = 0;\n\n while (idx < lines.length) {\n const rawLine = lines[idx] ?? \"\";\n const line = rawLine.trim();\n idx += 1;\n if (line.length === 0) continue;\n const colonIdx = line.indexOf(\":\");\n if (colonIdx < 0) continue;\n const key = line.slice(0, colonIdx).trim();\n const value = line.slice(colonIdx + 1).trim();\n\n if (key === \"content\" && value === \"|\") {\n const contentLines: string[] = [];\n while (idx < lines.length) {\n const next = lines[idx] ?? \"\";\n if (next.startsWith(\" \") || next.startsWith(\"\\t\")) {\n contentLines.push(next.replace(/^( |\\t)/, \"\"));\n idx += 1;\n continue;\n }\n if (next.trim().length === 0) {\n contentLines.push(\"\");\n idx += 1;\n continue;\n }\n break;\n }\n note.content = contentLines.join(\"\\n\").trim();\n continue;\n }\n\n switch (key) {\n case \"content\":\n note.content = value;\n break;\n case \"category\":\n note.category = value;\n break;\n case \"confidence\":\n note.confidence = parseInlineConfidence(value);\n break;\n case \"namespace\":\n note.namespace = value;\n break;\n case \"tags\":\n note.tags = value\n .split(\",\")\n .map((entry) => entry.trim())\n .filter(Boolean);\n break;\n case \"entityRef\":\n note.entityRef = value;\n break;\n case \"ttl\":\n note.ttl = value;\n break;\n case \"sourceReason\":\n note.sourceReason = value;\n break;\n default:\n break;\n }\n }\n\n return asTrimmed(note.content) ? (note as ExplicitCaptureInput) : null;\n}\n\nexport function parseInlineExplicitCaptureNotes(text: string): ExplicitCaptureInput[] {\n const notes: ExplicitCaptureInput[] = [];\n for (const match of text.matchAll(INLINE_NOTE_RE)) {\n const parsed = parseInlineNote(match[1] ?? \"\");\n if (parsed) notes.push(parsed);\n }\n return notes;\n}\n\nexport function hasInlineExplicitCaptureMarkup(text: string): boolean {\n return INLINE_NOTE_MARKUP_RE.test(text);\n}\n\nexport function stripInlineExplicitCaptureNotes(text: string): string {\n return text.replace(INLINE_NOTE_RE, \"\").trim();\n}\n\nexport function validateExplicitCaptureInput(\n input: ExplicitCaptureInput,\n mode: ExplicitCaptureValidationMode = \"strict_explicit\",\n): ValidExplicitCapture {\n const content = asTrimmed(input.content);\n if (!content) throw new Error(\"content is required\");\n if (mode === \"strict_explicit\") {\n if (content.length < 10) throw new Error(\"content must be at least 10 characters\");\n if (content.length > 4000) throw new Error(\"content must be 4000 characters or fewer\");\n }\n if (/<memory_note>/i.test(content) || /<\\/memory_note>/i.test(content)) {\n throw new Error(\"nested memory_note blocks are not allowed\");\n }\n\n const category = (asTrimmed(input.category) ?? \"fact\") as MemoryCategory;\n if (!INLINE_ALLOWED_CATEGORIES.has(category)) {\n throw new Error(`unsupported category: ${input.category ?? category}`);\n }\n\n const sanitized = sanitizeMemoryContent(content);\n if (!sanitized.clean) {\n throw new Error(\"content failed memory sanitization\");\n }\n for (const pattern of SECRET_PATTERNS) {\n if (pattern.test(content)) {\n throw new Error(\"content appears to contain a secret or credential\");\n }\n }\n assertNoSecretLikeMetadata(\"sourceReason\", input.sourceReason);\n assertNoSecretLikeMetadata(\"entityRef\", input.entityRef);\n assertNoSecretLikeMetadata(\"ttl\", input.ttl);\n assertNoSecretLikeMetadataList(\"tags\", input.tags);\n\n if (input.confidence !== undefined && !Number.isFinite(input.confidence)) {\n throw new Error(\"confidence must be a finite number\");\n }\n const confidence = input.confidence === undefined ? 0.95 : Number(input.confidence);\n if (confidence < 0 || confidence > 1) {\n throw new Error(\"confidence must be between 0 and 1\");\n }\n const requestedNamespace = asTrimmed(input.namespace);\n if (requestedNamespace && !isSafeRouteNamespace(requestedNamespace)) {\n throw new Error(`unsafe namespace: ${requestedNamespace}`);\n }\n const expiresAt = parseExplicitCaptureTtl(input.ttl);\n\n return {\n content,\n category,\n confidence,\n namespace: asTrimmed(input.namespace),\n tags: Array.from(new Set((input.tags ?? []).map((tag) => tag.trim()).filter(Boolean))),\n entityRef: asTrimmed(input.entityRef),\n expiresAt,\n sourceReason: asTrimmed(input.sourceReason),\n };\n}\n\nasync function findDuplicateExplicitCapture(\n orchestrator: Orchestrator,\n resolvedNamespace: string | undefined,\n candidate: ValidExplicitCapture,\n): Promise<string | null> {\n const storage = await orchestrator.getStorage(resolvedNamespace);\n if (\n candidate.category === \"fact\"\n && typeof (storage as { hasFactContentHash?: (content: string) => Promise<boolean> }).hasFactContentHash === \"function\"\n ) {\n try {\n const hasHash = await (storage as { hasFactContentHash: (content: string) => Promise<boolean> }).hasFactContentHash(\n candidate.content,\n );\n if (!hasHash) {\n const authoritative =\n typeof (storage as { isFactContentHashAuthoritative?: () => Promise<boolean> | boolean }).isFactContentHashAuthoritative\n === \"function\"\n ? await (storage as { isFactContentHashAuthoritative: () => Promise<boolean> | boolean })\n .isFactContentHashAuthoritative()\n : false;\n if (authoritative) return null;\n }\n } catch (err) {\n // Fail open: hash index is only an optimization, so fall back to the full corpus scan.\n void err;\n }\n }\n const existing = await storage.readAllMemories();\n const normalizedCandidate = normalizeCaptureContent(candidate.content);\n const match = existing.find((memory) => {\n const status = memory.frontmatter.status ?? \"active\";\n if (status !== \"active\") return false;\n if (memory.frontmatter.category !== candidate.category) return false;\n return normalizeCaptureContent(memory.content) === normalizedCandidate;\n });\n return match?.frontmatter.id ?? null;\n}\n\nexport async function persistExplicitCapture(\n orchestrator: Orchestrator,\n candidate: ValidExplicitCapture,\n source: ExplicitCaptureSource,\n): Promise<{ id: string; duplicateOf?: string; tombstoneBlocked?: boolean }> {\n const resolvedNamespace = candidate.namespacePreResolved\n ? asTrimmed(candidate.namespace)\n : resolveExplicitCaptureNamespace(orchestrator, candidate.namespace);\n const duplicateOf = await findDuplicateExplicitCapture(orchestrator, resolvedNamespace, candidate);\n if (duplicateOf) {\n return { id: duplicateOf, duplicateOf };\n }\n\n const storage = await orchestrator.getStorage(resolvedNamespace);\n // #1645 (review thread yG-): surface the tombstone block so callers\n // (memory_store tool, access-service HTTP/MCP) can report the capture as\n // queued for review instead of a successfully stored active memory.\n const { id, tombstoneBlocked } = await storage.writeMemory(candidate.category, candidate.content, {\n confidence: candidate.confidence,\n tags: candidate.tags,\n entityRef: candidate.entityRef,\n expiresAt: candidate.expiresAt,\n source: source === \"inline\" ? \"explicit-inline\" : \"explicit\",\n });\n // #1522: catalog touch handled at the storage chokepoint — the StorageManager's\n // post-write hook records the namespace touch automatically.\n\n const created = new Date().toISOString();\n const event: MemoryLifecycleEvent = {\n eventId: `mle-${randomUUID()}`,\n memoryId: id,\n eventType: \"explicit_capture_accepted\",\n timestamp: created,\n actor: explicitCaptureActor(source),\n reasonCode: candidate.sourceReason,\n ruleVersion: \"explicit-capture.v1\",\n };\n await storage.appendMemoryLifecycleEvents([event]);\n\n return { id, tombstoneBlocked };\n}\n\nfunction buildExplicitCaptureReviewContent(input: ExplicitCaptureInput, reason: string): string {\n const requestedContent = asTrimmed(input.content);\n const safeContent = sanitizeReviewText(requestedContent, \"[empty explicit capture]\");\n const safeCategory = sanitizeReviewMetadata(input.category);\n const safeNamespace = sanitizeReviewMetadata(input.namespace);\n const safeEntityRef = sanitizeReviewMetadata(input.entityRef);\n const safeTtl = sanitizeReviewMetadata(input.ttl);\n const safeSourceReason = sanitizeReviewMetadata(input.sourceReason);\n const safeTags = sanitizeReviewTags(input.tags);\n const lines = [\n \"Explicit capture queued for review.\",\n \"\",\n `Reason: ${reason}`,\n \"\",\n \"Submitted content:\",\n safeContent,\n ];\n const metadata = [\n safeCategory ? `Requested category: ${safeCategory}` : undefined,\n safeNamespace ? `Requested namespace: ${safeNamespace}` : undefined,\n safeEntityRef ? `Requested entityRef: ${safeEntityRef}` : undefined,\n safeTtl ? `Requested ttl: ${safeTtl}` : undefined,\n safeSourceReason ? `Requested sourceReason: ${safeSourceReason}` : undefined,\n safeTags.length > 0 ? `Requested tags: ${safeTags.join(\", \")}` : undefined,\n ].filter((entry): entry is string => typeof entry === \"string\" && entry.length > 0);\n if (metadata.length > 0) {\n lines.push(\"\", ...metadata);\n }\n return lines.join(\"\\n\");\n}\n\nasync function findQueuedExplicitCaptureDuplicate(\n orchestrator: Orchestrator,\n namespace: string | undefined,\n content: string,\n): Promise<string | null> {\n const storage = await orchestrator.getStorage(namespace);\n const existing = await storage.readAllMemories();\n const normalized = normalizeCaptureContent(content);\n const match = existing.find((memory) => {\n const status = memory.frontmatter.status ?? \"active\";\n if (status !== \"pending_review\") return false;\n if (!(memory.frontmatter.tags ?? []).includes(\"queued-review\")) return false;\n return normalizeCaptureContent(memory.content) === normalized;\n });\n return match?.frontmatter.id ?? null;\n}\n\nexport async function queueExplicitCaptureForReview(\n orchestrator: Orchestrator,\n input: ExplicitCaptureInput,\n source: ExplicitCaptureSource,\n error: unknown,\n): Promise<{ id: string; duplicateOf?: string }> {\n const reason = sanitizeReviewText(normalizeExplicitCaptureError(error), \"explicit capture failed\");\n const requestedNamespace = asTrimmed(input.namespace);\n // A caller-pre-authorized namespace (e.g. a session-owned project overlay\n // from the access service) routes directly; otherwise apply the static\n // policy allow-list guard (#1434).\n const queueNamespace = (input as { namespacePreResolved?: boolean }).namespacePreResolved\n ? requestedNamespace\n : resolveExplicitCaptureReviewNamespace(orchestrator, requestedNamespace);\n const content = buildExplicitCaptureReviewContent(input, reason);\n const duplicateOf = await findQueuedExplicitCaptureDuplicate(orchestrator, queueNamespace, content);\n if (duplicateOf) {\n return { id: duplicateOf, duplicateOf };\n }\n\n const requestedCategory = asTrimmed(input.category);\n const reviewCategory = requestedCategory && INLINE_ALLOWED_CATEGORIES.has(requestedCategory as MemoryCategory)\n ? requestedCategory as MemoryCategory\n : \"fact\";\n const requestedTags = sanitizeReviewTags(input.tags);\n const storage = await orchestrator.getStorage(queueNamespace);\n const { id: id } = await storage.writeMemory(reviewCategory, content, {\n confidence: 0.2,\n tags: Array.from(new Set([...EXPLICIT_CAPTURE_REVIEW_TAGS, ...requestedTags])),\n entityRef: sanitizeReviewMetadata(input.entityRef),\n source: source === \"inline\" ? \"explicit-inline-review\" : \"explicit-review\",\n });\n try {\n const created = await storage.getMemoryById(id);\n if (created) {\n await storage.writeMemoryFrontmatter(created, {\n status: \"pending_review\",\n updated: new Date().toISOString(),\n }, {\n actor: explicitCaptureActor(source),\n reasonCode: reason,\n ruleVersion: \"explicit-capture.v1\",\n });\n }\n } finally {\n // Record the catalog write touch (issue #1499, round 5/6 codex P2; NIhUg).\n // A queued review capture writes memory to the namespace's root (the DEFAULT\n // root when undefined), so its `lastWriteAt` must reflect the write once\n // `writeMemory` returns an id. If the later pending-review frontmatter update\n // fails, the memory file is still durable and must not disappear from\n // writtenSince/maintenance scheduling. Guarded optional hook (rule #33).\n // #1522: catalog touch handled at the storage chokepoint.\n }\n const event: MemoryLifecycleEvent = {\n eventId: `mle-${randomUUID()}`,\n memoryId: id,\n eventType: \"explicit_capture_queued\",\n timestamp: new Date().toISOString(),\n actor: explicitCaptureActor(source),\n reasonCode: reason,\n ruleVersion: \"explicit-capture.v1\",\n };\n await storage.appendMemoryLifecycleEvents([event]);\n return { id };\n}\n\nexport function shouldSkipImplicitExtraction(cfg: Pick<PluginConfig, \"captureMode\">): boolean {\n return cfg.captureMode === \"explicit\";\n}\n\nexport function shouldProcessInlineExplicitCapture(cfg: Pick<PluginConfig, \"captureMode\">): boolean {\n return cfg.captureMode !== \"implicit\";\n}\n"],"mappings":";;;;;;;;AAAA,SAAS,kBAAkB;AA+C3B,IAAM,iBAAiB;AACvB,IAAM,wBAAwB;AAC9B,IAAM,4BAA4B,oBAAI,IAAoB;AAAA,EACxD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,IAAM,kBAA4B;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,IAAM,4BAA6E;AAAA,EACjF,EAAE,SAAS,4BAA4B,aAAa,wBAAwB;AAAA,EAC5E,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,CAAC;AAAA,IAC5B,UAAU;AAAA,IACV,WAAW;AAAA,IACX,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,IAClC,OAAO,qBAAqB,MAAM;AAAA,IAClC,YAAY;AAAA,IACZ,aAAa;AAAA,EACf;AACA,QAAM,QAAQ,4BAA4B,CAAC,KAAK,CAAC;AACjD,SAAO,EAAE,GAAG;AACd;AAEO,SAAS,6BAA6B,KAAiD;AAC5F,SAAO,IAAI,gBAAgB;AAC7B;AAEO,SAAS,mCAAmC,KAAiD;AAClG,SAAO,IAAI,gBAAgB;AAC7B;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/namespaces/principal.ts"],"sourcesContent":["import type { PluginConfig } from \"../types.js\";\nimport { isLikelyUnsafeRegex } from \"../routing/engine.js\";\n\nconst MAX_REGEX_SESSION_KEY_LENGTH = 512;\n\nfunction compileSafePrincipalRegex(pattern: string): RegExp | null {\n if (isLikelyUnsafeRegex(pattern)) return null;\n try {\n return new RegExp(pattern);\n } catch {\n return null;\n }\n}\n\nexport function resolvePrincipal(sessionKey: string | undefined, config: PluginConfig): string | undefined {\n if (!config.namespacesEnabled) return \"default\";\n const sk = typeof sessionKey === \"string\" && sessionKey.trim().length > 0\n ? sessionKey\n : \"\";\n const mode = config.principalFromSessionKeyMode;\n const rules = config.principalFromSessionKeyRules ?? [];\n\n if (!sk) return undefined;\n\n if (mode === \"prefix\") {\n for (const r of rules) {\n if (sk.startsWith(r.match)) return r.principal;\n }\n } else if (mode === \"map\") {\n for (const r of rules) {\n if (sk === r.match) return r.principal;\n }\n } else if (mode === \"regex\") {\n if (sk.length <= MAX_REGEX_SESSION_KEY_LENGTH) {\n for (const r of rules) {\n const re = compileSafePrincipalRegex(r.match);\n if (re?.test(sk)) {\n return r.principal;\n }\n }\n }\n }\n\n // Fallback heuristic: \"agent:<agentId>:<channelType>:...\"\n const parts = sk.split(\":\");\n if (parts.length >= 2 && parts[0] === \"agent\") {\n const agentId = parts[1];\n if (agentId && agentId.length > 0) return agentId;\n }\n return \"default\";\n}\n\nexport function canReadNamespace(principal: string | undefined, namespace: string, config: PluginConfig): boolean {\n if (!config.namespacesEnabled) return true;\n if (!principal) return false;\n const policy = config.namespacePolicies.find((p) => p.name === namespace);\n if (!policy) return namespace === config.defaultNamespace || namespace === config.sharedNamespace;\n return policy.readPrincipals.includes(principal) || policy.readPrincipals.includes(\"*\");\n}\n\nexport function canWriteNamespace(principal: string | undefined, namespace: string, config: PluginConfig): boolean {\n if (!config.namespacesEnabled) return true;\n if (!principal) return false;\n const policy = config.namespacePolicies.find((p) => p.name === namespace);\n if (!policy) return namespace === config.defaultNamespace;\n return policy.writePrincipals.includes(principal) || policy.writePrincipals.includes(\"*\");\n}\n\n/**\n * Default \"self\" namespace for a principal.\n *\n * Heuristic:\n * - If there's a namespace policy with the same name as the principal, use it.\n * - Otherwise use config.defaultNamespace.\n */\nexport function defaultNamespaceForPrincipal(principal: string | undefined, config: PluginConfig): string {\n if (!config.namespacesEnabled) return config.defaultNamespace;\n if (!principal) return config.defaultNamespace;\n const exists = config.namespacePolicies.some((p) => p.name === principal);\n return exists ? principal : config.defaultNamespace;\n}\n\nexport function recallNamespacesForPrincipal(principal: string | undefined, config: PluginConfig): string[] {\n const out: string[] = [];\n if (!config.namespacesEnabled) return [config.defaultNamespace];\n if (!principal) return out;\n\n const selfNs = defaultNamespaceForPrincipal(principal, config);\n if (config.defaultRecallNamespaces.includes(\"self\") && canReadNamespace(principal, selfNs, config)) {\n out.push(selfNs);\n }\n if (config.defaultRecallNamespaces.includes(\"shared\") && canReadNamespace(principal, config.sharedNamespace, config)) {\n out.push(config.sharedNamespace);\n }\n\n for (const p of config.namespacePolicies) {\n if (p.includeInRecallByDefault && canReadNamespace(principal, p.name, config)) {\n if (!out.includes(p.name)) out.push(p.name);\n }\n }\n\n return out;\n}\n"],"mappings":";;;;;AAGA,IAAM,+BAA+B;AAErC,SAAS,0BAA0B,SAAgC;AACjE,MA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A,EACF;AAEA,SAAO;AACT;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/namespaces/storage.ts"],"sourcesContent":["import path from \"node:path\";\nimport { access, lstat, readdir } from \"node:fs/promises\";\nimport { isSafeRouteNamespace } from \"../routing/engine.js\";\nimport { StorageManager } from \"../storage.js\";\nimport type { PluginConfig } from \"../types.js\";\nimport { ALL_CATEGORY_DIRS } from \"../utils/category-dir.js\";\nimport { namespaceIdentityToken, normalizeNamespaceIdentity } from \"./identity.js\";\nimport type { NamespaceCatalog } from \"./catalog.js\";\nimport { MutationSerializer } from \"../utils/serialize-mutations.js\";\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await access(p);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function hasStoredEntries(p: string): Promise<boolean> {\n try {\n const entry = await lstat(p);\n if (entry.isSymbolicLink()) return true;\n if (!entry.isDirectory()) return true;\n const children = await readdir(p, { withFileTypes: true });\n for (const child of children) {\n const childPath = path.join(p, child.name);\n if (child.isSymbolicLink() || child.isFile()) return true;\n if (child.isDirectory() && (await hasStoredEntries(childPath))) return true;\n }\n return false;\n } catch {\n return false;\n }\n}\n\n// Build a per-namespace directory under `<memoryDir>/namespaces` and assert the\n// resolved path stays inside that base. Namespace identifiers can originate from\n// operator config (config.defaultNamespace) and request-derived routing, so this\n// containment check prevents directory traversal (CodeQL js/path-injection).\n// For safe segments this returns exactly `path.join(base, segment)`, so there is\n// no behavioral change for valid namespaces.\nfunction resolveNamespaceDir(memoryDir: string, segment: string): string {\n // Mirror isSafeRouteNamespace's separator/parent-ref rejection (without its\n // 64-char cap, so identity tokens still pass). Rejecting separators and \"..\"\n // up front keeps the value a single contained child of <memoryDir>/namespaces.\n if (\n segment.length === 0 ||\n segment.includes(\"/\") ||\n segment.includes(\"\\\\\") ||\n segment.includes(\"..\") ||\n path.isAbsolute(segment)\n ) {\n throw new Error(`unsafe namespace path segment: ${segment}`);\n }\n return path.join(memoryDir, \"namespaces\", segment);\n}\n\nconst LEGACY_NAMESPACE_CONTENT_CHILDREN = [\n ...ALL_CATEGORY_DIRS,\n \"entities\",\n \"artifacts\",\n \"identity\",\n \"config\",\n \"summaries\",\n \"profile.md\",\n] as const;\n\nconst LEGACY_NAMESPACE_RUNTIME_CHILDREN = [\"state\"] as const;\n\nasync function hasAnyLegacyData(\n rootDir: string,\n options: { includeRuntimeState?: boolean } = {},\n): Promise<boolean> {\n const children = options.includeRuntimeState === true\n ? [...LEGACY_NAMESPACE_CONTENT_CHILDREN, ...LEGACY_NAMESPACE_RUNTIME_CHILDREN]\n : LEGACY_NAMESPACE_CONTENT_CHILDREN;\n for (const child of children) {\n if (await hasStoredEntries(path.join(rootDir, child))) return true;\n }\n return false;\n}\n\nasync function hasAnyNamespaceStorageMarker(\n rootDir: string,\n options: { includeRuntimeState?: boolean } = {},\n): Promise<boolean> {\n const children = options.includeRuntimeState === true\n ? [...LEGACY_NAMESPACE_CONTENT_CHILDREN, ...LEGACY_NAMESPACE_RUNTIME_CHILDREN]\n : LEGACY_NAMESPACE_CONTENT_CHILDREN;\n for (const child of children) {\n if (await exists(path.join(rootDir, child))) return true;\n }\n return false;\n}\n\n/**\n * Storage routing for namespaces.\n *\n * Compatibility note:\n * - When namespaces are enabled, existing raw namespace roots are preserved.\n * New namespace roots use tokenized names under `memoryDir/namespaces/<token>`.\n * - The default namespace continues to use the legacy `memoryDir` root unless the caller\n * has created `memoryDir/namespaces/<defaultNamespace>` (in which case we use that).\n *\n * This avoids surprising \"lost memories\" when an install flips namespaces on without\n * migrating existing data.\n */\n/**\n * Optional hooks for the storage router. `onResolve` fires whenever a namespace's\n * storage is resolved/created, so a downstream consumer (e.g. the namespace\n * catalog, issue #1499) can register the namespace. The hook MUST NOT throw into\n * the router; the router invokes it defensively and a hook failure never affects\n * storage resolution.\n *\n * The hook MAY return (or resolve to) a boolean indicating whether the\n * registration actually PERSISTED (round 6, codex P2 — NEFoX). When it resolves\n * to `false` (a dropped/no-op registration), the router does NOT mark the\n * (namespace, storageDir) pair as notified, so the next resolve RETRIES it\n * instead of suppressing it forever. A `void`/`undefined` result is treated as\n * success (legacy hooks).\n */\nexport interface NamespaceStorageRouterHooks {\n onResolve?: (\n namespace: string,\n storageDir: string,\n ) => void | boolean | Promise<void | boolean>;\n}\n\n/**\n * Resolve the runtime storage root for the configured DEFAULT namespace.\n *\n * Shared between the live router (`NamespaceStorageRouter.defaultNamespaceRoot`)\n * and the rebuildable catalog (`NamespaceCatalog.rebuildFromDisk`) so the two\n * can never diverge (CLAUDE.md rule #22/#42 — read & write paths resolve through\n * the same logic). The contract is: while legacy memory data still lives\n * directly under `memoryDir`, the default root stays `memoryDir`; only once the\n * legacy root is empty and a `namespaces/<default|token>` dir holds data does\n * the default migrate into that tokenized/legacy-named dir.\n */\nexport async function resolveDefaultNamespaceRoot(config: PluginConfig): Promise<string> {\n if (!config.namespacesEnabled) {\n return config.memoryDir;\n }\n\n // Build the legacy default root from the NORMALIZED (trimmed) name so a\n // whitespace-padded `defaultNamespace` still finds the live `namespaces/default`\n // root (NIabe). `storageFor()` classifies the trimmed value as the default, and\n // the on-disk legacy dir is created under the trimmed name; using the raw spaced\n // name here would look for `namespaces/<spaced>` and miss the real root, falling\n // back to memoryDir/tokenized. `namespaceIdentityToken` already normalizes\n // internally, so the tokenized path is unaffected.\n const defaultIdentity = normalizeNamespaceIdentity(config.defaultNamespace);\n const legacyNsDir = resolveNamespaceDir(config.memoryDir, defaultIdentity);\n const tokenizedNsDir = resolveNamespaceDir(\n config.memoryDir,\n namespaceIdentityToken(config.defaultNamespace),\n );\n const tokenizedHasData =\n (await exists(tokenizedNsDir)) &&\n (await hasAnyNamespaceStorageMarker(tokenizedNsDir, { includeRuntimeState: true }));\n const nsDir = tokenizedHasData\n ? tokenizedNsDir\n : (await exists(legacyNsDir))\n ? legacyNsDir\n : tokenizedNsDir;\n return (await exists(nsDir)) && !(await hasAnyLegacyData(config.memoryDir))\n ? nsDir\n : config.memoryDir;\n}\n\n/**\n * Resolve the runtime storage root for ANY namespace exactly as the live router\n * would (`NamespaceStorageRouter.namespaceRoot`). Shared so the rebuildable\n * catalog records the SAME on-disk root the router routes to — a recall/read\n * touch must not guess `namespaces/<token>` when the router actually serves a\n * legacy raw-name dir or a migrated default root (CLAUDE.md rule #22/#42; round\n * 4, cursor Medium). The default namespace delegates to `resolveDefaultNamespaceRoot`;\n * every other namespace prefers the tokenized root when it has a storage marker,\n * else a legacy raw-name dir when present, else the tokenized root.\n */\nexport async function resolveNamespaceStorageRoot(\n config: PluginConfig,\n namespace: string,\n): Promise<string> {\n if (!config.namespacesEnabled) return config.memoryDir;\n // Compare on NORMALIZED identity so a whitespace-padded configured default name\n // still routes to the default root rather than a tokenized non-default dir\n // (NH-FH). The catalog keys records by the same normalized identity.\n if (normalizeNamespaceIdentity(namespace) === normalizeNamespaceIdentity(config.defaultNamespace)) {\n return resolveDefaultNamespaceRoot(config);\n }\n const legacyRoot = resolveNamespaceDir(config.memoryDir, namespace);\n const tokenizedRoot = resolveNamespaceDir(config.memoryDir, namespaceIdentityToken(namespace));\n if (\n (await exists(tokenizedRoot)) &&\n (await hasAnyNamespaceStorageMarker(tokenizedRoot, { includeRuntimeState: true }))\n ) {\n return tokenizedRoot;\n }\n return (await exists(legacyRoot)) ? legacyRoot : tokenizedRoot;\n}\n\nexport class NamespaceStorageRouter {\n private readonly cache = new Map<string, StorageManager>();\n private defaultNsRootResolved: string | null = null;\n // Dedup the resolve hook (round 6, cursor Medium — NCNL2). Recall/extraction\n // call `storageFor` repeatedly; firing `onResolve` (→ catalog loadCompacted +\n // append) on every cache hit grows `namespaces.jsonl` without bound between\n // rebuilds. We fire the hook only when the (namespace, storageDir) pair is new\n // or its dir changed, so a steady-state cache hit is a no-op for the catalog.\n private readonly notifiedResolved = new Map<string, string>();\n // Instance-scoped serializer for the resolve hook (issue #1524 adoption).\n // Replaces the bespoke `inFlightResolved` marker-then-clear pattern: the\n // serializer's per-key chain strictly orders concurrent notifications for the\n // SAME namespace, and the task re-checks `notifiedResolved` once it runs, so a\n // burst of cache hits before the first hook settles collapses to a single\n // hook invocation (the once-per-namespace intent). Recovery is preserved —\n // one rejected hook never poisons subsequent notifications for that key.\n private readonly resolveSerializer = new MutationSerializer();\n // (namespace, storageDir) pairs whose resolve hook is currently pending. Set SYNCHRONOUSLY in\n // notifyResolved (before queueing) so a burst of concurrent storageFor()\n // cache hits collapses onto the one in-flight hook instead of each enqueuing\n // its own task. Cleared when the queued hook settles. Without this, a dropped\n // hook (returns false on a rebuild-lock timeout) leaves notifiedResolved\n // unset, so every queued sibling task would re-run the hook — N serial lock\n // waits (cursor Medium 06f58a7c, codex P2).\n private readonly inFlightResolveHooks = new Set<string>();\n // Tracks every in-flight resolve-hook promise so callers can deterministically\n // await the fire-and-forget registrations that `storageFor()` kicks off (see\n // `whenResolveHooksSettled`). Entries are removed as each hook settles, so the\n // set holds at most one promise per concurrently-resolving namespace.\n private readonly pendingResolveHooks = new Set<Promise<unknown>>();\n // Pending post-write catalog touch promises (#1522). Like pendingResolveHooks,\n // lets tests await fire-and-forget write touches deterministically.\n private readonly pendingWriteTouches = new Set<Promise<unknown>>();\n\n // Normalized (trimmed) default namespace identity (NH-FH). `storageFor`\n // normalizes its input, so default-namespace branches must compare against the\n // normalized config default too — otherwise a whitespace-padded configured\n // default name routes the default namespace to a tokenized non-default root.\n private readonly defaultNamespaceIdentity: string;\n\n constructor(\n private readonly config: PluginConfig,\n private readonly hooks: NamespaceStorageRouterHooks = {},\n /** Catalog reference for post-write/read touches (issue #1522 chokepoint). */\n private readonly catalog?: NamespaceCatalog,\n ) {\n this.defaultNamespaceIdentity = normalizeNamespaceIdentity(config.defaultNamespace);\n }\n\n private async defaultNamespaceRoot(): Promise<string> {\n this.defaultNsRootResolved = await resolveDefaultNamespaceRoot(this.config);\n return this.defaultNsRootResolved;\n }\n\n private async namespaceRoot(namespace: string): Promise<string> {\n // NOTE: only used after defaultNamespaceRoot() resolution.\n if (!this.config.namespacesEnabled) return this.config.memoryDir;\n if (normalizeNamespaceIdentity(namespace) === this.defaultNamespaceIdentity) {\n return this.defaultNsRootResolved ?? this.config.memoryDir;\n }\n return resolveNamespaceStorageRoot(this.config, namespace);\n }\n\n async storageFor(namespace: string): Promise<StorageManager> {\n const ns = normalizeNamespaceIdentity(namespace || this.config.defaultNamespace);\n if (ns !== this.defaultNamespaceIdentity && !isSafeRouteNamespace(ns)) {\n throw new Error(`unsafe namespace: ${ns}`);\n }\n // Even when the default namespace is exempt from the check above, every\n // on-disk path is built through resolveNamespaceDir(), which rejects\n // traversal segments — so an unsafe configured default still cannot escape\n // <memoryDir>/namespaces (CodeQL js/path-injection).\n\n let root: string;\n if (ns === this.defaultNamespaceIdentity) {\n root = await this.defaultNamespaceRoot();\n const cached = this.cache.get(ns);\n if (cached && cached.dir === root) {\n this.notifyResolved(ns, root);\n return cached;\n }\n } else {\n const cached = this.cache.get(ns);\n root = await this.namespaceRoot(ns);\n if (cached && cached.dir === root) {\n this.notifyResolved(ns, root);\n return cached;\n }\n }\n\n const sm = new StorageManager(root, this.config.entitySchemas);\n // Propagate the inline-attribution template so that router-created storages\n // (used by extraction and shared-promotion paths) strip citations consistently,\n // matching the behaviour of the primary this.storage instance in the orchestrator.\n sm.citationTemplate = this.config.inlineSourceAttributionFormat;\n // #1522: install the post-write catalog touch at the chokepoint — every\n // successful write on this StorageManager records the namespace touch.\n this.bindCatalogWriteHook(sm, ns);\n // #1579: apply the tombstone non-resurrection config so every namespace\n // storage enforces the invariant at its own writeMemory chokepoint.\n this.applyTombstonesConfig(sm, ns);\n this.cache.set(ns, sm);\n this.notifyResolved(ns, root);\n return sm;\n }\n\n /**\n * Fire the resolve hook defensively. A hook failure (e.g. a catalog write\n * error) MUST NOT crash storage resolution — see CLAUDE.md gotcha #13.\n *\n * Issue #1524 adoption: hook invocations for the SAME namespace are now\n * strictly ordered through the shared `MutationSerializer` rather than the\n * bespoke `inFlightResolved` marker-then-clear pattern. The serializer\n * guarantees one in-flight hook per namespace; a concurrent burst of\n * `storageFor()` cache hits collapses to a single hook invocation because\n * each queued task re-checks `notifiedResolved` before invoking the hook. A\n * dropped (`false`) or rejected hook leaves `notifiedResolved` unset so the\n * next `storageFor()` retries — the serializer recovers from the rejection,\n * so a failed hook never poisons later notifications.\n */\n private notifyResolved(namespace: string, storageDir: string): void {\n const hook = this.hooks.onResolve;\n if (!hook) return;\n // Permanent dedup: skip once we've SUCCESSFULLY notified this exact\n // (namespace, storageDir). A changed dir (rare: migration/realignment)\n // still re-fires once. The mark is set ONLY AFTER the hook succeeds, so a\n // dropped registration (e.g. rebuild-lock timeout) is RETRIED on the next\n // cache hit instead of being suppressed forever (round 6, cursor Medium —\n // ND3EJ).\n if (this.notifiedResolved.get(namespace) === storageDir) return;\n // In-flight dedup (cursor Medium 06f58a7c, codex P2): if a hook for THIS\n // namespace is already pending, collapse this call onto it instead of\n // enqueueing another task. The serializer strictly orders queued tasks, but\n // ordering alone is not enough — when the first hook returns `false`\n // (dropped touch, e.g. rebuild-lock timeout), `notifiedResolved` stays\n // unset, so each queued sibling task would pass its re-check and re-run the\n // hook. With the real catalog hook each retry can spend the full lock wait,\n // so N cache hits during a rebuild leave N serial background lock attempts.\n // Collapsing here means at most ONE hook runs per in-flight registration;\n // its result (set `notifiedResolved` on success, leave unset on drop)\n // decides whether a LATER `storageFor()` retries — collapsing loses\n // nothing because the drop is already retried on the next cache hit.\n // Keyed by the composite (namespace, storageDir) so a CHANGED dir\n // (migration/realignment) for the same namespace still gets its own hook —\n // it is NOT collapsed onto the old dir's pending registration (cursor\n // Medium, codex P2).\n const inFlightKey = namespace + \"\\u0000\" + storageDir;\n if (this.inFlightResolveHooks.has(inFlightKey)) return;\n this.inFlightResolveHooks.add(inFlightKey);\n // Queue through the serializer. Concurrent calls for the same namespace\n // strictly order here; the 2nd call's task runs only after the 1st's hook\n // settles, by which point `notifiedResolved` is either set (no-op) or still\n // unset (retry). The returned promise is tracked for\n // `whenResolveHooksSettled()`. Rejections from the task body are caught so\n // they never reach the caller (best-effort hook contract); the serializer's\n // recovered tail still lets subsequent notifications run.\n const task = async (): Promise<void> => {\n // Re-check after queueing: a prior task in this same chain may have just\n // marked the pair as notified.\n if (this.notifiedResolved.get(namespace) === storageDir) return;\n try {\n // Hook may be sync or async; Promise.resolve normalizes both. A result\n // of `false` means the registration was dropped/no-op (e.g. rebuild-lock\n // timeout) — leave notifiedResolved UNSET so the next storageFor retries\n // (round 6, codex P2 — NEFoX). `void`/`undefined` is success for legacy\n // hooks. A rejection leaves notifiedResolved unset for the same reason.\n const persisted = await Promise.resolve(hook(namespace, storageDir));\n if (persisted !== false) {\n this.notifiedResolved.set(namespace, storageDir);\n }\n } catch {\n // Best-effort: a hook failure MUST NOT crash storage resolution. Leave\n // notifiedResolved unset so a later storageFor retries the registration.\n }\n };\n const queued = this.resolveSerializer.serialize(namespace, task);\n this.pendingResolveHooks.add(queued);\n // Clear the in-flight marker when the hook settles so a subsequent\n // storageFor() can retry after a drop, or short-circuit via notifiedResolved\n // after a success.\n const cleanup = (): void => {\n this.inFlightResolveHooks.delete(inFlightKey);\n this.pendingResolveHooks.delete(queued);\n };\n void queued.then(cleanup, cleanup);\n }\n\n /**\n * Install the post-write catalog touch hook on an externally-constructed\n * StorageManager (issue #1522). Used by the orchestrator for the legacy\n * default-namespace storage (`this.storage`) that bypasses the router.\n */\n bindCatalogWriteHook(sm: StorageManager, namespace: string): void {\n sm.onCatalogWrite = () => this.touchCatalogWrite(namespace, sm.dir);\n }\n\n /**\n * Install the tombstone config on an externally-constructed StorageManager\n * (issue #1579). Mirrors `bindCatalogWriteHook` — used for the legacy\n * default-namespace storage that bypasses the router. Router-created\n * storages are wired inline in `storageFor()` via `applyTombstonesConfig`.\n */\n bindTombstonesConfig(\n sm: StorageManager,\n namespace: string,\n config: { enabled: boolean; semanticMatch: boolean; semanticThreshold: number },\n ): void {\n this.tombstonesGlobalConfig = { ...config };\n sm.setTombstonesConfig({ ...config, namespace });\n }\n\n private tombstonesGlobalConfig: {\n enabled: boolean;\n semanticMatch: boolean;\n semanticThreshold: number;\n } = { enabled: false, semanticMatch: false, semanticThreshold: 0.9 };\n\n /**\n * Apply the tombstone config to a router-created StorageManager. Called\n * inline in `storageFor()` so every namespace storage enforces the\n * non-resurrection invariant, namespace-scoped (rule 42).\n */\n private applyTombstonesConfig(sm: StorageManager, namespace: string): void {\n sm.setTombstonesConfig({ ...this.tombstonesGlobalConfig, namespace });\n }\n\n /**\n * Post-write catalog touch (issue #1522 chokepoint). Called by every\n * StorageManager's post-write hook AFTER a successful write. Best-effort\n * and failure-tolerant — a catalog error MUST NOT affect the primary write\n * (gotcha #13, rule #40). Fire-and-forget by design.\n */\n private touchCatalogWrite(namespace: string, storageDir: string): void {\n if (!this.catalog) return;\n const touch = this.catalog\n .markWrite(namespace, { discoveredBy: \"write\", storageDir })\n .catch(() => undefined);\n this.pendingWriteTouches.add(touch);\n void touch.then(\n () => { this.pendingWriteTouches.delete(touch); },\n () => { this.pendingWriteTouches.delete(touch); },\n );\n }\n\n /**\n * Record a namespace read in the catalog (issue #1522 chokepoint move).\n * Best-effort and failure-tolerant. Used by recall paths so the read touch\n * lives in the storage layer, not at the caller.\n */\n recordRead(namespace: string, storageDir?: string): void {\n if (!this.catalog) return;\n const ns = normalizeNamespaceIdentity(namespace || this.config.defaultNamespace);\n void this.catalog\n .markRead(ns, { discoveredBy: \"read\", storageDir })\n .catch(() => undefined);\n }\n /**\n * Record a namespace write touch in the catalog (issue #1522). Best-effort\n * and failure-tolerant. Used by consolidation/cleanup passes that may mutate\n * the store via delete-only paths (e.g. entity-file merges, TTL cleanup) so\n * the namespace's lastWriteAt stays fresh even when no explicit write went\n * through the storage chokepoint. This is NOT a substitute for the chokepoint\n * — it's a belt-and-suspenders for paths the chokepoint doesn't cover.\n */\n recordWrite(namespace: string, storageDir?: string): void {\n if (!this.catalog) return;\n const ns = normalizeNamespaceIdentity(namespace || this.config.defaultNamespace);\n const touch = this.catalog\n .markWrite(ns, { discoveredBy: \"write\", storageDir })\n .catch(() => undefined);\n this.pendingWriteTouches.add(touch);\n void touch.then(\n () => { this.pendingWriteTouches.delete(touch); },\n () => { this.pendingWriteTouches.delete(touch); },\n );\n }\n\n /**\n * Resolve once every in-flight post-write catalog touch has settled (#1522).\n * Mirrors `whenResolveHooksSettled()`: the StorageManager's post-write hook\n * fires the catalog touch fire-and-forget, so tests asserting lastWriteAt\n * moved should await this instead of racing a timer.\n */\n async whenWriteTouchesSettled(): Promise<void> {\n while (this.pendingWriteTouches.size > 0) {\n await Promise.allSettled([...this.pendingWriteTouches]);\n }\n }\n\n /**\n * Resolve once every in-flight `onResolve` registration has settled.\n *\n * `storageFor()` fires the resolve hook fire-and-forget, so its catalog side\n * effect (e.g. `registerResolved(...)`) is not observable the moment\n * `storageFor()` returns. Callers that must act on that side effect — notably\n * tests asserting the catalog was updated — should await this instead of\n * racing a timer. Resolves immediately when no hook is registered or nothing\n * is in flight. The loop re-checks because a settling hook could, in\n * principle, trigger a follow-on resolution.\n */\n async whenResolveHooksSettled(): Promise<void> {\n while (this.pendingResolveHooks.size > 0) {\n await Promise.allSettled([...this.pendingResolveHooks]);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,OAAO,UAAU;AACjB,SAAS,QAAQ,OAAO,eAAe;AASvC,eAAe,OAAO,GAA6B;AACjD,MAAI;AACF,UAAM,OAAO,CAAC;AACd,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,eAAe,iBAAiB,GAA6B;AAC3D,MAAI;AACF,UAAM,QAAQ,MAAM,MAAM,CAAC;AAC3B,QAAI,MAAM,eAAe,EAAG,QAAO;AACnC,QAAI,CAAC,MAAM,YAAY,EAAG,QAAO;AACjC,UAAM,WAAW,MAAM,QAAQ,GAAG,EAAE,eAAe,KAAK,CAAC;AACzD,eAAW,SAAS,UAAU;AAC5B,YAAM,YAAY,KAAK,KAAK,GAAG,MAAM,IAAI;AACzC,UAAI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