@remnic/core 9.3.733 → 9.3.735

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.
Files changed (304) hide show
  1. package/dist/access-boundary.d.ts +13 -11
  2. package/dist/access-boundary.js +9 -9
  3. package/dist/access-cli.js +26 -24
  4. package/dist/access-cli.js.map +1 -1
  5. package/dist/access-http.d.ts +13 -11
  6. package/dist/access-http.js +14 -14
  7. package/dist/access-mcp.d.ts +13 -11
  8. package/dist/access-mcp.js +13 -13
  9. package/dist/access-operations-batch.js +11 -11
  10. package/dist/access-operations.d.ts +13 -11
  11. package/dist/access-operations.js +12 -12
  12. package/dist/access-schema.d.ts +4 -4
  13. package/dist/{access-service-Byoe3HsT.d.ts → access-service-CVx7mmvK.d.ts} +4 -4
  14. package/dist/access-service.d.ts +13 -11
  15. package/dist/access-service.js +8 -8
  16. package/dist/access-surface-catalog.d.ts +13 -11
  17. package/dist/action-confidence.d.ts +1 -1
  18. package/dist/active-memory-bridge.d.ts +1 -1
  19. package/dist/active-memory-bridge.js +3 -2
  20. package/dist/active-recall.d.ts +1 -1
  21. package/dist/behavior-learner.d.ts +1 -1
  22. package/dist/behavior-signals.d.ts +1 -1
  23. package/dist/bootstrap.d.ts +12 -10
  24. package/dist/briefing.d.ts +1 -1
  25. package/dist/buffer-surprise-report.d.ts +1 -1
  26. package/dist/buffer.d.ts +1 -1
  27. package/dist/calibration.d.ts +1 -1
  28. package/dist/capabilities.d.ts +196 -2
  29. package/dist/capabilities.js +21 -3
  30. package/dist/{catalog-DM1nk7cM.d.ts → catalog-BVhDEUhT.d.ts} +2 -2
  31. package/dist/causal-behavior.d.ts +1 -1
  32. package/dist/causal-consolidation.d.ts +1 -1
  33. package/dist/causal-trajectory-graph.d.ts +1 -1
  34. package/dist/{chunk-CX77GNMB.js → chunk-2T2N7ISV.js} +6 -3
  35. package/dist/chunk-2T2N7ISV.js.map +1 -0
  36. package/dist/{chunk-HHNSLPX7.js → chunk-5BOQNB2K.js} +10 -9
  37. package/dist/chunk-5BOQNB2K.js.map +1 -0
  38. package/dist/{chunk-QZHF4BWN.js → chunk-AAIHDIMD.js} +6 -6
  39. package/dist/{chunk-H3MB3F62.js → chunk-AB2E5DCN.js} +4 -3
  40. package/dist/chunk-AB2E5DCN.js.map +1 -0
  41. package/dist/{chunk-KSJCXXOU.js → chunk-AE7NTZ75.js} +6 -3
  42. package/dist/chunk-AE7NTZ75.js.map +1 -0
  43. package/dist/{chunk-OTQE66IX.js → chunk-AESC5OQJ.js} +6 -3
  44. package/dist/chunk-AESC5OQJ.js.map +1 -0
  45. package/dist/{chunk-FFUCCKPN.js → chunk-BXPG5AVX.js} +10 -7
  46. package/dist/chunk-BXPG5AVX.js.map +1 -0
  47. package/dist/{chunk-P3VJCTVE.js → chunk-CHJIWG2H.js} +4 -3
  48. package/dist/chunk-CHJIWG2H.js.map +1 -0
  49. package/dist/{chunk-FYWUNVFZ.js → chunk-E4LYJ7PY.js} +6 -6
  50. package/dist/{chunk-NIZQH6AU.js → chunk-FF36YNKY.js} +8 -7
  51. package/dist/chunk-FF36YNKY.js.map +1 -0
  52. package/dist/{chunk-OUITHS6V.js → chunk-FLCYY5JX.js} +801 -711
  53. package/dist/chunk-FLCYY5JX.js.map +1 -0
  54. package/dist/{chunk-PLBIPT6I.js → chunk-FLPKEMSO.js} +7 -4
  55. package/dist/chunk-FLPKEMSO.js.map +1 -0
  56. package/dist/{chunk-6TUWSUUD.js → chunk-G54IDCD3.js} +59 -53
  57. package/dist/chunk-G54IDCD3.js.map +1 -0
  58. package/dist/{chunk-J6BH2OBA.js → chunk-GB2FZOWB.js} +8 -5
  59. package/dist/chunk-GB2FZOWB.js.map +1 -0
  60. package/dist/{chunk-CGPHMNL4.js → chunk-GYICIICQ.js} +10 -6
  61. package/dist/chunk-GYICIICQ.js.map +1 -0
  62. package/dist/{chunk-DKT3X5C3.js → chunk-HFXZIF3V.js} +7 -4
  63. package/dist/chunk-HFXZIF3V.js.map +1 -0
  64. package/dist/{chunk-646B5ERJ.js → chunk-HLPYL6LC.js} +71 -65
  65. package/dist/chunk-HLPYL6LC.js.map +1 -0
  66. package/dist/{chunk-ZVHRSR2R.js → chunk-IPI45Q4S.js} +6 -3
  67. package/dist/chunk-IPI45Q4S.js.map +1 -0
  68. package/dist/{chunk-24D66MMN.js → chunk-IX4L7E5G.js} +7 -4
  69. package/dist/chunk-IX4L7E5G.js.map +1 -0
  70. package/dist/{chunk-SYX73XD7.js → chunk-IXGXALRV.js} +10 -7
  71. package/dist/chunk-IXGXALRV.js.map +1 -0
  72. package/dist/{chunk-ESF7TRYJ.js → chunk-JWDE7OVJ.js} +79 -2
  73. package/dist/chunk-JWDE7OVJ.js.map +1 -0
  74. package/dist/{chunk-GGL34GCW.js → chunk-K3Y2SJTN.js} +7 -4
  75. package/dist/chunk-K3Y2SJTN.js.map +1 -0
  76. package/dist/{chunk-PMAQRUN4.js → chunk-NDKW67ER.js} +5 -2
  77. package/dist/chunk-NDKW67ER.js.map +1 -0
  78. package/dist/{chunk-ZQUAVZNG.js → chunk-NNJKEAP2.js} +7 -4
  79. package/dist/chunk-NNJKEAP2.js.map +1 -0
  80. package/dist/{chunk-UZYLX7M6.js → chunk-OYHYBHHI.js} +9 -6
  81. package/dist/chunk-OYHYBHHI.js.map +1 -0
  82. package/dist/{chunk-NOU77OHX.js → chunk-P6VLG7KE.js} +2 -2
  83. package/dist/{chunk-O4ZIBPIW.js → chunk-QNTLWH3T.js} +3 -3
  84. package/dist/{chunk-LUCARK4W.js → chunk-UO6MPN77.js} +37 -35
  85. package/dist/chunk-UO6MPN77.js.map +1 -0
  86. package/dist/{chunk-HJWQJUKQ.js → chunk-VOEVVIP3.js} +3 -3
  87. package/dist/{chunk-KQYGNGON.js → chunk-ZBZ4XULO.js} +6 -3
  88. package/dist/chunk-ZBZ4XULO.js.map +1 -0
  89. package/dist/{cli-Dt-tuiYH.d.ts → cli-Cx5Mxwk7.d.ts} +3 -3
  90. package/dist/cli.d.ts +14 -12
  91. package/dist/cli.js +20 -20
  92. package/dist/compounding/engine.d.ts +3 -2
  93. package/dist/compounding/engine.js +2 -1
  94. package/dist/compounding/preference-consolidator.d.ts +1 -1
  95. package/dist/compression-optimizer.d.ts +1 -1
  96. package/dist/config.d.ts +1 -1
  97. package/dist/connectors/codex-materialize-runner.d.ts +1 -1
  98. package/dist/connectors/codex-materialize.d.ts +1 -1
  99. package/dist/connectors/index.d.ts +1 -1
  100. package/dist/consolidation-provenance-check.d.ts +1 -1
  101. package/dist/consolidation-undo.d.ts +1 -1
  102. package/dist/contradiction/index.d.ts +2 -2
  103. package/dist/contradiction/index.js +2 -1
  104. package/dist/{contradiction-scan-HWGEOUDS.js → contradiction-scan-2B4AE4TI.js} +3 -2
  105. package/dist/conversation-index/backend.d.ts +1 -1
  106. package/dist/conversation-index/chunker.d.ts +1 -1
  107. package/dist/conversation-index/faiss-adapter.d.ts +1 -1
  108. package/dist/conversation-index/indexer.d.ts +1 -1
  109. package/dist/conversation-index/search.d.ts +1 -1
  110. package/dist/day-summary.d.ts +1 -1
  111. package/dist/delinearize.d.ts +1 -1
  112. package/dist/direct-answer-wiring.d.ts +1 -1
  113. package/dist/direct-answer.d.ts +1 -1
  114. package/dist/embedding-fallback.d.ts +1 -1
  115. package/dist/embedding-fallback.js +2 -2
  116. package/dist/enrichment/index.d.ts +1 -1
  117. package/dist/entity-retrieval.d.ts +1 -1
  118. package/dist/entity-retrieval.js +2 -1
  119. package/dist/entity-schema.d.ts +1 -1
  120. package/dist/explicit-capture.d.ts +12 -10
  121. package/dist/explicit-capture.js +2 -1
  122. package/dist/extraction-faithfulness.d.ts +1 -1
  123. package/dist/extraction-judge-telemetry.d.ts +1 -1
  124. package/dist/extraction-judge-training.d.ts +1 -1
  125. package/dist/extraction-judge.d.ts +1 -1
  126. package/dist/extraction.d.ts +1 -1
  127. package/dist/extraction.js +3 -3
  128. package/dist/fallback-llm.d.ts +1 -1
  129. package/dist/{first-start-migration-OOR57AYR.js → first-start-migration-2RQYDIZ7.js} +10 -8
  130. package/dist/first-start-migration-2RQYDIZ7.js.map +1 -0
  131. package/dist/graph-dashboard-diff.d.ts +1 -1
  132. package/dist/graph-dashboard-key.d.ts +1 -1
  133. package/dist/graph-dashboard-parser.d.ts +1 -1
  134. package/dist/graph-edge-reinforcement.d.ts +1 -1
  135. package/dist/graph-snapshot.d.ts +1 -1
  136. package/dist/graph.d.ts +1 -1
  137. package/dist/identity-continuity.d.ts +1 -1
  138. package/dist/importance.d.ts +1 -1
  139. package/dist/index.d.ts +12 -12
  140. package/dist/index.js +44 -44
  141. package/dist/intent.d.ts +1 -1
  142. package/dist/lcm/engine.d.ts +1 -1
  143. package/dist/lcm/index.d.ts +1 -1
  144. package/dist/lcm/tools.d.ts +1 -1
  145. package/dist/lifecycle.d.ts +1 -1
  146. package/dist/live-connectors-runner.d.ts +1 -1
  147. package/dist/local-llm.d.ts +1 -1
  148. package/dist/local-llm.js +2 -1
  149. package/dist/local-model-endpoint.d.ts +1 -1
  150. package/dist/maintenance/memory-governance.d.ts +1 -1
  151. package/dist/mcp-memory-inspector-app.d.ts +13 -11
  152. package/dist/memory-action-policy.d.ts +1 -1
  153. package/dist/memory-cache.d.ts +1 -1
  154. package/dist/memory-lifecycle-ledger-utils.d.ts +1 -1
  155. package/dist/memory-projection-store.d.ts +1 -1
  156. package/dist/memory-provenance.d.ts +1 -1
  157. package/dist/memory-worth-outcomes.d.ts +1 -1
  158. package/dist/models-json.d.ts +1 -1
  159. package/dist/namespaces/migrate.d.ts +2 -2
  160. package/dist/namespaces/migrate.js +6 -6
  161. package/dist/namespaces/principal.d.ts +1 -1
  162. package/dist/namespaces/principal.js +2 -1
  163. package/dist/namespaces/search.d.ts +1 -1
  164. package/dist/namespaces/search.js +4 -4
  165. package/dist/namespaces/storage.d.ts +2 -2
  166. package/dist/namespaces/storage.js +2 -1
  167. package/dist/native-knowledge.d.ts +1 -1
  168. package/dist/operator-toolkit.d.ts +1 -1
  169. package/dist/operator-toolkit.js +11 -11
  170. package/dist/orchestration/compression-guideline-coordinator.d.ts +1 -1
  171. package/dist/orchestration/compression-guideline-coordinator.js +2 -1
  172. package/dist/orchestration/maintenance.d.ts +2 -2
  173. package/dist/orchestration/maintenance.js +6 -5
  174. package/dist/{orchestrator-B4KjaOtY.d.ts → orchestrator-oF0cceBX.d.ts} +143 -18
  175. package/dist/orchestrator.d.ts +8 -6
  176. package/dist/orchestrator.js +21 -19
  177. package/dist/patterns-cli.d.ts +1 -1
  178. package/dist/policy-runtime.d.ts +1 -1
  179. package/dist/provenance.d.ts +1 -1
  180. package/dist/qmd-recall-cache.d.ts +1 -1
  181. package/dist/qmd.d.ts +1 -1
  182. package/dist/recall-disclosure-escalation.d.ts +1 -1
  183. package/dist/recall-explain-renderer.d.ts +1 -1
  184. package/dist/recall-planner-llm.d.ts +1 -1
  185. package/dist/recall-state.d.ts +1 -1
  186. package/dist/recall-tag-filter.d.ts +1 -1
  187. package/dist/recall-xray-cli.d.ts +1 -1
  188. package/dist/recall-xray-renderer.d.ts +1 -1
  189. package/dist/recall-xray.d.ts +1 -1
  190. package/dist/resolve-auth-token.d.ts +1 -1
  191. package/dist/retrieval-agents.d.ts +1 -1
  192. package/dist/retrieval-tiers.d.ts +1 -1
  193. package/dist/routing/engine.d.ts +1 -1
  194. package/dist/routing/store.d.ts +1 -1
  195. package/dist/schemas.d.ts +2 -2
  196. package/dist/search/embed-helper.d.ts +1 -1
  197. package/dist/search/embed-helper.js +2 -2
  198. package/dist/search/factory.d.ts +1 -1
  199. package/dist/search/factory.js +3 -3
  200. package/dist/search/index.d.ts +1 -1
  201. package/dist/search/index.js +3 -3
  202. package/dist/search/lancedb-backend.d.ts +1 -1
  203. package/dist/search/meilisearch-backend.d.ts +1 -1
  204. package/dist/search/noop-backend.d.ts +1 -1
  205. package/dist/search/orama-backend.d.ts +1 -1
  206. package/dist/search/port.d.ts +1 -1
  207. package/dist/search/remote-backend.d.ts +1 -1
  208. package/dist/{semantic-SLAa_prH.d.ts → semantic-DJR8_DMQ.d.ts} +1 -1
  209. package/dist/{semantic-consolidation-CstTvHPo.d.ts → semantic-consolidation-DKGbufYO.d.ts} +1 -1
  210. package/dist/semantic-consolidation.d.ts +2 -2
  211. package/dist/semantic-rule-verifier.d.ts +1 -1
  212. package/dist/session-observer-bands.d.ts +1 -1
  213. package/dist/session-observer-state.d.ts +1 -1
  214. package/dist/shared-context/manager.d.ts +3 -3
  215. package/dist/signal.d.ts +1 -1
  216. package/dist/storage.d.ts +1 -1
  217. package/dist/summarizer.d.ts +1 -1
  218. package/dist/summarizer.js +3 -2
  219. package/dist/summary-snapshot.d.ts +1 -1
  220. package/dist/temporal-supersession.d.ts +1 -1
  221. package/dist/temporal-validity.d.ts +1 -1
  222. package/dist/threading.d.ts +1 -1
  223. package/dist/tier-migration.d.ts +1 -1
  224. package/dist/tier-routing.d.ts +1 -1
  225. package/dist/{tier-stats-3LYQ3VV5.js → tier-stats-KPDIISG7.js} +8 -4
  226. package/dist/tier-stats-KPDIISG7.js.map +1 -0
  227. package/dist/topics.d.ts +1 -1
  228. package/dist/transcript.d.ts +1 -1
  229. package/dist/transfer/types.d.ts +30 -30
  230. package/dist/trust-score-stage.d.ts +1 -1
  231. package/dist/trust-score.d.ts +1 -1
  232. package/dist/{types-VkxElCHR.d.ts → types-C7UCxpuO.d.ts} +1 -1
  233. package/dist/types.d.ts +1 -1
  234. package/dist/utility-runtime.d.ts +1 -1
  235. package/package.json +2 -2
  236. package/src/access-service.ts +61 -56
  237. package/src/active-memory-bridge.ts +2 -1
  238. package/src/admin/admin-surfaces.ts +2 -1
  239. package/src/capabilities.test.ts +375 -0
  240. package/src/capabilities.ts +403 -0
  241. package/src/cli/creation-ledger-commands.ts +2 -2
  242. package/src/cli/research-status-commands.ts +13 -13
  243. package/src/cli.ts +29 -25
  244. package/src/compounding/engine.ts +4 -3
  245. package/src/contradiction/contradiction-scan.ts +4 -3
  246. package/src/embedding-fallback.ts +5 -2
  247. package/src/entity-retrieval.ts +3 -2
  248. package/src/explicit-capture.ts +2 -1
  249. package/src/extraction.ts +6 -3
  250. package/src/local-llm.ts +4 -3
  251. package/src/maintenance/first-start-migration.ts +8 -5
  252. package/src/maintenance/namespace-maintenance-fanout.ts +2 -1
  253. package/src/maintenance/namespace-planner.ts +4 -3
  254. package/src/maintenance/tier-stats.ts +4 -3
  255. package/src/namespaces/catalog.ts +2 -1
  256. package/src/namespaces/migrate.ts +2 -1
  257. package/src/namespaces/principal.ts +6 -5
  258. package/src/namespaces/scope-profiles.ts +2 -1
  259. package/src/namespaces/search.ts +2 -1
  260. package/src/namespaces/storage.ts +4 -3
  261. package/src/operator-toolkit.ts +27 -26
  262. package/src/orchestration/compression-guideline-coordinator.ts +7 -6
  263. package/src/orchestration/lifecycle-policy-coordinator.ts +504 -0
  264. package/src/orchestration/maintenance.ts +8 -4
  265. package/src/orchestration/semantic-consolidation-coordinator.ts +454 -0
  266. package/src/orchestration/tier-migration-coordinator.ts +5 -4
  267. package/src/orchestrator.ts +106 -800
  268. package/src/scopes/scope-plan.ts +3 -2
  269. package/src/search/embed-helper.ts +5 -2
  270. package/src/search/factory.ts +9 -6
  271. package/src/summarizer.ts +3 -2
  272. package/dist/chunk-24D66MMN.js.map +0 -1
  273. package/dist/chunk-646B5ERJ.js.map +0 -1
  274. package/dist/chunk-6TUWSUUD.js.map +0 -1
  275. package/dist/chunk-CGPHMNL4.js.map +0 -1
  276. package/dist/chunk-CX77GNMB.js.map +0 -1
  277. package/dist/chunk-DKT3X5C3.js.map +0 -1
  278. package/dist/chunk-ESF7TRYJ.js.map +0 -1
  279. package/dist/chunk-FFUCCKPN.js.map +0 -1
  280. package/dist/chunk-GGL34GCW.js.map +0 -1
  281. package/dist/chunk-H3MB3F62.js.map +0 -1
  282. package/dist/chunk-HHNSLPX7.js.map +0 -1
  283. package/dist/chunk-J6BH2OBA.js.map +0 -1
  284. package/dist/chunk-KQYGNGON.js.map +0 -1
  285. package/dist/chunk-KSJCXXOU.js.map +0 -1
  286. package/dist/chunk-LUCARK4W.js.map +0 -1
  287. package/dist/chunk-NIZQH6AU.js.map +0 -1
  288. package/dist/chunk-OTQE66IX.js.map +0 -1
  289. package/dist/chunk-OUITHS6V.js.map +0 -1
  290. package/dist/chunk-P3VJCTVE.js.map +0 -1
  291. package/dist/chunk-PLBIPT6I.js.map +0 -1
  292. package/dist/chunk-PMAQRUN4.js.map +0 -1
  293. package/dist/chunk-SYX73XD7.js.map +0 -1
  294. package/dist/chunk-UZYLX7M6.js.map +0 -1
  295. package/dist/chunk-ZQUAVZNG.js.map +0 -1
  296. package/dist/chunk-ZVHRSR2R.js.map +0 -1
  297. package/dist/first-start-migration-OOR57AYR.js.map +0 -1
  298. package/dist/tier-stats-3LYQ3VV5.js.map +0 -1
  299. /package/dist/{chunk-QZHF4BWN.js.map → chunk-AAIHDIMD.js.map} +0 -0
  300. /package/dist/{chunk-FYWUNVFZ.js.map → chunk-E4LYJ7PY.js.map} +0 -0
  301. /package/dist/{chunk-NOU77OHX.js.map → chunk-P6VLG7KE.js.map} +0 -0
  302. /package/dist/{chunk-O4ZIBPIW.js.map → chunk-QNTLWH3T.js.map} +0 -0
  303. /package/dist/{chunk-HJWQJUKQ.js.map → chunk-VOEVVIP3.js.map} +0 -0
  304. /package/dist/{contradiction-scan-HWGEOUDS.js.map → contradiction-scan-2B4AE4TI.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/orchestration/compression-guideline-coordinator.ts"],"sourcesContent":["/**\n * Compression-guideline learning coordinator — extracted from the\n * orchestrator (issue #1526, seam 4).\n *\n * Owns the compression-guideline learning lifecycle:\n * - candidate computation from recorded memory-action events\n * - optional LLM semantic refinement of the candidate\n * - draft persistence + activation (optimizer/draft state files)\n * - the recall section that surfaces active guidelines during recall\n * - the consolidation-time learning pass that recomputes the draft\n *\n * The orchestrator constructs one instance and delegates the public\n * entrypoints (`optimizeCompressionGuidelines`,\n * `activateCompressionGuidelineDraft`) plus the two internal hooks\n * (`runCompressionGuidelineLearningPass`, called from the consolidation\n * loop; `buildCompressionGuidelineRecallSection`, called from the recall\n * pipeline) to it. Storage is the orchestrator's stable `this.storage`;\n * the fast-tier LLM call arrives as a callback so gateway routing stays\n * owned by the orchestrator.\n *\n * Behavior-preserving move from orchestrator.ts. No logic changes — the\n * orchestrator keeps thin delegating methods so existing call sites and\n * tests that exercise the public API continue to work.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { resolveCompressionCapabilities } from \"../capabilities.js\";\n\n// StorageManager type comes from the package barrel (type-only) so this\n// module does not add a direct storage.ts import (#1533 ratchet).\nimport type { StorageManager } from \"../index.js\";\nimport type { PluginConfig, MemoryActionType, MemoryActionEvent } from \"../types.js\";\nimport { log } from \"../logger.js\";\nimport {\n computeCompressionGuidelineCandidate,\n refineCompressionGuidelineCandidateSemantically,\n renderCompressionGuidelinesMarkdown,\n} from \"../compression-optimizer.js\";\n\n/** Dependencies injected by the orchestrator. All stable references or\n * live accessors. */\nexport interface CompressionGuidelineCoordinatorDeps {\n config: PluginConfig;\n /** Live accessor: the orchestrator's storage manager (stable post-ctor). */\n getStorage: () => StorageManager;\n /** Fast-tier LLM call used for optional semantic refinement. Routes\n * through the gateway chain when configured — owned by the\n * orchestrator, injected here so this module stays LLM-agnostic. */\n fastChatCompletion: (\n messages: Array<{ role: string; content: string }>,\n options: {\n temperature?: number;\n maxTokens?: number;\n timeoutMs?: number;\n operation?: string;\n priority?: \"background\" | \"recall-critical\";\n },\n ) => Promise<{ content: string } | null>;\n}\n\n/**\n * Coordinates compression-guideline learning. Holds no mutable state of\n * its own — all persistence flows through the injected storage manager.\n */\nexport class CompressionGuidelineCoordinator {\n constructor(private readonly deps: CompressionGuidelineCoordinatorDeps) {}\n\n private get storage(): StorageManager {\n return this.deps.getStorage();\n }\n\n private get config(): PluginConfig {\n return this.deps.config;\n }\n\n async optimizeCompressionGuidelines(options?: {\n dryRun?: boolean;\n eventLimit?: number;\n }): Promise<{\n enabled: boolean;\n dryRun: boolean;\n eventCount: number;\n previousGuidelineVersion: number | null;\n nextGuidelineVersion: number;\n changedRules: number;\n semanticRefinementApplied: boolean;\n persisted: boolean;\n draftContentHash: string | null;\n }> {\n const dryRun = options?.dryRun === true;\n const eventLimit =\n typeof options?.eventLimit === \"number\"\n ? Math.max(0, Math.floor(options.eventLimit))\n : 500;\n\n const [activeState, draftState] = await Promise.all([\n this.storage.readCompressionGuidelineOptimizerState(),\n this.storage.readCompressionGuidelineDraftState().catch(() => null),\n ]);\n const previousState =\n draftState &&\n ((activeState?.guidelineVersion ?? 0) < draftState.guidelineVersion ||\n (activeState?.guidelineVersion ?? 0) === draftState.guidelineVersion)\n ? draftState\n : activeState;\n\n if (!resolveCompressionCapabilities(this.config).compressionGuidelineLearning) {\n return {\n enabled: false,\n dryRun,\n eventCount: 0,\n previousGuidelineVersion: previousState?.guidelineVersion ?? null,\n nextGuidelineVersion: previousState?.guidelineVersion ?? 0,\n changedRules: 0,\n semanticRefinementApplied: false,\n persisted: false,\n draftContentHash: null,\n };\n }\n\n let events = await this.storage.readMemoryActionEvents(eventLimit);\n if (eventLimit > 0) {\n let effectiveEvents = events.filter((event) => event.dryRun !== true);\n let fetchLimit = eventLimit;\n while (\n effectiveEvents.length < eventLimit &&\n events.length === fetchLimit\n ) {\n fetchLimit = Math.min(fetchLimit * 2, fetchLimit + 1000);\n if (fetchLimit <= events.length) break;\n events = await this.storage.readMemoryActionEvents(fetchLimit);\n effectiveEvents = events.filter((event) => event.dryRun !== true);\n }\n events = effectiveEvents.slice(-eventLimit);\n }\n const generatedAt = new Date().toISOString();\n const candidate = computeCompressionGuidelineCandidate(events, {\n generatedAtIso: generatedAt,\n previousState,\n });\n if (candidate.eventCounts.total === 0) {\n return {\n enabled: true,\n dryRun,\n eventCount: 0,\n previousGuidelineVersion: previousState?.guidelineVersion ?? null,\n nextGuidelineVersion: previousState?.guidelineVersion ?? 0,\n changedRules: 0,\n semanticRefinementApplied: false,\n persisted: false,\n draftContentHash: null,\n };\n }\n const refinedCandidate =\n await refineCompressionGuidelineCandidateSemantically(candidate, {\n enabled: resolveCompressionCapabilities(this.config).compressionGuidelineSemanticRefinement,\n timeoutMs: this.config.compressionGuidelineSemanticTimeoutMs,\n runRefinement: async (baseline) => {\n const prompt = [\n \"You refine compression policy suggestions conservatively.\",\n \"Return JSON only in this shape:\",\n '{\"updates\":[{\"action\":\"summarize_node\",\"delta\":0.02,\"confidence\":\"medium\",\"note\":\"...\"}]}',\n \"Constraints:\",\n \"- Keep updates sparse and conservative.\",\n \"- delta must stay between -0.15 and 0.15.\",\n \"- Only include actions present in the input.\",\n \"Input candidate:\",\n JSON.stringify(baseline),\n ].join(\"\\n\");\n\n const response = await this.deps.fastChatCompletion(\n [\n {\n role: \"system\",\n content: \"Respond with strict JSON only. No markdown.\",\n },\n { role: \"user\", content: prompt },\n ],\n {\n temperature: 0.1,\n maxTokens: 400,\n operation: \"compression_guideline_semantic_refinement\",\n priority: \"background\",\n },\n );\n\n return this.parseCompressionSemanticRefinement(\n response?.content ?? \"\",\n );\n },\n });\n\n const content = renderCompressionGuidelinesMarkdown(refinedCandidate);\n const contentHash = createHash(\"sha256\").update(content).digest(\"hex\");\n const semanticRefinementApplied =\n JSON.stringify(refinedCandidate.ruleUpdates) !==\n JSON.stringify(candidate.ruleUpdates);\n const changedRules = refinedCandidate.ruleUpdates.filter(\n (rule) => rule.delta !== 0,\n ).length;\n\n if (!dryRun) {\n await this.storage.writeCompressionGuidelineDraft(content);\n await this.storage.writeCompressionGuidelineDraftState({\n version: refinedCandidate.optimizerVersion,\n updatedAt: refinedCandidate.generatedAt,\n sourceWindow: refinedCandidate.sourceWindow,\n eventCounts: refinedCandidate.eventCounts,\n guidelineVersion: refinedCandidate.guidelineVersion,\n contentHash,\n activationState: \"draft\",\n actionSummaries: refinedCandidate.actionSummaries,\n ruleUpdates: refinedCandidate.ruleUpdates,\n });\n }\n\n return {\n enabled: true,\n dryRun,\n eventCount: candidate.eventCounts.total,\n previousGuidelineVersion: previousState?.guidelineVersion ?? null,\n nextGuidelineVersion: refinedCandidate.guidelineVersion,\n changedRules,\n semanticRefinementApplied,\n persisted: !dryRun,\n draftContentHash: dryRun ? null : contentHash,\n };\n }\n\n async activateCompressionGuidelineDraft(options?: {\n expectedContentHash?: string;\n expectedGuidelineVersion?: number;\n }): Promise<{\n enabled: boolean;\n activated: boolean;\n guidelineVersion: number | null;\n reason?:\n | \"disabled\"\n | \"missing_draft\"\n | \"expected_revision_required\"\n | \"content_hash_mismatch\"\n | \"guideline_version_mismatch\"\n | \"draft_changed\";\n }> {\n if (!resolveCompressionCapabilities(this.config).compressionGuidelineLearning) {\n return {\n enabled: false,\n activated: false,\n guidelineVersion: null,\n reason: \"disabled\",\n };\n }\n\n const draftState = await this.storage.readCompressionGuidelineDraftState();\n if (!draftState) {\n return {\n enabled: true,\n activated: false,\n guidelineVersion: null,\n reason: \"missing_draft\",\n };\n }\n\n const expectedContentHash = options?.expectedContentHash?.trim();\n const expectedGuidelineVersion = options?.expectedGuidelineVersion;\n\n if (\n (!expectedContentHash || expectedContentHash.length === 0) &&\n typeof expectedGuidelineVersion !== \"number\"\n ) {\n return {\n enabled: true,\n activated: false,\n guidelineVersion: null,\n reason: \"expected_revision_required\",\n };\n }\n\n if (expectedContentHash && draftState.contentHash !== expectedContentHash) {\n return {\n enabled: true,\n activated: false,\n guidelineVersion: null,\n reason: \"content_hash_mismatch\",\n };\n }\n\n if (\n typeof expectedGuidelineVersion === \"number\" &&\n draftState.guidelineVersion !== expectedGuidelineVersion\n ) {\n return {\n enabled: true,\n activated: false,\n guidelineVersion: null,\n reason: \"guideline_version_mismatch\",\n };\n }\n\n const activated = await this.storage.activateCompressionGuidelineDraft({\n ...(expectedContentHash ? { expectedContentHash } : {}),\n ...(typeof expectedGuidelineVersion === \"number\"\n ? { expectedGuidelineVersion }\n : {}),\n });\n return {\n enabled: true,\n activated,\n guidelineVersion: activated ? draftState.guidelineVersion : null,\n ...(activated ? {} : { reason: \"draft_changed\" as const }),\n };\n }\n\n /** Consolidation-time hook: recompute the draft from recent events. */\n async runCompressionGuidelineLearningPass(): Promise<void> {\n if (!resolveCompressionCapabilities(this.config).compressionGuidelineLearning) return;\n try {\n const result = await this.optimizeCompressionGuidelines({\n dryRun: false,\n eventLimit: 500,\n });\n log.info(\n `compression guideline learning updated (${result.eventCount} events)`,\n );\n } catch (err) {\n log.warn(`compression guideline learning failed (ignored): ${err}`);\n }\n }\n\n /** Recall-time hook: surface active guidelines as a recall section. */\n async buildCompressionGuidelineRecallSection(): Promise<string | null> {\n if (!resolveCompressionCapabilities(this.config).contextCompressionActions) return null;\n if (!resolveCompressionCapabilities(this.config).compressionGuidelineLearning) return null;\n\n const state = await this.storage\n .readCompressionGuidelineOptimizerState()\n .catch(() => null);\n if (!state || state.guidelineVersion <= 0) return null;\n\n const raw = await this.storage\n .readCompressionGuidelines()\n .catch(() => null);\n const summary = raw ? formatCompressionGuidelinesForRecall(raw, 5) : null;\n if (!summary) return null;\n\n return [\n \"## Active Compression Guidelines\",\n \"\",\n `Guideline version: ${state.guidelineVersion}`,\n `Updated: ${state.updatedAt}`,\n \"\",\n summary,\n ].join(\"\\n\");\n }\n\n private parseCompressionSemanticRefinement(raw: string): {\n updates: Array<{\n action: MemoryActionType;\n delta?: number;\n confidence?: \"low\" | \"medium\" | \"high\";\n note?: string;\n }>;\n } | null {\n if (typeof raw !== \"string\" || raw.trim().length === 0) return null;\n const trimmed = raw.trim();\n const start = trimmed.indexOf(\"{\");\n const end = trimmed.lastIndexOf(\"}\");\n if (start === -1 || end === -1 || end <= start) return null;\n\n try {\n const parsed = JSON.parse(trimmed.slice(start, end + 1)) as {\n updates?: Array<{\n action?: unknown;\n delta?: unknown;\n confidence?: unknown;\n note?: unknown;\n }>;\n };\n if (!Array.isArray(parsed?.updates)) return null;\n\n const validActions = new Set<MemoryActionType>([\n \"store_episode\",\n \"store_note\",\n \"update_note\",\n \"create_artifact\",\n \"summarize_node\",\n \"discard\",\n \"link_graph\",\n ]);\n\n const updates = parsed.updates\n .filter(\n (item) =>\n item &&\n typeof item.action === \"string\" &&\n validActions.has(item.action as MemoryActionType),\n )\n .map((item) => {\n const confidence: \"low\" | \"medium\" | \"high\" | undefined =\n item.confidence === \"low\" ||\n item.confidence === \"medium\" ||\n item.confidence === \"high\"\n ? item.confidence\n : undefined;\n return {\n action: item.action as MemoryActionType,\n delta:\n typeof item.delta === \"number\" && Number.isFinite(item.delta)\n ? item.delta\n : undefined,\n confidence,\n note: typeof item.note === \"string\" ? item.note : undefined,\n };\n });\n\n return { updates };\n } catch {\n return null;\n }\n }\n}\n\n/**\n * Format the active compression-guidelines section for recall. Extracted\n * from the orchestrator (was a module-level export there); re-exported by\n * the orchestrator barrel to preserve the public API. Pure — no state.\n */\nexport function formatCompressionGuidelinesForRecall(\n raw: string,\n maxLines: number = 5,\n): string | null {\n if (typeof raw !== \"string\" || raw.trim().length === 0) return null;\n const sectionMatch = raw.match(\n // End the section at `\\n## ` or end-of-string. Plain $ (not \\s*$): the\n // \\s* branch overlapped the lazy body and backtracked polynomially\n // (CodeQL js/polynomial-redos). Captured lines are trimmed/filtered below,\n // so trailing whitespace handling is unchanged.\n /## Suggested Guidelines\\s*\\n([\\s\\S]*?)(?:\\n##\\s+|$)/i,\n );\n if (!sectionMatch) return null;\n\n const lines = sectionMatch[1]\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.startsWith(\"- \"))\n .slice(0, Math.max(1, Math.floor(maxLines)));\n if (lines.length === 0) return null;\n\n return lines.join(\"\\n\");\n}\n"],"mappings":";;;;;;;;;;;;;AAyBA,SAAS,kBAAkB;AAuCpB,IAAM,kCAAN,MAAsC;AAAA,EAC3C,YAA6B,MAA2C;AAA3C;AAAA,EAA4C;AAAA,EAA5C;AAAA,EAE7B,IAAY,UAA0B;AACpC,WAAO,KAAK,KAAK,WAAW;AAAA,EAC9B;AAAA,EAEA,IAAY,SAAuB;AACjC,WAAO,KAAK,KAAK;AAAA,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;AAAA,MACF,CAAC;AAEH,aAAO,EAAE,QAAQ;AAAA,IACnB,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAOO,SAAS,qCACd,KACA,WAAmB,GACJ;AACf,MAAI,OAAO,QAAQ,YAAY,IAAI,KAAK,EAAE,WAAW,EAAG,QAAO;AAC/D,QAAM,eAAe,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA,IAKvB;AAAA,EACF;AACA,MAAI,CAAC,aAAc,QAAO;AAE1B,QAAM,QAAQ,aAAa,CAAC,EACzB,MAAM,IAAI,EACV,IAAI,CAAC,SAAS,KAAK,KAAK,CAAC,EACzB,OAAO,CAAC,SAAS,KAAK,WAAW,IAAI,CAAC,EACtC,MAAM,GAAG,KAAK,IAAI,GAAG,KAAK,MAAM,QAAQ,CAAC,CAAC;AAC7C,MAAI,MAAM,WAAW,EAAG,QAAO;AAE/B,SAAO,MAAM,KAAK,IAAI;AACxB;","names":[]}
@@ -70,6 +70,74 @@ function resolveCreationMemoryCapabilities(config) {
70
70
  commitmentLifecycle: config.commitmentLifecycleEnabled
71
71
  });
72
72
  }
