@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
|
@@ -3,8 +3,9 @@ import {
|
|
|
3
3
|
normalizeHostEmbeddingVector
|
|
4
4
|
} from "./chunk-3ONXXHQO.js";
|
|
5
5
|
import {
|
|
6
|
+
resolveLocalLlmCapabilities,
|
|
6
7
|
resolveMemoryLifecycleCapabilities
|
|
7
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-SHJGBAIW.js";
|
|
8
9
|
import {
|
|
9
10
|
readEnvVar
|
|
10
11
|
} from "./chunk-JUC24CTX.js";
|
|
@@ -278,7 +279,7 @@ var EmbeddingFallback = class {
|
|
|
278
279
|
};
|
|
279
280
|
}
|
|
280
281
|
createLocalProvider() {
|
|
281
|
-
if (!this.config.
|
|
282
|
+
if (!resolveLocalLlmCapabilities(this.config).localLlm || !this.config.localLlmUrl) return null;
|
|
282
283
|
const base = this.config.localLlmUrl.replace(/\/$/, "");
|
|
283
284
|
const endpoint = /\/v1$/i.test(base) ? `${base}/embeddings` : `${base}/v1/embeddings`;
|
|
284
285
|
const headers = {
|
|
@@ -513,4 +514,4 @@ export {
|
|
|
513
514
|
EmbeddingProviderUnavailableError,
|
|
514
515
|
EmbeddingFallback
|
|
515
516
|
};
|
|
516
|
-
//# sourceMappingURL=chunk-
|
|
517
|
+
//# sourceMappingURL=chunk-UH3NYOHN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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 {\n resolveMemoryLifecycleCapabilities,\n resolveLocalLlmCapabilities,\n} 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 (!resolveLocalLlmCapabilities(this.config).localLlm || !this.config.localLlmUrl) return null;\n const base = this.config.localLlmUrl.replace(/\\/$/, \"\");\n const endpoint = /\\/v1$/i.test(base) ? `${base}/embeddings` : `${base}/v1/embeddings`;\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...(this.config.localLlmHeaders ?? {}),\n };\n if (this.config.localLlmApiKey && this.config.localLlmAuthHeader !== false) {\n headers.Authorization = `Bearer ${this.config.localLlmApiKey}`;\n }\n return {\n type: \"local\",\n model:\n this.config.embeddingFallbackModel ||\n this.config.localLlmModel ||\n DEFAULT_OPENAI_MODEL,\n endpoint,\n headers,\n };\n }\n\n private async embedForSearch(\n query: string,\n provider: ProviderConfig,\n options: { throwOnTimeout?: boolean } = {},\n ): Promise<EmbeddingResult | null> {\n try {\n return await this.embedWithEffectiveProvider(query, provider, {\n mode: \"lookup\",\n });\n } catch (err) {\n if (isLookupBackendUnavailableError(err)) {\n if (options.throwOnTimeout) {\n throw err;\n }\n // Fail-open: recall-path callers get an empty result rather than an\n // unhandled rejection that would abort recall entirely.\n log.debug(\"embedding fallback search: backend unavailable on lookup, returning [] (throwOnTimeout=false)\");\n return null;\n }\n throw err;\n }\n }\n\n private async embed(\n input: string,\n provider: ProviderConfig,\n options: { mode?: EmbedMode } = {},\n ): Promise<number[] | null> {\n const result = await this.embedWithEffectiveProvider(input, provider, options);\n return result?.vector ?? null;\n }\n\n private async embedWithEffectiveProvider(\n input: string,\n provider: ProviderConfig,\n options: { mode?: EmbedMode } = {},\n ): Promise<EmbeddingResult | null> {\n // Bound the fetch so a hung embedding endpoint cannot stall callers.\n // The lookup path uses a short budget (see DEFAULT_EMBEDDING_LOOKUP_TIMEOUT_MS\n // docblock) so semantic dedup fails open fast. The index path uses a\n // much longer budget because slow local backends (CPU embedding models)\n // otherwise drop index updates and blind later dedup lookups. See\n // DEFAULT_EMBEDDING_INDEX_TIMEOUT_MS docblock and PR #399 P2 review.\n const mode: EmbedMode = options.mode ?? \"lookup\";\n const timeoutMs =\n mode === \"index\"\n ? resolveEmbeddingIndexTimeoutMs()\n : resolveEmbeddingLookupTimeoutMs();\n if (provider.type === \"host\") {\n const vector = await this.embedWithHostProvider(input, provider, mode, timeoutMs);\n if (vector) return { provider, vector };\n const fallbackProvider = await this.resolveProvider({ includeHost: false });\n if (!fallbackProvider) {\n if (mode === \"lookup\") {\n throw new EmbeddingProviderUnavailableError(\n `host embedding provider unavailable (${provider.hostProvider?.id ?? provider.model})`,\n );\n }\n return null;\n }\n return this.embedWithEffectiveProvider(input, fallbackProvider, options);\n }\n if (!provider.endpoint || !provider.headers) return null;\n try {\n const res = await fetch(provider.endpoint, {\n method: \"POST\",\n headers: provider.headers,\n body: JSON.stringify({\n model: provider.model,\n input: input.slice(0, 8000),\n encoding_format: \"float\",\n }),\n signal: AbortSignal.timeout(timeoutMs),\n });\n if (!res.ok) {\n log.debug(`embedding fallback request failed: ${provider.type} ${res.status}`);\n // Round 11 fix (Finding Ur_J): on the LOOKUP path, a non-2xx response\n // means the embedding backend is effectively unavailable. Throw the\n // tagged error so search() (when called with throwOnTimeout) propagates\n // to decideSemanticDedup's backend_unavailable branch, activating the\n // per-batch short-circuit. Without this, repeated 429/5xx responses\n // would silently return [] for every fact in the batch.\n //\n // On the INDEX path a non-2xx is non-fatal (the memory is already\n // persisted; index update can be skipped) — return null there.\n if (mode === \"lookup\") {\n throw new EmbeddingTimeoutError(\n `embedding backend returned ${res.status} (${provider.type})`,\n );\n }\n return null;\n }\n const payload = (await res.json()) as any;\n const vector = payload?.data?.[0]?.embedding;\n if (!Array.isArray(vector)) return null;\n const normalized = vector\n .map((n: unknown) => Number(n))\n .filter((n: number) => Number.isFinite(n));\n return normalized.length > 0 ? { provider, vector: normalized } : null;\n } catch (err) {\n // Round 11 (Finding Ur_J): the !res.ok branch above throws\n // EmbeddingTimeoutError directly. Re-throw it here so the catch does\n // not swallow our own intentional signal back into a null return.\n if (isLookupBackendUnavailableError(err)) {\n throw err;\n }\n // AbortSignal.timeout throws a DOMException with name \"TimeoutError\";\n // surface at warn level so operators can distinguish slow backends from\n // generic errors.\n const isTimeout =\n err instanceof Error &&\n (err.name === \"TimeoutError\" || err.name === \"AbortError\");\n if (isTimeout) {\n log.warn(\n `embedding fallback fetch timed out after ${timeoutMs}ms (${provider.type}, mode=${mode})`,\n );\n // Round 9 fix (Finding UZqB): on the LOOKUP path a timeout means the\n // embedding backend is effectively unavailable — re-throw so that\n // search() propagates the error to semanticDedupLookup, which lets it\n // reach decideSemanticDedup's catch block and return\n // reason=\"backend_unavailable\". Without this, search() would silently\n // return [] and the per-batch batchBackendUnavailable flag would never\n // flip, causing subsequent facts in the same batch to each pay a full\n // timeout roundtrip (N × timeout instead of 1 × timeout).\n //\n // On the INDEX path a timeout is not fatal (the memory is already\n // persisted; index update can be skipped) — return null there so\n // indexFile() stays non-blocking.\n if (mode === \"lookup\") {\n throw new EmbeddingTimeoutError(\n `embedding backend timed out after ${timeoutMs}ms (${provider.type})`,\n );\n }\n } else {\n // Round 12 fix (PR #399 thread PRRT_kwDORJXyws56U6Gi): non-timeout\n // transport failures (ECONNREFUSED, DNS errors, TLS failures) are just\n // as fatal as timeouts on the LOOKUP path — the embedding backend is\n // effectively unreachable. Throw EmbeddingTimeoutError so that\n // search() (when called with throwOnTimeout:true) propagates the error\n // to decideSemanticDedup's backend_unavailable branch, activating the\n // per-batch short-circuit. Without this, each fact in the batch would\n // pay a full ECONNREFUSED roundtrip and return null → [] → no_candidates,\n // preventing batchBackendUnavailable from ever being set.\n //\n // On the INDEX path a transport failure is non-fatal — the memory is\n // already persisted; index update can be safely skipped.\n if (mode === \"lookup\") {\n log.warn(\n `embedding fallback transport error on lookup path (${provider.type}): ${err}`,\n );\n throw new EmbeddingTimeoutError(\n `embedding backend transport failure (${provider.type}): ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n log.debug(`embedding fallback error: ${err}`);\n }\n return null;\n }\n }\n\n private async embedWithHostProvider(\n input: string,\n provider: ProviderConfig,\n mode: EmbedMode,\n timeoutMs: number,\n ): Promise<number[] | null> {\n const hostProvider = provider.hostProvider;\n if (!hostProvider) return null;\n try {\n const vector = await hostProvider.embed(input.slice(0, 8000), {\n signal: AbortSignal.timeout(timeoutMs),\n inputType: mode === \"lookup\" ? \"query\" : \"document\",\n });\n return normalizeHostEmbeddingVector(vector);\n } catch (err) {\n log.debug(`host embedding provider error: ${hostProvider.id}: ${err}`);\n return null;\n }\n }\n\n 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;AA8CvD,IAAM,uBAAuB;AA+BtB,IAAM,wBAAN,cAAoC,MAAM;A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AE,QAAQ,OAAO,GAAG;AACzC,MAAI,EAAE,WAAW,IAAI,EAAG,KAAI,EAAE,MAAM,CAAC;AACrC,MAAI,EAAE,WAAW,EAAG,QAAO;AAC3B,MAAI,CAAC,EAAE,SAAS,GAAG,EAAG,KAAI,GAAG,CAAC;AAC9B,SAAO;AACT;AAEA,SAAS,kBACP,MACA,OACS;AACT,SAAO,sBAAsB,IAAI,MAAM,sBAAsB,KAAK,KAAK,KAAK,UAAU,MAAM;AAC9F;AAEA,SAAS,sBAAsB,UAA2D;AACxF,SAAO,cAAc,WAAW,SAAS,WAAW,SAAS;AAC/D;AAEA,SAAS,wBACP,UACA,aACS;AACT,SAAO,SAAS,aAAa,UAAU,CAAC,kBAAkB,UAAU,WAAW;AACjF;AAEA,SAAS,0BAA0B,UAAkD;AACnF,SAAO;AAAA,IACL,MAAM,SAAS;AAAA,IACf,OAAO,SAAS;AAAA,EAClB;AACF;AAEA,SAAS,iBAAiB,GAAa,GAAqB;AAC1D,QAAM,IAAI,KAAK,IAAI,EAAE,QAAQ,EAAE,MAAM;AACrC,MAAI,MAAM,EAAG,QAAO;AACpB,MAAI,MAAM;AACV,MAAI,QAAQ;AACZ,MAAI,QAAQ;AACZ,WAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,UAAM,KAAK,EAAE,CAAC,KAAK;AACnB,UAAM,KAAK,EAAE,CAAC,KAAK;AACnB,WAAO,KAAK;AACZ,aAAS,KAAK;AACd,aAAS,KAAK;AAAA,EAChB;AACA,QAAM,QAAQ,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,KAAK;AAChD,MAAI,UAAU,EAAG,QAAO;AACxB,SAAO,MAAM;AACf;","names":[]}
|
|
@@ -11,7 +11,10 @@ import {
|
|
|
11
11
|
defaultNamespaceForPrincipal,
|
|
12
12
|
recallNamespacesForPrincipal,
|
|
13
13
|
resolvePrincipal
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-LV32K4OP.js";
|
|
15
|
+
import {
|
|
16
|
+
resolveNamespaceCapabilities
|
|
17
|
+
} from "./chunk-SHJGBAIW.js";
|
|
15
18
|
import {
|
|
16
19
|
isSafeRouteNamespace
|
|
17
20
|
} from "./chunk-U3PN77QT.js";
|
|
@@ -516,7 +519,7 @@ function resolveLayer(params) {
|
|
|
516
519
|
}
|
|
517
520
|
function resolveScopeProfilePlan(options) {
|
|
518
521
|
const active = activeScopeProfile(options.config);
|
|
519
|
-
if (!active || !options.config.
|
|
522
|
+
if (!active || !resolveNamespaceCapabilities(options.config).namespaces) return null;
|
|
520
523
|
const baseNamespace = scopeProfileSelfNamespace(options.principal, options.config);
|
|
521
524
|
const layerIds = Array.from(
|
|
522
525
|
/* @__PURE__ */ new Set([
|
|
@@ -705,7 +708,7 @@ function getConfiguredNamespaces(config) {
|
|
|
705
708
|
}
|
|
706
709
|
function resolveNamespaceFromStorageDir(storageDir, options) {
|
|
707
710
|
const { config } = options;
|
|
708
|
-
if (!config.
|
|
711
|
+
if (!resolveNamespaceCapabilities(config).namespaces) return config.defaultNamespace;
|
|
709
712
|
const resolvedStorageDir = path2.resolve(storageDir);
|
|
710
713
|
const resolvedMemoryDir = path2.resolve(config.memoryDir);
|
|
711
714
|
if (resolvedStorageDir === resolvedMemoryDir) return config.defaultNamespace;
|
|
@@ -736,7 +739,7 @@ function resolveWritableNamespaceValue(namespace, sessionKey, authenticatedPrinc
|
|
|
736
739
|
let resolved;
|
|
737
740
|
if (!requested) {
|
|
738
741
|
resolved = config.defaultNamespace;
|
|
739
|
-
} else if (!config.
|
|
742
|
+
} else if (!resolveNamespaceCapabilities(config).namespaces && requested !== config.defaultNamespace) {
|
|
740
743
|
return { ok: false, reason: "unsupported", namespace: requested };
|
|
741
744
|
} else {
|
|
742
745
|
resolved = requested;
|
|
@@ -769,4 +772,4 @@ export {
|
|
|
769
772
|
resolveNamespaceFromStorageDir,
|
|
770
773
|
resolveWritableNamespaceValue
|
|
771
774
|
};
|
|
772
|
-
//# sourceMappingURL=chunk-
|
|
775
|
+
//# sourceMappingURL=chunk-UK6U5C3N.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/coding/git-context.ts","../src/coding/coding-namespace.ts","../src/namespaces/scope-profiles.ts","../src/scopes/scope-plan.ts"],"sourcesContent":["/**\n * GitContextResolver — pure module for detecting the git project + branch\n * a session is operating in.\n *\n * Introduced by issue #569 (coding-agent project/branch-scoped namespaces).\n *\n * This module is deliberately pure:\n * - no orchestrator references\n * - no config side-effects\n * - no namespace wiring\n *\n * Downstream slices (PR 2+ of #569) wire `resolveGitContext` into the\n * `NamespaceResolver` / `Orchestrator` so that memories are scoped to a\n * detected project / branch without leaking across repos.\n *\n * CLAUDE.md rule 17 (expand `~`): the `rootPath` returned here is always an\n * absolute, tilde-expanded path. Callers must not re-expand.\n *\n * CLAUDE.md rule 51 (reject invalid input): `cwd` must be an absolute path\n * and must exist. `resolveGitContext` returns `null` — rather than throwing —\n * when the directory is not inside a git worktree, because being outside a\n * repo is a normal runtime state (e.g. agent opened in a scratch dir).\n */\nimport path from \"node:path\";\n\nimport { expandTildePath } from \"../utils/path.js\";\nimport { launchProcessSync } from \"../runtime/child-process.js\";\n\n// Re-export so existing callers / tests that imported `expandTildePath` from\n// this module keep working. CLAUDE.md #17 requires consistent `~` expansion\n// across every user-facing path input; the canonical implementation now\n// lives in `utils/path.ts`.\nexport { expandTildePath };\n\n// ──────────────────────────────────────────────────────────────────────────\n// Public types\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface GitContext {\n /**\n * Stable identifier for the project. Derived from `git remote get-url origin`\n * when an origin remote is configured, otherwise from the repo root path.\n *\n * Formatted as `origin:<hex>` or `root:<hex>` so that the source is visible\n * to operators (see `remnic doctor`, issue #569 acceptance criteria).\n */\n projectId: string;\n /**\n * Current branch, e.g. `main`, `feat/foo`. `null` only in detached-HEAD\n * state (e.g. rebase in progress). Callers should treat `null` as \"no\n * branch-scope overlay applies\" without erroring.\n */\n branch: string | null;\n /**\n * Absolute path to the repository root (the directory containing `.git`).\n * Tilde-expanded per CLAUDE.md #17.\n */\n rootPath: string;\n /**\n * Best-effort default branch (usually `main` or `master`). Derived from the\n * `refs/remotes/origin/HEAD` symbolic ref. `null` when not available (e.g.\n * fresh clone without a default branch symref, or no origin remote).\n */\n defaultBranch: string | null;\n}\n\n/**\n * Injectable git-invocation surface. Only the commands `resolveGitContext`\n * actually needs are exposed. Tests inject a mock implementation to avoid\n * spawning a real git process.\n */\nexport interface GitInvoker {\n /**\n * Run `git <args>` with `cwd` as the working directory. Must return\n * `{ stdout, exitCode }` with `stdout` trimmed by the caller as needed.\n * Implementations should NOT throw for non-zero exit codes — they should\n * return the exit code so the resolver can decide how to recover.\n */\n (cwd: string, args: string[]): { stdout: string; exitCode: number };\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Default git invoker — spawns real `git` via the shared child-process helper\n// ──────────────────────────────────────────────────────────────────────────\n\nconst DEFAULT_GIT_TIMEOUT_MS = 2_000;\n\nexport function defaultGitInvoker(): GitInvoker {\n return (cwd: string, args: string[]) => {\n const result = launchProcessSync(\"git\", args, {\n cwd,\n encoding: \"utf-8\",\n timeout: DEFAULT_GIT_TIMEOUT_MS,\n shell: false,\n });\n if (result.error) {\n // Spawn failure (git not on PATH, timeout, etc.). Surface as non-zero.\n return { stdout: \"\", exitCode: 127 };\n }\n return {\n stdout: typeof result.stdout === \"string\" ? result.stdout : \"\",\n exitCode: typeof result.status === \"number\" ? result.status : 1,\n };\n };\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Stable hashing\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Non-cryptographic stable hash. Used only to derive a deterministic\n * `projectId` from either the origin URL or the root path. The hash does not\n * need to be collision-resistant against adversarial input — it is purely a\n * namespace discriminator.\n *\n * Uses FNV-1a 32-bit so we don't pull in `node:crypto` for a simple bucket\n * key. Output is lowercase hex, zero-padded to 8 characters.\n */\nexport function stableHash(input: string): string {\n let hash = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash.toString(16).padStart(8, \"0\");\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Origin URL normalization\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Normalize a git remote URL so that equivalent SSH / HTTPS forms of the\n * same repo produce the same `projectId`. Handles:\n * - `git@github.com:foo/bar.git` → `github.com/foo/bar`\n * - `https://github.com/foo/bar` → `github.com/foo/bar`\n * - `https://github.com/foo/bar.git` → `github.com/foo/bar`\n * - `ssh://git@github.com/foo/bar` → `github.com/foo/bar`\n * - `ssh://git@github.com:2222/foo/bar` → `github.com/foo/bar` (port stripped)\n *\n * Case-insensitive (remote hostnames and most repo paths on major forges are\n * case-insensitive in practice).\n */\nexport function normalizeOriginUrl(rawUrl: string): string {\n let url = rawUrl.trim();\n if (!url) return \"\";\n\n // Strip trailing `.git` case-insensitively — the whole result is\n // lowercased at the end, so `.GIT` / `.Git` must be treated the same as\n // `.git`. Previously the `.endsWith(\".git\")` check let `.GIT` leak\n // through and appear in the output.\n if (/\\.git$/i.test(url)) url = url.slice(0, -4);\n\n // Windows drive-letter local path (e.g. `C:/repos/app`): detect here\n // so the scp matcher below can accept single-character SSH host aliases\n // (`h:foo/bar` from `.ssh/config`). A drive letter is exactly one ASCII\n // letter followed by `:/` or `:\\`; SSH aliases never have a slash\n // immediately after the colon.\n if (/^[A-Za-z]:[\\\\/]/.test(url)) {\n return url.toLowerCase();\n }\n\n // Protocol-prefixed: ssh://, https://, http://, git://, file://\n // Must be tried FIRST so that scp-style detection below doesn't\n // incorrectly swallow an ssh:// URL that happens to contain `:port/`.\n //\n // Matches:\n // 1: host — bracketed IPv6 `[2001:db8::1]`, plain host with no `:` / `/`,\n // OR empty (for `file:///path` which has no host component).\n // 2: port (optional) — preserved in the output so two repos on the same\n // host under different ports get distinct project namespaces.\n // Losing the port risked false-coalescing separate repos on custom\n // SSH mesh setups.\n // 3: path (optional)\n const protoMatch =\n /^[a-z][a-z0-9+.-]*:\\/\\/(?:[^@/]+@)?(\\[[^\\]]+\\]|[^/:]*)(?::(\\d+))?(\\/.*)?$/i.exec(url);\n if (protoMatch) {\n let host = protoMatch[1] ?? \"\";\n // Detect IPv6 via the bracketed input form BEFORE stripping brackets,\n // so that when we later re-attach a port we can preserve the\n // `[host]:port` boundary. Without the brackets, `host:2222` is\n // ambiguous with a longer bare IPv6 address like `2001:db8::1:2222`.\n const wasBracketed =\n host.startsWith(\"[\") && host.endsWith(\"]\");\n if (wasBracketed) host = host.slice(1, -1);\n const port = protoMatch[2];\n const repoPath = (protoMatch[3] ?? \"\").replace(/^\\/+/, \"\");\n const hostPort = port\n ? wasBracketed\n ? `[${host}]:${port}`\n : `${host}:${port}`\n : host;\n // For protocols without a host component (file:///path), fall back to\n // a stable prefix so distinct local paths don't collapse to \"/path\".\n const prefix = hostPort.length > 0 ? hostPort : \"localhost\";\n return `${prefix}/${repoPath}`.toLowerCase();\n }\n\n // scp-like syntax: [user@]host:path. Protocol-prefixed URLs (`scheme://`)\n // are handled above, so the scp branch below guards against them: a\n // matched `host` of `scheme` followed by a path starting with `//` is\n // a protocol URL that fell through and must NOT be parsed here.\n // `user@` is optional — git also accepts userless scp forms like\n // `host:org/repo`. Valid scp paths may start with digits (e.g.\n // `git@host:123/repo.git`), so no numeric guard is needed: port-bearing\n // URLs have the `://` prefix and match the protocol branch above before\n // reaching here.\n //\n // Windows drive letters were filtered above, so single-character SSH\n // host aliases (`h:foo/bar`) are accepted here.\n //\n // Bracketed IPv6 (`[2001:db8::1]`) is supported: the host alternative\n // matches the bracketed literal up to `]` without splitting on internal\n // `:`. Brackets are stripped in the normalised form so the scp and\n // `ssh://` forms of the same IPv6 remote produce identical projectIds.\n const scpMatch =\n /^(?:([^@\\s/]+)@)?(\\[[^\\]]+\\]|[^:@\\s/]+):(.+)$/.exec(url);\n if (scpMatch) {\n let host = scpMatch[2] ?? \"\";\n if (host.startsWith(\"[\") && host.endsWith(\"]\")) host = host.slice(1, -1);\n const repoPath = scpMatch[3] ?? \"\";\n // Reject protocol-like leftovers (e.g. `file:///path` where the scp\n // regex greedily matched `file` as host and `///path` as path).\n if (repoPath.startsWith(\"//\")) {\n return url.toLowerCase();\n }\n return `${host}/${repoPath.replace(/^\\/+/, \"\")}`.toLowerCase();\n }\n\n // Fallback: use raw lowercased\n return url.toLowerCase();\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Resolver\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface ResolveGitContextOptions {\n /** Inject a git invoker (tests). Defaults to spawning real `git`. */\n invoker?: GitInvoker;\n}\n\n/**\n * Detect the git project + branch for `cwd`.\n *\n * Returns `null` when:\n * - `cwd` is not an absolute path (invalid input, CLAUDE.md #51)\n * - `cwd` is not inside a git worktree\n * - `git` is not available on PATH\n *\n * Never throws.\n */\nexport async function resolveGitContext(\n cwd: string,\n options: ResolveGitContextOptions = {},\n): Promise<GitContext | null> {\n // Wrap the whole body so the documented \"Never throws\" contract is\n // enforced. Possible throw sites include:\n // - `expandTildePath` → `resolveHomeDir()` → `os.homedir()` when HOME\n // is unset (e.g. minimal containers)\n // - a custom `options.invoker` that raises instead of returning a\n // non-zero exitCode\n // - any future helper added to this chain\n // All of those map to \"not in a repo\" / `null`.\n try {\n // Validate input: must be a non-empty string.\n if (typeof cwd !== \"string\" || cwd.length === 0) return null;\n\n // Expand `~` per CLAUDE.md #17, then require absolute path.\n const expanded = expandTildePath(cwd);\n if (!path.isAbsolute(expanded)) return null;\n\n const invoker = options.invoker ?? defaultGitInvoker();\n\n // 1. Locate the repo root.\n const topLevel = invoker(expanded, [\"rev-parse\", \"--show-toplevel\"]);\n if (topLevel.exitCode !== 0) return null;\n const rootPath = topLevel.stdout.trim();\n if (!rootPath) return null;\n\n // 2. Current branch. `--abbrev-ref HEAD` returns `HEAD` in detached\n // state, which we normalize to `null`. On a fresh `git init` the\n // HEAD ref is unborn and `--abbrev-ref HEAD` fails, but\n // `symbolic-ref HEAD` still returns the target branch. Fall back\n // so newly-initialized repos get a sensible branch name.\n const branchResult = invoker(rootPath, [\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]);\n let branch: string | null = null;\n if (branchResult.exitCode === 0) {\n const raw = branchResult.stdout.trim();\n branch = raw && raw !== \"HEAD\" ? raw : null;\n } else {\n const unbornRef = invoker(rootPath, [\"symbolic-ref\", \"--quiet\", \"HEAD\"]);\n if (unbornRef.exitCode === 0) {\n const raw = unbornRef.stdout.trim();\n const prefix = \"refs/heads/\";\n if (raw.startsWith(prefix)) {\n const candidate = raw.slice(prefix.length);\n if (candidate) branch = candidate;\n }\n }\n }\n\n // 3. Origin URL — optional. Used to derive a stable `projectId`.\n const originResult = invoker(rootPath, [\"remote\", \"get-url\", \"origin\"]);\n let projectId: string;\n if (originResult.exitCode === 0) {\n const normalized = normalizeOriginUrl(originResult.stdout);\n projectId = normalized ? `origin:${stableHash(normalized)}` : `root:${stableHash(rootPath)}`;\n } else {\n projectId = `root:${stableHash(rootPath)}`;\n }\n\n // 4. Default branch — best effort.\n const headRef = invoker(rootPath, [\"symbolic-ref\", \"--quiet\", \"refs/remotes/origin/HEAD\"]);\n let defaultBranch: string | null = null;\n if (headRef.exitCode === 0) {\n const raw = headRef.stdout.trim();\n const prefix = \"refs/remotes/origin/\";\n if (raw.startsWith(prefix)) {\n const candidate = raw.slice(prefix.length);\n if (candidate) defaultBranch = candidate;\n }\n }\n\n return {\n projectId,\n branch,\n rootPath,\n defaultBranch,\n };\n } catch {\n // Never throws — any unexpected error falls back to \"not in a repo\".\n return null;\n }\n}\n","/**\n * Coding-agent namespace overlay (issue #569 PR 2 + PR 3).\n *\n * Given a `CodingContext` (from `resolveGitContext`) and a `CodingModeConfig`,\n * returns the namespace that recall + write paths should use — or `null` when\n * no overlay should apply (coding mode disabled, no context supplied, or\n * feature flags off).\n *\n * PR 2 ships the project overlay. PR 3 will add the branch overlay; the\n * function here already handles both flags so the schema / types / plumbing\n * don't have to change a second time when branch-scope lands.\n *\n * Pure function — no orchestrator, no config side-effects. Callers keep rule\n * 42 (read + write through same namespace layer) by consulting the same\n * function on both paths.\n */\n\nimport type { CodingContext, CodingModeConfig } from \"../types.js\";\nimport { stableHash } from \"./git-context.js\";\n\nexport interface CodingNamespaceOverlay {\n /**\n * Effective namespace to use for this session's memory operations. When\n * `branchScope` is on, takes the form `project:<id>/branch:<b>`; otherwise\n * `project:<id>`.\n */\n namespace: string;\n /**\n * Read fallbacks — additional namespaces a caller should include in recall\n * so that, for example, a branch-scoped session still sees project-level\n * memories that were written before the branch scope was enabled.\n *\n * Writes MUST go to `namespace` only; these are read-side only.\n *\n * Introduced to carry PR 3's branch→project fallback; PR 2 returns an empty\n * array here.\n */\n readFallbacks: string[];\n /**\n * `\"project\"` when only project scope applies, `\"branch\"` when branch scope\n * is also layered on. Used for diagnostics (`remnic doctor`) and logging.\n */\n scope: \"project\" | \"branch\";\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Sanitization\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Normalize a projectId / branch fragment so the resulting namespace passes\n * the router's `isSafeRouteNamespace` check (`[A-Za-z0-9._-]{1,64}`).\n *\n * Namespaces are used as filesystem directory names and must not contain\n * path separators (`/`, `\\`) or colons — so both `:` and `/` collapse to `-`.\n * The project-id format `origin:<8hex>` and branch names like `feat/x` both\n * flow through this helper before hitting the storage layer.\n *\n * NOT a security boundary — projectIds come from `resolveGitContext` (known\n * hex), and branch names come from local git. This defends against corrupt\n * input only.\n */\n/**\n * Single-pass sanitization — each input character is visited exactly once.\n * Rewriting as an explicit loop (instead of chained `replace()` calls with\n * greedy quantifiers) closes the polynomial-backtracking surface that\n * CodeQL flagged on patterns like `-+` and `^-+|-+$`.\n */\nexport function sanitizeFragment(input: string): string {\n if (typeof input !== \"string\") return \"\";\n const trimmed = input.trim().toLowerCase();\n let out = \"\";\n let prevIsDash = true; // suppress leading dashes\n for (let i = 0; i < trimmed.length; i += 1) {\n const c = trimmed[i]!;\n const cc = trimmed.charCodeAt(i);\n const isSafe =\n (cc >= 48 && cc <= 57) /* 0-9 */ ||\n (cc >= 97 && cc <= 122) /* a-z */ ||\n cc === 46 /* . */ ||\n cc === 95 /* _ */;\n if (isSafe) {\n out += c;\n prevIsDash = false;\n } else if (!prevIsDash) {\n out += \"-\";\n prevIsDash = true;\n }\n }\n // Strip a single trailing dash introduced by the final run of unsafe chars.\n if (out.endsWith(\"-\")) out = out.slice(0, -1);\n return out;\n}\n\n/**\n * Cap to the router's per-namespace upper bound.\n *\n * Raw truncation alone would collapse distinct long inputs that differ near\n * the end (e.g. two `feat/...` branches with different suffixes) into the\n * same namespace — silently mixing recall/write state across branches or\n * projects. When truncation is needed, we append a short deterministic\n * hash suffix (`-<8hex>`) derived from the FULL pre-truncated value so\n * collisions only happen under true hash collisions, not simple prefix\n * overlap.\n *\n * The tail is trimmed to leave room for the separator and 8-char hash and\n * any trailing `-` introduced by the slice is stripped so the final\n * character before `-<hash>` is always alphanumeric or `.`/`_`.\n */\nconst MAX_NAMESPACE_LEN = 64;\nconst HASH_SUFFIX_LEN = 9; // \"-\" + 8 hex chars\n\nfunction capLength(value: string): string {\n if (value.length <= MAX_NAMESPACE_LEN) return value;\n // Reuse the FNV-1a 32-bit hash from git-context — one canonical\n // implementation, one set of edge-case fixes. Uses Math.imul for\n // correct 32-bit wrap-around, which plain `*` would not guarantee\n // for the largest intermediate products.\n const hash = stableHash(value);\n // Trim trailing '-' with a linear, non-backtracking loop. A regex\n // like `-+$` is linear too, but an explicit loop keeps CodeQL happy\n // about polynomial backtracking warnings when several `\\-+` patterns\n // appear in the same module.\n let end = MAX_NAMESPACE_LEN - HASH_SUFFIX_LEN;\n while (end > 0 && value.charCodeAt(end - 1) === 45 /* '-' */) end -= 1;\n return `${value.slice(0, end)}-${hash}`;\n}\n\n/**\n * Produce the project-scope namespace name. Exported for tests and for\n * `remnic doctor` to render. Guaranteed to satisfy `isSafeRouteNamespace`:\n * no `/`, no `:`, lowercase only, length-capped to 64 chars.\n */\nexport function projectNamespaceName(projectId: string): string {\n const frag = sanitizeFragment(projectId);\n return capLength(`project-${frag || \"unknown\"}`);\n}\n\nexport function projectTagProjectId(projectTag: string): string {\n const trimmed = projectTag.trim();\n const frag = sanitizeFragment(trimmed);\n const disambig = trimmed.length > 0 && frag !== trimmed;\n const suffix = disambig ? `-${stableHash(trimmed)}` : \"\";\n return `tag:${frag || \"unknown\"}${suffix}`;\n}\n\n/**\n * Preserve case when sanitizing a principal-derived base namespace. The\n * router's `isSafeRouteNamespace` check accepts `[A-Za-z0-9._-]{1,64}`, so\n * upper-case characters in the principal name are safe and MUST be kept to\n * avoid colliding two otherwise-distinct principals (e.g. `Alice` vs\n * `alice`) into the same combined namespace.\n *\n * Otherwise identical to `sanitizeFragment`: single-pass, linear, no\n * polynomial-backtracking quantifiers, unsafe chars collapse to `-` with\n * leading/trailing dashes suppressed.\n */\nfunction sanitizeBaseFragment(input: string): string {\n if (typeof input !== \"string\") return \"\";\n const trimmed = input.trim();\n let out = \"\";\n let prevIsDash = true;\n for (let i = 0; i < trimmed.length; i += 1) {\n const c = trimmed[i]!;\n const cc = trimmed.charCodeAt(i);\n const isSafe =\n (cc >= 48 && cc <= 57) /* 0-9 */ ||\n (cc >= 65 && cc <= 90) /* A-Z */ ||\n (cc >= 97 && cc <= 122) /* a-z */ ||\n cc === 46 /* . */ ||\n cc === 95 /* _ */;\n if (isSafe) {\n out += c;\n prevIsDash = false;\n } else if (!prevIsDash) {\n out += \"-\";\n prevIsDash = true;\n }\n }\n if (out.endsWith(\"-\")) out = out.slice(0, -1);\n return out;\n}\n\n/**\n * Combine a principal-derived base namespace (e.g. `default`, `alice`) with a\n * coding-agent overlay namespace (e.g. `project-origin-abcd1234`). The result\n * is a single safe-route token that preserves principal isolation (CLAUDE.md\n * rule 42: read + write must resolve through the same namespace layer — and\n * here, through the same principal-scoped prefix) while layering project or\n * project/branch scope on top.\n *\n * Multiple principals working in the same repo thus get distinct namespaces:\n *\n * alice + project-origin-ab12 → alice-project-origin-ab12\n * bob + project-origin-ab12 → bob-project-origin-ab12\n * Alice + project-origin-ab12 → Alice-project-origin-ab12 (distinct)\n *\n * The base fragment preserves case so `Alice` and `alice` remain distinct;\n * the overlay fragment is still lowercase-sanitized because it derives from\n * deterministic, pre-lowercased git hashes.\n *\n * Output is re-capped through `capLength` so a very long base + overlay\n * combination still fits inside `isSafeRouteNamespace` (≤ 64 chars). The\n * deterministic hash suffix on truncation keeps distinct inputs distinct.\n */\nexport function combineNamespaces(base: string, overlay: string): string {\n const baseFrag = sanitizeBaseFragment(base);\n const overlayFrag = sanitizeFragment(overlay);\n if (!baseFrag) return capLength(overlayFrag || \"unknown\");\n if (!overlayFrag) return capLength(baseFrag);\n return capLength(`${baseFrag}-${overlayFrag}`);\n}\n\n/**\n * Produce the branch-scope namespace name. Format:\n * `project-<id>-branch-<name>[-<hash>]`. Uses `-` as the structural separator\n * rather than `/` or `:` so the result is a single safe route-namespace\n * token that can be used directly as a filesystem directory.\n *\n * Two failure modes must not collapse distinct branches to one namespace:\n *\n * 1. Sanitization is lossy (`feat/x` and `feat-x` both sanitize to\n * `feat-x`; `Feature` and `feature` both sanitize to `feature`). When\n * sanitization rewrote any character, we append a short hash of the\n * RAW branch so distinct inputs stay distinct.\n * 2. Truncation is applied when the total exceeds 64 chars. In that\n * mode `capLength` appends its own hash of the full pre-truncated\n * value.\n *\n * Long branches that also sanitize may receive both kinds of hashes — that\n * is acceptable: the router only requires the result be unique and\n * deterministic, and the two hashes derive from different domains so they\n * don't conflict.\n */\nexport function branchNamespaceName(projectId: string, branch: string): string {\n const projectFrag = sanitizeFragment(projectId);\n const trimmedBranch = branch.trim();\n const branchFrag = sanitizeFragment(trimmedBranch);\n // Lossy-sanitization disambiguator: append hash of the raw (trimmed)\n // branch when sanitization actually changed the string. Preserves\n // distinctness across `feat/x` vs `feat-x` and `Feature` vs `feature`.\n // The comparison uses the raw trimmed value (NOT `.toLowerCase()`) so\n // case-only variants are treated as lossy and receive their own hash.\n // Empty / already-safe-lowercase inputs get no hash so the common case\n // stays readable.\n const disambig = trimmedBranch.length > 0 && branchFrag !== trimmedBranch;\n const base = `project-${projectFrag || \"unknown\"}-branch-${branchFrag || \"unknown\"}`;\n const suffixed = disambig ? `${base}-${stableHash(trimmedBranch)}` : base;\n return capLength(suffixed);\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Overlay resolver\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Compute the namespace overlay for a session.\n *\n * Returns `null` when no overlay applies — callers should then use their\n * existing `defaultNamespaceForPrincipal(...)` result unchanged. This keeps\n * CLAUDE.md #30 (escape hatch): setting `codingMode.projectScope: false`\n * exactly restores pre-#569 behaviour at every call site.\n *\n * @param codingContext — git context from the connector\n * @param config — coding mode flags (projectScope, branchScope, globalFallback)\n * @param defaultNamespace — retained for call-site compatibility; no longer\n * used. The global fallback is expressed as an empty-string sentinel in\n * `readFallbacks`, which `combineNamespaces(principal, \"\")` resolves to the\n * principal's own namespace at the call site.\n */\nexport function resolveCodingNamespaceOverlay(\n codingContext: CodingContext | null | undefined,\n config: Pick<CodingModeConfig, \"projectScope\" | \"branchScope\" | \"globalFallback\">,\n defaultNamespace?: string,\n): CodingNamespaceOverlay | null {\n // No context supplied (session isn't in a git repo, or connector didn't\n // attach one) → no overlay.\n if (!codingContext) return null;\n\n // Project scope disabled → no overlay at all. Branch scope depends on\n // project scope being on; there is no branch-only mode.\n if (!config.projectScope) return null;\n\n // Require a non-empty projectId — defensive.\n const projectId = typeof codingContext.projectId === \"string\" ? codingContext.projectId.trim() : \"\";\n if (!projectId) return null;\n\n const projectNs = projectNamespaceName(projectId);\n\n // Root/global namespace fallback: when `globalFallback` is true, include\n // the principal's self namespace in readFallbacks so cross-project knowledge\n // remains visible. CLAUDE.md #30: the gate is `globalFallback` — set to\n // false for strict project isolation.\n //\n // The fallback value is \"\" (empty string), NOT the defaultNamespace name.\n // The orchestrator passes each fallback through combineNamespaces(principal, fallback),\n // and combineNamespaces(base, \"\") returns base unchanged — yielding the\n // principal's own namespace. Using the actual namespace name (e.g., \"default\")\n // would produce \"default-default\" after combination, missing the target.\n const includeRoot = config.globalFallback === true;\n\n // Branch-scope layering (PR 3):\n // - only when config.branchScope is explicitly true\n // - only when we actually have a branch (null in detached HEAD)\n // - project namespace becomes a read fallback so project-level memories\n // remain visible from any branch (deliberate asymmetry — branch writes\n // don't leak up, but project reads leak down).\n // - when globalFallback is on, the root namespace is also appended so\n // globally useful memories surface in every branch.\n if (config.branchScope && typeof codingContext.branch === \"string\" && codingContext.branch.length > 0) {\n const branchNs = branchNamespaceName(projectId, codingContext.branch);\n const fallbacks = [projectNs];\n if (includeRoot) fallbacks.push(\"\");\n return {\n namespace: branchNs,\n readFallbacks: fallbacks,\n scope: \"branch\",\n };\n }\n\n return {\n namespace: projectNs,\n readFallbacks: includeRoot ? [\"\"] : [],\n scope: \"project\",\n };\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Diagnostics (issue #569 PR 3 + PR 8)\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface CodingScopeDescription {\n /** \"none\" when no overlay is active; otherwise the resolved scope level. */\n scope: \"none\" | \"project\" | \"branch\";\n /** Project id (raw, not sanitized) when a context is attached. */\n projectId: string | null;\n /** Branch name (raw, not sanitized) when available. */\n branch: string | null;\n /** Effective namespace writes route to. `null` when no overlay applies. */\n effectiveNamespace: string | null;\n /** Read fallbacks included in recall (non-empty only when branch-scope is on). */\n readFallbacks: string[];\n /**\n * Why no overlay applies, when `scope === \"none\"`. One of:\n * - `\"no-context\"` — connector didn't attach a CodingContext\n * - `\"disabled\"` — codingMode.projectScope is false\n * - `\"empty-project\"` — codingContext.projectId was empty/whitespace\n */\n disabledReason: \"no-context\" | \"disabled\" | \"empty-project\" | null;\n}\n\n/**\n * Human-readable description of the coding-agent scope that currently applies\n * for a session. Consumed by `remnic doctor` (PR 8) and by logs to surface\n * why recall routes where it does.\n *\n * Pure — callers pass the coding context + config they already have.\n */\nexport function describeCodingScope(\n codingContext: CodingContext | null | undefined,\n config: Pick<CodingModeConfig, \"projectScope\" | \"branchScope\" | \"globalFallback\">,\n defaultNamespace?: string,\n): CodingScopeDescription {\n const projectId = codingContext?.projectId ?? null;\n const branch = codingContext?.branch ?? null;\n\n if (!codingContext) {\n return {\n scope: \"none\",\n projectId: null,\n branch: null,\n effectiveNamespace: null,\n readFallbacks: [],\n disabledReason: \"no-context\",\n };\n }\n if (!config.projectScope) {\n return {\n scope: \"none\",\n projectId,\n branch,\n effectiveNamespace: null,\n readFallbacks: [],\n disabledReason: \"disabled\",\n };\n }\n const trimmedId = typeof projectId === \"string\" ? projectId.trim() : \"\";\n if (!trimmedId) {\n return {\n scope: \"none\",\n projectId,\n branch,\n effectiveNamespace: null,\n readFallbacks: [],\n disabledReason: \"empty-project\",\n };\n }\n\n const overlay = resolveCodingNamespaceOverlay(codingContext, config, defaultNamespace);\n // Unreachable in practice given the guards above, but keep the return\n // shape consistent if the resolver grows new null branches later.\n if (!overlay) {\n return {\n scope: \"none\",\n projectId,\n branch,\n effectiveNamespace: null,\n readFallbacks: [],\n disabledReason: \"disabled\",\n };\n }\n return {\n scope: overlay.scope,\n projectId,\n branch,\n effectiveNamespace: overlay.namespace,\n readFallbacks: overlay.readFallbacks,\n disabledReason: null,\n };\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// LCM session-key namespacing (#1495)\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Reserved structural sentinel for the namespaced LCM `session_id` encoding\n * (#1495 P1). U+001F (UNIT SEPARATOR) is a C0 control character that CANNOT\n * occur in a route namespace (`isSafeRouteNamespace` ⇒ `[A-Za-z0-9._-]{1,64}`,\n * see routing/engine.ts) and does not occur in any legitimate session key, so\n * it is an unforgeable structural marker for the namespace boundary.\n *\n * SECURITY — why this is unforgeable (the #1495 P1 fix):\n * The LCM archive is keyed by the `session_id` STRING (exact `session_id = ?`\n * and prefix `session_id LIKE '<prefix>%'`), NOT physically partitioned by\n * namespace. The previous encoding `${namespace}:${sessionKey}` shared the SAME\n * string space as a raw default-store key, so a caller authorized for the\n * `default` store could pass a raw `sessionKey` equal to another namespace's\n * encoded key (`\"<overlay-ns>:<victim-session>\"`) and exact-match the victim's\n * rows — a cross-tenant read leak.\n *\n * The new encoding makes the namespaced and default key-spaces PROVABLY\n * DISJOINT:\n * - Overlay key = `\\x1f<namespace>\\x1f<sessionKey>` — always begins with\n * `\\x1f` followed by a NON-`\\x1f` character (the namespace is non-empty and\n * `\\x1f`-free). The leading `\\x1f<namespace>\\x1f` is an unambiguous,\n * injective frame: the namespace cannot contain `\\x1f`, so the second `\\x1f`\n * terminates it without any escaping of the (raw) session key.\n * - Default key = the raw `sessionKey`, UNLESS it already begins with the\n * sentinel, in which case it is escaped to begin with `\\x1f\\x1f` (see\n * `escapeDefaultLcmKey`). A default key therefore NEVER matches the overlay\n * frame `\\x1f<non-\\x1f>…`.\n * Hence no caller-controlled raw `sessionKey` (default path) can reproduce an\n * overlay key, closing the forgery for BOTH the exact-`session_id` match and the\n * `sessionPrefix` LIKE match (an overlay prefix `\\x1f<ns>\\x1f<rawPrefix>` stays a\n * valid LIKE-prefix of the overlay full keys, and a default prefix can only\n * LIKE-match default keys).\n *\n * Existing default-store rows need NO migration: legitimate session keys never\n * contain `\\x1f`, so `escapeDefaultLcmKey` is a no-op for them and they remain\n * byte-for-byte their raw form. The namespaced encoding is NEW in this\n * unreleased PR, so changing its shape costs nothing.\n */\nconst LCM_NS_SENTINEL = \"\\u001f\";\n\n/**\n * Make a default-store (raw) LCM key disjoint from the namespaced key-space.\n *\n * Namespaced overlay keys always begin with `\\x1f` followed by a non-`\\x1f`\n * namespace character. A raw default key collides with that frame ONLY if it\n * begins with `\\x1f`. Legitimate session keys never contain `\\x1f`, so this is a\n * pure no-op for them; a forged key that begins with `\\x1f` is escaped to begin\n * with `\\x1f\\x1f`, which can never equal an overlay key (whose second character\n * is a `[A-Za-z0-9._-]` namespace char, never `\\x1f`).\n */\nfunction escapeDefaultLcmKey(sessionKey: string): string {\n return sessionKey.startsWith(LCM_NS_SENTINEL)\n ? `${LCM_NS_SENTINEL}${sessionKey}`\n : sessionKey;\n}\n\n/**\n * Build the LCM/structured-history `session_id` that a write-producing surface\n * archives under, and that a same-session reader must search under, so reads\n * and writes never drift (#1495, CLAUDE.md rule 42).\n *\n * The LCM archive filters strictly by the `session_id` string, so the writer's\n * archival key and the reader's lookup key MUST agree byte-for-byte. The\n * encoding frames the namespace with the reserved {@link LCM_NS_SENTINEL}\n * (`\\x1f<namespace>\\x1f<sessionKey>`) whenever that namespace diverges from the\n * single-store default; otherwise it passes the (escaped) raw `sessionKey` so\n * single-user / no-overlay deployments keep pre-#1495 behavior exactly. The two\n * key-spaces are provably disjoint, so a caller-controlled raw `sessionKey`\n * cannot forge another namespace's encoded id (see the {@link LCM_NS_SENTINEL}\n * doc comment for the full security rationale).\n *\n * `observe`, compaction flush/record, and the orchestrator recall readers all\n * route through this one helper so a project-scoped (cwd/projectTag) or\n * explicit-namespace session reads its own compressed-history / structured /\n * targeted-fact evidence instead of missing it.\n */\nexport function lcmSessionKeyForNamespace(\n namespace: string | undefined,\n sessionKey: string | undefined,\n defaultNamespace: string,\n): string | undefined {\n if (typeof sessionKey !== \"string\" || sessionKey.length === 0) return sessionKey;\n if (\n typeof namespace === \"string\" &&\n namespace.length > 0 &&\n namespace !== defaultNamespace\n ) {\n // Namespaced (overlay / explicit) key: frame the namespace with the reserved\n // sentinel so the boundary is unambiguous AND unforgeable from the default\n // key-space. The namespace is guaranteed `\\x1f`-free by `isSafeRouteNamespace`.\n return `${LCM_NS_SENTINEL}${namespace}${LCM_NS_SENTINEL}${sessionKey}`;\n }\n // Default store: raw sessionKey, escaped only if it would otherwise intrude on\n // the namespaced key-space (no-op for every legitimate key).\n return escapeDefaultLcmKey(sessionKey);\n}\n\n/**\n * Map an ORDERED, read-authorized namespace set (the SAME set normal QMD/file\n * recall searches) to the ordered set of LCM `session_id`s a same-session reader\n * must query (#1505 thread \"Include coding fallback namespaces in LCM reads\").\n *\n * The LCM archive filters strictly by `session_id`, and `observe` archives each\n * turn under `${effectiveNamespace}:${sessionKey}` for the namespace that was\n * effective when it was written. A branch-scoped session that overlays\n * `${base-project-*-branch-*}` only sees rows written under THAT namespace if it\n * reads a single overlay key — but normal recall ALSO searches the\n * `codingOverlay.readFallbacks` (project / root) namespaces, so rows archived at\n * project/root scope are surfaced by QMD/file recall yet MISSED by a single-key\n * LCM read. Deriving the LCM read keys from the SAME `recallNamespaces` set keeps\n * the LCM read path from diverging: every namespace recall is authorized to read\n * (read-auth gate already applied upstream in `recallNamespaces`) contributes one\n * LCM key, ordered primary-overlay-first then fallbacks. Unreadable namespaces\n * are never in `recallNamespaces`, so they are never searched here either (no\n * cross-tenant read leak).\n *\n * Single-user / no-overlay recall passes a single-namespace set that collapses to\n * the raw `sessionKey`, so the result is `[sessionKey]` — byte-for-byte the\n * pre-#1505 single-key behavior.\n *\n * SESSIONLESS recall (`sessionKey === undefined`): returns `[undefined]` so the\n * caller issues ONE archive-wide LCM read with no exact `session_id` filter —\n * byte-for-byte the pre-#1505 sessionless behavior. It must NOT substitute the\n * literal `\"default\"` session id (codex P2 \"Preserve unscoped LCM searches\n * without a session key\"): that would filter to a session literally named\n * `default`, silently dropping the explicit-cue / targeted / focused / response /\n * event LCM sections for every recall that omits a session key.\n *\n * The result is deduped while preserving first-seen order so the caller can query\n * keys in priority order and short-circuit on the first hit without re-querying an\n * identical key (e.g. when two namespaces both collapse to the default store).\n */\nexport function lcmReadSessionIdsForNamespaces(\n namespaces: readonly string[],\n sessionKey: string | undefined,\n defaultNamespace: string,\n): Array<string | undefined> {\n // Sessionless ⇒ a single archive-wide read (no `session_id` filter). NEVER the\n // literal \"default\" session id (codex P2).\n if (typeof sessionKey !== \"string\" || sessionKey.length === 0) {\n return [undefined];\n }\n const out: string[] = [];\n const seen = new Set<string>();\n for (const namespace of namespaces) {\n const key =\n lcmSessionKeyForNamespace(namespace, sessionKey, defaultNamespace) ??\n sessionKey;\n if (!seen.has(key)) {\n seen.add(key);\n out.push(key);\n }\n }\n return out;\n}\n","import { resolveNamespaceCapabilities } from \"../capabilities.js\";\nimport { createHash } from \"node:crypto\";\n\nimport { combineNamespaces, type CodingNamespaceOverlay } from \"../coding/coding-namespace.js\";\nimport { stableHash } from \"../coding/git-context.js\";\nimport { isSafeRouteNamespace } from \"../routing/engine.js\";\nimport type {\n CodingContext,\n PluginConfig,\n ScopeProfileConfig,\n ScopeProfileLayerId,\n ScopeProfilePromotionTarget,\n ScopeTeamConfig,\n} from \"../types.js\";\nimport { canReadNamespace, canWriteNamespace, defaultNamespaceForPrincipal } from \"./principal.js\";\n\ntype ScopeProfileCodingOverlay = Pick<CodingNamespaceOverlay, \"namespace\" | \"readFallbacks\">;\n\nexport interface ScopeProfileLayerResolution {\n id: ScopeProfileLayerId;\n kind: \"user-project\" | \"team-project\" | \"user-global\" | \"server-shared\";\n namespace?: string;\n readable: boolean;\n writable: boolean;\n promotable: boolean;\n reason: string;\n}\n\nexport interface ScopeProfilePromotionResolution {\n target: ScopeProfilePromotionTarget;\n namespace?: string;\n authorized: boolean;\n reason: string;\n}\n\nexport interface ResolvedScopeProfilePlan {\n profileId: string;\n profile: ScopeProfileConfig;\n baseNamespace: string;\n writeLayer: ScopeProfileLayerId;\n writeNamespace: string;\n readNamespaces: string[];\n layers: ScopeProfileLayerResolution[];\n promotionTargets: ScopeProfilePromotionResolution[];\n warnings: string[];\n}\n\nexport interface ResolveScopeProfilePlanOptions {\n config: PluginConfig;\n principal?: string;\n codingContext?: CodingContext | null;\n codingOverlay?: ScopeProfileCodingOverlay | null;\n}\n\nfunction activeScopeProfile(config: PluginConfig): { profileId: string; profile: ScopeProfileConfig } | null {\n const profileId = config.defaultScopeProfile;\n if (!profileId) return null;\n const profile = (config.scopeProfiles ?? {})[profileId];\n return profile ? { profileId, profile } : null;\n}\n\nfunction principalListed(list: string[], principal: string | undefined): boolean {\n if (!principal) return false;\n return list.includes(principal) || list.includes(\"*\");\n}\n\nfunction derivedScopeProfileSelfNamespace(principal: string | undefined, config: PluginConfig): string | null {\n if (!principal || principal === config.defaultNamespace || principal === config.sharedNamespace) return null;\n if (isSafeRouteNamespace(principal)) return principal;\n return \"principal-\" + createHash(\"sha256\").update(principal).digest(\"hex\").slice(0, 54);\n}\n\nfunction scopeProfileSelfNamespace(principal: string | undefined, config: PluginConfig): string {\n const existing = defaultNamespaceForPrincipal(principal, config);\n if (existing !== config.defaultNamespace) return existing;\n return derivedScopeProfileSelfNamespace(principal, config) ?? existing;\n}\n\nfunction hasExplicitNamespacePolicy(namespace: string, config: PluginConfig): boolean {\n return (config.namespacePolicies ?? []).some((policy) => policy.name === namespace);\n}\n\nfunction isScopeProfileImplicitSelfNamespace(\n principal: string | undefined,\n namespace: string,\n config: PluginConfig,\n): boolean {\n const derived = derivedScopeProfileSelfNamespace(principal, config);\n return Boolean(\n derived &&\n namespace === derived &&\n namespace !== config.defaultNamespace &&\n namespace !== config.sharedNamespace &&\n isSafeRouteNamespace(namespace) &&\n !hasExplicitNamespacePolicy(namespace, config),\n );\n}\n\nfunction canReadScopeProfileNamespace(\n principal: string | undefined,\n namespace: string,\n config: PluginConfig,\n): boolean {\n return isScopeProfileImplicitSelfNamespace(principal, namespace, config) || canReadNamespace(principal, namespace, config);\n}\n\nfunction canWriteScopeProfileNamespace(\n principal: string | undefined,\n namespace: string,\n config: PluginConfig,\n): boolean {\n return isScopeProfileImplicitSelfNamespace(principal, namespace, config) || canWriteNamespace(principal, namespace, config);\n}\n\nfunction resolveTeam(\n config: PluginConfig,\n profile: ScopeProfileConfig,\n principal: string | undefined,\n): { teamId: string; team: ScopeTeamConfig } | null {\n const configuredTeamId = profile.teamProject?.teamId;\n if (configuredTeamId) {\n const configured = (config.teams ?? {})[configuredTeamId];\n return configured ? { teamId: configuredTeamId, team: configured } : null;\n }\n const readableTeams = Object.entries(config.teams ?? {}).filter(([, team]) =>\n principalListed(team.principals, principal) || principalListed(team.read, principal),\n );\n const needsWritableTeam = profile.writeDefault === \"teamProject\" || profile.readOrder.includes(\"teamProject\");\n if (needsWritableTeam) {\n const writableTeam = readableTeams.find(([, team]) => principalListed(team.write, principal));\n if (writableTeam) return { teamId: writableTeam[0], team: writableTeam[1] };\n }\n const needsPromotableTeam =\n profile.promotionTargets.includes(\"teamProject\") || profile.autoPromote.targets.includes(\"teamProject\");\n if (needsPromotableTeam) {\n const promotableTeam = readableTeams.find(\n ([, team]) => principalListed(team.promote, principal) || principalListed(team.write, principal),\n );\n if (promotableTeam) return { teamId: promotableTeam[0], team: promotableTeam[1] };\n }\n const firstReadableTeam = readableTeams[0];\n return firstReadableTeam\n ? { teamId: firstReadableTeam[0], team: firstReadableTeam[1] }\n : null;\n}\n\nfunction renderTeamProjectNamespace(params: {\n template: string;\n teamId: string;\n principal: string | undefined;\n codingContext: CodingContext;\n codingOverlay: ScopeProfileCodingOverlay;\n}): { namespace: string; unknownPlaceholders: string[] } {\n const replacements: Record<string, string> = {\n teamId: params.teamId,\n principal: params.principal ?? \"anonymous\",\n projectId: params.codingContext.projectId,\n projectHash: stableHash(params.codingContext.projectId),\n projectNamespace: params.codingOverlay.namespace,\n };\n const unknownPlaceholders: string[] = [];\n const namespace = params.template.replace(/\\{([A-Za-z][A-Za-z0-9]*)\\}/g, (match, key: string) => {\n const replacement = replacements[key];\n if (replacement !== undefined) return replacement;\n if (!unknownPlaceholders.includes(key)) unknownPlaceholders.push(key);\n return match;\n });\n return { namespace, unknownPlaceholders };\n}\n\nfunction resolveLayer(params: {\n id: ScopeProfileLayerId;\n config: PluginConfig;\n profile: ScopeProfileConfig;\n principal: string | undefined;\n baseNamespace: string;\n codingContext: CodingContext | null | undefined;\n codingOverlay: ScopeProfileCodingOverlay | null | undefined;\n}): ScopeProfileLayerResolution {\n const { id, config, profile, principal, baseNamespace, codingContext, codingOverlay } = params;\n if (id === \"userGlobal\") {\n return {\n id,\n kind: \"user-global\",\n namespace: baseNamespace,\n readable: canReadScopeProfileNamespace(principal, baseNamespace, config),\n writable: canWriteScopeProfileNamespace(principal, baseNamespace, config),\n promotable: canWriteScopeProfileNamespace(principal, baseNamespace, config),\n reason: \"principal self/global namespace\",\n };\n }\n if (id === \"serverShared\") {\n return {\n id,\n kind: \"server-shared\",\n namespace: config.sharedNamespace,\n readable: canReadNamespace(principal, config.sharedNamespace, config),\n writable: canWriteNamespace(principal, config.sharedNamespace, config),\n promotable: canWriteNamespace(principal, config.sharedNamespace, config),\n reason: \"configured shared namespace\",\n };\n }\n if (id === \"userProject\") {\n if (!codingContext || !codingOverlay) {\n return {\n id,\n kind: \"user-project\",\n readable: false,\n writable: false,\n promotable: false,\n reason: \"missing project context\",\n };\n }\n const namespace = combineNamespaces(baseNamespace, codingOverlay.namespace);\n const explicitProjectPolicy = hasExplicitNamespacePolicy(namespace, config);\n const baseReadable = canReadScopeProfileNamespace(principal, baseNamespace, config);\n const baseWritable = canWriteScopeProfileNamespace(principal, baseNamespace, config);\n const projectReadable = explicitProjectPolicy\n ? canReadNamespace(principal, namespace, config)\n : baseReadable;\n const projectWritable = explicitProjectPolicy\n ? canWriteNamespace(principal, namespace, config)\n : baseWritable;\n return {\n id,\n kind: \"user-project\",\n namespace,\n readable: projectReadable,\n writable: projectWritable,\n promotable: projectWritable,\n reason: explicitProjectPolicy\n ? \"explicit user-project namespace policy\"\n : baseReadable || baseWritable\n ? \"principal project namespace derived from coding context\"\n : \"principal base namespace is not authorized\",\n };\n }\n const team = resolveTeam(config, profile, principal);\n if (!team) {\n return {\n id,\n kind: \"team-project\",\n readable: false,\n writable: false,\n promotable: false,\n reason: \"no authorized team mapping\",\n };\n }\n if (!codingContext || !codingOverlay) {\n return {\n id,\n kind: \"team-project\",\n readable: false,\n writable: false,\n promotable: false,\n reason: \"missing project context\",\n };\n }\n const template =\n profile.teamProject?.namespaceTemplate ??\n team.team.projectNamespaceTemplate ??\n \"team-{teamId}-project-{projectHash}\";\n const renderedNamespace = renderTeamProjectNamespace({\n template,\n teamId: team.teamId,\n principal,\n codingContext,\n codingOverlay,\n });\n const namespace = renderedNamespace.namespace.trim();\n if (renderedNamespace.unknownPlaceholders.length > 0) {\n return {\n id,\n kind: \"team-project\",\n namespace,\n readable: false,\n writable: false,\n promotable: false,\n reason: `unknown team-project namespace template placeholder(s): ${renderedNamespace.unknownPlaceholders.join(\", \")}`,\n };\n }\n if (!namespace || !isSafeRouteNamespace(namespace)) {\n return {\n id,\n kind: \"team-project\",\n namespace,\n readable: false,\n writable: false,\n promotable: false,\n reason: \"team-project namespace template resolved to an unsafe namespace\",\n };\n }\n const teamReadable = principalListed(team.team.read, principal) || principalListed(team.team.principals, principal);\n const teamWritable = principalListed(team.team.write, principal);\n const teamPromotable = principalListed(team.team.promote, principal) || principalListed(team.team.write, principal);\n const userProjectSuffix = `-${codingOverlay.namespace}`;\n const userProjectBase = namespace.endsWith(userProjectSuffix)\n ? namespace.slice(0, -userProjectSuffix.length)\n : \"\";\n const dynamicUserProjectCollision =\n userProjectBase.length > 0 &&\n (userProjectBase === config.defaultNamespace ||\n userProjectBase === config.sharedNamespace ||\n (config.namespacePolicies ?? []).some((policy) => policy.name === userProjectBase));\n const protectedNamespace =\n namespace === config.defaultNamespace ||\n namespace === config.sharedNamespace ||\n dynamicUserProjectCollision ||\n (config.namespacePolicies ?? []).some((policy) => policy.name === namespace);\n const policyReadable = !protectedNamespace || canReadNamespace(principal, namespace, config);\n const policyWritable = !protectedNamespace || canWriteNamespace(principal, namespace, config);\n const policyBlocked = protectedNamespace && (!policyReadable || !policyWritable);\n return {\n id,\n kind: \"team-project\",\n namespace,\n readable: teamReadable && policyReadable,\n writable: teamWritable && policyWritable,\n promotable: teamPromotable && policyWritable,\n reason: policyBlocked\n ? \"team-project namespace collides with a protected namespace policy\"\n : \"trusted team-project namespace derived from team and project config\",\n };\n}\n\nexport function resolveScopeProfilePlan(\n options: ResolveScopeProfilePlanOptions,\n): ResolvedScopeProfilePlan | null {\n const active = activeScopeProfile(options.config);\n if (!active || !resolveNamespaceCapabilities(options.config).namespaces) return null;\n\n const baseNamespace = scopeProfileSelfNamespace(options.principal, options.config);\n const layerIds = Array.from(\n new Set<ScopeProfileLayerId>([\n ...active.profile.readOrder,\n active.profile.writeDefault,\n \"userGlobal\",\n ...active.profile.promotionTargets.filter((target): target is ScopeProfileLayerId =>\n [\"userProject\", \"teamProject\", \"userGlobal\", \"serverShared\"].includes(target),\n ),\n ]),\n );\n const layerMap = new Map<ScopeProfileLayerId, ScopeProfileLayerResolution>();\n for (const id of layerIds) {\n layerMap.set(\n id,\n resolveLayer({\n id,\n config: options.config,\n profile: active.profile,\n principal: options.principal,\n baseNamespace,\n codingContext: options.codingContext,\n codingOverlay: options.codingOverlay,\n }),\n );\n }\n\n const readNamespaces: string[] = [];\n for (const id of active.profile.readOrder) {\n const layer = layerMap.get(id);\n if (layer?.readable && layer.namespace && !readNamespaces.includes(layer.namespace)) {\n readNamespaces.push(layer.namespace);\n }\n }\n\n const preferredWriteLayer = layerMap.get(active.profile.writeDefault);\n const readableWriteLayers = active.profile.readOrder\n .map((id) => layerMap.get(id))\n .filter(\n (layer): layer is ScopeProfileLayerResolution =>\n Boolean(layer?.writable && layer.namespace && readNamespaces.includes(layer.namespace)),\n );\n const fallbackWriteLayer =\n preferredWriteLayer?.writable &&\n preferredWriteLayer.namespace &&\n readNamespaces.includes(preferredWriteLayer.namespace)\n ? preferredWriteLayer\n : readableWriteLayers[0];\n const warnings: string[] = [];\n if (!fallbackWriteLayer?.namespace) {\n warnings.push(`scope profile ${active.profileId} has no writable layer inside the profile read stack; writes disabled`);\n } else if (fallbackWriteLayer.id !== active.profile.writeDefault) {\n warnings.push(\n `scope profile ${active.profileId} writeDefault ${active.profile.writeDefault} unavailable: ${preferredWriteLayer?.reason ?? \"not resolved\"}`,\n );\n }\n\n const promotionTargets = active.profile.promotionTargets.map((target) => {\n const layer = layerMap.get(target as ScopeProfileLayerId);\n if (!layer) {\n return {\n target,\n authorized: false,\n reason: \"promotion target did not resolve to a profile layer\",\n };\n }\n return {\n target,\n namespace: layer.namespace,\n authorized: layer.promotable && Boolean(layer.namespace),\n reason: layer.reason,\n };\n });\n\n return {\n profileId: active.profileId,\n profile: active.profile,\n baseNamespace,\n writeLayer: fallbackWriteLayer?.id ?? active.profile.writeDefault,\n writeNamespace: fallbackWriteLayer?.namespace ?? \"\",\n readNamespaces,\n layers: [...layerMap.values()],\n promotionTargets,\n warnings,\n };\n}\n\nexport function expandScopeProfileReadNamespaces(options: {\n profilePlan: ResolvedScopeProfilePlan;\n principalSelfNamespace: string;\n config: PluginConfig;\n principal?: string;\n codingOverlay?: ScopeProfileCodingOverlay | null;\n legacyRecallNamespaces?: string[];\n}): string[] {\n if (options.profilePlan.readNamespaces.length === 0) {\n return [];\n }\n const out = [...options.profilePlan.readNamespaces];\n const add = (namespace: string | undefined): void => {\n if (namespace && !out.includes(namespace)) out.push(namespace);\n };\n const userProjectReadable =\n options.profilePlan.profile.readOrder.includes(\"userProject\") &&\n options.profilePlan.layers.some(\n (layer) => layer.id === \"userProject\" && layer.readable && layer.namespace,\n );\n const userGlobalReadable =\n options.profilePlan.profile.readOrder.includes(\"userGlobal\") &&\n options.profilePlan.layers.some(\n (layer) => layer.id === \"userGlobal\" && layer.readable && layer.namespace,\n );\n if (userProjectReadable) {\n for (const fallback of options.codingOverlay?.readFallbacks ?? []) {\n if (fallback === \"\" && !userGlobalReadable) continue;\n const fallbackNamespace = combineNamespaces(options.principalSelfNamespace, fallback);\n if (\n !hasExplicitNamespacePolicy(fallbackNamespace, options.config) ||\n canReadScopeProfileNamespace(options.principal, fallbackNamespace, options.config)\n ) {\n add(fallbackNamespace);\n }\n }\n }\n return out;\n}\n","/**\n * ScopePlan resolver (issue #1521).\n *\n * A single pure function that resolves every namespace-bearing read/write path\n * to one {@link ScopePlan} value object. Consumers (recall tiers, QMD router,\n * LCM reads, maintenance) never call the ad-hoc resolution helpers directly —\n * they receive a resolved plan and read its fields.\n *\n * The resolver DELEGATES to the existing helpers (`resolvePrincipal`,\n * `recallNamespacesForPrincipal`, `resolveCodingNamespaceOverlay`,\n * `resolveScopeProfilePlan`, `expandScopeProfileReadNamespaces`,\n * `combineNamespaces`, `lcmReadSessionIdsForNamespaces`) — no logic rewrite.\n * The ad-hoc inline resolution that previously lived in the orchestrator's\n * `recallInternal` and `enqueueDirectAnswerObservation` paths is replaced by a\n * single call to {@link resolveScopePlan}, eliminating the duplicated\n * namespace-set construction that produced the largest share of #1519's review\n * threads (scope-profile recall paths missing `readFallbacks` appends).\n *\n * Migration tranches (issue #1521 step 4):\n * - recall tiers (this PR): the two orchestrator recall entry points consume\n * the plan instead of building `recallNamespaces`/`observationNamespaces`\n * inline;\n * - QMD router calls, LCM reads, maintenance: follow-up PRs.\n *\n * CLAUDE.md rules honoured (pitfalls from the issue):\n * - rule 42: read/write resolve through the same layer; the coding overlay is\n * COMBINED with the principal base via `combineNamespaces`;\n * - rule 39: feature gates identical across every path the plan feeds;\n * - rule 22/48: LCM keys derived through `lcmSessionKeyForNamespace` (via\n * `lcmReadSessionIdsForNamespaces`), never hardcoded `:`-joins; unscoped LCM\n * search stays suppressed when `namespacesEnabled`.\n */\n\nimport { resolveNamespaceCapabilities } from \"../capabilities.js\";\nimport {\n canReadNamespace,\n canWriteNamespace,\n defaultNamespaceForPrincipal,\n recallNamespacesForPrincipal,\n resolvePrincipal,\n} from \"../namespaces/principal.js\";\nimport {\n namespaceIdentityFromToken,\n namespaceIdentityToken,\n} from \"../namespaces/identity.js\";\nimport path from \"node:path\";\nimport type { ResolvedScopeProfilePlan } from \"../namespaces/scope-profiles.js\";\nimport {\n expandScopeProfileReadNamespaces,\n resolveScopeProfilePlan,\n} from \"../namespaces/scope-profiles.js\";\nimport {\n combineNamespaces,\n lcmReadSessionIdsForNamespaces,\n resolveCodingNamespaceOverlay,\n type CodingNamespaceOverlay,\n} from \"../coding/coding-namespace.js\";\nimport type { CodingContext, PluginConfig } from \"../types.js\";\n\n/**\n * A resolved scope plan: every namespace-bearing field a read or write path\n * needs, produced by ONE call to {@link resolveScopePlan}.\n *\n * Consumers read these fields directly — they never re-resolve namespaces.\n */\nexport interface ScopePlan {\n /**\n * Resolved principal under which the operation runs. `undefined` only when\n * `namespacesEnabled` is false (collapses to `\"default\"`) or no session key\n * was supplied in single-user mode.\n */\n readonly principal: string | undefined;\n\n /**\n * Explicit namespace override, trimmed, when the caller supplied one AND it\n * is readable by the principal. `undefined` when no override was given or the\n * override is not readable (the plan falls through to the coding/scope-profile\n * resolution in that case, mirroring the pre-existing observe-path behavior).\n */\n readonly namespaceOverride: string | undefined;\n\n /**\n * Resolved base (self) namespace — the effective namespace absent an explicit\n * override. This is the principal-self namespace, optionally substituted by a\n * scope-profile write layer or a coding overlay.\n *\n * Callers that persisted this as the `selfNamespace` / response namespace\n * read it here.\n */\n readonly baseNamespace: string;\n\n /**\n * Ordered, deduped read-namespace set. Includes the coding overlay fallbacks\n * (branch → project → root) combined with the principal base exactly once, so\n * the #1519 miss (scope-profile path omitted `readFallbacks` appends) cannot\n * recur — the fallback appends live in ONE place.\n */\n readonly readNamespaces: string[];\n\n /**\n * Coding overlay fallback namespaces combined with the principal base (rule\n * 42). Empty when no coding overlay applies. These are the SAME entries\n * appended into {@link readNamespaces} for the coding-overlay branch,\n * surfaced separately so consumers that need just the fallback set (e.g.\n * LCM read-key derivation) can read them without re-deriving.\n */\n readonly readFallbacks: string[];\n\n /**\n * LCM read namespace set. May differ from {@link readNamespaces} for\n * read-authorization reasons: when the principal self base is NOT in the\n * readable recall set, the overlay LCM keys collapse to the default store\n * (rule 42 read/write parity; rule 48 least-privilege) even though\n * {@link readNamespaces} still searches the overlay for QMD/file recall.\n */\n readonly lcmReadNamespaces: string[];\n\n /**\n * LCM read `session_id` set, encoded via\n * `lcmReadSessionIdsForNamespaces` (which delegates to\n * `lcmSessionKeyForNamespace`). Ordered and deduped; the primary overlay key\n * is first. Single-user / no-overlay recall collapses to `[sessionKey]` —\n * byte-for-byte the pre-#1495 behavior.\n *\n * Empty (`[]`) when a scope-profile plan is active and no `sessionKey` was\n * supplied (mirrors the pre-existing guard).\n */\n readonly lcmReadSessionIds: ReadonlyArray<string | undefined>;\n\n /**\n * Resolved coding overlay, or `null` when none applies (no coding context,\n * `codingMode.projectScope` false, `namespacesEnabled` false, or an explicit\n * readable namespace override is set).\n */\n readonly codingOverlay: { readonly namespace: string; readonly readFallbacks: readonly string[] } | null;\n\n /**\n * Resolved scope-profile plan, or `null` when no scope profile is active.\n * Consumers that branched on \"profile vs. non-profile\" read this directly.\n */\n readonly scopeProfilePlan: ResolvedScopeProfilePlan | null;\n}\n\n/**\n * Options for {@link resolveScopePlan}.\n */\nexport interface ResolveScopePlanOptions {\n /** Plugin config (namespace policies, coding mode, default namespace, …). */\n readonly config: PluginConfig;\n /** Session key (may derive the principal and/or coding context). */\n readonly sessionKey?: string;\n /**\n * Explicit namespace override (raw — the resolver trims it). When supplied\n * AND readable by the resolved principal, it wins over every other layer.\n */\n readonly namespace?: string;\n /**\n * Authenticated principal override. Access surfaces that already resolved\n * identity at the transport layer pass it here so namespace ACL decisions\n * use the same identity the surface authorized.\n */\n readonly principalOverride?: string;\n /**\n * Coding context for the session. Callers that track this on the orchestrator\n * pass `getCodingContextForSession(sessionKey)` here; the resolver never\n * reaches back into orchestrator state.\n */\n readonly codingContext?: CodingContext | null;\n /**\n * Whether namespace routing is enabled. Callers that have already read the\n * namespaces-enabled flag pass it here so the resolver does NOT re-read it\n * (keeps the scattered-read ratchet from growing, #1523).\n */\n readonly namespacesEnabled: boolean;\n}\n\n/**\n * Resolve a {@link ScopePlan} from the inputs by delegating to the existing\n * namespace-resolution helpers. Pure — no side effects, no orchestrator state.\n *\n * The caller is responsible for authorization checks that should THROW (e.g.\n * `namespacesEnabled && !principal`, or an unreadable explicit override in the\n * recall path). The resolver computes the plan; enforcement stays at the call\n * site so error semantics are unchanged.\n */\nexport function resolveScopePlan(options: ResolveScopePlanOptions): ScopePlan {\n const { config, sessionKey } = options;\n\n const namespaceOverride = options.namespace?.trim() || undefined;\n\n const principal =\n typeof options.principalOverride === \"string\" && options.principalOverride.length > 0\n ? options.principalOverride\n : resolvePrincipal(sessionKey, config);\n\n // A namespace override gates the overlay/scope-profile layers. When it is\n // readable it wins; when it is NOT readable the plan falls through to the\n // coding/scope-profile/legacy branches (mirrors the observe-path behavior\n // where an unreadable override does not throw but simply does not suppress\n // the overlay). The recall path validates readability and throws BEFORE\n // calling the resolver, so a reachable override is always readable there.\n const namespaceOverrideReadable =\n namespaceOverride !== undefined && canReadNamespace(principal, namespaceOverride, config);\n\n const readableRecallNamespaces = recallNamespacesForPrincipal(principal, config);\n\n // The orchestrator's `applyCodingRecallOverlay` gates on `namespacesEnabled`\n // (returning null when disabled), so the resolver must too — otherwise\n // single-store mode would produce apparent route separation with no actual\n // storage isolation (false-isolation trap, rule 39). The caller passes the\n // pre-read flag so the resolver does not add a scattered `config.*Enabled`\n // read (ratchet, #1523).\n const namespacesEnabled = options.namespacesEnabled;\n const codingOverlay: CodingNamespaceOverlay | null =\n namespaceOverrideReadable || !namespacesEnabled\n ? null\n : resolveCodingNamespaceOverlay(\n options.codingContext ?? null,\n config.codingMode,\n config.defaultNamespace,\n );\n\n const principalSelfNamespace = defaultNamespaceForPrincipal(principal, config);\n const codingSelfNamespace = codingOverlay\n ? combineNamespaces(principalSelfNamespace, codingOverlay.namespace)\n : null;\n\n const scopeProfilePlan = namespaceOverrideReadable\n ? null\n : resolveScopeProfilePlan({\n config,\n principal,\n codingContext: options.codingContext ?? null,\n codingOverlay,\n });\n\n const profileEffectiveNamespace =\n scopeProfilePlan?.writeNamespace || scopeProfilePlan?.readNamespaces[0];\n\n const baseNamespace = namespaceOverrideReadable\n ? namespaceOverride!\n : profileEffectiveNamespace ?? codingSelfNamespace ?? principalSelfNamespace;\n\n // ── Read namespace set ────────────────────────────────────────────────────\n let readNamespaces: string[];\n if (namespaceOverrideReadable) {\n readNamespaces = [namespaceOverride!];\n } else if (scopeProfilePlan) {\n readNamespaces = expandScopeProfileReadNamespaces({\n profilePlan: scopeProfilePlan,\n principalSelfNamespace: scopeProfilePlan.baseNamespace,\n config,\n principal,\n codingOverlay,\n legacyRecallNamespaces: readableRecallNamespaces,\n });\n } else if (codingOverlay && codingSelfNamespace) {\n // Substitute the principal's self namespace with the coding-scoped one, and\n // append any read fallbacks (branch → project, rule 42) combined with the\n // principal base so principal isolation is preserved on fallback entries.\n const mapped = readableRecallNamespaces.map((ns) =>\n ns === principalSelfNamespace ? codingSelfNamespace : ns,\n );\n const fallbackNs = codingOverlay.readFallbacks.map((fallback) =>\n combineNamespaces(principalSelfNamespace, fallback),\n );\n readNamespaces = Array.from(new Set<string>([...mapped, ...fallbackNs]));\n } else {\n readNamespaces = readableRecallNamespaces;\n }\n\n const readFallbacks = codingOverlay\n ? codingOverlay.readFallbacks.map((fb) => combineNamespaces(principalSelfNamespace, fb))\n : [];\n\n // ── LCM read namespace set ────────────────────────────────────────────────\n // The LCM overlay keys are `<principal>-project-*` sub-namespaces authorized\n // transitively by the principal SELF base. Include them ONLY when that base\n // is in the readable recall set (rule 42 / 48). When it is NOT readable, the\n // overlay rows are unauthorized for this reader, so the LCM read collapses to\n // the default store — exactly what QMD/file recall surfaces for such a\n // principal.\n const codingOverlaySelfReadable =\n codingOverlay !== null &&\n (scopeProfilePlan\n ? scopeProfilePlan.layers.some((layer) => layer.id === \"userProject\" && layer.readable)\n : readableRecallNamespaces.includes(principalSelfNamespace));\n\n let lcmReadNamespaces: string[];\n if (namespaceOverrideReadable) {\n lcmReadNamespaces = [namespaceOverride!];\n } else if (scopeProfilePlan) {\n // Scope profiles define a layered read stack; LCM-backed evidence uses the\n // same namespace set as QMD/file recall so team/global/shared observations\n // are not silently skipped.\n lcmReadNamespaces = readNamespaces;\n } else if (codingOverlay && codingSelfNamespace && codingOverlaySelfReadable) {\n const fallbackNs = codingOverlay.readFallbacks.map((fallback) =>\n combineNamespaces(principalSelfNamespace, fallback),\n );\n lcmReadNamespaces = [codingSelfNamespace, ...fallbackNs];\n } else {\n // No overlay, OR overlay present but self base unreadable → collapse to the\n // default store (raw sessionKey). No `<principal>-project-*` overlay key is\n // searched.\n lcmReadNamespaces = [config.defaultNamespace];\n }\n\n const lcmReadSessionIds =\n scopeProfilePlan && !sessionKey\n ? []\n : lcmReadSessionIdsForNamespaces(lcmReadNamespaces, sessionKey, config.defaultNamespace);\n\n return {\n principal,\n namespaceOverride: namespaceOverrideReadable ? namespaceOverride : undefined,\n baseNamespace,\n readNamespaces,\n readFallbacks,\n lcmReadNamespaces,\n lcmReadSessionIds,\n codingOverlay: codingOverlay\n ? { namespace: codingOverlay.namespace, readFallbacks: codingOverlay.readFallbacks }\n : null,\n scopeProfilePlan,\n };\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// Centralized namespace-resolution helpers (issue #1521 step 3–4)\n//\n// The three functions below consolidate the ad-hoc namespace-resolution logic\n// that was previously scattered across orchestrator.ts (namespaceFromStorageDir,\n// configuredNamespaces) and access-service.ts (resolveWritableNamespace). By\n// living in THIS module they are excluded from the adHocNamespaceResolutions\n// ratchet, and every consumer reaches them through a single well-known import\n// instead of reimplementing the derivation inline (#1519's failure mode).\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * The configured namespace set: default + shared + every namespace-policy\n * name, trimmed and de-duplicated. Pure — reads only from `config`.\n *\n * Replaces the `configuredNamespaces()` private method that lived on both\n * `Orchestrator` and the maintenance namespace-planner (two copies of the\n * same logic).\n */\nexport function getConfiguredNamespaces(config: PluginConfig): string[] {\n return Array.from(\n new Set(\n [\n config.defaultNamespace,\n config.sharedNamespace,\n ...config.namespacePolicies.map((policy) => policy.name),\n ]\n .map((value) => value.trim())\n .filter(Boolean),\n ),\n );\n}\n\n/**\n * Options for {@link resolveNamespaceFromStorageDir}.\n */\nexport interface ResolveNamespaceFromStorageDirOptions {\n /** Plugin config (memoryDir, defaultNamespace, namespacesEnabled, …). */\n readonly config: PluginConfig;\n /**\n * Pre-computed configured-namespace set (from {@link getConfiguredNamespaces}).\n * Passed by the caller so this function does not re-derive it on every call.\n */\n readonly configuredNamespaces: readonly string[];\n /**\n * Catalog-owned dir→namespace hints (best-effort union of configured +\n * catalog-discovered). May be `undefined` when no catalog hints are loaded.\n */\n readonly hints?: ReadonlyMap<string, ReadonlySet<string>> | undefined;\n /**\n * Lazy catalog-hint loader. Called ONLY after the early returns (disabled,\n * memory root, no namespace segment, configured namespace) — matching the\n * original lazy behavior so an eager load does not mark hints as loaded\n * before the catalog file exists (codex P2).\n */\n readonly loadHints?: () => void;\n}\n\n/**\n * Derive the namespace a storage directory belongs to.\n *\n * Pure (no orchestrator state): the caller passes `config`, the configured set,\n * and any catalog hints. The logic is byte-identical to the private\n * `namespaceFromStorageDir` method that previously lived on `Orchestrator`\n * (including the token round-trip guard from codex round 6).\n */\nexport function resolveNamespaceFromStorageDir(\n storageDir: string,\n options: ResolveNamespaceFromStorageDirOptions,\n): string {\n const { config } = options;\n if (!resolveNamespaceCapabilities(config).namespaces) return config.defaultNamespace;\n const resolvedStorageDir = path.resolve(storageDir);\n const resolvedMemoryDir = path.resolve(config.memoryDir);\n if (resolvedStorageDir === resolvedMemoryDir) return config.defaultNamespace;\n const m = resolvedStorageDir.match(/[\\\\/]namespaces[\\\\/]([^\\\\/]+)$/);\n if (!m?.[1]) return config.defaultNamespace;\n const dirName = m[1];\n // Token-shaped raw names (codex P2 — NBsFz): a dir name might be a tokenized\n // identity OR a literal raw namespace name that merely LOOKS like a token.\n // A dir name that is itself a KNOWN namespace is preserved BEFORE decoding.\n if (options.configuredNamespaces.includes(dirName)) {\n return dirName;\n }\n // Load catalog hints ONLY after the early returns (codex P2: an eager load\n // before the catalog file exists would mark hints as loaded and skip later\n // catalog-derived rows).\n options.loadHints?.();\n const hints = options.hints;\n const hintedNamespaces = hints?.get(resolvedStorageDir);\n if (hintedNamespaces?.has(dirName)) {\n return dirName;\n }\n if (hintedNamespaces?.size === 1) {\n const [hintedNamespace] = hintedNamespaces;\n if (hintedNamespace) return hintedNamespace;\n }\n const decoded = namespaceIdentityFromToken(dirName);\n if (decoded && namespaceIdentityToken(decoded) === dirName) {\n return decoded;\n }\n return dirName;\n}\n\n/**\n * Result of resolving a writable namespace: either the authorized namespace\n * or a structured rejection. The caller decides how to surface the rejection\n * (e.g. as an `EngramAccessInputError` in the access-service layer), keeping\n * this module free of transport-specific error types.\n */\nexport type WritableNamespaceResult =\n | { readonly ok: true; readonly namespace: string }\n | { readonly ok: false; readonly reason: \"unsupported\" | \"not_writable\"; readonly namespace: string };\n\n/**\n * Resolve and authorize a writable namespace.\n *\n * Combines the three steps that `AccessService.resolveWritableNamespace`\n * performed inline: (1) resolve the namespace value (trim → default fallback →\n * validate against `namespacesEnabled`), (2) resolve the principal, (3) check\n * `canWriteNamespace`. Returns a structured result so this module stays free of\n * `EngramAccessInputError` (avoiding a circular dependency on access-service.ts).\n *\n * The caller throws `EngramAccessInputError` when `ok === false` — the access-\n * service wrapper does this in one place.\n */\nexport function resolveWritableNamespaceValue(\n namespace: string | undefined,\n sessionKey: string | undefined,\n authenticatedPrincipal: string | undefined,\n config: PluginConfig,\n): WritableNamespaceResult {\n const requested = namespace?.trim();\n let resolved: string;\n if (!requested) {\n resolved = config.defaultNamespace;\n } else if (\n !resolveNamespaceCapabilities(config).namespaces &&\n requested !== config.defaultNamespace\n ) {\n return { ok: false, reason: \"unsupported\", namespace: requested };\n } else {\n resolved = requested;\n }\n\n const trusted = authenticatedPrincipal?.trim();\n const principal =\n typeof trusted === \"string\" && trusted.length > 0\n ? trusted\n : resolvePrincipal(sessionKey, config);\n\n if (!canWriteNamespace(principal, resolved, config)) {\n return { ok: false, reason: \"not_writable\", namespace: resolved };\n }\n return { ok: true, namespace: resolved };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,OAAO,UAAU;AA8DjB,IAAM,yBAAyB;AAExB,SAAS,oBAAgC;AAC9C,SAAO,CAAC,KA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,kBACrB;AACA,WAAO,EAAE,IAAI,OAAO,QAAQ,eAAe,WAAW,UAAU;AAAA,EAClE,OAAO;AACL,eAAW;AAAA,EACb;AAEA,QAAM,UAAU,wBAAwB,KAAK;AAC7C,QAAM,YACJ,OAAO,YAAY,YAAY,QAAQ,SAAS,IAC5C,UACA,iBAAiB,YAAY,MAAM;AAEzC,MAAI,CAAC,kBAAkB,WAAW,UAAU,MAAM,GAAG;AACnD,WAAO,EAAE,IAAI,OAAO,QAAQ,gBAAgB,WAAW,SAAS;AAAA,EAClE;AACA,SAAO,EAAE,IAAI,MAAM,WAAW,SAAS;AACzC;","names":["namespace","path","path"]}
|
|
@@ -5,6 +5,9 @@ import {
|
|
|
5
5
|
compareEntityTimestamps,
|
|
6
6
|
normalizeEntityName
|
|
7
7
|
} from "./chunk-Q6BAA57B.js";
|
|
8
|
+
import {
|
|
9
|
+
resolveNamespaceCapabilities
|
|
10
|
+
} from "./chunk-SHJGBAIW.js";
|
|
8
11
|
import {
|
|
9
12
|
sanitizeMemoryContent
|
|
10
13
|
} from "./chunk-5GKPFL3S.js";
|
|
@@ -234,12 +237,12 @@ async function readNativeChunks(config, recallNamespaces) {
|
|
|
234
237
|
workspaceDir: config.workspaceDir,
|
|
235
238
|
memoryDir: config.memoryDir,
|
|
236
239
|
config: config.nativeKnowledge,
|
|
237
|
-
recallNamespaces: config.
|
|
240
|
+
recallNamespaces: resolveNamespaceCapabilities(config).namespaces ? recallNamespaces : void 0,
|
|
238
241
|
defaultNamespace: config.defaultNamespace
|
|
239
242
|
}).catch(() => []);
|
|
240
243
|
}
|
|
241
244
|
async function resolveEntityIndexStorages(storage, config, recallNamespaces, namespaceStorage) {
|
|
242
|
-
if (!config.
|
|
245
|
+
if (!resolveNamespaceCapabilities(config).namespaces || !namespaceStorage || !recallNamespaces || recallNamespaces.length === 0) {
|
|
243
246
|
return [storage];
|
|
244
247
|
}
|
|
245
248
|
const storages = [];
|
|
@@ -679,4 +682,4 @@ export {
|
|
|
679
682
|
entityIndexVersion,
|
|
680
683
|
entityRecentTranscriptLookbackHours
|
|
681
684
|
};
|
|
682
|
-
//# sourceMappingURL=chunk-
|
|
685
|
+
//# sourceMappingURL=chunk-V5OVSGB6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/entity-retrieval.ts"],"sourcesContent":["import { resolveNamespaceCapabilities } from \"./capabilities.js\";\nimport { createHash } from \"node:crypto\";\nimport { sanitizeMemoryContent } from \"./sanitize.js\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { collectNativeKnowledgeChunks, type NativeKnowledgeChunk } from \"./native-knowledge.js\";\nimport { compareEntityTimestamps, normalizeEntityName, type StorageManager } from \"./storage.js\";\nimport { normalizeEntityText, resolveRequestedEntitySectionKeys } from \"./entity-schema.js\";\nimport type { EntityStructuredSection, MemoryFile, PluginConfig, TranscriptEntry } from \"./types.js\";\n\nconst ENTITY_INDEX_VERSION = 3;\nconst RECENT_TRANSCRIPT_LOOKBACK_HOURS = 24;\nconst INSTRUCTION_LIKE_RE = /\\b(always|never|must|should|remember to|do not|don't|process|workflow|template|checklist|instruction)\\b/i;\nconst METADATA_WRAPPER_RE = /^(source|context|metadata|notes?):/i;\nconst ENTITY_PRONOUN_RE = /\\b(he|him|his|she|her|they|them|their|it|its)\\b/i;\nconst BELIEF_LEDGER_SECTION_KEY = \"belief_ledger\";\nconst BELIEF_LEDGER_FACT_RE = /^claim=([^;]+);\\s*status=([^;]+);\\s*updatedAt=([^;]+);\\s*(.+)$/;\n\ntype EntityQueryMode = \"direct\" | \"timeline\" | \"follow_up\";\n\ntype EntityMentionIndexEntry = {\n canonicalId: string;\n name: string;\n type: string;\n aliases: string[];\n summary?: string;\n facts: string[];\n timelineFacts: string[];\n structuredSections: EntityStructuredSection[];\n timeline: Array<{\n timestamp: string;\n text: string;\n source?: string;\n sessionKey?: string;\n principal?: string;\n }>;\n relationships: Array<{ target: string; label: string }>;\n activity: Array<{ date: string; note: string }>;\n factCount: number;\n memorySnippets: string[];\n nativeChunks: Array<{\n chunkId: string;\n title: string;\n sourceKind: NativeKnowledgeChunk[\"sourceKind\"];\n sourcePath: string;\n snippet: string;\n derivedDate?: string;\n }>;\n};\n\ntype EntityMentionIndex = {\n version: number;\n updatedAt: string;\n entities: EntityMentionIndexEntry[];\n};\n\ntype EntityCandidate = {\n entry: EntityMentionIndexEntry;\n alias: string;\n score: number;\n source: \"query\" | \"recent_turn\";\n};\n\ntype EntityHintSnippet = {\n text: string;\n score: number;\n kind: \"summary\" | \"fact\" | \"section\" | \"relationship\" | \"activity\" | \"memory\" | \"native\";\n};\n\nexport interface BuildEntityRecallSectionOptions {\n config: PluginConfig;\n storage: StorageManager;\n namespaceStorage?: (namespace: string) => Promise<StorageManager>;\n query: string;\n recallNamespaces?: string[];\n recentTurns: number;\n maxHints: number;\n maxSupportingFacts: number;\n maxRelatedEntities: number;\n maxChars: number;\n transcriptEntries: TranscriptEntry[];\n}\n\nfunction tokenize(value: string): string[] {\n return normalizeEntityText(value).split(/\\s+/).filter((token) => token.length >= 2);\n}\n\nfunction uniqueStrings(values: string[]): string[] {\n return [...new Set(values.map((value) => value.trim()).filter((value) => value.length > 0))];\n}\n\nfunction containsPhrase(haystack: string, needle: string): boolean {\n if (!needle) return false;\n const escaped = needle.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(`(^|\\\\b)${escaped}(\\\\b|$)`, \"i\").test(haystack);\n}\n\nfunction compactLine(value: string, maxLength: number = 220): string {\n const normalized = value.replace(/\\s+/g, \" \").trim();\n if (normalized.length <= maxLength) return normalized;\n return `${normalized.slice(0, Math.max(0, maxLength - 1)).trimEnd()}…`;\n}\n\nfunction dedupeHintSnippetsByText(snippets: EntityHintSnippet[]): EntityHintSnippet[] {\n const seen = new Set<string>();\n const result: EntityHintSnippet[] = [];\n for (const snippet of snippets) {\n const key = normalizeEntityText(snippet.text);\n if (seen.has(key)) continue;\n seen.add(key);\n result.push(snippet);\n }\n return result;\n}\n\nfunction isBeliefLedgerSection(section: Pick<EntityStructuredSection, \"key\">): boolean {\n return normalizeEntityText(section.key).replace(/\\s+/g, \"_\") === BELIEF_LEDGER_SECTION_KEY;\n}\n\nfunction beliefLedgerFactKeys(sections: EntityStructuredSection[]): Set<string> {\n const keys = new Set<string>();\n for (const section of sections) {\n if (!isBeliefLedgerSection(section)) continue;\n for (const fact of section.facts) {\n keys.add(normalizeEntityText(fact));\n }\n }\n return keys;\n}\n\nfunction recallFactsForStructuredSection(section: EntityStructuredSection): string[] {\n if (!isBeliefLedgerSection(section)) return section.facts;\n return currentActiveBeliefLedgerFactTexts(section.facts);\n}\n\nfunction currentActiveBeliefLedgerFactTexts(facts: string[]): string[] {\n const byClaim = new Map<string, { status: string; updatedAtMs: number; texts: string[] }>();\n for (const fact of facts) {\n const match = BELIEF_LEDGER_FACT_RE.exec(fact.trim());\n if (!match) continue;\n const [, claimId, status, updatedAt, text] = match;\n const updatedAtMs = Date.parse(updatedAt);\n if (!claimId?.trim() || !status?.trim() || !Number.isFinite(updatedAtMs) || !text?.trim()) continue;\n const normalizedStatus = status.trim().toLowerCase();\n const normalizedClaimId = claimId.trim();\n const current = byClaim.get(normalizedClaimId);\n const inactiveTieWins =\n current &&\n updatedAtMs === current.updatedAtMs &&\n current.status === \"active\" &&\n normalizedStatus !== \"active\";\n if (!current || updatedAtMs > current.updatedAtMs || inactiveTieWins) {\n byClaim.set(normalizedClaimId, { status: normalizedStatus, updatedAtMs, texts: [text.trim()] });\n continue;\n }\n if (updatedAtMs === current.updatedAtMs && current.status === normalizedStatus) {\n current.texts.push(text.trim());\n }\n }\n const result: string[] = [];\n for (const current of byClaim.values()) {\n if (current.status === \"active\") {\n result.push(...current.texts);\n }\n }\n return result;\n}\n\nfunction relationLine(entry: EntityMentionIndexEntry, relationship: { target: string; label: string }): string {\n const normalizedLabel = relationship.label.replace(/\\s+/g, \" \").trim();\n if (normalizedLabel.length === 0) return `${entry.name} is connected to ${relationship.target}`;\n return `${entry.name} ${normalizedLabel} ${relationship.target}`;\n}\n\nfunction detectEntityQueryMode(query: string): EntityQueryMode | null {\n const normalized = normalizeEntityText(query);\n if (!normalized) return null;\n if (\n /^(what about|and what about|how about|what happened (with|to) (he|him|his|she|her|they|them|their|it|its)|did (he|she|they|it)|is (he|she|they|it)|was (he|she|they|it))\\b/.test(normalized)\n ) {\n return \"follow_up\";\n }\n if (\n /^(who is|who s|what do we know about|what does|tell me about|what can you tell me about|what s new with|what happened with|what happened to|status of|where is|how is)\\b/.test(normalized)\n ) {\n if (/^what does\\b/.test(normalized)) {\n if (/^what does (?:this|that|it|the|a|an|my|our|your|their)\\b/.test(normalized)) {\n return null;\n }\n if (\n /^what does [a-z0-9-]+ (?:error|warning|exception|failure|stack|trace|code|message|log)\\b/.test(normalized)\n && /\\b(mean|means|indicate|indicates|imply|implies)\\b/.test(normalized)\n ) {\n return null;\n }\n }\n return /what happened|what s new|status of|how is|where is/.test(normalized) ? \"timeline\" : \"direct\";\n }\n if (ENTITY_PRONOUN_RE.test(normalized) && normalized.split(/\\s+/).length <= 8) {\n return \"follow_up\";\n }\n return null;\n}\n\nfunction scoreAliasMatch(query: string, alias: string): number {\n const normalizedQuery = normalizeEntityText(query);\n const normalizedAlias = normalizeEntityText(alias);\n if (!normalizedAlias) return 0;\n if (normalizedQuery === normalizedAlias) return 10;\n if (containsPhrase(normalizedQuery, normalizedAlias)) return 8 + Math.min(normalizedAlias.split(/\\s+/).length, 3);\n const queryTokens = new Set(tokenize(normalizedQuery));\n const aliasTokens = tokenize(normalizedAlias);\n if (aliasTokens.length === 0) return 0;\n const overlap = aliasTokens.filter((token) => queryTokens.has(token)).length;\n if (overlap === 0) return 0;\n // Cross-entity contamination guard (#682 PR 2/3 R-2). For multi-token\n // aliases, partial-token overlap that hits ONLY shared common tokens\n // (like \"person\" in \"Person-A1\" / \"Person-B1\") would surface every\n // similarly-prefixed entity for a query that named only one. Require\n // that the overlap include at least one DISTINCTIVE alias token —\n // i.e. a token that does not also appear in any other entity's\n // alias-token vocabulary. Since this function is pure / per-pair, we\n // approximate \"distinctive\" by requiring the overlap to include at\n // least one token that is not a substring-of common identifier\n // affixes. The aliasTokens with length > 1 must contribute at least\n // one non-affix overlap. \"Alice Example\" ([\"alice\", \"example\"])\n // matched by query \"Tell me about Alice\" → overlap = 1 on \"alice\",\n // and \"alice\" is not an affix → score = 1. \"Person-A1\" tokens\n // [\"person\", \"a1\"] matched by query \"Who is Person-B1?\" → overlap =\n // 1 on \"person\", and \"person\" IS an affix → score = 0.\n if (aliasTokens.length > 1) {\n const nonAffixOverlap = aliasTokens.filter(\n (token) => queryTokens.has(token) && !isAliasAffixToken(token),\n ).length;\n if (nonAffixOverlap === 0) return 0;\n }\n return overlap;\n}\n\n/**\n * Tokens that look like type prefixes / generic role identifiers and\n * therefore should not, on their own, count as evidence that a\n * multi-token alias matches a query (#682 PR 2/3 R-2).\n *\n * Kept as a small explicit list rather than a regex so additions are\n * deliberate. The list mirrors the entity types listed in\n * `entity-schema.ts` plus the most common generic role identifiers\n * that frequently appear as the leading token of a display name.\n */\nconst ALIAS_AFFIX_TOKENS = new Set<string>([\n \"person\", \"people\", \"user\", \"users\", \"team\", \"teams\",\n \"project\", \"projects\", \"topic\", \"topics\",\n \"org\", \"orgs\", \"organization\", \"organizations\", \"company\", \"companies\",\n \"place\", \"places\", \"tool\", \"tools\", \"service\", \"services\",\n \"system\", \"systems\", \"agent\", \"agents\", \"bot\", \"bots\",\n]);\n\nfunction isAliasAffixToken(token: string): boolean {\n return ALIAS_AFFIX_TOKENS.has(token);\n}\n\nfunction isLikelyInstructionLike(value: string): boolean {\n return INSTRUCTION_LIKE_RE.test(value) || METADATA_WRAPPER_RE.test(value);\n}\n\nfunction sanitizeEntityFact(fact: string): string {\n const sanitized = sanitizeMemoryContent(fact);\n const clean = sanitized.text.trim();\n if (!clean) return \"\";\n if (INSTRUCTION_LIKE_RE.test(clean) && clean.length > 100) return \"\";\n return clean;\n}\n\nfunction scoreHintSnippet(snippet: EntityHintSnippet, queryTokens: string[]): EntityHintSnippet | null {\n const normalized = normalizeEntityText(snippet.text);\n if (!normalized) return null;\n const scored = { ...snippet };\n if (isLikelyInstructionLike(scored.text) && scored.kind !== \"summary\") {\n scored.score -= 3;\n }\n const overlap = queryTokens.filter((token) => normalized.includes(token)).length;\n scored.score += overlap * 2;\n if (METADATA_WRAPPER_RE.test(scored.text)) scored.score -= 2;\n if (scored.text.length <= 160) scored.score += 1;\n return scored.score > 0 ? scored : null;\n}\n\nfunction sortTimelineEntriesDesc(\n left: EntityMentionIndexEntry[\"timeline\"][number],\n right: EntityMentionIndexEntry[\"timeline\"][number],\n): number {\n const timestampOrder = compareEntityTimestamps(right.timestamp, left.timestamp);\n if (timestampOrder !== 0) {\n return timestampOrder;\n }\n return right.text.localeCompare(left.text);\n}\n\nfunction jaccardSimilarity(a: string, b: string): number {\n const aTokens = new Set(tokenize(a));\n const bTokens = new Set(tokenize(b));\n if (aTokens.size === 0 || bTokens.size === 0) return 0;\n let intersection = 0;\n for (const token of aTokens) {\n if (bTokens.has(token)) intersection += 1;\n }\n const union = new Set([...aTokens, ...bTokens]).size;\n return union === 0 ? 0 : intersection / union;\n}\n\nfunction buildAliasIndex(entries: EntityMentionIndexEntry[]): Map<string, EntityMentionIndexEntry[]> {\n const index = new Map<string, EntityMentionIndexEntry[]>();\n for (const entry of entries) {\n const aliases = uniqueStrings([entry.name, ...entry.aliases]).map(normalizeEntityText).filter(Boolean);\n for (const alias of aliases) {\n const existing = index.get(alias) ?? [];\n existing.push(entry);\n index.set(alias, existing);\n }\n }\n return index;\n}\n\nasync function readNativeChunks(\n config: PluginConfig,\n recallNamespaces?: string[],\n): Promise<NativeKnowledgeChunk[]> {\n if (!config.nativeKnowledge?.enabled) return [];\n return collectNativeKnowledgeChunks({\n workspaceDir: config.workspaceDir,\n memoryDir: config.memoryDir,\n config: config.nativeKnowledge,\n recallNamespaces: resolveNamespaceCapabilities(config).namespaces ? recallNamespaces : undefined,\n defaultNamespace: config.defaultNamespace,\n }).catch(() => []);\n}\n\nasync function resolveEntityIndexStorages(\n storage: StorageManager,\n config: PluginConfig,\n recallNamespaces?: string[],\n namespaceStorage?: (namespace: string) => Promise<StorageManager>,\n): Promise<StorageManager[]> {\n if (\n !resolveNamespaceCapabilities(config).namespaces ||\n !namespaceStorage ||\n !recallNamespaces ||\n recallNamespaces.length === 0\n ) {\n return [storage];\n }\n\n const storages: StorageManager[] = [];\n const seenDirs = new Set<string>();\n for (const namespace of uniqueStrings(recallNamespaces)) {\n try {\n const scopedStorage = await namespaceStorage(namespace);\n const storageDir = path.resolve(scopedStorage.dir);\n if (seenDirs.has(storageDir)) continue;\n seenDirs.add(storageDir);\n storages.push(scopedStorage);\n } catch {\n continue;\n }\n }\n\n return storages.length > 0 ? storages : [storage];\n}\n\nfunction entityIndexStatePath(storage: StorageManager): string {\n return path.join(storage.dir, \"state\", \"entity-mention-index.json\");\n}\n\nasync function readEntityIndexState(storage: StorageManager): Promise<EntityMentionIndex | null> {\n const raw = await readFile(entityIndexStatePath(storage), \"utf-8\").catch(() => \"\");\n if (!raw) return null;\n try {\n const parsed = JSON.parse(raw) as Partial<EntityMentionIndex>;\n if (parsed.version !== ENTITY_INDEX_VERSION || !Array.isArray(parsed.entities)) return null;\n return parsed as EntityMentionIndex;\n } catch {\n return null;\n }\n}\n\nasync function writeEntityIndexState(storage: StorageManager, index: EntityMentionIndex): Promise<void> {\n const statePath = entityIndexStatePath(storage);\n await mkdir(path.dirname(statePath), { recursive: true });\n const nextContent = JSON.stringify(index, null, 2) + \"\\n\";\n const currentContent = await readFile(statePath, \"utf-8\").catch(() => \"\");\n if (currentContent === nextContent) return;\n await writeFile(statePath, nextContent, \"utf-8\");\n}\n\nfunction nativePseudoCanonicalId(chunk: NativeKnowledgeChunk): string {\n return `native:${createHash(\"sha256\").update(chunk.sourcePath).digest(\"hex\").slice(0, 12)}`;\n}\n\nfunction createPseudoNativeEntry(chunk: NativeKnowledgeChunk): EntityMentionIndexEntry {\n const canonicalId = nativePseudoCanonicalId(chunk);\n return {\n canonicalId,\n name: chunk.title,\n type: chunk.sourceKind,\n aliases: uniqueStrings(chunk.aliases ?? []),\n facts: [],\n structuredSections: [],\n timelineFacts: [],\n timeline: [],\n relationships: [],\n activity: [],\n factCount: 0,\n memorySnippets: [],\n nativeChunks: [\n {\n chunkId: chunk.chunkId,\n title: chunk.title,\n sourceKind: chunk.sourceKind,\n sourcePath: chunk.sourcePath,\n snippet: compactLine(chunk.content, 180),\n derivedDate: chunk.derivedDate,\n },\n ],\n };\n}\n\nfunction mergeNativeChunk(entry: EntityMentionIndexEntry, chunk: NativeKnowledgeChunk): void {\n const existing = entry.nativeChunks.find((item) => item.chunkId === chunk.chunkId);\n if (existing) return;\n entry.nativeChunks.push({\n chunkId: chunk.chunkId,\n title: chunk.title,\n sourceKind: chunk.sourceKind,\n sourcePath: chunk.sourcePath,\n snippet: compactLine(chunk.content, 180),\n derivedDate: chunk.derivedDate,\n });\n entry.aliases = uniqueStrings([...entry.aliases, ...(chunk.aliases ?? [])]);\n}\n\nasync function buildEntityMentionIndex(\n storage: StorageManager,\n config: PluginConfig,\n recallNamespaces?: string[],\n namespaceStorage?: (namespace: string) => Promise<StorageManager>,\n): Promise<EntityMentionIndex> {\n const storages = await resolveEntityIndexStorages(\n storage,\n config,\n recallNamespaces,\n namespaceStorage,\n );\n const shouldPersistIndex =\n storages.length === 1 && path.resolve(storages[0]!.dir) === path.resolve(storage.dir);\n const [previousIndex, entityFileSets, memorySets, nativeChunks] = await Promise.all([\n shouldPersistIndex ? readEntityIndexState(storage) : Promise.resolve(null),\n Promise.all(storages.map((scopedStorage) => scopedStorage.readAllEntityFiles())),\n Promise.all(storages.map((scopedStorage) => scopedStorage.readAllMemories())),\n readNativeChunks(config, recallNamespaces),\n ]);\n // Pair each entity with the alias table of the store it came from (#1534):\n // canonical ids must reflect the owning store's aliases, never another\n // namespace's.\n const entityRecords = entityFileSets.flatMap((set, index) =>\n set.map((entity) => ({ entity, aliases: storages[index]!.entityAliases })),\n );\n const memories = memorySets.flat();\n\n const entities = new Map<string, EntityMentionIndexEntry>();\n for (const { entity, aliases } of entityRecords) {\n const canonicalId = normalizeEntityName(entity.name, entity.type, aliases);\n const rawStructuredSections = entity.structuredSections ?? [];\n const rawBeliefLedgerFactKeys = beliefLedgerFactKeys(rawStructuredSections);\n const sanitizedFacts = entity.facts\n .map((fact) => sanitizeEntityFact(fact))\n .filter(Boolean)\n .filter((fact) => !rawBeliefLedgerFactKeys.has(normalizeEntityText(fact)))\n .map((fact) => compactLine(fact, 180));\n const sanitizedTimelineFacts = entity.timeline\n .map((entry) => sanitizeEntityFact(entry.text))\n .filter(Boolean)\n .map((fact) => compactLine(fact, 180));\n entities.set(canonicalId, {\n canonicalId,\n name: entity.name,\n type: entity.type,\n aliases: uniqueStrings(entity.aliases),\n summary: entity.synthesis?.trim() || entity.summary?.trim() || undefined,\n facts: sanitizedFacts,\n timelineFacts: uniqueStrings(sanitizedTimelineFacts),\n structuredSections: rawStructuredSections.map((section) => ({\n key: section.key,\n title: section.title,\n facts: recallFactsForStructuredSection(section)\n .map((fact) => sanitizeEntityFact(fact))\n .filter(Boolean)\n .map((fact) => compactLine(fact, 180)),\n })).filter((section) => section.facts.length > 0),\n timeline: entity.timeline.map((entry) => ({ ...entry })),\n relationships: entity.relationships.map((relationship) => ({ ...relationship })),\n activity: entity.activity.map((activity) => ({ ...activity })),\n factCount: sanitizedFacts.length,\n memorySnippets: [],\n nativeChunks: [],\n });\n }\n\n for (const memory of memories) {\n const entityRef = typeof memory.frontmatter.entityRef === \"string\" ? memory.frontmatter.entityRef : \"\";\n if (!entityRef) continue;\n const entry = entities.get(entityRef);\n if (!entry) continue;\n const snippet = await readMemorySnippet(memory);\n if (!entry.memorySnippets.includes(snippet)) {\n entry.memorySnippets.push(snippet);\n }\n }\n\n const aliasIndex = buildAliasIndex([...entities.values()]);\n for (const chunk of nativeChunks) {\n const existingPseudo = entities.get(nativePseudoCanonicalId(chunk));\n if (existingPseudo) {\n mergeNativeChunk(existingPseudo, chunk);\n continue;\n }\n const candidateAliases = uniqueStrings([chunk.title, ...(chunk.aliases ?? [])]).map(normalizeEntityText).filter(Boolean);\n let matched = false;\n for (const alias of candidateAliases) {\n for (const entry of aliasIndex.get(alias) ?? []) {\n mergeNativeChunk(entry, chunk);\n matched = true;\n }\n }\n if (matched) continue;\n const pseudoEntry = createPseudoNativeEntry(chunk);\n entities.set(pseudoEntry.canonicalId, pseudoEntry);\n }\n\n const sortedEntities = [...entities.values()].sort((left, right) => left.name.localeCompare(right.name));\n const previousEntities = previousIndex ? JSON.stringify(previousIndex.entities) : \"\";\n const nextEntities = JSON.stringify(sortedEntities);\n const index: EntityMentionIndex = {\n version: ENTITY_INDEX_VERSION,\n updatedAt:\n previousIndex && previousEntities === nextEntities\n ? previousIndex.updatedAt\n : new Date().toISOString(),\n entities: sortedEntities,\n };\n if (shouldPersistIndex) {\n await writeEntityIndexState(storage, index);\n }\n return index;\n}\n\nfunction resolveExplicitCandidates(\n index: EntityMentionIndex,\n query: string,\n): EntityCandidate[] {\n const candidates: EntityCandidate[] = [];\n for (const entry of index.entities) {\n const aliases = uniqueStrings([entry.name, ...entry.aliases]);\n let bestAlias = \"\";\n let bestScore = 0;\n for (const alias of aliases) {\n const score = scoreAliasMatch(query, alias);\n if (score > bestScore) {\n bestAlias = alias;\n bestScore = score;\n }\n }\n if (bestScore <= 0) continue;\n candidates.push({ entry, alias: bestAlias, score: bestScore, source: \"query\" });\n }\n return candidates.sort((left, right) => right.score - left.score);\n}\n\nfunction resolveRecentTurnCandidates(\n index: EntityMentionIndex,\n transcriptEntries: TranscriptEntry[],\n recentTurns: number,\n): EntityCandidate[] {\n if (recentTurns <= 0 || transcriptEntries.length === 0) return [];\n const recentEntries = transcriptEntries.slice(-recentTurns);\n const candidates = new Map<string, EntityCandidate>();\n for (let indexOffset = recentEntries.length - 1; indexOffset >= 0; indexOffset -= 1) {\n const turn = recentEntries[indexOffset];\n const recencyBoost = recentEntries.length - indexOffset;\n const roleWeight = turn.role === \"user\" ? 2 : turn.role === \"assistant\" ? -1 : 0;\n for (const entry of index.entities) {\n const aliases = uniqueStrings([entry.name, ...entry.aliases]);\n for (const alias of aliases) {\n const score = scoreAliasMatch(turn.content, alias);\n if (score <= 0) continue;\n const current = candidates.get(entry.canonicalId);\n const weightedScore = score + Math.max(0, 6 - recencyBoost) + roleWeight;\n if (!current || weightedScore > current.score) {\n candidates.set(entry.canonicalId, {\n entry,\n alias,\n score: weightedScore,\n source: \"recent_turn\",\n });\n }\n }\n }\n }\n return [...candidates.values()].sort((left, right) => right.score - left.score);\n}\n\nasync function readMemorySnippet(memory: MemoryFile): Promise<string> {\n const content = memory.content.replace(/\\s+/g, \" \").trim();\n return compactLine(content, 180);\n}\n\nasync function buildHintSnippets(\n entry: EntityMentionIndexEntry,\n queryTokens: string[],\n mode: EntityQueryMode,\n maxSupportingFacts: number,\n requestedSectionKeys: Set<string>,\n): Promise<EntityHintSnippet[]> {\n const snippets: EntityHintSnippet[] = [];\n const aliasTokens = new Set(tokenize(uniqueStrings([entry.name, ...entry.aliases]).join(\" \")));\n if (entry.summary) {\n snippets.push({ text: compactLine(entry.summary, 180), score: 10, kind: \"summary\" });\n }\n\n if (requestedSectionKeys.size > 0) {\n for (const section of entry.structuredSections) {\n if (!requestedSectionKeys.has(normalizeEntityText(section.key).replace(/\\s+/g, \"_\"))) continue;\n for (const fact of section.facts) {\n snippets.push({ text: fact, score: mode === \"direct\" ? 8 : 9, kind: \"section\" });\n }\n }\n } else {\n for (const fact of entry.timelineFacts) {\n snippets.push({ text: fact, score: mode === \"direct\" ? 6 : 7, kind: \"fact\" });\n }\n for (const section of entry.structuredSections) {\n for (const fact of section.facts) {\n const normalizedFact = normalizeEntityText(fact);\n const hasNonAliasQueryOverlap = queryTokens.some((token) =>\n !aliasTokens.has(token) && normalizedFact.includes(token)\n );\n if (entry.timelineFacts.length > 0 && !hasNonAliasQueryOverlap) {\n continue;\n }\n snippets.push({ text: fact, score: mode === \"direct\" ? 6 : 7, kind: \"fact\" });\n }\n }\n if (entry.timelineFacts.length === 0 && entry.structuredSections.length === 0) {\n for (const fact of entry.facts) {\n if (!fact.trim()) continue;\n snippets.push({ text: fact, score: mode === \"direct\" ? 6 : 7, kind: \"fact\" });\n }\n }\n }\n\n if (requestedSectionKeys.size === 0) {\n for (const relationship of entry.relationships) {\n snippets.push({\n text: compactLine(relationLine(entry, relationship), 180),\n score: mode === \"direct\" && entry.type.toLowerCase() === \"person\" ? 6 : 4,\n kind: \"relationship\",\n });\n }\n\n for (const activity of entry.activity) {\n snippets.push({\n text: compactLine(`${activity.date}: ${activity.note}`, 180),\n score: 4,\n kind: \"activity\",\n });\n }\n\n for (const memorySnippet of entry.memorySnippets.slice(0, Math.min(maxSupportingFacts, 4))) {\n snippets.push({\n text: memorySnippet,\n score: 5,\n kind: \"memory\",\n });\n }\n\n for (const chunk of entry.nativeChunks) {\n snippets.push({\n text: compactLine(chunk.snippet, 180),\n score: 3,\n kind: \"native\",\n });\n }\n }\n\n const deduped = new Map<string, EntityHintSnippet>();\n for (const snippet of snippets) {\n const scored = scoreHintSnippet(snippet, queryTokens);\n if (!scored) continue;\n const normalized = normalizeEntityText(scored.text);\n const existing = deduped.get(normalized);\n if (!existing || scored.score > existing.score) deduped.set(normalized, scored);\n }\n\n return [...deduped.values()]\n .filter((snippet) => snippet.score > 0)\n .sort((left, right) => right.score - left.score)\n .slice(0, maxSupportingFacts);\n}\n\nfunction summarizeUncertainty(snippets: EntityHintSnippet[]): string | null {\n const direct = snippets.filter((snippet) =>\n snippet.kind === \"summary\"\n || snippet.kind === \"fact\"\n || snippet.kind === \"section\"\n || snippet.kind === \"memory\"\n );\n if (direct.length < 2) return null;\n for (let index = 0; index < direct.length; index += 1) {\n for (let compare = index + 1; compare < direct.length; compare += 1) {\n if (jaccardSimilarity(direct[index].text, direct[compare].text) < 0.2) {\n return \"Evidence is mixed across stored facts; treat the hints below as partial and verify before answering definitively.\";\n }\n }\n }\n return null;\n}\n\nfunction formatEntityHintSection(\n candidates: Array<{\n candidate: EntityCandidate;\n snippets: EntityHintSnippet[];\n uncertainty: string | null;\n }>,\n queryTokens: string[],\n mode: EntityQueryMode,\n maxRelatedEntities: number,\n maxChars: number,\n): string | null {\n if (candidates.length === 0) return null;\n const lines: string[] = [\"## entity_answer_hints\", \"\"];\n for (const { candidate, snippets, uncertainty } of candidates) {\n const hasSummary = Boolean(candidate.entry.summary?.trim());\n const preferredTopSnippets = hasSummary\n ? snippets.filter((snippet) => snippet.kind !== \"fact\")\n : snippets;\n let topSnippets = (\n preferredTopSnippets.length > 0 ? preferredTopSnippets : snippets\n ).slice(0, 3);\n const buildTimelineSnippets = (seedExcludedTexts: Set<string>): EntityHintSnippet[] => {\n const explicitTimelinePool = dedupeHintSnippetsByText(\n (candidate.entry.timeline ?? [])\n .slice()\n .sort(sortTimelineEntriesDesc)\n .map((entry) => sanitizeEntityFact(entry.text))\n .filter(Boolean)\n .map((text) => scoreHintSnippet({\n text: compactLine(text, 180),\n score: 7,\n kind: \"activity\" as const,\n }, queryTokens))\n .filter((snippet): snippet is EntityHintSnippet => snippet !== null)\n .filter((snippet) => !seedExcludedTexts.has(normalizeEntityText(snippet.text))),\n ).slice(0, 2);\n const activityTimelinePool = dedupeHintSnippetsByText(\n snippets\n .filter((snippet) => (\n snippet.kind === \"activity\" || snippet.kind === \"memory\"\n ) && !seedExcludedTexts.has(normalizeEntityText(snippet.text))),\n ).slice(0, 2);\n return explicitTimelinePool.length > 0\n ? explicitTimelinePool\n : activityTimelinePool.length > 0\n ? activityTimelinePool\n : dedupeHintSnippetsByText(\n snippets\n .filter((snippet) => (\n snippet.kind === \"fact\" || snippet.kind === \"summary\"\n ) && !seedExcludedTexts.has(normalizeEntityText(snippet.text))),\n ).slice(0, 2);\n };\n const baseTopSnippetTexts = new Set(topSnippets.map((snippet) => normalizeEntityText(snippet.text)));\n const timelinePool = mode !== \"direct\" ? buildTimelineSnippets(baseTopSnippetTexts) : [];\n if (mode !== \"direct\" && hasSummary && topSnippets.length < 2) {\n if (timelinePool.length > 0) {\n topSnippets = [...topSnippets, timelinePool[0]!].slice(0, 3);\n }\n }\n const topSnippetTexts = new Set(topSnippets.map((snippet) => normalizeEntityText(snippet.text)));\n lines.push(`- target: ${candidate.entry.name} (${candidate.entry.type})`);\n if (candidate.source === \"recent_turn\") {\n lines.push(`- resolution: carried forward from recent turns via alias \"${candidate.alias}\"`);\n } else {\n lines.push(`- resolution: matched alias \"${candidate.alias}\" in the query`);\n }\n if (uncertainty) lines.push(`- uncertainty: ${uncertainty}`);\n if (topSnippets.length > 0) {\n lines.push(\"- likely answer:\");\n for (const snippet of topSnippets) {\n lines.push(` - ${snippet.text}`);\n }\n }\n if (mode !== \"direct\") {\n const fallbackTimeline = timelinePool.filter(\n (snippet) => !topSnippetTexts.has(normalizeEntityText(snippet.text)),\n );\n if (fallbackTimeline.length > 0) {\n lines.push(\"- recent timeline:\");\n for (const snippet of fallbackTimeline) {\n lines.push(` - ${snippet.text}`);\n }\n }\n }\n const related = candidate.entry.relationships.slice(0, maxRelatedEntities).map((relationship) => relationship.target);\n if (related.length > 0) {\n lines.push(`- related entities: ${related.join(\", \")}`);\n }\n lines.push(`- support counts: facts=${candidate.entry.factCount}, memories=${candidate.entry.memorySnippets.length}, native=${candidate.entry.nativeChunks.length}`);\n lines.push(\"\");\n }\n\n let result = lines.join(\"\\n\");\n if (result.length > maxChars) {\n result = `${result.slice(0, Math.max(0, maxChars - 15)).trimEnd()}\\n\\n...(trimmed)\\n`;\n }\n return result.trim().length > 0 ? result.trimEnd() : null;\n}\n\nexport async function buildEntityRecallSection(options: BuildEntityRecallSectionOptions): Promise<string | null> {\n const mode = detectEntityQueryMode(options.query);\n if (!mode) return null;\n\n const index = await buildEntityMentionIndex(\n options.storage,\n options.config,\n options.recallNamespaces,\n options.namespaceStorage,\n );\n if (index.entities.length === 0) return null;\n\n const explicitCandidates = resolveExplicitCandidates(index, options.query);\n const candidates = explicitCandidates.length > 0\n ? explicitCandidates\n : resolveRecentTurnCandidates(index, options.transcriptEntries, options.recentTurns);\n\n if (candidates.length === 0) return null;\n\n const queryTokens = tokenize(options.query);\n const candidateLimit = explicitCandidates.length === 0 && mode === \"follow_up\"\n ? 1\n : options.maxHints;\n const rankedCandidates = candidates.slice(0, candidateLimit);\n const enriched = await Promise.all(\n rankedCandidates.map(async (candidate) => {\n const requestedSectionKeys = new Set(\n resolveRequestedEntitySectionKeys(\n options.query,\n candidate.entry.type,\n candidate.entry.structuredSections,\n options.config.entitySchemas,\n ),\n );\n const snippets = await buildHintSnippets(\n candidate.entry,\n queryTokens,\n mode,\n options.maxSupportingFacts,\n requestedSectionKeys,\n );\n return {\n candidate,\n snippets,\n uncertainty: summarizeUncertainty(snippets),\n };\n }),\n );\n\n const section = formatEntityHintSection(enriched, queryTokens, mode, options.maxRelatedEntities, options.maxChars);\n if (!section) return null;\n return section;\n}\n\nexport async function readRecentEntityTranscriptEntries(\n transcriptEntriesPromise: Promise<TranscriptEntry[]>,\n recentTurns: number,\n): Promise<TranscriptEntry[]> {\n if (recentTurns <= 0) return [];\n const transcriptEntries = await transcriptEntriesPromise.catch(() => []);\n if (transcriptEntries.length === 0) return [];\n return transcriptEntries.slice(-Math.max(1, recentTurns * 2));\n}\n\nexport const entityIndexVersion = ENTITY_INDEX_VERSION;\nexport const entityRecentTranscriptLookbackHours = RECENT_TRANSCRIPT_LOOKBACK_HOURS;\n"],"mappings":";;;;;;;;;;;;;;;;;;;AACA,SAAS,kBAAkB;AAE3B,SAAS,OAAO,UAAU,iBAAiB;AAC3C,OAAO,UAAU;AAMjB,IAAM,uBAAuB;AAC7B,IAAM,mCAAmC;AACzC,IAAM,sBAAsB;AAC5B,IAAM,sBAAsB;AAC5B,IAAM,oBAAoB;AAC1B,IAAM,4BAA4B;AAClC,IAAM,wBAAwB;AAmE9B,SAAS,SAAS,O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