@remnic/core 9.3.655 → 9.3.656

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 (247) hide show
  1. package/dist/access-cli.js +22 -22
  2. package/dist/access-http.d.ts +4 -4
  3. package/dist/access-http.js +10 -10
  4. package/dist/access-mcp.d.ts +4 -4
  5. package/dist/access-mcp.js +9 -9
  6. package/dist/access-schema.d.ts +10 -10
  7. package/dist/{access-service-BEJvriUt.d.ts → access-service-D_nbpexW.d.ts} +33 -2
  8. package/dist/access-service.d.ts +4 -4
  9. package/dist/access-service.js +8 -8
  10. package/dist/action-confidence.d.ts +1 -1
  11. package/dist/active-memory-bridge.d.ts +1 -1
  12. package/dist/active-recall.d.ts +1 -1
  13. package/dist/active-recall.js +1 -1
  14. package/dist/behavior-learner.d.ts +1 -1
  15. package/dist/behavior-signals.d.ts +1 -1
  16. package/dist/bootstrap.d.ts +3 -3
  17. package/dist/briefing.d.ts +1 -1
  18. package/dist/briefing.js +3 -3
  19. package/dist/buffer-surprise-report.d.ts +1 -1
  20. package/dist/buffer.d.ts +1 -1
  21. package/dist/calibration.d.ts +1 -1
  22. package/dist/causal-behavior.d.ts +1 -1
  23. package/dist/causal-consolidation.d.ts +1 -1
  24. package/dist/causal-consolidation.js +4 -4
  25. package/dist/{chunk-PVE7KSQP.js → chunk-2BD7DG37.js} +2 -2
  26. package/dist/{chunk-54LOUIBE.js → chunk-2MXEVL75.js} +2 -2
  27. package/dist/{chunk-55ZMNKMQ.js → chunk-4UL7VPTD.js} +276 -57
  28. package/dist/chunk-4UL7VPTD.js.map +1 -0
  29. package/dist/{chunk-COVZLGMR.js → chunk-54XF2FY7.js} +17 -17
  30. package/dist/{chunk-UYNFWZWG.js → chunk-AGJKWOKV.js} +2 -2
  31. package/dist/{chunk-TDZSSJV4.js → chunk-AZBV4RRY.js} +1 -1
  32. package/dist/chunk-AZBV4RRY.js.map +1 -0
  33. package/dist/{chunk-KOI765XP.js → chunk-CTAV55JM.js} +241 -1
  34. package/dist/chunk-CTAV55JM.js.map +1 -0
  35. package/dist/{chunk-A3Y37UWI.js → chunk-DIBWFCLA.js} +3 -3
  36. package/dist/{chunk-QDVQ4AN2.js → chunk-DR67OK4E.js} +5 -5
  37. package/dist/{chunk-XBIACVCO.js → chunk-EC2AYKRX.js} +2 -2
  38. package/dist/{chunk-IQ53ZSXV.js → chunk-GCYFUTUC.js} +2 -2
  39. package/dist/{chunk-YYN3LIYA.js → chunk-GSHW5VVD.js} +5 -5
  40. package/dist/chunk-GYSYLGNE.js +650 -0
  41. package/dist/chunk-GYSYLGNE.js.map +1 -0
  42. package/dist/{chunk-NRBGRZW4.js → chunk-IOZ5WBWD.js} +2 -2
  43. package/dist/{chunk-NCSJKK23.js → chunk-JSVFEHLL.js} +7 -5
  44. package/dist/chunk-JSVFEHLL.js.map +1 -0
  45. package/dist/{chunk-7LWRCOP7.js → chunk-LZTFCAKE.js} +2 -2
  46. package/dist/{chunk-TEO46GMM.js → chunk-NXCK7DO7.js} +2 -2
  47. package/dist/{chunk-XOFXKASO.js → chunk-PEPHBH2W.js} +2 -2
  48. package/dist/{chunk-WDTUYOLS.js → chunk-QZRKNA5F.js} +2 -2
  49. package/dist/{chunk-PS3SYNHP.js → chunk-R5DB26G6.js} +2 -2
  50. package/dist/{chunk-5QD3QD76.js → chunk-RDW5G6DO.js} +659 -123
  51. package/dist/chunk-RDW5G6DO.js.map +1 -0
  52. package/dist/{chunk-BGKXTVNG.js → chunk-SWDHVH2P.js} +2 -2
  53. package/dist/{chunk-67G4T7KI.js → chunk-SXYCVRLK.js} +3 -3
  54. package/dist/{chunk-UCEABZZN.js → chunk-TFFZUFEP.js} +7 -5
  55. package/dist/chunk-TFFZUFEP.js.map +1 -0
  56. package/dist/{chunk-UCEDY5M7.js → chunk-TIJYQXDI.js} +2 -2
  57. package/dist/{chunk-2RCGZ67B.js → chunk-VAEAGTEQ.js} +3 -3
  58. package/dist/{chunk-XRKQOQLY.js → chunk-WIKMCJUR.js} +2 -2
  59. package/dist/{chunk-KZZ4YAEC.js → chunk-WWMHAMAY.js} +2 -2
  60. package/dist/{chunk-OKW6F5S5.js → chunk-YEZHZCUO.js} +4 -4
  61. package/dist/{chunk-5FOCXX5E.js → chunk-YVVQUAOO.js} +3 -3
  62. package/dist/{chunk-5FOCXX5E.js.map → chunk-YVVQUAOO.js.map} +1 -1
  63. package/dist/{chunk-3XGWCZ63.js → chunk-YXLT4EMM.js} +2 -2
  64. package/dist/{chunk-PTMJ2FH2.js → chunk-Z6UDTNY6.js} +2 -2
  65. package/dist/{cli-BGahB_d3.d.ts → cli-aYxSuPvP.d.ts} +3 -3
  66. package/dist/cli.d.ts +5 -5
  67. package/dist/cli.js +22 -22
  68. package/dist/compounding/engine.d.ts +1 -1
  69. package/dist/compounding/engine.js +3 -3
  70. package/dist/compounding/preference-consolidator.d.ts +1 -1
  71. package/dist/compression-optimizer.d.ts +1 -1
  72. package/dist/config.d.ts +1 -1
  73. package/dist/config.js +1 -1
  74. package/dist/connectors/codex-materialize-runner.d.ts +1 -1
  75. package/dist/connectors/codex-materialize-runner.js +3 -3
  76. package/dist/connectors/codex-materialize.d.ts +1 -1
  77. package/dist/connectors/index.d.ts +1 -1
  78. package/dist/connectors/index.js +3 -3
  79. package/dist/consolidation-provenance-check.d.ts +1 -1
  80. package/dist/consolidation-undo.d.ts +1 -1
  81. package/dist/contradiction/index.d.ts +1 -1
  82. package/dist/conversation-index/backend.d.ts +1 -1
  83. package/dist/conversation-index/chunker.d.ts +1 -1
  84. package/dist/conversation-index/faiss-adapter.d.ts +1 -1
  85. package/dist/conversation-index/indexer.d.ts +1 -1
  86. package/dist/conversation-index/search.d.ts +1 -1
  87. package/dist/day-summary.d.ts +1 -1
  88. package/dist/delinearize.d.ts +1 -1
  89. package/dist/direct-answer-wiring.d.ts +1 -1
  90. package/dist/direct-answer.d.ts +1 -1
  91. package/dist/embedding-fallback.d.ts +1 -1
  92. package/dist/enrichment/index.d.ts +1 -1
  93. package/dist/entity-retrieval.d.ts +1 -1
  94. package/dist/entity-retrieval.js +3 -3
  95. package/dist/entity-schema.d.ts +1 -1
  96. package/dist/explicit-capture.d.ts +3 -3
  97. package/dist/explicit-cue-recall.js +2 -2
  98. package/dist/extraction-judge-telemetry.d.ts +1 -1
  99. package/dist/extraction-judge-training.d.ts +1 -1
  100. package/dist/extraction-judge.d.ts +1 -1
  101. package/dist/extraction.d.ts +1 -1
  102. package/dist/fallback-llm.d.ts +1 -1
  103. package/dist/focused-list-recall.js +2 -2
  104. package/dist/identity-continuity.d.ts +1 -1
  105. package/dist/importance.d.ts +1 -1
  106. package/dist/index.d.ts +121 -121
  107. package/dist/index.js +32 -32
  108. package/dist/intent.d.ts +1 -1
  109. package/dist/lcm/engine.d.ts +1 -1
  110. package/dist/lcm/index.d.ts +1 -1
  111. package/dist/lcm/tools.d.ts +1 -1
  112. package/dist/lcm-fallback-read.js +1 -1
  113. package/dist/lifecycle.d.ts +1 -1
  114. package/dist/live-connectors-runner.d.ts +1 -1
  115. package/dist/local-llm.d.ts +1 -1
  116. package/dist/maintenance/memory-governance.d.ts +1 -1
  117. package/dist/maintenance/memory-governance.js +3 -3
  118. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +3 -3
  119. package/dist/maintenance/rebuild-memory-projection.js +4 -4
  120. package/dist/mcp-memory-inspector-app.d.ts +4 -4
  121. package/dist/memory-action-policy.d.ts +1 -1
  122. package/dist/memory-cache.d.ts +1 -1
  123. package/dist/memory-lifecycle-ledger-utils.d.ts +1 -1
  124. package/dist/memory-projection-store.d.ts +1 -1
  125. package/dist/memory-provenance.d.ts +1 -1
  126. package/dist/memory-worth-outcomes.d.ts +1 -1
  127. package/dist/models-json.d.ts +1 -1
  128. package/dist/namespaces/migrate.d.ts +1 -1
  129. package/dist/namespaces/migrate.js +4 -4
  130. package/dist/namespaces/principal.d.ts +1 -1
  131. package/dist/namespaces/search.d.ts +1 -1
  132. package/dist/namespaces/storage.d.ts +1 -1
  133. package/dist/namespaces/storage.js +3 -3
  134. package/dist/native-knowledge.d.ts +1 -1
  135. package/dist/operator-toolkit.d.ts +1 -1
  136. package/dist/operator-toolkit.js +7 -7
  137. package/dist/{orchestrator-BgzZlWxH.d.ts → orchestrator-D1wcmPNj.d.ts} +8 -2
  138. package/dist/orchestrator.d.ts +3 -3
  139. package/dist/orchestrator.js +18 -18
  140. package/dist/patterns-cli.d.ts +1 -1
  141. package/dist/policy-runtime.d.ts +1 -1
  142. package/dist/qmd-recall-cache.d.ts +1 -1
  143. package/dist/qmd.d.ts +1 -1
  144. package/dist/recall-disclosure-escalation.d.ts +1 -1
  145. package/dist/recall-explain-renderer.d.ts +1 -1
  146. package/dist/recall-explain-renderer.js +3 -3
  147. package/dist/recall-planner-llm.d.ts +1 -1
  148. package/dist/recall-state.d.ts +1 -1
  149. package/dist/recall-tag-filter.d.ts +1 -1
  150. package/dist/recall-xray-cli.d.ts +1 -1
  151. package/dist/recall-xray-cli.js +4 -4
  152. package/dist/recall-xray-renderer.d.ts +1 -1
  153. package/dist/recall-xray-renderer.js +3 -3
  154. package/dist/recall-xray.d.ts +1 -1
  155. package/dist/recall-xray.js +2 -2
  156. package/dist/resolve-auth-token.d.ts +1 -1
  157. package/dist/response-guidance-recall.js +2 -2
  158. package/dist/resume-bundles.js +2 -2
  159. package/dist/retrieval-agents.d.ts +1 -1
  160. package/dist/retrieval-tiers.d.ts +1 -1
  161. package/dist/routing/engine.d.ts +1 -1
  162. package/dist/routing/store.d.ts +1 -1
  163. package/dist/search/embed-helper.d.ts +1 -1
  164. package/dist/search/factory.d.ts +1 -1
  165. package/dist/search/index.d.ts +1 -1
  166. package/dist/search/lancedb-backend.d.ts +1 -1
  167. package/dist/search/meilisearch-backend.d.ts +1 -1
  168. package/dist/search/noop-backend.d.ts +1 -1
  169. package/dist/search/orama-backend.d.ts +1 -1
  170. package/dist/search/port.d.ts +1 -1
  171. package/dist/search/remote-backend.d.ts +1 -1
  172. package/dist/{semantic-consolidation-Z8d_uMq8.d.ts → semantic-consolidation-MWOdNtSE.d.ts} +1 -1
  173. package/dist/semantic-consolidation.d.ts +2 -2
  174. package/dist/semantic-consolidation.js +4 -4
  175. package/dist/semantic-rule-promotion.js +3 -3
  176. package/dist/semantic-rule-verifier.d.ts +3 -2
  177. package/dist/semantic-rule-verifier.js +5 -3
  178. package/dist/session-observer-bands.d.ts +1 -1
  179. package/dist/session-observer-state.d.ts +1 -1
  180. package/dist/shared-context/manager.d.ts +1 -1
  181. package/dist/signal.d.ts +1 -1
  182. package/dist/storage.d.ts +1 -1
  183. package/dist/storage.js +2 -2
  184. package/dist/summarizer.d.ts +1 -1
  185. package/dist/summary-snapshot.d.ts +1 -1
  186. package/dist/targeted-fact-recall.js +2 -2
  187. package/dist/temporal-supersession.d.ts +1 -1
  188. package/dist/temporal-validity.d.ts +1 -1
  189. package/dist/threading.d.ts +1 -1
  190. package/dist/tier-migration.d.ts +1 -1
  191. package/dist/tier-routing.d.ts +1 -1
  192. package/dist/topics.d.ts +1 -1
  193. package/dist/transcript.d.ts +1 -1
  194. package/dist/{types-2OPlQWJG.d.ts → types-CgcCpUrf.d.ts} +39 -1
  195. package/dist/types.d.ts +1 -1
  196. package/dist/types.js +1 -1
  197. package/dist/utility-runtime.d.ts +1 -1
  198. package/dist/verified-recall.d.ts +2 -1
  199. package/dist/verified-recall.js +5 -3
  200. package/package.json +1 -1
  201. package/src/access-service-observe-lcm-parity.test.ts +86 -1
  202. package/src/access-service-observe-scope.test.ts +283 -1
  203. package/src/access-service-raw-excerpt-read-gate.test.ts +53 -0
  204. package/src/access-service.ts +391 -93
  205. package/src/coding/coding-namespace.ts +0 -3
  206. package/src/config.ts +282 -0
  207. package/src/lcm-fallback-read.ts +2 -6
  208. package/src/namespaces/scope-profiles.test.ts +1074 -0
  209. package/src/namespaces/scope-profiles.ts +456 -0
  210. package/src/orchestrator-flush.test.ts +142 -0
  211. package/src/orchestrator-source-attribution.test.ts +73 -0
  212. package/src/orchestrator.ts +835 -163
  213. package/src/semantic-rule-verifier.ts +13 -6
  214. package/src/types.ts +52 -0
  215. package/src/verified-recall.ts +10 -6
  216. package/dist/chunk-55ZMNKMQ.js.map +0 -1
  217. package/dist/chunk-5QD3QD76.js.map +0 -1
  218. package/dist/chunk-KOI765XP.js.map +0 -1
  219. package/dist/chunk-MMJANTJX.js +0 -339
  220. package/dist/chunk-MMJANTJX.js.map +0 -1
  221. package/dist/chunk-NCSJKK23.js.map +0 -1
  222. package/dist/chunk-TDZSSJV4.js.map +0 -1
  223. package/dist/chunk-UCEABZZN.js.map +0 -1
  224. /package/dist/{chunk-PVE7KSQP.js.map → chunk-2BD7DG37.js.map} +0 -0
  225. /package/dist/{chunk-54LOUIBE.js.map → chunk-2MXEVL75.js.map} +0 -0
  226. /package/dist/{chunk-COVZLGMR.js.map → chunk-54XF2FY7.js.map} +0 -0
  227. /package/dist/{chunk-UYNFWZWG.js.map → chunk-AGJKWOKV.js.map} +0 -0
  228. /package/dist/{chunk-A3Y37UWI.js.map → chunk-DIBWFCLA.js.map} +0 -0
  229. /package/dist/{chunk-QDVQ4AN2.js.map → chunk-DR67OK4E.js.map} +0 -0
  230. /package/dist/{chunk-XBIACVCO.js.map → chunk-EC2AYKRX.js.map} +0 -0
  231. /package/dist/{chunk-IQ53ZSXV.js.map → chunk-GCYFUTUC.js.map} +0 -0
  232. /package/dist/{chunk-YYN3LIYA.js.map → chunk-GSHW5VVD.js.map} +0 -0
  233. /package/dist/{chunk-NRBGRZW4.js.map → chunk-IOZ5WBWD.js.map} +0 -0
  234. /package/dist/{chunk-7LWRCOP7.js.map → chunk-LZTFCAKE.js.map} +0 -0
  235. /package/dist/{chunk-TEO46GMM.js.map → chunk-NXCK7DO7.js.map} +0 -0
  236. /package/dist/{chunk-XOFXKASO.js.map → chunk-PEPHBH2W.js.map} +0 -0
  237. /package/dist/{chunk-WDTUYOLS.js.map → chunk-QZRKNA5F.js.map} +0 -0
  238. /package/dist/{chunk-PS3SYNHP.js.map → chunk-R5DB26G6.js.map} +0 -0
  239. /package/dist/{chunk-BGKXTVNG.js.map → chunk-SWDHVH2P.js.map} +0 -0
  240. /package/dist/{chunk-67G4T7KI.js.map → chunk-SXYCVRLK.js.map} +0 -0
  241. /package/dist/{chunk-UCEDY5M7.js.map → chunk-TIJYQXDI.js.map} +0 -0
  242. /package/dist/{chunk-2RCGZ67B.js.map → chunk-VAEAGTEQ.js.map} +0 -0
  243. /package/dist/{chunk-XRKQOQLY.js.map → chunk-WIKMCJUR.js.map} +0 -0
  244. /package/dist/{chunk-KZZ4YAEC.js.map → chunk-WWMHAMAY.js.map} +0 -0
  245. /package/dist/{chunk-OKW6F5S5.js.map → chunk-YEZHZCUO.js.map} +0 -0
  246. /package/dist/{chunk-3XGWCZ63.js.map → chunk-YXLT4EMM.js.map} +0 -0
  247. /package/dist/{chunk-PTMJ2FH2.js.map → chunk-Z6UDTNY6.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/access-service.ts","../src/procedural/procedure-miner.ts","../src/procedural/procedure-stats.ts"],"sourcesContent":["import { stat } from \"node:fs/promises\";\nimport * as nodeFs from \"node:fs/promises\";\nimport { constants as fsConstants } from \"node:fs\";\nimport { createHash } from \"node:crypto\";\nimport { ZodError } from \"zod\";\nimport { AccessIdempotencyStore, hashAccessIdempotencyPayload } from \"./access-idempotency.js\";\nimport { AccessAuditAdapter, type AccessAuditConfig, type AccessAuditResult } from \"./access-audit.js\";\nimport type { AnomalyDetectorResult } from \"./recall-audit-anomaly.js\";\nimport { resolveGitContext } from \"./coding/git-context.js\";\nimport {\n combineNamespaces,\n lcmSessionKeyForNamespace,\n projectTagProjectId,\n resolveCodingNamespaceOverlay,\n} from \"./coding/coding-namespace.js\";\nimport { WorkStorage } from \"./work/storage.js\";\nimport {\n exportWorkBoardMarkdown,\n exportWorkBoardSnapshot,\n importWorkBoardSnapshot,\n} from \"./work/board.js\";\nimport { wrapWorkLayerContext } from \"./work/boundary.js\";\nimport {\n persistExplicitCapture,\n queueExplicitCaptureForReview,\n validateExplicitCaptureInput,\n type ExplicitCaptureInput,\n type ValidExplicitCapture,\n} from \"./explicit-capture.js\";\nimport { CrossNamespaceBudget, type BudgetDecision } from \"./cross-namespace-budget.js\";\nimport { log } from \"./logger.js\";\nimport {\n buildQualityScore,\n buildProposedActions,\n groupActionsByStatus,\n listMemoryGovernanceRuns,\n readMemoryGovernanceRunArtifact,\n runMemoryGovernance,\n} from \"./maintenance/memory-governance.js\";\nimport { runProcedureMining } from \"./procedural/procedure-miner.js\";\nimport { displayErrorDetail } from \"./runtime/better-sqlite.js\";\nimport type { PatternReinforcementResult } from \"./maintenance/pattern-reinforcement.js\";\nimport type { LiveConnectorsRunSummary } from \"./live-connectors-runner.js\";\nimport type { WearablesService } from \"./wearables/service.js\";\nimport {\n computeProcedureStats,\n type ProcedureStatsReport,\n} from \"./procedural/procedure-stats.js\";\nimport {\n normalizeProjectionPreview,\n normalizeProjectionTags,\n} from \"./memory-projection-format.js\";\nimport {\n inferMemoryStatus,\n toMemoryPathRel,\n} from \"./memory-lifecycle-ledger-utils.js\";\nimport { getMemoryProjectionPath } from \"./memory-projection-store.js\";\nimport { canReadNamespace, canWriteNamespace, defaultNamespaceForPrincipal, recallNamespacesForPrincipal, resolvePrincipal } from \"./namespaces/principal.js\";\nimport { namespaceIdentityFromToken } from \"./namespaces/identity.js\";\nimport { namespaceCollectionName } from \"./namespaces/search.js\";\nimport { SecureStoreLockedError } from \"./secure-store/index.js\";\nimport { isPathInsideStorageRoot } from \"./storage-paths.js\";\nimport type { LastRecallSnapshot } from \"./recall-state.js\";\nimport type {\n GraphRecallSnapshot,\n IntentDebugSnapshot,\n Orchestrator,\n RecallInvocationOptions,\n} from \"./orchestrator.js\";\nimport { parseEntityFile, StorageManager } from \"./storage.js\";\nimport {\n buildGraphSnapshot,\n type GraphSnapshotRequest,\n type GraphSnapshotResponse,\n type GraphSnapshotNodeMetadata,\n} from \"./graph-snapshot.js\";\nimport * as nodePath from \"node:path\";\nimport {\n buildBriefing,\n FileCalendarSource,\n parseBriefingFocus,\n parseBriefingWindow,\n} from \"./briefing.js\";\nimport {\n getTrustZoneStoreStatus,\n isTrustZoneName,\n listTrustZoneRecords,\n promoteTrustZoneRecord,\n scoreTrustZoneProvenance,\n seedTrustZoneDemoDataset,\n summarizeTrustZonePromotionReadiness,\n type TrustZoneDemoSeedResult,\n type TrustZoneName,\n type TrustZonePromotionResult,\n type TrustZoneProvenanceScore,\n type TrustZoneRecord,\n type TrustZoneRecordKind,\n type TrustZoneSourceClass,\n type TrustZoneStoreStatus,\n} from \"./trust-zones.js\";\nimport type {\n EntityFile,\n MemoryFile,\n MemoryActionOutcome,\n CodingContext,\n MemoryActionType,\n MemoryLifecycleEvent,\n MemoryStatus,\n PluginConfig,\n RecallDisclosure,\n RecallPlanMode,\n} from \"./types.js\";\nimport { DEFAULT_RECALL_DISCLOSURE, isRecallDisclosure } from \"./types.js\";\nimport { estimateRecallTokens, type RecallXraySnapshot } from \"./recall-xray.js\";\nimport type {\n LcmMessagePartInput,\n MessagePartSourceFormat,\n} from \"./message-parts/index.js\";\nimport {\n applyTagFilter,\n normalizeTags,\n parseTagMatch,\n type TagMatchMode,\n} from \"./recall-tag-filter.js\";\nimport { decideDisclosureEscalation } from \"./recall-disclosure-escalation.js\";\nimport type { LocalLlmClient } from \"./local-llm.js\";\nimport type { FallbackLlmClient } from \"./fallback-llm.js\";\nimport type { SemanticDedupLookup } from \"./dedup/semantic.js\";\nimport { toRecallExplainJson } from \"./recall-explain-renderer.js\";\nimport {\n recordMemoryOutcome,\n type MemoryOutcomeKind,\n type RecordMemoryOutcomeResult,\n} from \"./memory-worth-outcomes.js\";\nimport { objectiveStateStoreOverrideForNamespace } from \"./objective-state.js\";\nimport { recordObjectiveStateSnapshotsFromObservedMessages } from \"./objective-state-writers.js\";\nimport {\n importCapsule as importCapsuleFn,\n type ImportCapsuleOptions,\n type ImportCapsuleResult,\n} from \"./transfer/capsule-import.js\";\nimport {\n exportCapsule as exportCapsuleFn,\n type ExportCapsuleOptions,\n type ExportCapsuleResult,\n} from \"./transfer/capsule-export.js\";\nimport {\n defaultCapsulesDir,\n type CapsuleListEntry,\n} from \"./capsule-cli.js\";\nimport {\n applyOfflineSyncFileContentChunk,\n applyOfflineSyncChangeset,\n buildOfflineSyncSnapshot,\n buildOfflineSyncSnapshotFromBase,\n buildOfflineSyncSnapshotForPaths,\n iterateOfflineSyncSnapshotFileRecords,\n OFFLINE_SYNC_SNAPSHOT_FORMAT,\n readOfflineSyncFileContentChunk,\n type OfflineSyncApplyFileContentChunkResult,\n type OfflineSyncApplyChangesetResult,\n type OfflineSyncFileRecord,\n type OfflineSyncFileContentChunk,\n type OfflineSyncFileState,\n type OfflineSyncSnapshot,\n} from \"./offline-sync.js\";\nimport {\n evaluateActionConfidence,\n type ActionConfidenceInput,\n type ActionConfidenceResult,\n} from \"./action-confidence.js\";\nimport { formatProfileTraceAscii } from \"./profiling.js\";\n\nexport class EngramAccessInputError extends Error {}\n\nfunction qmdCollectionPathParts(resultPath: string): {\n collection: string;\n relativePath: string;\n} | null {\n if (!resultPath || nodePath.isAbsolute(resultPath)) return null;\n const normalized = resultPath.replace(/\\\\/g, \"/\").replace(/^\\/+/, \"\");\n const slashIndex = normalized.indexOf(\"/\");\n if (slashIndex <= 0 || slashIndex >= normalized.length - 1) return null;\n const collection = normalized.slice(0, slashIndex);\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(collection)) return null;\n return {\n collection,\n relativePath: normalized.slice(slashIndex + 1),\n };\n}\n\nfunction qmdResultPathCandidates(\n storageDir: string,\n resultPath: string,\n): string[] {\n const candidates = new Set<string>();\n const storageRoot = nodePath.resolve(storageDir);\n const addCandidate = (candidate: string) => {\n const resolved = nodePath.resolve(candidate);\n if (isPathInsideStorageRoot(storageRoot, resolved)) {\n candidates.add(resolved);\n }\n };\n const addRelativeCandidates = (relativePath: string) => {\n const normalized = relativePath.replace(/\\\\/g, \"/\").replace(/^\\/+/, \"\");\n if (!normalized) return;\n addCandidate(nodePath.join(storageRoot, normalized));\n if (/^\\d{4}-\\d{2}-\\d{2}\\//.test(normalized)) {\n addCandidate(nodePath.join(storageRoot, \"facts\", normalized));\n }\n };\n\n if (nodePath.isAbsolute(resultPath)) {\n addCandidate(resultPath);\n } else {\n addRelativeCandidates(resultPath);\n }\n\n return [...candidates];\n}\n\ntype AccessProfilingReportRequest = {\n format?: string;\n limit?: number;\n};\n\ntype AccessProfilingReportResponse = {\n enabled: boolean;\n format?: \"ascii\" | \"json\";\n report?: string;\n traces?: unknown[];\n stats?: unknown;\n bottleneck?: string | null;\n reason?: string;\n message?: string;\n};\n\nlet cachedPackageVersion: string | null = null;\n\nasync function getPackageVersion(): Promise<string> {\n if (cachedPackageVersion !== null) return cachedPackageVersion;\n try {\n const raw = await nodeFs.readFile(new URL(\"../package.json\", import.meta.url), \"utf-8\");\n const parsed = JSON.parse(raw) as { version?: unknown };\n cachedPackageVersion = typeof parsed.version === \"string\" && parsed.version.length > 0\n ? parsed.version\n : \"unknown\";\n } catch {\n cachedPackageVersion = \"unknown\";\n }\n return cachedPackageVersion;\n}\n\nfunction normalizeTrustZoneInputError(error: unknown): EngramAccessInputError | null {\n const message = error instanceof Error ? error.message : null;\n if (!message) {\n return null;\n }\n if (\n /^sourceRecordId must /.test(message) ||\n /^promotionReason must /.test(message) ||\n /^recordedAt must /.test(message) ||\n /^trust zone promotion requires /.test(message) ||\n /^source trust-zone record not found: /.test(message) ||\n /^trust-zone promotion denied: /.test(message) ||\n /^trust zone demo seed requires /.test(message) ||\n /^unsupported trust-zone demo scenario: /.test(message)\n ) {\n return new EngramAccessInputError(message);\n }\n return null;\n}\n\nexport const ENGRAM_ACCESS_WRITE_SCHEMA_VERSION = 1;\n\nexport interface EngramAccessHealthResponse {\n ok: true;\n memoryDir: string;\n namespacesEnabled: boolean;\n defaultNamespace: string;\n searchBackend: string;\n qmdEnabled: boolean;\n qmd: EngramAccessQmdHealthResponse;\n nativeKnowledgeEnabled: boolean;\n projectionAvailable: boolean;\n}\n\nexport type EngramAccessQmdCollectionState =\n | \"present\"\n | \"missing\"\n | \"unknown\"\n | \"skipped\";\n\nexport interface EngramAccessQmdHealthResponse {\n enabled: boolean;\n active: boolean;\n degraded: boolean;\n mode: \"cli\" | \"daemon\" | \"fallback\" | \"disabled\" | \"not-selected\";\n collection: string;\n collectionState: EngramAccessQmdCollectionState;\n installedVersion: string | null;\n supportedVersion: string | null;\n supported: boolean | null;\n upgradeAvailable: boolean | null;\n doctorAvailable: boolean | null;\n debugStatus: string;\n}\n\nexport interface EngramAccessRecallRequest {\n query: string;\n sessionKey?: string;\n namespace?: string;\n authenticatedPrincipal?: string;\n idempotencyKey?: string;\n topK?: number;\n mode?: RecallPlanMode | \"auto\";\n includeDebug?: boolean;\n /**\n * Recall disclosure depth (issue #677). Selects how much content each\n * result returns: `\"chunk\"` (default), `\"section\"`, or `\"raw\"`. Omitting\n * this field is equivalent to passing `\"chunk\"` and preserves pre-#677\n * behavior. Surfaces (CLI / HTTP / MCP) and per-level token telemetry\n * are wired in subsequent PRs of #677.\n */\n disclosure?: RecallDisclosure;\n /**\n * Coding-agent context (issue #569). When a connector resolves a git\n * context for the session's cwd, it passes it here and the access service\n * attaches it to the orchestrator before recall so project- / branch-\n * scoped namespace overlays apply.\n *\n * Keyed by `sessionKey`; ignored when `sessionKey` is absent.\n */\n codingContext?: {\n projectId: string;\n branch: string | null;\n rootPath: string;\n defaultBranch: string | null;\n } | null;\n /**\n * Working directory of the calling agent session. When provided and no\n * `codingContext` is already attached to the session, the service resolves\n * git context from this path and attaches it automatically. This enables\n * Claude Code hooks (and any connector that knows its cwd) to get\n * project-scoped memory without explicitly constructing a `codingContext`.\n */\n cwd?: string;\n /**\n * Arbitrary project tag for non-git-based project scoping. When provided,\n * creates a `CodingContext` with `projectId: \"tag:<projectTag>\"`.\n * Useful for OpenClaw sessions where the whole workspace is one git repo\n * but different conversations correspond to different client projects.\n * Takes precedence over `cwd`-based git resolution but NOT over an\n * explicit `codingContext`.\n */\n projectTag?: string;\n /**\n * Historical recall pin (issue #680). ISO 8601 timestamp. When set,\n * the orchestrator filters out memories whose `valid_at` is after this\n * instant OR whose `invalid_at` is at-or-before this instant, so the\n * caller sees the corpus as it existed at `asOf`. Invalid values are\n * rejected here with `EngramAccessInputError` (CLAUDE.md rule 51).\n */\n asOf?: string;\n /**\n * Free-form recall tag filter (issue #689). When non-empty, recall results\n * whose frontmatter `tags` do not match are removed from the response.\n * Comparison is case-sensitive exact match against tags stored on each\n * memory's frontmatter (see `storage.ts` and `docs/tags.md`).\n */\n tags?: string[];\n /**\n * Match mode for `tags` (issue #689). `\"any\"` (default when omitted)\n * admits results that carry at least one filter tag. `\"all\"` requires\n * every filter tag to be present. Ignored when `tags` is absent or empty.\n */\n tagMatch?: \"any\" | \"all\";\n /**\n * Issue #681 — when `true`, bypasses the configured\n * `graphTraversalConfidenceFloor` for this recall and includes graph edges\n * below the floor in traversal. Useful for diagnostic queries that need to\n * surface results pruned by confidence decay. Default `false`.\n */\n includeLowConfidence?: boolean;\n}\n\n/**\n * Standalone request to attach / clear the coding context for a session\n * without performing a recall. Used by the Claude Code / Codex connectors\n * at session start, and by the `remnic.set_coding_context` MCP tool (PR 7).\n */\nexport interface EngramAccessSetCodingContextRequest {\n sessionKey: string;\n codingContext: {\n projectId: string;\n branch: string | null;\n rootPath: string;\n defaultBranch: string | null;\n } | null;\n}\n\nexport interface EngramAccessRecallResponse {\n query: string;\n sessionKey?: string;\n namespace: string;\n context: string;\n count: number;\n memoryIds: string[];\n results: EngramAccessMemorySummary[];\n recordedAt?: string;\n traceId?: string;\n plannerMode?: RecallPlanMode;\n fallbackUsed: boolean;\n sourcesUsed: string[];\n /**\n * Disclosure depth applied to this recall (issue #677). Reflects the\n * caller-requested level after defaulting; useful for surfaces that want\n * to render a \"served at depth X\" hint without re-deriving it. PR 1 of\n * #677 wires this end-to-end for plumbing only — section/raw payload\n * shaping ships in later PRs.\n */\n disclosure: RecallDisclosure;\n budgetsApplied?: LastRecallSnapshot[\"budgetsApplied\"];\n auditAnomalies?: AnomalyDetectorResult;\n budgetWarning?: BudgetDecision;\n latencyMs?: number;\n debug?: {\n snapshot?: LastRecallSnapshot;\n intent?: IntentDebugSnapshot | null;\n graph?: GraphRecallSnapshot | null;\n };\n}\n\nexport interface EngramAccessRecallExplainRequest {\n sessionKey?: string;\n namespace?: string;\n /** Caller principal for namespace access checks. Transport-bound; never from untrusted payloads. */\n authenticatedPrincipal?: string;\n}\n\nexport interface EngramAccessRecallExplainResponse {\n found: boolean;\n snapshot?: LastRecallSnapshot;\n intent?: IntentDebugSnapshot | null;\n graph?: GraphRecallSnapshot | null;\n}\n\nexport interface EngramAccessDaySummaryRequest {\n memories?: string;\n sessionKey?: string;\n namespace?: string;\n timeZone?: string;\n}\n\n/** Inputs accepted by the `remnic_briefing` MCP tool. */\nexport interface EngramAccessBriefingRequest {\n since?: string;\n focus?: string;\n namespace?: string;\n format?: \"markdown\" | \"json\";\n maxFollowups?: number;\n /** Caller principal for namespace access checks. Transport-bound — never from untrusted payloads. */\n principal?: string;\n}\n\n/** Response for `remnic_briefing`. */\nexport interface EngramAccessBriefingResponse {\n format: \"markdown\" | \"json\";\n window: { from: string; to: string };\n namespace: string;\n markdown: string;\n json: Record<string, unknown>;\n followupsUnavailableReason?: string;\n}\n\nexport interface EngramAccessMemoryRecord {\n id: string;\n path: string;\n category: string;\n status?: string;\n created?: string;\n updated?: string;\n content: string;\n frontmatter: MemoryFile[\"frontmatter\"];\n}\n\nexport interface EngramAccessMemorySummary {\n id: string;\n path: string;\n category: string;\n status: string;\n created?: string;\n updated?: string;\n tags: string[];\n entityRef?: string;\n preview: string;\n /**\n * Disclosure depth at which this result was served (issue #677). Set by\n * recall paths; omitted on non-recall surfaces (e.g. memory browse) where\n * the concept does not apply. PR 1 of #677 always reports the\n * request-level disclosure on recall results; per-result divergence is\n * reserved for the auto-escalation policy that ships in PR 4/4.\n */\n disclosure?: RecallDisclosure;\n /**\n * Full memory content (markdown body) — populated when `disclosure` is\n * `\"section\"` or `\"raw\"` (issue #677 PR 2/4). At `\"chunk\"` depth callers\n * only receive the short `preview`, preserving the cheap-by-default\n * recall payload. Browse/non-recall paths leave `content` undefined.\n */\n content?: string;\n /**\n * Raw transcript excerpts surfaced from the LCM archive when `disclosure`\n * is `\"raw\"` and the LCM engine is enabled (issue #677 PR 2/4). Each\n * entry is a per-message excerpt sized by the LCM archive's\n * configured excerpt window. Empty array when LCM is disabled or has\n * no matching transcript content. Always omitted at chunk/section.\n */\n rawExcerpts?: Array<{\n turnIndex: number;\n role: string;\n content: string;\n sessionId: string;\n }>;\n}\n\nexport interface EngramAccessMemoryBrowseRequest {\n query?: string;\n status?: string;\n category?: string;\n namespace?: string;\n authenticatedPrincipal?: string;\n sort?: \"updated_desc\" | \"updated_asc\" | \"created_desc\" | \"created_asc\";\n limit?: number;\n offset?: number;\n}\n\nexport interface EngramAccessMemoryBrowseResponse {\n namespace: string;\n sort: \"updated_desc\" | \"updated_asc\" | \"created_desc\" | \"created_asc\";\n total: number;\n count: number;\n limit: number;\n offset: number;\n memories: EngramAccessMemorySummary[];\n}\n\nexport interface EngramAccessMemoryResponse {\n found: boolean;\n namespace: string;\n memory?: EngramAccessMemoryRecord;\n}\n\nexport interface EngramAccessTimelineResponse {\n found: boolean;\n namespace: string;\n count: number;\n timeline: MemoryLifecycleEvent[];\n}\n\nexport interface EngramAccessEntitySummary {\n name: string;\n type: string;\n updated: string;\n summary?: string;\n aliases: string[];\n}\n\nexport interface EngramAccessEntityListResponse {\n namespace: string;\n total: number;\n count: number;\n limit: number;\n offset: number;\n entities: EngramAccessEntitySummary[];\n}\n\nexport interface EngramAccessEntityResponse {\n found: boolean;\n namespace: string;\n entity?: EntityFile;\n}\n\nexport interface EngramAccessReviewQueueResponse {\n found: boolean;\n namespace?: string;\n runId?: string;\n summary?: Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"summary\"];\n metrics?: Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"metrics\"];\n qualityScore?: Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"qualityScore\"];\n reviewQueue?: Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"reviewQueue\"];\n appliedActions?: Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"appliedActions\"];\n transitionReport?: Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"transitionReport\"];\n report?: string;\n}\n\nexport interface EngramAccessMaintenanceResponse {\n namespace: string;\n health: EngramAccessHealthResponse;\n latestGovernanceRun: EngramAccessReviewQueueResponse;\n}\n\nexport interface EngramAccessTrustZoneStatusResponse {\n namespace: string;\n status: TrustZoneStoreStatus;\n}\n\nexport interface EngramAccessTrustZoneRecordSummary {\n recordId: string;\n filePath: string;\n zone: TrustZoneName;\n recordedAt: string;\n kind: TrustZoneRecordKind;\n summary: string;\n sourceClass: TrustZoneSourceClass;\n sessionKey?: string;\n sourceId?: string;\n evidenceHashPresent: boolean;\n anchored: boolean;\n entityRefs: string[];\n tags: string[];\n metadata?: Record<string, string>;\n trustScore?: TrustZoneProvenanceScore;\n nextPromotionTarget?: TrustZoneName;\n nextPromotionAllowed: boolean;\n nextPromotionReasons: string[];\n corroborationCount?: number;\n corroborationSourceClasses?: TrustZoneSourceClass[];\n}\n\nexport interface EngramAccessTrustZoneBrowseRequest {\n query?: string;\n zone?: TrustZoneName;\n kind?: TrustZoneRecordKind;\n sourceClass?: TrustZoneSourceClass;\n namespace?: string;\n limit?: number;\n offset?: number;\n}\n\nexport interface EngramAccessTrustZoneBrowseResponse {\n namespace: string;\n total: number;\n count: number;\n limit: number;\n offset: number;\n records: EngramAccessTrustZoneRecordSummary[];\n}\n\nexport interface EngramAccessTrustZonePromoteRequest {\n recordId: string;\n targetZone: TrustZoneName;\n promotionReason: string;\n recordedAt?: string;\n summary?: string;\n dryRun?: boolean;\n namespace?: string;\n authenticatedPrincipal?: string;\n}\n\nexport interface EngramAccessTrustZonePromoteResponse extends TrustZonePromotionResult {\n namespace: string;\n dryRun: boolean;\n}\n\nexport interface EngramAccessTrustZoneDemoSeedRequest {\n scenario?: string;\n recordedAt?: string;\n dryRun?: boolean;\n namespace?: string;\n authenticatedPrincipal?: string;\n}\n\nexport interface EngramAccessTrustZoneDemoSeedResponse extends TrustZoneDemoSeedResult {\n namespace: string;\n}\n\nexport interface EngramAccessQualityResponse {\n namespace: string;\n totalMemories: number;\n statusCounts: Record<string, number>;\n categoryCounts: Record<string, number>;\n confidenceTierCounts: Record<string, number>;\n ageBucketCounts: Record<string, number>;\n archivePressure: {\n pendingReview: number;\n quarantined: number;\n archived: number;\n staleActive: number;\n lowConfidenceActive: number;\n };\n latestGovernanceRun: {\n found: boolean;\n runId?: string;\n qualityScore?: EngramAccessReviewQueueResponse[\"qualityScore\"];\n reviewQueueCount: number;\n };\n}\n\nexport interface EngramAccessCapsuleListResponse {\n namespace: string;\n capsulesDir: string;\n capsules: CapsuleListEntry[];\n}\n\nexport interface EngramAccessOfflineSyncSnapshotRequest {\n namespace?: string;\n principal?: string;\n includeTranscripts?: boolean;\n includeContent?: boolean;\n baseCapturedAt?: Date;\n baseFiles?: OfflineSyncFileState[];\n}\n\nexport interface EngramAccessOfflineSyncFilesRequest {\n namespace?: string;\n principal?: string;\n includeTranscripts?: boolean;\n paths: string[];\n}\n\nexport interface EngramAccessOfflineSyncFileContentRequest {\n namespace?: string;\n principal?: string;\n includeTranscripts?: boolean;\n path: string;\n offset?: number;\n length?: number;\n}\n\nexport interface EngramAccessOfflineSyncApplyFileContentRequest {\n namespace?: string;\n principal?: string;\n includeTranscripts?: boolean;\n sourceId: string;\n path: string;\n sha256: string;\n bytes: number;\n mtimeMs: number;\n offset?: number;\n baseSha256?: string;\n content: Buffer;\n}\n\nexport interface EngramAccessOfflineSyncApplyRequest {\n namespace?: string;\n principal?: string;\n changeset: unknown;\n returnCurrentFiles?: boolean;\n}\n\nexport interface EngramAccessOfflineSyncSnapshotResponse extends OfflineSyncSnapshot {\n namespace: string;\n}\n\nexport interface EngramAccessOfflineSyncSnapshotStreamResponse extends Omit<OfflineSyncSnapshot, \"files\"> {\n namespace: string;\n files: AsyncIterable<OfflineSyncFileRecord>;\n}\n\nexport interface EngramAccessOfflineSyncFilesResponse extends OfflineSyncSnapshot {\n namespace: string;\n}\n\nexport interface EngramAccessOfflineSyncFileContentResponse extends OfflineSyncFileContentChunk {\n namespace: string;\n}\n\nexport interface EngramAccessOfflineSyncApplyFileContentResponse extends OfflineSyncApplyFileContentChunkResult {\n namespace: string;\n}\n\nexport interface EngramAccessOfflineSyncApplyResponse extends OfflineSyncApplyChangesetResult {\n namespace: string;\n}\n\nexport type EngramAccessActionConfidenceRequest = ActionConfidenceInput;\nexport type EngramAccessActionConfidenceResponse = ActionConfidenceResult;\n\nasync function buildProjectedGovernanceProposedActions(\n storage: Awaited<ReturnType<Orchestrator[\"getStorage\"]>>,\n projected: NonNullable<Awaited<ReturnType<Awaited<ReturnType<Orchestrator[\"getStorage\"]>>[\"getProjectedGovernanceRecord\"]>>>,\n): Promise<Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"appliedActions\"]> {\n const reviewQueue = projected.reviewQueueRows.map((row) => ({\n entryId: row.entryId,\n memoryId: row.memoryId,\n path: row.path,\n reasonCode: row.reasonCode,\n severity: row.severity,\n suggestedAction: row.suggestedAction,\n suggestedStatus: row.suggestedStatus,\n relatedMemoryIds: row.relatedMemoryIds,\n })) as Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"reviewQueue\"];\n const memories = (await Promise.all(projected.reviewQueueRows.map((row) => storage.getMemoryById(row.memoryId))))\n .filter((memory): memory is MemoryFile => Boolean(memory));\n return buildProposedActions(reviewQueue, memories);\n}\n\nfunction hasGroupedGovernanceActions(\n grouped?: Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"transitionReport\"][\"proposed\"],\n): boolean {\n if (!grouped) return false;\n return Object.values(grouped).some((actions) => Array.isArray(actions) && actions.length > 0);\n}\n\nexport interface EngramAccessReviewDispositionRequest {\n memoryId: string;\n status: MemoryStatus | \"archived\";\n reasonCode: string;\n namespace?: string;\n /**\n * Trusted transport-bound principal. This must never come from untrusted client payloads.\n * When present, write authorization is evaluated against this principal instead of sessionKey.\n */\n authenticatedPrincipal?: string;\n}\n\nexport interface EngramAccessReviewDispositionResponse {\n ok: boolean;\n namespace: string;\n memoryId: string;\n status: MemoryStatus | \"archived\";\n previousStatus: MemoryStatus;\n currentPath?: string;\n}\n\nexport interface EngramAccessWriteEnvelope {\n schemaVersion?: number;\n idempotencyKey?: string;\n dryRun?: boolean;\n sessionKey?: string;\n /**\n * Trusted transport-bound principal. This must never come from untrusted client payloads.\n * When present, write authorization is evaluated against this principal instead of sessionKey.\n */\n authenticatedPrincipal?: string;\n}\n\n/**\n * Optional git/project context for project-scoped writes (#1434). When no\n * explicit `namespace` is supplied, these route the write to the same project\n * namespace recall/observe resolve from `cwd`/`projectTag` (rule 42 symmetry).\n */\nexport interface CodingScopedWriteInput {\n cwd?: string;\n projectTag?: string;\n}\n\n/**\n * Internal, single-resolution plan describing the effective memory scope for a\n * write-producing access request (#1495, seed for epic #1494). One plan is\n * resolved per request and EVERY side effect (LCM archival, extraction replay,\n * objective-state snapshot, response) consumes the same `writeNamespace`, so an\n * observed turn and its extracted memories never drift away from the namespace a\n * same-session project-scoped recall searches (rule 39 / 42).\n *\n * The resolver that produces this is READ-ONLY with respect to namespace\n * authorization: an explicit namespace is authorized through the existing\n * `canWriteNamespace` policy path, and a coding overlay is always REBUILT from\n * the authenticated principal's base — never accepted as a caller string — so a\n * caller can never reach another principal's overlay by forging an\n * overlay-shaped namespace (rule 42 / 47 / 48).\n */\nexport interface MemoryScopePlan {\n /** Resolved request principal (auth precedence applied), or undefined. */\n principal?: string;\n /** Explicit `namespace` supplied by the caller, if any (already authorized). */\n explicitNamespace?: string;\n /** Principal self base namespace before any coding overlay. */\n baseNamespace: string;\n /** Effective write namespace — what every side effect must use. */\n writeNamespace: string;\n /**\n * Effective namespace the objective-state snapshot writer must target.\n *\n * Objective-state has a STRICTER, pre-#1495 contract than the LCM/extraction\n * write path (#928): an IMPLICIT (no explicit `namespace`) snapshot is based\n * on the PRINCIPAL SELF namespace (`defaultNamespaceForPrincipal`) and is\n * authorized against THAT base (rule 48, least-privilege) — never silently\n * routed to `config.defaultNamespace`. Only the LCM/extraction/response path\n * collapses an unqualified write to `config.defaultNamespace` (memory_store\n * parity, rule 39). With an explicit namespace, or once a coding overlay\n * applies, both targets converge: `objectiveStateNamespace === writeNamespace`.\n *\n * Keeping the two as separate fields of ONE plan preserves rule 22 (single\n * resolution point) while honoring each consumer's historical contract.\n */\n objectiveStateNamespace: string;\n /** Namespaces a same-session recall would read (cheap subset). */\n readNamespaces: string[];\n /** Whether the coding overlay changed the base namespace. */\n codingOverlayApplied: boolean;\n /** Non-fatal diagnostics surfaced during resolution. */\n warnings: string[];\n}\n\nexport interface EngramAccessMemoryStoreRequest\n extends EngramAccessWriteEnvelope,\n ExplicitCaptureInput,\n CodingScopedWriteInput {}\n\nexport interface EngramAccessSuggestionSubmitRequest\n extends EngramAccessWriteEnvelope,\n ExplicitCaptureInput,\n CodingScopedWriteInput {}\n\nexport interface EngramAccessWriteResponse {\n schemaVersion: 1;\n operation: \"memory_store\" | \"suggestion_submit\";\n namespace: string;\n dryRun: boolean;\n accepted: boolean;\n queued: boolean;\n status: \"validated\" | \"stored\" | \"duplicate\" | \"queued_for_review\";\n memoryId?: string;\n duplicateOf?: string;\n idempotencyKey?: string;\n idempotencyReplay?: boolean;\n}\n\nexport interface EngramAccessObserveMessage {\n role: \"user\" | \"assistant\";\n content: string;\n parts?: LcmMessagePartInput[];\n rawContent?: unknown;\n sourceFormat?: MessagePartSourceFormat;\n}\n\nexport interface EngramAccessObserveRequest {\n sessionKey: string;\n messages: EngramAccessObserveMessage[];\n namespace?: string;\n authenticatedPrincipal?: string;\n skipExtraction?: boolean;\n /**\n * Working directory of the calling agent session (issue #569 wiring).\n * When provided and no `codingContext` is attached for this session,\n * resolves git context from the path and attaches it so writes route to\n * the correct project namespace.\n */\n cwd?: string;\n /**\n * Arbitrary project tag for non-git-based project scoping (issue #569).\n * Creates a `CodingContext` with `projectId: \"tag:<projectTag>\"`.\n */\n projectTag?: string;\n}\n\n/**\n * Additive diagnostic view of the effective {@link MemoryScopePlan} resolved for\n * an `observe` request (#1495 / epic #1494). Lets callers and tests inspect\n * which namespace the operation actually wrote to without changing the\n * backward-compatible `namespace` field. Purely informational — never gates\n * authorization.\n */\nexport interface EngramAccessScopeDebug {\n /** Resolved principal, or `undefined` when none could be derived. */\n principal?: string;\n /** Explicit `namespace` from the request, if one was supplied. */\n explicitNamespace?: string;\n /** Principal self base before any coding overlay. */\n baseNamespace: string;\n /** Effective write namespace every side effect of the request uses. */\n writeNamespace: string;\n /** Whether the coding (project/branch) overlay changed the base namespace. */\n codingOverlayApplied: boolean;\n /** Namespaces a same-session recall would read, when cheap to compute. */\n readNamespaces?: string[];\n}\n\nexport interface EngramAccessObserveResponse {\n accepted: number;\n sessionKey: string;\n /**\n * Backward-compatible base writable namespace (pre-#1495 semantics). Kept\n * unchanged so existing callers/tests are not broken. The namespace the\n * operation ACTUALLY wrote to is {@link EngramAccessObserveResponse.effectiveNamespace}.\n */\n namespace: string;\n /**\n * Effective write namespace every memory-producing side effect of this\n * request used (LCM archival, extraction replay, objective-state snapshot).\n * Equals the namespace a same-session project-scoped recall searches (#1495).\n */\n effectiveNamespace: string;\n /** Additive diagnostic view of the resolved scope plan (#1495). */\n scopeDebug?: EngramAccessScopeDebug;\n lcmArchived: boolean;\n extractionQueued: boolean;\n}\n\nexport interface EngramAccessLcmSearchRequest {\n query: string;\n sessionKey?: string;\n sessionPrefix?: string;\n namespace?: string;\n limit?: number;\n authenticatedPrincipal?: string;\n}\n\nexport interface EngramAccessLcmSearchResponse {\n query: string;\n namespace: string;\n results: Array<{ sessionId: string; content: string; turnIndex?: number }>;\n count: number;\n lcmEnabled: boolean;\n}\n\nexport interface EngramAccessLcmStatusResponse {\n enabled: boolean;\n archiveAvailable: boolean;\n stats?: { totalTurns?: number };\n}\n\nexport interface EngramAccessLcmCompactionFlushRequest {\n sessionKey: string;\n namespace?: string;\n authenticatedPrincipal?: string;\n}\n\nexport interface EngramAccessLcmCompactionFlushResponse {\n enabled: boolean;\n flushed: boolean;\n sessionKey: string;\n namespace: string;\n reason?: string;\n}\n\nexport interface EngramAccessLcmCompactionRecordRequest {\n sessionKey: string;\n namespace?: string;\n tokensBefore: number;\n tokensAfter: number;\n authenticatedPrincipal?: string;\n}\n\nexport interface EngramAccessLcmCompactionRecordResponse {\n enabled: boolean;\n recorded: boolean;\n sessionKey: string;\n namespace: string;\n reason?: string;\n}\n\ntype EngramAccessIdempotencyStatus = \"miss\" | \"replay\" | \"conflict\";\n\nfunction normalizePagination(limit?: number, offset?: number): { limit: number; offset: number } {\n const normalizedLimit = Number.isFinite(limit) ? Math.max(1, Math.min(200, Math.floor(limit ?? 50))) : 50;\n const normalizedOffset = Number.isFinite(offset) ? Math.max(0, Math.floor(offset ?? 0)) : 0;\n return { limit: normalizedLimit, offset: normalizedOffset };\n}\n\nfunction normalizeBrowseSort(\n sort?: EngramAccessMemoryBrowseRequest[\"sort\"],\n): NonNullable<EngramAccessMemoryBrowseRequest[\"sort\"]> {\n switch (sort) {\n case \"updated_asc\":\n case \"created_desc\":\n case \"created_asc\":\n return sort;\n case \"updated_desc\":\n default:\n return \"updated_desc\";\n }\n}\n\nfunction bucketMemoryAge(referenceIso: string | undefined, nowMs: number): string {\n const referenceMs = referenceIso ? Date.parse(referenceIso) : Number.NaN;\n if (!Number.isFinite(referenceMs)) return \"unknown\";\n const ageDays = Math.floor((nowMs - referenceMs) / 86_400_000);\n if (ageDays <= 7) return \"0_7_days\";\n if (ageDays <= 30) return \"8_30_days\";\n if (ageDays <= 90) return \"31_90_days\";\n return \"91_plus_days\";\n}\n\nfunction incrementCount(counts: Record<string, number>, key: string): void {\n counts[key] = (counts[key] ?? 0) + 1;\n}\n\nfunction summarizeTrustZoneRecord(\n record: TrustZoneRecord,\n filePath: string,\n allRecords: TrustZoneRecord[],\n poisoningDefenseEnabled: boolean,\n trustZonesEnabled: boolean,\n promotionEnabled: boolean,\n): EngramAccessTrustZoneRecordSummary {\n const trustScore = poisoningDefenseEnabled ? scoreTrustZoneProvenance(record) : undefined;\n const readiness = summarizeTrustZonePromotionReadiness({\n record,\n allRecords,\n poisoningDefenseEnabled,\n });\n const promotionReasons = [...readiness.reasons];\n const promotionAllowed = readiness.allowed && trustZonesEnabled === true && promotionEnabled === true;\n if (trustZonesEnabled !== true) {\n promotionReasons.push(\"trust zone promotion requires trustZonesEnabled=true\");\n }\n if (promotionEnabled !== true) {\n promotionReasons.push(\"trust zone promotion requires quarantinePromotionEnabled=true\");\n }\n return {\n recordId: record.recordId,\n filePath,\n zone: record.zone,\n recordedAt: record.recordedAt,\n kind: record.kind,\n summary: record.summary,\n sourceClass: record.provenance.sourceClass,\n sessionKey: record.provenance.sessionKey,\n sourceId: record.provenance.sourceId,\n evidenceHashPresent: typeof record.provenance.evidenceHash === \"string\",\n anchored: Boolean(record.provenance.sourceId && record.provenance.evidenceHash),\n entityRefs: [...(record.entityRefs ?? [])],\n tags: [...(record.tags ?? [])],\n metadata: record.metadata,\n trustScore,\n nextPromotionTarget: readiness.nextTargetZone,\n nextPromotionAllowed: promotionAllowed,\n nextPromotionReasons: promotionReasons,\n corroborationCount: readiness.requiresCorroboration ? readiness.corroborationCount : undefined,\n corroborationSourceClasses: readiness.requiresCorroboration ? readiness.corroborationSourceClasses : undefined,\n };\n}\n\nfunction compareBrowseMemory(\n sort: NonNullable<EngramAccessMemoryBrowseRequest[\"sort\"]>,\n left: MemoryFile,\n right: MemoryFile,\n): number {\n const leftUpdated = left.frontmatter.updated ?? left.frontmatter.created ?? \"\";\n const rightUpdated = right.frontmatter.updated ?? right.frontmatter.created ?? \"\";\n const leftCreated = left.frontmatter.created ?? \"\";\n const rightCreated = right.frontmatter.created ?? \"\";\n\n switch (sort) {\n case \"updated_asc\":\n return (\n leftUpdated.localeCompare(rightUpdated) ||\n leftCreated.localeCompare(rightCreated) ||\n left.frontmatter.id.localeCompare(right.frontmatter.id)\n );\n case \"created_desc\":\n return (\n rightCreated.localeCompare(leftCreated) ||\n rightUpdated.localeCompare(leftUpdated) ||\n left.frontmatter.id.localeCompare(right.frontmatter.id)\n );\n case \"created_asc\":\n return (\n leftCreated.localeCompare(rightCreated) ||\n leftUpdated.localeCompare(rightUpdated) ||\n left.frontmatter.id.localeCompare(right.frontmatter.id)\n );\n case \"updated_desc\":\n default:\n return (\n rightUpdated.localeCompare(leftUpdated) ||\n rightCreated.localeCompare(leftCreated) ||\n left.frontmatter.id.localeCompare(right.frontmatter.id)\n );\n }\n}\n\n/**\n * Pure helper that shapes a {@link EngramAccessMemorySummary} from a\n * {@link MemoryFile} based on the requested disclosure depth (issue #677\n * PR 2/4). Extracted so the shaping invariants — chunk emits preview\n * only, section attaches `content`, raw also surfaces `rawExcerpts` when\n * the caller passes them — can be unit-tested without booting an\n * orchestrator.\n *\n * Browse / non-recall paths pass `disclosure === undefined` so the\n * `disclosure`, `content`, and `rawExcerpts` fields are all omitted —\n * preserving the cheap-by-default browse projection.\n */\nexport function shapeMemorySummary(\n memory: MemoryFile,\n baseDir: string,\n disclosure?: RecallDisclosure,\n rawExcerpts?: EngramAccessMemorySummary[\"rawExcerpts\"],\n): EngramAccessMemorySummary {\n const includeFullContent =\n disclosure === \"section\" || disclosure === \"raw\";\n return {\n id: memory.frontmatter.id,\n path: memory.path,\n category: memory.frontmatter.category,\n status: inferMemoryStatus(memory.frontmatter, toMemoryPathRel(baseDir, memory.path)),\n created: memory.frontmatter.created,\n updated: memory.frontmatter.updated,\n tags: normalizeProjectionTags(memory.frontmatter.tags),\n entityRef: memory.frontmatter.entityRef,\n preview: normalizeProjectionPreview(memory.content),\n ...(disclosure !== undefined ? { disclosure } : {}),\n ...(includeFullContent ? { content: memory.content } : {}),\n ...(disclosure === \"raw\" && rawExcerpts !== undefined\n ? { rawExcerpts }\n : {}),\n };\n}\n\nexport class EngramAccessService {\n private readonly idempotency: AccessIdempotencyStore;\n private readonly idempotencyLocks = new Map<string, Promise<void>>();\n private readonly budgetLocks = new Map<string, Promise<void>>();\n private readonly budget: CrossNamespaceBudget;\n private readonly auditAdapter: AccessAuditAdapter | null;\n\n constructor(private readonly orchestrator: Orchestrator) {\n this.idempotency = new AccessIdempotencyStore(orchestrator.config.memoryDir);\n this.budget = new CrossNamespaceBudget({\n enabled: orchestrator.config.recallCrossNamespaceBudgetEnabled,\n windowMs: orchestrator.config.recallCrossNamespaceBudgetWindowMs,\n softLimit: orchestrator.config.recallCrossNamespaceBudgetSoftLimit,\n hardLimit: orchestrator.config.recallCrossNamespaceBudgetHardLimit,\n });\n\n const auditEnabled = orchestrator.config.recallAuditAnomalyDetectionEnabled === true;\n const auditLogEnabled = false; // Audit JSONL logging — off until wired to a directory\n if (auditEnabled || auditLogEnabled) {\n const auditConfig: AccessAuditConfig = {\n audit: {\n enabled: auditLogEnabled,\n rootDir: orchestrator.config.memoryDir,\n },\n detection: {\n enabled: auditEnabled,\n windowMs: orchestrator.config.recallAuditAnomalyWindowMs,\n repeatQueryLimit: orchestrator.config.recallAuditAnomalyRepeatQueryLimit,\n namespaceWalkLimit: orchestrator.config.recallAuditAnomalyNamespaceWalkLimit,\n highCardinalityReturnLimit: orchestrator.config.recallAuditAnomalyHighCardinalityLimit,\n rapidFireLimit: orchestrator.config.recallAuditAnomalyRapidFireLimit,\n },\n };\n this.auditAdapter = new AccessAuditAdapter(auditConfig);\n } else {\n this.auditAdapter = null;\n }\n }\n\n get briefingEnabled(): boolean {\n return this.orchestrator.config.briefing?.enabled === true;\n }\n\n private resolveNamespace(namespace?: string): string {\n const requested = namespace?.trim();\n if (!requested) return this.orchestrator.config.defaultNamespace;\n if (!this.orchestrator.config.namespacesEnabled && requested !== this.orchestrator.config.defaultNamespace) {\n throw new EngramAccessInputError(`unsupported namespace: ${requested}`);\n }\n return requested;\n }\n\n private normalizeRecallMode(mode?: RecallPlanMode | \"auto\"): RecallPlanMode | undefined {\n if (!mode || mode === \"auto\") return undefined;\n if (mode === \"no_recall\" || mode === \"minimal\" || mode === \"full\" || mode === \"graph_mode\") {\n return mode;\n }\n throw new EngramAccessInputError(`unsupported recall mode: ${mode}`);\n }\n\n private resolveRecallNamespace(\n namespace: string | undefined,\n sessionKey: string | undefined,\n authenticatedPrincipal?: string,\n ): string | undefined {\n const requested = namespace?.trim();\n if (!requested) return undefined;\n const resolved = this.resolveNamespace(requested);\n const principal = this.resolveRequestPrincipal(sessionKey, authenticatedPrincipal);\n if (!canReadNamespace(principal, resolved, this.orchestrator.config)) {\n throw new EngramAccessInputError(`namespace override is not readable: ${resolved}`);\n }\n return resolved;\n }\n\n private resolveRequestPrincipal(sessionKey: string | undefined, authenticatedPrincipal?: string): string | undefined {\n const trusted = authenticatedPrincipal?.trim();\n if (trusted) return trusted;\n return resolvePrincipal(sessionKey, this.orchestrator.config);\n }\n\n private resolveWritableNamespace(\n namespace: string | undefined,\n sessionKey: string | undefined,\n authenticatedPrincipal?: string,\n ): string {\n const resolved = this.resolveNamespace(namespace);\n const principal = this.resolveRequestPrincipal(sessionKey, authenticatedPrincipal);\n if (!canWriteNamespace(principal, resolved, this.orchestrator.config)) {\n throw new EngramAccessInputError(`namespace is not writable: ${resolved}`);\n }\n return resolved;\n }\n\n /**\n * Resolve a coding context from `cwd`/`projectTag` WITHOUT persisting it to\n * any session — the read-only half of `maybeAttachCodingContext`. Returns\n * null when project scoping is off or nothing resolves. `projectTag` takes\n * priority over `cwd` (matching `maybeAttachCodingContext`).\n */\n private async resolveCodingContextFromOptions(\n options: CodingScopedWriteInput,\n ): Promise<CodingContext | null> {\n if (!this.orchestrator.config.codingMode?.projectScope) return null;\n if (typeof options.projectTag === \"string\" && options.projectTag.trim().length > 0) {\n const projectId = projectTagProjectId(options.projectTag);\n return { projectId, branch: null, rootPath: projectId, defaultBranch: null };\n }\n if (typeof options.cwd === \"string\" && options.cwd.trim().length > 0) {\n try {\n const gitCtx = await resolveGitContext(options.cwd);\n if (gitCtx) {\n return {\n projectId: gitCtx.projectId,\n branch: gitCtx.branch,\n rootPath: gitCtx.rootPath,\n defaultBranch: gitCtx.defaultBranch,\n };\n }\n } catch {\n // resolveGitContext never throws, but stay defensive — not being in a\n // repo is normal and must not break the write.\n }\n }\n return null;\n }\n\n /**\n * Resolve the write namespace for explicit-write tools (memory_store /\n * suggestion_submit), project-scoping the write the same way recall does so a\n * memory stored with a client-injected `cwd`/`projectTag` is discoverable by\n * project-scoped recall (#1434, rule 42).\n *\n * Precedence:\n * - An explicit `namespace` always wins and is authorized strictly via\n * `resolveWritableNamespace` → `canWriteNamespace`. A coding-overlay\n * namespace string (`<base>-project-*`) is NOT a writable target via the\n * explicit field — project scoping is requested with `cwd`/`projectTag`,\n * never by naming the derived namespace — so there is no way to bypass the\n * policy allow-list by guessing/forging an overlay name (Codex review).\n * - With NO coding overlay, the write stays on `config.defaultNamespace` —\n * exactly the pre-#1434 behavior, so an unqualified write is NOT silently\n * moved to a principal self namespace (Codex review).\n * - WITH a coding overlay, the base is the principal self namespace\n * (`defaultNamespaceForPrincipal`, write-checked) — the SAME base recall,\n * observe, and the orchestrator buffer-flush write path overlay onto\n * (rule 42 / Cursor) — so a project-scoped store lands exactly where\n * project-scoped recall searches. The overlay namespace is always REBUILT\n * from the authenticated principal's base, never accepted as a caller\n * string, so a caller can never reach another principal's subtree.\n *\n * Read-only: this NEVER mutates session coding context, so the idempotency\n * peeks and dryRun preflights that call it stay side-effect free (Codex\n * review). It prefers the per-call `cwd`/`projectTag` (the project explicitly\n * identified for this write), else the session's existing context. The HTTP\n * surface lets the peek and the write each resolve independently; the peek's\n * namespace only gates rate-limiting (memory_store/suggestion_submit run their\n * own idempotency check), so a benign session-context change between the two\n * never fails a write — there is no namespace to \"pin\".\n */\n private async resolveCodingScopedWriteNamespace(\n request: CodingScopedWriteInput & {\n namespace?: string;\n sessionKey?: string;\n authenticatedPrincipal?: string;\n },\n ): Promise<string> {\n const hasExplicitNamespace =\n typeof request.namespace === \"string\" && request.namespace.trim().length > 0;\n if (hasExplicitNamespace) {\n return this.resolveWritableNamespace(\n request.namespace,\n request.sessionKey,\n request.authenticatedPrincipal,\n );\n }\n // Project scoping only applies when namespaces are enabled (else overlaying\n // would create false isolation over a single storage dir) and projectScope\n // is on. The coding context MUST be resolved exactly as the recall path\n // resolves it, or a scoped store won't be discoverable by scoped recall\n // (the whole point of #1434). Recall calls `maybeAttachCodingContext`, which\n // returns early when the session already has a context — so recall is\n // SESSION-FIRST: an existing session binding wins, and the per-call\n // cwd/projectTag is only used to seed a context when none is attached yet.\n // Mirror that precedence here: session context first, per-call as fallback\n // (Codex review — a per-call-wins write would land in a project that the\n // same session's recall, still on the bound project, never searches).\n //\n // A sessionKey is REQUIRED to apply the overlay. The recall path can only\n // attach/look up coding context per session (`maybeAttachCodingContext` and\n // `applyCodingNamespaceOverlay` both no-op without a sessionKey), so a\n // sessionless recall always searches the base namespace. A sessionless\n // write must therefore also stay on the base — otherwise a client that\n // injects cwd/projectTag but no sessionKey would store into\n // `default-project-*` that its own recall never searches (Codex review).\n const hasSession =\n typeof request.sessionKey === \"string\" && request.sessionKey.length > 0;\n const overlay =\n hasSession &&\n this.orchestrator.config.namespacesEnabled &&\n this.orchestrator.config.codingMode?.projectScope\n ? resolveCodingNamespaceOverlay(\n this.orchestrator.getCodingContextForSession(request.sessionKey) ??\n (await this.resolveCodingContextFromOptions(request)),\n this.orchestrator.config.codingMode,\n this.orchestrator.config.defaultNamespace,\n )\n : null;\n if (!overlay) {\n // No coding overlay → unqualified write stays on config.defaultNamespace,\n // exactly the pre-#1434 behavior (auth-checked, like the legacy path).\n return this.resolveWritableNamespace(\n undefined,\n request.sessionKey,\n request.authenticatedPrincipal,\n );\n }\n // Coding overlay → overlay onto the principal self base, the SAME namespace\n // recall/observe/buffer-flush use. The result is a principal-owned\n // `project-*` sub-namespace derived from this authorized base, so it needs\n // no separate write policy.\n const principal = this.resolveRequestPrincipal(\n request.sessionKey,\n request.authenticatedPrincipal,\n );\n const base = defaultNamespaceForPrincipal(principal, this.orchestrator.config);\n if (!canWriteNamespace(principal, base, this.orchestrator.config)) {\n throw new EngramAccessInputError(`namespace is not writable: ${base}`);\n }\n return combineNamespaces(base, overlay.namespace);\n }\n\n /**\n * Resolve ONE effective memory scope plan for a write-producing request\n * (#1495 / seed for epic #1494). The returned {@link MemoryScopePlan} is the\n * single source of truth `observe` (and, later, other write surfaces) consume\n * so every side effect lands in `plan.writeNamespace`.\n *\n * Authorization mirrors {@link resolveCodingScopedWriteNamespace} EXACTLY so\n * `observe`'s scoping is identical to `memory_store`/`suggestion_submit`\n * (rule 39 — feature gates identical across code paths):\n * - an explicit `namespace` always wins and is authorized strictly through\n * `resolveWritableNamespace` → `canWriteNamespace`; an overlay-shaped string\n * is never a writable target (rule 42 / 47 / 48);\n * - with NO overlay, the base stays on `config.defaultNamespace` (pre-#1434\n * behavior), auth-checked;\n * - WITH an overlay, the base is the principal self namespace and the overlay\n * is REBUILT from that authorized base — never accepted as a caller string.\n *\n * READ-ONLY: this never mutates session coding context. Callers that need the\n * `cwd`/`projectTag` bound to the session (so a later bare recall is scoped)\n * must attach it via `maybeAttachCodingContext` BEFORE calling this, which\n * also preserves the no-orphan-context guard (attach only after auth passes).\n * The overlay here reads the session's attached context first (matching recall\n * precedence), falling back to the per-call `cwd`/`projectTag`.\n */\n private async resolveMemoryScopePlan(\n request: CodingScopedWriteInput & {\n namespace?: string;\n sessionKey?: string;\n authenticatedPrincipal?: string;\n },\n ): Promise<MemoryScopePlan> {\n const warnings: string[] = [];\n const principal = this.resolveRequestPrincipal(\n request.sessionKey,\n request.authenticatedPrincipal,\n );\n const hasExplicitNamespace =\n typeof request.namespace === \"string\" && request.namespace.trim().length > 0;\n\n if (hasExplicitNamespace) {\n // Explicit namespace wins; authorized through the existing policy path.\n // The overlay never applies, so base == write == the explicit namespace.\n // Objective-state converges on the same explicit target (the stricter\n // principal-self contract only governs the IMPLICIT path).\n const writeNamespace = this.resolveWritableNamespace(\n request.namespace,\n request.sessionKey,\n request.authenticatedPrincipal,\n );\n return {\n principal,\n explicitNamespace: request.namespace!.trim(),\n baseNamespace: writeNamespace,\n writeNamespace,\n objectiveStateNamespace: writeNamespace,\n readNamespaces: [writeNamespace],\n codingOverlayApplied: false,\n warnings,\n };\n }\n\n // No explicit namespace → principal self base, optionally overlaid with the\n // session's coding (project/branch) context — the SAME resolution recall and\n // the orchestrator buffer-flush write path use (rule 42 symmetry).\n const baseNamespace = defaultNamespaceForPrincipal(\n principal,\n this.orchestrator.config,\n );\n\n // Resolve the coding overlay through the SAME orchestrator method recall and\n // the buffer-flush write path use (`applyCodingNamespaceOverlay`), NOT a\n // private re-implementation. Routing through the one shared method (rule 22 /\n // 42) means a project-scoped observe writes to byte-for-byte the namespace a\n // same-session recall reads — and that the read/write overlay logic cannot\n // drift (the #1495 drift this PR exists to close). The orchestrator method\n // already gates on `namespacesEnabled` + a bound/derivable coding context, so\n // it returns the base unchanged when no overlay applies.\n //\n // `applyCodingNamespaceOverlay` reads the session's ATTACHED context. The\n // scope plan runs BEFORE `maybeAttachCodingContext` (resolve-before-mutate),\n // so when nothing is attached yet we seed the per-call cwd/projectTag context\n // first — identical to what attach would bind — so the overlay is the same\n // either way (Codex review precedence: session context first, per-call\n // fallback).\n const hasSession =\n typeof request.sessionKey === \"string\" && request.sessionKey.length > 0;\n const overlayEligible =\n hasSession &&\n this.orchestrator.config.namespacesEnabled === true &&\n this.orchestrator.config.codingMode?.projectScope === true;\n\n // Resolve the coding context the overlay must use: the session's ATTACHED\n // context first (so a bound session wins), else the per-call cwd/projectTag —\n // identical precedence to recall and to `resolveCodingScopedWriteNamespace`.\n let attachedContext = hasSession\n ? this.orchestrator.getCodingContextForSession(request.sessionKey)\n : null;\n // Track whether WE seeded the per-call context so we can leave the session\n // exactly as we found it on any rejection (read-only contract / no-orphan\n // guard, observe-scope \"unauthorized overlay self-base\" test).\n let seededContext = false;\n if (overlayEligible && !attachedContext) {\n attachedContext = await this.resolveCodingContextFromOptions(request);\n if (attachedContext) {\n // Seed the per-call context so the shared\n // `applyCodingNamespaceOverlay` (which reads ATTACHED session context)\n // overlays it through the ONE method recall/buffer-flush use (rule 22 /\n // 42) — no private re-implementation that could drift. On the happy\n // path `maybeAttachCodingContext` re-binds the identical context after\n // auth passes; on a rejection we clear the seed below, so the session is\n // untouched either way.\n this.orchestrator.setCodingContextForSession(\n request.sessionKey!,\n attachedContext,\n );\n seededContext = true;\n }\n }\n\n // Clear a seed we added, used only on the rejection paths so a failed\n // observe never leaves an orphaned project binding (read-only contract).\n const clearSeededContext = (): void => {\n if (seededContext && hasSession) {\n this.orchestrator.setCodingContextForSession(request.sessionKey!, null);\n }\n };\n\n const overlaidBase = this.orchestrator.applyCodingNamespaceOverlay(\n request.sessionKey,\n baseNamespace,\n );\n const codingOverlayApplied = overlaidBase !== baseNamespace;\n\n if (!codingOverlayApplied) {\n // No overlay → the LCM/extraction/response write namespace mirrors the\n // legacy memory_store path (resolveWritableNamespace with no explicit\n // namespace), collapsing the namespaces-disabled / no-session /\n // projectScope-off cases to config.defaultNamespace exactly as before\n // (rule 39 parity with resolveCodingScopedWriteNamespace).\n const writeNamespace = this.resolveWritableNamespace(\n undefined,\n request.sessionKey,\n request.authenticatedPrincipal,\n );\n // Objective-state keeps its STRICTER pre-#1495 contract (#928): an implicit\n // snapshot is based on the PRINCIPAL SELF namespace and authorized against\n // THAT base (rule 48 least-privilege). This rejection MUST stay (security):\n // an implicit observe by a principal that cannot write its own self\n // namespace must not silently snapshot objective-state to the default\n // store.\n //\n // GATED on objective-state writes being ENABLED, exactly like the pre-#1495\n // code (`if (shouldWriteObjectiveState && !hasExplicitNamespace && …)`).\n // The general LCM/extraction write path collapses an unqualified write to\n // config.defaultNamespace (always writable), so when objective-state writes\n // are OFF there is no self-base write to authorize and observe must NOT\n // reject (the \"skips … when writes are disabled\" invariant). When namespaces\n // are off the self base collapses to config.defaultNamespace, so this is a\n // no-op for single-store deployments either way.\n const willWriteObjectiveState =\n this.orchestrator.config.objectiveStateMemoryEnabled === true &&\n this.orchestrator.config.objectiveStateSnapshotWritesEnabled === true;\n if (\n willWriteObjectiveState &&\n this.orchestrator.config.namespacesEnabled === true &&\n !canWriteNamespace(principal, baseNamespace, this.orchestrator.config)\n ) {\n clearSeededContext();\n throw new EngramAccessInputError(\n `namespace is not writable: ${baseNamespace}`,\n );\n }\n return {\n principal,\n // scopeDebug.baseNamespace must report the principal SELF base\n // (`defaultNamespaceForPrincipal`), NOT the general write namespace —\n // which collapses to config.defaultNamespace on this implicit no-overlay\n // path (#1505 cursor \"Wrong scopeDebug base namespace\"). It already\n // matches `objectiveStateNamespace` below; `writeNamespace` is unchanged.\n baseNamespace,\n writeNamespace,\n // Implicit objective-state stays on the principal self base, NOT the\n // (possibly default) general write namespace — preserving the #928\n // semantics the objective-state suite asserts.\n objectiveStateNamespace: baseNamespace,\n readNamespaces: [writeNamespace],\n codingOverlayApplied: false,\n warnings,\n };\n }\n\n // Overlay applied → both the general write namespace AND objective-state\n // converge on the overlaid principal self base. Authorize the self base\n // (the overlay is a principal-owned `project-*` sub-namespace derived from\n // it, so it needs no separate write policy — rule 42 / 47 / 48).\n if (!canWriteNamespace(principal, baseNamespace, this.orchestrator.config)) {\n clearSeededContext();\n throw new EngramAccessInputError(\n `namespace is not writable: ${baseNamespace}`,\n );\n }\n const writeNamespace = overlaidBase;\n const readNamespaces = [writeNamespace];\n // Include read fallbacks (branch→project→root) so the diagnostic readNamespaces\n // matches what a same-session recall searches. Resolved through the pure\n // overlay helper to enumerate fallbacks; the write namespace itself already\n // came from `applyCodingNamespaceOverlay` so the two agree.\n const overlay = resolveCodingNamespaceOverlay(\n attachedContext,\n this.orchestrator.config.codingMode,\n this.orchestrator.config.defaultNamespace,\n );\n for (const fallback of overlay?.readFallbacks ?? []) {\n const ns = combineNamespaces(baseNamespace, fallback);\n if (!readNamespaces.includes(ns)) readNamespaces.push(ns);\n }\n return {\n principal,\n baseNamespace,\n writeNamespace,\n objectiveStateNamespace: writeNamespace,\n readNamespaces,\n codingOverlayApplied: true,\n warnings,\n };\n }\n\n private async objectiveStateStoreLocationForNamespace(namespace: string): Promise<{\n memoryDir: string;\n objectiveStateStoreDir?: string;\n }> {\n if (!this.orchestrator.config.namespacesEnabled) {\n return {\n memoryDir: this.orchestrator.config.memoryDir,\n objectiveStateStoreDir: this.orchestrator.config.objectiveStateStoreDir,\n };\n }\n const storage = await this.orchestrator.getStorage(namespace);\n return {\n memoryDir: storage.dir,\n objectiveStateStoreDir: objectiveStateStoreOverrideForNamespace({\n memoryDir: this.orchestrator.config.memoryDir,\n configuredStoreDir: this.orchestrator.config.objectiveStateStoreDir,\n namespacesEnabled: this.orchestrator.config.namespacesEnabled,\n namespace,\n }),\n };\n }\n\n private resolveReadableNamespace(namespace: string | undefined, principal?: string): string {\n const resolved = this.resolveNamespace(namespace);\n const namespacesEnabled = this.orchestrator.config.namespacesEnabled;\n\n if (!namespacesEnabled) {\n // Namespaces are disabled globally — no ACL needed for any caller.\n return resolved;\n }\n\n // Namespaces are enabled. An absent principal means the caller is\n // unauthenticated. Unauthenticated callers must NOT be allowed to read\n // arbitrary namespaces: that would bypass all readPrincipals policies.\n if (!principal) {\n throw new EngramAccessInputError(\n \"authentication required: namespaces are enabled and no principal was supplied\",\n );\n }\n\n // Authenticated caller — enforce the namespace ACL as normal.\n if (!canReadNamespace(principal, resolved, this.orchestrator.config)) {\n throw new EngramAccessInputError(`namespace is not readable: ${resolved}`);\n }\n return resolved;\n }\n\n private resolveReadableNamespacesForSearch(namespace: string | undefined, principal?: string): string[] {\n const requested = namespace?.trim();\n if (requested) {\n return [this.resolveReadableNamespace(requested, principal)];\n }\n\n if (!this.orchestrator.config.namespacesEnabled) {\n return [this.resolveNamespace(undefined)];\n }\n\n if (!principal) {\n throw new EngramAccessInputError(\n \"authentication required: namespaces are enabled and no principal was supplied\",\n );\n }\n\n return recallNamespacesForPrincipal(principal, this.orchestrator.config)\n .filter((ns) => canReadNamespace(principal, ns, this.orchestrator.config));\n }\n\n private resolveAllReadableConfiguredNamespaces(principal: string): string[] {\n const config = this.orchestrator.config;\n const candidates = [\n config.defaultNamespace,\n config.sharedNamespace,\n ...config.namespacePolicies.map((policy) => policy.name),\n ];\n return [...new Set(candidates)]\n .filter((namespace) => canReadNamespace(principal, namespace, config));\n }\n\n private resolveMemorySearchNamespacesForCollection(\n collection: string | undefined,\n namespaces: string[],\n collectionPrincipal?: string,\n ): string[] {\n if (!this.orchestrator.config.namespacesEnabled) {\n return namespaces;\n }\n\n const baseCollection = this.orchestrator.config.qmdCollection;\n if (!collection || collection === \"global\" || collection === baseCollection) {\n return namespaces;\n }\n\n const candidates = collectionPrincipal\n ? this.resolveAllReadableConfiguredNamespaces(collectionPrincipal)\n : namespaces;\n const matchedNamespaces = candidates.filter((namespace) => {\n const canonical = namespaceCollectionName(baseCollection, namespace, {\n defaultNamespace: this.orchestrator.config.defaultNamespace,\n useLegacyDefaultCollection: false,\n });\n const legacyDefault = namespaceCollectionName(baseCollection, namespace, {\n defaultNamespace: this.orchestrator.config.defaultNamespace,\n useLegacyDefaultCollection: true,\n });\n return collection === canonical || collection === legacyDefault;\n });\n\n if (matchedNamespaces.length > 0) {\n return matchedNamespaces;\n }\n\n throw new EngramAccessInputError(\n \"collection is not namespace-scoped for the requested principal\",\n );\n }\n\n private async buildRecallDebug(\n snapshot: LastRecallSnapshot | null,\n namespace: string,\n includeDebug: boolean,\n sessionKey?: string,\n ): Promise<EngramAccessRecallResponse[\"debug\"] | undefined> {\n if (!includeDebug) return undefined;\n if (!sessionKey?.trim()) return undefined;\n const [intent, graph] = await Promise.all([\n this.orchestrator.getLastIntentSnapshot(namespace),\n this.orchestrator.getLastGraphRecallSnapshot(namespace),\n ]);\n return snapshot || intent || graph\n ? {\n snapshot: snapshot ?? undefined,\n intent,\n graph,\n }\n : undefined;\n }\n\n private async buildRecallResponseFromXraySnapshot(options: {\n query: string;\n sessionKey?: string;\n snapshot: RecallXraySnapshot;\n disclosure: RecallDisclosure;\n startedAt: number;\n requestedMode?: RecallPlanMode | \"auto\";\n normalizedMode?: RecallPlanMode;\n /**\n * Read-authorization-gated namespace for the raw-excerpt LCM lookup (#1505\n * thread 2f7). Threaded through to `serializeRecallResults` so the\n * `includeRecall` x-ray path honours the SAME read gate as normal recall and\n * never attaches overlay transcript rows the gate excludes.\n */\n rawExcerptNamespace?: string;\n /**\n * Ordered, read-authorized LCM read session_id SET (#1505 fallback\n * unification). Threaded through to `serializeRecallResults` so the x-ray raw\n * disclosure path also finds excerpts archived at the coding read fallbacks.\n */\n rawExcerptSessionIds?: string[];\n /**\n * Force NO raw excerpts (#1505 thread NBHWz). Set when the IMPLICIT\n * raw-excerpt read gate found NO readable LCM namespace, so the x-ray\n * includeRecall path degrades to empty excerpts rather than falling back to\n * the write/overlay namespace the read gate excludes.\n */\n rawExcerptsSuppressed?: boolean;\n }): Promise<EngramAccessRecallResponse> {\n const memoryIds = options.snapshot.results.map((result) => result.memoryId);\n const resultPaths = options.snapshot.results.map((result) => result.path);\n const namespace = options.snapshot.namespace\n ? this.resolveNamespace(options.snapshot.namespace)\n : this.orchestrator.config.defaultNamespace;\n const sourcesUsed = Array.from(\n new Set(options.snapshot.results.map((result) => result.servedBy)),\n );\n const snapshotForSerialization: LastRecallSnapshot = {\n sessionKey: options.sessionKey ?? \"\",\n recordedAt: new Date(options.snapshot.capturedAt).toISOString(),\n queryHash: createHash(\"sha256\").update(options.query).digest(\"hex\"),\n queryLen: options.query.length,\n memoryIds,\n namespace,\n recallNamespaces: [namespace],\n traceId: options.snapshot.traceId,\n plannerMode: options.normalizedMode,\n requestedMode:\n options.requestedMode && options.requestedMode !== \"auto\"\n ? options.requestedMode\n : undefined,\n sourcesUsed,\n budgetsApplied: {\n appliedTopK: memoryIds.length,\n recallBudgetChars: options.snapshot.budget.chars,\n maxMemoryTokens: this.orchestrator.config.maxMemoryTokens,\n finalContextChars: options.snapshot.budget.used,\n },\n latencyMs: Date.now() - options.startedAt,\n resultPaths,\n };\n const results = await this.serializeRecallResults(\n snapshotForSerialization,\n options.disclosure,\n {\n query: options.query,\n ...(options.sessionKey ? { sessionKey: options.sessionKey } : {}),\n ...(options.rawExcerptNamespace\n ? { rawExcerptNamespace: options.rawExcerptNamespace }\n : {}),\n ...(options.rawExcerptSessionIds\n ? { rawExcerptSessionIds: options.rawExcerptSessionIds }\n : {}),\n ...(options.rawExcerptsSuppressed\n ? { rawExcerptsSuppressed: options.rawExcerptsSuppressed }\n : {}),\n },\n );\n const context = results\n .map((result) => {\n const content =\n typeof result.content === \"string\" && result.content.length > 0\n ? result.content\n : \"\";\n return content || result.preview;\n })\n .filter((text) => text.length > 0)\n .join(\"\\n\\n\");\n\n return {\n query: options.query,\n ...(options.sessionKey ? { sessionKey: options.sessionKey } : {}),\n namespace,\n context,\n count: memoryIds.length,\n memoryIds,\n results,\n recordedAt: snapshotForSerialization.recordedAt,\n traceId: options.snapshot.traceId,\n plannerMode: options.normalizedMode,\n fallbackUsed: sourcesUsed.some((source) => source !== \"hybrid\"),\n sourcesUsed,\n disclosure: options.disclosure,\n budgetsApplied: snapshotForSerialization.budgetsApplied,\n latencyMs: snapshotForSerialization.latencyMs,\n };\n }\n\n private async serializeRecallResults(\n snapshot: LastRecallSnapshot | null,\n disclosure: RecallDisclosure,\n rawContext:\n | {\n query: string;\n sessionKey?: string;\n /**\n * Read-authorization-gated namespace for the raw-excerpt LCM lookup\n * (#1505 thread 2f7). When the caller supplies it, the raw lookup uses\n * THIS namespace prefix instead of `snapshot.namespace` (the\n * write/overlay namespace), so raw disclosure honours the SAME read\n * gate as normal recall + `lcmSearch`. Omitted ⇒ falls back to the\n * snapshot namespace (single-store / sessionless callers, unchanged).\n */\n rawExcerptNamespace?: string;\n /**\n * Ordered, read-authorized LCM read session_id SET (#1505 fallback\n * unification). When supplied, raw disclosure queries each key (primary\n * coding overlay → read fallbacks) and merges rows so a branch-scoped\n * session finds excerpts archived at project/root scope. Already\n * read-gated, so no unauthorized overlay key is present. Omitted ⇒ the\n * legacy single `rawExcerptNamespace`-prefixed key (unchanged).\n */\n rawExcerptSessionIds?: string[];\n /**\n * Force NO raw excerpts even when `disclosure === \"raw\"` (#1505 thread\n * NBHWz). Set by callers when the IMPLICIT raw-excerpt read gate found\n * NO readable LCM namespace (a restrictive `default` READ policy with\n * no readable overlay/self namespace). The lookup must NOT fall back to\n * `snapshot.namespace` (the write/overlay namespace the read gate\n * excludes) — it returns empty excerpts so raw recall degrades\n * gracefully instead of leaking unreadable rows or throwing.\n */\n rawExcerptsSuppressed?: boolean;\n }\n | null = null,\n ): Promise<EngramAccessMemorySummary[]> {\n if (!snapshot) return [];\n const namespace = snapshot.namespace ? this.resolveNamespace(snapshot.namespace) : this.orchestrator.config.defaultNamespace;\n const storage = await this.orchestrator.getStorage(namespace);\n const storageDir = storage.dir;\n const recallNamespaces = Array.from(\n new Set(\n [\n namespace,\n ...(Array.isArray(snapshot.recallNamespaces)\n ? snapshot.recallNamespaces.map((ns) => this.resolveNamespace(ns))\n : []),\n this.orchestrator.config.defaultNamespace,\n this.orchestrator.config.sharedNamespace,\n ...(this.orchestrator.config.namespacePolicies ?? []).map((p) => p.name),\n ].filter((ns): ns is string => typeof ns === \"string\" && ns.length > 0),\n ),\n );\n const results: EngramAccessMemorySummary[] = [];\n const seen = new Set<string>();\n const collectionNamespaceFromPrefix = (collectionPrefix: string): string | null => {\n const baseCollection = this.orchestrator.config.qmdCollection;\n if (collectionPrefix === baseCollection) return this.orchestrator.config.defaultNamespace;\n const namespaceSuffix = collectionPrefix.startsWith(`${baseCollection}--`)\n ? collectionPrefix.slice(baseCollection.length + 2)\n : \"\";\n if (!namespaceSuffix) return null;\n\n const decoded = namespaceIdentityFromToken(namespaceSuffix);\n if (decoded !== null) return decoded || this.orchestrator.config.defaultNamespace;\n if (namespaceSuffix.startsWith(\"ns--\")) {\n const legacyNamespace = namespaceSuffix.slice(\"ns--\".length).trim();\n return legacyNamespace || null;\n }\n return null;\n };\n const readResultPath = async (\n memoryPath: string,\n ): Promise<{ memory: MemoryFile; baseDir: string } | null> => {\n const parts = qmdCollectionPathParts(memoryPath);\n const coldCollection =\n this.orchestrator.config.qmdColdCollection ?? \"openclaw-engram-cold\";\n if (parts && parts.collection === coldCollection) {\n const storages: Array<{ storage: StorageManager; dir: string }> = [];\n const seenStorageDirs = new Set<string>();\n const addStorage = (candidateStorage: StorageManager): void => {\n const candidateDir = nodePath.resolve(candidateStorage.dir);\n if (seenStorageDirs.has(candidateDir)) return;\n seenStorageDirs.add(candidateDir);\n storages.push({ storage: candidateStorage, dir: candidateDir });\n };\n addStorage(storage);\n for (const recallNamespace of recallNamespaces) {\n try {\n addStorage(await this.orchestrator.getStorage(recallNamespace));\n } catch {\n continue;\n }\n }\n for (const candidateStorage of storages) {\n try {\n const coldRoot = nodePath.join(candidateStorage.dir, \"cold\");\n for (const candidatePath of qmdResultPathCandidates(\n coldRoot,\n parts.relativePath,\n )) {\n const memory =\n await candidateStorage.storage.readMemoryByPath(candidatePath);\n if (memory) return { memory, baseDir: candidateStorage.dir };\n }\n } catch (err) {\n if (err instanceof SecureStoreLockedError) throw err;\n continue;\n }\n }\n return null;\n }\n\n const collectionNamespace = parts\n ? collectionNamespaceFromPrefix(parts.collection)\n : null;\n\n if (parts && collectionNamespace) {\n try {\n const collectionStorage =\n await this.orchestrator.getStorage(collectionNamespace);\n for (const candidate of qmdResultPathCandidates(\n collectionStorage.dir,\n parts.relativePath,\n )) {\n const memory = await collectionStorage.readMemoryByPath(candidate);\n if (memory) return { memory, baseDir: collectionStorage.dir };\n }\n return null;\n } catch (err) {\n if (err instanceof SecureStoreLockedError) throw err;\n return null;\n }\n }\n\n if (nodePath.isAbsolute(memoryPath)) {\n const ownerStorage = await this.storageForAbsoluteRecallPath(\n memoryPath,\n namespace,\n recallNamespaces,\n );\n if (!ownerStorage) return null;\n for (const candidate of qmdResultPathCandidates(\n ownerStorage.dir,\n memoryPath,\n )) {\n const memory = await ownerStorage.storage.readMemoryByPath(candidate);\n if (memory) return { memory, baseDir: ownerStorage.dir };\n }\n return null;\n }\n\n for (const candidate of qmdResultPathCandidates(storageDir, memoryPath)) {\n const memory = await storage.readMemoryByPath(candidate);\n if (memory) return { memory, baseDir: storageDir };\n }\n return null;\n };\n\n // Pre-fetch raw excerpts once when `disclosure === \"raw\"` so we don't\n // hit the LCM archive per-result (issue #677 PR 2/4). Excerpts are\n // attached to the first result; per-result attribution is reserved\n // for a future PR if/when the LCM index can be joined to memory ids.\n // Coerce `null` (non-raw disclosure) to `undefined` so the optional\n // serializer field is never explicitly `null`.\n // Namespace for the LCM `${namespace}:${sessionKey}` prefix: prefer the\n // caller-supplied READ-AUTHORIZATION-GATED `rawExcerptNamespace` (#1505\n // thread 2f7) so raw disclosure honours the same read gate as normal recall\n // + `lcmSearch` and never attaches `<principal>-project-*` overlay rows the\n // gate excludes. Fall back to the snapshot's resolved namespace only when no\n // gated namespace was threaded (sessionless / legacy callers) — unchanged.\n const rawExcerptsResult =\n rawContext?.rawExcerptsSuppressed === true\n ? // Implicit raw recall with NO readable LCM namespace (#1505 thread\n // NBHWz): emit empty excerpts rather than falling back to the\n // write/overlay `namespace` the read gate excludes.\n []\n : await this.fetchRawExcerpts(\n disclosure,\n rawContext\n ? {\n query: rawContext.query,\n ...(rawContext.sessionKey\n ? { sessionKey: rawContext.sessionKey }\n : {}),\n namespace: rawContext.rawExcerptNamespace ?? namespace,\n ...(rawContext.rawExcerptSessionIds\n ? { lcmSessionIds: rawContext.rawExcerptSessionIds }\n : {}),\n }\n : null,\n );\n const rawExcerpts = rawExcerptsResult ?? undefined;\n\n for (const memoryPath of snapshot.resultPaths ?? []) {\n if (!memoryPath || seen.has(memoryPath)) continue;\n const resolved = await readResultPath(memoryPath);\n if (!resolved) continue;\n const { memory, baseDir } = resolved;\n seen.add(memoryPath);\n results.push(\n this.serializeMemorySummary(\n memory,\n baseDir,\n disclosure,\n // Attach the (possibly empty) raw excerpts to the first raw\n // result; subsequent results do not duplicate the array.\n results.length === 0 ? rawExcerpts : undefined,\n ),\n );\n }\n\n if (results.length > 0) return results;\n\n for (const memoryId of snapshot.memoryIds) {\n const memory = await storage.getMemoryById(memoryId);\n if (!memory || seen.has(memory.path)) continue;\n seen.add(memory.path);\n results.push(\n this.serializeMemorySummary(\n memory,\n storageDir,\n disclosure,\n results.length === 0 ? rawExcerpts : undefined,\n ),\n );\n }\n return results;\n }\n\n private async storageForAbsoluteRecallPath(\n memoryPath: string,\n primaryNamespace: string,\n recallNamespaces: readonly string[] = [],\n ): Promise<{ storage: StorageManager; dir: string } | null> {\n const resolvedPath = nodePath.resolve(memoryPath);\n const memoryRoot = nodePath.resolve(this.orchestrator.config.memoryDir);\n const namespacesRoot = nodePath.join(memoryRoot, \"namespaces\");\n const configuredNamespaces = new Set<string>();\n configuredNamespaces.add(primaryNamespace);\n for (const namespace of recallNamespaces) {\n configuredNamespaces.add(namespace);\n }\n configuredNamespaces.add(this.orchestrator.config.defaultNamespace);\n configuredNamespaces.add(this.orchestrator.config.sharedNamespace);\n if (isPathInsideStorageRoot(namespacesRoot, resolvedPath)) {\n const relativeToNamespaces = nodePath.relative(namespacesRoot, resolvedPath);\n const [namespaceSegment] = relativeToNamespaces.split(/[\\\\/]/);\n if (namespaceSegment) {\n configuredNamespaces.add(\n namespaceIdentityFromToken(namespaceSegment) ?? namespaceSegment,\n );\n }\n }\n for (const policy of this.orchestrator.config.namespacePolicies ?? []) {\n configuredNamespaces.add(policy.name);\n }\n\n const matches: Array<{ storage: StorageManager; dir: string }> = [];\n for (const ns of configuredNamespaces) {\n if (!ns) continue;\n let candidateStorage: StorageManager;\n try {\n candidateStorage = await this.orchestrator.getStorage(ns);\n } catch {\n continue;\n }\n const candidateRoot = nodePath.resolve(candidateStorage.dir);\n if (!isPathInsideStorageRoot(candidateRoot, resolvedPath)) continue;\n if (\n candidateRoot === memoryRoot &&\n isPathInsideStorageRoot(namespacesRoot, resolvedPath)\n ) {\n continue;\n }\n matches.push({ storage: candidateStorage, dir: candidateRoot });\n }\n\n matches.sort((a, b) => b.dir.length - a.dir.length);\n return matches[0] ?? null;\n }\n\n /**\n * Fetch raw transcript excerpts from the LCM archive for `disclosure ===\n * \"raw\"` recalls (issue #677 PR 2/4). Returns `null` for non-raw recall\n * depths, an empty array when LCM is disabled / not initialized / has no\n * matches, and an array of LCM-side excerpts otherwise. Errors are\n * swallowed and treated as \"no excerpts\" so a failing LCM never breaks\n * the recall response.\n *\n * Namespace handling: LCM archival prefixes non-default-namespace\n * sessions with `${namespace}:${sessionKey}` (see `observe()` around\n * line 2498), so the lookup must mirror that prefix or raw recalls in\n * non-default namespaces miss their own excerpts.\n */\n private async fetchRawExcerpts(\n disclosure: RecallDisclosure,\n context: {\n query: string;\n sessionKey?: string;\n namespace?: string;\n /**\n * Pre-resolved, ordered, read-authorized LCM read session_id SET (#1505\n * fallback unification). When supplied, raw disclosure queries each key in\n * order (primary coding overlay → read fallbacks) and merges rows, exactly\n * as the orchestrator recall path and `lcmSearch` do, so a branch-scoped\n * session finds excerpts archived at project/root scope. Already\n * read-gated by `resolveLcmReadSessionIds`, so an unauthorized\n * `<principal>-project-*` key is never present. Falls back to the legacy\n * single `namespace`-prefixed key when absent (sessionless / legacy\n * callers).\n */\n lcmSessionIds?: string[];\n } | null,\n ): Promise<EngramAccessMemorySummary[\"rawExcerpts\"] | null> {\n if (disclosure !== \"raw\") return null;\n if (!context || !context.query) return [];\n // Privacy guard: raw disclosure must be session-scoped. Without a\n // sessionKey, `lcm.searchContextFull(query, n, undefined)` searches\n // across every archived session in the LCM store and would return\n // excerpts from unrelated sessions (potentially crossing namespaces\n // via their `${namespace}:${sessionKey}` prefix encoding). Treat a\n // missing sessionKey as \"no excerpts\" — callers asking for raw\n // disclosure outside a session get an empty list, not a leak.\n if (!context.sessionKey) return [];\n const lcm = this.orchestrator.lcmEngine;\n if (!lcm || !lcm.enabled) return [];\n try {\n const legacyKey =\n context.namespace &&\n context.namespace !== this.orchestrator.config.defaultNamespace\n ? `${context.namespace}:${context.sessionKey}`\n : context.sessionKey;\n const lcmSessionIds =\n context.lcmSessionIds && context.lcmSessionIds.length > 0\n ? context.lcmSessionIds\n : [legacyKey];\n // Cap the excerpt fanout so recall responses stay bounded. Five matches\n // is enough to anchor the model in the raw transcript without ballooning\n // token spend; raw is meant as the escape hatch, not the default. The cap\n // is applied across the MERGED result set so adding fallback keys never\n // inflates the excerpt budget.\n const limit = 5;\n const seenRows = new Set<string>();\n const excerpts: NonNullable<EngramAccessMemorySummary[\"rawExcerpts\"]> = [];\n for (const lcmSessionKey of lcmSessionIds) {\n if (excerpts.length >= limit) break;\n const rows = await lcm.searchContextFull(\n context.query,\n limit,\n lcmSessionKey,\n );\n for (const r of rows) {\n const dedupeKey = `${r.session_id} ${r.turn_index}`;\n if (seenRows.has(dedupeKey)) continue;\n seenRows.add(dedupeKey);\n excerpts.push({\n turnIndex: r.turn_index,\n role: r.role,\n content: r.content,\n sessionId: r.session_id,\n });\n if (excerpts.length >= limit) break;\n }\n }\n return excerpts;\n } catch {\n // CLAUDE.md rule 13: never let an external subsystem (LCM/SQLite)\n // crash the primary recall flow.\n return [];\n }\n }\n\n private async handleIdempotentWrite<T extends EngramAccessWriteResponse>(options: {\n operation: T[\"operation\"];\n idempotencyKey?: string;\n requestFingerprint: unknown;\n skip?: boolean;\n /**\n * Invoked exactly once, immediately before an ACTUAL (non-replay, non-skip)\n * write is committed — atomically with the idempotency miss determination.\n * The HTTP surface uses this to enforce the write rate limit against the\n * real write/miss (and the real resolved namespace), so a namespace-divergent\n * idempotency peek can never let a fresh write skip the quota check (#1434\n * Codex review). It is NOT called on dryRun (skip) or replay, preserving the\n * replay-bypasses-a-full-window behavior.\n */\n beforeExecute?: () => void | Promise<void>;\n execute: () => Promise<T>;\n }): Promise<T> {\n if (options.skip === true) {\n return options.execute();\n }\n const key = options.idempotencyKey?.trim();\n if (!key) {\n if (options.beforeExecute) await options.beforeExecute();\n return options.execute();\n }\n return this.withIdempotencyLock(key, async () => {\n return this.idempotency.withKeyLock(key, async () => {\n const requestHash = hashAccessIdempotencyPayload({\n operation: options.operation,\n request: options.requestFingerprint,\n });\n const existing = await this.idempotency.get(key, requestHash);\n if (existing.conflict) {\n throw new EngramAccessInputError(`idempotencyKey reuse conflict: ${key}`);\n }\n if (existing.response) {\n return {\n ...(existing.response as T),\n idempotencyReplay: true,\n };\n }\n if (options.beforeExecute) await options.beforeExecute();\n const response = await options.execute();\n await this.idempotency.put(key, requestHash, response);\n return response;\n });\n });\n }\n\n private async handleIdempotentRead<T>(options: {\n operation: string;\n idempotencyKey?: string;\n requestFingerprint: unknown;\n execute: () => Promise<T>;\n afterStore?: (response: T) => Promise<void> | void;\n }): Promise<T> {\n const key = options.idempotencyKey?.trim();\n if (!key) {\n const response = await options.execute();\n await options.afterStore?.(response);\n return response;\n }\n return this.withIdempotencyLock(key, async () => {\n return this.idempotency.withKeyLock(key, async () => {\n const requestHash = hashAccessIdempotencyPayload({\n operation: options.operation,\n request: options.requestFingerprint,\n });\n const existing = await this.idempotency.get(key, requestHash);\n if (existing.conflict) {\n throw new EngramAccessInputError(`idempotencyKey reuse conflict: ${key}`);\n }\n if (existing.response) {\n return existing.response as T;\n }\n const response = await options.execute();\n await this.idempotency.put(key, requestHash, response);\n await options.afterStore?.(response);\n return response;\n });\n });\n }\n\n private async peekIdempotentWrite(options: {\n operation: EngramAccessWriteResponse[\"operation\"];\n idempotencyKey?: string;\n requestFingerprint: unknown;\n skip?: boolean;\n }): Promise<EngramAccessIdempotencyStatus> {\n if (options.skip === true) {\n return \"miss\";\n }\n const key = options.idempotencyKey?.trim();\n if (!key) {\n return \"miss\";\n }\n return this.withIdempotencyLock(key, async () => {\n return this.idempotency.withKeyLock(key, async () => {\n const requestHash = hashAccessIdempotencyPayload({\n operation: options.operation,\n request: options.requestFingerprint,\n });\n const existing = await this.idempotency.get(key, requestHash);\n if (existing.conflict) {\n return \"conflict\";\n }\n return existing.response ? \"replay\" : \"miss\";\n });\n });\n }\n\n private async withIdempotencyLock<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const previous = this.idempotencyLocks.get(key) ?? Promise.resolve();\n let release!: () => void;\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n const queued = previous.then(() => current, () => current);\n this.idempotencyLocks.set(key, queued);\n\n await previous.catch(() => {});\n try {\n return await fn();\n } finally {\n release();\n if (this.idempotencyLocks.get(key) === queued) {\n this.idempotencyLocks.delete(key);\n }\n }\n }\n\n private async withBudgetLock<T>(principal: string, fn: () => Promise<T>): Promise<T> {\n const key = principal || \"__anonymous__\";\n const previous = this.budgetLocks.get(key) ?? Promise.resolve();\n let release!: () => void;\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n const queued = previous.then(() => current, () => current);\n this.budgetLocks.set(key, queued);\n\n await previous.catch(() => {});\n try {\n return await fn();\n } finally {\n release();\n if (this.budgetLocks.get(key) === queued) {\n this.budgetLocks.delete(key);\n }\n }\n }\n\n async health(namespace?: string): Promise<EngramAccessHealthResponse> {\n const resolvedNamespace = this.resolveNamespace(namespace);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const searchBackend = this.orchestrator.config.searchBackend ?? \"qmd\";\n const qmdEnabled = this.orchestrator.config.qmdEnabled === true;\n let projectionAvailable = false;\n try {\n await stat(getMemoryProjectionPath(storage.dir));\n projectionAvailable = true;\n } catch {\n projectionAvailable = false;\n }\n\n return {\n ok: true,\n memoryDir: storage.dir,\n namespacesEnabled: this.orchestrator.config.namespacesEnabled === true,\n defaultNamespace: this.orchestrator.config.defaultNamespace,\n searchBackend,\n qmdEnabled,\n qmd: await this.qmdHealth(\n searchBackend,\n qmdEnabled,\n resolvedNamespace,\n this.qmdCollectionForHealth(resolvedNamespace, storage.dir),\n ),\n nativeKnowledgeEnabled: this.orchestrator.config.nativeKnowledge?.enabled === true,\n projectionAvailable,\n };\n }\n\n private qmdCollectionForHealth(namespace: string, storageDir: string): string {\n if (this.orchestrator.config.namespacesEnabled !== true) {\n return this.orchestrator.config.qmdCollection;\n }\n\n const useLegacyDefaultCollection =\n namespace === this.orchestrator.config.defaultNamespace &&\n storageDir === this.orchestrator.config.memoryDir;\n return namespaceCollectionName(this.orchestrator.config.qmdCollection, namespace, {\n defaultNamespace: this.orchestrator.config.defaultNamespace,\n useLegacyDefaultCollection,\n });\n }\n\n private async qmdHealth(\n searchBackend: string,\n qmdEnabled: boolean,\n namespace: string,\n collection: string,\n ): Promise<EngramAccessQmdHealthResponse> {\n if (searchBackend !== \"qmd\" || !qmdEnabled) {\n return {\n enabled: qmdEnabled,\n active: false,\n degraded: false,\n mode: searchBackend !== \"qmd\" ? \"not-selected\" : \"disabled\",\n collection,\n collectionState: \"skipped\",\n installedVersion: null,\n supportedVersion: null,\n supported: null,\n upgradeAvailable: null,\n doctorAvailable: null,\n debugStatus: searchBackend !== \"qmd\" ? `backend=${searchBackend}` : \"backend=disabled\",\n };\n }\n\n if (this.orchestrator.config.namespacesEnabled === true) {\n const namespaceHealth = await this.namespaceQmdHealth(searchBackend, qmdEnabled, namespace, collection);\n if (namespaceHealth) return namespaceHealth;\n }\n\n const qmd = this.orchestrator.qmd;\n if (!qmd) {\n return {\n enabled: true,\n active: false,\n degraded: true,\n mode: \"fallback\",\n collection,\n collectionState: \"unknown\",\n installedVersion: null,\n supportedVersion: null,\n supported: null,\n upgradeAvailable: null,\n doctorAvailable: null,\n debugStatus: \"backend=unavailable\",\n };\n }\n const diagnosticAvailable = await this.qmdProbeAvailable(searchBackend, qmdEnabled);\n const operationalAvailable = diagnosticAvailable || qmd.isAvailable();\n const collectionState = diagnosticAvailable\n ? await this.qmdCollectionState(searchBackend, qmdEnabled, collection)\n : \"unknown\";\n const active = operationalAvailable && collectionState !== \"missing\";\n const degraded =\n searchBackend === \"qmd\" &&\n qmdEnabled &&\n (!active || !diagnosticAvailable || collectionState === \"unknown\");\n const debugStatus = qmd.debugStatus();\n const versionStatus =\n \"getVersionStatus\" in qmd && typeof qmd.getVersionStatus === \"function\"\n ? qmd.getVersionStatus()\n : null;\n const daemonMode =\n \"isDaemonMode\" in qmd && typeof qmd.isDaemonMode === \"function\"\n ? qmd.isDaemonMode() === true\n : false;\n const mode =\n searchBackend !== \"qmd\"\n ? \"not-selected\"\n : !qmdEnabled\n ? \"disabled\"\n : !active\n ? \"fallback\"\n : daemonMode\n ? \"daemon\"\n : \"cli\";\n\n return {\n enabled: qmdEnabled,\n active,\n degraded,\n mode,\n collection,\n collectionState,\n installedVersion: versionStatus?.installedVersion ?? null,\n supportedVersion: versionStatus?.supportedVersion ?? null,\n supported: versionStatus?.supported ?? null,\n upgradeAvailable: versionStatus?.upgradeAvailable ?? null,\n doctorAvailable: versionStatus?.capabilities?.doctor ?? null,\n debugStatus,\n };\n }\n\n private async namespaceQmdHealth(\n searchBackend: string,\n qmdEnabled: boolean,\n namespace: string,\n fallbackCollection: string,\n ): Promise<EngramAccessQmdHealthResponse | null> {\n if (searchBackend !== \"qmd\" || !qmdEnabled) return null;\n const searchHealthForNamespace = (\n this.orchestrator as Orchestrator & {\n searchHealthForNamespace?: (\n namespace: string,\n execution?: { signal?: AbortSignal },\n ) => Promise<{\n collection: string;\n available: boolean;\n collectionState: EngramAccessQmdCollectionState;\n debugStatus: string;\n installedVersion: string | null;\n supportedVersion: string | null;\n supported: boolean | null;\n upgradeAvailable: boolean | null;\n doctorAvailable: boolean | null;\n daemonMode: boolean | null;\n }>;\n }\n ).searchHealthForNamespace;\n if (typeof searchHealthForNamespace !== \"function\") return null;\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), 2_000);\n timer.unref?.();\n try {\n const health = await searchHealthForNamespace.call(this.orchestrator, namespace, {\n signal: controller.signal,\n });\n const active = health.available && health.collectionState !== \"missing\";\n const degraded = !active || health.collectionState === \"unknown\";\n const mode =\n !active\n ? \"fallback\"\n : health.daemonMode === true\n ? \"daemon\"\n : \"cli\";\n\n return {\n enabled: true,\n active,\n degraded,\n mode,\n collection: health.collection || fallbackCollection,\n collectionState: health.collectionState,\n installedVersion: health.installedVersion,\n supportedVersion: health.supportedVersion,\n supported: health.supported,\n upgradeAvailable: health.upgradeAvailable,\n doctorAvailable: health.doctorAvailable,\n debugStatus: health.debugStatus,\n };\n } catch (error) {\n const detail = displayErrorDetail(error) || \"unknown\";\n return {\n enabled: true,\n active: false,\n degraded: true,\n mode: \"fallback\",\n collection: fallbackCollection,\n collectionState: \"unknown\",\n installedVersion: null,\n supportedVersion: null,\n supported: null,\n upgradeAvailable: null,\n doctorAvailable: null,\n debugStatus: `backend=namespace-unavailable error=${detail}`,\n };\n } finally {\n clearTimeout(timer);\n }\n }\n\n private async qmdCollectionState(\n searchBackend: string,\n qmdEnabled: boolean,\n collection: string,\n ): Promise<EngramAccessQmdCollectionState> {\n if (searchBackend !== \"qmd\" || !qmdEnabled) return \"skipped\";\n const qmd = this.orchestrator.qmd;\n if (!qmd.isAvailable()) return \"unknown\";\n if (!qmd.checkCollection) return \"skipped\";\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), 2_000);\n timer.unref?.();\n try {\n return await qmd.checkCollection(collection, {\n signal: controller.signal,\n });\n } catch {\n return \"unknown\";\n } finally {\n clearTimeout(timer);\n }\n }\n\n private async qmdProbeAvailable(\n searchBackend: string,\n qmdEnabled: boolean,\n ): Promise<boolean> {\n if (searchBackend !== \"qmd\" || !qmdEnabled) return false;\n const qmd = this.orchestrator.qmd;\n if (!qmd) return false;\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), 2_000);\n timer.unref?.();\n try {\n return await new Promise<boolean>((resolve) => {\n const onAbort = () => {\n controller.signal.removeEventListener(\"abort\", onAbort);\n resolve(false);\n };\n controller.signal.addEventListener(\"abort\", onAbort, { once: true });\n const probe =\n typeof qmd.checkAvailability === \"function\"\n ? qmd.checkAvailability({ signal: controller.signal })\n : qmd.probe();\n probe\n .then(resolve, () => resolve(false))\n .finally(() => {\n controller.signal.removeEventListener(\"abort\", onAbort);\n });\n });\n } finally {\n clearTimeout(timer);\n }\n }\n\n async actionConfidence(\n request: EngramAccessActionConfidenceRequest = {},\n ): Promise<EngramAccessActionConfidenceResponse> {\n return evaluateActionConfidence(request);\n }\n\n async daySummary(\n request: EngramAccessDaySummaryRequest,\n ): Promise<import(\"./types.js\").DaySummaryResult | null> {\n if (!this.orchestrator.config.daySummaryEnabled) {\n throw new EngramAccessInputError(\"day summary is disabled\");\n }\n\n const memories = (request.memories ?? \"\").trim();\n const namespace = this.resolveRecallNamespace(request.namespace, request.sessionKey);\n\n if (memories.length === 0) {\n // Auto-gather today's facts from the resolved namespace\n return this.orchestrator.generateDaySummaryAuto(namespace, {\n timeZone: request.timeZone,\n });\n }\n return this.orchestrator.generateDaySummary(memories);\n }\n\n /**\n * Build a daily context briefing. Gracefully degrades when the OpenAI key\n * or Responses API is unavailable — never throws for LLM-related problems.\n */\n async briefing(\n request: EngramAccessBriefingRequest,\n ): Promise<EngramAccessBriefingResponse> {\n const config = this.orchestrator.config;\n if (!config.briefing.enabled) {\n throw new EngramAccessInputError(\"briefing is disabled\");\n }\n\n const namespace = this.resolveReadableNamespace(request.namespace, request.principal);\n const storage = await this.orchestrator.getStorage(namespace);\n\n const token = typeof request.since === \"string\" && request.since.trim().length > 0\n ? request.since.trim()\n : config.briefing.defaultWindow;\n const window = parseBriefingWindow(token);\n if (!window) {\n throw new EngramAccessInputError(`invalid briefing window: ${token}`);\n }\n\n // Validate focus: only treat undefined / empty strings as \"no filter\".\n // Anything else that parses to null (e.g. \"project:\", \"topic:\") is malformed\n // and must be rejected so a templating miss never silently broadens the\n // briefing from a targeted project view to all memories.\n const rawFocus = typeof request.focus === \"string\" ? request.focus.trim() : \"\";\n let focus = null;\n if (rawFocus.length > 0) {\n focus = parseBriefingFocus(rawFocus);\n if (!focus) {\n throw new EngramAccessInputError(\n `invalid briefing focus filter: ${request.focus}`,\n );\n }\n }\n\n // Reject unsupported format values explicitly. Programmatic callers that\n // bypass CLI/MCP pre-validation (which already use validateBriefingFormat)\n // could otherwise send a typo like \"jsno\" and silently receive a response\n // in the default format, masking the client bug and breaking format-dependent\n // automation. Only undefined / absent format falls through to the default.\n const SUPPORTED_FORMATS = [\"markdown\", \"json\"] as const;\n if (\n typeof request.format === \"string\" &&\n !(SUPPORTED_FORMATS as readonly string[]).includes(request.format)\n ) {\n throw new EngramAccessInputError(\n `unsupported briefing format: \"${request.format}\". Accepted: ${SUPPORTED_FORMATS.join(\", \")}.`,\n );\n }\n const format: \"markdown\" | \"json\" = request.format === \"json\"\n ? \"json\"\n : request.format === \"markdown\"\n ? \"markdown\"\n : config.briefing.defaultFormat;\n\n const maxFollowups = typeof request.maxFollowups === \"number\" && Number.isFinite(request.maxFollowups)\n ? Math.max(0, Math.min(10, Math.floor(request.maxFollowups)))\n : config.briefing.maxFollowups;\n\n const calendarSource = config.briefing.calendarSource\n ? new FileCalendarSource(config.briefing.calendarSource)\n : undefined;\n\n const result = await buildBriefing({\n storage,\n namespace,\n window,\n focus,\n calendarSource,\n maxFollowups,\n allowLlm: config.briefing.llmFollowups,\n openaiApiKey: config.openaiApiKey,\n openaiBaseUrl: config.openaiBaseUrl,\n model: config.model,\n // Without a direct OpenAI key, route follow-ups through the configured\n // LLM chain (gateway model source or local LLM) — same fallback every\n // other LLM feature uses. A configured key keeps its precedence so\n // existing deployments are unchanged.\n followupGenerator: config.openaiApiKey\n ? undefined\n : this.orchestrator.briefingChainFollowupGenerator,\n });\n\n return {\n format,\n window: result.window,\n namespace,\n markdown: result.markdown,\n json: result.json,\n followupsUnavailableReason: result.followupsUnavailableReason,\n };\n }\n\n /**\n * Attach a coding context to a session (issue #569). Used by the Claude\n * Code / Codex / generic-MCP connectors at session start so that recall +\n * write paths can route to a project- / branch-scoped namespace.\n *\n * Validates the input shape and rejects malformed payloads rather than\n * silently accepting them (CLAUDE.md #51). Pass `codingContext: null` to\n * clear.\n */\n setCodingContext(request: EngramAccessSetCodingContextRequest): void {\n const sessionKey = typeof request.sessionKey === \"string\" ? request.sessionKey.trim() : \"\";\n if (!sessionKey) {\n throw new EngramAccessInputError(\"sessionKey is required for setCodingContext\");\n }\n if (request.codingContext === null) {\n this.orchestrator.setCodingContextForSession(sessionKey, null);\n return;\n }\n const ctx = request.codingContext;\n if (!ctx || typeof ctx !== \"object\") {\n throw new EngramAccessInputError(\"codingContext must be an object or null\");\n }\n if (typeof ctx.projectId !== \"string\" || ctx.projectId.trim().length === 0) {\n throw new EngramAccessInputError(\"codingContext.projectId must be a non-empty string\");\n }\n // Whitespace-only rootPath must be rejected just like whitespace-only\n // projectId — otherwise a payload like `{ rootPath: \" \" }` slips past\n // validation and produces a session whose rootPath is meaningless for\n // `remnic doctor` output and for downstream namespace decisions.\n if (typeof ctx.rootPath !== \"string\" || ctx.rootPath.trim().length === 0) {\n throw new EngramAccessInputError(\"codingContext.rootPath must be a non-empty string\");\n }\n if (ctx.branch !== null && typeof ctx.branch !== \"string\") {\n throw new EngramAccessInputError(\"codingContext.branch must be a string or null\");\n }\n if (ctx.defaultBranch !== null && typeof ctx.defaultBranch !== \"string\") {\n throw new EngramAccessInputError(\"codingContext.defaultBranch must be a string or null\");\n }\n this.orchestrator.setCodingContextForSession(sessionKey, {\n projectId: ctx.projectId,\n branch: ctx.branch,\n rootPath: ctx.rootPath,\n defaultBranch: ctx.defaultBranch,\n });\n }\n\n /**\n * Auto-resolve and attach a coding context for a session when one is not\n * already present. Resolves from `projectTag` (highest priority after\n * explicit `codingContext`), then from `cwd` via git detection.\n *\n * This is a no-op when:\n * - `sessionKey` is missing\n * - the session already has a coding context attached\n * - codingMode.projectScope is disabled (CLAUDE.md #30)\n * - neither `cwd` nor `projectTag` is provided\n *\n * Never throws — git resolution failures are silently ignored because not\n * being in a repo is a normal runtime state.\n */\n private async maybeAttachCodingContext(\n sessionKey: string | undefined,\n options: { cwd?: string; projectTag?: string },\n ): Promise<void> {\n if (!sessionKey) return;\n // Respect the configuration gate (CLAUDE.md #30).\n if (!this.orchestrator.config.codingMode?.projectScope) return;\n // Don't overwrite an already-attached context.\n if (this.orchestrator.getCodingContextForSession(sessionKey)) return;\n // projectTag takes priority over cwd.\n if (typeof options.projectTag === \"string\" && options.projectTag.trim().length > 0) {\n const projectId = projectTagProjectId(options.projectTag);\n this.orchestrator.setCodingContextForSession(sessionKey, {\n projectId,\n branch: null,\n rootPath: projectId,\n defaultBranch: null,\n });\n return;\n }\n // cwd → git resolution\n if (typeof options.cwd === \"string\" && options.cwd.trim().length > 0) {\n try {\n const gitCtx = await resolveGitContext(options.cwd);\n if (gitCtx) {\n this.setCodingContext({\n sessionKey,\n codingContext: {\n projectId: gitCtx.projectId,\n branch: gitCtx.branch,\n rootPath: gitCtx.rootPath,\n defaultBranch: gitCtx.defaultBranch,\n },\n });\n }\n } catch {\n // Silently ignore git resolution failures — not being in a repo\n // is normal. resolveGitContext itself never throws, but the\n // setCodingContext validation might reject edge-case rootPaths.\n }\n }\n }\n\n /**\n * Seed the session's coding binding AFTER a committed, project-scoped explicit\n * write (memory_store / suggestion_submit), mirroring the recall path's\n * `maybeAttachCodingContext` so a later bare recall/write on the same session\n * is scoped to the same project. Called only from the post-persist path, so it\n * never fires on dryRun, replay/conflict, or quota-rejected requests. Skips\n * when an explicit `namespace` was supplied — that write bypassed the coding\n * overlay, so binding the session to a project it never wrote to would make\n * later bare recalls miss (Codex review).\n */\n private async attachCodingContextAfterScopedWrite(\n request: CodingScopedWriteInput & { namespace?: string; sessionKey?: string },\n ): Promise<void> {\n const hasExplicitNamespace =\n typeof request.namespace === \"string\" && request.namespace.trim().length > 0;\n if (hasExplicitNamespace) return;\n await this.maybeAttachCodingContext(request.sessionKey, {\n cwd: request.cwd,\n projectTag: request.projectTag,\n });\n }\n\n async recall(request: EngramAccessRecallRequest): Promise<EngramAccessRecallResponse> {\n const query = request.query.trim();\n if (query.length === 0) {\n throw new EngramAccessInputError(\"query is required\");\n }\n const normalizedRequest = { ...request, query };\n const authenticatedPrincipal = request.authenticatedPrincipal?.trim();\n const principal = this.resolveRequestPrincipal(request.sessionKey, authenticatedPrincipal);\n if (this.orchestrator.config.namespacesEnabled && !principal) {\n throw new EngramAccessInputError(\n \"authentication required: namespaces are enabled and no principal was supplied\",\n );\n }\n const budgetLockPrincipal = principal ?? \"default\";\n return this.withBudgetLock(budgetLockPrincipal, async () => {\n let budgetRecordPrincipal: string | null = null;\n const response = await this.handleIdempotentRead({\n operation: \"recall\",\n idempotencyKey: request.idempotencyKey,\n requestFingerprint: normalizedRequest,\n execute: async () => {\n const result = await this.executeRecall(normalizedRequest);\n budgetRecordPrincipal = result.budgetRecordPrincipal;\n return result.response;\n },\n afterStore: () => {\n if (!budgetRecordPrincipal) return;\n const recordedBudgetDecision = this.budget.record(budgetRecordPrincipal);\n if (!recordedBudgetDecision.allowed) {\n throw new EngramAccessInputError(\n `recall denied: cross-namespace budget exceeded (${recordedBudgetDecision.count}/${recordedBudgetDecision.limit.hardLimit} in ${recordedBudgetDecision.limit.windowMs}ms window)`,\n );\n }\n },\n });\n return response;\n });\n }\n\n private async executeRecall(\n request: EngramAccessRecallRequest,\n ): Promise<{\n response: EngramAccessRecallResponse;\n budgetRecordPrincipal: string | null;\n }> {\n const query = request.query;\n // Disclosure depth (issue #677). Default to `\"chunk\"` when omitted so\n // pre-#677 callers see unchanged behavior. Reject explicitly invalid\n // string values per CLAUDE.md rule 51 (do not silently fall back).\n const callerProvidedDisclosure =\n request.disclosure !== undefined && request.disclosure !== null;\n const requestedDisclosure: RecallDisclosure = (() => {\n if (!callerProvidedDisclosure) {\n return DEFAULT_RECALL_DISCLOSURE;\n }\n if (!isRecallDisclosure(request.disclosure)) {\n throw new EngramAccessInputError(\n `disclosure must be one of: chunk, section, raw (got: ${String(request.disclosure)})`,\n );\n }\n return request.disclosure;\n })();\n // Attach any coding context shipped with the recall request BEFORE\n // namespace resolution so the overlay applies to this recall (issue #569).\n if (request.codingContext !== undefined && request.sessionKey) {\n this.setCodingContext({\n sessionKey: request.sessionKey,\n codingContext: request.codingContext,\n });\n }\n // Auto-resolve coding context from cwd/projectTag when no explicit\n // codingContext was supplied (issue #569 wiring). This allows Claude\n // Code hooks and OpenClaw connectors to get project-scoped memory\n // transparently.\n if (request.codingContext === undefined && request.sessionKey) {\n await this.maybeAttachCodingContext(request.sessionKey, {\n cwd: request.cwd,\n projectTag: request.projectTag,\n });\n }\n const authenticatedPrincipal = request.authenticatedPrincipal?.trim();\n const namespaceOverride = this.resolveRecallNamespace(\n request.namespace,\n request.sessionKey,\n authenticatedPrincipal,\n );\n const namespace = namespaceOverride ?? this.orchestrator.config.defaultNamespace;\n // Normalize mode early so that no_recall / invalid modes skip budget\n // accounting (Codex P1: budget recorded before mode validation).\n const mode = this.normalizeRecallMode(request.mode);\n const maybePrincipal = this.resolveRequestPrincipal(request.sessionKey, authenticatedPrincipal);\n if (this.orchestrator.config.namespacesEnabled && !maybePrincipal) {\n throw new EngramAccessInputError(\n \"authentication required: namespaces are enabled and no principal was supplied\",\n );\n }\n const principal = maybePrincipal ?? \"default\";\n const principalNamespace = defaultNamespaceForPrincipal(principal, this.orchestrator.config);\n // Skip budget checks for modes that never perform a cross-namespace read.\n const modeSkipsBudget = mode === \"no_recall\";\n // Derive the full set of namespaces the orchestrator will actually search.\n // When no explicit override is provided, `recallNamespacesForPrincipal()` may\n // expand to shared / policy-default namespaces. Budget must be checked\n // against every cross-namespace entry in the effective set so that omitting\n // `namespace` cannot bypass the limiter (Cursor/Codex review feedback).\n //\n // NOTE: coding overlays (branch/project scope) are resolved inside\n // orchestrator.recall() AFTER this check. The access-service does not\n // duplicate that resolution here to avoid tight coupling. Coding-overlay\n // namespaces are a second-layer defense covered by the anomaly detector\n // (PR 5/5 of issue #565).\n const effectiveNamespaces = namespaceOverride\n ? [namespaceOverride]\n : recallNamespacesForPrincipal(principal, this.orchestrator.config);\n let budgetDecision: BudgetDecision;\n let recordBudgetAfterSuccess = false;\n if (modeSkipsBudget) {\n budgetDecision = {\n allowed: true as const,\n reason: \"allowed-same-namespace\" as const,\n count: 0,\n limit: {\n softLimit: this.orchestrator.config.recallCrossNamespaceBudgetSoftLimit ?? 10,\n hardLimit: this.orchestrator.config.recallCrossNamespaceBudgetHardLimit ?? 30,\n windowMs: this.orchestrator.config.recallCrossNamespaceBudgetWindowMs ?? 60_000,\n },\n };\n } else {\n // Peek at every effective namespace to determine whether ANY would be\n // cross-namespace WITHOUT recording side effects (Cursor review:\n // multi-count bug). Record a single budget event only when at least\n // one effective namespace differs from the principal's self namespace,\n // and only after recall succeeds so retried transient failures do not\n // consume budget multiple times before a successful response can be\n // cached behind the request idempotency key.\n let anyCrossNamespace = false;\n let denied: BudgetDecision | null = null;\n let crossNamespaceDecision: BudgetDecision | null = null;\n for (const ns of effectiveNamespaces) {\n const peek = this.budget.peek({\n principal,\n principalNamespace,\n queryNamespace: ns,\n });\n if (peek.reason !== \"allowed-same-namespace\") {\n anyCrossNamespace = true;\n crossNamespaceDecision ??= peek;\n }\n if (!peek.allowed) {\n denied = peek;\n break;\n }\n }\n if (denied) {\n // The peek projected a denial — deny without recording so the\n // bucket is not inflated by rejected attempts.\n budgetDecision = denied;\n } else if (anyCrossNamespace) {\n budgetDecision = crossNamespaceDecision ?? {\n allowed: true as const,\n reason: \"allowed-under-soft\" as const,\n count: 0,\n limit: {\n softLimit: this.orchestrator.config.recallCrossNamespaceBudgetSoftLimit ?? 10,\n hardLimit: this.orchestrator.config.recallCrossNamespaceBudgetHardLimit ?? 30,\n windowMs: this.orchestrator.config.recallCrossNamespaceBudgetWindowMs ?? 60_000,\n },\n };\n recordBudgetAfterSuccess = true;\n } else {\n budgetDecision = {\n allowed: true as const,\n reason: \"allowed-same-namespace\" as const,\n count: 0,\n limit: {\n softLimit: this.orchestrator.config.recallCrossNamespaceBudgetSoftLimit ?? 10,\n hardLimit: this.orchestrator.config.recallCrossNamespaceBudgetHardLimit ?? 30,\n windowMs: this.orchestrator.config.recallCrossNamespaceBudgetWindowMs ?? 60_000,\n },\n };\n }\n if (!budgetDecision.allowed) {\n throw new EngramAccessInputError(\n `recall denied: cross-namespace budget exceeded (${budgetDecision.count}/${budgetDecision.limit.hardLimit} in ${budgetDecision.limit.windowMs}ms window)`,\n );\n }\n // Prune expired principal buckets to prevent unbounded Map growth from\n // high-cardinality / transient principals (Codex P2 review feedback).\n this.budget.gc();\n }\n const topK = Number.isFinite(request.topK) ? Math.max(0, Math.floor(request.topK ?? 0)) : undefined;\n // Issue #680 — historical recall pin. Validate at the input\n // boundary so a malformed `asOf` is rejected with a structured\n // 400 instead of silently flooring at NaN inside the orchestrator\n // (CLAUDE.md rule 51, gotcha #51). Empty / undefined is fine —\n // means \"no pin\".\n let asOf: string | undefined;\n if (request.asOf !== undefined && request.asOf !== null) {\n if (typeof request.asOf !== \"string\" || request.asOf.trim().length === 0) {\n throw new EngramAccessInputError(\n \"asOf must be a non-empty ISO 8601 timestamp string\",\n );\n }\n const parsed = Date.parse(request.asOf);\n if (!Number.isFinite(parsed)) {\n throw new EngramAccessInputError(\n `asOf must be a parseable ISO 8601 timestamp (got: \"${request.asOf}\")`,\n );\n }\n asOf = request.asOf;\n }\n const recallOptions: RecallInvocationOptions = {\n namespace: namespaceOverride,\n topK,\n mode,\n ...(authenticatedPrincipal ? { principalOverride: authenticatedPrincipal } : {}),\n ...(asOf !== undefined ? { asOf } : {}),\n ...(request.includeLowConfidence === true ? { includeLowConfidence: true } : {}),\n };\n const startedAt = Date.now();\n const context = await this.orchestrator.recall(query, request.sessionKey, recallOptions);\n const snapshot = request.sessionKey\n ? this.orchestrator.lastRecall.get(request.sessionKey)\n : null;\n const effectiveNamespace = snapshot?.namespace\n ? this.resolveNamespace(snapshot.namespace)\n : namespace;\n // Auto-escalation policy (issue #677 PR 4/4). When the operator\n // configured `recallDisclosureEscalation: \"auto\"` AND the caller\n // did not explicitly choose a disclosure level AND recall produced\n // a low-confidence result set (proxied by fill ratio: results\n // returned / topK requested), we escalate the default `chunk`\n // shape to `section` so the LLM gets richer context to compensate\n // for ambiguous retrieval. Manual mode and explicit caller\n // disclosure both bypass the policy. Documented in\n // `recall-disclosure-escalation.ts` and unit-tested there.\n // Confidence-proxy denominator: priority order is\n // 1. `snapshot.budgetsApplied.appliedTopK` (ALWAYS wins) — this is\n // the limit the orchestrator actually applied after planner /\n // minimal-mode / section-cap narrowing. Codex P1 rounds 2+3\n // on #705 emphasize that even a caller's explicit `request.topK`\n // is wrong when the orchestrator caps below it (e.g. topK=50\n // but appliedTopK=3 makes a 2-hit recall actually 0.67, not\n // 0.04).\n // 2. The caller's explicit `topK` when the snapshot lacks\n // `budgetsApplied` (early-return paths, error cases).\n // 3. Config `qmdMaxResults` as a last-resort fallback.\n // Floor at observed-results so the ratio stays in [0, 1] even if\n // any of the signals drifts below the actual hit count.\n const resultsReturned = snapshot?.memoryIds?.length ?? 0;\n const appliedTopK = snapshot?.budgetsApplied?.appliedTopK;\n const configMaxResults =\n typeof this.orchestrator.config.qmdMaxResults === \"number\" &&\n Number.isFinite(this.orchestrator.config.qmdMaxResults) &&\n this.orchestrator.config.qmdMaxResults > 0\n ? this.orchestrator.config.qmdMaxResults\n : 0;\n const topKDenominator =\n typeof appliedTopK === \"number\" &&\n Number.isFinite(appliedTopK) &&\n appliedTopK > 0\n ? Math.max(appliedTopK, resultsReturned)\n : typeof topK === \"number\" && topK > 0\n ? Math.max(topK, resultsReturned)\n : Math.max(configMaxResults, resultsReturned, 1);\n // When the recall produced no snapshot (sessionless / namespace\n // mismatch / early-return path), there is no confidence signal to\n // base escalation on. Pass `undefined` so the helper takes its\n // `no-top-k-confidence` branch instead of computing 0/N=0 and\n // forcing auto-escalation on every sessionless caller (Codex P2\n // review on PR #705).\n const topKConfidence =\n snapshot && topKDenominator > 0\n ? Math.min(1, resultsReturned / topKDenominator)\n : undefined;\n const escalationDecision = decideDisclosureEscalation({\n mode: this.orchestrator.config.recallDisclosureEscalation,\n threshold: this.orchestrator.config.recallDisclosureEscalationThreshold,\n originalDisclosure: requestedDisclosure,\n callerProvidedDisclosure,\n topKConfidence,\n });\n const disclosure = escalationDecision.effective;\n // Gate the raw-excerpt LCM read with the SAME read-authorization namespace\n // `lcmSearch` + the in-prompt LCM sections use (#1505 thread 2f7), so\n // `disclosure: \"raw\"` never attaches `<principal>-project-*` overlay rows\n // when the principal can WRITE but not READ its self base (or\n // `defaultRecallNamespaces` omits `self`). Computed ONLY for raw disclosure:\n // it is the sole consumer, and resolving the overlay on every chunk/section\n // recall would be wasted work — keeping non-raw recall byte-for-byte\n // unchanged.\n // Trim the sessionKey to match what `orchestrator.recall(...)` already does\n // (`request.sessionKey?.trim() || undefined`) and what the x-ray raw-excerpt\n // path uses (cursor \"Raw excerpt key not trimmed\"). A whitespace-padded key\n // otherwise drives recall under one identity but resolves the raw-excerpt\n // overlay namespace + LCM `session_id` under a DIFFERENT (untrimmed) prefix,\n // so excerpts are gated/queried inconsistently with recall and the x-ray path.\n const trimmedSessionKey = request.sessionKey?.trim() || undefined;\n const rawExcerptNamespace =\n disclosure === \"raw\"\n ? this.resolveRawExcerptReadNamespace(\n request.namespace,\n trimmedSessionKey,\n authenticatedPrincipal,\n )\n : undefined;\n // `undefined` for an IMPLICIT raw recall means NO readable LCM namespace\n // exists (restrictive `default` READ policy, no readable overlay/self) —\n // suppress excerpts rather than fall back to the write/overlay namespace the\n // read gate excludes (#1505 thread NBHWz). An EXPLICIT namespace always\n // resolves (or throws) above, so suppression only applies to the implicit\n // path.\n const hasExplicitNamespace =\n typeof request.namespace === \"string\" &&\n request.namespace.trim().length > 0;\n const rawExcerptsSuppressed =\n disclosure === \"raw\" &&\n !hasExplicitNamespace &&\n rawExcerptNamespace === undefined;\n // Ordered, read-authorized LCM read key SET (#1505 fallback unification) so\n // raw disclosure finds excerpts a branch-scoped session archived at\n // project/root scope — exactly as recall + `lcmSearch` do. Only with a\n // concrete sessionKey; already read-gated.\n const rawExcerptSessionIds =\n disclosure === \"raw\" && rawExcerptNamespace && trimmedSessionKey\n ? this.resolveLcmReadSessionIds(\n request.namespace,\n rawExcerptNamespace,\n trimmedSessionKey,\n authenticatedPrincipal,\n )\n : undefined;\n let results = await this.serializeRecallResults(snapshot, disclosure, {\n query,\n sessionKey: trimmedSessionKey,\n ...(rawExcerptNamespace ? { rawExcerptNamespace } : {}),\n ...(rawExcerptSessionIds ? { rawExcerptSessionIds } : {}),\n ...(rawExcerptsSuppressed ? { rawExcerptsSuppressed } : {}),\n });\n\n // Tag filter (issue #689). Applied post-recall, post-serialization so\n // the actual frontmatter tags are already loaded onto each result. When\n // `tags` is absent or empty the filter is a no-op; an invalid `tagMatch`\n // throws via `parseTagMatch` (CLAUDE.md rule 51).\n const filterTags = normalizeTags(request.tags);\n let tagMatchMode: TagMatchMode | undefined;\n try {\n tagMatchMode = parseTagMatch(request.tagMatch);\n } catch (err) {\n throw new EngramAccessInputError(\n err instanceof Error ? err.message : String(err),\n );\n }\n let effectiveContext = context;\n if (filterTags && filterTags.length > 0) {\n const beforeIds = results.map((r) => r.id);\n const { results: admitted } = applyTagFilter(results, {\n tags: filterTags,\n tagMatch: tagMatchMode,\n });\n results = admitted;\n // Codex P1: `context` was generated by orchestrator.recall(...)\n // BEFORE the tag filter ran, so it can contain memories that don't\n // match the requested tags. Surfaces consuming `context` (the\n // prompt-injection string) would leak excluded content into the\n // LLM. When the filter actually drops any result, rebuild context\n // from the admitted set so excluded content is unreachable through\n // any field of the response. The rebuilt context concatenates each\n // admitted result's available text (full content at section/raw\n // disclosure, otherwise the preview) — a different wire format\n // than the orchestrator's native context, but a strict subset\n // safe to inject.\n const admittedIds = new Set(results.map((r) => r.id));\n const droppedAny = beforeIds.some((id) => !admittedIds.has(id));\n if (droppedAny) {\n effectiveContext = results\n .map((r) => {\n const content =\n typeof (r as { content?: unknown }).content === \"string\"\n ? ((r as { content?: string }).content ?? \"\")\n : \"\";\n const preview =\n typeof (r as { preview?: unknown }).preview === \"string\"\n ? ((r as { preview?: string }).preview ?? \"\")\n : \"\";\n return content || preview;\n })\n .filter((s) => s.length > 0)\n .join(\"\\n\\n\");\n }\n }\n const filteredMemoryIds = filterTags && filterTags.length > 0\n ? results.map((r) => r.id)\n : (snapshot?.memoryIds ?? []);\n const debug = await this.buildRecallDebug(\n snapshot,\n effectiveNamespace,\n request.includeDebug === true,\n request.sessionKey,\n );\n\n // Fire-and-forget audit recording. Must never block or crash recall.\n let auditAnomalies: AccessAuditResult[\"anomalies\"] | undefined;\n if (this.auditAdapter) {\n try {\n const resolvedAgentId = principal ?? \"__anonymous__\";\n const auditEntry = {\n ts: new Date().toISOString(),\n sessionKey: request.sessionKey ?? \"\",\n agentId: resolvedAgentId,\n trigger: \"access-surface\",\n queryText: query,\n candidateMemoryIds: snapshot?.memoryIds ?? [],\n // Audit must reflect what was actually injected, not what\n // recall produced before the tag filter. Using `context`\n // (pre-filter) overstates injectedChars and can leak content\n // from excluded memories into the audit summary (cursor\n // Medium on PR #712).\n summary: effectiveContext.slice(0, 200) || null,\n injectedChars: effectiveContext.length,\n toggleState: \"enabled\" as const,\n latencyMs: Date.now() - startedAt,\n plannerMode: snapshot?.plannerMode ?? mode,\n requestedMode: mode,\n fallbackUsed: snapshot?.fallbackUsed ?? false,\n };\n const auditResult = await this.auditAdapter.record(\n resolvedAgentId || \"__anonymous__\",\n auditEntry,\n );\n auditAnomalies = auditResult.anomalies;\n } catch {\n // Audit failures must never crash the recall path.\n }\n }\n\n return {\n response: {\n query,\n sessionKey: request.sessionKey,\n namespace: effectiveNamespace,\n context: effectiveContext,\n count: filterTags && filterTags.length > 0\n ? results.length\n : (snapshot?.memoryIds.length ?? results.length),\n memoryIds: filteredMemoryIds,\n results,\n recordedAt: snapshot?.recordedAt,\n traceId: snapshot?.traceId,\n plannerMode: snapshot?.plannerMode ?? mode,\n fallbackUsed: snapshot?.fallbackUsed ?? false,\n sourcesUsed: snapshot?.sourcesUsed ?? [],\n disclosure,\n budgetsApplied: snapshot?.budgetsApplied,\n auditAnomalies,\n budgetWarning: budgetDecision.reason === \"warn-over-soft\" ? budgetDecision : undefined,\n latencyMs: snapshot?.latencyMs ?? (Date.now() - startedAt),\n debug,\n },\n budgetRecordPrincipal: recordBudgetAfterSuccess ? principal : null,\n };\n }\n\n async recallExplain(\n request: EngramAccessRecallExplainRequest = {},\n ): Promise<EngramAccessRecallExplainResponse> {\n const requestedNamespace = request.namespace?.trim()\n ? this.resolveNamespace(request.namespace)\n : undefined;\n const authenticatedPrincipal = request.authenticatedPrincipal?.trim();\n const principal =\n authenticatedPrincipal\n || resolvePrincipal(request.sessionKey, this.orchestrator.config);\n if (requestedNamespace) {\n if (!canReadNamespace(principal, requestedNamespace, this.orchestrator.config)) {\n return { found: false };\n }\n } else if (\n this.orchestrator.config.namespacesEnabled\n && !principal\n ) {\n return { found: false };\n }\n const snapshot = request.sessionKey\n ? (() => {\n const candidate = this.orchestrator.lastRecall.get(request.sessionKey);\n if (!candidate) return null;\n if (!requestedNamespace) return candidate;\n return candidate.namespace === requestedNamespace ? candidate : null;\n })()\n : (() => {\n const candidate = this.orchestrator.lastRecall.getMostRecent();\n if (!candidate) return null;\n if (!requestedNamespace) return candidate;\n return candidate.namespace === requestedNamespace ? candidate : null;\n })();\n const readableSnapshot = (() => {\n if (!snapshot || !this.orchestrator.config.namespacesEnabled) return snapshot;\n const snapshotNamespace = snapshot.namespace ?? this.orchestrator.config.defaultNamespace;\n return canReadNamespace(principal, snapshotNamespace, this.orchestrator.config)\n ? snapshot\n : null;\n })();\n const namespace = (() => {\n if (requestedNamespace) return requestedNamespace;\n if (readableSnapshot?.namespace) return readableSnapshot.namespace;\n const fallbackNamespace = this.orchestrator.config.defaultNamespace;\n if (!this.orchestrator.config.namespacesEnabled) return fallbackNamespace;\n return canReadNamespace(principal, fallbackNamespace, this.orchestrator.config)\n ? fallbackNamespace\n : null;\n })();\n if (!namespace) return { found: false };\n const [intent, graph] = await Promise.all([\n this.orchestrator.getLastIntentSnapshot(namespace),\n this.orchestrator.getLastGraphRecallSnapshot(namespace),\n ]);\n if (!readableSnapshot && !intent && !graph) return { found: false };\n return { found: true, snapshot: readableSnapshot ?? undefined, intent, graph };\n }\n\n async recallTierExplain(\n sessionKey?: string,\n namespace?: string,\n authenticatedPrincipal?: string,\n ) {\n const namespacesEnabled = this.orchestrator.config.namespacesEnabled;\n const requestedNamespace = namespace?.trim()\n ? this.resolveNamespace(namespace)\n : undefined;\n const principal = authenticatedPrincipal?.trim()\n || resolvePrincipal(sessionKey, this.orchestrator.config);\n\n if (requestedNamespace) {\n if (!canReadNamespace(principal, requestedNamespace, this.orchestrator.config)) {\n return toRecallExplainJson(null);\n }\n } else if (namespacesEnabled && !authenticatedPrincipal?.trim() && !sessionKey?.trim()) {\n return toRecallExplainJson(null);\n }\n\n const candidate = sessionKey\n ? this.orchestrator.lastRecall.get(sessionKey)\n : this.orchestrator.lastRecall.getMostRecent();\n\n const snapshot = (() => {\n if (!candidate) return null;\n if (requestedNamespace) {\n return candidate.namespace === requestedNamespace ? candidate : null;\n }\n if (!namespacesEnabled) return candidate;\n const snapshotNs = candidate.namespace\n ?? this.orchestrator.config.defaultNamespace;\n return canReadNamespace(principal, snapshotNs, this.orchestrator.config)\n ? candidate\n : null;\n })();\n\n return toRecallExplainJson(snapshot);\n }\n\n /**\n * Recall X-ray (issue #570). Runs a recall with `xrayCapture: true`\n * and returns the resulting snapshot as structured JSON so every\n * surface (CLI / HTTP / MCP) gets the same payload. Namespace scope\n * is enforced before the recall fires (CLAUDE.md rule 42 — read and\n * write paths must resolve through the same namespace layer) so an\n * unauthorized principal cannot capture an x-ray for a namespace it\n * cannot read.\n */\n async recallXray(request: {\n query: string;\n sessionKey?: string;\n namespace?: string;\n budget?: number;\n authenticatedPrincipal?: string;\n /**\n * Disclosure depth used to shape per-result payload (issue #677\n * PR 3/4). When set, each X-ray result is decorated with the\n * matching `disclosure` field and `estimatedTokens` computed from\n * the actual rendered content at that depth, so the renderer's\n * \"Token spend by disclosure\" summary reflects real spend rather\n * than staying empty when no caller wires the depth knob through.\n */\n disclosure?: RecallDisclosure;\n /**\n * Free-form recall tag filter (issue #689). Mirrors the field on\n * `EngramAccessRecallRequest`. When non-empty, the captured X-ray\n * snapshot's `results` are filtered down to memories whose\n * frontmatter tags satisfy `tagMatch` (\"any\" by default), and a\n * `tag-filter` entry is appended to `filters`.\n */\n tags?: string[];\n /** Match mode for `tags`. See `EngramAccessRecallRequest.tagMatch`. */\n tagMatch?: \"any\" | \"all\";\n /** Recall planner mode override. Mirrors `EngramAccessRecallRequest.mode`. */\n mode?: RecallPlanMode | \"auto\";\n /**\n * User-aware context scopes active for this recall. Forwarded into\n * provenance construction so boundary scopes are evaluated against\n * the caller's real context instead of an empty-context default.\n */\n currentContextScopes?: readonly unknown[];\n /**\n * Internal inspector affordance: include a recall-shaped response\n * derived from the same X-ray snapshot. Left off by default so the\n * regular X-ray API/CLI/MCP surfaces keep their existing payload shape.\n */\n includeRecall?: boolean;\n }): Promise<{\n snapshotFound: boolean;\n snapshot?: RecallXraySnapshot;\n recall?: EngramAccessRecallResponse;\n }> {\n const query = typeof request.query === \"string\" ? request.query : \"\";\n if (query.trim().length === 0) {\n // Match the CLI contract (CLAUDE.md rule 51): reject empty\n // input with an explicit error rather than silently producing\n // an empty snapshot.\n throw new Error(\"recallXray: query is required and must be non-empty\");\n }\n // Validate disclosure UP FRONT — before recall executes, before\n // the xray queue mutex is acquired, before namespace resolution.\n // A bad value should fail fast rather than after we've burned\n // cycles on an irreversible recall (Cursor Medium review on PR\n // #699).\n if (\n request.disclosure !== undefined &&\n !isRecallDisclosure(request.disclosure)\n ) {\n throw new EngramAccessInputError(\n `recallXray: disclosure must be one of: chunk, section, raw (got: ${String(request.disclosure)})`,\n );\n }\n\n const namespacesEnabled = this.orchestrator.config.namespacesEnabled;\n const requestedNamespace = request.namespace?.trim()\n ? this.resolveNamespace(request.namespace)\n : undefined;\n const authenticatedPrincipal = request.authenticatedPrincipal?.trim();\n const principal =\n authenticatedPrincipal\n || resolvePrincipal(request.sessionKey, this.orchestrator.config);\n\n if (requestedNamespace) {\n if (\n !canReadNamespace(\n principal,\n requestedNamespace,\n this.orchestrator.config,\n )\n ) {\n return { snapshotFound: false };\n }\n } else if (\n namespacesEnabled\n && !authenticatedPrincipal\n && !request.sessionKey?.trim()\n ) {\n // Namespaces enabled but no identity supplied — reject rather\n // than scanning the global namespace (CLAUDE.md rule 48:\n // least-privileged default).\n return { snapshotFound: false };\n }\n\n // Optional `--budget` override must be a positive integer. Invalid\n // values throw rather than silently defaulting (CLAUDE.md rule 51).\n let budgetOverride: number | undefined;\n if (request.budget !== undefined && request.budget !== null) {\n const parsed =\n typeof request.budget === \"number\"\n ? request.budget\n : Number(request.budget);\n if (\n !Number.isFinite(parsed)\n || parsed <= 0\n || !Number.isInteger(parsed)\n ) {\n throw new Error(\n `recallXray: budget expects a positive integer; got ${JSON.stringify(request.budget)}`,\n );\n }\n budgetOverride = parsed;\n }\n const mode = this.normalizeRecallMode(request.mode);\n const disclosure = request.disclosure ?? DEFAULT_RECALL_DISCLOSURE;\n\n // Serialize x-ray invocations behind a per-service mutex so the\n // per-process `getLastXraySnapshot()` slot cannot be clobbered by\n // a concurrent capturing call before this caller reads it back.\n // Budget and principal are now threaded through\n // `RecallInvocationOptions`, so global config mutation is gone\n // (CLAUDE.md rule 47: no shared mutable state across async\n // boundaries). The mutex stays only for the snapshot-slot\n // ordering guarantee.\n const previousQueue = this.xrayQueue;\n let release: () => void = () => {};\n this.xrayQueue = new Promise<void>((resolve) => {\n release = resolve;\n });\n await previousQueue;\n const recallStartedAt = Date.now();\n\n const recallSessionKey = request.sessionKey?.trim() || undefined;\n let xrayResponse: {\n snapshotFound: boolean;\n snapshot?: RecallXraySnapshot;\n } = { snapshotFound: false };\n\n try {\n // Clear any prior snapshot so a capture failure surfaces as\n // `{snapshotFound: false}` rather than returning stale data\n // from an earlier call on the same orchestrator.\n this.orchestrator.clearLastXraySnapshot();\n await this.orchestrator.recall(query, recallSessionKey, {\n xrayCapture: true,\n ...(requestedNamespace ? { namespace: requestedNamespace } : {}),\n ...(budgetOverride !== undefined\n ? { budgetCharsOverride: budgetOverride }\n : {}),\n ...(mode !== undefined ? { mode } : {}),\n // When the caller supplies an authenticated principal, forward\n // it via the dedicated override channel so orchestrator-side\n // ACL decisions use the SAME principal the access-surface\n // pre-check above authorized. Threading an\n // `authenticatedPrincipal` through `sessionKey` would be wrong:\n // `resolvePrincipal(sessionKey)` only maps configured raw\n // session keys and otherwise collapses to `\"default\"`, which\n // in namespace-enabled deployments produces false denials /\n // wrong-scope serving despite the pre-check passing\n // (CLAUDE.md rule 42).\n ...(authenticatedPrincipal\n ? { principalOverride: authenticatedPrincipal }\n : {}),\n ...(request.currentContextScopes !== undefined\n ? { currentContextScopes: request.currentContextScopes }\n : {}),\n });\n\n const rawSnapshot = this.orchestrator.getLastXraySnapshot();\n // Re-check namespace after capture: the recall may have served\n // from a different namespace than the caller requested. Drop\n // the snapshot rather than leak cross-tenant data (CLAUDE.md\n // rules 42 + 47). The comparison is strict so a snapshot whose\n // namespace is `undefined` cannot bypass the scope the caller\n // asked for.\n const namespaceMismatch =\n requestedNamespace !== undefined &&\n rawSnapshot?.namespace !== requestedNamespace;\n if (!rawSnapshot) {\n xrayResponse = { snapshotFound: false };\n } else if (namespaceMismatch) {\n xrayResponse = { snapshotFound: false };\n } else {\n // Tag filter (issue #689). Mirrors `recall()` semantics — applied\n // post-capture by reading each result's frontmatter tags and\n // dropping non-matching results. Filter activity surfaces as a\n // `tag-filter` entry in `snapshot.filters` so X-ray consumers can\n // see the \"considered → admitted\" delta.\n let snapshot = rawSnapshot;\n const xrayFilterTags = normalizeTags(request.tags);\n let xrayTagMatch: TagMatchMode | undefined;\n try {\n xrayTagMatch = parseTagMatch(request.tagMatch);\n } catch (err) {\n throw new EngramAccessInputError(\n err instanceof Error ? err.message : String(err),\n );\n }\n if (xrayFilterTags && xrayFilterTags.length > 0) {\n const namespace = snapshot.namespace\n ? this.resolveNamespace(snapshot.namespace)\n : this.orchestrator.config.defaultNamespace;\n const tagsByIndex = await Promise.all(\n snapshot.results.map(async (result) => {\n try {\n const storage = await this.orchestrator.getStorage(namespace);\n const memory = await storage.readMemoryByPath(result.path);\n const t = memory?.frontmatter?.tags;\n // Normalize identically to the recall path\n // (`normalizeProjectionTags`): trim and drop empty strings\n // so X-ray tag matching stays consistent with the recall\n // surface. Without this, a frontmatter tag like \" draft \"\n // would match in recall but not in X-ray (cursor review).\n return Array.isArray(t) ? normalizeProjectionTags(t) : [];\n } catch {\n return [];\n }\n }),\n );\n const tagged = snapshot.results.map((result, index) => ({\n result,\n tags: tagsByIndex[index] ?? [],\n }));\n const { results: admittedTagged, trace } = applyTagFilter(tagged, {\n tags: xrayFilterTags,\n tagMatch: xrayTagMatch,\n });\n const admittedResults = admittedTagged.map((entry) => entry.result);\n const filters = trace ? [...snapshot.filters, trace] : snapshot.filters;\n snapshot = { ...snapshot, results: admittedResults, filters };\n }\n // Decorate per-result disclosure + token estimate when the caller\n // wired a depth knob (issue #677 PR 3/4 — codex review on #699\n // flagged that the renderer's per-disclosure summary stays empty\n // until callers populate these fields). Estimate tokens from\n // the actual rendered payload at the requested depth so the\n // summary reflects real spend; chunk uses the preview, section\n // and raw use full content. Best-effort only — a missing\n // memory or read failure is silently dropped (CLAUDE.md rule 13).\n if (request.disclosure !== undefined) {\n // Disclosure already validated up front; pin to the narrowed\n // type here. Re-validation inside the queue would be dead code.\n const disclosure: RecallDisclosure = request.disclosure;\n const namespace = snapshot.namespace\n ? this.resolveNamespace(snapshot.namespace)\n : this.orchestrator.config.defaultNamespace;\n // Pre-fetch raw excerpts ONCE so the first raw-disclosure\n // result's token estimate includes the LCM-side excerpt spend\n // that `shapeMemorySummary` actually attaches in the recall\n // response. Without this, raw recalls systematically\n // undercounted spend on the first result (Cursor Medium review\n // on PR #699). Excerpts are scoped to the same session +\n // namespace as the recall.\n // Trim sessionKey to match what `orchestrator.recall(...)`\n // already does (`request.sessionKey?.trim() || undefined`),\n // otherwise a whitespace-padded key drives recall under one\n // identity but probes LCM under a different prefix and\n // misses stored excerpts (Cursor Low review on PR #699).\n const trimmedSessionKey = request.sessionKey?.trim() || undefined;\n // Read-authorization-gated namespace for the raw-excerpt LCM lookup\n // (#1505 thread 2f7). NOT `snapshot.namespace` (the write/overlay\n // namespace), which would attach `<principal>-project-*` overlay rows\n // when the principal can WRITE but not READ its self base. Mirrors the\n // recall + `lcmSearch` read gate. Resolved ONLY for raw disclosure (its\n // sole consumer); the `namespace` above is still used for the\n // memory-FILE reads below (a separate, snapshot-scoped read), so non-raw\n // x-ray decoration stays byte-for-byte unchanged.\n const rawExcerptNamespace =\n disclosure === \"raw\"\n ? this.resolveRawExcerptReadNamespace(\n request.namespace,\n trimmedSessionKey,\n authenticatedPrincipal,\n )\n : namespace;\n // `undefined` for an IMPLICIT raw recall means NO readable LCM namespace\n // exists (restrictive `default` READ policy, no readable overlay/self)\n // — suppress excerpts rather than fall back to the write/overlay\n // namespace the read gate excludes (#1505 thread NBHWz).\n const xrayHasExplicitNamespace =\n typeof request.namespace === \"string\" &&\n request.namespace.trim().length > 0;\n const rawExcerptsSuppressed =\n disclosure === \"raw\" &&\n !xrayHasExplicitNamespace &&\n rawExcerptNamespace === undefined;\n // Ordered, read-authorized LCM read key SET (#1505 fallback\n // unification) so raw disclosure finds excerpts a branch-scoped session\n // archived at project/root scope — exactly as recall + `lcmSearch` do.\n // Only meaningful with a concrete sessionKey + a readable namespace;\n // already read-gated so no unauthorized overlay key is present.\n const rawExcerptSessionIds =\n disclosure === \"raw\" && trimmedSessionKey && rawExcerptNamespace\n ? this.resolveLcmReadSessionIds(\n request.namespace,\n rawExcerptNamespace,\n trimmedSessionKey,\n authenticatedPrincipal,\n )\n : undefined;\n const rawExcerpts =\n disclosure === \"raw\" && !rawExcerptsSuppressed\n ? await this.fetchRawExcerpts(disclosure, {\n query,\n ...(trimmedSessionKey ? { sessionKey: trimmedSessionKey } : {}),\n ...(rawExcerptNamespace\n ? { namespace: rawExcerptNamespace }\n : {}),\n ...(rawExcerptSessionIds\n ? { lcmSessionIds: rawExcerptSessionIds }\n : {}),\n })\n : disclosure === \"raw\"\n ? []\n : null;\n const rawExcerptText =\n rawExcerpts && rawExcerpts.length > 0\n ? rawExcerpts.map((e) => e.content).join(\"\\n\")\n : \"\";\n // Pre-load every memory in parallel so we can:\n // (a) re-attribute raw excerpts to the *first readable* result\n // rather than always to index 0 (Cursor Low review on PR\n // #699: a missing/unreadable result[0] orphaned the excerpt\n // budget); and\n // (b) include the metadata fields `shapeMemorySummary` actually\n // emits at every depth (id, path, category, status, created,\n // updated, tags, entityRef) in the token estimate, so the\n // summary reflects real spend rather than only payload-body\n // spend (Cursor Low review on PR #699).\n const memoryByIndex = await Promise.all(\n snapshot.results.map(async (result) => {\n try {\n const storage = await this.orchestrator.getStorage(namespace);\n return await storage.readMemoryByPath(result.path);\n } catch {\n return null;\n }\n }),\n );\n const firstReadableIndex = memoryByIndex.findIndex((m) => m !== null);\n const baseDir =\n (await this.orchestrator.getStorage(namespace)).dir;\n const decorated = snapshot.results.map((result, index) => {\n const memory = memoryByIndex[index];\n if (!memory) {\n // Unreadable result: attach the disclosure tag anyway so\n // the per-disclosure summary classifies it correctly,\n // but skip the token estimate since we don't have the\n // content to measure. Without the disclosure tag the\n // result silently flows into the `unspecified` bucket\n // even though the caller explicitly requested a depth\n // (Cursor Low review on PR #699).\n return { ...result, disclosure };\n }\n // Build a representative shaped summary so the estimate\n // counts every field `shapeMemorySummary` actually emits.\n // The serialized JSON form is a close-enough proxy for the\n // wire payload size.\n const shaped = shapeMemorySummary(\n memory,\n baseDir,\n disclosure,\n disclosure === \"raw\" &&\n index === firstReadableIndex &&\n rawExcerpts &&\n rawExcerpts.length > 0\n ? rawExcerpts\n : undefined,\n );\n return {\n ...result,\n disclosure,\n estimatedTokens: estimateRecallTokens(JSON.stringify(shaped)),\n };\n });\n // Edge case: every result was unreadable but rawExcerpts\n // still has content — credit that spend to result[0] rather\n // than dropping it on the floor. Without this, the raw row\n // in the per-disclosure summary under-reports spend whenever\n // every memory file is missing/unreadable.\n if (\n disclosure === \"raw\" &&\n firstReadableIndex === -1 &&\n rawExcerptText.length > 0 &&\n decorated.length > 0\n ) {\n decorated[0] = {\n ...decorated[0]!,\n disclosure,\n estimatedTokens: estimateRecallTokens(rawExcerptText),\n };\n }\n const decoratedSnapshot = { ...snapshot, results: decorated };\n xrayResponse = {\n snapshotFound: true,\n snapshot: decoratedSnapshot,\n };\n } else {\n xrayResponse = {\n snapshotFound: true,\n snapshot,\n };\n }\n }\n } finally {\n release();\n }\n\n if (\n request.includeRecall === true &&\n xrayResponse.snapshotFound === true &&\n xrayResponse.snapshot\n ) {\n // Same read-authorization-gated raw-excerpt namespace the recall path uses\n // (#1505 thread 2f7), so the includeRecall x-ray path can't leak overlay\n // transcript rows via raw disclosure. Resolved ONLY for raw disclosure (the\n // sole consumer) so non-raw x-ray recall stays byte-for-byte unchanged. The\n // ordered LCM read key SET (#1505 fallback unification) adds the coding read\n // fallbacks so a branch-scoped session also finds excerpts at project/root\n // scope.\n const xrayRawExcerptNamespace =\n disclosure === \"raw\"\n ? this.resolveRawExcerptReadNamespace(\n request.namespace,\n recallSessionKey,\n authenticatedPrincipal,\n )\n : undefined;\n // `undefined` for an IMPLICIT raw recall means NO readable LCM namespace\n // exists — suppress excerpts rather than fall back to the write/overlay\n // namespace the read gate excludes (#1505 thread NBHWz).\n const xrayHasExplicitNamespace =\n typeof request.namespace === \"string\" &&\n request.namespace.trim().length > 0;\n const xrayRawExcerptsSuppressed =\n disclosure === \"raw\" &&\n !xrayHasExplicitNamespace &&\n xrayRawExcerptNamespace === undefined;\n const xrayRawExcerptSessionIds =\n disclosure === \"raw\" && xrayRawExcerptNamespace && recallSessionKey\n ? this.resolveLcmReadSessionIds(\n request.namespace,\n xrayRawExcerptNamespace,\n recallSessionKey,\n authenticatedPrincipal,\n )\n : undefined;\n return {\n ...xrayResponse,\n recall: await this.buildRecallResponseFromXraySnapshot({\n query,\n sessionKey: recallSessionKey,\n snapshot: xrayResponse.snapshot,\n disclosure,\n startedAt: recallStartedAt,\n requestedMode: request.mode,\n normalizedMode: mode,\n ...(xrayRawExcerptNamespace\n ? { rawExcerptNamespace: xrayRawExcerptNamespace }\n : {}),\n ...(xrayRawExcerptSessionIds\n ? { rawExcerptSessionIds: xrayRawExcerptSessionIds }\n : {}),\n ...(xrayRawExcerptsSuppressed\n ? { rawExcerptsSuppressed: xrayRawExcerptsSuppressed }\n : {}),\n }),\n };\n }\n return xrayResponse;\n }\n // Sequence lock for `recallXray` — see comment inside the method.\n // Lives on the instance so every x-ray call on the same service\n // shares it, and so separate services in the same process (e.g.\n // per-tenant) do not block each other.\n private xrayQueue: Promise<void> = Promise.resolve();\n\n async memoryStore(\n request: EngramAccessMemoryStoreRequest,\n hooks?: { enforceWriteQuota?: () => void | Promise<void> },\n ): Promise<EngramAccessWriteResponse> {\n const namespace = await this.resolveCodingScopedWriteNamespace(request);\n const schemaVersion = request.schemaVersion ?? ENGRAM_ACCESS_WRITE_SCHEMA_VERSION;\n if (schemaVersion !== ENGRAM_ACCESS_WRITE_SCHEMA_VERSION) {\n throw new EngramAccessInputError(`unsupported schemaVersion: ${schemaVersion}`);\n }\n const execute = async (): Promise<EngramAccessWriteResponse> => {\n const candidate = this.validateWriteCandidate(request, namespace);\n if (request.dryRun === true) {\n return {\n schemaVersion: ENGRAM_ACCESS_WRITE_SCHEMA_VERSION,\n operation: \"memory_store\",\n namespace,\n dryRun: true,\n accepted: true,\n queued: false,\n status: \"validated\",\n idempotencyKey: request.idempotencyKey?.trim() || undefined,\n };\n }\n const result = await persistExplicitCapture(this.orchestrator, candidate, \"memory_store\");\n // Seed the session's coding binding ONLY after a real write commits, and\n // only when the namespace came from project scoping (no explicit\n // namespace). This mirrors recall's maybeAttachCodingContext so a LATER\n // bare recall/write on the same session is scoped to the same project —\n // but never binds the session on a dryRun, replay/conflict, quota\n // rejection, or an explicit-namespace write (which bypasses the overlay),\n // since those don't reach this point or aren't project-scoped (Codex review).\n await this.attachCodingContextAfterScopedWrite(request);\n const response: EngramAccessWriteResponse = {\n schemaVersion: ENGRAM_ACCESS_WRITE_SCHEMA_VERSION,\n operation: \"memory_store\",\n namespace,\n dryRun: false,\n accepted: true,\n queued: false,\n status: result.duplicateOf ? \"duplicate\" : \"stored\",\n memoryId: result.id,\n duplicateOf: result.duplicateOf,\n idempotencyKey: request.idempotencyKey?.trim() || undefined,\n };\n log.info(\n `access-write op=memory_store namespace=${namespace} dryRun=false status=${response.status} memoryId=${response.memoryId ?? \"-\"} idempotency=${response.idempotencyKey ? \"yes\" : \"no\"}`,\n );\n return response;\n };\n return this.handleIdempotentWrite({\n operation: \"memory_store\",\n idempotencyKey: request.idempotencyKey,\n requestFingerprint: {\n schemaVersion,\n content: request.content,\n category: request.category,\n confidence: request.confidence,\n namespace,\n tags: request.tags,\n entityRef: request.entityRef,\n ttl: request.ttl,\n sourceReason: request.sourceReason,\n },\n skip: request.dryRun === true,\n beforeExecute: hooks?.enforceWriteQuota,\n execute,\n });\n }\n\n async peekMemoryStoreIdempotency(request: EngramAccessMemoryStoreRequest): Promise<EngramAccessIdempotencyStatus> {\n const namespace = await this.resolveCodingScopedWriteNamespace(request);\n const schemaVersion = request.schemaVersion ?? ENGRAM_ACCESS_WRITE_SCHEMA_VERSION;\n if (schemaVersion !== ENGRAM_ACCESS_WRITE_SCHEMA_VERSION) {\n throw new EngramAccessInputError(`unsupported schemaVersion: ${schemaVersion}`);\n }\n return this.peekIdempotentWrite({\n operation: \"memory_store\",\n idempotencyKey: request.idempotencyKey,\n requestFingerprint: {\n schemaVersion,\n content: request.content,\n category: request.category,\n confidence: request.confidence,\n namespace,\n tags: request.tags,\n entityRef: request.entityRef,\n ttl: request.ttl,\n sourceReason: request.sourceReason,\n },\n skip: request.dryRun === true,\n });\n }\n\n async suggestionSubmit(\n request: EngramAccessSuggestionSubmitRequest,\n hooks?: { enforceWriteQuota?: () => void | Promise<void> },\n ): Promise<EngramAccessWriteResponse> {\n const namespace = await this.resolveCodingScopedWriteNamespace(request);\n const schemaVersion = request.schemaVersion ?? ENGRAM_ACCESS_WRITE_SCHEMA_VERSION;\n if (schemaVersion !== ENGRAM_ACCESS_WRITE_SCHEMA_VERSION) {\n throw new EngramAccessInputError(`unsupported schemaVersion: ${schemaVersion}`);\n }\n const execute = async (): Promise<EngramAccessWriteResponse> => {\n const candidate = this.validateWriteCandidate(request, namespace);\n if (request.dryRun === true) {\n return {\n schemaVersion: ENGRAM_ACCESS_WRITE_SCHEMA_VERSION,\n operation: \"suggestion_submit\",\n namespace,\n dryRun: true,\n accepted: true,\n queued: true,\n status: \"validated\",\n idempotencyKey: request.idempotencyKey?.trim() || undefined,\n };\n }\n const result = await queueExplicitCaptureForReview(\n this.orchestrator,\n candidate,\n \"suggestion_submit\",\n new Error(request.sourceReason?.trim() || \"submitted via engram suggestion_submit\"),\n );\n // Seed the session binding only after a real, project-scoped submit commits\n // (mirrors memory_store / recall; skips dryRun, replay, quota-reject, and\n // explicit-namespace writes — Codex review).\n await this.attachCodingContextAfterScopedWrite(request);\n const response: EngramAccessWriteResponse = {\n schemaVersion: ENGRAM_ACCESS_WRITE_SCHEMA_VERSION,\n operation: \"suggestion_submit\",\n namespace,\n dryRun: false,\n accepted: true,\n queued: true,\n status: \"queued_for_review\",\n memoryId: result.id,\n duplicateOf: result.duplicateOf,\n idempotencyKey: request.idempotencyKey?.trim() || undefined,\n };\n log.info(\n `access-write op=suggestion_submit namespace=${namespace} dryRun=false status=${response.status} memoryId=${response.memoryId ?? \"-\"} idempotency=${response.idempotencyKey ? \"yes\" : \"no\"}`,\n );\n return response;\n };\n return this.handleIdempotentWrite({\n operation: \"suggestion_submit\",\n idempotencyKey: request.idempotencyKey,\n requestFingerprint: {\n schemaVersion,\n content: request.content,\n category: request.category,\n confidence: request.confidence,\n namespace,\n tags: request.tags,\n entityRef: request.entityRef,\n ttl: request.ttl,\n sourceReason: request.sourceReason,\n },\n skip: request.dryRun === true,\n beforeExecute: hooks?.enforceWriteQuota,\n execute,\n });\n }\n\n async peekSuggestionSubmitIdempotency(\n request: EngramAccessSuggestionSubmitRequest,\n ): Promise<EngramAccessIdempotencyStatus> {\n const namespace = await this.resolveCodingScopedWriteNamespace(request);\n const schemaVersion = request.schemaVersion ?? ENGRAM_ACCESS_WRITE_SCHEMA_VERSION;\n if (schemaVersion !== ENGRAM_ACCESS_WRITE_SCHEMA_VERSION) {\n throw new EngramAccessInputError(`unsupported schemaVersion: ${schemaVersion}`);\n }\n return this.peekIdempotentWrite({\n operation: \"suggestion_submit\",\n idempotencyKey: request.idempotencyKey,\n requestFingerprint: {\n schemaVersion,\n content: request.content,\n category: request.category,\n confidence: request.confidence,\n namespace,\n tags: request.tags,\n entityRef: request.entityRef,\n ttl: request.ttl,\n sourceReason: request.sourceReason,\n },\n skip: request.dryRun === true,\n });\n }\n\n private validateWriteCandidate(\n request: EngramAccessMemoryStoreRequest | EngramAccessSuggestionSubmitRequest,\n namespace: string,\n ): ValidExplicitCapture {\n try {\n return {\n ...validateExplicitCaptureInput(\n {\n ...request,\n namespace,\n },\n \"legacy_tool\",\n ),\n // The namespace was resolved AND authorized by\n // resolveCodingScopedWriteNamespace (explicit namespaces via\n // resolveWritableNamespace; otherwise an auth-checked base + a\n // session-owned project overlay), so the persist/queue layer must not\n // re-reject a legitimately-derived dynamic project namespace (#1434).\n namespacePreResolved: true,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new EngramAccessInputError(message);\n }\n }\n\n async memoryGet(memoryId: string, namespace?: string, principal?: string): Promise<EngramAccessMemoryResponse> {\n const resolvedNamespace = this.resolveReadableNamespace(namespace, principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const memory = await storage.getMemoryById(memoryId);\n if (!memory) {\n return { found: false, namespace: resolvedNamespace };\n }\n return {\n found: true,\n namespace: resolvedNamespace,\n memory: this.serializeMemory(memory),\n };\n }\n\n async memoryBrowse(\n request: EngramAccessMemoryBrowseRequest = {},\n ): Promise<EngramAccessMemoryBrowseResponse> {\n const resolvedNamespace = this.resolveReadableNamespace(\n request.namespace,\n request.authenticatedPrincipal,\n );\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const { limit, offset } = normalizePagination(request.limit, request.offset);\n const sort = normalizeBrowseSort(request.sort);\n const query = request.query?.trim().toLowerCase() ?? \"\";\n const statusFilter = request.status?.trim().toLowerCase();\n const categoryFilter = request.category?.trim().toLowerCase();\n\n const projected = await storage.browseProjectedMemories({\n query,\n status: statusFilter,\n category: categoryFilter,\n sort,\n limit,\n offset,\n });\n if (projected) {\n return {\n namespace: resolvedNamespace,\n sort,\n total: projected.total,\n count: projected.memories.length,\n limit,\n offset,\n memories: projected.memories.map((row) => ({ ...row })),\n };\n }\n\n let memories = [...await storage.readAllMemories(), ...await storage.readArchivedMemories()];\n memories = memories.filter((memory) => {\n const status = inferMemoryStatus(memory.frontmatter, toMemoryPathRel(storage.dir, memory.path)).toLowerCase();\n if (statusFilter && status !== statusFilter) return false;\n if (categoryFilter && memory.frontmatter.category.toLowerCase() !== categoryFilter) return false;\n if (!query) return true;\n const haystack = [\n memory.frontmatter.id,\n memory.path,\n memory.content,\n memory.frontmatter.entityRef ?? \"\",\n ...memory.frontmatter.tags,\n ].join(\"\\n\").toLowerCase();\n return haystack.includes(query);\n });\n\n memories.sort((left, right) => compareBrowseMemory(sort, left, right));\n\n const page = memories\n .slice(offset, offset + limit)\n .map((memory) => this.serializeMemorySummary(memory, storage.dir));\n return {\n namespace: resolvedNamespace,\n sort,\n total: memories.length,\n count: page.length,\n limit,\n offset,\n memories: page,\n };\n }\n\n async memoryTimeline(\n memoryId: string,\n namespace?: string,\n limit: number = 200,\n principal?: string,\n ): Promise<EngramAccessTimelineResponse> {\n const resolvedNamespace = this.resolveReadableNamespace(namespace, principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const timeline = await storage.getMemoryTimeline(memoryId, limit);\n return {\n found: timeline.length > 0,\n namespace: resolvedNamespace,\n count: timeline.length,\n timeline,\n };\n }\n\n async entityList(options: {\n namespace?: string;\n query?: string;\n limit?: number;\n offset?: number;\n } = {}): Promise<EngramAccessEntityListResponse> {\n const storage = await this.orchestrator.getStorage(options.namespace);\n const resolvedNamespace = options.namespace?.trim() || this.orchestrator.config.defaultNamespace;\n const { limit, offset } = normalizePagination(options.limit, options.offset);\n const query = options.query?.trim().toLowerCase() ?? \"\";\n\n const names = await storage.listEntityNames();\n const entities: EngramAccessEntitySummary[] = [];\n for (const name of names) {\n const raw = await storage.readEntity(name);\n if (!raw) continue;\n const entity = parseEntityFile(raw, this.orchestrator.config.entitySchemas);\n if (query) {\n const haystack = [\n entity.name,\n entity.type,\n entity.synthesis || entity.summary || \"\",\n ...entity.aliases,\n ...entity.facts,\n ...(entity.structuredSections ?? []).flatMap((section) => [section.title, ...section.facts]),\n ].join(\"\\n\").toLowerCase();\n if (!haystack.includes(query)) continue;\n }\n entities.push({\n name: entity.name,\n type: entity.type,\n updated: entity.updated,\n summary: entity.synthesis || entity.summary,\n aliases: entity.aliases,\n });\n }\n\n entities.sort((left, right) => left.name.localeCompare(right.name));\n const page = entities.slice(offset, offset + limit);\n return {\n namespace: resolvedNamespace,\n total: entities.length,\n count: page.length,\n limit,\n offset,\n entities: page,\n };\n }\n\n async entityGet(name: string, namespace?: string): Promise<EngramAccessEntityResponse> {\n const storage = await this.orchestrator.getStorage(namespace);\n const resolvedNamespace = namespace?.trim() || this.orchestrator.config.defaultNamespace;\n const raw = await storage.readEntity(name);\n if (!raw) return { found: false, namespace: resolvedNamespace };\n return {\n found: true,\n namespace: resolvedNamespace,\n entity: parseEntityFile(raw, this.orchestrator.config.entitySchemas),\n };\n }\n\n async reviewQueue(runId?: string, namespace?: string, principal?: string): Promise<EngramAccessReviewQueueResponse> {\n const resolvedNamespace = this.resolveReadableNamespace(namespace, principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const projected = await storage.getProjectedGovernanceRecord();\n if (projected && (!runId || projected.runId === runId.trim())) {\n const projectedAppliedActions = projected.appliedActionRows.map((row) => ({\n action: row.action,\n memoryId: row.memoryId,\n reasonCode: row.reasonCode,\n beforeStatus: row.beforeStatus,\n afterStatus: row.afterStatus,\n originalPath: row.originalPath,\n currentPath: row.currentPath,\n })) as Awaited<\n ReturnType<typeof readMemoryGovernanceRunArtifact>\n >[\"appliedActions\"];\n const projectedProposedActions = await buildProjectedGovernanceProposedActions(storage, projected);\n const projectedArtifact = await (async () => {\n try {\n return await readMemoryGovernanceRunArtifact(storage.dir, projected.runId);\n } catch {\n return null;\n }\n })();\n const metrics = projected.metrics as Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"metrics\"];\n const fallbackTransitionReport = {\n proposed: groupActionsByStatus(projectedProposedActions),\n applied: groupActionsByStatus(projectedAppliedActions),\n };\n const transitionReport = projectedArtifact?.transitionReport\n ? {\n proposed:\n hasGroupedGovernanceActions(projectedArtifact.transitionReport.proposed) || projectedProposedActions.length === 0\n ? projectedArtifact.transitionReport.proposed\n : fallbackTransitionReport.proposed,\n applied:\n hasGroupedGovernanceActions(projectedArtifact.transitionReport.applied) || projectedAppliedActions.length === 0\n ? projectedArtifact.transitionReport.applied\n : fallbackTransitionReport.applied,\n }\n : fallbackTransitionReport;\n const qualityScore = projectedArtifact?.qualityScore ?? metrics?.qualityScore ?? buildQualityScore(metrics?.reviewReasons ?? {\n exact_duplicate: 0,\n semantic_duplicate_candidate: 0,\n disputed_memory: 0,\n speculative_low_confidence: 0,\n archive_candidate: 0,\n explicit_capture_review: 0,\n malformed_import: 0,\n });\n const effectiveMetrics = metrics ? { ...metrics, qualityScore: metrics.qualityScore ?? qualityScore } : metrics;\n\n return {\n found: true,\n namespace: resolvedNamespace,\n runId: projected.runId,\n summary: projected.summary as Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"summary\"],\n metrics: effectiveMetrics,\n qualityScore,\n reviewQueue: projected.reviewQueueRows.map((row) => ({\n entryId: row.entryId,\n memoryId: row.memoryId,\n path: row.path,\n reasonCode: row.reasonCode,\n severity: row.severity,\n suggestedAction: row.suggestedAction,\n suggestedStatus: row.suggestedStatus,\n relatedMemoryIds: row.relatedMemoryIds,\n })) as Awaited<\n ReturnType<typeof readMemoryGovernanceRunArtifact>\n >[\"reviewQueue\"],\n appliedActions: projectedAppliedActions,\n transitionReport,\n report: projected.report,\n };\n }\n\n const resolvedRunId = runId?.trim() || (await listMemoryGovernanceRuns(storage.dir))[0];\n if (!resolvedRunId) return { found: false, namespace: resolvedNamespace };\n const artifact = await readMemoryGovernanceRunArtifact(storage.dir, resolvedRunId);\n return {\n found: true,\n namespace: resolvedNamespace,\n runId: resolvedRunId,\n summary: artifact.summary,\n metrics: artifact.metrics,\n qualityScore: artifact.qualityScore,\n reviewQueue: artifact.reviewQueue,\n appliedActions: artifact.appliedActions,\n transitionReport: artifact.transitionReport,\n report: artifact.report,\n };\n }\n\n async maintenance(namespace?: string, principal?: string): Promise<EngramAccessMaintenanceResponse> {\n const resolvedNamespace = this.resolveReadableNamespace(namespace, principal);\n return {\n namespace: resolvedNamespace,\n health: await this.health(resolvedNamespace),\n latestGovernanceRun: await this.reviewQueue(undefined, resolvedNamespace, principal),\n };\n }\n\n async quality(namespace?: string, principal?: string): Promise<EngramAccessQualityResponse> {\n const resolvedNamespace = this.resolveReadableNamespace(namespace, principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const governance = await this.reviewQueue(undefined, resolvedNamespace, principal);\n const nowMs = Date.now();\n const statusCounts: Record<string, number> = {};\n const categoryCounts: Record<string, number> = {};\n const confidenceTierCounts: Record<string, number> = {};\n const ageBucketCounts: Record<string, number> = {};\n let staleActive = 0;\n let lowConfidenceActive = 0;\n\n const memories = [...await storage.readAllMemories(), ...await storage.readArchivedMemories()];\n for (const memory of memories) {\n const status = inferMemoryStatus(memory.frontmatter, toMemoryPathRel(storage.dir, memory.path)).toLowerCase();\n const confidenceTier = memory.frontmatter.confidenceTier ?? \"unknown\";\n const ageBucket = bucketMemoryAge(memory.frontmatter.updated ?? memory.frontmatter.created, nowMs);\n\n incrementCount(statusCounts, status);\n incrementCount(categoryCounts, memory.frontmatter.category);\n incrementCount(confidenceTierCounts, confidenceTier);\n incrementCount(ageBucketCounts, ageBucket);\n\n if (status === \"active\") {\n if (ageBucket === \"91_plus_days\") staleActive += 1;\n if ((memory.frontmatter.confidence ?? 0) < 0.6) lowConfidenceActive += 1;\n }\n }\n\n return {\n namespace: resolvedNamespace,\n totalMemories: memories.length,\n statusCounts,\n categoryCounts,\n confidenceTierCounts,\n ageBucketCounts,\n archivePressure: {\n pendingReview: statusCounts.pending_review ?? 0,\n quarantined: statusCounts.quarantined ?? 0,\n archived: statusCounts.archived ?? 0,\n staleActive,\n lowConfidenceActive,\n },\n latestGovernanceRun: {\n found: governance.found,\n runId: governance.runId,\n qualityScore: governance.qualityScore ?? governance.metrics?.qualityScore,\n reviewQueueCount: governance.reviewQueue?.length ?? 0,\n },\n };\n }\n\n async governanceRun(\n request: {\n namespace?: string;\n mode?: \"shadow\" | \"apply\";\n recentDays?: number;\n maxMemories?: number;\n batchSize?: number;\n authenticatedPrincipal?: string;\n },\n principal?: string,\n ): Promise<{\n namespace: string;\n runId: string;\n traceId: string;\n mode: \"shadow\" | \"apply\";\n reviewQueueCount: number;\n proposedActionCount: number;\n appliedActionCount: number;\n summaryPath: string;\n reportPath: string;\n }> {\n const deepSleep = this.orchestrator.config.dreamsPhases.deepSleep;\n if (deepSleep.enabled === false && deepSleep.enabledExplicitlySet === true) {\n throw new Error(\"memory governance is disabled by dreams.phases.deepSleep.enabled=false\");\n }\n const resolvedNamespace = this.resolveWritableNamespace(\n request.namespace,\n undefined,\n request.authenticatedPrincipal ?? principal,\n );\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const mode = request.mode === \"apply\" ? \"apply\" : \"shadow\";\n const boundedBatchSize =\n typeof request.batchSize === \"number\" && Number.isFinite(request.batchSize)\n ? Math.max(1, Math.floor(request.batchSize))\n : undefined;\n const result = await runMemoryGovernance({\n memoryDir: storage.dir,\n mode,\n recentDays:\n typeof request.recentDays === \"number\" && Number.isFinite(request.recentDays)\n ? Math.max(1, Math.floor(request.recentDays))\n : undefined,\n maxMemories:\n typeof request.maxMemories === \"number\" && Number.isFinite(request.maxMemories)\n ? Math.max(1, Math.floor(request.maxMemories))\n : undefined,\n batchSize: boundedBatchSize,\n });\n if (mode === \"apply\") {\n try {\n await this.orchestrator.processEntitySynthesisQueue(\n resolvedNamespace,\n Math.min(boundedBatchSize ?? 5, 5),\n );\n } catch (error) {\n log.debug(`governanceRun: entity synthesis refresh failed after governance apply: ${error}`);\n }\n }\n\n return {\n namespace: resolvedNamespace,\n runId: result.runId,\n traceId: result.traceId,\n mode: result.mode,\n reviewQueueCount: result.reviewQueue.length,\n proposedActionCount: result.proposedActions.length,\n appliedActionCount: result.appliedActions.length,\n summaryPath: result.summaryPath,\n reportPath: result.reportPath,\n };\n }\n\n async procedureMiningRun(\n request: {\n namespace?: string;\n authenticatedPrincipal?: string;\n },\n principal?: string,\n ): Promise<{\n namespace: string;\n clustersProcessed: number;\n proceduresWritten: number;\n skippedReason?: string;\n }> {\n const resolvedNamespace = this.resolveWritableNamespace(\n request.namespace,\n undefined,\n request.authenticatedPrincipal ?? principal,\n );\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const result = await runProcedureMining({\n memoryDir: storage.dir,\n storage,\n config: this.orchestrator.config,\n });\n return {\n namespace: resolvedNamespace,\n clustersProcessed: result.clustersProcessed,\n proceduresWritten: result.proceduresWritten,\n skippedReason: result.skippedReason,\n };\n }\n\n async liveConnectorsRun(\n request: {\n authenticatedPrincipal?: string;\n force?: boolean;\n } = {},\n principal?: string,\n ): Promise<LiveConnectorsRunSummary> {\n this.resolveWritableNamespace(\n undefined,\n undefined,\n request.authenticatedPrincipal ?? principal,\n );\n return this.orchestrator.runLiveConnectors({\n force: request.force === true,\n });\n }\n\n /**\n * Run the pattern-reinforcement maintenance job (issue #687 PR 2/4).\n *\n * Cluster duplicate non-procedural memories and reinforce the\n * canonical (most-recent) member. Gated on\n * `patternReinforcementEnabled` — when disabled, returns\n * `{ ran: false, skippedReason: \"disabled\" }` so the cron payload\n * surface in CI logs cleanly.\n *\n * Resolves the namespace via the same writable path used by\n * `procedureMiningRun` so cross-tenant writes are impossible\n * (CLAUDE.md rule 42).\n *\n * Delegates the run to `orchestrator.runPatternReinforcement` so\n * the cadence floor (`patternReinforcementCadenceMs`) is enforced\n * uniformly across cron + MCP paths (PR #730 review feedback,\n * Codex P2). Accepts `force: true` for ad-hoc operator runs that\n * must bypass the cadence floor — mirrors the pattern used by\n * other maintenance MCP tools.\n */\n async patternReinforcementRun(\n request: {\n namespace?: string;\n authenticatedPrincipal?: string;\n force?: boolean;\n } = {},\n principal?: string,\n ): Promise<{\n namespace: string;\n ran: boolean;\n skippedReason?: \"disabled\" | \"cadence\";\n clustersFound: number;\n canonicalsUpdated: number;\n duplicatesSuperseded: number;\n result?: PatternReinforcementResult;\n }> {\n const resolvedNamespace = this.resolveWritableNamespace(\n request.namespace,\n undefined,\n request.authenticatedPrincipal ?? principal,\n );\n const outcome = await this.orchestrator.runPatternReinforcement({\n namespace: resolvedNamespace,\n force: request.force === true,\n });\n if (!outcome.ran) {\n return {\n namespace: resolvedNamespace,\n ran: false,\n skippedReason: outcome.skippedReason,\n clustersFound: 0,\n canonicalsUpdated: 0,\n duplicatesSuperseded: 0,\n };\n }\n const result = outcome.result!;\n return {\n namespace: resolvedNamespace,\n ran: true,\n clustersFound: result.clustersFound,\n canonicalsUpdated: result.canonicalsUpdated,\n duplicatesSuperseded: result.duplicatesSuperseded,\n result,\n };\n }\n\n /**\n * Procedural memory stats (issue #567 PR 5/5). Read-only — resolves the\n * namespace via the same path used by `recallExplain` / `trustZoneStatus`\n * so cross-tenant reads are impossible (CLAUDE.md rule 42).\n */\n async procedureStats(\n request: { namespace?: string } = {},\n principal?: string,\n ): Promise<ProcedureStatsReport & { namespace: string }> {\n const resolvedNamespace = this.resolveReadableNamespace(\n request.namespace,\n principal,\n );\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const report = await computeProcedureStats({\n storage,\n config: this.orchestrator.config,\n });\n return { namespace: resolvedNamespace, ...report };\n }\n\n async memorySummarizeHourly(): Promise<{\n ok: true;\n message: string;\n }> {\n await this.orchestrator.summarizer.runHourly();\n return {\n ok: true,\n message: \"Hourly summarization completed. Check the summaries directory for results.\",\n };\n }\n\n async conversationIndexUpdate(\n request: {\n sessionKey?: string;\n hours?: number;\n embed?: boolean;\n } = {},\n ): Promise<{\n enabled: boolean;\n sessionKey?: string;\n sessions: number;\n chunks: number;\n skipped: number;\n skippedSessionKeys: string[];\n embeddedRuns: number;\n reason?: string;\n retryAfterMs?: number;\n }> {\n if (!this.orchestrator.config.conversationIndexEnabled) {\n return {\n enabled: false,\n sessions: 0,\n chunks: 0,\n skipped: 0,\n skippedSessionKeys: [],\n embeddedRuns: 0,\n reason: \"disabled\",\n };\n }\n\n const hours =\n typeof request.hours === \"number\" && Number.isFinite(request.hours)\n ? Math.max(1, Math.floor(request.hours))\n : 24;\n\n let sessionKey: string | undefined;\n if (request.sessionKey !== undefined) {\n if (typeof request.sessionKey !== \"string\" || request.sessionKey.trim().length === 0) {\n throw new EngramAccessInputError(\"sessionKey must be a non-empty string when provided\");\n }\n sessionKey = request.sessionKey.trim();\n }\n\n if (sessionKey) {\n const result = await this.orchestrator.updateConversationIndex(\n sessionKey,\n hours,\n { embed: request.embed },\n );\n return {\n enabled: true,\n sessionKey,\n sessions: 1,\n chunks: result.chunks,\n skipped: result.skipped ? 1 : 0,\n skippedSessionKeys: result.skipped ? [sessionKey] : [],\n embeddedRuns: result.embedded ? 1 : 0,\n reason: result.reason,\n retryAfterMs: result.retryAfterMs,\n };\n }\n\n const sessionKeys = await this.orchestrator.transcript.listSessionKeys();\n let chunks = 0;\n let skipped = 0;\n const skippedSessionKeys: string[] = [];\n let embeddedRuns = 0;\n\n for (const sessionKey of sessionKeys) {\n const result = await this.orchestrator.updateConversationIndex(\n sessionKey,\n hours,\n { embed: request.embed },\n );\n chunks += result.chunks;\n if (result.skipped) {\n skipped += 1;\n skippedSessionKeys.push(sessionKey);\n }\n if (result.embedded) {\n embeddedRuns += 1;\n }\n }\n\n return {\n enabled: true,\n sessions: sessionKeys.length,\n chunks,\n skipped,\n skippedSessionKeys,\n embeddedRuns,\n };\n }\n\n async profilingReport(\n request: AccessProfilingReportRequest = {},\n ): Promise<AccessProfilingReportResponse> {\n const profiler = this.orchestrator.profiler;\n if (!profiler.isEnabled) {\n return {\n enabled: false,\n reason: \"disabled\",\n message: \"Profiling is disabled. Set profilingEnabled: true in your plugin config to enable.\",\n };\n }\n\n const format = request.format ?? \"ascii\";\n if (format !== \"ascii\" && format !== \"json\") {\n throw new EngramAccessInputError(\"format must be one of: ascii, json\");\n }\n\n const limit = request.limit ?? 5;\n if (!Number.isInteger(limit) || limit < 1 || limit > 20) {\n throw new EngramAccessInputError(\"limit must be an integer between 1 and 20\");\n }\n\n const traces = profiler.getRecentTraces(limit);\n const stats = profiler.getStats();\n const bottleneck = profiler.identifyBottleneck();\n\n if (format === \"json\") {\n return {\n enabled: true,\n format,\n traces,\n stats,\n bottleneck,\n };\n }\n\n const lines: string[] = [];\n lines.push(\"Engram Profiling Report\");\n lines.push(\"=\".repeat(60));\n lines.push(\"\");\n\n type BucketEntry = { count: number; avgMs: number; p50Ms: number; p95Ms: number; maxMs: number };\n const allBuckets: Array<[string, Record<string, BucketEntry>]> = [\n [\"byKind\", stats.byKind],\n [\"bySpan\", stats.bySpan],\n ];\n const hasStats = allBuckets.some(([, entries]) => Object.keys(entries).length > 0);\n if (hasStats) {\n lines.push(\"Aggregate Stats (all retained traces):\");\n for (const [bucket, entries] of allBuckets) {\n for (const [key, summary] of Object.entries(entries)) {\n lines.push(\n ` ${bucket}/${key}: avg=${summary.avgMs}ms p50=${summary.p50Ms}ms p95=${summary.p95Ms}ms max=${summary.maxMs}ms (n=${summary.count})`,\n );\n }\n }\n lines.push(\"\");\n }\n\n if (bottleneck) {\n lines.push(`Bottleneck: ${bottleneck}`);\n lines.push(\"\");\n }\n\n if (traces.length === 0) {\n lines.push(\"No traces recorded yet. Trigger a recall or extraction to see timing data.\");\n } else {\n for (const trace of traces) {\n lines.push(formatProfileTraceAscii(trace));\n lines.push(\"\");\n }\n }\n\n return {\n enabled: true,\n format,\n report: lines.join(\"\\n\"),\n };\n }\n\n async trustZoneStatus(namespace?: string, principal?: string): Promise<EngramAccessTrustZoneStatusResponse> {\n const resolvedNamespace = this.resolveReadableNamespace(namespace, principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n return {\n namespace: resolvedNamespace,\n status: await getTrustZoneStoreStatus({\n memoryDir: storage.dir,\n trustZoneStoreDir: this.orchestrator.config.trustZoneStoreDir,\n enabled: this.orchestrator.config.trustZonesEnabled === true,\n promotionEnabled: this.orchestrator.config.quarantinePromotionEnabled === true,\n poisoningDefenseEnabled: this.orchestrator.config.memoryPoisoningDefenseEnabled === true,\n }),\n };\n }\n\n async trustZoneBrowse(\n request: EngramAccessTrustZoneBrowseRequest,\n principal?: string,\n ): Promise<EngramAccessTrustZoneBrowseResponse> {\n const resolvedNamespace = this.resolveReadableNamespace(request.namespace, principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const result = await listTrustZoneRecords({\n memoryDir: storage.dir,\n trustZoneStoreDir: this.orchestrator.config.trustZoneStoreDir,\n query: request.query,\n zone: request.zone,\n kind: request.kind,\n sourceClass: request.sourceClass,\n limit: request.limit,\n offset: request.offset,\n });\n return {\n namespace: resolvedNamespace,\n total: result.total,\n count: result.count,\n limit: result.limit,\n offset: result.offset,\n records: result.records.map((entry) =>\n summarizeTrustZoneRecord(\n entry.record,\n entry.filePath,\n result.allRecords,\n this.orchestrator.config.memoryPoisoningDefenseEnabled === true,\n this.orchestrator.config.trustZonesEnabled === true,\n this.orchestrator.config.quarantinePromotionEnabled === true,\n )),\n };\n }\n\n async trustZonePromote(\n request: EngramAccessTrustZonePromoteRequest,\n ): Promise<EngramAccessTrustZonePromoteResponse> {\n if (!isTrustZoneName(request.targetZone)) {\n throw new EngramAccessInputError(`unsupported trust-zone target: ${String(request.targetZone)}`);\n }\n const resolvedNamespace = this.resolveWritableNamespace(\n request.namespace,\n undefined,\n request.authenticatedPrincipal,\n );\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n let result: TrustZonePromotionResult;\n try {\n result = await promoteTrustZoneRecord({\n memoryDir: storage.dir,\n trustZoneStoreDir: this.orchestrator.config.trustZoneStoreDir,\n enabled: this.orchestrator.config.trustZonesEnabled === true,\n promotionEnabled: this.orchestrator.config.quarantinePromotionEnabled === true,\n poisoningDefenseEnabled: this.orchestrator.config.memoryPoisoningDefenseEnabled === true,\n sourceRecordId: request.recordId,\n targetZone: request.targetZone,\n recordedAt: request.recordedAt ?? new Date().toISOString(),\n promotionReason: request.promotionReason,\n summary: request.summary,\n dryRun: request.dryRun === true,\n });\n } catch (error) {\n throw normalizeTrustZoneInputError(error) ?? error;\n }\n return {\n namespace: resolvedNamespace,\n ...result,\n dryRun: request.dryRun === true,\n };\n }\n\n async trustZoneDemoSeed(\n request: EngramAccessTrustZoneDemoSeedRequest,\n ): Promise<EngramAccessTrustZoneDemoSeedResponse> {\n const resolvedNamespace = this.resolveWritableNamespace(\n request.namespace,\n undefined,\n request.authenticatedPrincipal,\n );\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n let result: TrustZoneDemoSeedResult;\n try {\n result = await seedTrustZoneDemoDataset({\n memoryDir: storage.dir,\n trustZoneStoreDir: this.orchestrator.config.trustZoneStoreDir,\n enabled: this.orchestrator.config.trustZonesEnabled === true,\n scenario: request.scenario,\n recordedAt: request.recordedAt,\n dryRun: request.dryRun === true,\n });\n } catch (error) {\n throw normalizeTrustZoneInputError(error) ?? error;\n }\n return {\n namespace: resolvedNamespace,\n ...result,\n };\n }\n\n async reviewDisposition(\n request: EngramAccessReviewDispositionRequest,\n ): Promise<EngramAccessReviewDispositionResponse> {\n const memoryId = request.memoryId.trim();\n const reasonCode = request.reasonCode.trim();\n if (memoryId.length === 0) {\n throw new EngramAccessInputError(\"memoryId is required\");\n }\n if (reasonCode.length === 0) {\n throw new EngramAccessInputError(\"reasonCode is required\");\n }\n\n const resolvedNamespace = this.resolveWritableNamespace(\n request.namespace,\n undefined,\n request.authenticatedPrincipal,\n );\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const memory = await storage.getMemoryById(memoryId);\n if (!memory) {\n throw new EngramAccessInputError(`memory not found: ${memoryId}`);\n }\n\n const previousStatus = memory.frontmatter.status ?? \"active\";\n const updatedAt = new Date().toISOString();\n const lifecycle = {\n actor: \"admin-console.review-disposition\",\n reasonCode,\n ruleVersion: \"memory-governance.v1\",\n };\n\n if (request.status === \"archived\") {\n const archivedPath = await storage.archiveMemory(memory, {\n at: new Date(updatedAt),\n ...lifecycle,\n });\n if (!archivedPath) {\n throw new Error(`failed to archive memory disposition: ${memoryId}`);\n }\n return {\n ok: true,\n namespace: resolvedNamespace,\n memoryId,\n status: \"archived\",\n previousStatus,\n currentPath: archivedPath,\n };\n }\n\n const updated = await storage.writeMemoryFrontmatter(memory, {\n status: request.status,\n updated: updatedAt,\n }, lifecycle);\n if (!updated) {\n throw new Error(`failed to update memory disposition: ${memoryId}`);\n }\n return {\n ok: true,\n namespace: resolvedNamespace,\n memoryId,\n status: request.status,\n previousStatus,\n currentPath: memory.path,\n };\n }\n\n private serializeMemory(memory: MemoryFile): EngramAccessMemoryRecord {\n return {\n id: memory.frontmatter.id,\n path: memory.path,\n category: memory.frontmatter.category,\n status: memory.frontmatter.status,\n created: memory.frontmatter.created,\n updated: memory.frontmatter.updated,\n content: memory.content,\n frontmatter: memory.frontmatter,\n };\n }\n\n private serializeMemorySummary(\n memory: MemoryFile,\n baseDir: string,\n disclosure?: RecallDisclosure,\n rawExcerpts?: EngramAccessMemorySummary[\"rawExcerpts\"],\n ): EngramAccessMemorySummary {\n return shapeMemorySummary(memory, baseDir, disclosure, rawExcerpts);\n }\n\n async observe(request: EngramAccessObserveRequest): Promise<EngramAccessObserveResponse> {\n if (!request.sessionKey || typeof request.sessionKey !== \"string\" || request.sessionKey.trim().length === 0) {\n throw new EngramAccessInputError(\"sessionKey is required and must be a non-empty string\");\n }\n if (!Array.isArray(request.messages) || request.messages.length === 0) {\n throw new EngramAccessInputError(\"messages is required and must be a non-empty array\");\n }\n for (const msg of request.messages) {\n if (!msg || typeof msg !== \"object\" || typeof msg.role !== \"string\" || typeof msg.content !== \"string\") {\n throw new EngramAccessInputError(\"each message must have a string 'role' and 'content'\");\n }\n if (msg.role !== \"user\" && msg.role !== \"assistant\") {\n throw new EngramAccessInputError(`invalid message role: ${msg.role} (expected 'user' or 'assistant')`);\n }\n }\n\n // 1. Resolve the FULL effective scope plan BEFORE any session mutation\n // (Codex P2 / Cursor \"orphan context after overlay auth\"). The plan is\n // read-only and re-runs the SAME authorization as\n // memory_store/suggestion_submit (rule 39): the explicit-namespace check\n // AND the coding-overlay self-base `canWriteNamespace` check both run\n // here. Because `maybeAttachCodingContext` has NOT run yet, the plan's\n // overlay resolves from the per-call `cwd`/`projectTag` fallback\n // (`resolveCodingContextFromOptions`) — identical to the context that\n // would be attached — so the scope is the same either way. Running the\n // plan first means an `observe` that ultimately throws on a non-writable\n // self base leaves NO coding context bound to the session, matching how\n // `memory_store` resolves its full scoped write namespace before any\n // session mutation.\n const scope = await this.resolveMemoryScopePlan(request);\n const writeNamespace = scope.writeNamespace;\n\n // Backward-compatible BASE writable namespace (pre-#1495 response semantics)\n // for the legacy `namespace` response field. DERIVED from the already-resolved\n // scope plan — NOT a second `resolveWritableNamespace(request.namespace,...)`\n // call (#1505 thread jvO). The fresh call re-authorized `undefined ⇒\n // config.defaultNamespace` a SECOND time; under a restrictive default-namespace\n // write policy that re-auth could REJECT an otherwise valid project-scoped\n // observe whose effective self/project write target the scope plan already\n // authorized (the same target memory_store/suggestion_submit accept). Worse,\n // that post-plan rejection fired AFTER `resolveMemoryScopePlan` may have seeded\n // the coding context, leaving an orphaned session binding behind. The plan is\n // the single authorization point (rule 22 / 39); the legacy field must reuse it\n // and never re-authorize. Pre-#1495 semantics were exactly\n // `resolveWritableNamespace(request.namespace)` (overlay-agnostic): the explicit\n // namespace when supplied, else `config.defaultNamespace`. `scope.explicitNamespace`\n // carries the authorized explicit value; the no-overlay implicit\n // `scope.writeNamespace` IS `config.defaultNamespace`, so an unqualified observe\n // stays byte-for-byte identical to the legacy response.\n const namespace = scope.explicitNamespace\n ? scope.writeNamespace\n : scope.codingOverlayApplied\n ? this.orchestrator.config.defaultNamespace\n : scope.writeNamespace;\n const shouldWriteObjectiveState =\n this.orchestrator.config.objectiveStateMemoryEnabled === true &&\n this.orchestrator.config.objectiveStateSnapshotWritesEnabled === true;\n\n // 2. Auto-resolve coding context from cwd/projectTag so a LATER bare recall\n // on the same session is project-scoped (rule 42: same namespace layer as\n // recall). Done AFTER the scope plan authorized the write, so a rejected\n // request never leaves orphaned context on the session.\n await this.maybeAttachCodingContext(request.sessionKey, {\n cwd: request.cwd,\n projectTag: request.projectTag,\n });\n\n // Prefix sessionKey with the EFFECTIVE write namespace for LCM archival so\n // observed turns are scoped to the same namespace project-scoped recall\n // reads. The SAME `lcmSessionKeyForNamespace` helper is used by the\n // orchestrator recall readers and by compaction flush/record, so the LCM\n // write key and every read/flush key agree (#1495, rule 42). Only prefixes\n // when the namespace diverges from the default store; a single-store\n // deployment keeps the raw sessionKey unchanged.\n const lcmSessionKey =\n lcmSessionKeyForNamespace(\n writeNamespace,\n request.sessionKey,\n this.orchestrator.config.defaultNamespace,\n ) ?? request.sessionKey;\n\n // 4. Objective-state snapshots → the scope plan's objective-state namespace.\n // For explicit-namespace and coding-overlay writes this equals\n // writeNamespace; for an IMPLICIT write it is the principal SELF base\n // (#928 contract, already auth-checked inside the scope plan), not the\n // general default-store write namespace.\n if (shouldWriteObjectiveState) {\n try {\n const objectiveStateLocation =\n await this.objectiveStateStoreLocationForNamespace(\n scope.objectiveStateNamespace,\n );\n await recordObjectiveStateSnapshotsFromObservedMessages({\n memoryDir: objectiveStateLocation.memoryDir,\n objectiveStateStoreDir: objectiveStateLocation.objectiveStateStoreDir,\n objectiveStateMemoryEnabled: this.orchestrator.config.objectiveStateMemoryEnabled,\n objectiveStateSnapshotWritesEnabled:\n this.orchestrator.config.objectiveStateSnapshotWritesEnabled,\n sessionKey: request.sessionKey,\n recordedAt: new Date().toISOString(),\n messages: request.messages,\n });\n } catch (err) {\n log.error(`access-observe objective-state snapshot write failed: ${err}`);\n }\n }\n\n // 5. LCM archival → effective write namespace.\n // lcmArchived in the response means \"LCM archival was queued\" (not\n // \"completed\"), matching extractionQueued semantics. Both run async.\n let lcmArchived = false;\n if (this.orchestrator.lcmEngine && this.orchestrator.lcmEngine.enabled) {\n // Fire-and-forget: LCM archival writes to SQLite and builds summary\n // DAGs, which can take tens of seconds for large sessions. Don't\n // block the HTTP response — the caller only needs acknowledgment.\n try {\n this.orchestrator.lcmEngine.enqueueObserveMessages(lcmSessionKey, request.messages);\n lcmArchived = true;\n } catch (err) {\n log.error(`access-observe LCM enqueue failed: ${err}`);\n }\n }\n\n // 6. Extraction/replay → effective write namespace for STORAGE, ORIGINAL\n // sessionKey for IDENTITY (provenance + threading).\n let extractionQueued = false;\n if (request.skipExtraction !== true) {\n const turns = request.messages.map((m) => ({\n source: \"openclaw\" as const,\n // Identity-vs-routing separation (#1505 thread 1, cursor): extraction\n // derives the provenance principal via `resolvePrincipal(turn.sessionKey)`\n // and threads `turn.sessionKey` into conversation threading. Feeding the\n // namespace-PREFIXED `lcmSessionKey` here mis-derived the principal to\n // `default` (a `<ns>:<key>` string matches no prefix/map rule and fails\n // the `agent:` heuristic). Pass the ORIGINAL sessionKey so identity is\n // correct; storage routing is pinned separately via\n // writeNamespaceOverride below, and the authenticated principal is pinned\n // via principalOverride.\n sessionKey: request.sessionKey,\n role: m.role,\n content: m.content,\n parts: m.parts,\n rawContent: m.rawContent,\n sourceFormat: m.sourceFormat,\n timestamp: new Date().toISOString(),\n }));\n // Pin extraction STORAGE to the effective namespace rather than letting the\n // orchestrator re-derive one from the session key + coding overlay — that\n // re-derivation would have to reparse identity and could miss the overlay\n // (the #1495 drift). Passing writeNamespaceOverride makes the extraction\n // target deterministic and identical to LCM/objective-state (rule 39).\n //\n // Pin WHENEVER namespaces are enabled, not only when writeNamespace differs\n // from the default store (#1505 round 3, codex \"Pin default-store extraction\n // writes too\"). For an unqualified/no-overlay observe by a principal that\n // HAS a self namespace, writeNamespace is `config.defaultNamespace` but an\n // unpinned `runExtraction` would fall back to\n // `defaultNamespaceForPrincipal(principal)` = the SELF namespace — diverging\n // from where LCM/objective-state/response wrote (`default`). Pinning the\n // resolved writeNamespace forces all side effects onto the one scope-plan\n // namespace. When namespaces are DISABLED the router collapses every\n // namespace to one store, so leaving the override undefined preserves the\n // existing single-store routing byte-for-byte.\n const writeNamespaceOverride =\n this.orchestrator.config.namespacesEnabled === true\n ? writeNamespace\n : undefined;\n // Pin provenance PRINCIPAL to the scope plan's resolved principal (#1505\n // thread 1). The scope plan already applied auth precedence\n // (authenticatedPrincipal/principalOverride > resolvePrincipal(original\n // sessionKey)), so this is the same identity the surface authorized — never\n // a `default` fallback parsed from a prefixed key. Omitted when no principal\n // resolved (namespaces-disabled / unauthenticated single-store), preserving\n // existing behavior.\n const principalOverride =\n typeof scope.principal === \"string\" && scope.principal.length > 0\n ? scope.principal\n : undefined;\n // Fire-and-forget: queue extraction in the background so the HTTP\n // response returns immediately. LCM archival (above) is also\n // enqueue-only; extraction involves LLM calls that can take\n // minutes under load and should not block the caller.\n //\n // Backpressure: the orchestrator's own extraction queue already\n // limits concurrency (one extraction at a time per session via\n // queueBufferedExtraction). Fire-and-forget here just decouples\n // the HTTP response from the queue drain.\n try {\n const extractionPromise = this.orchestrator.ingestReplayBatch(turns, {\n archiveLcm: false,\n writeNamespaceOverride,\n principalOverride,\n });\n extractionPromise.catch((err) => {\n log.error(`access-observe background extraction failed: ${err}`);\n });\n extractionQueued = true;\n } catch (err) {\n // Synchronous enqueue failure (e.g. orchestrator disposed)\n log.error(`access-observe extraction enqueue failed: ${err}`);\n }\n }\n\n log.info(\n `access-observe namespace=${namespace} effectiveNamespace=${writeNamespace} sessionKey=${request.sessionKey} messages=${request.messages.length} lcm=${lcmArchived} extraction=${extractionQueued}`,\n );\n\n return {\n accepted: request.messages.length,\n sessionKey: request.sessionKey,\n namespace,\n effectiveNamespace: writeNamespace,\n scopeDebug: {\n principal: scope.principal,\n explicitNamespace: scope.explicitNamespace,\n baseNamespace: scope.baseNamespace,\n writeNamespace: scope.writeNamespace,\n codingOverlayApplied: scope.codingOverlayApplied,\n readNamespaces: scope.readNamespaces,\n },\n lcmArchived,\n extractionQueued,\n };\n }\n\n async lcmSearch(request: EngramAccessLcmSearchRequest): Promise<EngramAccessLcmSearchResponse> {\n if (!request.query || typeof request.query !== \"string\" || request.query.trim().length === 0) {\n throw new EngramAccessInputError(\"query is required and must be a non-empty string\");\n }\n\n const principal = this.resolveRequestPrincipal(request.sessionKey, request.authenticatedPrincipal);\n const hasExplicitNamespace =\n typeof request.namespace === \"string\" &&\n request.namespace.trim().length > 0;\n // Resolve the readable base namespace WITHOUT pre-authorizing `default`\n // (#1505 thread NBHWz). An EXPLICIT namespace is still authorized strictly\n // via `resolveReadableNamespace` (explicit reads must pass the ACL — throws\n // on an unreadable explicit namespace). For an IMPLICIT read, derive the\n // fallback from the ALREADY read-authorized recall namespace set instead of\n // read-authorizing `config.defaultNamespace`: under a restrictive `default`\n // READ policy where the principal's self namespace is readable, normal recall\n // still succeeds via `recallNamespacesForPrincipal`, so `lcmSearch` must too\n // (the same defect class the raw-excerpt path fixes). `undefined` ⇒ no\n // readable LCM namespace exists, so return NO rows rather than throwing.\n const namespace = hasExplicitNamespace\n ? this.resolveReadableNamespace(request.namespace, principal)\n : this.resolveImplicitLcmReadFallbackNamespace(principal);\n\n if (!this.orchestrator.lcmEngine || !this.orchestrator.lcmEngine.enabled) {\n return {\n query: request.query,\n namespace: namespace ?? this.orchestrator.config.defaultNamespace,\n results: [],\n count: 0,\n lcmEnabled: false,\n };\n }\n\n // No readable LCM namespace for an IMPLICIT read (restrictive `default` READ\n // policy, no readable overlay/self) ⇒ return NO rows instead of pre-\n // authorizing the denied default (#1505 thread NBHWz). Normal recall still\n // succeeds through the readable self namespace; LCM search degrades to empty.\n if (namespace === undefined) {\n return {\n query: request.query,\n namespace: this.orchestrator.config.defaultNamespace,\n results: [],\n count: 0,\n lcmEnabled: true,\n };\n }\n\n const limit = Math.max(1, Math.min(request.limit ?? 10, 100));\n // Route the LCM read session_id AND prefix through the SAME overlay-aware\n // namespace `observe`'s write key and compaction use (#1505 round 3). A\n // project-scoped `observe` with no explicit namespace archived under the\n // coding-overlay namespace; deriving the prefix only from the readable\n // `namespace` (as before) would search the raw key and miss those turns.\n // The effective namespace is resolved ONCE from the real session\n // (`request.sessionKey`) — the prefix is a search fragment with no bound\n // coding context, so it inherits the same namespace. Collapses to the raw key\n // for single-store / no-overlay / explicit-default flows (existing behavior).\n const lcmReadNamespace = this.resolveLcmReadNamespace(\n request.namespace,\n namespace,\n request.sessionKey,\n request.authenticatedPrincipal,\n );\n // Ordered, read-authorized LCM read key SET for a concrete `sessionKey`\n // (#1505 fallback unification). A branch-scoped session whose rows were\n // archived at project/root scope is found by querying the primary overlay key\n // first, then each coding read fallback — exactly as the orchestrator recall\n // path does. Collapses to a single key for explicit-namespace / no-overlay /\n // unreadable-self flows. The `sessionPrefix` search fragment stays on the\n // primary overlay namespace (its own coding context can't be looked up).\n const lcmSessionKeyIds = request.sessionKey\n ? this.resolveLcmReadSessionIds(\n request.namespace,\n namespace,\n request.sessionKey,\n request.authenticatedPrincipal,\n )\n : [undefined];\n const lcmSessionPrefix = request.sessionPrefix\n ? lcmSessionKeyForNamespace(\n lcmReadNamespace,\n request.sessionPrefix,\n this.orchestrator.config.defaultNamespace,\n ) ?? request.sessionPrefix\n : request.sessionPrefix;\n // SECURITY (#1495 P1 + codex P1 r2 \"Require a scoped LCM filter before\n // archive searches\"): a sessionless, prefixless `lcmSearch` issues\n // `searchContextFull(query, limit, undefined, undefined)`, an archive-wide\n // FTS scan over EVERY `session_id`, including the sentinel-framed\n // `<ns>`-scoped overlay/tenant rows. The LCM archive is keyed by the\n // `session_id` STRING and is NOT partitioned by namespace, so an unscoped\n // scan CANNOT be constrained to the caller's authorized namespace — neither\n // an explicit `namespace` nor a readable `default` confines its results to\n // rows the caller may read. The scan is therefore safe ONLY in single-store\n // mode (namespaces disabled, one shared archive owned by the caller). When\n // namespaces are ENABLED, an unscoped `lcmSearch` (no `sessionKey` AND no\n // `sessionPrefix`) must be SUPPRESSED — return EMPTY — regardless of an\n // explicit namespace or default-readability, so a caller authorized for\n // `default` (or for one explicit namespace) cannot read other namespaces'\n // transcript rows via the archive-wide scan (cross-tenant read leak). A\n // SCOPED call (sessionKey or sessionPrefix present) is unaffected: it carries\n // a namespace-framed `session_id` / prefix filter that already constrains the\n // search to the caller's authorized, read-gated namespace.\n const hasScopedSession =\n (typeof request.sessionKey === \"string\" &&\n request.sessionKey.length > 0) ||\n (typeof lcmSessionPrefix === \"string\" && lcmSessionPrefix.length > 0);\n if (!hasScopedSession && this.orchestrator.config.namespacesEnabled === true) {\n return {\n query: request.query,\n namespace,\n results: [],\n count: 0,\n lcmEnabled: true,\n };\n }\n // Query each LCM read key in order, merging + deduping rows (by\n // sessionId+turnIndex) and preserving first-seen order, capped at `limit`.\n const seenRows = new Set<string>();\n const results: Array<{ sessionId: string; content: string; turnIndex: number }> = [];\n for (const lcmSessionKey of lcmSessionKeyIds) {\n if (results.length >= limit) break;\n const rawResults = await this.orchestrator.lcmEngine.searchContextFull(\n request.query,\n limit,\n lcmSessionKey,\n lcmSessionPrefix,\n );\n for (const r of rawResults as Array<{ session_id: string; content: string; turn_index: number }>) {\n const dedupeKey = `${r.session_id}\u0000${r.turn_index}`;\n if (seenRows.has(dedupeKey)) continue;\n seenRows.add(dedupeKey);\n results.push({\n sessionId: r.session_id,\n content: r.content,\n turnIndex: r.turn_index,\n });\n if (results.length >= limit) break;\n }\n }\n\n return {\n query: request.query,\n namespace,\n results,\n count: results.length,\n lcmEnabled: true,\n };\n }\n\n /**\n * Resolve the LCM `session_id` a same-session READER (compaction flush/record,\n * `lcmSearch`, raw-excerpt lookup) must target so it matches the key `observe`\n * archived under (#1495 thread 2 + #1505 round 3, rule 42). One helper for\n * EVERY access-surface LCM read so the read key cannot drift from the write key\n * (rule 22).\n *\n * Precedence mirrors `observe`'s effective write namespace:\n * - With an explicit `request.namespace`, use the already-authorized\n * `resolvedNamespace` (the overlay never applies to an explicit write).\n * - With NO explicit namespace, an auto-scoped session was archived under\n * its coding-overlay namespace, so overlay the session's bound coding\n * context onto the principal self base — the SAME resolution\n * `resolveMemoryScopePlan`/recall use. `applyCodingNamespaceOverlay`\n * returns the base unchanged when projectScope/namespaces are off or no\n * context is bound, so single-store / no-overlay flows collapse to the raw\n * sessionKey exactly as before.\n *\n * Then encode the `${namespace}:${sessionKey}` prefix via the shared helper\n * so the read key is byte-for-byte what the LCM write and the recall readers\n * use.\n */\n /**\n * Resolve the effective LCM NAMESPACE a same-session operation must prefix\n * with (the namespace half of {@link resolveLcmReadSessionKey}). Split out so\n * `lcmSearch` can apply ONE namespace to BOTH its `sessionKey` and its\n * `sessionPrefix` — the prefix is a search fragment, not a real session, so its\n * own coding context can't be looked up; it must inherit the namespace resolved\n * from the real session (`sessionKeyForOverlay`).\n *\n * `purpose` selects the AUTHORIZATION gate applied before honouring the\n * coding overlay (#1505 round 3 + round 4, codex P2):\n *\n * - `\"read\"` (`lcmSearch` / raw-excerpt recall): the overlay rows are only\n * visible when the principal SELF base is in the READABLE RECALL SET — the\n * same gate the orchestrator's `lcmReadNamespaceForSession` and the recall\n * namespace set use (`recallNamespacesForPrincipal`, gated by both\n * `defaultRecallNamespaces.includes(\"self\")` AND `canReadNamespace`). A\n * caller that passed the default read check must NOT receive\n * `<principal>-project-*` rows the policy never granted (cross-tenant read\n * leak). When the self base is not readable, keep the just-authorized\n * namespace (collapses to the raw key on the default store).\n *\n * - `\"write\"` (`lcmCompactionFlush` / `lcmCompactionRecord`): these are\n * write/maintenance operations on the SAME queue `observe` just wrote, so\n * the gate must mirror observe's WRITE authorization (`canWriteNamespace`\n * on the self base), NOT readability. A principal that can WRITE but not\n * READ its self namespace (or whose `defaultRecallNamespaces` omits `self`)\n * archived under the overlay key via `observe`; gating compaction by\n * readability would fall back to the default/raw key and leave that queue\n * never flushed/recorded (round-4 codex P2). Write-authorized ⇒ overlay\n * key, matching the observe write key (rule 42 read/write parity; rule 39\n * identical gates across paths).\n */\n private resolveLcmReadNamespace(\n explicitNamespace: string | undefined,\n resolvedNamespace: string,\n sessionKeyForOverlay: string | undefined,\n authenticatedPrincipal: string | undefined,\n purpose: \"read\" | \"write\" = \"read\",\n ): string {\n const hasExplicitNamespace =\n typeof explicitNamespace === \"string\" && explicitNamespace.trim().length > 0;\n if (hasExplicitNamespace) return resolvedNamespace;\n // Mirror observe's write resolution: use the coding-overlay namespace when\n // one applies, else the default store. NOT the principal self base — an\n // unqualified observe archives under the default store, so a self-base prefix\n // here would target a queue observe never wrote to (#1495).\n const principal = this.resolveRequestPrincipal(\n sessionKeyForOverlay,\n authenticatedPrincipal,\n );\n const base = defaultNamespaceForPrincipal(principal, this.orchestrator.config);\n const overlaid = this.orchestrator.applyCodingNamespaceOverlay(\n sessionKeyForOverlay,\n base,\n );\n // No overlay → the default store (raw sessionKey), as before.\n if (overlaid === base) return this.orchestrator.config.defaultNamespace;\n // Overlay applied. Authorize access to the principal's `<principal>-project-*`\n // overlay base before switching the LCM key to it. The gate differs by\n // operation purpose (see the doc comment): reads use the readable-recall-set\n // gate (no cross-tenant read leak), writes use observe's write authorization\n // (so compaction targets the same overlay queue observe wrote to).\n const authorized =\n purpose === \"write\"\n ? canWriteNamespace(principal, base, this.orchestrator.config)\n : recallNamespacesForPrincipal(\n principal,\n this.orchestrator.config,\n ).includes(base);\n if (authorized) return overlaid;\n // Unauthorized overlay base. For READS, collapse to the DEFAULT STORE (the\n // raw sessionKey) EXACTLY like the orchestrator's `lcmReadNamespaceForSession`\n // (rule 39 / 42) — NOT the caller's `resolvedNamespace`, which for an implicit\n // read can be a readable recall namespace (e.g. `shared`). Returning that\n // would prefix LCM reads with `shared:sessionKey` while in-prompt recall uses\n // the raw `sessionKey`, diverging `lcmSearch`/raw disclosure from orchestrator\n // LCM reads (cursor \"LCM read gate wrong fallback\"). For an explicit read the\n // method already returned at the top, so this only affects implicit reads.\n // The (currently unused) write purpose preserves its prior `resolvedNamespace`\n // fallback for backward compatibility.\n if (purpose === \"read\") return this.orchestrator.config.defaultNamespace;\n return resolvedNamespace;\n }\n\n /**\n * Resolve the namespace the raw-disclosure excerpt lookup\n * ({@link fetchRawExcerpts}) must prefix its LCM `session_id` with (#1505\n * thread 2f7). Raw disclosure reads the SAME LCM archive `lcmSearch` and the\n * in-prompt LCM sections read, so it MUST pass through the identical\n * read-authorization gate — NOT `snapshot.namespace`, which records the\n * effective WRITE/overlay namespace (`<principal>-project-*`) even when the\n * principal can WRITE but not READ its self base (or `defaultRecallNamespaces`\n * omits `self`). Routing through `resolveLcmReadNamespace(..., \"read\")` makes\n * raw disclosure fall back to the default store exactly like normal recall +\n * `lcmSearch`, so it never attaches overlay transcript rows the read gate\n * excludes (cross-tenant read leak). Collapses to the default store / raw\n * sessionKey for single-store / no-overlay / explicit-default flows, so\n * single-user recall is byte-for-byte unchanged.\n *\n * Returns `undefined` when NO readable LCM namespace exists for an IMPLICIT\n * (no explicit `namespace`) raw recall — i.e. a restrictive `default` READ\n * policy denies the principal `default` AND no overlay/self namespace is\n * readable. In that case the caller emits NO excerpts rather than throwing\n * `namespace is not readable: default` (#1505 thread NBHWz): normal recall\n * still succeeds via `recallNamespacesForPrincipal`, so `disclosure: \"raw\"`\n * must degrade gracefully (empty excerpts), never pre-authorize `default`.\n *\n * IMPLICIT-namespace fallback selection derives from the ALREADY\n * read-authorized recall namespace set (`recallNamespacesForPrincipal` +\n * `canReadNamespace`) — the principal's self base when it is in the readable\n * recall set, else `config.defaultNamespace` ONLY when the principal may read\n * it. It NEVER pre-authorizes `default`. An EXPLICIT `namespace` is still\n * authorized strictly via `resolveReadableNamespace` (explicit reads must pass\n * the ACL — no behavior change).\n */\n private resolveRawExcerptReadNamespace(\n explicitNamespace: string | undefined,\n sessionKey: string | undefined,\n authenticatedPrincipal: string | undefined,\n ): string | undefined {\n const principal = this.resolveRequestPrincipal(\n sessionKey,\n authenticatedPrincipal,\n );\n const hasExplicitNamespace =\n typeof explicitNamespace === \"string\" &&\n explicitNamespace.trim().length > 0;\n if (hasExplicitNamespace) {\n // Explicit reads must pass the ACL — authorize strictly, exactly as\n // `lcmSearch` does (throws on an unreadable explicit namespace).\n const resolvedNamespace = this.resolveReadableNamespace(\n explicitNamespace,\n principal,\n );\n return this.resolveLcmReadNamespace(\n explicitNamespace,\n resolvedNamespace,\n sessionKey,\n authenticatedPrincipal,\n \"read\",\n );\n }\n // IMPLICIT raw recall: derive the read fallback from the ALREADY\n // read-authorized recall namespace set — NEVER pre-authorize `default`\n // (#1505 thread NBHWz). When namespaces are disabled the default store is the\n // only namespace and is always readable (byte-for-byte single-user path).\n const fallbackNamespace =\n this.resolveImplicitLcmReadFallbackNamespace(principal);\n // No readable LCM namespace at all ⇒ no excerpts (caller short-circuits).\n if (fallbackNamespace === undefined) return undefined;\n return this.resolveLcmReadNamespace(\n explicitNamespace,\n fallbackNamespace,\n sessionKey,\n authenticatedPrincipal,\n \"read\",\n );\n }\n\n /**\n * The base `resolvedNamespace` an IMPLICIT (no explicit `namespace`)\n * same-session LCM READER (`resolveRawExcerptReadNamespace`, `lcmSearch`)\n * passes into {@link resolveLcmReadNamespace} — WITHOUT pre-authorizing\n * `default` (#1505 thread NBHWz). It decides PROCEED vs SUPPRESS only; the\n * actual LCM prefix is then resolved by `resolveLcmReadNamespace`, which\n * mirrors the orchestrator's `lcmReadNamespaceForSession` EXACTLY (rule 39 /\n * 42): the coding overlay when the principal SELF base is in the readable\n * recall set, else `config.defaultNamespace` (the raw key).\n *\n * Returns `config.defaultNamespace` (PROCEED) whenever the principal has ANY\n * readable LCM access — either `default` itself is readable, OR a coding\n * overlay / self base is in the readable recall set. The returned value is\n * ALWAYS `config.defaultNamespace`, NEVER an arbitrary readable recall\n * namespace (e.g. `shared`): `resolveLcmReadNamespace` returns this fallback\n * verbatim only on the overlay-applies-but-self-unreadable branch, where the\n * orchestrator collapses to the default store — so returning anything but the\n * default store there would prefix LCM reads with `shared:sessionKey` while\n * in-prompt recall uses the raw `sessionKey`, diverging the two (cursor\n * \"LCM read gate wrong fallback\").\n *\n * Returns `undefined` (SUPPRESS) only when NO readable LCM namespace exists —\n * a restrictive `default` READ policy AND no readable overlay/self — so the\n * caller emits NO rows instead of throwing `namespace is not readable:\n * default`. Normal recall still succeeds through the readable self namespace.\n *\n * Single-store / namespaces-disabled deployments resolve to\n * `config.defaultNamespace`, keeping single-user recall byte-for-byte\n * unchanged.\n */\n private resolveImplicitLcmReadFallbackNamespace(\n principal: string | undefined,\n ): string | undefined {\n const config = this.orchestrator.config;\n if (!config.namespacesEnabled) return config.defaultNamespace;\n // PROCEED when `default` is readable (single-store / readable-default flows)\n // — the LCM prefix resolves to the overlay when self-authorized, else the\n // default raw key.\n if (canReadNamespace(principal, config.defaultNamespace, config)) {\n return config.defaultNamespace;\n }\n // Restrictive `default` READ policy. The ONLY way the implicit LCM read can\n // target an AUTHORIZED key is via the coding OVERLAY, which\n // `resolveLcmReadNamespace` switches to ONLY when the principal SELF base is\n // in the readable recall set (the SAME gate the orchestrator's\n // `lcmReadNamespaceForSession` uses). So PROCEED here ONLY when the SELF base\n // is readable-in-recall — NOT when merely some OTHER recall namespace (e.g.\n // `shared`) is readable: the LCM read can never legitimately target `shared`,\n // and returning `config.defaultNamespace` for that case would let a sessionless\n // `lcmSearch`/raw recall scan the DENIED default LCM store (codex P1 \"Don't\n // treat any readable namespace as default LCM access\"). The downstream\n // overlay-unreadable READ branch and `lcmSearch`'s sessionless guard both\n // collapse to the default raw key, so a self-readable PROCEED still yields the\n // scoped overlay key (with a session) or empty (sessionless). SUPPRESS\n // (`undefined`) when the self base is not readable-in-recall.\n const selfBase = defaultNamespaceForPrincipal(principal, config);\n const selfReadableInRecall = recallNamespacesForPrincipal(\n principal,\n config,\n ).includes(selfBase);\n return selfReadableInRecall ? config.defaultNamespace : undefined;\n }\n\n private resolveLcmReadSessionKey(\n explicitNamespace: string | undefined,\n resolvedNamespace: string,\n sessionKey: string,\n authenticatedPrincipal: string | undefined,\n purpose: \"read\" | \"write\" = \"read\",\n ): string {\n const effectiveNamespace = this.resolveLcmReadNamespace(\n explicitNamespace,\n resolvedNamespace,\n sessionKey,\n authenticatedPrincipal,\n purpose,\n );\n return (\n lcmSessionKeyForNamespace(\n effectiveNamespace,\n sessionKey,\n this.orchestrator.config.defaultNamespace,\n ) ?? sessionKey\n );\n }\n\n /**\n * Resolve the ORDERED, read-authorized set of LCM `session_id`s a same-session\n * READER (`lcmSearch`, raw-excerpt disclosure) must query so it matches every\n * key `observe` archived under across the coding scope (#1505 thread \"Include\n * coding fallback namespaces in LCM reads\").\n *\n * Mirrors the orchestrator recall path exactly (rule 39): `observe` archives\n * each turn under `${effectiveNamespace}:${sessionKey}` for whichever namespace\n * was effective at write time, and normal QMD/file recall searches the primary\n * coding-overlay namespace AND `codingOverlay.readFallbacks` (project → root).\n * A single overlay key therefore MISSES rows a branch-scoped session archived at\n * project/root scope. This returns the primary overlay LCM key first, then one\n * per read fallback, deduped + ordered so the caller can short-circuit on the\n * first hit.\n *\n * READ-AUTHORIZATION (preserved from the round-3..5 `resolveLcmReadNamespace`\n * \"read\" gate; rule 42 / 48): the overlay + fallbacks are `<principal>-project-*`\n * sub-namespaces authorized transitively by the principal SELF base. They are\n * included ONLY when the self base is in the readable recall set\n * (`recallNamespacesForPrincipal`). When the self base is NOT readable (write-\n * only / self-omitted principal), or when an explicit namespace was supplied,\n * or no overlay applies, this collapses to the single key\n * {@link resolveLcmReadSessionKey} returns — byte-for-byte the prior behavior\n * (single-store / no-overlay flows stay the raw `sessionKey`). No\n * `<principal>-project-*` key is ever searched for an unauthorized reader (no\n * cross-tenant read leak).\n */\n private resolveLcmReadSessionIds(\n explicitNamespace: string | undefined,\n resolvedNamespace: string,\n sessionKey: string,\n authenticatedPrincipal: string | undefined,\n ): string[] {\n const primary = this.resolveLcmReadSessionKey(\n explicitNamespace,\n resolvedNamespace,\n sessionKey,\n authenticatedPrincipal,\n \"read\",\n );\n const hasExplicitNamespace =\n typeof explicitNamespace === \"string\" &&\n explicitNamespace.trim().length > 0;\n // Explicit namespace → no overlay fallbacks (the overlay never applies to an\n // explicit read). Single key, unchanged.\n if (hasExplicitNamespace) return [primary];\n\n const principal = this.resolveRequestPrincipal(\n sessionKey,\n authenticatedPrincipal,\n );\n const base = defaultNamespaceForPrincipal(\n principal,\n this.orchestrator.config,\n );\n const overlaid = this.orchestrator.applyCodingNamespaceOverlay(\n sessionKey,\n base,\n );\n // No overlay → single default-store key, unchanged.\n if (overlaid === base) return [primary];\n // Overlay present but self base unreadable → the \"read\" gate already\n // collapsed `primary` to the default store; do NOT add overlay fallbacks\n // (they would be unauthorized `<principal>-project-*` keys). Single key.\n const selfReadableInRecall = recallNamespacesForPrincipal(\n principal,\n this.orchestrator.config,\n ).includes(base);\n if (!selfReadableInRecall) return [primary];\n // Self base readable → overlay rows authorized. Append one LCM key per coding\n // read fallback (project → root), combined with the principal base for\n // isolation — the SAME ordered set the orchestrator recall path searches.\n const overlay = resolveCodingNamespaceOverlay(\n this.orchestrator.getCodingContextForSession(sessionKey),\n this.orchestrator.config.codingMode,\n this.orchestrator.config.defaultNamespace,\n );\n const fallbackNamespaces = (overlay?.readFallbacks ?? []).map((fallback) =>\n combineNamespaces(base, fallback),\n );\n const out = [primary];\n const seen = new Set<string>([primary]);\n for (const ns of fallbackNamespaces) {\n const key =\n lcmSessionKeyForNamespace(\n ns,\n sessionKey,\n this.orchestrator.config.defaultNamespace,\n ) ?? sessionKey;\n if (!seen.has(key)) {\n seen.add(key);\n out.push(key);\n }\n }\n return out;\n }\n\n async lcmCompactionFlush(\n request: EngramAccessLcmCompactionFlushRequest,\n ): Promise<EngramAccessLcmCompactionFlushResponse> {\n if (!request.sessionKey || typeof request.sessionKey !== \"string\" || request.sessionKey.trim().length === 0) {\n throw new EngramAccessInputError(\"sessionKey is required and must be a non-empty string\");\n }\n\n // Authorize compaction against the SCOPED WRITE TARGET — the SAME effective\n // write namespace `observe` archived the LCM queue under — NOT a premature\n // `resolveWritableNamespace(undefined ⇒ config.defaultNamespace)` (#1505\n // thread NBHWs). Under a restrictive `default` WRITE policy where the\n // principal can still write its self/project overlay, that premature default\n // write-auth threw `namespace is not writable: default` BEFORE the scoped key\n // was computed, so the overlay queue `observe` just wrote could never be\n // flushed. `resolveMemoryScopePlan` is the ONE write-scoped plan/gate observe\n // uses (rule 22 / 39 / 42): it authorizes the principal self base for an\n // overlay write and only collapses to `config.defaultNamespace` (always\n // writable) when no overlay applies — so it never throws `not writable:\n // default` for a validly scoped observe's queue.\n const scope = await this.resolveMemoryScopePlan(request);\n // Legacy `namespace` response field: pre-#1505 semantics were exactly\n // `resolveWritableNamespace(request.namespace)` (overlay-agnostic) — the\n // authorized explicit namespace when supplied, else `config.defaultNamespace`.\n // DERIVED from the scope plan (NOT a second auth pass, #1505 thread jvO):\n // explicit ⇒ writeNamespace; coding overlay ⇒ defaultNamespace; no overlay ⇒\n // writeNamespace (== defaultNamespace). Identical to observe's legacy field.\n const namespace = scope.explicitNamespace\n ? scope.writeNamespace\n : scope.codingOverlayApplied\n ? this.orchestrator.config.defaultNamespace\n : scope.writeNamespace;\n if (!this.orchestrator.lcmEngine || !this.orchestrator.lcmEngine.enabled) {\n return {\n enabled: false,\n flushed: false,\n sessionKey: request.sessionKey,\n namespace,\n reason: \"LCM is disabled\",\n };\n }\n\n // Flush the SAME LCM session_id `observe` archived under: encode the scope\n // plan's EFFECTIVE write namespace (the coding overlay when one applies, else\n // the default store) through the SAME `lcmSessionKeyForNamespace` helper\n // observe uses for archival, so the flush key is byte-for-byte the write key\n // (#1495 thread 2 / #1505 thread NBHWs, rule 42). A write-only / self-omitted\n // principal still flushes the overlay queue because the scope plan authorized\n // the write target by WRITE policy, not readability.\n const lcmSessionKey =\n lcmSessionKeyForNamespace(\n scope.writeNamespace,\n request.sessionKey,\n this.orchestrator.config.defaultNamespace,\n ) ?? request.sessionKey;\n await this.orchestrator.lcmEngine.waitForSessionObserveIdle(lcmSessionKey);\n await this.orchestrator.lcmEngine.preCompactionFlush(lcmSessionKey);\n return {\n enabled: true,\n flushed: true,\n sessionKey: request.sessionKey,\n namespace,\n };\n }\n\n async lcmCompactionRecord(\n request: EngramAccessLcmCompactionRecordRequest,\n ): Promise<EngramAccessLcmCompactionRecordResponse> {\n if (!request.sessionKey || typeof request.sessionKey !== \"string\" || request.sessionKey.trim().length === 0) {\n throw new EngramAccessInputError(\"sessionKey is required and must be a non-empty string\");\n }\n if (!Number.isInteger(request.tokensBefore) || request.tokensBefore < 0) {\n throw new EngramAccessInputError(\"tokensBefore must be a non-negative integer\");\n }\n if (!Number.isInteger(request.tokensAfter) || request.tokensAfter < 0) {\n throw new EngramAccessInputError(\"tokensAfter must be a non-negative integer\");\n }\n\n // Authorize compaction against the SCOPED WRITE TARGET — the SAME effective\n // write namespace `observe` archived the LCM queue under — NOT a premature\n // `resolveWritableNamespace(undefined ⇒ config.defaultNamespace)` (#1505\n // thread NBHWs). See `lcmCompactionFlush` for the full rationale: under a\n // restrictive `default` WRITE policy where the principal can still write its\n // self/project overlay, the old premature default write-auth threw `namespace\n // is not writable: default` before the scoped key was computed, leaving the\n // overlay queue observe wrote unrecordable. `resolveMemoryScopePlan` is the\n // ONE write-scoped plan/gate observe uses; it authorizes the self base for an\n // overlay write and never throws `not writable: default` for a validly scoped\n // observe's queue.\n const scope = await this.resolveMemoryScopePlan(request);\n const namespace = scope.explicitNamespace\n ? scope.writeNamespace\n : scope.codingOverlayApplied\n ? this.orchestrator.config.defaultNamespace\n : scope.writeNamespace;\n if (!this.orchestrator.lcmEngine || !this.orchestrator.lcmEngine.enabled) {\n return {\n enabled: false,\n recorded: false,\n sessionKey: request.sessionKey,\n namespace,\n reason: \"LCM is disabled\",\n };\n }\n\n // Record against the SAME LCM session_id `observe` archived under — encode\n // the scope plan's EFFECTIVE write namespace through the SAME\n // `lcmSessionKeyForNamespace` helper observe uses, so the record key is\n // byte-for-byte the write key (#1495 thread 2 / #1505 thread NBHWs, rule 42).\n // A write-only / self-omitted principal still records on the overlay queue\n // because the scope plan authorized the write target by WRITE policy.\n const lcmSessionKey =\n lcmSessionKeyForNamespace(\n scope.writeNamespace,\n request.sessionKey,\n this.orchestrator.config.defaultNamespace,\n ) ?? request.sessionKey;\n await this.orchestrator.lcmEngine.waitForSessionObserveIdle(lcmSessionKey);\n await this.orchestrator.lcmEngine.recordCompaction(\n lcmSessionKey,\n request.tokensBefore,\n request.tokensAfter,\n );\n return {\n enabled: true,\n recorded: true,\n sessionKey: request.sessionKey,\n namespace,\n };\n }\n\n // ── Parity tools (match OpenClaw plugin feature set) ──────────────────\n\n // ── Continuity / Identity ──────────────────────────────────────────────\n\n async continuityAuditGenerate(request: {\n period?: \"weekly\" | \"monthly\";\n key?: string;\n }): Promise<{ enabled: boolean; reason?: string; period?: string; key?: string; reportPath?: string }> {\n if (!this.orchestrator.config.identityContinuityEnabled) {\n return { enabled: false, reason: \"Identity continuity is disabled. Enable `identityContinuityEnabled: true`.\" };\n }\n if (!this.orchestrator.config.continuityAuditEnabled) {\n return { enabled: false, reason: \"Continuity audits are disabled. Enable `continuityAuditEnabled: true`.\" };\n }\n if (!this.orchestrator.compounding) {\n return { enabled: false, reason: \"Compounding engine is disabled. Enable `compoundingEnabled: true`.\" };\n }\n const period = request.period === \"monthly\" ? \"monthly\" : \"weekly\";\n const key = request.key?.trim() || undefined;\n const audit = await this.orchestrator.compounding.synthesizeContinuityAudit({ period, key });\n return { enabled: true, period: audit.period, key: audit.key, reportPath: audit.reportPath };\n }\n\n async continuityIncidentOpen(request: {\n symptom: string;\n namespace?: string;\n principal?: string;\n triggerWindow?: string;\n suspectedCause?: string;\n }): Promise<unknown> {\n if (!this.orchestrator.config.identityContinuityEnabled) {\n return { enabled: false, reason: \"Identity continuity is disabled. Enable `identityContinuityEnabled: true`.\" };\n }\n if (!this.orchestrator.config.continuityIncidentLoggingEnabled) {\n return { enabled: false, reason: \"Continuity incident logging is disabled. Enable `continuityIncidentLoggingEnabled: true`.\" };\n }\n const symptom = request.symptom?.trim();\n if (!symptom) throw new EngramAccessInputError(\"symptom is required\");\n const resolvedNs = this.resolveWritableNamespace(request.namespace, undefined, request.principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const created = await storage.appendContinuityIncident({\n symptom,\n triggerWindow: request.triggerWindow?.trim() || undefined,\n suspectedCause: request.suspectedCause?.trim() || undefined,\n });\n return { created: true, incident: created };\n }\n\n async continuityIncidentClose(request: {\n id: string;\n namespace?: string;\n principal?: string;\n fixApplied: string;\n verificationResult: string;\n preventiveRule?: string;\n }): Promise<unknown> {\n if (!this.orchestrator.config.identityContinuityEnabled) {\n return { enabled: false, reason: \"Identity continuity is disabled.\" };\n }\n if (!this.orchestrator.config.continuityIncidentLoggingEnabled) {\n return { enabled: false, reason: \"Continuity incident logging is disabled.\" };\n }\n const id = request.id?.trim();\n if (!id) throw new EngramAccessInputError(\"id is required\");\n const fixApplied = request.fixApplied?.trim();\n if (!fixApplied) throw new EngramAccessInputError(\"fixApplied is required\");\n const verificationResult = request.verificationResult?.trim();\n if (!verificationResult) throw new EngramAccessInputError(\"verificationResult is required\");\n const resolvedNs = this.resolveWritableNamespace(request.namespace, undefined, request.principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const closed = await storage.closeContinuityIncident(id, {\n fixApplied,\n verificationResult,\n preventiveRule: request.preventiveRule?.trim() || undefined,\n });\n if (!closed) return { closed: false, reason: `Incident not found: ${id}` };\n return { closed: true, incident: closed };\n }\n\n async continuityIncidentList(request: {\n state?: \"open\" | \"closed\" | \"all\";\n namespace?: string;\n principal?: string;\n limit?: number;\n }): Promise<unknown> {\n if (!this.orchestrator.config.identityContinuityEnabled) {\n return { enabled: false, reason: \"Identity continuity is disabled.\" };\n }\n const state = request.state === \"closed\" || request.state === \"all\" ? request.state : \"open\";\n const limit = Math.max(1, Math.min(200, Math.floor(request.limit ?? 25)));\n const resolvedNs = this.resolveReadableNamespace(request.namespace, request.principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const incidents = await storage.readContinuityIncidents(limit, state);\n return { state, incidents, count: incidents.length };\n }\n\n async continuityLoopAddOrUpdate(request: {\n id: string;\n cadence: \"daily\" | \"weekly\" | \"monthly\" | \"quarterly\";\n purpose: string;\n status: \"active\" | \"paused\" | \"retired\";\n killCondition: string;\n namespace?: string;\n principal?: string;\n lastReviewed?: string;\n notes?: string;\n }): Promise<unknown> {\n if (!this.orchestrator.config.identityContinuityEnabled) {\n return { enabled: false, reason: \"Identity continuity is disabled.\" };\n }\n const resolvedNs = this.resolveWritableNamespace(request.namespace, undefined, request.principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const loop = await storage.upsertIdentityImprovementLoop({\n id: request.id?.trim() || \"\",\n cadence: request.cadence,\n purpose: request.purpose?.trim() || \"\",\n status: request.status,\n killCondition: request.killCondition?.trim() || \"\",\n lastReviewed: request.lastReviewed?.trim() || undefined,\n notes: request.notes?.trim() || undefined,\n });\n return { saved: true, loop };\n }\n\n async continuityLoopReview(request: {\n id: string;\n namespace?: string;\n principal?: string;\n status?: \"active\" | \"paused\" | \"retired\";\n notes?: string;\n reviewedAt?: string;\n }): Promise<unknown> {\n if (!this.orchestrator.config.identityContinuityEnabled) {\n return { enabled: false, reason: \"Identity continuity is disabled.\" };\n }\n const id = request.id?.trim();\n if (!id) throw new EngramAccessInputError(\"id is required\");\n const resolvedNs = this.resolveWritableNamespace(request.namespace, undefined, request.principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const reviewed = await storage.reviewIdentityImprovementLoop(id, {\n status: request.status,\n notes: request.notes?.trim() || undefined,\n reviewedAt: request.reviewedAt?.trim() || undefined,\n });\n if (!reviewed) return { reviewed: false, reason: `Continuity loop not found: ${id}` };\n return { reviewed: true, loop: reviewed };\n }\n\n async identityAnchorGet(request: {\n namespace?: string;\n principal?: string;\n }): Promise<unknown> {\n if (!this.orchestrator.config.identityContinuityEnabled) {\n return { enabled: false, reason: \"Identity continuity is disabled.\" };\n }\n const resolvedNs = this.resolveReadableNamespace(request.namespace, request.principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const anchor = await storage.readIdentityAnchor();\n if (!anchor) return { found: false, message: \"No identity anchor found yet. Use identity_anchor_update to create one.\" };\n return { found: true, anchor };\n }\n\n /**\n * @deprecated since issue #679 PR 5/5 — the identity-anchor model is\n * superseded by the peer registry. Use `peerSet({ id: \"self\", ... })` or\n * `remnic peer set self` to update the self peer's identity kernel, and\n * `remnic peer migrate` to seed `peers/self/identity.md` from existing\n * legacy anchor data. This method continues to function for backward\n * compatibility but will be removed in a future major version.\n */\n async identityAnchorUpdate(request: {\n namespace?: string;\n principal?: string;\n identityTraits?: string;\n communicationPreferences?: string;\n operatingPrinciples?: string;\n continuityNotes?: string;\n }): Promise<unknown> {\n if (!this.orchestrator.config.identityContinuityEnabled) {\n return { enabled: false, reason: \"Identity continuity is disabled.\" };\n }\n\n const updates: Record<string, string | undefined> = {\n \"Identity Traits\": request.identityTraits?.trim() || undefined,\n \"Communication Preferences\": request.communicationPreferences?.trim() || undefined,\n \"Operating Principles\": request.operatingPrinciples?.trim() || undefined,\n \"Continuity Notes\": request.continuityNotes?.trim() || undefined,\n };\n const hasUpdate = Object.values(updates).some((v) => typeof v === \"string\" && v.length > 0);\n if (!hasUpdate) throw new EngramAccessInputError(\"At least one section field is required.\");\n\n const resolvedNs = this.resolveWritableNamespace(request.namespace, undefined, request.principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const existing = await storage.readIdentityAnchor();\n\n // Merge sections conservatively (append, don't overwrite)\n const merged = this.mergeIdentityAnchorSections(existing, updates);\n await storage.writeIdentityAnchor(merged);\n\n const updatedSections = Object.entries(updates)\n .filter(([, v]) => typeof v === \"string\" && v.length > 0)\n .map(([name]) => name);\n return { updated: true, sections: updatedSections, anchor: merged };\n }\n\n async memoryIdentity(request: {\n namespace?: string;\n principal?: string;\n }): Promise<unknown> {\n const resolvedNs = this.resolveReadableNamespace(request.namespace, request.principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const identity = await storage.readIdentityReflections();\n if (!identity) return { found: false, message: \"No identity reflections found.\" };\n return { found: true, identity };\n }\n\n // ── Work Layer ──────────────────────────────────────────────────────────\n\n async workTask(request: {\n action: \"create\" | \"get\" | \"list\" | \"update\" | \"transition\" | \"delete\";\n id?: string;\n title?: string;\n description?: string;\n status?: string;\n priority?: string;\n owner?: string;\n assignee?: string;\n projectId?: string;\n tags?: string[];\n dueAt?: string;\n }): Promise<unknown> {\n const STATUSES = new Set([\"todo\", \"in_progress\", \"blocked\", \"done\", \"cancelled\"]);\n const PRIORITIES = new Set([\"low\", \"medium\", \"high\"]);\n const asStatus = (v?: string) => (v && STATUSES.has(v) ? v as \"todo\" | \"in_progress\" | \"blocked\" | \"done\" | \"cancelled\" : undefined);\n const asPriority = (v?: string) => (v && PRIORITIES.has(v) ? v as \"low\" | \"medium\" | \"high\" : undefined);\n\n const storage = new WorkStorage(this.orchestrator.config.memoryDir);\n await storage.ensureDirectories();\n const action = request.action;\n\n if (action === \"create\") {\n if (!request.title?.trim()) throw new EngramAccessInputError(\"title is required for create\");\n const task = await storage.createTask({\n title: request.title,\n description: request.description,\n status: asStatus(request.status),\n priority: asPriority(request.priority),\n owner: request.owner?.trim() || undefined,\n assignee: request.assignee?.trim() || undefined,\n projectId: request.projectId?.trim() || undefined,\n tags: request.tags,\n dueAt: request.dueAt?.trim() || undefined,\n });\n return { action, task };\n }\n if (action === \"get\") {\n if (!request.id?.trim()) throw new EngramAccessInputError(\"id is required for get\");\n return { action, task: await storage.getTask(request.id) };\n }\n if (action === \"list\") {\n const tasks = await storage.listTasks({\n status: asStatus(request.status),\n owner: request.owner?.trim() || undefined,\n assignee: request.assignee?.trim() || undefined,\n projectId: request.projectId?.trim() || undefined,\n });\n return { action, count: tasks.length, tasks };\n }\n if (action === \"update\") {\n if (!request.id?.trim()) throw new EngramAccessInputError(\"id is required for update\");\n const patch: Record<string, unknown> = {};\n if (request.title !== undefined) patch.title = request.title;\n if (request.description !== undefined) patch.description = request.description;\n const st = asStatus(request.status); if (st) patch.status = st;\n const pr = asPriority(request.priority); if (pr) patch.priority = pr;\n if (request.owner !== undefined) patch.owner = request.owner || null;\n if (request.assignee !== undefined) patch.assignee = request.assignee || null;\n if (request.projectId !== undefined) patch.projectId = request.projectId || null;\n if (request.tags) patch.tags = request.tags;\n if (request.dueAt !== undefined) patch.dueAt = request.dueAt || null;\n return { action, task: await storage.updateTask(request.id, patch as any) };\n }\n if (action === \"transition\") {\n if (!request.id?.trim()) throw new EngramAccessInputError(\"id is required for transition\");\n const st = asStatus(request.status);\n if (!st) throw new EngramAccessInputError(\"valid status is required for transition\");\n return { action, task: await storage.transitionTask(request.id, st) };\n }\n if (action === \"delete\") {\n if (!request.id?.trim()) throw new EngramAccessInputError(\"id is required for delete\");\n return { action, deleted: await storage.deleteTask(request.id) };\n }\n throw new EngramAccessInputError(`Unsupported work_task action: ${action}`);\n }\n\n async workProject(request: {\n action: \"create\" | \"get\" | \"list\" | \"update\" | \"delete\" | \"link_task\";\n id?: string;\n name?: string;\n description?: string;\n status?: string;\n owner?: string;\n tags?: string[];\n taskId?: string;\n projectId?: string;\n }): Promise<unknown> {\n const STATUSES = new Set([\"active\", \"on_hold\", \"completed\", \"archived\"]);\n const asStatus = (v?: string) => (v && STATUSES.has(v) ? v as \"active\" | \"on_hold\" | \"completed\" | \"archived\" : undefined);\n\n const storage = new WorkStorage(this.orchestrator.config.memoryDir);\n await storage.ensureDirectories();\n const action = request.action;\n\n if (action === \"create\") {\n if (!request.name?.trim()) throw new EngramAccessInputError(\"name is required for create\");\n const project = await storage.createProject({\n name: request.name,\n description: request.description,\n status: asStatus(request.status),\n owner: request.owner?.trim() || undefined,\n tags: request.tags,\n });\n return { action, project };\n }\n if (action === \"get\") {\n if (!request.id?.trim()) throw new EngramAccessInputError(\"id is required for get\");\n return { action, project: await storage.getProject(request.id) };\n }\n if (action === \"list\") {\n const projects = await storage.listProjects();\n return { action, count: projects.length, projects };\n }\n if (action === \"update\") {\n if (!request.id?.trim()) throw new EngramAccessInputError(\"id is required for update\");\n const patch: Record<string, unknown> = {};\n if (request.name !== undefined) patch.name = request.name;\n if (request.description !== undefined) patch.description = request.description;\n const st = asStatus(request.status); if (st) patch.status = st;\n if (request.owner !== undefined) patch.owner = request.owner || null;\n if (request.tags) patch.tags = request.tags;\n return { action, project: await storage.updateProject(request.id, patch as any) };\n }\n if (action === \"delete\") {\n if (!request.id?.trim()) throw new EngramAccessInputError(\"id is required for delete\");\n return { action, deleted: await storage.deleteProject(request.id) };\n }\n if (action === \"link_task\") {\n if (!request.taskId?.trim() || !request.projectId?.trim()) {\n throw new EngramAccessInputError(\"taskId and projectId are required for link_task\");\n }\n return { action, linked: await storage.linkTaskToProject(request.taskId, request.projectId) };\n }\n throw new EngramAccessInputError(`Unsupported work_project action: ${action}`);\n }\n\n async workBoard(request: {\n action: \"export_markdown\" | \"export_snapshot\" | \"import_snapshot\";\n projectId?: string;\n snapshotJson?: string;\n linkToMemory?: boolean;\n }): Promise<unknown> {\n const memoryDir = this.orchestrator.config.memoryDir;\n await new WorkStorage(memoryDir).ensureDirectories();\n const action = request.action;\n const projectId = request.projectId?.trim() || undefined;\n\n if (action === \"export_markdown\") {\n const markdown = await exportWorkBoardMarkdown({ memoryDir, projectId });\n return { action, markdown: wrapWorkLayerContext(markdown, { linkToMemory: request.linkToMemory === true }) };\n }\n if (action === \"export_snapshot\") {\n const snapshot = await exportWorkBoardSnapshot({ memoryDir, projectId });\n return { action, snapshot };\n }\n if (action === \"import_snapshot\") {\n if (!request.snapshotJson?.trim()) throw new EngramAccessInputError(\"snapshotJson is required for import_snapshot\");\n const snapshot = JSON.parse(request.snapshotJson);\n const result = await importWorkBoardSnapshot({ memoryDir, snapshot, projectId });\n return { action, result };\n }\n throw new EngramAccessInputError(`Unsupported work_board action: ${action}`);\n }\n\n // ── Shared Context / Compounding ────────────────────────────────────────\n\n async sharedContextWriteOutput(request: {\n agentId: string;\n title: string;\n content: string;\n }): Promise<unknown> {\n if (!this.orchestrator.sharedContext) {\n return { enabled: false, reason: \"Shared context is disabled. Enable `sharedContextEnabled: true`.\" };\n }\n const fp = await this.orchestrator.sharedContext.writeAgentOutput({\n agentId: request.agentId,\n title: request.title,\n content: request.content,\n });\n return { written: true, path: fp };\n }\n\n async sharedFeedbackRecord(request: {\n agent: string;\n decision: \"approved\" | \"approved_with_feedback\" | \"rejected\";\n reason: string;\n date?: string;\n learning?: string;\n outcome?: string;\n severity?: \"low\" | \"medium\" | \"high\";\n confidence?: number;\n workflow?: string;\n tags?: string[];\n evidenceWindowStart?: string;\n evidenceWindowEnd?: string;\n refs?: string[];\n }): Promise<unknown> {\n if (!this.orchestrator.sharedContext) {\n return { enabled: false, reason: \"Shared context is disabled. Enable `sharedContextEnabled: true`.\" };\n }\n await this.orchestrator.sharedContext.appendFeedback({\n agent: request.agent,\n decision: request.decision,\n reason: request.reason,\n date: request.date?.trim() || new Date().toISOString(),\n learning: request.learning,\n outcome: request.outcome,\n severity: request.severity,\n confidence: request.confidence,\n workflow: request.workflow,\n tags: request.tags,\n evidenceWindowStart: request.evidenceWindowStart,\n evidenceWindowEnd: request.evidenceWindowEnd,\n refs: request.refs,\n });\n return { recorded: true };\n }\n\n async sharedPrioritiesAppend(request: {\n agentId: string;\n text: string;\n }): Promise<unknown> {\n if (!this.orchestrator.sharedContext) {\n return { enabled: false, reason: \"Shared context is disabled. Enable `sharedContextEnabled: true`.\" };\n }\n await this.orchestrator.sharedContext.appendPrioritiesInbox({\n agentId: request.agentId,\n text: request.text,\n });\n return { appended: true };\n }\n\n async sharedContextCrossSignalsRun(request: {\n date?: string;\n }): Promise<unknown> {\n if (!this.orchestrator.sharedContext) {\n return { enabled: false, reason: \"Shared context is disabled. Enable `sharedContextEnabled: true`.\" };\n }\n const result = await this.orchestrator.sharedContext.synthesizeCrossSignals({ date: request.date });\n return {\n crossSignalsMarkdownPath: result.crossSignalsMarkdownPath,\n crossSignalsPath: result.crossSignalsPath,\n sourceCount: result.report.sourceCount,\n feedbackCount: result.report.feedbackCount,\n overlapCount: result.overlapCount,\n };\n }\n\n async sharedContextCurateDaily(request: {\n date?: string;\n }): Promise<unknown> {\n if (!this.orchestrator.sharedContext) {\n return { enabled: false, reason: \"Shared context is disabled. Enable `sharedContextEnabled: true`.\" };\n }\n const result = await this.orchestrator.sharedContext.curateDaily({ date: request.date });\n return {\n roundtablePath: result.roundtablePath,\n crossSignalsMarkdownPath: result.crossSignalsMarkdownPath,\n crossSignalsPath: result.crossSignalsPath,\n overlapCount: result.overlapCount,\n };\n }\n\n async compoundingWeeklySynthesize(request: {\n weekId?: string;\n }): Promise<unknown> {\n if (!this.orchestrator.compounding) {\n return { enabled: false, reason: \"Compounding engine is disabled. Enable `compoundingEnabled: true`.\" };\n }\n const res = await this.orchestrator.compounding.synthesizeWeekly({ weekId: request.weekId });\n return {\n weekId: res.weekId,\n reportPath: res.reportPath,\n reportJsonPath: res.reportJsonPath,\n rubricsPath: res.rubricsPath,\n rubricsIndexPath: res.rubricsIndexPath,\n mistakesCount: res.mistakesCount,\n promotionCandidateCount: res.promotionCandidateCount,\n };\n }\n\n async compoundingPromoteCandidate(request: {\n weekId: string;\n candidateId: string;\n dryRun?: boolean;\n }): Promise<unknown> {\n if (!this.orchestrator.compounding) {\n return { enabled: false, reason: \"Compounding engine is disabled. Enable `compoundingEnabled: true`.\" };\n }\n return await this.orchestrator.compounding.promoteCandidate({\n weekId: request.weekId,\n candidateId: request.candidateId,\n dryRun: request.dryRun,\n });\n }\n\n // ── Compression Guidelines ────────────────────────────────────────────\n\n async compressionGuidelinesOptimize(request: {\n dryRun?: boolean;\n eventLimit?: number;\n }): Promise<unknown> {\n if (!this.orchestrator.config.compressionGuidelineLearningEnabled) {\n return { enabled: false, reason: \"Compression guideline learning is disabled. Enable `compressionGuidelineLearningEnabled: true`.\" };\n }\n return await this.orchestrator.optimizeCompressionGuidelines({\n dryRun: request.dryRun,\n eventLimit: request.eventLimit,\n });\n }\n\n async compressionGuidelinesActivate(request: {\n expectedContentHash?: string;\n expectedGuidelineVersion?: number;\n }): Promise<unknown> {\n if (!this.orchestrator.config.compressionGuidelineLearningEnabled) {\n return { enabled: false, reason: \"Compression guideline learning is disabled.\" };\n }\n return await this.orchestrator.activateCompressionGuidelineDraft({\n expectedContentHash: request.expectedContentHash,\n expectedGuidelineVersion: request.expectedGuidelineVersion,\n });\n }\n\n /** Conservative identity anchor section merge (matches tools.ts mergeIdentityAnchor logic). */\n private mergeIdentityAnchorSections(\n existingRaw: string | null,\n updates: Record<string, string | undefined>,\n ): string {\n const TITLE = \"# Identity Continuity Anchor\";\n const SECTION_ORDER = [\"Identity Traits\", \"Communication Preferences\", \"Operating Principles\", \"Continuity Notes\"];\n\n const lines = (existingRaw ?? \"\").replace(/\\r/g, \"\").split(\"\\n\");\n const headerLines: string[] = [];\n const sectionContent = new Map<string, string[]>();\n const order: string[] = [];\n let current: string | null = null;\n for (const line of lines) {\n const m = line.match(/^##\\s+(.+?)\\s*$/);\n if (m) { current = m[1].trim(); if (!sectionContent.has(current)) { sectionContent.set(current, []); order.push(current); } continue; }\n if (!current) { headerLines.push(line); } else { sectionContent.get(current)?.push(line); }\n }\n const sections = new Map<string, string>();\n for (const [name, cLines] of sectionContent) sections.set(name, cLines.join(\"\\n\").trim());\n\n const header = headerLines.join(\"\\n\").trim() || TITLE;\n for (const sectionName of SECTION_ORDER) {\n const prev = sections.get(sectionName)?.trim();\n const next = updates[sectionName]?.trim();\n const existing = prev === \"- (empty)\" ? \"\" : prev;\n if (!next) { if (!sections.has(sectionName)) sections.set(sectionName, \"\"); continue; }\n if (!existing) { sections.set(sectionName, next); continue; }\n if (existing.includes(next)) continue;\n if (next.includes(existing)) { sections.set(sectionName, next); continue; }\n sections.set(sectionName, `${existing}\\n\\n${next}`);\n }\n\n const finalOrder = [...SECTION_ORDER.filter((s) => sections.has(s)), ...order.filter((s) => !SECTION_ORDER.includes(s) && sections.has(s))];\n const out: string[] = [header, \"\"];\n for (const name of finalOrder) {\n out.push(`## ${name}`, \"\");\n const body = sections.get(name)?.trim();\n if (body) out.push(body, \"\");\n else out.push(\"\");\n }\n return out.join(\"\\n\").replace(/\\n{3,}/g, \"\\n\\n\").trimEnd() + \"\\n\";\n }\n\n // ── Memory search & debug ─────────────────────────────────────────────\n\n async memorySearch(request: {\n query: string;\n namespace?: string;\n maxResults?: number;\n collection?: string;\n principal?: string;\n }): Promise<{ query: string; results: Array<{ path: string; score: number; snippet: string }>; count: number }> {\n const { query, namespace, maxResults, principal } = request;\n const collection = request.collection?.trim();\n if (request.collection !== undefined && !collection) {\n throw new EngramAccessInputError(\"collection must be a non-empty string\");\n }\n\n let results: Array<{ path: string; score: number; snippet?: string }>;\n if (!this.orchestrator.config.namespacesEnabled) {\n this.resolveReadableNamespace(namespace, principal);\n results = collection === \"global\"\n ? await this.orchestrator.qmd.searchGlobal(query, maxResults)\n : await this.orchestrator.qmd.search(query, collection, maxResults);\n } else {\n const readableNamespaces = this.resolveReadableNamespacesForSearch(namespace, principal);\n const namespaces = this.resolveMemorySearchNamespacesForCollection(\n collection,\n readableNamespaces,\n namespace?.trim() ? undefined : principal,\n );\n results = namespaces.length === 0\n ? []\n : await this.orchestrator.searchAcrossNamespaces({\n query,\n namespaces,\n maxResults,\n mode: \"search\",\n });\n }\n\n return {\n query,\n results: results.map((r) => ({\n path: r.path,\n score: r.score,\n snippet: (r.snippet ?? \"\").slice(0, 800),\n })),\n count: results.length,\n };\n }\n\n async memoryProfile(namespace?: string, principal?: string): Promise<Record<string, unknown>> {\n const resolvedNs = this.resolveReadableNamespace(namespace, principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const profile = await storage.readProfile();\n return {\n profile: profile || \"No profile built yet. The profile builds automatically through conversations.\",\n };\n }\n\n async memoryEntitiesList(namespace?: string, principal?: string): Promise<{ entities: string[]; count: number }> {\n const resolvedNs = this.resolveReadableNamespace(namespace, principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const entities = await storage.readEntities();\n return { entities, count: entities.length };\n }\n\n async memoryQuestions(namespace?: string, principal?: string): Promise<{ questions: Array<{ id: string; question: string; resolved: boolean }>; count: number }> {\n const resolvedNs = this.resolveReadableNamespace(namespace, principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const questions = await storage.readQuestions();\n return {\n questions: questions.map((q) => ({ id: q.id, question: q.question, resolved: q.resolved })),\n count: questions.length,\n };\n }\n\n async lastRecallSnapshot(sessionKey?: string): Promise<unknown> {\n const snapshot = sessionKey\n ? this.orchestrator.lastRecall.get(sessionKey)\n : this.orchestrator.lastRecall.getMostRecent();\n return snapshot ?? { message: \"No recall snapshot available\" };\n }\n\n async intentDebug(namespace?: string): Promise<unknown> {\n const snapshot = await this.orchestrator.getLastIntentSnapshot(namespace);\n return snapshot ?? { message: \"No intent debug snapshot available\" };\n }\n\n async qmdDebug(namespace?: string): Promise<unknown> {\n const snapshot = await this.orchestrator.getLastQmdRecallSnapshot(namespace);\n return snapshot ?? { message: \"No QMD debug snapshot available\" };\n }\n\n async graphExplainLastRecall(namespace?: string): Promise<unknown> {\n const explanation = await this.orchestrator.explainLastGraphRecall({ namespace });\n return { explanation };\n }\n\n /**\n * Read-only graph snapshot for the admin pane (issue #691 PR 2/5).\n *\n * Reads adjacency from the JSONL edge store written by `GraphIndex` and\n * resolves node metadata via the namespaced storage manager. Namespace\n * resolution mirrors the read-side path used by `recall` /\n * `procedureStats`, so multi-principal deployments can't leak edges from\n * a peer namespace (CLAUDE.md rule 42).\n */\n async graphSnapshot(\n request: GraphSnapshotRequest & { namespace?: string },\n authenticatedPrincipal?: string,\n ): Promise<GraphSnapshotResponse> {\n const namespace = this.resolveReadableNamespace(\n request.namespace,\n authenticatedPrincipal,\n );\n const storage = await this.orchestrator.getStorage(namespace);\n const cfg = this.orchestrator.config;\n // Canonicalize the storage root once — through `realpath` so that any\n // symlink in the namespace root path itself is resolved before we\n // compare children against it. This is required because\n // `GraphEdge.from` / `to` are JSONL-parsed strings — a malformed edge\n // with an absolute path, a `..` segment, OR a symlink that resolves\n // to a file outside the namespace would otherwise read a memory file\n // from a peer namespace, leaking metadata across tenants\n // (codex P1 + follow-up on PR #734; CLAUDE.md rule 42).\n let namespaceRootReal: string;\n try {\n namespaceRootReal = await nodeFs.realpath(storage.dir);\n } catch {\n // If the namespace root itself doesn't exist on disk yet (fresh\n // install with no memories), fall back to the lexical resolve so\n // the snapshot can still return an empty result rather than\n // throwing. No symlink can resolve through a missing path, so\n // this fallback is safe — every candidate we see will fail the\n // realpath step below and surface as `null`.\n namespaceRootReal = nodePath.resolve(storage.dir);\n }\n const namespaceRootWithSep = namespaceRootReal.endsWith(nodePath.sep)\n ? namespaceRootReal\n : namespaceRootReal + nodePath.sep;\n const loadNode = async (relPath: string): Promise<GraphSnapshotNodeMetadata | null> => {\n // `GraphEdge.from` / `to` are storage-relative paths; resolve against\n // the namespaced storage root so the metadata read honors namespace\n // boundaries even when the same memory id exists in multiple\n // namespaces.\n //\n // Three-stage guard:\n // 1. Reject absolute paths up front — only relative endpoints are\n // ever produced by the writer, so anything else is malformed.\n // 2. Lexical containment check on the resolved path. This catches\n // `..` traversals before we touch the filesystem.\n // 3. `fs.realpath` containment check — resolves symlinks so an\n // in-namespace path that *points* at an out-of-namespace file\n // is still rejected. Without this step a symlinked endpoint\n // could leak a peer namespace's frontmatter.\n // Bad paths surface a length-only warning (never echo the offending\n // segments — those would themselves cross namespace boundaries\n // through the log surface) and fall through to a `null` metadata\n // result.\n if (nodePath.isAbsolute(relPath)) {\n log.warn(\n `graphSnapshot: rejected absolute edge endpoint (len=${relPath.length}) `\n + `outside namespace root`,\n );\n return null;\n }\n const candidate = nodePath.resolve(namespaceRootReal, relPath);\n if (candidate !== namespaceRootReal && !candidate.startsWith(namespaceRootWithSep)) {\n log.warn(\n `graphSnapshot: rejected traversing edge endpoint (len=${relPath.length}) `\n + `outside namespace root`,\n );\n return null;\n }\n let canonical: string;\n try {\n canonical = await nodeFs.realpath(candidate);\n } catch {\n // Missing file — `readMemoryByPath` will return null too. We\n // intentionally still call it so callers see a consistent\n // \"unknown\" result rather than special-casing missing edges.\n canonical = candidate;\n }\n if (canonical !== namespaceRootReal && !canonical.startsWith(namespaceRootWithSep)) {\n log.warn(\n `graphSnapshot: rejected symlinked edge endpoint (len=${relPath.length}) `\n + `that resolved outside namespace root`,\n );\n return null;\n }\n // Both `canonical` (realpath of candidate) and `namespaceRootReal`\n // (realpath of storage.dir) are fully resolved here, so the\n // containment check above is comparing apples-to-apples even when\n // storage.dir (= storage.baseDir) is itself a symlink to the real\n // directory. Pass `canonical` — not the pre-realpath `candidate` —\n // so the storage read also uses the stable real path.\n const memory = await storage.readMemoryByPath(canonical);\n if (!memory) return null;\n const fm = memory.frontmatter;\n return {\n category: fm.category ?? \"unknown\",\n label: fm.id ?? nodePath.basename(canonical, nodePath.extname(canonical)),\n updated: fm.updated,\n };\n };\n // Use the realpath-resolved namespace root for the edge-file read so\n // the JSONL location is stable whether storage.dir is a direct path\n // or a symlink. namespaceRootReal was computed via `fs.realpath`\n // above; using it here keeps both the graph-file I/O and the loadNode\n // containment check on the same resolved base path.\n return buildGraphSnapshot({\n memoryDir: namespaceRootReal,\n graphConfig: {\n entityGraphEnabled: cfg.entityGraphEnabled === true,\n timeGraphEnabled: cfg.timeGraphEnabled === true,\n causalGraphEnabled: cfg.causalGraphEnabled === true,\n },\n request: {\n limit: request.limit,\n since: request.since,\n focusNodeId: request.focusNodeId,\n categories: request.categories,\n },\n loadNode,\n });\n }\n\n async memoryFeedback(request: {\n memoryId: string;\n vote: \"up\" | \"down\";\n note?: string;\n }): Promise<{ recorded: boolean; enabled?: boolean; reason?: string }> {\n if (!this.orchestrator.config.feedbackEnabled) {\n return {\n recorded: false,\n enabled: false,\n reason: \"Feedback is disabled. Enable `feedbackEnabled: true` in the Engram config to store feedback.\",\n };\n }\n await this.orchestrator.recordMemoryFeedback(\n request.memoryId,\n request.vote,\n request.note,\n );\n return { recorded: true };\n }\n\n /**\n * Record a Memory Worth outcome observation (issue #560 PR 3).\n *\n * This is distinct from `memoryFeedback` — feedback is a human thumbs\n * up/down on whether a recalled memory was relevant; outcome is an\n * automated signal about whether the session that consumed the memory\n * ultimately succeeded or failed. Outcomes feed the Laplace-smoothed\n * worth score (`computeMemoryWorth`, PR 2) that PR 4 will use to\n * downweight memories correlated with bad sessions.\n *\n * The underlying writer only touches fact-category memories. Corrections,\n * procedures, and other kinds return `{ ok: false, reason:\n * \"ineligible_category\" }` so a ledger drainer doesn't need to pre-filter.\n */\n async memoryOutcome(request: {\n memoryId: string;\n outcome: MemoryOutcomeKind;\n namespace?: string;\n principal?: string;\n sessionKey?: string;\n timestamp?: string;\n }): Promise<RecordMemoryOutcomeResult> {\n if (request.memoryId.includes(\"/\") || request.memoryId.includes(\"\\\\\")) {\n throw new EngramAccessInputError(\n \"memoryId must not contain path separators\",\n );\n }\n const resolvedNs = this.resolveWritableNamespace(\n request.namespace,\n request.sessionKey,\n request.principal,\n );\n const storage = await this.orchestrator.getStorage(resolvedNs);\n // We only have the ID at the access surface, but `recordMemoryOutcome`\n // accepts a path for the benefit of ledger-driven callers that already\n // have the path in hand. Build the conventional `<id>.md` shape —\n // `memoryIdFromPath` extracts the basename so the intermediate\n // directory layout doesn't matter.\n return recordMemoryOutcome(storage, {\n memoryPath: `${request.memoryId}.md`,\n outcome: request.outcome,\n timestamp: request.timestamp,\n });\n }\n\n async memoryPromote(request: {\n memoryId: string;\n namespace?: string;\n principal?: string;\n sessionKey?: string;\n }): Promise<unknown> {\n const resolvedNs = this.resolveWritableNamespace(request.namespace, request.sessionKey, request.principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n // Update frontmatter to active status (promote from pending/draft)\n await storage.updateMemoryFrontmatter(request.memoryId, {\n lifecycleState: \"active\",\n updated: new Date().toISOString(),\n });\n return { promoted: true, memoryId: request.memoryId };\n }\n\n async memoryActionApply(request: {\n action: string;\n outcome?: string;\n reason?: string;\n memoryId?: string;\n namespace?: string;\n principal?: string;\n sessionKey?: string;\n content?: string;\n category?: string;\n linkTargetId?: string;\n linkType?: string;\n linkStrength?: number;\n artifactType?: string;\n execute?: boolean;\n sourcePrompt?: string;\n dryRun?: boolean;\n }): Promise<unknown> {\n const actionTypes = 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 if (!actionTypes.has(request.action as MemoryActionType)) {\n throw new EngramAccessInputError(\n `memory_action_apply: invalid action ${JSON.stringify(request.action)}`,\n );\n }\n\n if (this.orchestrator.config.contextCompressionActionsEnabled !== true) {\n throw new EngramAccessInputError(\n \"memory_action_apply is disabled; enable contextCompressionActionsEnabled to use this tool\",\n );\n }\n\n const outcome = request.outcome ?? \"skipped\";\n if (outcome !== \"applied\" && outcome !== \"skipped\" && outcome !== \"failed\") {\n throw new EngramAccessInputError(\n `memory_action_apply: outcome must be \"applied\", \"skipped\", or \"failed\"; got ${JSON.stringify(outcome)}`,\n );\n }\n\n const resolvedNs = this.resolveWritableNamespace(\n request.namespace,\n request.sessionKey,\n request.principal,\n );\n const inputSummaryParts = [\n request.content,\n request.category ? `category=${request.category}` : undefined,\n request.linkTargetId ? `linkTargetId=${request.linkTargetId}` : undefined,\n request.linkType ? `linkType=${request.linkType}` : undefined,\n typeof request.linkStrength === \"number\"\n ? `linkStrength=${request.linkStrength}`\n : undefined,\n request.artifactType ? `artifactType=${request.artifactType}` : undefined,\n typeof request.execute === \"boolean\" ? `execute=${request.execute}` : undefined,\n ].filter((part): part is string => typeof part === \"string\" && part.length > 0);\n\n const event = {\n action: request.action as MemoryActionType,\n outcome: outcome as MemoryActionOutcome,\n namespace: resolvedNs,\n actor: \"access.memory_action_apply\",\n subsystem: \"access.memory_action_apply\",\n reason: request.reason,\n memoryId: request.memoryId,\n sourceSessionKey: request.sessionKey,\n inputSummary: inputSummaryParts.length > 0\n ? inputSummaryParts.join(\" | \").slice(0, 500)\n : undefined,\n dryRun: request.dryRun === true,\n promptHash:\n typeof request.sourcePrompt === \"string\" && request.sourcePrompt.length > 0\n ? createHash(\"sha256\").update(request.sourcePrompt).digest(\"hex\")\n : undefined,\n };\n const preview = this.orchestrator.previewMemoryActionEvent(event);\n if (request.dryRun === true) {\n return { recorded: false, dryRun: true, event: preview };\n }\n\n const recorded = await this.orchestrator.appendMemoryActionEvent(event);\n return { recorded, event: preview };\n }\n\n async contextCheckpoint(request: {\n sessionKey: string;\n context: string;\n namespace?: string;\n principal?: string;\n }): Promise<{ saved: boolean }> {\n const resolvedNs = this.resolveWritableNamespace(request.namespace, request.sessionKey, request.principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const storageDir = storage.dir;\n const { writeFile, mkdir } = await import(\"node:fs/promises\");\n const { join, resolve } = await import(\"node:path\");\n // Sanitize sessionKey to prevent path traversal\n const safeKey = request.sessionKey.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n if (!safeKey) throw new EngramAccessInputError(\"sessionKey is required\");\n const checkpointDir = join(storageDir, \"checkpoints\", safeKey);\n // Double-check resolved path stays inside storageDir\n const resolved = resolve(checkpointDir);\n if (!resolved.startsWith(resolve(storageDir))) {\n throw new EngramAccessInputError(\"Invalid sessionKey\");\n }\n await mkdir(checkpointDir, { recursive: true });\n const ts = new Date().toISOString().replace(/[:.]/g, \"-\");\n const filePath = join(checkpointDir, `checkpoint-${ts}.md`);\n await writeFile(filePath, request.context, \"utf-8\");\n return { saved: true };\n }\n\n async lcmStatus(): Promise<EngramAccessLcmStatusResponse> {\n if (!this.orchestrator.lcmEngine || !this.orchestrator.lcmEngine.enabled) {\n return {\n enabled: false,\n archiveAvailable: false,\n };\n }\n\n const stats = await this.orchestrator.lcmEngine.getStats();\n return {\n enabled: true,\n archiveAvailable: true,\n stats: {\n totalTurns: stats.totalMessages,\n },\n };\n }\n\n /**\n * Record citation usage from an observed oai-mem-citation block.\n * For each citation entry, extract the memory ID from the path and\n * increment its access tracking via the orchestrator. Returns the\n * count of submitted IDs and the count of IDs that matched real memories.\n */\n async recordCitationUsage(request: {\n sessionId?: string;\n namespace?: string;\n authenticatedPrincipal?: string;\n entries: Array<{ path: string; lineStart: number; lineEnd: number; note: string }>;\n rolloutIds: string[];\n }): Promise<{ submitted: number; matched: number }> {\n if (request.entries.length === 0) return { submitted: 0, matched: 0 };\n\n // Enforce namespace ACLs — citation tracking is a write-like operation.\n // Pass authenticatedPrincipal so the principal resolution matches other\n // write endpoints (gotcha #42: read and write paths must resolve through\n // the same namespace layer).\n const resolvedNamespace = this.resolveWritableNamespace(\n request.namespace,\n request.sessionId,\n request.authenticatedPrincipal,\n );\n\n // Extract memory IDs from citation paths. The path in citations\n // follows the pattern `facts/<id>.md` or just `<id>.md`.\n const memoryIds: string[] = [];\n for (const entry of request.entries) {\n // Strip directory prefix and .md extension to derive the memory ID.\n const basename = entry.path.split(\"/\").pop() ?? entry.path;\n const id = basename.endsWith(\".md\") ? basename.slice(0, -3) : basename;\n if (id.length > 0) {\n memoryIds.push(id);\n }\n }\n\n if (memoryIds.length === 0) return { submitted: 0, matched: 0 };\n\n // Determine which IDs correspond to real memories in storage using a\n // targeted file-existence scan instead of loading all memories (Finding #2).\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const existingIds = await storage.filterExistingMemoryIds(memoryIds);\n const matchedIds = memoryIds.filter((id) => existingIds.has(id));\n\n if (matchedIds.length > 0) {\n try {\n this.orchestrator.trackMemoryAccess(matchedIds);\n } catch {\n // Fail gracefully — citation usage tracking is best-effort.\n log.debug(\"citation usage tracking: failed to record access for cited memories\");\n }\n }\n\n return { submitted: memoryIds.length, matched: matchedIds.length };\n }\n\n // ── Operator Console state (issue #688 PR 2/3) ────────────────────────────\n\n /**\n * Gather a point-in-time `ConsoleStateSnapshot` from the orchestrator.\n *\n * Principal-aware: `resolveReadableNamespace` enforces ACL before the\n * snapshot is gathered, so callers cannot read a namespace they don't\n * have read access to (CLAUDE.md rule 42). The resolved namespace's\n * storage directory is forwarded as `config.memoryDir` so the ledger-\n * tail reader in `gatherConsoleState` scans the correct namespace root\n * rather than the global root. Read-only — never mutates orchestrator state.\n */\n async consoleState(\n namespace?: string,\n principal?: string,\n ): Promise<import(\"./console/state.js\").ConsoleStateSnapshot> {\n // Enforce namespace ACL — throws EngramAccessInputError if unauthorized.\n const resolvedNamespace = this.resolveReadableNamespace(namespace, principal);\n // Resolve the storage dir for the namespace so the ledger-tail reader\n // scans the right directory tree.\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const { gatherConsoleState } = await import(\"./console/state.js\");\n // Pass a thin proxy that overrides config.memoryDir with the namespace-\n // scoped storage dir while delegating everything else to the real\n // orchestrator (buffer, qmd, extraction queue, etc. are process-global\n // and don't require further namespace scoping for a read-only snapshot).\n const orchestratorProxy = Object.create(this.orchestrator, {\n config: {\n value: { ...this.orchestrator.config, memoryDir: storage.dir },\n enumerable: true,\n configurable: true,\n },\n }) as import(\"./console/state.js\").ConsoleStateOrchestratorLike;\n return gatherConsoleState(orchestratorProxy);\n }\n\n // ── Peer Registry surfaces (issue #679 PR 4/5) ────────────────────────────\n\n /**\n * List all registered peers. Returns the array of `Peer` objects in\n * deterministic alphabetical order (mirroring `listPeers` storage semantics).\n */\n async peerList(): Promise<{ peers: import(\"./peers/types.js\").Peer[] }> {\n const { listPeers } = await import(\"./peers/index.js\");\n const peers = await listPeers(this.orchestrator.config.memoryDir);\n return { peers };\n }\n\n /**\n * Get a single peer by id. Returns `{ found: false }` when the peer does\n * not exist rather than throwing, matching the `memoryGet` / `entityGet`\n * pattern used throughout the service.\n */\n async peerGet(\n peerId: string,\n ): Promise<\n | { found: true; peer: import(\"./peers/types.js\").Peer }\n | { found: false }\n > {\n const peers = await import(\"./peers/index.js\");\n const validateId: (id: unknown) => void = peers.assertValidPeerId;\n try {\n validateId(peerId);\n } catch (err) {\n throw new EngramAccessInputError((err as Error).message);\n }\n const peer = await peers.readPeer(this.orchestrator.config.memoryDir, peerId);\n if (!peer) return { found: false };\n return { found: true, peer };\n }\n\n /**\n * Upsert a peer. Writes `peers/{id}/identity.md`. On first write the\n * `createdAt` timestamp is set to now; on subsequent writes only\n * `displayName` and `notes` are mutated (kind and createdAt are immutable\n * once set, per the storage contract).\n *\n * Returns `{ created: true }` on first write, `{ created: false }` on update.\n */\n async peerSet(input: {\n id: string;\n kind?: string;\n displayName?: string;\n notes?: string;\n }): Promise<{ ok: true; created: boolean; peer: import(\"./peers/types.js\").Peer }> {\n const peers = await import(\"./peers/index.js\");\n const validateId: (id: unknown) => void = peers.assertValidPeerId;\n\n const { id } = input;\n try {\n validateId(id);\n } catch (err) {\n throw new EngramAccessInputError((err as Error).message);\n }\n\n const memoryDir = this.orchestrator.config.memoryDir;\n const now = new Date().toISOString();\n const existing = await peers.readPeer(memoryDir, id);\n\n const ALLOWED_KINDS = new Set([\"self\", \"human\", \"agent\", \"integration\"]);\n if (!existing) {\n // First write — require kind.\n const kind = input.kind ?? \"human\";\n if (!ALLOWED_KINDS.has(kind)) {\n throw new EngramAccessInputError(\n `peer kind must be one of ${[...ALLOWED_KINDS].join(\", \")}`,\n );\n }\n const newPeer: import(\"./peers/types.js\").Peer = {\n id,\n kind: kind as import(\"./peers/types.js\").PeerKind,\n displayName: input.displayName ?? id,\n createdAt: now,\n updatedAt: now,\n ...(typeof input.notes === \"string\" ? { notes: input.notes } : {}),\n };\n await peers.writePeer(memoryDir, newPeer);\n return { ok: true, created: true, peer: newPeer };\n }\n\n // Update — kind and createdAt are immutable.\n const updated: import(\"./peers/types.js\").Peer = {\n id: existing.id,\n kind: existing.kind,\n createdAt: existing.createdAt,\n updatedAt: now,\n displayName: input.displayName !== undefined ? input.displayName : existing.displayName,\n ...(input.notes !== undefined\n ? { notes: input.notes }\n : existing.notes !== undefined\n ? { notes: existing.notes }\n : {}),\n };\n await peers.writePeer(memoryDir, updated);\n return { ok: true, created: false, peer: updated };\n }\n\n /**\n * Delete a peer by removing `peers/{id}/identity.md`. If the file does not\n * exist the call is a no-op (idempotent). The peer directory itself\n * (`peers/{id}/`) is intentionally left in place — profile and interaction\n * log data are not destroyed.\n */\n async peerDelete(peerId: string): Promise<{ ok: true; deleted: boolean }> {\n const peers = await import(\"./peers/index.js\");\n const validateId: (id: unknown) => void = peers.assertValidPeerId;\n try {\n validateId(peerId);\n } catch (err) {\n throw new EngramAccessInputError((err as Error).message);\n }\n // Cursor M (PR #756 review): route through `peers.deletePeer` so\n // the unlink runs `assertPeerDirNotEscaped`, the peers-root\n // symlink check, and the parent-inode-stable / O_NOFOLLOW guards\n // shared with `readPeer`/`writePeer`. A manual `path.join` +\n // raw `fs.unlink` would let a symlinked `peers/<id>/` redirect\n // the delete to an arbitrary `identity.md` outside `memoryDir`.\n const deleted = await peers.deletePeer(this.orchestrator.config.memoryDir, peerId);\n return { ok: true, deleted };\n }\n\n /**\n * Destructively purge the entire peer directory for a given peerId —\n * `identity.md`, `profile.md`, `interactions.log.md`, and any other\n * files in `peers/{id}/`. Requires `confirm: \"yes\"` to prevent\n * accidental invocation.\n *\n * This is the DESTRUCTIVE counterpart to `peerDelete`, which only\n * removes `identity.md`. All companion files are permanently removed.\n *\n * Returns `{ ok: true, purged: true }` when the directory existed and\n * was removed; `{ ok: true, purged: false }` when the directory did\n * not exist (idempotent no-op).\n */\n async peerForget(\n peerId: string,\n opts: { confirm: string },\n ): Promise<{ ok: true; purged: boolean }> {\n const peers = await import(\"./peers/index.js\");\n const validateId: (id: unknown) => void = peers.assertValidPeerId;\n try {\n validateId(peerId);\n } catch (err) {\n throw new EngramAccessInputError((err as Error).message);\n }\n if (opts.confirm !== \"yes\") {\n throw new EngramAccessInputError(\n \"peerForget requires confirm: 'yes' to prevent accidental data loss\",\n );\n }\n const result = await peers.forgetPeer(this.orchestrator.config.memoryDir, peerId, {\n confirm: \"yes\",\n });\n return { ok: true, purged: result.purged };\n }\n\n /**\n * Get the evolving cognitive profile for a peer. Returns `{ found: false }`\n * when no profile file exists yet (profile is written by the async reasoner,\n * PR 2/5). The peer identity itself need not exist for a profile to exist,\n * but in practice the reasoner only writes profiles for registered peers.\n */\n async peerProfileGet(\n peerId: string,\n ): Promise<\n | { found: true; profile: import(\"./peers/types.js\").PeerProfile }\n | { found: false }\n > {\n const peers = await import(\"./peers/index.js\");\n const validateId: (id: unknown) => void = peers.assertValidPeerId;\n try {\n validateId(peerId);\n } catch (err) {\n throw new EngramAccessInputError((err as Error).message);\n }\n const profile = await peers.readPeerProfile(this.orchestrator.config.memoryDir, peerId);\n if (!profile) return { found: false };\n return { found: true, profile };\n }\n\n // ── Contradiction Review (issue #520) ──────────────────────────────────────\n\n get memoryDir(): string {\n return this.orchestrator.config.memoryDir;\n }\n\n /**\n * Resolve the storage directory for a given namespace. Used by the SSE\n * graph-event handler to subscribe to the correct per-namespace bus rather\n * than the global root (CLAUDE.md rule 42 — read/write paths must resolve\n * through the same namespace layer).\n *\n * `principal` must be the transport-bound request principal (from\n * `resolveRequestPrincipal`). When namespaces are enabled, an absent\n * principal causes `resolveReadableNamespace` to throw an auth error,\n * matching the behaviour of every other authenticated read path.\n *\n * Falls back to `this.memoryDir` when namespaces are disabled or the\n * namespace is absent, matching the behaviour of every other read path.\n */\n async getMemoryDirForNamespace(namespace?: string, principal?: string): Promise<string> {\n const resolved = this.resolveReadableNamespace(namespace, principal);\n const storage = await this.orchestrator.getStorage(resolved);\n return storage.dir;\n }\n\n async getReadableStorageForNamespace(namespace?: string, principal?: string): Promise<{\n namespace: string;\n storage: StorageManager;\n }> {\n const resolved = this.resolveReadableNamespace(namespace, principal);\n const storage = await this.orchestrator.getStorage(resolved);\n return { namespace: resolved, storage };\n }\n\n async getWritableStorageForNamespace(namespace?: string, principal?: string): Promise<{\n namespace: string;\n storage: StorageManager;\n }> {\n if (this.orchestrator.config.namespacesEnabled && !principal?.trim()) {\n throw new EngramAccessInputError(\n \"authentication required: namespaces are enabled and no principal was supplied\",\n );\n }\n const resolved = this.resolveWritableNamespace(namespace, undefined, principal);\n const storage = await this.orchestrator.getStorage(resolved);\n return { namespace: resolved, storage };\n }\n\n get storageRef(): StorageManager {\n return this.orchestrator.storage;\n }\n\n /**\n * Best-effort catalog write touch delegate (issue #1499 sweep). HTTP/MCP\n * surfaces resolve a per-namespace storage and write through it directly (e.g.\n * a contradiction merge), bypassing the extraction write path that owns\n * `markCatalogWrite`. They call this to record the write so a (possibly\n * dynamic) namespace's `lastWriteAt` stays accurate and QMD maintenance does\n * not miss it. Fire-and-forget and failure-tolerant on the orchestrator side.\n */\n recordCatalogWrite(namespace?: string, storageDir?: string): void {\n this.orchestrator.recordCatalogWrite(namespace, storageDir);\n }\n\n get configRef(): PluginConfig {\n return this.orchestrator.config;\n }\n\n get localLlmRef(): LocalLlmClient | null {\n return this.orchestrator.localLlm ?? null;\n }\n\n get fallbackLlmRef(): FallbackLlmClient | null {\n return this.orchestrator.fastGatewayLlm ?? null;\n }\n\n get embeddingLookupFactoryRef(): (storage: import(\"./storage.js\").StorageManager) => SemanticDedupLookup | undefined {\n return (storage) => {\n if (!this.orchestrator.config.embeddingFallbackEnabled) return undefined;\n return async (content: string, limit: number) => {\n try {\n return await this.orchestrator.semanticDedupLookup(content, limit, storage);\n } catch {\n return [];\n }\n };\n };\n }\n\n /**\n * Import a capsule archive into the orchestrator's memory directory.\n *\n * Delegates directly to the standalone {@link importCapsuleFn} function.\n * The `root` parameter defaults to the orchestrator's `memoryDir` when\n * omitted, so callers that only have access to the service do not need to\n * thread the config value through.\n *\n * `versioning` defaults to the orchestrator's page-versioning config so\n * `mode: \"overwrite\"` automatically snapshots prior content without the\n * caller having to construct the config object.\n */\n async capsuleImport(\n opts: Omit<ImportCapsuleOptions, \"root\" | \"memoryDir\"> & {\n root?: string;\n memoryDir?: string;\n namespace?: string;\n principal?: string;\n },\n ): Promise<ImportCapsuleResult> {\n const { namespace, principal, root: explicitRoot, memoryDir: explicitMemoryDir, ...importOptions } = opts;\n const resolvedNamespace = this.resolveWritableNamespace(namespace, undefined, principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const root = explicitRoot ?? storage.dir;\n const memoryDir = explicitMemoryDir ?? this.orchestrator.config.memoryDir;\n const versioning = importOptions.versioning ?? {\n enabled: this.orchestrator.config.versioningEnabled,\n maxVersionsPerPage: this.orchestrator.config.versioningMaxPerPage,\n sidecarDir: this.orchestrator.config.versioningSidecarDir,\n };\n await this.validateCapsuleImportArchivePath(importOptions.archivePath);\n try {\n return await importCapsuleFn({ ...importOptions, root, memoryDir, versioning });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (this.isCapsuleImportArchiveInputError(err, message)) {\n throw new EngramAccessInputError(`capsule import failed: ${message}`);\n }\n throw err;\n }\n }\n\n private async validateCapsuleImportArchivePath(archivePath: string): Promise<void> {\n let archiveStat;\n try {\n archiveStat = await stat(archivePath);\n } catch (err) {\n if (!this.isCapsuleImportPathInputFsError(err)) throw err;\n const message = err instanceof Error ? err.message : String(err);\n throw new EngramAccessInputError(`capsule import failed: archive is not readable: ${message}`);\n }\n if (!archiveStat.isFile()) {\n throw new EngramAccessInputError(\"capsule import failed: archivePath must point to a file\");\n }\n try {\n await nodeFs.access(archivePath, fsConstants.R_OK);\n } catch (err) {\n if (!this.isCapsuleImportPathInputFsError(err)) throw err;\n const message = err instanceof Error ? err.message : String(err);\n throw new EngramAccessInputError(`capsule import failed: archive is not readable: ${message}`);\n }\n }\n\n private isCapsuleImportPathInputFsError(err: unknown): boolean {\n const code = typeof err === \"object\" && err !== null && \"code\" in err\n ? (err as { code?: unknown }).code\n : undefined;\n return (\n code === \"ENOENT\" ||\n code === \"ENOTDIR\" ||\n code === \"EACCES\" ||\n code === \"EPERM\" ||\n code === \"ELOOP\"\n );\n }\n\n private isCapsuleImportArchiveInputError(err: unknown, message: string): boolean {\n if (err instanceof ZodError) return true;\n const code = typeof err === \"object\" && err !== null && \"code\" in err\n ? (err as { code?: unknown }).code\n : undefined;\n if (typeof code === \"string\" && code.startsWith(\"Z_\")) return true;\n return (\n message.startsWith(\"importCapsule: archive\") ||\n message.startsWith(\"importCapsule: bundle\") ||\n message.startsWith(\"importCapsule: manifest\") ||\n message.startsWith(\"importCapsule: record\") ||\n /incorrect header check|invalid stored block lengths|not in gzip format|unexpected end of file/i.test(message)\n );\n }\n\n /**\n * Export a capsule archive from the orchestrator's memory directory.\n *\n * HTTP and future MCP surfaces use this rather than calling the transfer\n * helper directly so namespace ACL checks stay consistent with the archive\n * write side effect. The exporter still owns archive construction and\n * validation.\n */\n async capsuleExport(\n opts: Omit<ExportCapsuleOptions, \"root\" | \"memoryDir\"> & {\n root?: string;\n memoryDir?: string;\n namespace?: string;\n principal?: string;\n },\n ): Promise<ExportCapsuleResult> {\n const { namespace, principal, root: explicitRoot, memoryDir: explicitMemoryDir, ...exportOptions } = opts;\n const resolvedNamespace = this.resolveWritableNamespace(namespace, undefined, principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const root = explicitRoot ?? storage.dir;\n const memoryDir = explicitMemoryDir ?? this.orchestrator.config.memoryDir;\n const pluginVersion = exportOptions.pluginVersion ?? await getPackageVersion();\n return exportCapsuleFn({\n ...exportOptions,\n pluginVersion,\n root,\n memoryDir: exportOptions.encrypt === true ? memoryDir : undefined,\n });\n }\n\n /**\n * List capsule archives in the namespace-scoped capsule store.\n *\n * MCP uses this access-layer method instead of reading arbitrary paths so\n * capsule discovery remains bound to the same namespace ACLs as export and\n * import.\n */\n async capsuleList(options?: {\n namespace?: string;\n principal?: string;\n }): Promise<EngramAccessCapsuleListResponse> {\n const resolvedNamespace = this.resolveReadableNamespace(options?.namespace, options?.principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const capsulesDir = defaultCapsulesDir(storage.dir);\n let dirEntries: import(\"node:fs\").Dirent[];\n try {\n const capsulesDirStat = await nodeFs.lstat(capsulesDir);\n if (capsulesDirStat.isSymbolicLink()) {\n throw new EngramAccessInputError(\"capsule list failed: capsule store directory must not be a symlink\");\n }\n if (!capsulesDirStat.isDirectory()) {\n throw new EngramAccessInputError(\"capsule list failed: capsule store path must be a directory\");\n }\n dirEntries = await nodeFs.readdir(capsulesDir, { withFileTypes: true });\n } catch (err) {\n const code = typeof err === \"object\" && err !== null && \"code\" in err\n ? (err as { code?: unknown }).code\n : undefined;\n if (code === \"ENOENT\") {\n return { namespace: resolvedNamespace, capsulesDir, capsules: [] };\n }\n throw err;\n }\n\n const archiveNames = dirEntries\n .filter(\n (entry) =>\n entry.isFile() &&\n (entry.name.endsWith(\".capsule.json.gz\") ||\n entry.name.endsWith(\".capsule.json.gz.enc\")),\n )\n .map((entry) => entry.name)\n .sort();\n\n const capsules: CapsuleListEntry[] = [];\n for (const archiveName of archiveNames) {\n const archivePath = nodePath.join(capsulesDir, archiveName);\n const id = archiveName\n .replace(/\\.capsule\\.json\\.gz\\.enc$/, \"\")\n .replace(/\\.capsule\\.json\\.gz$/, \"\");\n const manifestPath = nodePath.join(capsulesDir, `${id}.manifest.json`);\n\n let createdAt: string | null = null;\n let pluginVersion: string | null = null;\n let fileCount: number | null = null;\n let description: string | null = null;\n let manifestPathOrNull: string | null = manifestPath;\n\n try {\n const manifestStat = await nodeFs.lstat(manifestPath);\n if (manifestStat.isSymbolicLink() || !manifestStat.isFile()) {\n capsules.push({\n id,\n archivePath,\n manifestPath: manifestPathOrNull,\n createdAt,\n pluginVersion,\n fileCount,\n description,\n });\n continue;\n }\n const raw = await nodeFs.readFile(manifestPath, \"utf-8\");\n const sidecar = JSON.parse(raw) as Record<string, unknown>;\n createdAt = typeof sidecar.createdAt === \"string\" ? sidecar.createdAt : null;\n pluginVersion = typeof sidecar.pluginVersion === \"string\" ? sidecar.pluginVersion : null;\n fileCount = Array.isArray(sidecar.files) ? sidecar.files.length : null;\n const capsule = sidecar.capsule as Record<string, unknown> | undefined;\n description = capsule && typeof capsule.description === \"string\"\n ? capsule.description\n : null;\n } catch (err) {\n const code = typeof err === \"object\" && err !== null && \"code\" in err\n ? (err as { code?: unknown }).code\n : undefined;\n if (code === \"ENOENT\") {\n manifestPathOrNull = null;\n }\n }\n\n capsules.push({\n id,\n archivePath,\n manifestPath: manifestPathOrNull,\n createdAt,\n pluginVersion,\n fileCount,\n description,\n });\n }\n\n return { namespace: resolvedNamespace, capsulesDir, capsules };\n }\n\n async offlineSyncSnapshot(\n options: EngramAccessOfflineSyncSnapshotRequest & { signal?: AbortSignal } = {},\n ): Promise<EngramAccessOfflineSyncSnapshotResponse> {\n const resolvedNamespace = this.resolveReadableNamespace(options.namespace, options.principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const storageHash = createHash(\"sha256\").update(storage.dir).digest(\"hex\").slice(0, 16);\n const snapshotBuilder = options.includeContent === false && options.baseFiles && options.baseFiles.length > 0\n ? buildOfflineSyncSnapshotFromBase\n : buildOfflineSyncSnapshot;\n const snapshot = await snapshotBuilder({\n root: storage.dir,\n sourceId: `remnic:${resolvedNamespace}:${storageHash}`,\n ...(options.baseFiles && options.baseFiles.length > 0 ? { baseFiles: options.baseFiles } : {}),\n includeContent: options.includeContent !== false,\n includeTranscripts: options.includeTranscripts !== false,\n readFile: async ({ filePath }) => storage.readOfflineSyncFile(filePath),\n readFileDigest: async ({ filePath }) => storage.digestOfflineSyncFile(filePath),\n signal: options.signal,\n });\n return {\n namespace: resolvedNamespace,\n ...snapshot,\n };\n }\n\n async offlineSyncSnapshotStream(\n options: Omit<EngramAccessOfflineSyncSnapshotRequest, \"baseCapturedAt\" | \"baseFiles\"> & { signal?: AbortSignal } = {},\n ): Promise<EngramAccessOfflineSyncSnapshotStreamResponse> {\n const resolvedNamespace = this.resolveReadableNamespace(options.namespace, options.principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const storageHash = createHash(\"sha256\").update(storage.dir).digest(\"hex\").slice(0, 16);\n return {\n namespace: resolvedNamespace,\n format: OFFLINE_SYNC_SNAPSHOT_FORMAT,\n schemaVersion: 1,\n createdAt: new Date().toISOString(),\n sourceId: `remnic:${resolvedNamespace}:${storageHash}`,\n includeTranscripts: options.includeTranscripts !== false,\n files: iterateOfflineSyncSnapshotFileRecords({\n root: storage.dir,\n includeContent: options.includeContent === true,\n includeTranscripts: options.includeTranscripts !== false,\n readFile: async ({ filePath }) => storage.readOfflineSyncFile(filePath),\n readFileDigest: async ({ filePath }) => storage.digestOfflineSyncFile(filePath),\n signal: options.signal,\n }),\n };\n }\n\n async offlineSyncFiles(\n options: EngramAccessOfflineSyncFilesRequest,\n ): Promise<EngramAccessOfflineSyncFilesResponse> {\n const resolvedNamespace = this.resolveReadableNamespace(options.namespace, options.principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const storageHash = createHash(\"sha256\").update(storage.dir).digest(\"hex\").slice(0, 16);\n try {\n const snapshot = await buildOfflineSyncSnapshotForPaths({\n root: storage.dir,\n sourceId: `remnic:${resolvedNamespace}:${storageHash}`,\n paths: options.paths,\n includeContent: true,\n includeTranscripts: options.includeTranscripts !== false,\n readFile: async ({ filePath }) => storage.readOfflineSyncFile(filePath),\n });\n return {\n namespace: resolvedNamespace,\n ...snapshot,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (\n message.startsWith(\"paths[]:\") ||\n message.startsWith(\"buildOfflineSyncSnapshotForPaths: record path \") ||\n message.startsWith(\"offline sync snapshot path is excluded:\")\n ) {\n throw new EngramAccessInputError(message);\n }\n throw error;\n }\n }\n\n async offlineSyncFileContent(\n options: EngramAccessOfflineSyncFileContentRequest,\n ): Promise<EngramAccessOfflineSyncFileContentResponse> {\n const resolvedNamespace = this.resolveReadableNamespace(options.namespace, options.principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n try {\n const chunk = await readOfflineSyncFileContentChunk({\n root: storage.dir,\n path: options.path,\n offset: options.offset,\n length: options.length,\n includeTranscripts: options.includeTranscripts !== false,\n readFile: async ({ filePath }) => storage.readOfflineSyncFile(filePath),\n });\n return {\n namespace: resolvedNamespace,\n ...chunk,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (\n message.startsWith(\"path:\") ||\n message.startsWith(\"offset \") ||\n message.startsWith(\"offset must \") ||\n message.startsWith(\"length \") ||\n message.startsWith(\"offline sync file content \")\n ) {\n throw new EngramAccessInputError(message);\n }\n throw error;\n }\n }\n\n async offlineSyncApplyFileContent(\n options: EngramAccessOfflineSyncApplyFileContentRequest,\n ): Promise<EngramAccessOfflineSyncApplyFileContentResponse> {\n const resolvedNamespace = this.resolveWritableNamespace(\n options.namespace,\n undefined,\n options.principal,\n );\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n try {\n const result = await applyOfflineSyncFileContentChunk({\n root: storage.dir,\n sourceId: options.sourceId,\n path: options.path,\n sha256: options.sha256,\n bytes: options.bytes,\n mtimeMs: options.mtimeMs,\n offset: options.offset,\n baseSha256: options.baseSha256,\n content: options.content,\n includeTranscripts: options.includeTranscripts !== false,\n readFile: async ({ filePath }) => storage.readOfflineSyncFile(filePath),\n readFileDigest: async ({ filePath }) => storage.digestOfflineSyncFile(filePath),\n writeFile: async ({ filePath, content }) => storage.writeOfflineSyncFile(filePath, content),\n writeStagingFile: async ({ filePath, content }) => storage.writeOfflineSyncStagingFile(filePath, content),\n writeFileChunks: async ({ filePath, chunks }) => storage.writeOfflineSyncFileChunks(filePath, chunks),\n });\n return {\n namespace: resolvedNamespace,\n ...result,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (\n message.startsWith(\"offline sync\") ||\n message.startsWith(\"path:\") ||\n message.startsWith(\"sourceId must \") ||\n message.startsWith(\"sha256 must \") ||\n message.startsWith(\"baseSha256 must \") ||\n message.startsWith(\"bytes must \") ||\n message.startsWith(\"mtimeMs must \") ||\n message.startsWith(\"offset must \") ||\n message.startsWith(\"content chunk \") ||\n message === \"content must be a Buffer\"\n ) {\n throw new EngramAccessInputError(message);\n }\n throw error;\n }\n }\n\n async offlineSyncApply(\n options: EngramAccessOfflineSyncApplyRequest,\n ): Promise<EngramAccessOfflineSyncApplyResponse> {\n const resolvedNamespace = this.resolveWritableNamespace(\n options.namespace,\n undefined,\n options.principal,\n );\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n try {\n const result = await applyOfflineSyncChangeset({\n root: storage.dir,\n changeset: options.changeset,\n returnCurrentFiles: options.returnCurrentFiles,\n readFile: async ({ filePath }) => storage.readOfflineSyncFile(filePath),\n readFileDigest: async ({ filePath }) => storage.digestOfflineSyncFile(filePath),\n writeFile: async ({ filePath, content }) => storage.writeOfflineSyncFile(filePath, content),\n deleteFile: async ({ filePath }) => storage.deleteOfflineSyncFile(filePath),\n });\n return {\n namespace: resolvedNamespace,\n ...result,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (message.startsWith(\"offline sync\")) {\n throw new EngramAccessInputError(message);\n }\n throw error;\n }\n }\n\n // ── Dreams pipeline telemetry surfaces (issue #678 PR 3+4) ──────────────\n\n /**\n * Return per-phase Dreams telemetry for the last N hours (default 24).\n */\n async dreamsStatus(options?: {\n windowHours?: number;\n namespace?: string;\n principal?: string;\n }): Promise<import(\"./types.js\").DreamsStatusResult> {\n const { getDreamsStatus, normalizeDreamsStatusWindowHours } = await import(\"./maintenance/dreams-ledger.js\");\n let windowHours: number;\n try {\n windowHours = normalizeDreamsStatusWindowHours(options?.windowHours);\n } catch (error) {\n throw new EngramAccessInputError(error instanceof Error ? error.message : String(error));\n }\n const resolvedNamespace = this.resolveReadableNamespace(options?.namespace, options?.principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n return getDreamsStatus(storage.dir, windowHours);\n }\n\n /**\n * Manually invoke a single Dreams phase pass (PR 4/4).\n *\n * Deep-sleep delegates to memory governance (shadow → dry-run, apply → live).\n * Light-sleep and REM scan the observation ledger and memory corpus\n * respectively, returning the same telemetry shape as a scheduled run.\n */\n async dreamsRun(options: {\n phase: import(\"./types.js\").DreamsPhase;\n dryRun?: boolean;\n namespace?: string;\n authenticatedPrincipal?: string;\n }): Promise<import(\"./types.js\").DreamsRunResult> {\n const { runDreamsPhase } = await import(\"./maintenance/dreams-ledger.js\");\n const validPhases = [\"lightSleep\", \"rem\", \"deepSleep\"];\n if (!validPhases.includes(options.phase)) {\n throw new EngramAccessInputError(\n `Invalid phase: ${String(options.phase)}. Must be one of: ${validPhases.join(\", \")}`,\n );\n }\n const deepSleep = this.orchestrator.config.dreamsPhases.deepSleep;\n if (\n options.phase === \"deepSleep\" &&\n deepSleep.enabled === false &&\n deepSleep.enabledExplicitlySet === true\n ) {\n throw new EngramAccessInputError(\n \"memory governance is disabled by dreams.phases.deepSleep.enabled=false\",\n );\n }\n const dryRun = options.dryRun === true;\n const resolvedNamespace = this.resolveWritableNamespace(\n options.namespace,\n undefined,\n options.authenticatedPrincipal,\n );\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const memoryDir = storage.dir;\n const phaseRunner = dryRun || options.phase === \"deepSleep\"\n ? undefined\n : async (_opts: { memoryDir: string; phase: \"lightSleep\" | \"rem\" }) => {\n if (_opts.phase === \"lightSleep\") {\n const result = await this.orchestrator.runLifecyclePolicyNow(storage);\n return {\n itemsProcessed: result.memoriesAssessed,\n notes: `scored ${result.memoriesAssessed} memories`,\n };\n }\n const result = await this.orchestrator.runSemanticConsolidationNow({\n dryRun: false,\n storage,\n });\n const itemsProcessed = result.clusters.reduce(\n (sum, cluster) => sum + cluster.memories.length,\n 0,\n );\n return {\n itemsProcessed,\n notes: `REM consolidation found ${result.clustersFound} clusters`,\n };\n };\n const governanceRunner = options.phase === \"deepSleep\"\n ? async (_opts: { memoryDir: string; dryRun: boolean }) => {\n return this.orchestrator.runDeepSleepGovernanceNow({\n storage,\n dryRun: _opts.dryRun,\n });\n }\n : undefined;\n const result = await runDreamsPhase(\n { memoryDir, phase: options.phase, dryRun },\n governanceRunner,\n phaseRunner,\n );\n return {\n phase: result.phase,\n dryRun: result.dryRun,\n durationMs: result.durationMs,\n itemsProcessed: result.itemsProcessed,\n notes: result.notes,\n };\n }\n\n // ---------------------------------------------------------------------------\n // Wearables (Limitless / Bee / Omi transcript ingestion)\n //\n // Thin delegations to the orchestrator-owned WearablesService — the\n // same instance behind the CLI, so HTTP/MCP callers observe identical\n // behavior and validation (renderer-sharing rule).\n // ---------------------------------------------------------------------------\n\n async wearablesStatus(): Promise<\n Awaited<ReturnType<WearablesService[\"status\"]>>\n > {\n return this.orchestrator.getWearablesService().status();\n }\n\n async wearablesSync(request: {\n source?: string;\n date?: string;\n days?: number;\n forceMemories?: boolean;\n }): Promise<Awaited<ReturnType<WearablesService[\"sync\"]>>> {\n return this.orchestrator.getWearablesService().sync({\n source: request.source,\n date: request.date,\n days: request.days,\n forceMemories: request.forceMemories,\n });\n }\n\n async wearablesTranscriptDay(request: {\n date: string;\n source?: string;\n }): Promise<Awaited<ReturnType<WearablesService[\"dayTranscript\"]>>> {\n return this.orchestrator\n .getWearablesService()\n .dayTranscript(request.date, request.source);\n }\n\n async wearablesTranscriptSearch(request: {\n query: string;\n source?: string;\n from?: string;\n to?: string;\n limit?: number;\n }): Promise<Awaited<ReturnType<WearablesService[\"searchTranscripts\"]>>> {\n return this.orchestrator.getWearablesService().searchTranscripts(request.query, {\n source: request.source,\n from: request.from,\n to: request.to,\n limit: request.limit,\n });\n }\n\n async wearablesTranscriptMemories(request: {\n source?: string;\n date?: string;\n limit?: number;\n }): Promise<Awaited<ReturnType<WearablesService[\"transcriptMemories\"]>>> {\n return this.orchestrator.getWearablesService().transcriptMemories({\n source: request.source,\n date: request.date,\n limit: request.limit,\n });\n }\n}\n","/**\n * Cluster causal trajectories into candidate procedure memories (issue #519).\n */\n\nimport type { PluginConfig } from \"../types.js\";\nimport type { StorageManager } from \"../storage.js\";\nimport type { CausalTrajectoryRecord } from \"../causal-trajectory.js\";\nimport { createHash } from \"node:crypto\";\nimport { mkdir, rm, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n readCausalTrajectoryRecords,\n filterTrajectoriesByLookbackDays,\n} from \"../causal-trajectory.js\";\nimport { buildProcedurePersistBody, normalizeProcedureSteps, type ProcedureStep } from \"./procedure-types.js\";\nimport { clusterByKey } from \"./reinforcement-core.js\";\nimport { log } from \"../logger.js\";\n\n/** Must match truncation on `procedure_cluster` structured attribute (dedupe + storage). */\nconst PROCEDURE_CLUSTER_ATTR_MAX = 500;\nconst PROCEDURE_CLUSTER_LOCK_STALE_MS = 120_000;\nconst PROCEDURE_CLUSTER_LOCK_TIMEOUT_MS = 30_000;\n\nconst inProcessClusterWriteLocks = new Map<string, Promise<void>>();\n\nexport interface ProcedureMiningResult {\n clustersProcessed: number;\n proceduresWritten: number;\n skippedReason?: string;\n}\n\nfunction clusterKey(record: CausalTrajectoryRecord): string {\n const goal = record.goal.trim().toLowerCase().replace(/\\s+/g, \" \").slice(0, 120);\n const refs = [...(record.entityRefs ?? [])].map((r) => r.trim().toLowerCase()).sort();\n return `${goal}|${refs.join(\",\")}`;\n}\n\nfunction clusterKeyHash(cluster: string): string {\n return createHash(\"sha256\").update(cluster).digest(\"hex\");\n}\n\nfunction isErrnoCode(error: unknown, code: string): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: unknown }).code === code\n );\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function acquireClusterWriteLock(memoryDir: string, clusterHash: string): Promise<() => Promise<void>> {\n const lockRoot = path.join(path.resolve(memoryDir), \"state\", \"procedure-miner-locks\");\n const lockDir = path.join(lockRoot, `${clusterHash}.lock`);\n await mkdir(lockRoot, { recursive: true });\n\n const startedAt = Date.now();\n let attempts = 0;\n while (true) {\n try {\n await mkdir(lockDir);\n return async () => {\n await rm(lockDir, { recursive: true, force: true });\n };\n } catch (err) {\n if (!isErrnoCode(err, \"EEXIST\")) throw err;\n }\n\n try {\n const info = await stat(lockDir);\n if (Date.now() - info.mtimeMs > PROCEDURE_CLUSTER_LOCK_STALE_MS) {\n await rm(lockDir, { recursive: true, force: true });\n continue;\n }\n } catch (err) {\n if (isErrnoCode(err, \"ENOENT\")) continue;\n throw err;\n }\n\n if (Date.now() - startedAt > PROCEDURE_CLUSTER_LOCK_TIMEOUT_MS) {\n throw new Error(`Timed out waiting for procedure cluster write lock ${clusterHash}`);\n }\n\n attempts += 1;\n await sleep(Math.min(250, 25 * attempts));\n }\n}\n\nasync function withClusterWriteLock<T>(\n memoryDir: string,\n clusterHash: string,\n fn: () => Promise<T>,\n): Promise<T> {\n const inProcessKey = `${path.resolve(memoryDir)}:${clusterHash}`;\n const previous = inProcessClusterWriteLocks.get(inProcessKey) ?? Promise.resolve();\n let releaseInProcess!: () => void;\n const current = previous.catch(() => undefined).then(\n () =>\n new Promise<void>((resolve) => {\n releaseInProcess = resolve;\n }),\n );\n inProcessClusterWriteLocks.set(inProcessKey, current);\n\n await previous.catch(() => undefined);\n let releaseDisk: (() => Promise<void>) | null = null;\n try {\n releaseDisk = await acquireClusterWriteLock(memoryDir, clusterHash);\n return await fn();\n } finally {\n try {\n if (releaseDisk) await releaseDisk();\n } finally {\n releaseInProcess();\n if (inProcessClusterWriteLocks.get(inProcessKey) === current) {\n inProcessClusterWriteLocks.delete(inProcessKey);\n }\n }\n }\n}\n\nfunction successRate(group: CausalTrajectoryRecord[]): number {\n if (group.length === 0) return 0;\n const ok = group.filter((g) => g.outcomeKind === \"success\" || g.outcomeKind === \"partial\").length;\n return ok / group.length;\n}\n\n/** Derive ordered pseudo-steps from trajectory text (v1 heuristic; no tool-call array on records). */\nfunction pseudoStepsFromCluster(group: CausalTrajectoryRecord[]): ProcedureStep[] {\n const sentences: string[] = [];\n const pushUnique = (raw: string) => {\n const t = raw.trim();\n if (t.length < 8) return;\n if (!sentences.includes(t)) sentences.push(t);\n };\n for (const g of group) {\n const parts = [g.actionSummary, g.observationSummary, g.outcomeSummary]\n .join(\" \")\n .split(/[.!?]\\s+|;|\\n+/)\n .map((s) => s.trim())\n .filter((s) => s.length > 12);\n for (const p of parts) pushUnique(p);\n if (sentences.length >= 5) break;\n }\n if (sentences.length < 2 && group[0]) {\n pushUnique(`${group[0].goal.trim()} — confirm prerequisites and context.`);\n pushUnique(\"Execute the planned actions, then record the outcome.\");\n }\n return sentences.slice(0, 6).map((intent, i) => ({\n order: i + 1,\n intent,\n }));\n}\n\nasync function hasExistingClusterWrite(\n storage: StorageManager,\n cluster: string,\n): Promise<boolean> {\n const clusterKey = cluster.slice(0, PROCEDURE_CLUSTER_ATTR_MAX);\n const clusterHash = clusterKeyHash(cluster);\n const memories = await storage.readAllMemories();\n for (const m of memories) {\n if (m.frontmatter.category !== \"procedure\") continue;\n const h = m.frontmatter.structuredAttributes?.procedure_cluster_hash;\n if (typeof h === \"string\") {\n if (h === clusterHash) return true;\n continue;\n }\n const c = m.frontmatter.structuredAttributes?.procedure_cluster;\n if (c === clusterKey) return true;\n }\n return false;\n}\n\n/**\n * Mine recurring successful trajectories into `procedure` memories (pending_review\n * by default; active when auto-promotion thresholds are met).\n */\nexport async function runProcedureMining(options: {\n memoryDir: string;\n storage: StorageManager;\n config: PluginConfig;\n}): Promise<ProcedureMiningResult> {\n const cfg = options.config.procedural;\n if (!cfg?.enabled) {\n return { clustersProcessed: 0, proceduresWritten: 0, skippedReason: \"procedural_disabled\" };\n }\n if (cfg.minOccurrences <= 0) {\n return { clustersProcessed: 0, proceduresWritten: 0, skippedReason: \"minOccurrences_zero\" };\n }\n\n const trajectoryDir =\n typeof options.config.causalTrajectoryStoreDir === \"string\" &&\n options.config.causalTrajectoryStoreDir.trim().length > 0\n ? options.config.causalTrajectoryStoreDir.trim()\n : undefined;\n const { trajectories } = await readCausalTrajectoryRecords({\n memoryDir: options.memoryDir,\n causalTrajectoryStoreDir: trajectoryDir,\n });\n const recent = filterTrajectoriesByLookbackDays(trajectories, cfg.lookbackDays);\n\n const clusters = clusterByKey(recent, clusterKey);\n\n let clustersProcessed = 0;\n let proceduresWritten = 0;\n\n for (const [key, group] of clusters) {\n if (group.length < cfg.minOccurrences) continue;\n const rate = successRate(group);\n if (rate < cfg.successFloor) continue;\n\n clustersProcessed += 1;\n\n const steps = normalizeProcedureSteps(pseudoStepsFromCluster(group));\n if (steps.length < 2) continue;\n\n const title = `When you work on goals like: ${group[0].goal.trim().slice(0, 140)}`;\n const body = buildProcedurePersistBody(title, steps);\n const clusterHash = clusterKeyHash(key);\n\n const promote =\n cfg.autoPromoteEnabled === true && group.length >= cfg.autoPromoteOccurrences && rate >= cfg.successFloor;\n\n const wrote = await withClusterWriteLock(options.memoryDir, clusterHash, async () => {\n if (await hasExistingClusterWrite(options.storage, key)) {\n log.debug(`procedure-miner: skip duplicate cluster key=${key.slice(0, 40)}…`);\n return false;\n }\n\n await options.storage.writeMemory(\"procedure\", body, {\n source: \"procedure-miner\",\n status: promote ? \"active\" : \"pending_review\",\n tags: [\"procedure-miner\", \"causal-trajectory\"],\n structuredAttributes: {\n procedure_cluster: key.slice(0, PROCEDURE_CLUSTER_ATTR_MAX),\n procedure_cluster_hash: clusterHash,\n trajectory_ids: group\n .map((g) => g.trajectoryId)\n .join(\",\")\n .slice(0, 1900),\n trajectory_count: String(group.length),\n success_rate: rate.toFixed(4),\n },\n });\n return true;\n });\n if (wrote) proceduresWritten += 1;\n }\n\n return { clustersProcessed, proceduresWritten };\n}\n","/**\n * Procedural memory stats surface (issue #567 PR 5/5).\n *\n * Pure helper that tallies procedure memories by status and summarizes the\n * current `procedural.*` config so operators (and the dashboard) can see,\n * in one call, how procedural memory is behaving in a namespace.\n *\n * Consumed by:\n * - CLI `remnic procedural stats`\n * - HTTP `GET /engram/v1/procedural/stats`\n * - MCP `remnic.procedural_stats` (+ `engram.procedural_stats` alias)\n */\nimport type { MemoryFile, MemoryStatus, PluginConfig } from \"../types.js\";\nimport type { StorageManager } from \"../storage.js\";\n\nexport interface ProcedureStatusCounts {\n total: number;\n active: number;\n pending_review: number;\n rejected: number;\n quarantined: number;\n superseded: number;\n archived: number;\n /** Any status the enum doesn't yet cover. */\n other: number;\n}\n\nexport interface ProcedureStatsConfigSnapshot {\n enabled: boolean;\n minOccurrences: number;\n successFloor: number;\n autoPromoteOccurrences: number;\n autoPromoteEnabled: boolean;\n lookbackDays: number;\n recallMaxProcedures: number;\n}\n\nexport interface ProcedureStatsRecent {\n /** ISO 8601 timestamp of the most recent procedure write, or null. */\n lastWriteAt: string | null;\n /** Count of procedure files with `created` (or `updated`) in the last 7 days. */\n writesLast7Days: number;\n /** Count of procedures whose `source` is the procedure miner. */\n minerSourced: number;\n}\n\nexport interface ProcedureStatsReport {\n schemaVersion: 1;\n generatedAt: string;\n counts: ProcedureStatusCounts;\n recent: ProcedureStatsRecent;\n config: ProcedureStatsConfigSnapshot;\n}\n\nfunction snapshotConfig(config: PluginConfig): ProcedureStatsConfigSnapshot {\n const p = config.procedural;\n return {\n enabled: p?.enabled === true,\n minOccurrences: typeof p?.minOccurrences === \"number\" ? p.minOccurrences : 0,\n successFloor: typeof p?.successFloor === \"number\" ? p.successFloor : 0,\n autoPromoteOccurrences:\n typeof p?.autoPromoteOccurrences === \"number\"\n ? p.autoPromoteOccurrences\n : 0,\n autoPromoteEnabled: p?.autoPromoteEnabled === true,\n lookbackDays: typeof p?.lookbackDays === \"number\" ? p.lookbackDays : 0,\n recallMaxProcedures:\n typeof p?.recallMaxProcedures === \"number\" ? p.recallMaxProcedures : 0,\n };\n}\n\nfunction tsMs(value: unknown): number | null {\n if (typeof value !== \"string\") return null;\n const ms = Date.parse(value);\n return Number.isFinite(ms) ? ms : null;\n}\n\n/**\n * Read all memories from storage and tally procedures by status + recency.\n * `nowMs` is injectable so tests can pin the \"last 7 days\" window.\n */\nexport async function computeProcedureStats(options: {\n storage: StorageManager;\n config: PluginConfig;\n nowMs?: number;\n}): Promise<ProcedureStatsReport> {\n const { storage, config } = options;\n const nowMs = options.nowMs ?? Date.now();\n const sevenDaysMs = 7 * 24 * 60 * 60 * 1000;\n\n const counts: ProcedureStatusCounts = {\n total: 0,\n active: 0,\n pending_review: 0,\n rejected: 0,\n quarantined: 0,\n superseded: 0,\n archived: 0,\n other: 0,\n };\n\n let lastWriteMs: number | null = null;\n let writesLast7Days = 0;\n let minerSourced = 0;\n\n const known: MemoryStatus[] = [\n \"active\",\n \"pending_review\",\n \"rejected\",\n \"quarantined\",\n \"superseded\",\n \"archived\",\n ];\n\n // Iterate both live and archived memories so the counts surface matches\n // what operators expect when procedures have been archived via\n // `archiveMemory` (Codex P2 on #611). `readAllMemories` alone skips\n // `archive/`, which would otherwise underreport `counts.archived` and\n // `counts.total`.\n const seen = new Set<string>();\n const live = await storage.readAllMemories();\n const archived = await storage.readArchivedMemories();\n const pool: MemoryFile[] = [...live, ...archived];\n for (const m of pool) {\n if (m.frontmatter.category !== \"procedure\") continue;\n // Dedupe by id so a procedure appearing in both live + archive (mid-\n // archive race) isn't counted twice.\n if (seen.has(m.frontmatter.id)) continue;\n seen.add(m.frontmatter.id);\n counts.total += 1;\n const status = m.frontmatter.status ?? \"active\";\n if ((known as string[]).includes(status)) {\n // Safe index: the status enum values are the counts keys.\n (counts as unknown as Record<string, number>)[status] += 1;\n } else {\n counts.other += 1;\n }\n\n // Recency semantics (Codex P2 on #611): use the latest of `updated` and\n // `created`, not a fallback chain, so recently-edited procedures are\n // reflected in `lastWriteAt` and `writesLast7Days`. Missing timestamps\n // skip the row.\n const createdMs = tsMs(m.frontmatter.created);\n const updatedMs = tsMs(m.frontmatter.updated);\n const latestMs =\n createdMs !== null && updatedMs !== null\n ? Math.max(createdMs, updatedMs)\n : (updatedMs ?? createdMs);\n if (latestMs !== null) {\n if (lastWriteMs === null || latestMs > lastWriteMs) {\n lastWriteMs = latestMs;\n }\n // Exclusive upper bound per CLAUDE.md rule 35 — use half-open window.\n if (latestMs >= nowMs - sevenDaysMs && latestMs < nowMs) {\n writesLast7Days += 1;\n }\n }\n\n if (m.frontmatter.source === \"procedure-miner\") {\n minerSourced += 1;\n }\n }\n\n return {\n schemaVersion: 1,\n generatedAt: new Date(nowMs).toISOString(),\n counts,\n recent: {\n lastWriteAt: lastWriteMs !== null ? new Date(lastWriteMs).toISOString() : null,\n writesLast7Days,\n minerSourced,\n },\n config: snapshotConfig(config),\n };\n}\n\n/**\n * Render `ProcedureStatsReport` as a human-friendly plain-text block for CLI\n * operators. Keep it deterministic — no colors, no ANSI. Used by `--format text`.\n */\nexport function formatProcedureStatsText(report: ProcedureStatsReport): string {\n const { counts, recent, config } = report;\n const lines: string[] = [];\n lines.push(`Procedural memory stats (schema v${report.schemaVersion})`);\n lines.push(` generated: ${report.generatedAt}`);\n lines.push(\"\");\n lines.push(` config:`);\n lines.push(` enabled: ${config.enabled}`);\n lines.push(` minOccurrences: ${config.minOccurrences}`);\n lines.push(` successFloor: ${config.successFloor}`);\n lines.push(` autoPromoteOccurrences: ${config.autoPromoteOccurrences}`);\n lines.push(` autoPromoteEnabled: ${config.autoPromoteEnabled}`);\n lines.push(` lookbackDays: ${config.lookbackDays}`);\n lines.push(` recallMaxProcedures: ${config.recallMaxProcedures}`);\n lines.push(\"\");\n lines.push(` counts:`);\n lines.push(` total: ${counts.total}`);\n lines.push(` active: ${counts.active}`);\n lines.push(` pending_review: ${counts.pending_review}`);\n lines.push(` rejected: ${counts.rejected}`);\n lines.push(` quarantined: ${counts.quarantined}`);\n lines.push(` superseded: ${counts.superseded}`);\n lines.push(` archived: ${counts.archived}`);\n if (counts.other > 0) {\n lines.push(` other: ${counts.other}`);\n }\n lines.push(\"\");\n lines.push(` recent:`);\n lines.push(` lastWriteAt: ${recent.lastWriteAt ?? \"(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,QAAQ,MAAM,QAAQ,MAAM;AAAA,EAC/C;AAAA,EAEA,MAAM,0BAA0B,SAMwC;AACtE,WAAO,KAAK,aAAa,oBAAoB,EAAE,kBAAkB,QAAQ,OAAO;AAAA,MAC9E,QAAQ,QAAQ;AAAA,MAChB,MAAM,QAAQ;AAAA,MACd,IAAI,QAAQ;AAAA,MACZ,OAAO,QAAQ;AAAA,IACjB,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,4BAA4B,SAIuC;AACvE,WAAO,KAAK,aAAa,oBAAoB,EAAE,mBAAmB;AAAA,MAChE,QAAQ,QAAQ;AAAA,MAChB,MAAM,QAAQ;AAAA,MACd,OAAO,QAAQ;AAAA,IACjB,CAAC;AAAA,EACH;AACF;","names":["stat","createHash","resolve","clusterKey","writeNamespace","createHash","resolve","stat","disclosure","sessionKey","mkdir","join","basename","result"]}