73
+ function resolveNamespaceCapabilities(config) {
74
+ return Object.freeze({
75
+ namespaces: config.namespacesEnabled
76
+ });
77
+ }
78
+ function resolveQmdCapabilities(config) {
79
+ return Object.freeze({
80
+ qmd: config.qmdEnabled,
81
+ qmdTierMigration: config.qmdTierMigrationEnabled,
82
+ qmdTierAutoBackfill: config.qmdTierAutoBackfillEnabled,
83
+ qmdAutoEmbed: config.qmdAutoEmbedEnabled,
84
+ qmdMaintenance: config.qmdMaintenanceEnabled,
85
+ qmdColdTier: config.qmdColdTierEnabled === true,
86
+ qmdDaemon: config.qmdDaemonEnabled,
87
+ qmdTierParityGraph: config.qmdTierParityGraphEnabled,
88
+ qmdQueryRerank: config.qmdQueryRerankEnabled,
89
+ qmdIntentHints: config.qmdIntentHintsEnabled,
90
+ qmdExplain: config.qmdExplainEnabled,
91
+ qmdAutoUpgrade: config.qmdAutoUpgradeEnabled
92
+ });
93
+ }
94
+ function resolveIdentityContinuityCapabilities(config) {
95
+ return Object.freeze({
96
+ identityContinuity: config.identityContinuityEnabled
97
+ });
98
+ }
99
+ function resolveLocalLlmCapabilities(config) {
100
+ return Object.freeze({
101
+ localLlm: config.localLlmEnabled
102
+ });
103
+ }
104
+ function resolveSecurityCapabilities(config) {
105
+ return Object.freeze({
106
+ trustZones: config.trustZonesEnabled,
107
+ quarantinePromotion: config.quarantinePromotionEnabled,
108
+ memoryPoisoningDefense: config.memoryPoisoningDefenseEnabled,
109
+ trustZoneRecall: config.trustZoneRecallEnabled
110
+ });
111
+ }
112
+ function resolveEvalCapabilities(config) {
113
+ return Object.freeze({
114
+ evalHarness: config.evalHarnessEnabled,
115
+ evalShadowMode: config.evalShadowModeEnabled,
116
+ benchmarkBaselineSnapshots: config.benchmarkBaselineSnapshotsEnabled,
117
+ benchmarkDeltaReporter: config.benchmarkDeltaReporterEnabled,
118
+ memoryRedTeamBench: config.memoryRedTeamBenchEnabled
119
+ });
120
+ }
121
+ function resolveUtilityLearningCapabilities(config) {
122
+ return Object.freeze({
123
+ memoryUtilityLearning: config.memoryUtilityLearningEnabled,
124
+ promotionByOutcome: config.promotionByOutcomeEnabled
125
+ });
126
+ }
127
+ function resolveObjectiveStateCapabilities(config) {
128
+ return Object.freeze({
129
+ objectiveStateMemory: config.objectiveStateMemoryEnabled,
130
+ objectiveStateSnapshotWrites: config.objectiveStateSnapshotWritesEnabled,
131
+ objectiveStateRecall: config.objectiveStateRecallEnabled
132
+ });
133
+ }
134
+ function resolveCompressionCapabilities(config) {
135
+ return Object.freeze({
136
+ compressionGuidelineLearning: config.compressionGuidelineLearningEnabled,
137
+ compressionGuidelineSemanticRefinement: config.compressionGuidelineSemanticRefinementEnabled,
138
+ contextCompressionActions: config.contextCompressionActionsEnabled
139
+ });
140
+ }
73
141
 
