@remnic/core 1.1.0 → 1.1.1

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 (287) hide show
  1. package/dist/access-audit.d.ts +56 -0
  2. package/dist/access-audit.js +9 -0
  3. package/dist/access-cli.js +62 -45
  4. package/dist/access-cli.js.map +1 -1
  5. package/dist/access-http.d.ts +16 -9
  6. package/dist/access-http.js +25 -17
  7. package/dist/access-mcp.d.ts +16 -9
  8. package/dist/access-mcp.js +29 -7
  9. package/dist/access-schema.d.ts +124 -33
  10. package/dist/access-schema.js +5 -1
  11. package/dist/{access-service-HmO1Trrx.d.ts → access-service-Br8ZydTK.d.ts} +158 -63
  12. package/dist/access-service.d.ts +13 -6
  13. package/dist/access-service.js +22 -14
  14. package/dist/bootstrap.d.ts +6 -3
  15. package/dist/briefing.d.ts +1 -0
  16. package/dist/briefing.js +7 -6
  17. package/dist/buffer-surprise-report.d.ts +70 -0
  18. package/dist/buffer-surprise-report.js +7 -0
  19. package/dist/buffer-surprise-report.js.map +1 -0
  20. package/dist/buffer-surprise.d.ts +98 -0
  21. package/dist/buffer-surprise.js +11 -0
  22. package/dist/buffer-surprise.js.map +1 -0
  23. package/dist/buffer.d.ts +100 -2
  24. package/dist/buffer.js +1 -1
  25. package/dist/calibration.js +5 -5
  26. package/dist/causal-behavior.js +4 -4
  27. package/dist/causal-chain.js +2 -2
  28. package/dist/causal-consolidation.js +17 -16
  29. package/dist/causal-consolidation.js.map +1 -1
  30. package/dist/causal-retrieval.js +4 -4
  31. package/dist/causal-trajectory.js +1 -1
  32. package/dist/{chunk-QNJMBKFK.js → chunk-2LGMW3DJ.js} +3 -2
  33. package/dist/chunk-2LGMW3DJ.js.map +1 -0
  34. package/dist/{chunk-QDYXG4CS.js → chunk-3FPTCC3Z.js} +4 -3
  35. package/dist/chunk-3FPTCC3Z.js.map +1 -0
  36. package/dist/chunk-3GPTTA4J.js +57 -0
  37. package/dist/chunk-3GPTTA4J.js.map +1 -0
  38. package/dist/{chunk-44ICJRF3.js → chunk-3GXCSUXR.js} +4 -4
  39. package/dist/{chunk-ITRLGI2T.js → chunk-3OGMS3PE.js} +2 -2
  40. package/dist/chunk-54V4BZWP.js +139 -0
  41. package/dist/chunk-54V4BZWP.js.map +1 -0
  42. package/dist/chunk-5JRF2PZA.js +67 -0
  43. package/dist/chunk-5JRF2PZA.js.map +1 -0
  44. package/dist/chunk-64NJRYU2.js +332 -0
  45. package/dist/chunk-64NJRYU2.js.map +1 -0
  46. package/dist/{chunk-OIT5QGG4.js → chunk-6AUUAZEX.js} +72 -2
  47. package/dist/chunk-6AUUAZEX.js.map +1 -0
  48. package/dist/{chunk-ZVBB3T7V.js → chunk-7I7FKFZH.js} +24 -22
  49. package/dist/chunk-7I7FKFZH.js.map +1 -0
  50. package/dist/chunk-AJU4PJGY.js +126 -0
  51. package/dist/chunk-AJU4PJGY.js.map +1 -0
  52. package/dist/chunk-ASAITVLA.js +64 -0
  53. package/dist/chunk-ASAITVLA.js.map +1 -0
  54. package/dist/{chunk-3QHL5ABG.js → chunk-B5WXLVDY.js} +187 -6
  55. package/dist/chunk-B5WXLVDY.js.map +1 -0
  56. package/dist/{chunk-SYUK3VLY.js → chunk-BGJGXLZ7.js} +111 -2
  57. package/dist/{chunk-SYUK3VLY.js.map → chunk-BGJGXLZ7.js.map} +1 -1
  58. package/dist/{chunk-MBJHSA7F.js → chunk-BK2EFTE2.js} +258 -13
  59. package/dist/chunk-BK2EFTE2.js.map +1 -0
  60. package/dist/chunk-C4SQJZAF.js +486 -0
  61. package/dist/chunk-C4SQJZAF.js.map +1 -0
  62. package/dist/{chunk-6UJ47TVX.js → chunk-CUPFXL3J.js} +2 -2
  63. package/dist/chunk-DF3RVK3X.js +119 -0
  64. package/dist/chunk-DF3RVK3X.js.map +1 -0
  65. package/dist/{chunk-37UIFYWO.js → chunk-DFTTJYSO.js} +108 -9
  66. package/dist/chunk-DFTTJYSO.js.map +1 -0
  67. package/dist/chunk-DGVM5SFL.js +69 -0
  68. package/dist/chunk-DGVM5SFL.js.map +1 -0
  69. package/dist/chunk-EIR5VLIH.js +90 -0
  70. package/dist/chunk-EIR5VLIH.js.map +1 -0
  71. package/dist/{chunk-PAORGQRI.js → chunk-EPQJM2GC.js} +37 -23
  72. package/dist/chunk-EPQJM2GC.js.map +1 -0
  73. package/dist/{chunk-GV6NLQ4X.js → chunk-F5VP6YCB.js} +374 -16
  74. package/dist/chunk-F5VP6YCB.js.map +1 -0
  75. package/dist/{chunk-6ZH4TU6I.js → chunk-FAAFWE4G.js} +2 -1
  76. package/dist/chunk-FAAFWE4G.js.map +1 -0
  77. package/dist/{chunk-7WQ6SLIE.js → chunk-FVA6TGI3.js} +2 -2
  78. package/dist/chunk-GDFS42HT.js +206 -0
  79. package/dist/chunk-GDFS42HT.js.map +1 -0
  80. package/dist/{chunk-MVTHXUBX.js → chunk-GKFXUTJ2.js} +479 -20
  81. package/dist/chunk-GKFXUTJ2.js.map +1 -0
  82. package/dist/{chunk-NQEVYWX6.js → chunk-HK3FGIEW.js} +209 -5
  83. package/dist/chunk-HK3FGIEW.js.map +1 -0
  84. package/dist/chunk-IISBCCWR.js +52 -0
  85. package/dist/chunk-IISBCCWR.js.map +1 -0
  86. package/dist/{chunk-WBSAYXVI.js → chunk-INXV5JBT.js} +198 -42
  87. package/dist/chunk-INXV5JBT.js.map +1 -0
  88. package/dist/chunk-JBMSGZEQ.js +441 -0
  89. package/dist/chunk-JBMSGZEQ.js.map +1 -0
  90. package/dist/{chunk-J4IYOZZ5.js → chunk-JXS5PDQ7.js} +3 -1
  91. package/dist/chunk-JXS5PDQ7.js.map +1 -0
  92. package/dist/{chunk-6LX5ORAS.js → chunk-KUB6JU6H.js} +4 -4
  93. package/dist/chunk-KVBLZUKV.js +173 -0
  94. package/dist/chunk-KVBLZUKV.js.map +1 -0
  95. package/dist/chunk-LBLXEFWK.js +51 -0
  96. package/dist/chunk-LBLXEFWK.js.map +1 -0
  97. package/dist/{chunk-3WHVNEN7.js → chunk-LTCGGW2D.js} +1 -1
  98. package/dist/chunk-LTCGGW2D.js.map +1 -0
  99. package/dist/{chunk-UEYA6UC7.js → chunk-NZLQTHS5.js} +25 -2
  100. package/dist/chunk-NZLQTHS5.js.map +1 -0
  101. package/dist/chunk-PVPWZSSI.js +37 -0
  102. package/dist/chunk-PVPWZSSI.js.map +1 -0
  103. package/dist/{chunk-4NRAJUDS.js → chunk-RBBWYEFJ.js} +1 -1
  104. package/dist/chunk-RFYAYKTD.js +146 -0
  105. package/dist/chunk-RFYAYKTD.js.map +1 -0
  106. package/dist/{chunk-DHHP2Z4X.js → chunk-RGLL5SPU.js} +2 -2
  107. package/dist/{chunk-3SV6CQHO.js → chunk-S3EEFKNY.js} +101 -65
  108. package/dist/chunk-S3EEFKNY.js.map +1 -0
  109. package/dist/chunk-SOBJ6NEY.js +18 -0
  110. package/dist/chunk-SOBJ6NEY.js.map +1 -0
  111. package/dist/{chunk-JIU55F3X.js → chunk-SPI27QT6.js} +2 -2
  112. package/dist/chunk-TVVEYCNW.js +65 -0
  113. package/dist/chunk-TVVEYCNW.js.map +1 -0
  114. package/dist/chunk-ULYOGL6R.js +322 -0
  115. package/dist/chunk-ULYOGL6R.js.map +1 -0
  116. package/dist/{chunk-47UU5PU2.js → chunk-VBVG2M5G.js} +18 -3
  117. package/dist/chunk-VBVG2M5G.js.map +1 -0
  118. package/dist/{chunk-7ECD5ATE.js → chunk-VDX363PS.js} +2 -2
  119. package/dist/{chunk-DEPL3635.js → chunk-VYM3VWOF.js} +1432 -188
  120. package/dist/chunk-VYM3VWOF.js.map +1 -0
  121. package/dist/{chunk-MTLYEMJB.js → chunk-WCLICCGB.js} +18 -3
  122. package/dist/chunk-WCLICCGB.js.map +1 -0
  123. package/dist/{chunk-4LACOVZX.js → chunk-WVVA7F5A.js} +2 -2
  124. package/dist/chunk-X6GF3FX2.js +26 -0
  125. package/dist/chunk-X6GF3FX2.js.map +1 -0
  126. package/dist/{chunk-3QFQGRHO.js → chunk-XMHBH5H6.js} +4 -4
  127. package/dist/{chunk-BLKTA7MM.js → chunk-YNQKWQT4.js} +50 -17
  128. package/dist/chunk-YNQKWQT4.js.map +1 -0
  129. package/dist/chunk-ZAIM4TUE.js +488 -0
  130. package/dist/chunk-ZAIM4TUE.js.map +1 -0
  131. package/dist/{chunk-N42IWANG.js → chunk-ZEM3OK2K.js} +2 -2
  132. package/dist/chunk-ZZTOURJI.js +91 -0
  133. package/dist/chunk-ZZTOURJI.js.map +1 -0
  134. package/dist/{cli-BneVIEvh.d.ts → cli-BkeRaYfk.d.ts} +2 -2
  135. package/dist/cli.d.ts +13 -6
  136. package/dist/cli.js +40 -29
  137. package/dist/config.js +1 -1
  138. package/dist/consolidation-operator.d.ts +41 -0
  139. package/dist/consolidation-operator.js +11 -0
  140. package/dist/consolidation-operator.js.map +1 -0
  141. package/dist/consolidation-provenance-check.d.ts +68 -0
  142. package/dist/consolidation-provenance-check.js +9 -0
  143. package/dist/consolidation-provenance-check.js.map +1 -0
  144. package/dist/consolidation-undo.d.ts +123 -0
  145. package/dist/consolidation-undo.js +426 -0
  146. package/dist/consolidation-undo.js.map +1 -0
  147. package/dist/{contradiction-scan-GR33PONM.js → contradiction-scan-E3GJTI4F.js} +43 -7
  148. package/dist/contradiction-scan-E3GJTI4F.js.map +1 -0
  149. package/dist/cross-namespace-budget.d.ts +133 -0
  150. package/dist/cross-namespace-budget.js +9 -0
  151. package/dist/cross-namespace-budget.js.map +1 -0
  152. package/dist/direct-answer-wiring.js +5 -70
  153. package/dist/direct-answer-wiring.js.map +1 -1
  154. package/dist/{engine-5TIQBYZR.js → engine-F3GOXGE5.js} +8 -7
  155. package/dist/engine-F3GOXGE5.js.map +1 -0
  156. package/dist/entity-retrieval.d.ts +1 -0
  157. package/dist/entity-retrieval.js +7 -6
  158. package/dist/explicit-capture.d.ts +6 -3
  159. package/dist/explicit-capture.js +2 -2
  160. package/dist/extraction-judge-telemetry.d.ts +113 -0
  161. package/dist/extraction-judge-telemetry.js +14 -0
  162. package/dist/extraction-judge-telemetry.js.map +1 -0
  163. package/dist/extraction-judge-training.d.ts +85 -0
  164. package/dist/extraction-judge-training.js +16 -0
  165. package/dist/extraction-judge-training.js.map +1 -0
  166. package/dist/extraction-judge.d.ts +124 -2
  167. package/dist/extraction-judge.js +11 -1
  168. package/dist/extraction.js +6 -5
  169. package/dist/fallback-llm.js +2 -2
  170. package/dist/graph-recall.d.ts +100 -0
  171. package/dist/graph-recall.js +8 -0
  172. package/dist/graph-recall.js.map +1 -0
  173. package/dist/graph-retrieval.d.ts +271 -0
  174. package/dist/graph-retrieval.js +21 -0
  175. package/dist/graph-retrieval.js.map +1 -0
  176. package/dist/importance.js +1 -1
  177. package/dist/index.d.ts +585 -20
  178. package/dist/index.js +503 -312
  179. package/dist/index.js.map +1 -1
  180. package/dist/memory-worth-bench.d.ts +51 -0
  181. package/dist/memory-worth-bench.js +131 -0
  182. package/dist/memory-worth-bench.js.map +1 -0
  183. package/dist/memory-worth-filter.d.ts +128 -0
  184. package/dist/memory-worth-filter.js +10 -0
  185. package/dist/memory-worth-filter.js.map +1 -0
  186. package/dist/memory-worth-outcomes.d.ts +118 -0
  187. package/dist/memory-worth-outcomes.js +9 -0
  188. package/dist/memory-worth-outcomes.js.map +1 -0
  189. package/dist/memory-worth.d.ts +102 -0
  190. package/dist/memory-worth.js +7 -0
  191. package/dist/memory-worth.js.map +1 -0
  192. package/dist/operator-toolkit.d.ts +40 -1
  193. package/dist/operator-toolkit.js +23 -14
  194. package/dist/{orchestrator-DRYA6_lW.d.ts → orchestrator-CmJ-NTdJ.d.ts} +233 -8
  195. package/dist/orchestrator.d.ts +6 -3
  196. package/dist/orchestrator.js +49 -39
  197. package/dist/page-versioning.d.ts +12 -1
  198. package/dist/page-versioning.js +5 -3
  199. package/dist/{port-C1GZFv8h.d.ts → port-BADbLZU5.d.ts} +2 -2
  200. package/dist/qmd-recall-cache.d.ts +1 -1
  201. package/dist/qmd.d.ts +5 -3
  202. package/dist/qmd.js +1 -1
  203. package/dist/reasoning-trace-recall.d.ts +90 -0
  204. package/dist/reasoning-trace-recall.js +13 -0
  205. package/dist/reasoning-trace-recall.js.map +1 -0
  206. package/dist/reasoning-trace-types.d.ts +54 -0
  207. package/dist/reasoning-trace-types.js +17 -0
  208. package/dist/reasoning-trace-types.js.map +1 -0
  209. package/dist/recall-audit-anomaly.d.ts +112 -0
  210. package/dist/recall-audit-anomaly.js +11 -0
  211. package/dist/recall-audit-anomaly.js.map +1 -0
  212. package/dist/recall-audit.js +5 -44
  213. package/dist/recall-audit.js.map +1 -1
  214. package/dist/recall-explain-renderer.d.ts +49 -0
  215. package/dist/recall-explain-renderer.js +18 -0
  216. package/dist/recall-explain-renderer.js.map +1 -0
  217. package/dist/recall-state.d.ts +12 -1
  218. package/dist/recall-state.js +1 -1
  219. package/dist/recall-xray-cli.d.ts +40 -0
  220. package/dist/recall-xray-cli.js +11 -0
  221. package/dist/recall-xray-cli.js.map +1 -0
  222. package/dist/recall-xray-renderer.d.ts +44 -0
  223. package/dist/recall-xray-renderer.js +18 -0
  224. package/dist/recall-xray-renderer.js.map +1 -0
  225. package/dist/recall-xray.d.ts +179 -0
  226. package/dist/recall-xray.js +13 -0
  227. package/dist/recall-xray.js.map +1 -0
  228. package/dist/resume-bundles.js +5 -5
  229. package/dist/retrieval-agents.d.ts +1 -1
  230. package/dist/retrieval-tiers.d.ts +17 -0
  231. package/dist/retrieval-tiers.js +9 -0
  232. package/dist/retrieval-tiers.js.map +1 -0
  233. package/dist/schemas.d.ts +287 -31
  234. package/dist/schemas.js +1 -1
  235. package/dist/{semantic-consolidation-DrvSYRdB.d.ts → semantic-consolidation-CxJU6MJk.d.ts} +62 -1
  236. package/dist/semantic-consolidation.d.ts +2 -1
  237. package/dist/semantic-consolidation.js +21 -7
  238. package/dist/semantic-rule-promotion.js +7 -6
  239. package/dist/semantic-rule-verifier.js +7 -6
  240. package/dist/storage.d.ts +82 -1
  241. package/dist/storage.js +6 -5
  242. package/dist/summarizer.js +3 -3
  243. package/dist/temporal-supersession.d.ts +1 -0
  244. package/dist/tier-migration.d.ts +2 -1
  245. package/dist/types.d.ts +276 -2
  246. package/dist/types.js +1 -1
  247. package/dist/verified-recall.js +7 -6
  248. package/package.json +1 -1
  249. package/dist/chunk-37UIFYWO.js.map +0 -1
  250. package/dist/chunk-3QHL5ABG.js.map +0 -1
  251. package/dist/chunk-3SV6CQHO.js.map +0 -1
  252. package/dist/chunk-3WHVNEN7.js.map +0 -1
  253. package/dist/chunk-47UU5PU2.js.map +0 -1
  254. package/dist/chunk-6ZH4TU6I.js.map +0 -1
  255. package/dist/chunk-BLKTA7MM.js.map +0 -1
  256. package/dist/chunk-DEPL3635.js.map +0 -1
  257. package/dist/chunk-GV6NLQ4X.js.map +0 -1
  258. package/dist/chunk-J4IYOZZ5.js.map +0 -1
  259. package/dist/chunk-LAYN4LDC.js +0 -267
  260. package/dist/chunk-LAYN4LDC.js.map +0 -1
  261. package/dist/chunk-MBJHSA7F.js.map +0 -1
  262. package/dist/chunk-MTLYEMJB.js.map +0 -1
  263. package/dist/chunk-MVTHXUBX.js.map +0 -1
  264. package/dist/chunk-NQEVYWX6.js.map +0 -1
  265. package/dist/chunk-OIT5QGG4.js.map +0 -1
  266. package/dist/chunk-PAORGQRI.js.map +0 -1
  267. package/dist/chunk-QDYXG4CS.js.map +0 -1
  268. package/dist/chunk-QNJMBKFK.js.map +0 -1
  269. package/dist/chunk-UEYA6UC7.js.map +0 -1
  270. package/dist/chunk-UVJFDP7P.js +0 -202
  271. package/dist/chunk-UVJFDP7P.js.map +0 -1
  272. package/dist/chunk-WBSAYXVI.js.map +0 -1
  273. package/dist/chunk-ZVBB3T7V.js.map +0 -1
  274. package/dist/contradiction-scan-GR33PONM.js.map +0 -1
  275. /package/dist/{engine-5TIQBYZR.js.map → access-audit.js.map} +0 -0
  276. /package/dist/{chunk-44ICJRF3.js.map → chunk-3GXCSUXR.js.map} +0 -0
  277. /package/dist/{chunk-ITRLGI2T.js.map → chunk-3OGMS3PE.js.map} +0 -0
  278. /package/dist/{chunk-6UJ47TVX.js.map → chunk-CUPFXL3J.js.map} +0 -0
  279. /package/dist/{chunk-7WQ6SLIE.js.map → chunk-FVA6TGI3.js.map} +0 -0
  280. /package/dist/{chunk-6LX5ORAS.js.map → chunk-KUB6JU6H.js.map} +0 -0
  281. /package/dist/{chunk-4NRAJUDS.js.map → chunk-RBBWYEFJ.js.map} +0 -0
  282. /package/dist/{chunk-DHHP2Z4X.js.map → chunk-RGLL5SPU.js.map} +0 -0
  283. /package/dist/{chunk-JIU55F3X.js.map → chunk-SPI27QT6.js.map} +0 -0
  284. /package/dist/{chunk-7ECD5ATE.js.map → chunk-VDX363PS.js.map} +0 -0
  285. /package/dist/{chunk-4LACOVZX.js.map → chunk-WVVA7F5A.js.map} +0 -0
  286. /package/dist/{chunk-3QFQGRHO.js.map → chunk-XMHBH5H6.js.map} +0 -0
  287. /package/dist/{chunk-N42IWANG.js.map → chunk-ZEM3OK2K.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/access-service.ts","../src/work/storage.ts","../src/work/board.ts","../src/procedural/procedure-miner.ts","../src/procedural/procedure-stats.ts"],"sourcesContent":["import { stat } from \"node:fs/promises\";\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 { 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 {\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 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 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 MemoryLifecycleEvent,\n MemoryStatus,\n PluginConfig,\n RecallPlanMode,\n} from \"./types.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\";\n\nexport class EngramAccessInputError extends Error {}\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 nativeKnowledgeEnabled: boolean;\n projectionAvailable: boolean;\n}\n\nexport interface EngramAccessRecallRequest {\n query: string;\n sessionKey?: string;\n namespace?: string;\n topK?: number;\n mode?: RecallPlanMode | \"auto\";\n includeDebug?: boolean;\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\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 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}\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}\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\nexport interface EngramAccessMemoryBrowseRequest {\n query?: string;\n status?: string;\n category?: string;\n namespace?: 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\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\nexport interface EngramAccessMemoryStoreRequest extends EngramAccessWriteEnvelope, ExplicitCaptureInput {}\n\nexport interface EngramAccessSuggestionSubmitRequest extends EngramAccessWriteEnvelope, ExplicitCaptureInput {}\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 EngramAccessObserveRequest {\n sessionKey: string;\n messages: Array<{ role: \"user\" | \"assistant\"; content: string }>;\n namespace?: string;\n authenticatedPrincipal?: string;\n skipExtraction?: boolean;\n}\n\nexport interface EngramAccessObserveResponse {\n accepted: number;\n sessionKey: string;\n namespace: string;\n lcmArchived: boolean;\n extractionQueued: boolean;\n}\n\nexport interface EngramAccessLcmSearchRequest {\n query: string;\n sessionKey?: 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\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\nexport class EngramAccessService {\n private readonly idempotency: AccessIdempotencyStore;\n private readonly idempotencyLocks = 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(namespace: string | undefined, sessionKey: string | undefined): string | undefined {\n const requested = namespace?.trim();\n if (!requested) return undefined;\n const resolved = this.resolveNamespace(requested);\n const principal = resolvePrincipal(sessionKey, this.orchestrator.config);\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 resolveWritePrincipal(sessionKey: string | undefined, authenticatedPrincipal?: string): string {\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.resolveWritePrincipal(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 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 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 serializeRecallResults(snapshot: LastRecallSnapshot | null): 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 results: EngramAccessMemorySummary[] = [];\n const seen = new Set<string>();\n\n for (const memoryPath of snapshot.resultPaths ?? []) {\n if (!memoryPath || seen.has(memoryPath)) continue;\n const memory = await storage.readMemoryByPath(memoryPath);\n if (!memory) continue;\n seen.add(memoryPath);\n results.push(this.serializeMemorySummary(memory, storageDir));\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(this.serializeMemorySummary(memory, storageDir));\n }\n return results;\n }\n\n private async handleIdempotentWrite<T extends EngramAccessWriteResponse>(options: {\n operation: T[\"operation\"];\n idempotencyKey?: string;\n requestFingerprint: unknown;\n skip?: boolean;\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 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 const response = await options.execute();\n await this.idempotency.put(key, requestHash, 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 async health(namespace?: string): Promise<EngramAccessHealthResponse> {\n const resolvedNamespace = this.resolveNamespace(namespace);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\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: this.orchestrator.config.searchBackend ?? \"qmd\",\n qmdEnabled: this.orchestrator.config.qmdEnabled === true,\n nativeKnowledgeEnabled: this.orchestrator.config.nativeKnowledge?.enabled === true,\n projectionAvailable,\n };\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 }\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 });\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 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 // 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 const namespaceOverride = this.resolveRecallNamespace(request.namespace, request.sessionKey);\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 principal = resolvePrincipal(request.sessionKey, this.orchestrator.config);\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 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 let anyCrossNamespace = false;\n let denied: 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 }\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 = this.budget.record(principal);\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 const recallOptions: RecallInvocationOptions = {\n namespace: namespaceOverride,\n topK,\n mode,\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 const results = await this.serializeRecallResults(snapshot);\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 = resolvePrincipal(\n request.sessionKey,\n this.orchestrator.config,\n );\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 summary: context.slice(0, 200) || null,\n injectedChars: context.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 query,\n sessionKey: request.sessionKey,\n namespace: effectiveNamespace,\n context,\n count: snapshot?.memoryIds.length ?? results.length,\n memoryIds: snapshot?.memoryIds ?? [],\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 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 }\n\n async recallExplain(\n request: EngramAccessRecallExplainRequest = {},\n ): Promise<EngramAccessRecallExplainResponse> {\n const requestedNamespace = request.namespace?.trim()\n ? this.resolveNamespace(request.namespace)\n : undefined;\n if (requestedNamespace) {\n const principal = resolvePrincipal(request.sessionKey, this.orchestrator.config);\n if (!canReadNamespace(principal, requestedNamespace, this.orchestrator.config)) {\n return { found: false };\n }\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 namespace = requestedNamespace ?? snapshot?.namespace ?? this.orchestrator.config.defaultNamespace;\n const [intent, graph] = await Promise.all([\n this.orchestrator.getLastIntentSnapshot(namespace),\n this.orchestrator.getLastGraphRecallSnapshot(namespace),\n ]);\n if (!snapshot && !intent && !graph) return { found: false };\n return { found: true, snapshot: snapshot ?? 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 }): Promise<{\n snapshotFound: boolean;\n snapshot?: import(\"./recall-xray.js\").RecallXraySnapshot;\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\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\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\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, request.sessionKey?.trim() || undefined, {\n xrayCapture: true,\n ...(requestedNamespace ? { namespace: requestedNamespace } : {}),\n ...(budgetOverride !== undefined\n ? { budgetCharsOverride: budgetOverride }\n : {}),\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 });\n\n const snapshot = this.orchestrator.getLastXraySnapshot();\n if (!snapshot) return { snapshotFound: false };\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 if (requestedNamespace && snapshot.namespace !== requestedNamespace) {\n return { snapshotFound: false };\n }\n return { snapshotFound: true, snapshot };\n } finally {\n release();\n }\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(request: EngramAccessMemoryStoreRequest): Promise<EngramAccessWriteResponse> {\n const namespace = this.resolveWritableNamespace(\n request.namespace,\n request.sessionKey,\n request.authenticatedPrincipal,\n );\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 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 execute,\n });\n }\n\n async peekMemoryStoreIdempotency(request: EngramAccessMemoryStoreRequest): Promise<EngramAccessIdempotencyStatus> {\n const namespace = this.resolveWritableNamespace(\n request.namespace,\n request.sessionKey,\n request.authenticatedPrincipal,\n );\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(request: EngramAccessSuggestionSubmitRequest): Promise<EngramAccessWriteResponse> {\n const namespace = this.resolveWritableNamespace(\n request.namespace,\n request.sessionKey,\n request.authenticatedPrincipal,\n );\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 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 execute,\n });\n }\n\n async peekSuggestionSubmitIdempotency(\n request: EngramAccessSuggestionSubmitRequest,\n ): Promise<EngramAccessIdempotencyStatus> {\n const namespace = this.resolveWritableNamespace(\n request.namespace,\n request.sessionKey,\n request.authenticatedPrincipal,\n );\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 validateExplicitCaptureInput(\n {\n ...request,\n namespace,\n },\n \"legacy_tool\",\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 storage = await this.orchestrator.getStorage(request.namespace);\n const resolvedNamespace = request.namespace?.trim() || this.orchestrator.config.defaultNamespace;\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 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 /**\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 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(memory: MemoryFile, baseDir: string): EngramAccessMemorySummary {\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 };\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 const namespace = this.resolveWritableNamespace(\n request.namespace,\n request.sessionKey,\n request.authenticatedPrincipal,\n );\n\n // Prefix sessionKey with namespace for LCM archival so turns are namespace-scoped.\n // This ensures multi-tenant isolation in the LCM archive.\n const lcmSessionKey = namespace !== this.orchestrator.config.defaultNamespace\n ? `${namespace}:${request.sessionKey}`\n : request.sessionKey;\n\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 let extractionQueued = false;\n if (request.skipExtraction !== true) {\n const turns = request.messages.map((m) => ({\n source: \"openclaw\" as const,\n sessionKey: lcmSessionKey,\n role: m.role,\n content: m.content,\n timestamp: new Date().toISOString(),\n }));\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 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} 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 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.resolveWritePrincipal(request.sessionKey, request.authenticatedPrincipal);\n const namespace = this.resolveReadableNamespace(request.namespace, principal);\n\n if (!this.orchestrator.lcmEngine || !this.orchestrator.lcmEngine.enabled) {\n return {\n query: request.query,\n namespace,\n results: [],\n count: 0,\n lcmEnabled: false,\n };\n }\n\n const limit = Math.max(1, Math.min(request.limit ?? 10, 100));\n const lcmSessionKey = request.sessionKey && namespace !== this.orchestrator.config.defaultNamespace\n ? `${namespace}:${request.sessionKey}`\n : request.sessionKey;\n const rawResults = await this.orchestrator.lcmEngine.searchContextFull(\n request.query,\n limit,\n lcmSessionKey,\n );\n\n const results = rawResults.map((r: { session_id: string; content: string; turn_index: number }) => ({\n sessionId: r.session_id,\n content: r.content,\n turnIndex: r.turn_index,\n }));\n\n return {\n query: request.query,\n namespace,\n results,\n count: results.length,\n lcmEnabled: true,\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 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, collection, principal } = request;\n const resolvedNs = this.resolveReadableNamespace(namespace, principal);\n const namespaceFilter = resolvedNs !== this.orchestrator.config.defaultNamespace ? resolvedNs : undefined;\n\n const results = collection === \"global\"\n ? (await this.orchestrator.qmd.searchGlobal(query, maxResults)).filter((r) =>\n namespaceFilter\n ? r.path.includes(`/namespaces/${namespaceFilter}/`) ||\n (!r.path.includes(\"/namespaces/\") && namespaceFilter === this.orchestrator.config.defaultNamespace)\n : true,\n )\n : await this.orchestrator.searchAcrossNamespaces({\n query,\n namespaces: namespaceFilter ? [namespaceFilter] : undefined,\n maxResults,\n mode: \"search\",\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 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 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 // ── Contradiction Review (issue #520) ──────────────────────────────────────\n\n get memoryDir(): string {\n return this.orchestrator.config.memoryDir;\n }\n\n get storageRef(): StorageManager {\n return this.orchestrator.storage;\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","import path from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\nimport { mkdir, readdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport type {\n CreateWorkProjectInput,\n CreateWorkTaskInput,\n UpdateWorkProjectInput,\n UpdateWorkTaskInput,\n WorkProject,\n WorkProjectStatus,\n WorkTask,\n WorkTaskListFilter,\n WorkTaskStatus,\n} from \"./types.js\";\n\nconst TASK_TRANSITIONS: Record<WorkTaskStatus, Set<WorkTaskStatus>> = {\n todo: new Set([\"in_progress\", \"blocked\", \"cancelled\"]),\n in_progress: new Set([\"todo\", \"blocked\", \"done\", \"cancelled\"]),\n blocked: new Set([\"todo\", \"in_progress\", \"cancelled\"]),\n done: new Set(),\n cancelled: new Set(),\n};\n\nfunction serializeFrontmatter(values: object): string {\n const lines = Object.entries(values).map(([k, v]) => `${k}: ${JSON.stringify(v)}`);\n return `---\\n${lines.join(\"\\n\")}\\n---`;\n}\n\nfunction parseFrontmatter(raw: string): { data: Record<string, unknown>; body: string } | null {\n const match = raw.match(/^---\\n([\\s\\S]*?)\\n---\\n?([\\s\\S]*)$/);\n if (!match) return null;\n const fm = match[1] ?? \"\";\n const body = match[2] ?? \"\";\n const data: Record<string, unknown> = {};\n for (const line of fm.split(\"\\n\")) {\n if (!line.trim()) continue;\n const idx = line.indexOf(\":\");\n if (idx <= 0) continue;\n const key = line.slice(0, idx).trim();\n const rawValue = line.slice(idx + 1).trim();\n try {\n data[key] = JSON.parse(rawValue);\n } catch {\n data[key] = rawValue;\n }\n }\n return { data, body };\n}\n\nfunction toSafeSlug(value: string): string {\n let slug = value.toLowerCase().trim().replace(/[^a-z0-9]+/g, \"-\");\n // Trim leading/trailing dashes without ReDoS-prone anchored quantifiers\n let start = 0;\n while (start < slug.length && slug[start] === \"-\") start++;\n let end = slug.length;\n while (end > start && slug[end - 1] === \"-\") end--;\n return slug.slice(start, end).slice(0, 80);\n}\n\nexport const WORK_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9-]{0,127}$/;\n\nfunction makeId(prefix: string, titleOrName: string, now: Date): string {\n const slug = toSafeSlug(titleOrName) || \"item\";\n const nonce = randomUUID().slice(0, 8);\n return `${prefix}-${now.getTime()}-${slug}-${nonce}`;\n}\n\nfunction assertValidWorkId(id: string, kind: \"task\" | \"project\"): void {\n if (!WORK_ID_PATTERN.test(id)) {\n throw new Error(`invalid ${kind} id: ${id}`);\n }\n}\n\nfunction ensureString(value: unknown, fallback = \"\"): string {\n return typeof value === \"string\" ? value : fallback;\n}\n\nfunction ensureStringArray(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.filter((entry) => typeof entry === \"string\");\n}\n\nfunction ensureNullableString(value: unknown): string | null {\n return typeof value === \"string\" ? value : null;\n}\n\nfunction ensureTaskStatus(value: unknown): WorkTaskStatus {\n if (value === \"todo\" || value === \"in_progress\" || value === \"blocked\" || value === \"done\" || value === \"cancelled\") {\n return value;\n }\n return \"todo\";\n}\n\nfunction ensureTaskPriority(value: unknown): WorkTask[\"priority\"] {\n if (value === \"low\" || value === \"medium\" || value === \"high\") return value;\n return \"medium\";\n}\n\nfunction ensureProjectStatus(value: unknown): WorkProjectStatus {\n if (value === \"active\" || value === \"on_hold\" || value === \"completed\" || value === \"archived\") return value;\n return \"active\";\n}\n\nexport class WorkStorage {\n private readonly tasksDir: string;\n private readonly projectsDir: string;\n\n constructor(private readonly memoryDir: string) {\n this.tasksDir = path.join(memoryDir, \"work\", \"tasks\");\n this.projectsDir = path.join(memoryDir, \"work\", \"projects\");\n }\n\n async ensureDirectories(): Promise<void> {\n await mkdir(this.tasksDir, { recursive: true });\n await mkdir(this.projectsDir, { recursive: true });\n }\n\n private taskPath(id: string): string {\n assertValidWorkId(id, \"task\");\n return path.join(this.tasksDir, `${id}.md`);\n }\n\n private projectPath(id: string): string {\n assertValidWorkId(id, \"project\");\n return path.join(this.projectsDir, `${id}.md`);\n }\n\n private serializeTask(task: WorkTask): string {\n return `${serializeFrontmatter(task)}\\n\\n${task.description}\\n`;\n }\n\n private serializeProject(project: WorkProject): string {\n return `${serializeFrontmatter(project)}\\n\\n${project.description}\\n`;\n }\n\n private parseTask(raw: string): WorkTask | null {\n const parsed = parseFrontmatter(raw);\n if (!parsed) return null;\n const d = parsed.data;\n return {\n id: ensureString(d.id),\n title: ensureString(d.title),\n description: ensureString(d.description, parsed.body.trim()),\n status: ensureTaskStatus(d.status),\n priority: ensureTaskPriority(d.priority),\n owner: ensureNullableString(d.owner),\n assignee: ensureNullableString(d.assignee),\n projectId: ensureNullableString(d.projectId),\n tags: ensureStringArray(d.tags),\n dueAt: ensureNullableString(d.dueAt),\n createdAt: ensureString(d.createdAt),\n updatedAt: ensureString(d.updatedAt),\n };\n }\n\n private parseProject(raw: string): WorkProject | null {\n const parsed = parseFrontmatter(raw);\n if (!parsed) return null;\n const d = parsed.data;\n return {\n id: ensureString(d.id),\n name: ensureString(d.name),\n description: ensureString(d.description, parsed.body.trim()),\n status: ensureProjectStatus(d.status),\n owner: ensureNullableString(d.owner),\n tags: ensureStringArray(d.tags),\n taskIds: ensureStringArray(d.taskIds),\n createdAt: ensureString(d.createdAt),\n updatedAt: ensureString(d.updatedAt),\n };\n }\n\n async createTask(input: CreateWorkTaskInput, now = new Date()): Promise<WorkTask> {\n await this.ensureDirectories();\n const timestamp = now.toISOString();\n const task: WorkTask = {\n id: input.id ?? makeId(\"task\", input.title, now),\n title: input.title,\n description: input.description ?? \"\",\n status: input.status ?? \"todo\",\n priority: input.priority ?? \"medium\",\n owner: input.owner ?? null,\n assignee: input.assignee ?? null,\n projectId: input.projectId ?? null,\n tags: input.tags ?? [],\n dueAt: input.dueAt ?? null,\n createdAt: timestamp,\n updatedAt: timestamp,\n };\n\n if (task.projectId) {\n const project = await this.getProject(task.projectId);\n if (!project) {\n throw new Error(`project not found: ${task.projectId}`);\n }\n }\n\n await writeFile(this.taskPath(task.id), this.serializeTask(task), \"utf-8\");\n\n if (task.projectId) {\n await this.addTaskIdToProject(task.projectId, task.id, now);\n }\n\n return task;\n }\n\n async getTask(id: string): Promise<WorkTask | null> {\n try {\n const raw = await readFile(this.taskPath(id), \"utf-8\");\n return this.parseTask(raw);\n } catch {\n return null;\n }\n }\n\n async listTasks(filter?: WorkTaskListFilter): Promise<WorkTask[]> {\n await this.ensureDirectories();\n const entries = await readdir(this.tasksDir, { withFileTypes: true });\n const out: WorkTask[] = [];\n for (const entry of entries) {\n if (!entry.isFile() || !entry.name.endsWith(\".md\")) continue;\n const raw = await readFile(path.join(this.tasksDir, entry.name), \"utf-8\");\n const task = this.parseTask(raw);\n if (!task) continue;\n if (filter?.status && task.status !== filter.status) continue;\n if (filter?.owner && task.owner !== filter.owner) continue;\n if (filter?.assignee && task.assignee !== filter.assignee) continue;\n if (filter?.projectId && task.projectId !== filter.projectId) continue;\n out.push(task);\n }\n out.sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n return out;\n }\n\n async updateTask(\n id: string,\n patch: UpdateWorkTaskInput,\n now = new Date(),\n options?: { skipStatusTransitionValidation?: boolean },\n ): Promise<WorkTask | null> {\n const existing = await this.getTask(id);\n if (!existing) return null;\n\n const projectIdPatched = Object.prototype.hasOwnProperty.call(patch, \"projectId\");\n const statusPatched = Object.prototype.hasOwnProperty.call(patch, \"status\");\n const nextProjectId = projectIdPatched ? patch.projectId ?? null : existing.projectId;\n\n if (\n statusPatched\n && patch.status\n && existing.status !== patch.status\n && options?.skipStatusTransitionValidation !== true\n && !TASK_TRANSITIONS[existing.status].has(patch.status)\n ) {\n throw new Error(`invalid task status transition: ${existing.status} -> ${patch.status}`);\n }\n\n if (projectIdPatched && nextProjectId) {\n const nextProject = await this.getProject(nextProjectId);\n if (!nextProject) {\n throw new Error(`project not found: ${nextProjectId}`);\n }\n }\n\n if (projectIdPatched && existing.projectId !== nextProjectId) {\n if (existing.projectId) {\n await this.removeTaskIdFromProject(existing.projectId, id, now);\n }\n if (nextProjectId) {\n await this.addTaskIdToProject(nextProjectId, id, now);\n }\n }\n\n const next: WorkTask = {\n ...existing,\n ...patch,\n projectId: nextProjectId,\n tags: patch.tags ?? existing.tags,\n updatedAt: now.toISOString(),\n };\n await writeFile(this.taskPath(id), this.serializeTask(next), \"utf-8\");\n return next;\n }\n\n async transitionTask(id: string, nextStatus: WorkTaskStatus, now = new Date()): Promise<WorkTask> {\n const existing = await this.getTask(id);\n if (!existing) throw new Error(`task not found: ${id}`);\n if (existing.status === nextStatus) return existing;\n if (!TASK_TRANSITIONS[existing.status].has(nextStatus)) {\n throw new Error(`invalid task status transition: ${existing.status} -> ${nextStatus}`);\n }\n const updated = await this.updateTask(id, { status: nextStatus }, now);\n if (!updated) throw new Error(`task not found after update: ${id}`);\n return updated;\n }\n\n async deleteTask(id: string): Promise<boolean> {\n try {\n const existing = await this.getTask(id);\n await rm(this.taskPath(id));\n if (existing?.projectId) {\n await this.removeTaskIdFromProject(existing.projectId, id);\n }\n return true;\n } catch {\n return false;\n }\n }\n\n async createProject(input: CreateWorkProjectInput, now = new Date()): Promise<WorkProject> {\n await this.ensureDirectories();\n const timestamp = now.toISOString();\n const project: WorkProject = {\n id: input.id ?? makeId(\"project\", input.name, now),\n name: input.name,\n description: input.description ?? \"\",\n status: input.status ?? \"active\",\n owner: input.owner ?? null,\n tags: input.tags ?? [],\n taskIds: [],\n createdAt: timestamp,\n updatedAt: timestamp,\n };\n await writeFile(this.projectPath(project.id), this.serializeProject(project), \"utf-8\");\n return project;\n }\n\n async getProject(id: string): Promise<WorkProject | null> {\n try {\n const raw = await readFile(this.projectPath(id), \"utf-8\");\n return this.parseProject(raw);\n } catch {\n return null;\n }\n }\n\n async listProjects(): Promise<WorkProject[]> {\n await this.ensureDirectories();\n const entries = await readdir(this.projectsDir, { withFileTypes: true });\n const out: WorkProject[] = [];\n for (const entry of entries) {\n if (!entry.isFile() || !entry.name.endsWith(\".md\")) continue;\n const raw = await readFile(path.join(this.projectsDir, entry.name), \"utf-8\");\n const project = this.parseProject(raw);\n if (project) out.push(project);\n }\n out.sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n return out;\n }\n\n async updateProject(id: string, patch: UpdateWorkProjectInput, now = new Date()): Promise<WorkProject | null> {\n const existing = await this.getProject(id);\n if (!existing) return null;\n const next: WorkProject = {\n ...existing,\n ...patch,\n tags: patch.tags ?? existing.tags,\n taskIds: patch.taskIds ? [...patch.taskIds].sort() : existing.taskIds,\n updatedAt: now.toISOString(),\n };\n await writeFile(this.projectPath(id), this.serializeProject(next), \"utf-8\");\n return next;\n }\n\n async deleteProject(id: string): Promise<boolean> {\n try {\n const existing = await this.getProject(id);\n if (existing) {\n for (const taskId of existing.taskIds) {\n await this.updateTask(taskId, { projectId: null });\n }\n }\n await rm(this.projectPath(id));\n return true;\n } catch {\n return false;\n }\n }\n\n async linkTaskToProject(taskId: string, projectId: string, now = new Date()): Promise<{ task: WorkTask; project: WorkProject }> {\n const task = await this.getTask(taskId);\n if (!task) throw new Error(`task not found: ${taskId}`);\n const project = await this.getProject(projectId);\n if (!project) throw new Error(`project not found: ${projectId}`);\n\n const updatedTask = await this.updateTask(taskId, { projectId }, now);\n if (!updatedTask) throw new Error(`task not found after update: ${taskId}`);\n\n const updatedProject = await this.getProject(projectId);\n if (!updatedProject) throw new Error(`project not found after update: ${projectId}`);\n\n return { task: updatedTask, project: updatedProject };\n }\n\n private async removeTaskIdFromProject(projectId: string, taskId: string, now = new Date()): Promise<void> {\n const project = await this.getProject(projectId);\n if (!project) return;\n\n const filtered = project.taskIds.filter((id) => id !== taskId);\n if (filtered.length === project.taskIds.length) return;\n\n await this.updateProject(projectId, { taskIds: filtered }, now);\n }\n\n private async addTaskIdToProject(projectId: string, taskId: string, now = new Date()): Promise<void> {\n const project = await this.getProject(projectId);\n if (!project) return;\n\n const taskIds = new Set(project.taskIds);\n taskIds.add(taskId);\n await this.updateProject(projectId, { taskIds: Array.from(taskIds) }, now);\n }\n}\n","import type { WorkProject, WorkTask, WorkTaskPriority, WorkTaskStatus } from \"./types.js\";\nimport { WORK_ID_PATTERN, WorkStorage } from \"./storage.js\";\n\nconst BOARD_STATUS_ORDER: WorkTaskStatus[] = [\n \"todo\",\n \"in_progress\",\n \"blocked\",\n \"done\",\n \"cancelled\",\n];\n\nconst BOARD_STATUS_LABEL: Record<WorkTaskStatus, string> = {\n todo: \"Todo\",\n in_progress: \"In Progress\",\n blocked: \"Blocked\",\n done: \"Done\",\n cancelled: \"Cancelled\",\n};\n\nconst PRIORITY_WEIGHT: Record<WorkTaskPriority, number> = {\n high: 0,\n medium: 1,\n low: 2,\n};\n\nexport interface WorkBoardItem {\n id: string;\n title: string;\n description: string;\n status: WorkTaskStatus;\n priority: WorkTaskPriority;\n owner: string | null;\n assignee: string | null;\n projectId: string | null;\n tags: string[];\n dueAt: string | null;\n}\n\nexport interface WorkBoardSnapshot {\n version: 1;\n generatedAt: string;\n projectId: string | null;\n projectName: string | null;\n items: WorkBoardItem[];\n}\n\nexport interface ImportWorkBoardResult {\n created: number;\n updated: number;\n}\n\nfunction stableSortTasks(tasks: WorkTask[]): WorkTask[] {\n return [...tasks].sort((a, b) => {\n const priorityCmp = PRIORITY_WEIGHT[a.priority] - PRIORITY_WEIGHT[b.priority];\n if (priorityCmp !== 0) return priorityCmp;\n const createdCmp = a.createdAt.localeCompare(b.createdAt);\n if (createdCmp !== 0) return createdCmp;\n return a.id.localeCompare(b.id);\n });\n}\n\nfunction projectMatches(task: WorkTask, projectId?: string): boolean {\n if (!projectId) return true;\n return task.projectId === projectId;\n}\n\nfunction assertValidImportEnums(item: WorkBoardItem): void {\n if (![\"todo\", \"in_progress\", \"blocked\", \"done\", \"cancelled\"].includes(item.status)) {\n throw new Error(`invalid task status in snapshot for ${item.id}: ${item.status}`);\n }\n if (![\"low\", \"medium\", \"high\"].includes(item.priority)) {\n throw new Error(`invalid task priority in snapshot for ${item.id}: ${item.priority}`);\n }\n}\n\nfunction normalizeImportedProjectId(\n rawValue: unknown,\n taskId: string,\n fallbackForUndefined: string | null,\n): string | null {\n if (rawValue === undefined) return fallbackForUndefined;\n if (rawValue === null) return null;\n if (typeof rawValue === \"string\") {\n const trimmed = rawValue.trim();\n return trimmed.length > 0 ? trimmed : null;\n }\n throw new Error(`invalid task projectId in snapshot for ${taskId}`);\n}\n\nfunction normalizeImportedTags(rawValue: unknown, taskId: string): string[] {\n if (rawValue === undefined || rawValue === null) return [];\n if (!Array.isArray(rawValue)) {\n throw new Error(`invalid task tags in snapshot for ${taskId}`);\n }\n if (!rawValue.every((entry) => typeof entry === \"string\")) {\n throw new Error(`invalid task tags in snapshot for ${taskId}`);\n }\n return [...rawValue];\n}\n\nfunction assertValidImportedTaskId(rawValue: unknown): string {\n if (typeof rawValue !== \"string\") {\n throw new Error(\"invalid task id in snapshot\");\n }\n const trimmed = rawValue.trim();\n if (!WORK_ID_PATTERN.test(trimmed)) {\n throw new Error(`invalid task id in snapshot: ${trimmed}`);\n }\n return trimmed;\n}\n\nfunction normalizeImportedNullableField(\n rawValue: unknown,\n taskId: string,\n fieldName: \"owner\" | \"assignee\" | \"dueAt\",\n fallbackForUndefined: string | null,\n): string | null {\n if (rawValue === undefined) return fallbackForUndefined;\n if (rawValue === null) return null;\n if (typeof rawValue === \"string\") return rawValue;\n throw new Error(`invalid task ${fieldName} in snapshot for ${taskId}`);\n}\n\nfunction normalizeImportedTitle(rawValue: unknown, taskId: string): string {\n if (typeof rawValue !== \"string\") {\n throw new Error(`invalid task title in snapshot for ${taskId}`);\n }\n const trimmed = rawValue.trim();\n if (trimmed.length === 0) {\n throw new Error(`invalid task title in snapshot for ${taskId}`);\n }\n return trimmed;\n}\n\nfunction normalizeImportedDescription(rawValue: unknown, taskId: string): string {\n if (typeof rawValue !== \"string\") {\n throw new Error(`invalid task description in snapshot for ${taskId}`);\n }\n return rawValue;\n}\n\nfunction asBoardItem(task: WorkTask): WorkBoardItem {\n return {\n id: task.id,\n title: task.title,\n description: task.description,\n status: task.status,\n priority: task.priority,\n owner: task.owner,\n assignee: task.assignee,\n projectId: task.projectId,\n tags: [...task.tags],\n dueAt: task.dueAt,\n };\n}\n\nfunction formatTaskLine(task: WorkBoardItem): string {\n const bits: string[] = [`id:${task.id}`, `priority:${task.priority}`];\n if (task.assignee) bits.push(`assignee:${task.assignee}`);\n if (task.owner) bits.push(`owner:${task.owner}`);\n if (task.dueAt) bits.push(`due:${task.dueAt}`);\n if (task.tags.length > 0) bits.push(`tags:${task.tags.join(\",\")}`);\n const checked = task.status === \"done\";\n return `- [${checked ? \"x\" : \" \"}] ${task.title} \\`[${bits.join(\" \")}]\\``;\n}\n\nexport async function exportWorkBoardSnapshot(options: {\n memoryDir: string;\n projectId?: string;\n now?: Date;\n}): Promise<WorkBoardSnapshot> {\n const storage = new WorkStorage(options.memoryDir);\n await storage.ensureDirectories();\n\n const projectId = options.projectId?.trim() || undefined;\n let project: WorkProject | null = null;\n if (projectId) {\n project = await storage.getProject(projectId);\n if (!project) throw new Error(`project not found: ${projectId}`);\n }\n\n const allTasks = await storage.listTasks();\n const filtered = stableSortTasks(allTasks.filter((task) => projectMatches(task, projectId)));\n return {\n version: 1,\n generatedAt: (options.now ?? new Date()).toISOString(),\n projectId: projectId ?? null,\n projectName: project?.name ?? null,\n items: filtered.map(asBoardItem),\n };\n}\n\nfunction renderWorkBoardMarkdown(snapshot: WorkBoardSnapshot): string {\n const lines: string[] = [];\n lines.push(\"# Work Board\");\n lines.push(\"\");\n lines.push(`Generated: ${snapshot.generatedAt}`);\n lines.push(`Project: ${snapshot.projectName ?? \"all\"} (${snapshot.projectId ?? \"all\"})`);\n lines.push(\"\");\n\n for (const status of BOARD_STATUS_ORDER) {\n const bucket = snapshot.items.filter((item) => item.status === status);\n lines.push(`## ${BOARD_STATUS_LABEL[status]} (${bucket.length})`);\n if (bucket.length === 0) {\n lines.push(\"_none_\");\n } else {\n for (const item of bucket) {\n lines.push(formatTaskLine(item));\n }\n }\n lines.push(\"\");\n }\n\n return `${lines.join(\"\\n\").trim()}\\n`;\n}\n\nexport async function exportWorkBoardMarkdown(options: {\n memoryDir: string;\n projectId?: string;\n now?: Date;\n}): Promise<string> {\n const snapshot = await exportWorkBoardSnapshot(options);\n return renderWorkBoardMarkdown(snapshot);\n}\n\nexport async function importWorkBoardSnapshot(options: {\n memoryDir: string;\n snapshot: WorkBoardSnapshot;\n projectId?: string | null;\n now?: Date;\n}): Promise<ImportWorkBoardResult> {\n if (options.snapshot.version !== 1) {\n throw new Error(`unsupported work board snapshot version: ${options.snapshot.version}`);\n }\n\n const storage = new WorkStorage(options.memoryDir);\n await storage.ensureDirectories();\n\n const forcedProjectId = options.projectId === undefined\n ? undefined\n : (options.projectId?.trim() || null);\n const snapshotProjectId = normalizeImportedProjectId(\n (options.snapshot as unknown as { projectId?: unknown }).projectId,\n \"snapshot\",\n null,\n );\n\n type PreparedImportRow = {\n item: WorkBoardItem;\n existing: WorkTask | null;\n id: string;\n title: string;\n description: string;\n projectId: string | null;\n tags: string[];\n owner: string | null;\n assignee: string | null;\n dueAt: string | null;\n };\n\n const preparedRows: PreparedImportRow[] = [];\n const seenItemIds = new Set<string>();\n for (const item of options.snapshot.items) {\n const id = assertValidImportedTaskId((item as unknown as { id?: unknown }).id);\n if (seenItemIds.has(id)) {\n throw new Error(`duplicate task id in snapshot: ${id}`);\n }\n seenItemIds.add(id);\n assertValidImportEnums(item);\n const existing = await storage.getTask(id);\n const title = normalizeImportedTitle((item as unknown as { title?: unknown }).title, id);\n const description = normalizeImportedDescription((item as unknown as { description?: unknown }).description, id);\n const fallbackProjectId = existing ? existing.projectId : snapshotProjectId;\n const projectId = forcedProjectId === undefined\n ? normalizeImportedProjectId(\n (item as unknown as { projectId?: unknown }).projectId,\n item.id,\n fallbackProjectId,\n )\n : forcedProjectId;\n\n const hasTagsField = Object.prototype.hasOwnProperty.call(\n item as unknown as Record<string, unknown>,\n \"tags\",\n );\n const tags = hasTagsField\n ? normalizeImportedTags((item as unknown as { tags?: unknown }).tags, item.id)\n : (existing ? [...existing.tags] : []);\n\n const owner = normalizeImportedNullableField(\n (item as unknown as { owner?: unknown }).owner,\n id,\n \"owner\",\n existing?.owner ?? null,\n );\n const assignee = normalizeImportedNullableField(\n (item as unknown as { assignee?: unknown }).assignee,\n id,\n \"assignee\",\n existing?.assignee ?? null,\n );\n const dueAt = normalizeImportedNullableField(\n (item as unknown as { dueAt?: unknown }).dueAt,\n id,\n \"dueAt\",\n existing?.dueAt ?? null,\n );\n\n preparedRows.push({ item, existing, id, title, description, projectId, tags, owner, assignee, dueAt });\n }\n\n const projectIdsToValidate = new Set(\n preparedRows\n .map((row) => row.projectId)\n .filter((projectId): projectId is string => typeof projectId === \"string\"),\n );\n for (const projectId of projectIdsToValidate) {\n const project = await storage.getProject(projectId);\n if (!project) throw new Error(`project not found: ${projectId}`);\n }\n\n let created = 0;\n let updated = 0;\n for (const row of preparedRows) {\n const { item, existing, id, title, description, projectId, tags, owner, assignee, dueAt } = row;\n\n if (existing) {\n await storage.updateTask(id, {\n title,\n description,\n status: item.status,\n priority: item.priority,\n owner,\n assignee,\n projectId,\n tags,\n dueAt,\n }, options.now, { skipStatusTransitionValidation: true });\n updated += 1;\n continue;\n }\n\n await storage.createTask({\n id,\n title,\n description,\n status: item.status,\n priority: item.priority,\n owner,\n assignee,\n projectId,\n tags,\n dueAt,\n }, options.now);\n created += 1;\n }\n\n return { created, updated };\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 {\n readCausalTrajectoryRecords,\n filterTrajectoriesByLookbackDays,\n} from \"../causal-trajectory.js\";\nimport { buildProcedurePersistBody, normalizeProcedureSteps, type ProcedureStep } from \"./procedure-types.js\";\nimport { log } from \"../logger.js\";\n\n/** Must match truncation on `procedure_cluster` structured attribute (dedupe + storage). */\nconst PROCEDURE_CLUSTER_ATTR_MAX = 500;\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 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 memories = await storage.readAllMemories();\n for (const m of memories) {\n if (m.frontmatter.category !== \"procedure\") continue;\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 = new Map<string, CausalTrajectoryRecord[]>();\n for (const t of recent) {\n const key = clusterKey(t);\n const arr = clusters.get(key) ?? [];\n arr.push(t);\n clusters.set(key, arr);\n }\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 if (await hasExistingClusterWrite(options.storage, key)) {\n log.debug(`procedure-miner: skip duplicate cluster key=${key.slice(0, 40)}…`);\n continue;\n }\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\n const promote =\n cfg.autoPromoteEnabled === true && group.length >= cfg.autoPromoteOccurrences && rate >= cfg.successFloor;\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 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 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 ?? \"(none)\"}`);\n lines.push(` writesLast7Days: ${recent.writesLast7Days}`);\n lines.push(` minerSourced: ${recent.minerSourced}`);\n return lines.join(\"\\n\") + \"\\n\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY;;;ACArB,OAAO,UAAU;AACjB,SAAS,kBAAkB;AAC3B,SA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