74
142
  export {
75
143
  resolveCapabilities,
@@ -77,6 +145,15 @@ export {
77
145
  resolveAccessSetupCapabilities,
78
146
  resolveMemoryLifecycleCapabilities,
79
147
  resolveIndexingCapabilities,
80
- resolveCreationMemoryCapabilities
148
+ resolveCreationMemoryCapabilities,
149
+ resolveNamespaceCapabilities,
150
+ resolveQmdCapabilities,
151
+ resolveIdentityContinuityCapabilities,
152
+ resolveLocalLlmCapabilities,
153
+ resolveSecurityCapabilities,
154
+ resolveEvalCapabilities,
155
+ resolveUtilityLearningCapabilities,
156
+ resolveObjectiveStateCapabilities,
157
+ resolveCompressionCapabilities
81
158
  };
82
- //# sourceMappingURL=chunk-ESF7TRYJ.js.map
159
+ //# sourceMappingURL=chunk-JWDE7OVJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/capabilities.ts"],"sourcesContent":["/**\n * CapabilitySet — recall-operation feature gates resolved once, then threaded.\n *\n * Issue #1523 (Phase 1 of epic #1520). Root cause this addresses: 161+\n * scattered `config.<flag>Enabled` reads mean each gate is re-derived at every\n * call site, and reviews keep finding parallel code paths where one branch\n * checks a gate the other forgot (CLAUDE.md rule 39 — the \"gate divergence\"\n * defect class). The fix is to resolve a frozen capability projection ONCE at\n * the top of the recall operation and pass it down explicitly.\n *\n * Scope of THIS module (first migration PR): only the recall-operation-scoped\n * flags below. Flags that are also read in graph construction, writes, CLI, or\n * the summarizer are deliberately deferred to a follow-up so we never leave a\n * single flag half-migrated (some sites on `caps.`, some on `config.`).\n *\n * Field naming: each field is the config flag name with the trailing `Enabled`\n * removed (`recallMmrEnabled` → `recallMmr`).\n *\n * This is plumbing, not a feature — there is deliberately NO `enabled` gate for\n * the CapabilitySet itself (rule 30 governs behavior changes; resolving and\n * threading a capability projection must stay behavior-preserving).\n */\n\nimport type { PluginConfig } from \"./types.js\";\n\n/**\n * Frozen projection of recall-operation feature gates.\n *\n * Every field is `readonly boolean`. The composition that maps a config flag to\n * a capability (including default-when-undefined semantics for optional flags)\n * lives ONLY in {@link resolveCapabilities} — call sites must read the\n * capability, never re-derive it from raw config.\n */\nexport interface CapabilitySet {\n /** `rerankCacheEnabled` — cache reranker scores across recall passes. */\n readonly rerankCache: boolean;\n /** `recallDirectAnswerEnabled` — observation-mode direct-answer tier. */\n readonly recallDirectAnswer: boolean;\n /** `recallMemoryWorthFilterEnabled` — Memory-Worth score reweighting. */\n readonly recallMemoryWorthFilter: boolean;\n /** `trustScoreEnabled` — unified TrustScore recall stage (issue #1577). */\n readonly recallTrustScore: boolean;\n /** `recallMmrEnabled` — maximal-marginal-relevance diversification. */\n readonly recallMmr: boolean;\n /** `recallReasoningTraceBoostEnabled` — boost reasoning-trace memories. */\n readonly recallReasoningTraceBoost: boolean;\n /** `recallPlannerLlmEnabled` — LLM-backed recall-mode planner. */\n readonly recallPlannerLlm: boolean;\n /** `recallPlannerEnabled` — recall-mode planner (heuristic + optional LLM). */\n readonly recallPlanner: boolean;\n /** `recallConfidenceGateEnabled` — Synapse-style confidence gate. */\n readonly recallConfidenceGate: boolean;\n /** `graphRecallEnabled` — graph-mode recall tier (gates planner graph mode). */\n readonly graphRecall: boolean;\n /** `graphAssistInFullModeEnabled` — graph-assist overlay in full mode. */\n readonly graphAssistInFullMode: boolean;\n /** `graphExpandedIntentEnabled` — promote broad-intent asks to graph mode. */\n readonly graphExpandedIntent: boolean;\n // --- Issue #1566 Cluster C: mixed-operation flags (recall + summarizer/CLI/writes) ---\n /** `rerankEnabled` — optional LLM reranking of recall candidates. */\n readonly rerank: boolean;\n /** `harmonicRetrievalEnabled` — abstraction-node harmonic retrieval tier. */\n readonly harmonicRetrieval: boolean;\n /** `parallelRetrievalEnabled` — three-agent parallel retrieval (DirectFact + Contextual + Temporal). */\n readonly parallelRetrieval: boolean;\n}\n\n/**\n * Resolve the recall-operation {@link CapabilitySet} from parsed config.\n *\n * Call this ONCE per recall operation (at the `recall()` / `recallInternal`\n * entry) and thread the result down. Composition lives here and only here.\n *\n * Session toggles are intentionally not a parameter yet: `session-toggles.ts`\n * is agent-scoped (per session/agent enable-disable of the whole plugin), not\n * flag-scoped — none of the flags projected here have a per-session override,\n * so there is nothing for a toggle argument to compose at this layer.\n */\nexport function resolveCapabilities(config: PluginConfig): CapabilitySet {\n return Object.freeze({\n rerankCache: config.rerankCacheEnabled,\n recallDirectAnswer: config.recallDirectAnswerEnabled,\n recallMemoryWorthFilter: config.recallMemoryWorthFilterEnabled,\n // Issue #1577: TrustScore subsumes the Memory Worth multiplier when on;\n // the orchestrator runs exactly one of the two (mutual exclusion, rule 39).\n recallTrustScore: config.trustScoreEnabled === true,\n recallMmr: config.recallMmrEnabled,\n recallReasoningTraceBoost: config.recallReasoningTraceBoostEnabled,\n recallPlannerLlm: config.recallPlannerLlmEnabled,\n recallPlanner: config.recallPlannerEnabled,\n recallConfidenceGate: config.recallConfidenceGateEnabled,\n graphRecall: config.graphRecallEnabled,\n // Optional flags: preserve the exact default-when-undefined semantics the\n // migrated call sites used (`!== false` = default-on, `=== true` = default-off).\n graphAssistInFullMode: config.graphAssistInFullModeEnabled !== false,\n graphExpandedIntent: config.graphExpandedIntentEnabled === true,\n // Issue #1566 Cluster C: mixed-operation flags resolved once per recall op.\n rerank: config.rerankEnabled,\n harmonicRetrieval: config.harmonicRetrievalEnabled,\n parallelRetrieval: config.parallelRetrievalEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Graph-construction capability set (issue #1566 Cluster A).\n//\n// The recall CapabilitySet above covers flags whose EVERY read site lives on\n// the recall call chain. The five flags below are read on graph-construction,\n// write/extraction, AND recall paths — so they cannot join the recall set\n// without leaving some sites on `caps.` and others on `config.` (the exact\n// divergence #1523 forbade). They get their own projection, resolved at graph\n// build/write entry (and alongside `caps` when recall reads them).\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of graph-construction feature gates.\n *\n * Every field is `readonly boolean`. Composition (including default-when-\n * undefined semantics for the optional `graphWriteSessionAdjacencyEnabled`)\n * lives ONLY in {@link resolveGraphConstructionCapabilities}.\n */\nexport interface GraphConstructionCapabilitySet {\n /** `entityGraphEnabled` — maintain entity co-reference graph edges. */\n readonly entityGraph: boolean;\n /** `timeGraphEnabled` — maintain thread-adjacency graph edges. */\n readonly timeGraph: boolean;\n /** `causalGraphEnabled` — maintain causal-language graph edges. */\n readonly causalGraph: boolean;\n /** `multiGraphMemoryEnabled` — master switch for multi-graph writes/traversal. */\n readonly multiGraphMemory: boolean;\n /** `graphWriteSessionAdjacencyEnabled` — session-adjacency fallback for time edges (default-on). */\n readonly graphWriteSessionAdjacency: boolean;\n}\n\n/**\n * Resolve the {@link GraphConstructionCapabilitySet} from parsed config.\n *\n * Call this ONCE at graph build/write entry (extraction, recall graph\n * expansion, graph-health/repair) and thread the result down — exactly the\n * pattern {@link resolveCapabilities} established for recall.\n */\nexport type GraphConstructionConfigProjection = Pick<\n PluginConfig,\n | \"entityGraphEnabled\"\n | \"timeGraphEnabled\"\n | \"causalGraphEnabled\"\n | \"multiGraphMemoryEnabled\"\n | \"graphWriteSessionAdjacencyEnabled\"\n>;\n\nexport function resolveGraphConstructionCapabilities(\n config: GraphConstructionConfigProjection,\n): GraphConstructionCapabilitySet {\n return Object.freeze({\n entityGraph: config.entityGraphEnabled,\n timeGraph: config.timeGraphEnabled,\n causalGraph: config.causalGraphEnabled,\n multiGraphMemory: config.multiGraphMemoryEnabled,\n // Optional flag: preserve the exact default-when-undefined semantics the\n // migrated call site used (`!== false` = default-on).\n graphWriteSessionAdjacency: config.graphWriteSessionAdjacencyEnabled !== false,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Access-setup capability set (issue #1566 Cluster B).\n//\n// These two flags gate cross-namespace recall budgeting and anomaly-detection\n// auditing. Resolved once at access-service handler entry (and the operator\n// doctor check) rather than re-derived from raw config at each site.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of access-setup feature gates (issue #1566 Cluster B).\n *\n * Every field is `readonly boolean`. Composition (including the default-off\n * semantics for the optional `recallAuditAnomalyDetectionEnabled`) lives ONLY\n * in {@link resolveAccessSetupCapabilities}.\n */\nexport interface AccessSetupCapabilitySet {\n /** `recallCrossNamespaceBudgetEnabled` — rolling cross-namespace recall budget. */\n readonly recallCrossNamespaceBudget: boolean;\n /** `recallAuditAnomalyDetectionEnabled` — access-audit anomaly detection (default-off). */\n readonly recallAuditAnomalyDetection: boolean;\n}\n\n/**\n * Resolve the {@link AccessSetupCapabilitySet} from parsed config.\n *\n * Call this ONCE at access-service handler entry and thread the result down.\n */\nexport type AccessSetupConfigProjection = Pick<\n PluginConfig,\n \"recallCrossNamespaceBudgetEnabled\" | \"recallAuditAnomalyDetectionEnabled\"\n>;\n\nexport function resolveAccessSetupCapabilities(\n config: AccessSetupConfigProjection,\n): AccessSetupCapabilitySet {\n return Object.freeze({\n recallCrossNamespaceBudget: config.recallCrossNamespaceBudgetEnabled,\n // Optional/default-off flag: preserve `=== true` semantics.\n recallAuditAnomalyDetection: config.recallAuditAnomalyDetectionEnabled === true,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Memory-lifecycle capability set (issue #1523 batch 3).\n//\n// The flags below gate memory WRITE/EXTRACTION (extraction judge, scope\n// classification, dedupe, telemetry prefilter), temporal supersession of\n// stored facts, and the lifecycle policy pass (promotion / decay / stale\n// filtering). They are read on the persistExtraction write path, the recall\n// candidate-filter path, and the maintenance / lifecycle-pass path — so, like\n// the graph-construction set above, they get their own projection resolved\n// ONCE at each operation entry that reads them (never re-derived from raw\n// config mid-operation — the gate-divergence defect class #1523 targets).\n//\n// Every field projects from an already-resolved PluginConfig boolean (defaults\n// are applied at the config-parse boundary, rule 36), so the resolver is a\n// pure projection — no `!== false` / `=== true` re-coercion here.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of memory-lifecycle feature gates (issue #1523 batch 3).\n *\n * Resolved once per write / recall-filter / maintenance operation and threaded\n * down. Composition lives ONLY in {@link resolveMemoryLifecycleCapabilities}.\n */\nexport interface MemoryLifecycleCapabilitySet {\n /** `temporalSupersessionEnabled` — supersede stale structured facts on write, filter on recall. */\n readonly temporalSupersession: boolean;\n /** `temporalMemoryTreeEnabled` — temporal-memory-tree build + recall tier. */\n readonly temporalMemoryTree: boolean;\n /** `lifecyclePolicyEnabled` — lifecycle promotion / decay metadata pass. */\n readonly lifecyclePolicy: boolean;\n /** `lifecycleFilterStaleEnabled` — filter stale-lifecycle memories from recall. */\n readonly lifecycleFilterStale: boolean;\n /** `lifecycleMetricsEnabled` — emit lifecycle-pass metrics. */\n readonly lifecycleMetrics: boolean;\n /** `extractionScopeClassificationEnabled` — LLM classifies each fact's scope. */\n readonly extractionScopeClassification: boolean;\n /** `extractionJudgeEnabled` — LLM-as-judge fact-worthiness gate. */\n readonly extractionJudge: boolean;\n /** `extractionDedupeEnabled` — dedupe against recent extractions. */\n readonly extractionDedupe: boolean;\n /** `extractionTelemetryPrefilterEnabled` — skip mechanical-telemetry transcripts. */\n readonly extractionTelemetryPrefilter: boolean;\n /** `extractionJudgeTelemetryEnabled` — collect judge verdict telemetry. */\n readonly extractionJudgeTelemetry: boolean;\n /** `embeddingFallbackEnabled` — semantic-dedup / archive-search embedding fallback. */\n readonly embeddingFallback: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveMemoryLifecycleCapabilities}.\n */\nexport type MemoryLifecycleConfigProjection = Pick<\n PluginConfig,\n | \"temporalSupersessionEnabled\"\n | \"temporalMemoryTreeEnabled\"\n | \"lifecyclePolicyEnabled\"\n | \"lifecycleFilterStaleEnabled\"\n | \"lifecycleMetricsEnabled\"\n | \"extractionScopeClassificationEnabled\"\n | \"extractionJudgeEnabled\"\n | \"extractionDedupeEnabled\"\n | \"extractionTelemetryPrefilterEnabled\"\n | \"extractionJudgeTelemetryEnabled\"\n | \"embeddingFallbackEnabled\"\n>;\n\n/**\n * Resolve the {@link MemoryLifecycleCapabilitySet} from parsed config.\n *\n * Call this ONCE per write / recall-filter / maintenance operation entry and\n * thread the result down — exactly the pattern {@link resolveCapabilities}\n * established for recall.\n */\nexport function resolveMemoryLifecycleCapabilities(\n config: MemoryLifecycleConfigProjection,\n): MemoryLifecycleCapabilitySet {\n return Object.freeze({\n temporalSupersession: config.temporalSupersessionEnabled,\n temporalMemoryTree: config.temporalMemoryTreeEnabled,\n lifecyclePolicy: config.lifecyclePolicyEnabled,\n lifecycleFilterStale: config.lifecycleFilterStaleEnabled,\n lifecycleMetrics: config.lifecycleMetricsEnabled,\n extractionScopeClassification: config.extractionScopeClassificationEnabled,\n extractionJudge: config.extractionJudgeEnabled,\n extractionDedupe: config.extractionDedupeEnabled,\n extractionTelemetryPrefilter: config.extractionTelemetryPrefilterEnabled,\n extractionJudgeTelemetry: config.extractionJudgeTelemetryEnabled,\n embeddingFallback: config.embeddingFallbackEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Indexing capability set (issue #1523 batch 4).\n//\n// The flags below gate query-aware indexing (temporal/tag index build +\n// prefilter) and the conversation index (QMD/FAISS backend selection). They\n// are read on the recall path, the extraction/persist path, and the\n// maintenance/invalidation path — so they get their own projection resolved\n// ONCE at each operation entry that reads them.\n//\n// Every field projects from an already-resolved PluginConfig boolean (defaults\n// applied at the parse boundary), so the resolver is a pure projection.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of indexing feature gates (issue #1523 batch 4).\n *\n * Resolved once per recall / extraction / maintenance operation and threaded\n * down. Composition lives ONLY in {@link resolveIndexingCapabilities}.\n */\nexport interface IndexingCapabilitySet {\n /** `queryAwareIndexingEnabled` — build + use temporal/tag index for recall prefilter. */\n readonly queryAwareIndexing: boolean;\n /** `conversationIndexEnabled` — conversation-index backend (QMD / FAISS). */\n readonly conversationIndex: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveIndexingCapabilities}.\n */\nexport type IndexingConfigProjection = Pick<\n PluginConfig,\n \"queryAwareIndexingEnabled\" | \"conversationIndexEnabled\"\n>;\n\n/**\n * Resolve the {@link IndexingCapabilitySet} from parsed config.\n *\n * Call this ONCE per recall / extraction / maintenance operation entry and\n * thread the result down — exactly the pattern {@link resolveCapabilities}\n * established for recall.\n */\nexport function resolveIndexingCapabilities(\n config: IndexingConfigProjection,\n): IndexingCapabilitySet {\n return Object.freeze({\n queryAwareIndexing: config.queryAwareIndexingEnabled,\n conversationIndex: config.conversationIndexEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Creation-memory capability set (issue #1523 batch 4).\n//\n// The flags below gate the creation-memory subsystem: resume-bundle handoff,\n// commitment ledger, commitment lifecycle, and the master creation-memory\n// switch. They are read on the extraction/persist path, the recall\n// enrichment path, and the CLI command surface — so they get their own\n// projection resolved ONCE at each operation entry that reads them.\n//\n// Every field projects from an already-resolved PluginConfig boolean (defaults\n// applied at the parse boundary), so the resolver is a pure projection.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of creation-memory feature gates (issue #1523 batch 4).\n *\n * Resolved once per creation-memory operation (CLI command, extraction,\n * recall enrichment) and threaded down. Composition lives ONLY in\n * {@link resolveCreationMemoryCapabilities}.\n */\nexport interface CreationMemoryCapabilitySet {\n /** `creationMemoryEnabled` — master switch for creation-memory subsystem. */\n readonly creationMemory: boolean;\n /** `commitmentLedgerEnabled` — commitment-ledger read/write. */\n readonly commitmentLedger: boolean;\n /** `resumeBundlesEnabled` — resume-bundle handoff bundles. */\n readonly resumeBundles: boolean;\n /** `commitmentLifecycleEnabled` — commitment lifecycle (promotion / decay). */\n readonly commitmentLifecycle: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveCreationMemoryCapabilities}.\n */\nexport type CreationMemoryConfigProjection = Pick<\n PluginConfig,\n | \"creationMemoryEnabled\"\n | \"commitmentLedgerEnabled\"\n | \"resumeBundlesEnabled\"\n | \"commitmentLifecycleEnabled\"\n>;\n\n/**\n * Resolve the {@link CreationMemoryCapabilitySet} from parsed config.\n *\n * Call this ONCE per creation-memory operation entry and thread the result\n * down — exactly the pattern {@link resolveCapabilities} established for\n * recall.\n */\nexport function resolveCreationMemoryCapabilities(\n config: CreationMemoryConfigProjection,\n): CreationMemoryCapabilitySet {\n return Object.freeze({\n creationMemory: config.creationMemoryEnabled,\n commitmentLedger: config.commitmentLedgerEnabled,\n resumeBundles: config.resumeBundlesEnabled,\n commitmentLifecycle: config.commitmentLifecycleEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Namespace capability set (issue #1523 batch 5).\n//\n// `namespacesEnabled` is the single most-scattered config flag in the codebase\n// (101 read sites outside config.ts across 18 files — orchestrator, access-service,\n// namespace modules, maintenance, CLI, admin). It gates whether the multi-namespace\n// system is active at all: every namespace resolution, storage path, recall budget,\n// and maintenance fanout checks it. Like the other projections above it gets its own\n// resolver invoked ONCE per operation entry rather than re-derived at each site.\n//\n// The field is a non-optional boolean in PluginConfig, so no coercion is needed.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of namespace feature gates (issue #1523 batch 5).\n *\n * Every field is `readonly boolean`. Composition lives ONLY in\n * {@link resolveNamespaceCapabilities}.\n */\nexport interface NamespaceCapabilitySet {\n /** `namespacesEnabled` — multi-namespace system master switch. */\n readonly namespaces: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveNamespaceCapabilities}.\n */\nexport type NamespaceConfigProjection = Pick<PluginConfig, \"namespacesEnabled\">;\n\n/**\n * Resolve the {@link NamespaceCapabilitySet} from parsed config.\n *\n * Call this ONCE at operation entry and thread the result down. The flag is a\n * non-optional boolean so the projection is a pure pass-through.\n */\nexport function resolveNamespaceCapabilities(\n config: NamespaceConfigProjection,\n): NamespaceCapabilitySet {\n return Object.freeze({\n namespaces: config.namespacesEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// QMD capability set (issue #1523 batch 6).\n//\n// The twelve QMD (query-managed database) flags are the largest remaining\n// scattered cluster after batch 5. They gate every aspect of the tiered\n// memory system: master switch, tier migration, cold tier, daemon, auto-embed,\n// maintenance, query rerank, intent hints, explain, auto-upgrade, and parity\n// graph. Read sites span orchestrator, operator-toolkit, access-service, and\n// search/factory. All flags are non-optional booleans on PluginConfig (defaults\n// resolved at the parse boundary), so the projection is pure pass-through.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of QMD feature gates (issue #1523 batch 6).\n *\n * Every field is `readonly boolean`. Composition lives ONLY in\n * {@link resolveQmdCapabilities}.\n */\nexport interface QmdCapabilitySet {\n /** `qmdEnabled` — QMD tiered-memory master switch. */\n readonly qmd: boolean;\n /** `qmdTierMigrationEnabled` — automatic tier promotion/demotion. */\n readonly qmdTierMigration: boolean;\n /** `qmdTierAutoBackfillEnabled` — backfill stale tier entries. */\n readonly qmdTierAutoBackfill: boolean;\n /** `qmdAutoEmbedEnabled` — auto-embed documents on write. */\n readonly qmdAutoEmbed: boolean;\n /** `qmdMaintenanceEnabled` — QMD maintenance pass runner. */\n readonly qmdMaintenance: boolean;\n /** `qmdColdTierEnabled` — cold-tier storage. */\n readonly qmdColdTier: boolean;\n /** `qmdDaemonEnabled` — background QMD daemon. */\n readonly qmdDaemon: boolean;\n /** `qmdTierParityGraphEnabled` — tier parity graph. */\n readonly qmdTierParityGraph: boolean;\n /** `qmdQueryRerankEnabled` — QMD query reranking. */\n readonly qmdQueryRerank: boolean;\n /** `qmdIntentHintsEnabled` — QMD intent hint extraction. */\n readonly qmdIntentHints: boolean;\n /** `qmdExplainEnabled` — QMD explain output. */\n readonly qmdExplain: boolean;\n /** `qmdAutoUpgradeEnabled` — QMD auto-upgrade tiers. */\n readonly qmdAutoUpgrade: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveQmdCapabilities}.\n */\nexport type QmdConfigProjection = Pick<\n PluginConfig,\n | \"qmdEnabled\"\n | \"qmdTierMigrationEnabled\"\n | \"qmdTierAutoBackfillEnabled\"\n | \"qmdAutoEmbedEnabled\"\n | \"qmdMaintenanceEnabled\"\n | \"qmdColdTierEnabled\"\n | \"qmdDaemonEnabled\"\n | \"qmdTierParityGraphEnabled\"\n | \"qmdQueryRerankEnabled\"\n | \"qmdIntentHintsEnabled\"\n | \"qmdExplainEnabled\"\n | \"qmdAutoUpgradeEnabled\"\n>;\n\n/**\n * Resolve the {@link QmdCapabilitySet} from parsed config.\n *\n * Call this ONCE at operation entry and thread the result down. Eleven flags\n * are non-optional booleans (pure pass-through); `qmdColdTierEnabled` is\n * optional and coerced with `=== true` (matching the pre-migration call sites).\n */\nexport function resolveQmdCapabilities(config: QmdConfigProjection): QmdCapabilitySet {\n return Object.freeze({\n qmd: config.qmdEnabled,\n qmdTierMigration: config.qmdTierMigrationEnabled,\n qmdTierAutoBackfill: config.qmdTierAutoBackfillEnabled,\n qmdAutoEmbed: config.qmdAutoEmbedEnabled,\n qmdMaintenance: config.qmdMaintenanceEnabled,\n qmdColdTier: config.qmdColdTierEnabled === true,\n qmdDaemon: config.qmdDaemonEnabled,\n qmdTierParityGraph: config.qmdTierParityGraphEnabled,\n qmdQueryRerank: config.qmdQueryRerankEnabled,\n qmdIntentHints: config.qmdIntentHintsEnabled,\n qmdExplain: config.qmdExplainEnabled,\n qmdAutoUpgrade: config.qmdAutoUpgradeEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Identity-continuity capability set (issue #1523 batch 6).\n//\n// `identityContinuityEnabled` gates the identity/continuity system (agent\n// identity tracking, continuity incident logging). Its 13 read sites span\n// orchestrator, access-service, and CLI. The flag is a non-optional boolean\n// on PluginConfig, so the projection is a pure pass-through.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of identity-continuity feature gates (issue #1523 batch 6).\n */\nexport interface IdentityContinuityCapabilitySet {\n /** `identityContinuityEnabled` — identity-continuity master switch. */\n readonly identityContinuity: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveIdentityContinuityCapabilities}.\n */\nexport type IdentityContinuityConfigProjection = Pick<PluginConfig, \"identityContinuityEnabled\">;\n\n/**\n * Resolve the {@link IdentityContinuityCapabilitySet} from parsed config.\n */\nexport function resolveIdentityContinuityCapabilities(\n config: IdentityContinuityConfigProjection,\n): IdentityContinuityCapabilitySet {\n return Object.freeze({\n identityContinuity: config.identityContinuityEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Local-LLM capability set (issue #1523 batch 6).\n//\n// `localLlmEnabled` gates whether a local (on-device) LLM is used for\n// summarization, embedding fallback, extraction, and search. Its 11 read\n// sites span orchestrator, extraction, embedding-fallback, local-llm,\n// search/embed-helper, and summarizer. The flag is a non-optional boolean.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of local-LLM feature gates (issue #1523 batch 6).\n */\nexport interface LocalLlmCapabilitySet {\n /** `localLlmEnabled` — local (on-device) LLM master switch. */\n readonly localLlm: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveLocalLlmCapabilities}.\n */\nexport type LocalLlmConfigProjection = Pick<PluginConfig, \"localLlmEnabled\">;\n\n/**\n * Resolve the {@link LocalLlmCapabilitySet} from parsed config.\n */\nexport function resolveLocalLlmCapabilities(\n config: LocalLlmConfigProjection,\n): LocalLlmCapabilitySet {\n return Object.freeze({\n localLlm: config.localLlmEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Security capability set (issue #1523 batch 7).\n//\n// The four security/trust-zone flags gate quarantine promotion, poisoning\n// defense, and trust-zone recall. Read sites span orchestrator, access-service,\n// CLI, and research-status commands. All flags are non-optional booleans on\n// PluginConfig (defaults resolved at the parse boundary), so the projection is\n// a pure pass-through.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of security/trust-zone feature gates (issue #1523 batch 7).\n */\nexport interface SecurityCapabilitySet {\n /** `trustZonesEnabled` — master switch for trust-zone enforcement. */\n readonly trustZones: boolean;\n /** `quarantinePromotionEnabled` — promote quarantined memories after review. */\n readonly quarantinePromotion: boolean;\n /** `memoryPoisoningDefenseEnabled` — detect and defend against memory poisoning. */\n readonly memoryPoisoningDefense: boolean;\n /** `trustZoneRecallEnabled` — restrict recall to trusted zones. */\n readonly trustZoneRecall: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveSecurityCapabilities}.\n */\nexport type SecurityConfigProjection = Pick<\n PluginConfig,\n \"trustZonesEnabled\" | \"quarantinePromotionEnabled\" | \"memoryPoisoningDefenseEnabled\" | \"trustZoneRecallEnabled\"\n>;\n\n/**\n * Resolve the {@link SecurityCapabilitySet} from parsed config.\n */\nexport function resolveSecurityCapabilities(config: SecurityConfigProjection): SecurityCapabilitySet {\n return Object.freeze({\n trustZones: config.trustZonesEnabled,\n quarantinePromotion: config.quarantinePromotionEnabled,\n memoryPoisoningDefense: config.memoryPoisoningDefenseEnabled,\n trustZoneRecall: config.trustZoneRecallEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Eval/benchmark capability set (issue #1523 batch 7).\n//\n// The five eval/benchmark flags gate the evaluation harness, shadow mode,\n// baseline snapshot management, delta reporting, and red-team benchmarking.\n// Read sites span orchestrator, CLI, and operator-toolkit. All flags are\n// non-optional booleans on PluginConfig.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of eval/benchmark feature gates (issue #1523 batch 7).\n */\nexport interface EvalCapabilitySet {\n /** `evalHarnessEnabled` — master switch for the eval harness. */\n readonly evalHarness: boolean;\n /** `evalShadowModeEnabled` — run evaluations in shadow mode. */\n readonly evalShadowMode: boolean;\n /** `benchmarkBaselineSnapshotsEnabled` — manage baseline snapshots. */\n readonly benchmarkBaselineSnapshots: boolean;\n /** `benchmarkDeltaReporterEnabled` — report benchmark deltas. */\n readonly benchmarkDeltaReporter: boolean;\n /** `memoryRedTeamBenchEnabled` — red-team benchmarking of memory. */\n readonly memoryRedTeamBench: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveEvalCapabilities}.\n */\nexport type EvalConfigProjection = Pick<\n PluginConfig,\n \"evalHarnessEnabled\" | \"evalShadowModeEnabled\" | \"benchmarkBaselineSnapshotsEnabled\" | \"benchmarkDeltaReporterEnabled\" | \"memoryRedTeamBenchEnabled\"\n>;\n\n/**\n * Resolve the {@link EvalCapabilitySet} from parsed config.\n */\nexport function resolveEvalCapabilities(config: EvalConfigProjection): EvalCapabilitySet {\n return Object.freeze({\n evalHarness: config.evalHarnessEnabled,\n evalShadowMode: config.evalShadowModeEnabled,\n benchmarkBaselineSnapshots: config.benchmarkBaselineSnapshotsEnabled,\n benchmarkDeltaReporter: config.benchmarkDeltaReporterEnabled,\n memoryRedTeamBench: config.memoryRedTeamBenchEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Utility-learning capability set (issue #1523 batch 7).\n//\n// The two utility-learning flags gate memory utility learning and\n// promotion-by-outcome. Read sites span orchestrator, CLI research-status\n// commands, and maintenance files. Both flags are non-optional booleans.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of utility-learning feature gates (issue #1523 batch 7).\n */\nexport interface UtilityLearningCapabilitySet {\n /** `memoryUtilityLearningEnabled` — learn memory utility weights from outcomes. */\n readonly memoryUtilityLearning: boolean;\n /** `promotionByOutcomeEnabled` — promote memories by outcome tracking. */\n readonly promotionByOutcome: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveUtilityLearningCapabilities}.\n */\nexport type UtilityLearningConfigProjection = Pick<\n PluginConfig,\n \"memoryUtilityLearningEnabled\" | \"promotionByOutcomeEnabled\"\n>;\n\n/**\n * Resolve the {@link UtilityLearningCapabilitySet} from parsed config.\n */\nexport function resolveUtilityLearningCapabilities(config: UtilityLearningConfigProjection): UtilityLearningCapabilitySet {\n return Object.freeze({\n memoryUtilityLearning: config.memoryUtilityLearningEnabled,\n promotionByOutcome: config.promotionByOutcomeEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Objective-state capability set (issue #1523 batch 7).\n//\n// The three objective-state flags gate objective-state memory, snapshot\n// writes, and recall. Read sites span orchestrator, access-service, CLI\n// creation-ledger commands, and research-status commands. All flags are\n// non-optional booleans.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of objective-state feature gates (issue #1523 batch 7).\n */\nexport interface ObjectiveStateCapabilitySet {\n /** `objectiveStateMemoryEnabled` — store objective-state memories. */\n readonly objectiveStateMemory: boolean;\n /** `objectiveStateSnapshotWritesEnabled` — write objective-state snapshots. */\n readonly objectiveStateSnapshotWrites: boolean;\n /** `objectiveStateRecallEnabled` — recall objective-state memories. */\n readonly objectiveStateRecall: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveObjectiveStateCapabilities}.\n */\nexport type ObjectiveStateConfigProjection = Pick<\n PluginConfig,\n \"objectiveStateMemoryEnabled\" | \"objectiveStateSnapshotWritesEnabled\" | \"objectiveStateRecallEnabled\"\n>;\n\n/**\n * Resolve the {@link ObjectiveStateCapabilitySet} from parsed config.\n */\nexport function resolveObjectiveStateCapabilities(config: ObjectiveStateConfigProjection): ObjectiveStateCapabilitySet {\n return Object.freeze({\n objectiveStateMemory: config.objectiveStateMemoryEnabled,\n objectiveStateSnapshotWrites: config.objectiveStateSnapshotWritesEnabled,\n objectiveStateRecall: config.objectiveStateRecallEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Compression capability set (issue #1523 batch 7).\n//\n// The three compression flags gate guideline learning, semantic refinement,\n// and context-compression actions. Read sites span orchestrator,\n// access-service, and the compression-guideline coordinator. All flags are\n// non-optional booleans.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of compression feature gates (issue #1523 batch 7).\n */\nexport interface CompressionCapabilitySet {\n /** `compressionGuidelineLearningEnabled` — learn compression guidelines. */\n readonly compressionGuidelineLearning: boolean;\n /** `compressionGuidelineSemanticRefinementEnabled` — semantically refine guidelines. */\n readonly compressionGuidelineSemanticRefinement: boolean;\n /** `contextCompressionActionsEnabled` — apply context-compression actions. */\n readonly contextCompressionActions: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveCompressionCapabilities}.\n */\nexport type CompressionConfigProjection = Pick<\n PluginConfig,\n \"compressionGuidelineLearningEnabled\" | \"compressionGuidelineSemanticRefinementEnabled\" | \"contextCompressionActionsEnabled\"\n>;\n\n/**\n * Resolve the {@link CompressionCapabilitySet} from parsed config.\n */\nexport function resolveCompressionCapabilities(config: CompressionConfigProjection): CompressionCapabilitySet {\n return Object.freeze({\n compressionGuidelineLearning: config.compressionGuidelineLearningEnabled,\n compressionGuidelineSemanticRefinement: config.compressionGuidelineSemanticRefinementEnab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AO;AAAA,EAC1B,CAAC;AACH;AAsCO,SAAS,wBAAwB,QAAiD;AACvF,SAAO,OAAO,OAAO;AAAA,IACnB,aAAa,OAAO;AAAA,IACpB,gBAAgB,OAAO;AAAA,IACvB,4BAA4B,OAAO;AAAA,IACnC,wBAAwB,OAAO;AAAA,IAC/B,oBAAoB,OAAO;AAAA,EAC7B,CAAC;AACH;AA+BO,SAAS,mCAAmC,QAAuE;AACxH,SAAO,OAAO,OAAO;AAAA,IACnB,uBAAuB,OAAO;AAAA,IAC9B,oBAAoB,OAAO;AAAA,EAC7B,CAAC;AACH;AAkCO,SAAS,kCAAkC,QAAqE;AACrH,SAAO,OAAO,OAAO;AAAA,IACnB,sBAAsB,OAAO;AAAA,IAC7B,8BAA8B,OAAO;AAAA,IACrC,sBAAsB,OAAO;AAAA,EAC/B,CAAC;AACH;AAkCO,SAAS,+BAA+B,QAA+D;AAC5G,SAAO,OAAO,OAAO;AAAA,IACnB,8BAA8B,OAAO;AAAA,IACrC,wCAAwC,OAAO;AAAA,IAC/C,2BAA2B,OAAO;AAAA,EACpC,CAAC;AACH;","names":[]}
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  NamespaceStorageRouter
3
- } from "./chunk-ZQUAVZNG.js";
3
+ } from "./chunk-NNJKEAP2.js";
4
4
  import {
5
5
  namespaceCollectionName
6
- } from "./chunk-KQYGNGON.js";
6
+ } from "./chunk-ZBZ4XULO.js";
7
7
  import {
8
8
  namespaceIdentityFromToken,
9
9
  namespaceIdentityToken
@@ -11,6 +11,9 @@ import {
11
11
  import {
12
12
  ALL_CATEGORY_DIRS
13
13
  } from "./chunk-VS2IYZRU.js";
14
+ import {
15
+ resolveNamespaceCapabilities
16
+ } from "./chunk-JWDE7OVJ.js";
14
17
  import {
15
18
  isSafeRouteNamespace
16
19
  } from "./chunk-U3PN77QT.js";
@@ -100,7 +103,7 @@ async function verifyNamespaces(options) {
100
103
  };
101
104
  }
102
105
  async function runNamespaceMigration(options) {
103
- if (!options.config.namespacesEnabled) {
106
+ if (!resolveNamespaceCapabilities(options.config).namespaces) {
104
107
  throw new Error("Namespaces are disabled.");
105
108
  }
106
109
  const targetNamespace = options.to.trim();
@@ -204,4 +207,4 @@ export {
204
207
  verifyNamespaces,
205
208
  runNamespaceMigration
206
209
  };
207
- //# sourceMappingURL=chunk-GGL34GCW.js.map
210
+ //# sourceMappingURL=chunk-K3Y2SJTN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/namespaces/migrate.ts"],"sourcesContent":["import { resolveNamespaceCapabilities } from \"../capabilities.js\";\nimport path from \"node:path\";\nimport { access, lstat, mkdir, readdir, realpath, rename, rmdir } from \"node:fs/promises\";\nimport type { PluginConfig } from \"../types.js\";\nimport { NamespaceStorageRouter } from \"./storage.js\";\nimport { namespaceCollectionName } from \"./search.js\";\nimport { isSafeRouteNamespace } from \"../routing/engine.js\";\nimport { namespaceIdentityFromToken, namespaceIdentityToken } from \"./identity.js\";\nimport { ALL_CATEGORY_DIRS } from \"../utils/category-dir.js\";\n\nconst LEGACY_NAMESPACE_CHILDREN = [\n ...ALL_CATEGORY_DIRS,\n \"entities\",\n \"artifacts\",\n \"identity\",\n \"state\",\n \"config\",\n \"summaries\",\n \"profile.md\",\n] as const;\n\nexport interface NamespaceInventoryEntry {\n namespace: string;\n rootDir: string;\n exists: boolean;\n usesLegacyRoot: boolean;\n hasMemoryData: boolean;\n collection: string;\n}\n\nexport interface NamespaceVerifyReport {\n ok: boolean;\n problems: string[];\n namespaces: NamespaceInventoryEntry[];\n}\n\nexport interface NamespaceMigrationMove {\n from: string;\n to: string;\n}\n\nexport interface NamespaceMigrationReport {\n dryRun: boolean;\n fromRoot: string;\n targetRoot: string;\n moved: NamespaceMigrationMove[];\n collection: string;\n}\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await access(p);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function hasAnyLegacyData(rootDir: string): Promise<boolean> {\n for (const child of LEGACY_NAMESPACE_CHILDREN) {\n if (await exists(path.join(rootDir, child))) return true;\n }\n return false;\n}\n\nasync function discoverConfiguredNamespaces(\n config: PluginConfig,\n): Promise<string[]> {\n const discovered = new Set<string>([\n config.defaultNamespace,\n config.sharedNamespace,\n ...config.namespacePolicies.map((policy) => policy.name),\n ]);\n const configuredNamespaces = new Set(discovered);\n\n const namespacesDir = path.join(config.memoryDir, \"namespaces\");\n try {\n const entries = await readdir(namespacesDir, { withFileTypes: true });\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const namespace = configuredNamespaces.has(entry.name)\n ? entry.name\n : namespaceIdentityFromToken(entry.name) ?? entry.name;\n if (isSafeRouteNamespace(namespace)) {\n discovered.add(namespace);\n }\n }\n } catch {\n // No namespace directory yet.\n }\n\n return [...discovered];\n}\n\nexport async function listNamespaces(options: {\n config: PluginConfig;\n storageRouter?: NamespaceStorageRouter;\n}): Promise<NamespaceInventoryEntry[]> {\n const storageRouter = options.storageRouter ?? new NamespaceStorageRouter(options.config);\n const namespaces = await discoverConfiguredNamespaces(options.config);\n const items = await Promise.all(\n namespaces.map(async (namespace) => {\n const storage = await storageRouter.storageFor(namespace);\n const usesLegacyRoot =\n namespace === options.config.defaultNamespace &&\n storage.dir === options.config.memoryDir;\n return {\n namespace,\n rootDir: storage.dir,\n exists: await exists(storage.dir),\n usesLegacyRoot,\n hasMemoryData: await hasAnyLegacyData(storage.dir),\n collection: namespaceCollectionName(options.config.qmdCollection, namespace, {\n defaultNamespace: options.config.defaultNamespace,\n useLegacyDefaultCollection: usesLegacyRoot,\n }),\n } satisfies NamespaceInventoryEntry;\n }),\n );\n\n return items.sort((a, b) => a.namespace.localeCompare(b.namespace));\n}\n\nexport async function verifyNamespaces(options: {\n config: PluginConfig;\n storageRouter?: NamespaceStorageRouter;\n}): Promise<NamespaceVerifyReport> {\n const namespaces = await listNamespaces(options);\n const problems: string[] = [];\n\n for (const entry of namespaces) {\n if (entry.exists && !entry.hasMemoryData) {\n problems.push(`${entry.namespace}: root exists but contains no Engram data`);\n }\n }\n\n return {\n ok: problems.length === 0,\n problems,\n namespaces,\n };\n}\n\nexport async function runNamespaceMigration(options: {\n config: PluginConfig;\n to: string;\n dryRun?: boolean;\n renameFn?: typeof rename;\n}): Promise<NamespaceMigrationReport> {\n if (!resolveNamespaceCapabilities(options.config).namespaces) {\n throw new Error(\"Namespaces are disabled.\");\n }\n\n const targetNamespace = options.to.trim();\n if (!isSafeRouteNamespace(targetNamespace)) {\n throw new Error(`Invalid namespace: ${options.to}`);\n }\n\n const targetRoot = path.join(\n options.config.memoryDir,\n \"namespaces\",\n namespaceIdentityToken(targetNamespace),\n );\n const moved: NamespaceMigrationMove[] = [];\n const renamePath = options.renameFn ?? rename;\n\n for (const child of LEGACY_NAMESPACE_CHILDREN) {\n const from = path.join(options.config.memoryDir, child);\n if (!(await exists(from))) continue;\n const to = path.join(targetRoot, child);\n if (await exists(to)) {\n throw new Error(`Target already contains ${child}: ${to}`);\n }\n const sourceStat = await lstat(from);\n if (sourceStat.isSymbolicLink()) {\n throw new Error(`Refusing to migrate symlinked legacy path: ${from}`);\n }\n moved.push({ from, to });\n }\n\n if (!options.dryRun && moved.length > 0) {\n await assertSafeNamespaceTarget(options.config.memoryDir, targetRoot);\n await mkdir(targetRoot, { recursive: true });\n await assertSafeNamespaceTarget(options.config.memoryDir, targetRoot);\n const completed: NamespaceMigrationMove[] = [];\n try {\n for (const move of moved) {\n await renamePath(move.from, move.to);\n completed.push(move);\n }\n } catch (cause) {\n const rollbackErrors: string[] = [];\n for (const move of completed.reverse()) {\n try {\n if (!(await exists(move.from)) && (await exists(move.to))) {\n await rename(move.to, move.from);\n }\n } catch (rollbackCause) {\n rollbackErrors.push(rollbackCause instanceof Error ? rollbackCause.message : String(rollbackCause));\n }\n }\n try {\n await rmdir(targetRoot);\n } catch {\n // Target may predate migration or still contain unrelated files.\n }\n const message = cause instanceof Error ? cause.message : String(cause);\n throw new Error(\n `Namespace migration failed and was rolled back: ${message}` +\n (rollbackErrors.length > 0 ? `; rollback errors: ${rollbackErrors.join(\"; \")}` : \"\"),\n { cause },\n );\n }\n }\n\n return {\n dryRun: options.dryRun === true,\n fromRoot: options.config.memoryDir,\n targetRoot,\n moved,\n collection: namespaceCollectionName(options.config.qmdCollection, targetNamespace, {\n defaultNamespace: options.config.defaultNamespace,\n useLegacyDefaultCollection: false,\n }),\n };\n}\n\nasync function assertSafeNamespaceTarget(memoryDir: string, targetRoot: string): Promise<void> {\n const memoryReal = await realpath(memoryDir);\n const namespacesDir = path.join(memoryDir, \"namespaces\");\n if (await exists(namespacesDir)) {\n const namespacesStat = await lstat(namespacesDir);\n if (namespacesStat.isSymbolicLink()) {\n throw new Error(`Refusing to migrate through symlinked namespaces directory: ${namespacesDir}`);\n }\n const namespacesReal = await realpath(namespacesDir);\n if (!isPathInside(memoryReal, namespacesReal)) {\n throw new Error(`Refusing to migrate through namespaces directory outside memoryDir: ${namespacesDir}`);\n }\n }\n if (await exists(targetRoot)) {\n const targetStat = await lstat(targetRoot);\n if (targetStat.isSymbolicLink()) {\n throw new Error(`Refusing to migrate into symlinked namespace root: ${targetRoot}`);\n }\n const targetReal = await realpath(targetRoot);\n if (!isPathInside(memoryReal, targetReal)) {\n throw new Error(`Refusing to migrate into namespace root outside memoryDir: ${targetRoot}`);\n }\n }\n}\n\nfunction isPathInside(root: string, child: string): boolean {\n const relative = path.relative(root, child);\n return relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,QAAQ,OAAO,OAAO,SAAS,UAAU,QAAQ,aAAa;AAQvE,IAAM,4BAA4B;AAAA,EAChC,GAAG;AAAA,EACH;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA8BA,eAAe,OAAO,GAA6B;AACjD,MAAI;AACF,UAAM,OAAO,CAAC;AACd,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;A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chunk-U3PN77QT.js";
@@ -112,7 +115,7 @@ function resolveExplicitCaptureReviewNamespace(orchestrator, namespace) {
112
115
  function resolveExplicitCaptureNamespace(orchestrator, namespace) {
113
116
  const normalized = asTrimmed(namespace);
114
117
  if (!normalized) return void 0;
115
- if (!orchestrator.config.namespacesEnabled) {
118
+ if (!resolveNamespaceCapabilities(orchestrator.config).namespaces) {
116
119
  if (normalized !== orchestrator.config.defaultNamespace) {
117
120
  throw new Error(`unsupported namespace: ${normalized}`);
118
121
  }
@@ -438,4 +441,4 @@ export {
438
441
  shouldSkipImplicitExtraction,
439
442
  shouldProcessInlineExplicitCapture
440
443
  };
441
- //# sourceMappingURL=chunk-PMAQRUN4.js.map
444
+ //# sourceMappingURL=chunk-NDKW67ER.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/explicit-capture.ts"],"sourcesContent":["import { resolveNamespaceCapabilities } from \"./capabilities.js\";\nimport { randomUUID } from \"node:crypto\";\nimport type { Orchestrator } from \"./orchestrator.js\";\nimport { isSafeRouteNamespace } from \"./routing/engine.js\";\nimport { sanitizeMemoryContent } from \"./sanitize.js\";\nimport { ContentHashIndex } from \"./storage.js\";\nimport type { CaptureMode, MemoryCategory, MemoryLifecycleEvent, PluginConfig } from \"./types.js\";\n\nexport type ExplicitCaptureInput = {\n content: string;\n category?: string;\n confidence?: number;\n namespace?: string;\n tags?: string[];\n entityRef?: string;\n ttl?: string;\n sourceReason?: string;\n};\n\nexport type ValidExplicitCapture = {\n content: string;\n category: MemoryCategory;\n confidence: number;\n namespace?: string;\n tags: string[];\n entityRef?: string;\n expiresAt?: string;\n sourceReason?: string;\n /**\n * When true, `namespace` was already resolved AND authorized by the caller\n * (the access service's `resolveCodingScopedWriteNamespace`, which auth-checks\n * the base and derives a session-owned `project-*` overlay). The persist /\n * queue layer then routes to it directly instead of re-validating against the\n * static policy allow-list — which would otherwise reject legitimately-derived\n * dynamic project namespaces (#1434). Callers that do NOT pre-authorize the\n * namespace must leave this unset so the allow-list guard still applies.\n */\n namespacePreResolved?: boolean;\n};\n\nexport type ExplicitCaptureSource = \"memory_store\" | \"memory_capture\" | \"suggestion_submit\" | \"inline\";\ntype ExplicitCaptureValidationMode = \"legacy_tool\" | \"strict_explicit\";\n\n// Bounded body {0,100000} instead of an unbounded lazy *? so scanning for the\n// closing tag cannot backtrack polynomially on unterminated <memory_note>\n// markup in hostile turn text (CodeQL js/polynomial-redos). 100 000 chars far\n// exceeds any real inline note, so matching is behavior-preserving; the outer\n// \\s* groups were also dropped (body absorbs whitespace; captures are trimmed).\nconst INLINE_NOTE_RE = /<memory_note>([\\s\\S]{0,100000}?)<\\/memory_note>/gi;\nconst INLINE_NOTE_MARKUP_RE = /<memory_note>[\\s\\S]{0,100000}?<\\/memory_note>/i;\nconst INLINE_ALLOWED_CATEGORIES = new Set<MemoryCategory>([\n \"fact\",\n \"preference\",\n \"correction\",\n \"entity\",\n \"decision\",\n \"relationship\",\n \"principle\",\n \"commitment\",\n \"moment\",\n \"skill\",\n \"rule\",\n \"procedure\",\n \"reasoning_trace\",\n]);\n\nconst SECRET_PATTERNS: RegExp[] = [\n /\\bsk-[A-Za-z0-9]{16,}\\b/,\n /\\bAKIA[0-9A-Z]{16}\\b/,\n /\\bBearer\\s+[A-Za-z0-9._-]{16,}\\b/i,\n /\\b(?:api[_-]?key|secret|token|password|passwd)\\s*[:=]\\s*[^\\s]{8,}\\b/i,\n /\\b(?:authorization)\\s*:\\s*[^\\s]{8,}\\b/i,\n];\nconst SECRET_REDACTION_PATTERNS: Array<{ pattern: RegExp; replacement: string }> = [\n { pattern: /\\bsk-[A-Za-z0-9]{16,}\\b/g, replacement: \"[redacted openai key]\" },\n { pattern: /\\bAKIA[0-9A-Z]{16}\\b/g, replacement: \"[redacted aws key]\" },\n { pattern: /\\bBearer\\s+[A-Za-z0-9._-]{16,}\\b/gi, replacement: \"Bearer [redacted token]\" },\n {\n pattern: /\\b(?:api[_-]?key|secret|token|password|passwd)\\s*[:=]\\s*[^\\s]{8,}\\b/gi,\n replacement: \"[redacted credential]\",\n },\n {\n pattern: /\\b(?:authorization)\\s*:\\s*[^\\s]{8,}\\b/gi,\n replacement: \"authorization: [redacted credential]\",\n },\n];\nconst EXPLICIT_CAPTURE_REVIEW_TAGS = [\"explicit-capture\", \"queued-review\"];\n\nfunction explicitCaptureActor(source: ExplicitCaptureSource): string {\n switch (source) {\n case \"inline\":\n return \"inline.memory_note\";\n case \"memory_store\":\n return \"tool.memory_store\";\n case \"suggestion_submit\":\n return \"tool.suggestion_submit\";\n default:\n return \"tool.memory_capture\";\n }\n}\n\nfunction asTrimmed(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction normalizeCaptureContent(value: string): string {\n return value\n .toLowerCase()\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\nfunction redactSecrets(value: string): string {\n let redacted = value;\n for (const { pattern, replacement } of SECRET_REDACTION_PATTERNS) {\n redacted = redacted.replace(pattern, replacement);\n }\n return redacted;\n}\n\nfunction containsSecretLikeValue(value: string): boolean {\n return SECRET_PATTERNS.some((pattern) => pattern.test(value));\n}\n\nfunction assertNoSecretLikeMetadata(field: string, value: string | undefined): void {\n const trimmed = asTrimmed(value);\n if (trimmed && containsSecretLikeValue(trimmed)) {\n throw new Error(`${field} appears to contain a secret or credential`);\n }\n}\n\nfunction assertNoSecretLikeMetadataList(field: string, values: string[] | undefined): void {\n for (const value of values ?? []) {\n assertNoSecretLikeMetadata(field, value);\n }\n}\n\nfunction sanitizeReviewText(value: string | undefined, fallback: string): string {\n const redacted = redactSecrets(asTrimmed(value) ?? fallback);\n const sanitized = sanitizeMemoryContent(redacted);\n const safe = sanitized.text.trim();\n return safe.length > 0 ? safe : fallback;\n}\n\nfunction sanitizeReviewMetadata(value: string | undefined): string | undefined {\n const trimmed = asTrimmed(value);\n if (!trimmed) return undefined;\n return sanitizeReviewText(trimmed, \"[redacted]\");\n}\n\nfunction sanitizeReviewTags(tags: string[] | undefined): string[] {\n return Array.from(new Set((tags ?? [])\n .map((tag) => sanitizeReviewMetadata(tag))\n .filter((tag): tag is string => typeof tag === \"string\" && tag.length > 0)));\n}\n\nfunction normalizeExplicitCaptureError(error: unknown): string {\n if (error instanceof Error && error.message.trim().length > 0) return error.message.trim();\n const rendered = String(error).trim();\n return rendered.length > 0 ? rendered : \"explicit capture failed\";\n}\n\nfunction resolveExplicitCaptureReviewNamespace(\n orchestrator: Orchestrator,\n namespace: string | undefined,\n): string | undefined {\n const normalized = asTrimmed(namespace);\n if (!normalized) return undefined;\n return resolveExplicitCaptureNamespace(orchestrator, normalized);\n}\n\nfunction resolveExplicitCaptureNamespace(\n orchestrator: Orchestrator,\n namespace: string | undefined,\n): string | undefined {\n const normalized = asTrimmed(namespace);\n if (!normalized) return undefined;\n if (!resolveNamespaceCapabilities(orchestrator.config).namespaces) {\n if (normalized !== orchestrator.config.defaultNamespace) {\n throw new Error(`unsupported namespace: ${normalized}`);\n }\n return normalized;\n }\n const allowed = new Set([\n orchestrator.config.defaultNamespace,\n orchestrator.config.sharedNamespace,\n ...orchestrator.config.namespacePolicies.map((policy) => policy.name),\n ].map((value) => value.trim()).filter(Boolean));\n if (!allowed.has(normalized)) {\n throw new Error(`unsupported namespace: ${normalized}`);\n }\n return normalized;\n}\n\nfunction parseExplicitCaptureTtl(ttl: string | undefined): string | undefined {\n const raw = asTrimmed(ttl);\n if (!raw) return undefined;\n\n const absoluteMs = Date.parse(raw);\n if (Number.isFinite(absoluteMs)) {\n return new Date(absoluteMs).toISOString();\n }\n\n const relative = raw.match(/^(\\d+)\\s*([mhdw])$/i);\n if (!relative) {\n throw new Error(\"ttl must be an ISO-8601 timestamp or relative duration like 30m, 12h, 7d, or 2w\");\n }\n\n const amount = Number.parseInt(relative[1] ?? \"\", 10);\n const unit = (relative[2] ?? \"\").toLowerCase();\n if (!Number.isFinite(amount) || amount <= 0) {\n throw new Error(\"ttl duration must be a positive integer\");\n }\n\n const multiplier =\n unit === \"m\" ? 60_000\n : unit === \"h\" ? 60 * 60_000\n : unit === \"d\" ? 24 * 60 * 60_000\n : 7 * 24 * 60 * 60_000;\n return new Date(Date.now() + amount * multiplier).toISOString();\n}\n\nfunction parseInlineConfidence(value: string): number {\n const trimmed = value.trim();\n if (!/^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i.test(trimmed)) {\n return Number.NaN;\n }\n const parsed = Number(trimmed);\n return Number.isFinite(parsed) ? parsed : Number.NaN;\n}\n\nfunction parseInlineNote(block: string): ExplicitCaptureInput | null {\n const lines = block.replace(/\\r/g, \"\").split(\"\\n\");\n const note: Partial<ExplicitCaptureInput> = {};\n let idx = 0;\n\n while (idx < lines.length) {\n const rawLine = lines[idx] ?? \"\";\n const line = rawLine.trim();\n idx += 1;\n if (line.length === 0) continue;\n const colonIdx = line.indexOf(\":\");\n if (colonIdx < 0) continue;\n const key = line.slice(0, colonIdx).trim();\n const value = line.slice(colonIdx + 1).trim();\n\n if (key === \"content\" && value === \"|\") {\n const contentLines: string[] = [];\n while (idx < lines.length) {\n const next = lines[idx] ?? \"\";\n if (next.startsWith(\" \") || next.startsWith(\"\\t\")) {\n contentLines.push(next.replace(/^( |\\t)/, \"\"));\n idx += 1;\n continue;\n }\n if (next.trim().length === 0) {\n contentLines.push(\"\");\n idx += 1;\n continue;\n }\n break;\n }\n note.content = contentLines.join(\"\\n\").trim();\n continue;\n }\n\n switch (key) {\n case \"content\":\n note.content = value;\n break;\n case \"category\":\n note.category = value;\n break;\n case \"confidence\":\n note.confidence = parseInlineConfidence(value);\n break;\n case \"namespace\":\n note.namespace = value;\n break;\n case \"tags\":\n note.tags = value\n .split(\",\")\n .map((entry) => entry.trim())\n .filter(Boolean);\n break;\n case \"entityRef\":\n note.entityRef = value;\n break;\n case \"ttl\":\n note.ttl = value;\n break;\n case \"sourceReason\":\n note.sourceReason = value;\n break;\n default:\n break;\n }\n }\n\n return asTrimmed(note.content) ? (note as ExplicitCaptureInput) : null;\n}\n\nexport function parseInlineExplicitCaptureNotes(text: string): ExplicitCaptureInput[] {\n const notes: ExplicitCaptureInput[] = [];\n for (const match of text.matchAll(INLINE_NOTE_RE)) {\n const parsed = parseInlineNote(match[1] ?? \"\");\n if (parsed) notes.push(parsed);\n }\n return notes;\n}\n\nexport function hasInlineExplicitCaptureMarkup(text: string): boolean {\n return INLINE_NOTE_MARKUP_RE.test(text);\n}\n\nexport function stripInlineExplicitCaptureNotes(text: string): string {\n return text.replace(INLINE_NOTE_RE, \"\").trim();\n}\n\nexport function validateExplicitCaptureInput(\n input: ExplicitCaptureInput,\n mode: ExplicitCaptureValidationMode = \"strict_explicit\",\n): ValidExplicitCapture {\n const content = asTrimmed(input.content);\n if (!content) throw new Error(\"content is required\");\n if (mode === \"strict_explicit\") {\n if (content.length < 10) throw new Error(\"content must be at least 10 characters\");\n if (content.length > 4000) throw new Error(\"content must be 4000 characters or fewer\");\n }\n if (/<memory_note>/i.test(content) || /<\\/memory_note>/i.test(content)) {\n throw new Error(\"nested memory_note blocks are not allowed\");\n }\n\n const category = (asTrimmed(input.category) ?? \"fact\") as MemoryCategory;\n if (!INLINE_ALLOWED_CATEGORIES.has(category)) {\n throw new Error(`unsupported category: ${input.category ?? category}`);\n }\n\n const sanitized = sanitizeMemoryContent(content);\n if (!sanitized.clean) {\n throw new Error(\"content failed memory sanitization\");\n }\n for (const pattern of SECRET_PATTERNS) {\n if (pattern.test(content)) {\n throw new Error(\"content appears to contain a secret or credential\");\n }\n }\n assertNoSecretLikeMetadata(\"sourceReason\", input.sourceReason);\n assertNoSecretLikeMetadata(\"entityRef\", input.entityRef);\n assertNoSecretLikeMetadata(\"ttl\", input.ttl);\n assertNoSecretLikeMetadataList(\"tags\", input.tags);\n\n if (input.confidence !== undefined && !Number.isFinite(input.confidence)) {\n throw new Error(\"confidence must be a finite number\");\n }\n const confidence = input.confidence === undefined ? 0.95 : Number(input.confidence);\n if (confidence < 0 || confidence > 1) {\n throw new Error(\"confidence must be between 0 and 1\");\n }\n const requestedNamespace = asTrimmed(input.namespace);\n if (requestedNamespace && !isSafeRouteNamespace(requestedNamespace)) {\n throw new Error(`unsafe namespace: ${requestedNamespace}`);\n }\n const expiresAt = parseExplicitCaptureTtl(input.ttl);\n\n return {\n content,\n category,\n confidence,\n namespace: asTrimmed(input.namespace),\n tags: Array.from(new Set((input.tags ?? []).map((tag) => tag.trim()).filter(Boolean))),\n entityRef: asTrimmed(input.entityRef),\n expiresAt,\n sourceReason: asTrimmed(input.sourceReason),\n };\n}\n\nasync function findDuplicateExplicitCapture(\n orchestrator: Orchestrator,\n resolvedNamespace: string | undefined,\n candidate: ValidExplicitCapture,\n): Promise<string | null> {\n const storage = await orchestrator.getStorage(resolvedNamespace);\n if (\n candidate.category === \"fact\"\n && typeof (storage as { hasFactContentHash?: (content: string) => Promise<boolean> }).hasFactContentHash === \"function\"\n ) {\n try {\n const hasHash = await (storage as { hasFactContentHash: (content: string) => Promise<boolean> }).hasFactContentHash(\n candidate.content,\n );\n if (!hasHash) {\n const authoritative =\n typeof (storage as { isFactContentHashAuthoritative?: () => Promise<boolean> | boolean }).isFactContentHashAuthoritative\n === \"function\"\n ? await (storage as { isFactContentHashAuthoritative: () => Promise<boolean> | boolean })\n .isFactContentHashAuthoritative()\n : false;\n if (authoritative) return null;\n }\n } catch (err) {\n // Fail open: hash index is only an optimization, so fall back to the full corpus scan.\n void err;\n }\n }\n const existing = await storage.readAllMemories();\n const normalizedCandidate = normalizeCaptureContent(candidate.content);\n const match = existing.find((memory) => {\n const status = memory.frontmatter.status ?? \"active\";\n if (status !== \"active\") return false;\n if (memory.frontmatter.category !== candidate.category) return false;\n return normalizeCaptureContent(memory.content) === normalizedCandidate;\n });\n return match?.frontmatter.id ?? null;\n}\n\nexport async function persistExplicitCapture(\n orchestrator: Orchestrator,\n candidate: ValidExplicitCapture,\n source: ExplicitCaptureSource,\n): Promise<{ id: string; duplicateOf?: string; tombstoneBlocked?: boolean }> {\n const resolvedNamespace = candidate.namespacePreResolved\n ? asTrimmed(candidate.namespace)\n : resolveExplicitCaptureNamespace(orchestrator, candidate.namespace);\n const duplicateOf = await findDuplicateExplicitCapture(orchestrator, resolvedNamespace, candidate);\n if (duplicateOf) {\n return { id: duplicateOf, duplicateOf };\n }\n\n const storage = await orchestrator.getStorage(resolvedNamespace);\n // #1645 (review thread yG-): surface the tombstone block so callers\n // (memory_store tool, access-service HTTP/MCP) can report the capture as\n // queued for review instead of a successfully stored active memory.\n const { id, tombstoneBlocked } = await storage.writeMemory(candidate.category, candidate.content, {\n confidence: candidate.confidence,\n tags: candidate.tags,\n entityRef: candidate.entityRef,\n expiresAt: candidate.expiresAt,\n source: source === \"inline\" ? \"explicit-inline\" : \"explicit\",\n });\n // #1522: catalog touch handled at the storage chokepoint — the StorageManager's\n // post-write hook records the namespace touch automatically.\n\n const created = new Date().toISOString();\n const event: MemoryLifecycleEvent = {\n eventId: `mle-${randomUUID()}`,\n memoryId: id,\n eventType: \"explicit_capture_accepted\",\n timestamp: created,\n actor: explicitCaptureActor(source),\n reasonCode: candidate.sourceReason,\n ruleVersion: \"explicit-capture.v1\",\n };\n await storage.appendMemoryLifecycleEvents([event]);\n\n return { id, tombstoneBlocked };\n}\n\nfunction buildExplicitCaptureReviewContent(input: ExplicitCaptureInput, reason: string): string {\n const requestedContent = asTrimmed(input.content);\n const safeContent = sanitizeReviewText(requestedContent, \"[empty explicit capture]\");\n const safeCategory = sanitizeReviewMetadata(input.category);\n const safeNamespace = sanitizeReviewMetadata(input.namespace);\n const safeEntityRef = sanitizeReviewMetadata(input.entityRef);\n const safeTtl = sanitizeReviewMetadata(input.ttl);\n const safeSourceReason = sanitizeReviewMetadata(input.sourceReason);\n const safeTags = sanitizeReviewTags(input.tags);\n const lines = [\n \"Explicit capture queued for review.\",\n \"\",\n `Reason: ${reason}`,\n \"\",\n \"Submitted content:\",\n safeContent,\n ];\n const metadata = [\n safeCategory ? `Requested category: ${safeCategory}` : undefined,\n safeNamespace ? `Requested namespace: ${safeNamespace}` : undefined,\n safeEntityRef ? `Requested entityRef: ${safeEntityRef}` : undefined,\n safeTtl ? `Requested ttl: ${safeTtl}` : undefined,\n safeSourceReason ? `Requested sourceReason: ${safeSourceReason}` : undefined,\n safeTags.length > 0 ? `Requested tags: ${safeTags.join(\", \")}` : undefined,\n ].filter((entry): entry is string => typeof entry === \"string\" && entry.length > 0);\n if (metadata.length > 0) {\n lines.push(\"\", ...metadata);\n }\n return lines.join(\"\\n\");\n}\n\nasync function findQueuedExplicitCaptureDuplicate(\n orchestrator: Orchestrator,\n namespace: string | undefined,\n content: string,\n): Promise<string | null> {\n const storage = await orchestrator.getStorage(namespace);\n const existing = await storage.readAllMemories();\n const normalized = normalizeCaptureContent(content);\n const match = existing.find((memory) => {\n const status = memory.frontmatter.status ?? \"active\";\n if (status !== \"pending_review\") return false;\n if (!(memory.frontmatter.tags ?? []).includes(\"queued-review\")) return false;\n return normalizeCaptureContent(memory.content) === normalized;\n });\n return match?.frontmatter.id ?? null;\n}\n\nexport async function queueExplicitCaptureForReview(\n orchestrator: Orchestrator,\n input: ExplicitCaptureInput,\n source: ExplicitCaptureSource,\n error: unknown,\n): Promise<{ id: string; duplicateOf?: string }> {\n const reason = sanitizeReviewText(normalizeExplicitCaptureError(error), \"explicit capture failed\");\n const requestedNamespace = asTrimmed(input.namespace);\n // A caller-pre-authorized namespace (e.g. a session-owned project overlay\n // from the access service) routes directly; otherwise apply the static\n // policy allow-list guard (#1434).\n const queueNamespace = (input as { namespacePreResolved?: boolean }).namespacePreResolved\n ? requestedNamespace\n : resolveExplicitCaptureReviewNamespace(orchestrator, requestedNamespace);\n const content = buildExplicitCaptureReviewContent(input, reason);\n const duplicateOf = await findQueuedExplicitCaptureDuplicate(orchestrator, queueNamespace, content);\n if (duplicateOf) {\n return { id: duplicateOf, duplicateOf };\n }\n\n const requestedCategory = asTrimmed(input.category);\n const reviewCategory = requestedCategory && INLINE_ALLOWED_CATEGORIES.has(requestedCategory as MemoryCategory)\n ? requestedCategory as MemoryCategory\n : \"fact\";\n const requestedTags = sanitizeReviewTags(input.tags);\n const storage = await orchestrator.getStorage(queueNamespace);\n const { id: id } = await storage.writeMemory(reviewCategory, content, {\n confidence: 0.2,\n tags: Array.from(new Set([...EXPLICIT_CAPTURE_REVIEW_TAGS, ...requestedTags])),\n entityRef: sanitizeReviewMetadata(input.entityRef),\n source: source === \"inline\" ? \"explicit-inline-review\" : \"explicit-review\",\n });\n try {\n const created = await storage.getMemoryById(id);\n if (created) {\n await storage.writeMemoryFrontmatter(created, {\n status: \"pending_review\",\n updated: new Date().toISOString(),\n }, {\n actor: explicitCaptureActor(source),\n reasonCode: reason,\n ruleVersion: \"explicit-capture.v1\",\n });\n }\n } finally {\n // Record the catalog write touch (issue #1499, round 5/6 codex P2; NIhUg).\n // A queued review capture writes memory to the namespace's root (the DEFAULT\n // root when undefined), so its `lastWriteAt` must reflect the write once\n // `writeMemory` returns an id. If the later pending-review frontmatter update\n // fails, the memory file is still durable and must not disappear from\n // writtenSince/maintenance scheduling. Guarded optional hook (rule #33).\n // #1522: catalog touch handled at the storage chokepoint.\n }\n const event: MemoryLifecycleEvent = {\n eventId: `mle-${randomUUID()}`,\n memoryId: id,\n eventType: \"explicit_capture_queued\",\n timestamp: new Date().toISOString(),\n actor: explicitCaptureActor(source),\n reasonCode: reason,\n ruleVersion: \"explicit-capture.v1\",\n };\n await storage.appendMemoryLifecycleEvents([event]);\n return { id };\n}\n\nexport function shouldSkipImplicitExtraction(cfg: Pick<PluginConfig, \"captureMode\">): boolean {\n return cfg.captureMode === \"explicit\";\n}\n\nexport function shouldProcessInlineExplicitCapture(cfg: Pick<PluginConfig, \"captureMode\">): boolean {\n return cfg.captureMode !== \"implicit\";\n}\n"],"mappings":";;;;;;;;;;;AACA,SAAS,kBAAkB;AA+C3B,IAAM,iBAAiB;AACvB,IAAM,wBAAwB;AAC9B,IAAM,4BAA4B,oBAAI,IAAoB;AAAA,EACxD;A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EAAE;AAC9C,QAAI,SAAS;AACX,YAAM,QAAQ,uBAAuB,SAAS;AAAA,QAC5C,QAAQ;AAAA,QACR,UAAS,oBAAI,KAAK,GAAE,YAAY;AAAA,MAClC,GAAG;AAAA,QACD,OAAO,qBAAqB,MAAM;AAAA,QAClC,YAAY;AAAA,QACZ,aAAa;AAAA,MACf,CAAC;AAAA,IACH;AAAA,EACF,UAAE;AAAA,EAQF;AACA,QAAM,QAA8B;AAAA,IAClC,SAAS,OAAO,WAAW,CAAC;AAAA,IAC5B,UAAU;AAAA,IACV,WAAW;AAAA,IACX,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,IAClC,OAAO,qBAAqB,MAAM;AAAA,IAClC,YAAY;AAAA,IACZ,aAAa;AAAA,EACf;AACA,QAAM,QAAQ,4BAA4B,CAAC,KAAK,CAAC;AACjD,SAAO,EAAE,GAAG;AACd;AAEO,SAAS,6BAA6B,KAAiD;AAC5F,SAAO,IAAI,gBAAgB;AAC7B;AAEO,SAAS,mCAAmC,KAAiD;AAClG,SAAO,IAAI,gBAAgB;AAC7B;","names":[]}
@@ -11,6 +11,9 @@ import {
11
11
  import {
12
12
  ALL_CATEGORY_DIRS
13
13
  } from "./chunk-VS2IYZRU.js";
14
+ import {
15
+ resolveNamespaceCapabilities
16
+ } from "./chunk-JWDE7OVJ.js";
14
17
  import {
15
18
  isSafeRouteNamespace
16
19
  } from "./chunk-U3PN77QT.js";
@@ -73,7 +76,7 @@ async function hasAnyNamespaceStorageMarker(rootDir, options = {}) {
73
76
  return false;
74
77
  }
75
78
  async function resolveDefaultNamespaceRoot(config) {
76
- if (!config.namespacesEnabled) {
79
+ if (!resolveNamespaceCapabilities(config).namespaces) {
77
80
  return config.memoryDir;
78
81
  }
79
82
  const defaultIdentity = normalizeNamespaceIdentity(config.defaultNamespace);
@@ -87,7 +90,7 @@ async function resolveDefaultNamespaceRoot(config) {
87
90
  return await exists(nsDir) && !await hasAnyLegacyData(config.memoryDir) ? nsDir : config.memoryDir;
88
91
  }
89
92
  async function resolveNamespaceStorageRoot(config, namespace) {
90
- if (!config.namespacesEnabled) return config.memoryDir;
93
+ if (!resolveNamespaceCapabilities(config).namespaces) return config.memoryDir;
91
94
  if (normalizeNamespaceIdentity(namespace) === normalizeNamespaceIdentity(config.defaultNamespace)) {
92
95
  return resolveDefaultNamespaceRoot(config);
93
96
  }
@@ -150,7 +153,7 @@ var NamespaceStorageRouter = class {
150
153
  return this.defaultNsRootResolved;
151
154
  }
152
155
  async namespaceRoot(namespace) {
153
- if (!this.config.namespacesEnabled) return this.config.memoryDir;
156
+ if (!resolveNamespaceCapabilities(this.config).namespaces) return this.config.memoryDir;
154
157
  if (normalizeNamespaceIdentity(namespace) === this.defaultNamespaceIdentity) {
155
158
  return this.defaultNsRootResolved ?? this.config.memoryDir;
156
159
  }
@@ -336,4 +339,4 @@ export {
336
339
  resolveNamespaceStorageRoot,
337
340
  NamespaceStorageRouter
338
341
  };
339
- //# sourceMappingURL=chunk-ZQUAVZNG.js.map
342
+ //# sourceMappingURL=chunk-NNJKEAP2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/namespaces/storage.ts"],"sourcesContent":["import { resolveNamespaceCapabilities } from \"../capabilities.js\";\nimport path from \"node:path\";\nimport { access, lstat, readdir } from \"node:fs/promises\";\nimport { isSafeRouteNamespace } from \"../routing/engine.js\";\nimport { StorageManager } from \"../storage.js\";\nimport type { PluginConfig } from \"../types.js\";\nimport { ALL_CATEGORY_DIRS } from \"../utils/category-dir.js\";\nimport { namespaceIdentityToken, normalizeNamespaceIdentity } from \"./identity.js\";\nimport type { NamespaceCatalog } from \"./catalog.js\";\nimport { MutationSerializer } from \"../utils/serialize-mutations.js\";\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await access(p);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function hasStoredEntries(p: string): Promise<boolean> {\n try {\n const entry = await lstat(p);\n if (entry.isSymbolicLink()) return true;\n if (!entry.isDirectory()) return true;\n const children = await readdir(p, { withFileTypes: true });\n for (const child of children) {\n const childPath = path.join(p, child.name);\n if (child.isSymbolicLink() || child.isFile()) return true;\n if (child.isDirectory() && (await hasStoredEntries(childPath))) return true;\n }\n return false;\n } catch {\n return false;\n }\n}\n\n// Build a per-namespace directory under `<memoryDir>/namespaces` and assert the\n// resolved path stays inside that base. Namespace identifiers can originate from\n// operator config (config.defaultNamespace) and request-derived routing, so this\n// containment check prevents directory traversal (CodeQL js/path-injection).\n// For safe segments this returns exactly `path.join(base, segment)`, so there is\n// no behavioral change for valid namespaces.\nfunction resolveNamespaceDir(memoryDir: string, segment: string): string {\n // Mirror isSafeRouteNamespace's separator/parent-ref rejection (without its\n // 64-char cap, so identity tokens still pass). Rejecting separators and \"..\"\n // up front keeps the value a single contained child of <memoryDir>/namespaces.\n if (\n segment.length === 0 ||\n segment.includes(\"/\") ||\n segment.includes(\"\\\\\") ||\n segment.includes(\"..\") ||\n path.isAbsolute(segment)\n ) {\n throw new Error(`unsafe namespace path segment: ${segment}`);\n }\n return path.join(memoryDir, \"namespaces\", segment);\n}\n\nconst LEGACY_NAMESPACE_CONTENT_CHILDREN = [\n ...ALL_CATEGORY_DIRS,\n \"entities\",\n \"artifacts\",\n \"identity\",\n \"config\",\n \"summaries\",\n \"profile.md\",\n] as const;\n\nconst LEGACY_NAMESPACE_RUNTIME_CHILDREN = [\"state\"] as const;\n\nasync function hasAnyLegacyData(\n rootDir: string,\n options: { includeRuntimeState?: boolean } = {},\n): Promise<boolean> {\n const children = options.includeRuntimeState === true\n ? [...LEGACY_NAMESPACE_CONTENT_CHILDREN, ...LEGACY_NAMESPACE_RUNTIME_CHILDREN]\n : LEGACY_NAMESPACE_CONTENT_CHILDREN;\n for (const child of children) {\n if (await hasStoredEntries(path.join(rootDir, child))) return true;\n }\n return false;\n}\n\nasync function hasAnyNamespaceStorageMarker(\n rootDir: string,\n options: { includeRuntimeState?: boolean } = {},\n): Promise<boolean> {\n const children = options.includeRuntimeState === true\n ? [...LEGACY_NAMESPACE_CONTENT_CHILDREN, ...LEGACY_NAMESPACE_RUNTIME_CHILDREN]\n : LEGACY_NAMESPACE_CONTENT_CHILDREN;\n for (const child of children) {\n if (await exists(path.join(rootDir, child))) return true;\n }\n return false;\n}\n\n/**\n * Storage routing for namespaces.\n *\n * Compatibility note:\n * - When namespaces are enabled, existing raw namespace roots are preserved.\n * New namespace roots use tokenized names under `memoryDir/namespaces/<token>`.\n * - The default namespace continues to use the legacy `memoryDir` root unless the caller\n * has created `memoryDir/namespaces/<defaultNamespace>` (in which case we use that).\n *\n * This avoids surprising \"lost memories\" when an install flips namespaces on without\n * migrating existing data.\n */\n/**\n * Optional hooks for the storage router. `onResolve` fires whenever a namespace's\n * storage is resolved/created, so a downstream consumer (e.g. the namespace\n * catalog, issue #1499) can register the namespace. The hook MUST NOT throw into\n * the router; the router invokes it defensively and a hook failure never affects\n * storage resolution.\n *\n * The hook MAY return (or resolve to) a boolean indicating whether the\n * registration actually PERSISTED (round 6, codex P2 — NEFoX). When it resolves\n * to `false` (a dropped/no-op registration), the router does NOT mark the\n * (namespace, storageDir) pair as notified, so the next resolve RETRIES it\n * instead of suppressing it forever. A `void`/`undefined` result is treated as\n * success (legacy hooks).\n */\nexport interface NamespaceStorageRouterHooks {\n onResolve?: (\n namespace: string,\n storageDir: string,\n ) => void | boolean | Promise<void | boolean>;\n}\n\n/**\n * Resolve the runtime storage root for the configured DEFAULT namespace.\n *\n * Shared between the live router (`NamespaceStorageRouter.defaultNamespaceRoot`)\n * and the rebuildable catalog (`NamespaceCatalog.rebuildFromDisk`) so the two\n * can never diverge (CLAUDE.md rule #22/#42 — read & write paths resolve through\n * the same logic). The contract is: while legacy memory data still lives\n * directly under `memoryDir`, the default root stays `memoryDir`; only once the\n * legacy root is empty and a `namespaces/<default|token>` dir holds data does\n * the default migrate into that tokenized/legacy-named dir.\n */\nexport async function resolveDefaultNamespaceRoot(config: PluginConfig): Promise<string> {\n if (!resolveNamespaceCapabilities(config).namespaces) {\n return config.memoryDir;\n }\n\n // Build the legacy default root from the NORMALIZED (trimmed) name so a\n // whitespace-padded `defaultNamespace` still finds the live `namespaces/default`\n // root (NIabe). `storageFor()` classifies the trimmed value as the default, and\n // the on-disk legacy dir is created under the trimmed name; using the raw spaced\n // name here would look for `namespaces/<spaced>` and miss the real root, falling\n // back to memoryDir/tokenized. `namespaceIdentityToken` already normalizes\n // internally, so the tokenized path is unaffected.\n const defaultIdentity = normalizeNamespaceIdentity(config.defaultNamespace);\n const legacyNsDir = resolveNamespaceDir(config.memoryDir, defaultIdentity);\n const tokenizedNsDir = resolveNamespaceDir(\n config.memoryDir,\n namespaceIdentityToken(config.defaultNamespace),\n );\n const tokenizedHasData =\n (await exists(tokenizedNsDir)) &&\n (await hasAnyNamespaceStorageMarker(tokenizedNsDir, { includeRuntimeState: true }));\n const nsDir = tokenizedHasData\n ? tokenizedNsDir\n : (await exists(legacyNsDir))\n ? legacyNsDir\n : tokenizedNsDir;\n return (await exists(nsDir)) && !(await hasAnyLegacyData(config.memoryDir))\n ? nsDir\n : config.memoryDir;\n}\n\n/**\n * Resolve the runtime storage root for ANY namespace exactly as the live router\n * would (`NamespaceStorageRouter.namespaceRoot`). Shared so the rebuildable\n * catalog records the SAME on-disk root the router routes to — a recall/read\n * touch must not guess `namespaces/<token>` when the router actually serves a\n * legacy raw-name dir or a migrated default root (CLAUDE.md rule #22/#42; round\n * 4, cursor Medium). The default namespace delegates to `resolveDefaultNamespaceRoot`;\n * every other namespace prefers the tokenized root when it has a storage marker,\n * else a legacy raw-name dir when present, else the tokenized root.\n */\nexport async function resolveNamespaceStorageRoot(\n config: PluginConfig,\n namespace: string,\n): Promise<string> {\n if (!resolveNamespaceCapabilities(config).namespaces) return config.memoryDir;\n // Compare on NORMALIZED identity so a whitespace-padded configured default name\n // still routes to the default root rather than a tokenized non-default dir\n // (NH-FH). The catalog keys records by the same normalized identity.\n if (normalizeNamespaceIdentity(namespace) === normalizeNamespaceIdentity(config.defaultNamespace)) {\n return resolveDefaultNamespaceRoot(config);\n }\n const legacyRoot = resolveNamespaceDir(config.memoryDir, namespace);\n const tokenizedRoot = resolveNamespaceDir(config.memoryDir, namespaceIdentityToken(namespace));\n if (\n (await exists(tokenizedRoot)) &&\n (await hasAnyNamespaceStorageMarker(tokenizedRoot, { includeRuntimeState: true }))\n ) {\n return tokenizedRoot;\n }\n return (await exists(legacyRoot)) ? legacyRoot : tokenizedRoot;\n}\n\nexport class NamespaceStorageRouter {\n private readonly cache = new Map<string, StorageManager>();\n private defaultNsRootResolved: string | null = null;\n // Dedup the resolve hook (round 6, cursor Medium — NCNL2). Recall/extraction\n // call `storageFor` repeatedly; firing `onResolve` (→ catalog loadCompacted +\n // append) on every cache hit grows `namespaces.jsonl` without bound between\n // rebuilds. We fire the hook only when the (namespace, storageDir) pair is new\n // or its dir changed, so a steady-state cache hit is a no-op for the catalog.\n private readonly notifiedResolved = new Map<string, string>();\n // Instance-scoped serializer for the resolve hook (issue #1524 adoption).\n // Replaces the bespoke `inFlightResolved` marker-then-clear pattern: the\n // serializer's per-key chain strictly orders concurrent notifications for the\n // SAME namespace, and the task re-checks `notifiedResolved` once it runs, so a\n // burst of cache hits before the first hook settles collapses to a single\n // hook invocation (the once-per-namespace intent). Recovery is preserved —\n // one rejected hook never poisons subsequent notifications for that key.\n private readonly resolveSerializer = new MutationSerializer();\n // (namespace, storageDir) pairs whose resolve hook is currently pending. Set SYNCHRONOUSLY in\n // notifyResolved (before queueing) so a burst of concurrent storageFor()\n // cache hits collapses onto the one in-flight hook instead of each enqueuing\n // its own task. Cleared when the queued hook settles. Without this, a dropped\n // hook (returns false on a rebuild-lock timeout) leaves notifiedResolved\n // unset, so every queued sibling task would re-run the hook — N serial lock\n // waits (cursor Medium 06f58a7c, codex P2).\n private readonly inFlightResolveHooks = new Set<string>();\n // Tracks every in-flight resolve-hook promise so callers can deterministically\n // await the fire-and-forget registrations that `storageFor()` kicks off (see\n // `whenResolveHooksSettled`). Entries are removed as each hook settles, so the\n // set holds at most one promise per concurrently-resolving namespace.\n private readonly pendingResolveHooks = new Set<Promise<unknown>>();\n // Pending post-write catalog touch promises (#1522). Like pendingResolveHooks,\n // lets tests await fire-and-forget write touches deterministically.\n private readonly pendingWriteTouches = new Set<Promise<unknown>>();\n\n // Normalized (trimmed) default namespace identity (NH-FH). `storageFor`\n // normalizes its input, so default-namespace branches must compare against the\n // normalized config default too — otherwise a whitespace-padded configured\n // default name routes the default namespace to a tokenized non-default root.\n private readonly defaultNamespaceIdentity: string;\n\n constructor(\n private readonly config: PluginConfig,\n private readonly hooks: NamespaceStorageRouterHooks = {},\n /** Catalog reference for post-write/read touches (issue #1522 chokepoint). */\n private readonly catalog?: NamespaceCatalog,\n ) {\n this.defaultNamespaceIdentity = normalizeNamespaceIdentity(config.defaultNamespace);\n }\n\n private async defaultNamespaceRoot(): Promise<string> {\n this.defaultNsRootResolved = await resolveDefaultNamespaceRoot(this.config);\n return this.defaultNsRootResolved;\n }\n\n private async namespaceRoot(namespace: string): Promise<string> {\n // NOTE: only used after defaultNamespaceRoot() resolution.\n if (!resolveNamespaceCapabilities(this.config).namespaces) return this.config.memoryDir;\n if (normalizeNamespaceIdentity(namespace) === this.defaultNamespaceIdentity) {\n return this.defaultNsRootResolved ?? this.config.memoryDir;\n }\n return resolveNamespaceStorageRoot(this.config, namespace);\n }\n\n async storageFor(namespace: string): Promise<StorageManager> {\n const ns = normalizeNamespaceIdentity(namespace || this.config.defaultNamespace);\n if (ns !== this.defaultNamespaceIdentity && !isSafeRouteNamespace(ns)) {\n throw new Error(`unsafe namespace: ${ns}`);\n }\n // Even when the default namespace is exempt from the check above, every\n // on-disk path is built through resolveNamespaceDir(), which rejects\n // traversal segments — so an unsafe configured default still cannot escape\n // <memoryDir>/namespaces (CodeQL js/path-injection).\n\n let root: string;\n if (ns === this.defaultNamespaceIdentity) {\n root = await this.defaultNamespaceRoot();\n const cached = this.cache.get(ns);\n if (cached && cached.dir === root) {\n this.notifyResolved(ns, root);\n return cached;\n }\n } else {\n const cached = this.cache.get(ns);\n root = await this.namespaceRoot(ns);\n if (cached && cached.dir === root) {\n this.notifyResolved(ns, root);\n return cached;\n }\n }\n\n const sm = new StorageManager(root, this.config.entitySchemas);\n // Propagate the inline-attribution template so that router-created storages\n // (used by extraction and shared-promotion paths) strip citations consistently,\n // matching the behaviour of the primary this.storage instance in the orchestrator.\n sm.citationTemplate = this.config.inlineSourceAttributionFormat;\n // #1522: install the post-write catalog touch at the chokepoint — every\n // successful write on this StorageManager records the namespace touch.\n this.bindCatalogWriteHook(sm, ns);\n // #1579: apply the tombstone non-resurrection config so every namespace\n // storage enforces the invariant at its own writeMemory chokepoint.\n this.applyTombstonesConfig(sm, ns);\n this.cache.set(ns, sm);\n this.notifyResolved(ns, root);\n return sm;\n }\n\n /**\n * Fire the resolve hook defensively. A hook failure (e.g. a catalog write\n * error) MUST NOT crash storage resolution — see CLAUDE.md gotcha #13.\n *\n * Issue #1524 adoption: hook invocations for the SAME namespace are now\n * strictly ordered through the shared `MutationSerializer` rather than the\n * bespoke `inFlightResolved` marker-then-clear pattern. The serializer\n * guarantees one in-flight hook per namespace; a concurrent burst of\n * `storageFor()` cache hits collapses to a single hook invocation because\n * each queued task re-checks `notifiedResolved` before invoking the hook. A\n * dropped (`false`) or rejected hook leaves `notifiedResolved` unset so the\n * next `storageFor()` retries — the serializer recovers from the rejection,\n * so a failed hook never poisons later notifications.\n */\n private notifyResolved(namespace: string, storageDir: string): void {\n const hook = this.hooks.onResolve;\n if (!hook) return;\n // Permanent dedup: skip once we've SUCCESSFULLY notified this exact\n // (namespace, storageDir). A changed dir (rare: migration/realignment)\n // still re-fires once. The mark is set ONLY AFTER the hook succeeds, so a\n // dropped registration (e.g. rebuild-lock timeout) is RETRIED on the next\n // cache hit instead of being suppressed forever (round 6, cursor Medium —\n // ND3EJ).\n if (this.notifiedResolved.get(namespace) === storageDir) return;\n // In-flight dedup (cursor Medium 06f58a7c, codex P2): if a hook for THIS\n // namespace is already pending, collapse this call onto it instead of\n // enqueueing another task. The serializer strictly orders queued tasks, but\n // ordering alone is not enough — when the first hook returns `false`\n // (dropped touch, e.g. rebuild-lock timeout), `notifiedResolved` stays\n // unset, so each queued sibling task would pass its re-check and re-run the\n // hook. With the real catalog hook each retry can spend the full lock wait,\n // so N cache hits during a rebuild leave N serial background lock attempts.\n // Collapsing here means at most ONE hook runs per in-flight registration;\n // its result (set `notifiedResolved` on success, leave unset on drop)\n // decides whether a LATER `storageFor()` retries — collapsing loses\n // nothing because the drop is already retried on the next cache hit.\n // Keyed by the composite (namespace, storageDir) so a CHANGED dir\n // (migration/realignment) for the same namespace still gets its own hook —\n // it is NOT collapsed onto the old dir's pending registration (cursor\n // Medium, codex P2).\n const inFlightKey = namespace + \"\\u0000\" + storageDir;\n if (this.inFlightResolveHooks.has(inFlightKey)) return;\n this.inFlightResolveHooks.add(inFlightKey);\n // Queue through the serializer. Concurrent calls for the same namespace\n // strictly order here; the 2nd call's task runs only after the 1st's hook\n // settles, by which point `notifiedResolved` is either set (no-op) or still\n // unset (retry). The returned promise is tracked for\n // `whenResolveHooksSettled()`. Rejections from the task body are caught so\n // they never reach the caller (best-effort hook contract); the serializer's\n // recovered tail still lets subsequent notifications run.\n const task = async (): Promise<void> => {\n // Re-check after queueing: a prior task in this same chain may have just\n // marked the pair as notified.\n if (this.notifiedResolved.get(namespace) === storageDir) return;\n try {\n // Hook may be sync or async; Promise.resolve normalizes both. A result\n // of `false` means the registration was dropped/no-op (e.g. rebuild-lock\n // timeout) — leave notifiedResolved UNSET so the next storageFor retries\n // (round 6, codex P2 — NEFoX). `void`/`undefined` is success for legacy\n // hooks. A rejection leaves notifiedResolved unset for the same reason.\n const persisted = await Promise.resolve(hook(namespace, storageDir));\n if (persisted !== false) {\n this.notifiedResolved.set(namespace, storageDir);\n }\n } catch {\n // Best-effort: a hook failure MUST NOT crash storage resolution. Leave\n // notifiedResolved unset so a later storageFor retries the registration.\n }\n };\n const queued = this.resolveSerializer.serialize(namespace, task);\n this.pendingResolveHooks.add(queued);\n // Clear the in-flight marker when the hook settles so a subsequent\n // storageFor() can retry after a drop, or short-circuit via notifiedResolved\n // after a success.\n const cleanup = (): void => {\n this.inFlightResolveHooks.delete(inFlightKey);\n this.pendingResolveHooks.delete(queued);\n };\n void queued.then(cleanup, cleanup);\n }\n\n /**\n * Install the post-write catalog touch hook on an externally-constructed\n * StorageManager (issue #1522). Used by the orchestrator for the legacy\n * default-namespace storage (`this.storage`) that bypasses the router.\n */\n bindCatalogWriteHook(sm: StorageManager, namespace: string): void {\n sm.onCatalogWrite = () => this.touchCatalogWrite(namespace, sm.dir);\n }\n\n /**\n * Install the tombstone config on an externally-constructed StorageManager\n * (issue #1579). Mirrors `bindCatalogWriteHook` — used for the legacy\n * default-namespace storage that bypasses the router. Router-created\n * storages are wired inline in `storageFor()` via `applyTombstonesConfig`.\n */\n bindTombstonesConfig(\n sm: StorageManager,\n namespace: string,\n config: { enabled: boolean; semanticMatch: boolean; semanticThreshold: number },\n ): void {\n this.tombstonesGlobalConfig = { ...config };\n sm.setTombstonesConfig({ ...config, namespace });\n }\n\n private tombstonesGlobalConfig: {\n enabled: boolean;\n semanticMatch: boolean;\n semanticThreshold: number;\n } = { enabled: false, semanticMatch: false, semanticThreshold: 0.9 };\n\n /**\n * Apply the tombstone config to a router-created StorageManager. Called\n * inline in `storageFor()` so every namespace storage enforces the\n * non-resurrection invariant, namespace-scoped (rule 42).\n */\n private applyTombstonesConfig(sm: StorageManager, namespace: string): void {\n sm.setTombstonesConfig({ ...this.tombstonesGlobalConfig, namespace });\n }\n\n /**\n * Post-write catalog touch (issue #1522 chokepoint). Called by every\n * StorageManager's post-write hook AFTER a successful write. Best-effort\n * and failure-tolerant — a catalog error MUST NOT affect the primary write\n * (gotcha #13, rule #40). Fire-and-forget by design.\n */\n private touchCatalogWrite(namespace: string, storageDir: string): void {\n if (!this.catalog) return;\n const touch = this.catalog\n .markWrite(namespace, { discoveredBy: \"write\", storageDir })\n .catch(() => undefined);\n this.pendingWriteTouches.add(touch);\n void touch.then(\n () => { this.pendingWriteTouches.delete(touch); },\n () => { this.pendingWriteTouches.delete(touch); },\n );\n }\n\n /**\n * Record a namespace read in the catalog (issue #1522 chokepoint move).\n * Best-effort and failure-tolerant. Used by recall paths so the read touch\n * lives in the storage layer, not at the caller.\n */\n recordRead(namespace: string, storageDir?: string): void {\n if (!this.catalog) return;\n const ns = normalizeNamespaceIdentity(namespace || this.config.defaultNamespace);\n void this.catalog\n .markRead(ns, { discoveredBy: \"read\", storageDir })\n .catch(() => undefined);\n }\n /**\n * Record a namespace write touch in the catalog (issue #1522). Best-effort\n * and failure-tolerant. Used by consolidation/cleanup passes that may mutate\n * the store via delete-only paths (e.g. entity-file merges, TTL cleanup) so\n * the namespace's lastWriteAt stays fresh even when no explicit write went\n * through the storage chokepoint. This is NOT a substitute for the chokepoint\n * — it's a belt-and-suspenders for paths the chokepoint doesn't cover.\n */\n recordWrite(namespace: string, storageDir?: string): void {\n if (!this.catalog) return;\n const ns = normalizeNamespaceIdentity(namespace || this.config.defaultNamespace);\n const touch = this.catalog\n .markWrite(ns, { discoveredBy: \"write\", storageDir })\n .catch(() => undefined);\n this.pendingWriteTouches.add(touch);\n void touch.then(\n () => { this.pendingWriteTouches.delete(touch); },\n () => { this.pendingWriteTouches.delete(touch); },\n );\n }\n\n /**\n * Resolve once every in-flight post-write catalog touch has settled (#1522).\n * Mirrors `whenResolveHooksSettled()`: the StorageManager's post-write hook\n * fires the catalog touch fire-and-forget, so tests asserting lastWriteAt\n * moved should await this instead of racing a timer.\n */\n async whenWriteTouchesSettled(): Promise<void> {\n while (this.pendingWriteTouches.size > 0) {\n await Promise.allSettled([...this.pendingWriteTouches]);\n }\n }\n\n /**\n * Resolve once every in-flight `onResolve` registration has settled.\n *\n * `storageFor()` fires the resolve hook fire-and-forget, so its catalog side\n * effect (e.g. `registerResolved(...)`) is not observable the moment\n * `storageFor()` returns. Callers that must act on that side effect — notably\n * tests asserting the catalog was updated — should await this instead of\n * racing a timer. Resolves immediately when no hook is registered or nothing\n * is in flight. The loop re-checks because a settling hook could, in\n * principle, trigger a follow-on resolution.\n */\n async whenResolveHooksSettled(): Promise<void> {\n while (this.pendingResolveHooks.size > 0) {\n await Promise.allSettled([...this.pendingResolveHooks]);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,QAAQ,OAAO,eAAe;AASvC,eAAe,OAAO,GAA6B;AACjD,MAAI;AACF,UAAM,OAAO,CAAC;AACd,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,eAAe,iBAAiB,GAA6B;AAC3D,MAAI;AACF,UAAM,QAAQ,MAAM,MAAM,CAAC;AAC3B,QAAI,MAAM,eAAe,EAAG,QAAO;AACnC,QAAI,CAAC,MAAM,YAAY,EAAG,QAAO;AACjC,UAAM,WAAW,MAAM,QAAQ,GAAG,EAAE,eAAe,KAAK,CAAC;AACzD,eAAW,SAAS,UAAU;AAC5B,YAAM,YAAY,KAAK,KAAK,GAAG,MAAM,IAAI;AACzC,UAAI,MAAM,eAAe,KAAK,MAAM,OAAO,EAAG,QAAO;AACrD,UAAI,MAAM,YAAY,KAAM,MAAM,iBAAiB,SAAS,EAAI,QAAO;AAAA,IACzE;AACA,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAQA,SAAS,oBAAoB,WAAmB,SAAyB;AAIvE,MACE,QAAQ,WAAW,KACnB,QAAQ,SAAS,GAAG,KACpB,QAAQ,SAAS,IAAI,KACrB,QAAQ,SAAS,IAAI,KACrB,KAAK,WAAW,OAAO,GACvB;AACA,UAAM,IAAI,MAAM,kCAAkC,OAAO,EAAE;AAAA,EAC7D;AACA,SAAO,KAAK,KAAK,WAAW,cAAc,OAAO;AACnD;AAEA,IAAM,oCAAoC;AAAA,EACxC,GAAG;AAAA,EACH;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AA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C;AAAA,IACxD;AAAA,EACF;AACF;","names":[]}
@@ -1,3 +1,6 @@
1
+ import {
2
+ resolveNamespaceCapabilities
3
+ } from "./chunk-JWDE7OVJ.js";
1
4
  import {
2
5
  isLikelyUnsafeRegex
3
6
  } from "./chunk-U3PN77QT.js";
@@ -13,7 +16,7 @@ function compileSafePrincipalRegex(pattern) {
13
16
  }
14
17
  }
15
18
  function resolvePrincipal(sessionKey, config) {
16
- if (!config.namespacesEnabled) return "default";
19
+ if (!resolveNamespaceCapabilities(config).namespaces) return "default";
17
20
  const sk = typeof sessionKey === "string" && sessionKey.trim().length > 0 ? sessionKey : "";
18
21
  const mode = config.principalFromSessionKeyMode;
19
22
  const rules = config.principalFromSessionKeyRules ?? [];
@@ -44,28 +47,28 @@ function resolvePrincipal(sessionKey, config) {
44
47
  return "default";
45
48
  }
46
49
  function canReadNamespace(principal, namespace, config) {
47
- if (!config.namespacesEnabled) return true;
50
+ if (!resolveNamespaceCapabilities(config).namespaces) return true;
48
51
  if (!principal) return false;
49
52
  const policy = config.namespacePolicies.find((p) => p.name === namespace);
50
53
  if (!policy) return namespace === config.defaultNamespace || namespace === config.sharedNamespace;
51
54
  return policy.readPrincipals.includes(principal) || policy.readPrincipals.includes("*");
52
55
  }
53
56
  function canWriteNamespace(principal, namespace, config) {
54
- if (!config.namespacesEnabled) return true;
57
+ if (!resolveNamespaceCapabilities(config).namespaces) return true;
55
58
  if (!principal) return false;
56
59
  const policy = config.namespacePolicies.find((p) => p.name === namespace);
57
60
  if (!policy) return namespace === config.defaultNamespace;
58
61
  return policy.writePrincipals.includes(principal) || policy.writePrincipals.includes("*");
59
62
  }
60
63
  function defaultNamespaceForPrincipal(principal, config) {
61
- if (!config.namespacesEnabled) return config.defaultNamespace;
64
+ if (!resolveNamespaceCapabilities(config).namespaces) return config.defaultNamespace;
62
65
  if (!principal) return config.defaultNamespace;
63
66
  const exists = config.namespacePolicies.some((p) => p.name === principal);
64
67
  return exists ? principal : config.defaultNamespace;
65
68
  }
66
69
  function recallNamespacesForPrincipal(principal, config) {
67
70
  const out = [];
68
- if (!config.namespacesEnabled) return [config.defaultNamespace];
71
+ if (!resolveNamespaceCapabilities(config).namespaces) return [config.defaultNamespace];
69
72
  if (!principal) return out;
70
73
  const selfNs = defaultNamespaceForPrincipal(principal, config);
71
74
  if (config.defaultRecallNamespaces.includes("self") && canReadNamespace(principal, selfNs, config)) {
@@ -89,4 +92,4 @@ export {
89
92
  defaultNamespaceForPrincipal,
90
93
  recallNamespacesForPrincipal
91
94
  };
92
- //# sourceMappingURL=chunk-UZYLX7M6.js.map
95
+ //# sourceMappingURL=chunk-OYHYBHHI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/namespaces/principal.ts"],"sourcesContent":["import { resolveNamespaceCapabilities } from \"../capabilities.js\";\nimport type { PluginConfig } from \"../types.js\";\nimport { isLikelyUnsafeRegex } from \"../routing/engine.js\";\n\nconst MAX_REGEX_SESSION_KEY_LENGTH = 512;\n\nfunction compileSafePrincipalRegex(pattern: string): RegExp | null {\n if (isLikelyUnsafeRegex(pattern)) return null;\n try {\n return new RegExp(pattern);\n } catch {\n return null;\n }\n}\n\nexport function resolvePrincipal(sessionKey: string | undefined, config: PluginConfig): string | undefined {\n if (!resolveNamespaceCapabilities(config).namespaces) return \"default\";\n const sk = typeof sessionKey === \"string\" && sessionKey.trim().length > 0\n ? sessionKey\n : \"\";\n const mode = config.principalFromSessionKeyMode;\n const rules = config.principalFromSessionKeyRules ?? [];\n\n if (!sk) return undefined;\n\n if (mode === \"prefix\") {\n for (const r of rules) {\n if (sk.startsWith(r.match)) return r.principal;\n }\n } else if (mode === \"map\") {\n for (const r of rules) {\n if (sk === r.match) return r.principal;\n }\n } else if (mode === \"regex\") {\n if (sk.length <= MAX_REGEX_SESSION_KEY_LENGTH) {\n for (const r of rules) {\n const re = compileSafePrincipalRegex(r.match);\n if (re?.test(sk)) {\n return r.principal;\n }\n }\n }\n }\n\n // Fallback heuristic: \"agent:<agentId>:<channelType>:...\"\n const parts = sk.split(\":\");\n if (parts.length >= 2 && parts[0] === \"agent\") {\n const agentId = parts[1];\n if (agentId && agentId.length > 0) return agentId;\n }\n return \"default\";\n}\n\nexport function canReadNamespace(principal: string | undefined, namespace: string, config: PluginConfig): boolean {\n if (!resolveNamespaceCapabilities(config).namespaces) return true;\n if (!principal) return false;\n const policy = config.namespacePolicies.find((p) => p.name === namespace);\n if (!policy) return namespace === config.defaultNamespace || namespace === config.sharedNamespace;\n return policy.readPrincipals.includes(principal) || policy.readPrincipals.includes(\"*\");\n}\n\nexport function canWriteNamespace(principal: string | undefined, namespace: string, config: PluginConfig): boolean {\n if (!resolveNamespaceCapabilities(config).namespaces) return true;\n if (!principal) return false;\n const policy = config.namespacePolicies.find((p) => p.name === namespace);\n if (!policy) return namespace === config.defaultNamespace;\n return policy.writePrincipals.includes(principal) || policy.writePrincipals.includes(\"*\");\n}\n\n/**\n * Default \"self\" namespace for a principal.\n *\n * Heuristic:\n * - If there's a namespace policy with the same name as the principal, use it.\n * - Otherwise use config.defaultNamespace.\n */\nexport function defaultNamespaceForPrincipal(principal: string | undefined, config: PluginConfig): string {\n if (!resolveNamespaceCapabilities(config).namespaces) return config.defaultNamespace;\n if (!principal) return config.defaultNamespace;\n const exists = config.namespacePolicies.some((p) => p.name === principal);\n return exists ? principal : config.defaultNamespace;\n}\n\nexport function recallNamespacesForPrincipal(principal: string | undefined, config: PluginConfig): string[] {\n const out: string[] = [];\n if (!resolveNamespaceCapabilities(config).namespaces) return [config.defaultNamespace];\n if (!principal) return out;\n\n const selfNs = defaultNamespaceForPrincipal(principal, config);\n if (config.defaultRecallNamespaces.includes(\"self\") && canReadNamespace(principal, selfNs, config)) {\n out.push(selfNs);\n }\n if (config.defaultRecallNamespaces.includes(\"shared\") && canReadNamespace(principal, config.sharedNamespace, config)) {\n out.push(config.sharedNamespace);\n }\n\n for (const p of config.namespacePolicies) {\n if (p.includeInRecallByDefault && canReadNamespace(principal, p.name, config)) {\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