@remnic/core 9.54.7 → 9.54.8

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 (258) hide show
  1. package/dist/access-admin-ops-surface.d.ts +5 -5
  2. package/dist/access-admin-ops-surface.js +42 -41
  3. package/dist/access-authorization-probe.d.ts +5 -5
  4. package/dist/access-authorization-probe.js +43 -42
  5. package/dist/access-boundary.d.ts +5 -5
  6. package/dist/access-boundary.js +42 -41
  7. package/dist/access-cli.js +92 -91
  8. package/dist/access-cli.js.map +1 -1
  9. package/dist/access-extraction-force-flush.d.ts +5 -5
  10. package/dist/access-extraction-force-flush.js +42 -41
  11. package/dist/access-http-lcm-compaction.d.ts +5 -5
  12. package/dist/access-http-lifecycle-flush.d.ts +5 -5
  13. package/dist/access-http-offline-stream.d.ts +5 -5
  14. package/dist/access-http-query.js +42 -41
  15. package/dist/access-http.d.ts +6 -6
  16. package/dist/access-http.js +56 -55
  17. package/dist/access-identity-continuity-surface.d.ts +4 -4
  18. package/dist/access-identity-continuity-surface.js +42 -41
  19. package/dist/access-lcm-surface.d.ts +5 -5
  20. package/dist/access-lcm-surface.js +42 -41
  21. package/dist/access-mcp.d.ts +5 -5
  22. package/dist/access-mcp.js +49 -48
  23. package/dist/access-namespace-preflight.js +42 -41
  24. package/dist/access-observe-write-surface.d.ts +5 -5
  25. package/dist/access-observe-write-surface.js +42 -41
  26. package/dist/access-offline-manifest.d.ts +4 -4
  27. package/dist/access-offline-manifest.js +1 -1
  28. package/dist/access-operations-batch.js +44 -43
  29. package/dist/access-operations.d.ts +5 -5
  30. package/dist/access-operations.js +48 -47
  31. package/dist/access-recall-concurrency.d.ts +5 -5
  32. package/dist/access-recall-concurrency.js +42 -41
  33. package/dist/access-recall-response.d.ts +5 -5
  34. package/dist/access-recall-response.js +42 -41
  35. package/dist/access-recall-surface.d.ts +5 -5
  36. package/dist/access-recall-surface.js +42 -41
  37. package/dist/access-schema.js +3 -3
  38. package/dist/{access-service-DK82xdNi.d.ts → access-service-PEduVt8q.d.ts} +3 -3
  39. package/dist/access-service-helpers.d.ts +5 -5
  40. package/dist/access-service.d.ts +5 -5
  41. package/dist/access-service.js +42 -41
  42. package/dist/access-surface-catalog.d.ts +5 -5
  43. package/dist/access-surface-catalog.js +44 -43
  44. package/dist/access-surface-catalog.js.map +1 -1
  45. package/dist/access-wearables-meetings-surface.d.ts +2 -2
  46. package/dist/adapters/index.js +4 -4
  47. package/dist/adapters/registry.js +2 -2
  48. package/dist/behavior-learner.js +1 -1
  49. package/dist/bootstrap.d.ts +4 -4
  50. package/dist/briefing-window.d.ts +36 -0
  51. package/dist/briefing-window.js +9 -0
  52. package/dist/briefing.d.ts +1 -1
  53. package/dist/briefing.js +15 -14
  54. package/dist/buffer.d.ts +1 -1
  55. package/dist/buffer.js +4 -4
  56. package/dist/causal-behavior.js +2 -2
  57. package/dist/causal-chain.js +2 -2
  58. package/dist/causal-consolidation.js +17 -17
  59. package/dist/causal-retrieval.js +2 -2
  60. package/dist/causal-trajectory-graph.js +2 -2
  61. package/dist/causal-trajectory.js +1 -1
  62. package/dist/{chunk-LEPOP46W.js → chunk-227UFSEQ.js} +4 -4
  63. package/dist/{chunk-ZUKIUXHQ.js → chunk-2GD6MLXD.js} +9 -9
  64. package/dist/{chunk-2FKEIPIT.js → chunk-2T5AWWMF.js} +2 -2
  65. package/dist/{chunk-HBUFQRIM.js → chunk-3DVG3GRQ.js} +2 -2
  66. package/dist/{chunk-QZLDRQ4I.js → chunk-47J4EDGR.js} +3 -3
  67. package/dist/{chunk-K26NWEOC.js → chunk-4ESX4WX2.js} +4 -4
  68. package/dist/{chunk-46SZBVDS.js → chunk-4GE3NA5I.js} +2 -2
  69. package/dist/{chunk-FPLM2TKD.js → chunk-5V64M56S.js} +2 -2
  70. package/dist/{chunk-37DZZFFM.js → chunk-6G4D222J.js} +2 -2
  71. package/dist/{chunk-FFRTNF3L.js → chunk-6PCND4O2.js} +2 -2
  72. package/dist/{chunk-26ZXBTYN.js → chunk-7DISPKXT.js} +4 -4
  73. package/dist/{chunk-JYG4OLWH.js → chunk-7SF5BAWF.js} +2 -2
  74. package/dist/{chunk-XZHE2DEN.js → chunk-BXIMH7MC.js} +2 -2
  75. package/dist/{chunk-FTPONF6B.js → chunk-E2GZSFR5.js} +2 -2
  76. package/dist/{chunk-I3MSGFGD.js → chunk-ELXP665P.js} +2 -2
  77. package/dist/{chunk-EKTP7MNS.js → chunk-F2BOUJUS.js} +6 -6
  78. package/dist/{chunk-3TIZPSJC.js → chunk-FEBHRT2I.js} +3 -3
  79. package/dist/{chunk-W5ZKPI34.js → chunk-FPKKFDO4.js} +124 -124
  80. package/dist/{chunk-UPLZNJKN.js → chunk-FYZKFLKY.js} +2 -2
  81. package/dist/{chunk-FWX7W5PM.js → chunk-G7YUH4WT.js} +2 -2
  82. package/dist/{chunk-PT54WISF.js → chunk-IEQCHXUS.js} +9 -9
  83. package/dist/{chunk-YXQEKCZM.js → chunk-IOYXIY7W.js} +2 -2
  84. package/dist/{chunk-CIAI24TQ.js → chunk-JKW663ZN.js} +2 -2
  85. package/dist/{chunk-V6ERBR7U.js → chunk-K44N3CFW.js} +2 -2
  86. package/dist/{chunk-TO7ZTWJW.js → chunk-KMWYZTIE.js} +2 -2
  87. package/dist/{chunk-IPLYGWQF.js → chunk-KQAFEZQX.js} +5 -5
  88. package/dist/{chunk-S354QO4R.js → chunk-LHIBA4G7.js} +2 -2
  89. package/dist/{chunk-UCTS3DDH.js → chunk-M3UYE6PS.js} +2 -2
  90. package/dist/{chunk-RUNORG2P.js → chunk-MANCJV6J.js} +6 -11
  91. package/dist/chunk-MANCJV6J.js.map +1 -0
  92. package/dist/{chunk-D3LBIUWV.js → chunk-MTF5EFFF.js} +39 -39
  93. package/dist/{chunk-IKP5OYQQ.js → chunk-NUA4VM46.js} +2 -2
  94. package/dist/{chunk-UYYW2KPU.js → chunk-OIOV4RJE.js} +2 -2
  95. package/dist/{chunk-BIJAWZYW.js → chunk-OLT3YTDH.js} +4 -4
  96. package/dist/{chunk-RZQ6W2W4.js → chunk-OS5DYALF.js} +23 -23
  97. package/dist/{chunk-IQ4NVWEF.js → chunk-OTUFRUV3.js} +2 -2
  98. package/dist/{chunk-KFBOPMF6.js → chunk-OWC42MDT.js} +4 -4
  99. package/dist/{chunk-GJ776BC2.js → chunk-P2FA65P2.js} +4 -3
  100. package/dist/{chunk-GJ776BC2.js.map → chunk-P2FA65P2.js.map} +1 -1
  101. package/dist/{chunk-43SEBY2M.js → chunk-PCRHFB75.js} +1 -1
  102. package/dist/{chunk-GN3WRFJY.js → chunk-QC6BILS7.js} +6 -6
  103. package/dist/{chunk-NISZQW72.js → chunk-QDWDVNWU.js} +2 -2
  104. package/dist/{chunk-6CYHUWCO.js → chunk-QGKCM7C4.js} +2 -2
  105. package/dist/{chunk-2QSZNTDO.js → chunk-RKNJBZ55.js} +4 -4
  106. package/dist/{chunk-QCECHYZL.js → chunk-RVO6TCTU.js} +6 -6
  107. package/dist/{chunk-MIH3CJPN.js → chunk-TPWBUKS3.js} +3 -3
  108. package/dist/chunk-UBCBDJOB.js +22 -0
  109. package/dist/chunk-UBCBDJOB.js.map +1 -0
  110. package/dist/{chunk-UKYS3NU5.js → chunk-UQWUDD7E.js} +2 -2
  111. package/dist/{chunk-7BD6O7ZV.js → chunk-XCO2NXPZ.js} +3 -3
  112. package/dist/{chunk-7TBXNYLO.js → chunk-XDBFSUHX.js} +2 -2
  113. package/dist/{chunk-W6FNX2LP.js → chunk-XWZ6KOL6.js} +2 -2
  114. package/dist/{chunk-M4YHAODQ.js → chunk-XXRRHING.js} +285 -232
  115. package/dist/chunk-XXRRHING.js.map +1 -0
  116. package/dist/{chunk-ZRZVLB7O.js → chunk-YZFPEHXF.js} +2 -2
  117. package/dist/{chunk-OUKBMQ2O.js → chunk-Z3SQEEB6.js} +2 -2
  118. package/dist/{chunk-BRR5EUTF.js → chunk-Z463UYI6.js} +2 -2
  119. package/dist/{chunk-5FD7JMTX.js → chunk-ZUJW327U.js} +2 -2
  120. package/dist/{chunk-AHZOMHWN.js → chunk-ZXGKQQ3L.js} +1 -1
  121. package/dist/{cli-BPDUXnAl.d.ts → cli-DNvGlD4i.d.ts} +3 -3
  122. package/dist/cli.d.ts +6 -6
  123. package/dist/cli.js +68 -67
  124. package/dist/coding/pre-action-gate.js +2 -2
  125. package/dist/compounding/engine.d.ts +1 -1
  126. package/dist/compounding/engine.js +14 -14
  127. package/dist/connectors/codex-materialize-runner.js +14 -14
  128. package/dist/connectors/index.js +14 -14
  129. package/dist/consolidation-provenance-check.d.ts +1 -1
  130. package/dist/consolidation-undo.d.ts +1 -1
  131. package/dist/contradiction/index.d.ts +1 -1
  132. package/dist/convergence-refresh.d.ts +1 -1
  133. package/dist/convergence-refresh.js +16 -16
  134. package/dist/conversation-index/backend.js +2 -2
  135. package/dist/corpus-watermark.js +16 -16
  136. package/dist/entity-retrieval.d.ts +1 -1
  137. package/dist/entity-retrieval.js +14 -14
  138. package/dist/explicit-capture.d.ts +4 -4
  139. package/dist/external-wiki-access.d.ts +5 -5
  140. package/dist/external-wiki-access.js +43 -42
  141. package/dist/external-wiki-mcp-tools.d.ts +5 -5
  142. package/dist/extraction.js +24 -24
  143. package/dist/{graph-edge-decay-65KMOJWY.js → graph-edge-decay-JI2XDCTY.js} +4 -4
  144. package/dist/graph-edge-decay-JI2XDCTY.js.map +1 -0
  145. package/dist/graph-snapshot.js +3 -3
  146. package/dist/graph.js +2 -2
  147. package/dist/harmonic-retrieval.js +1 -1
  148. package/dist/index.d.ts +11 -11
  149. package/dist/index.js +124 -123
  150. package/dist/local-llm.js +2 -2
  151. package/dist/maintenance/memory-governance.js +14 -14
  152. package/dist/maintenance/rebuild-memory-lifecycle-ledger.d.ts +1 -1
  153. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +14 -14
  154. package/dist/maintenance/rebuild-memory-projection.d.ts +1 -1
  155. package/dist/maintenance/rebuild-memory-projection.js +15 -15
  156. package/dist/{maintenance-C8aRWfhq.d.ts → maintenance-laHYTo0s.d.ts} +1 -1
  157. package/dist/mcp-memory-inspector-app.d.ts +5 -5
  158. package/dist/memory-worth-outcomes.d.ts +1 -1
  159. package/dist/namespaces/migrate.d.ts +1 -1
  160. package/dist/namespaces/migrate.js +15 -15
  161. package/dist/namespaces/search.js +6 -6
  162. package/dist/namespaces/storage.d.ts +1 -1
  163. package/dist/namespaces/storage.js +14 -14
  164. package/dist/offline-sync-impression-drain.js +1 -1
  165. package/dist/operator-doctor-corpus.js +17 -17
  166. package/dist/operator-toolkit.d.ts +1 -1
  167. package/dist/operator-toolkit.js +24 -24
  168. package/dist/orchestration/compression-guideline-coordinator.d.ts +1 -1
  169. package/dist/orchestration/maintenance.d.ts +2 -2
  170. package/dist/orchestration/maintenance.js +20 -20
  171. package/dist/{orchestrator-D85CzDDY.d.ts → orchestrator-Cz2QmqsN.d.ts} +3 -3
  172. package/dist/orchestrator.d.ts +4 -4
  173. package/dist/orchestrator.js +127 -126
  174. package/dist/policy-runtime.js +1 -1
  175. package/dist/{public-http-D3GBeII4.d.ts → public-http-Dq2iqtcI.d.ts} +1 -1
  176. package/dist/qmd.js +4 -4
  177. package/dist/recall-planner-llm.js +3 -3
  178. package/dist/search/factory.js +5 -5
  179. package/dist/search/index.js +5 -5
  180. package/dist/semantic-consolidation.js +15 -15
  181. package/dist/semantic-rule-promotion.js +14 -14
  182. package/dist/semantic-rule-verifier.js +14 -14
  183. package/dist/{service-DT-pJyda.d.ts → service-D_ddZmpI.d.ts} +1 -1
  184. package/dist/source-agent-qualifier.js +19 -19
  185. package/dist/{storage-qOnaJ1Lw.d.ts → storage-Cdz7jb9t.d.ts} +14 -9
  186. package/dist/storage.d.ts +1 -1
  187. package/dist/storage.js +13 -13
  188. package/dist/summarizer.js +3 -3
  189. package/dist/support-passport/index.d.ts +8 -8
  190. package/dist/support-passport/index.js +45 -44
  191. package/dist/tier-migration.d.ts +1 -1
  192. package/dist/transfer/autodetect.js +1 -1
  193. package/dist/transfer/backup.js +1 -1
  194. package/dist/transfer/capsule-export.js +2 -2
  195. package/dist/verified-recall.js +14 -14
  196. package/package.json +2 -2
  197. package/src/briefing-window.ts +27 -0
  198. package/src/briefing.test.ts +29 -0
  199. package/src/briefing.ts +2 -9
  200. package/src/maintenance/memory-governance.ts +1 -0
  201. package/src/storage/memory-read-store.ts +1 -0
  202. package/src/storage/windowed-memory-read.ts +109 -0
  203. package/src/storage.ts +7 -13
  204. package/src/testing/subjects/windowed-memory-read.test.ts +146 -0
  205. package/dist/chunk-M4YHAODQ.js.map +0 -1
  206. package/dist/chunk-RUNORG2P.js.map +0 -1
  207. /package/dist/{graph-edge-decay-65KMOJWY.js.map → briefing-window.js.map} +0 -0
  208. /package/dist/{chunk-LEPOP46W.js.map → chunk-227UFSEQ.js.map} +0 -0
  209. /package/dist/{chunk-ZUKIUXHQ.js.map → chunk-2GD6MLXD.js.map} +0 -0
  210. /package/dist/{chunk-2FKEIPIT.js.map → chunk-2T5AWWMF.js.map} +0 -0
  211. /package/dist/{chunk-HBUFQRIM.js.map → chunk-3DVG3GRQ.js.map} +0 -0
  212. /package/dist/{chunk-QZLDRQ4I.js.map → chunk-47J4EDGR.js.map} +0 -0
  213. /package/dist/{chunk-K26NWEOC.js.map → chunk-4ESX4WX2.js.map} +0 -0
  214. /package/dist/{chunk-46SZBVDS.js.map → chunk-4GE3NA5I.js.map} +0 -0
  215. /package/dist/{chunk-FPLM2TKD.js.map → chunk-5V64M56S.js.map} +0 -0
  216. /package/dist/{chunk-37DZZFFM.js.map → chunk-6G4D222J.js.map} +0 -0
  217. /package/dist/{chunk-FFRTNF3L.js.map → chunk-6PCND4O2.js.map} +0 -0
  218. /package/dist/{chunk-26ZXBTYN.js.map → chunk-7DISPKXT.js.map} +0 -0
  219. /package/dist/{chunk-JYG4OLWH.js.map → chunk-7SF5BAWF.js.map} +0 -0
  220. /package/dist/{chunk-XZHE2DEN.js.map → chunk-BXIMH7MC.js.map} +0 -0
  221. /package/dist/{chunk-FTPONF6B.js.map → chunk-E2GZSFR5.js.map} +0 -0
  222. /package/dist/{chunk-I3MSGFGD.js.map → chunk-ELXP665P.js.map} +0 -0
  223. /package/dist/{chunk-EKTP7MNS.js.map → chunk-F2BOUJUS.js.map} +0 -0
  224. /package/dist/{chunk-3TIZPSJC.js.map → chunk-FEBHRT2I.js.map} +0 -0
  225. /package/dist/{chunk-W5ZKPI34.js.map → chunk-FPKKFDO4.js.map} +0 -0
  226. /package/dist/{chunk-UPLZNJKN.js.map → chunk-FYZKFLKY.js.map} +0 -0
  227. /package/dist/{chunk-FWX7W5PM.js.map → chunk-G7YUH4WT.js.map} +0 -0
  228. /package/dist/{chunk-PT54WISF.js.map → chunk-IEQCHXUS.js.map} +0 -0
  229. /package/dist/{chunk-YXQEKCZM.js.map → chunk-IOYXIY7W.js.map} +0 -0
  230. /package/dist/{chunk-CIAI24TQ.js.map → chunk-JKW663ZN.js.map} +0 -0
  231. /package/dist/{chunk-V6ERBR7U.js.map → chunk-K44N3CFW.js.map} +0 -0
  232. /package/dist/{chunk-TO7ZTWJW.js.map → chunk-KMWYZTIE.js.map} +0 -0
  233. /package/dist/{chunk-IPLYGWQF.js.map → chunk-KQAFEZQX.js.map} +0 -0
  234. /package/dist/{chunk-S354QO4R.js.map → chunk-LHIBA4G7.js.map} +0 -0
  235. /package/dist/{chunk-UCTS3DDH.js.map → chunk-M3UYE6PS.js.map} +0 -0
  236. /package/dist/{chunk-D3LBIUWV.js.map → chunk-MTF5EFFF.js.map} +0 -0
  237. /package/dist/{chunk-IKP5OYQQ.js.map → chunk-NUA4VM46.js.map} +0 -0
  238. /package/dist/{chunk-UYYW2KPU.js.map → chunk-OIOV4RJE.js.map} +0 -0
  239. /package/dist/{chunk-BIJAWZYW.js.map → chunk-OLT3YTDH.js.map} +0 -0
  240. /package/dist/{chunk-RZQ6W2W4.js.map → chunk-OS5DYALF.js.map} +0 -0
  241. /package/dist/{chunk-IQ4NVWEF.js.map → chunk-OTUFRUV3.js.map} +0 -0
  242. /package/dist/{chunk-KFBOPMF6.js.map → chunk-OWC42MDT.js.map} +0 -0
  243. /package/dist/{chunk-43SEBY2M.js.map → chunk-PCRHFB75.js.map} +0 -0
  244. /package/dist/{chunk-GN3WRFJY.js.map → chunk-QC6BILS7.js.map} +0 -0
  245. /package/dist/{chunk-NISZQW72.js.map → chunk-QDWDVNWU.js.map} +0 -0
  246. /package/dist/{chunk-6CYHUWCO.js.map → chunk-QGKCM7C4.js.map} +0 -0
  247. /package/dist/{chunk-2QSZNTDO.js.map → chunk-RKNJBZ55.js.map} +0 -0
  248. /package/dist/{chunk-QCECHYZL.js.map → chunk-RVO6TCTU.js.map} +0 -0
  249. /package/dist/{chunk-MIH3CJPN.js.map → chunk-TPWBUKS3.js.map} +0 -0
  250. /package/dist/{chunk-UKYS3NU5.js.map → chunk-UQWUDD7E.js.map} +0 -0
  251. /package/dist/{chunk-7BD6O7ZV.js.map → chunk-XCO2NXPZ.js.map} +0 -0
  252. /package/dist/{chunk-7TBXNYLO.js.map → chunk-XDBFSUHX.js.map} +0 -0
  253. /package/dist/{chunk-W6FNX2LP.js.map → chunk-XWZ6KOL6.js.map} +0 -0
  254. /package/dist/{chunk-ZRZVLB7O.js.map → chunk-YZFPEHXF.js.map} +0 -0
  255. /package/dist/{chunk-OUKBMQ2O.js.map → chunk-Z3SQEEB6.js.map} +0 -0
  256. /package/dist/{chunk-BRR5EUTF.js.map → chunk-Z463UYI6.js.map} +0 -0
  257. /package/dist/{chunk-5FD7JMTX.js.map → chunk-ZUJW327U.js.map} +0 -0
  258. /package/dist/{chunk-AHZOMHWN.js.map → chunk-ZXGKQQ3L.js.map} +0 -0
@@ -7,6 +7,9 @@ import {
7
7
  import {
8
8
  openclawReplayNormalizer
9
9
  } from "./chunk-H4CKS5B2.js";
10
+ import {
11
+ importSqlite
12
+ } from "./chunk-PYHOAXTI.js";
10
13
  import {
11
14
  exportJsonBundle
12
15
  } from "./chunk-UP6MOYCB.js";
@@ -16,9 +19,6 @@ import {
16
19
  import {
17
20
  importMarkdownBundle
18
21
  } from "./chunk-HDDRVXX4.js";
19
- import {
20
- importSqlite
21
- } from "./chunk-PYHOAXTI.js";
22
22
  import {
23
23
  detectImportFormat
24
24
  } from "./chunk-OZKVVUJB.js";
@@ -54,7 +54,7 @@ import {
54
54
  } from "./chunk-IIFFC3RL.js";
55
55
  import {
56
56
  rebuildMemoryLifecycleLedger
57
- } from "./chunk-46SZBVDS.js";
57
+ } from "./chunk-4GE3NA5I.js";
58
58
  import {
59
59
  rebuildObservations
60
60
  } from "./chunk-DQTCGVFK.js";
@@ -72,7 +72,7 @@ import {
72
72
  } from "./chunk-HSSERO3E.js";
73
73
  import {
74
74
  searchVerifiedEpisodes
75
- } from "./chunk-5FD7JMTX.js";
75
+ } from "./chunk-ZUJW327U.js";
76
76
  import {
77
77
  getUtilityLearningStatus,
78
78
  learnUtilityPromotionWeights
@@ -86,10 +86,10 @@ import {
86
86
  } from "./chunk-OJP3N7UK.js";
87
87
  import {
88
88
  promoteSemanticRuleFromMemory
89
- } from "./chunk-IQ4NVWEF.js";
89
+ } from "./chunk-OTUFRUV3.js";
90
90
  import {
91
91
  searchVerifiedSemanticRules
92
- } from "./chunk-FWX7W5PM.js";
92
+ } from "./chunk-G7YUH4WT.js";
93
93
  import {
94
94
  buildResumeBundleFromState,
95
95
  getResumeBundleStatus,
@@ -118,7 +118,7 @@ import {
118
118
  runOperatorInventory,
119
119
  runOperatorRepair,
120
120
  runOperatorSetup
121
- } from "./chunk-ZUKIUXHQ.js";
121
+ } from "./chunk-2GD6MLXD.js";
122
122
  import {
123
123
  analyzeSessionIntegrity,
124
124
  applySessionRepair,
@@ -152,7 +152,7 @@ import {
152
152
  } from "./chunk-6GUG4YNM.js";
153
153
  import {
154
154
  searchHarmonicRetrieval
155
- } from "./chunk-43SEBY2M.js";
155
+ } from "./chunk-PCRHFB75.js";
156
156
  import {
157
157
  rescoreMemoryImportance
158
158
  } from "./chunk-JXS5PDQ7.js";
@@ -169,7 +169,7 @@ import {
169
169
  rebuildMemoryProjection,
170
170
  repairMemoryProjection,
171
171
  verifyMemoryProjection
172
- } from "./chunk-3TIZPSJC.js";
172
+ } from "./chunk-FEBHRT2I.js";
173
173
  import {
174
174
  getCueAnchorStoreStatus
175
175
  } from "./chunk-ACPCA4NO.js";
@@ -200,7 +200,7 @@ import {
200
200
  import {
201
201
  EngramAccessHttpServer,
202
202
  MeetingsInputError
203
- } from "./chunk-PT54WISF.js";
203
+ } from "./chunk-IEQCHXUS.js";
204
204
  import {
205
205
  WearablesInputError
206
206
  } from "./chunk-V7IZKJI3.js";
@@ -213,13 +213,13 @@ import {
213
213
  createProductionChatLlmAdapter,
214
214
  loadChatSession,
215
215
  sessionBelongsToPrincipal
216
- } from "./chunk-7BD6O7ZV.js";
216
+ } from "./chunk-XCO2NXPZ.js";
217
217
  import {
218
218
  getAbstractionNodeStoreStatus
219
219
  } from "./chunk-DJUKBGAD.js";
220
220
  import {
221
221
  EngramAccessService
222
- } from "./chunk-D3LBIUWV.js";
222
+ } from "./chunk-MTF5EFFF.js";
223
223
  import {
224
224
  WorkStorage
225
225
  } from "./chunk-GDB4J2H3.js";
@@ -239,7 +239,7 @@ import {
239
239
  } from "./chunk-H7NAZ3UB.js";
240
240
  import {
241
241
  readAggregateExtractionWatermark
242
- } from "./chunk-JYG4OLWH.js";
242
+ } from "./chunk-7SF5BAWF.js";
243
243
  import {
244
244
  getObjectiveStateStoreStatus
245
245
  } from "./chunk-HTP6XRUI.js";
@@ -248,24 +248,24 @@ import {
248
248
  readMemoryGovernanceRunArtifact,
249
249
  restoreMemoryGovernanceRun,
250
250
  runMemoryGovernance
251
- } from "./chunk-GJ776BC2.js";
251
+ } from "./chunk-P2FA65P2.js";
252
252
  import {
253
253
  listNamespaces,
254
254
  runNamespaceMigration,
255
255
  verifyNamespaces
256
- } from "./chunk-MIH3CJPN.js";
256
+ } from "./chunk-TPWBUKS3.js";
257
+ import {
258
+ analyzeGraphHealth
259
+ } from "./chunk-OLT3YTDH.js";
257
260
  import {
258
261
  resolveNamespaceChildRoot
259
- } from "./chunk-BRR5EUTF.js";
262
+ } from "./chunk-Z463UYI6.js";
260
263
  import {
261
264
  getCausalTrajectoryStoreStatus
262
- } from "./chunk-AHZOMHWN.js";
263
- import {
264
- analyzeGraphHealth
265
- } from "./chunk-BIJAWZYW.js";
265
+ } from "./chunk-ZXGKQQ3L.js";
266
266
  import {
267
267
  meetingIdDate
268
- } from "./chunk-M4YHAODQ.js";
268
+ } from "./chunk-XXRRHING.js";
269
269
  import {
270
270
  isValidTranscriptDate
271
271
  } from "./chunk-UHVXE24Y.js";
@@ -7995,4 +7995,4 @@ export {
7995
7995
  listMemoryMarkdownFilePaths,
7996
7996
  registerCli
7997
7997
  };
7998
- //# sourceMappingURL=chunk-RZQ6W2W4.js.map
7998
+ //# sourceMappingURL=chunk-OS5DYALF.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  StorageManager
3
- } from "./chunk-M4YHAODQ.js";
3
+ } from "./chunk-XXRRHING.js";
4
4
  import {
5
5
  composeMemoryEnvelope
6
6
  } from "./chunk-NSVDUN76.js";
@@ -546,4 +546,4 @@ export {
546
546
  setSemanticRulePromotionTestHooks,
547
547
  promoteSemanticRuleFromMemory
548
548
  };
549
- //# sourceMappingURL=chunk-IQ4NVWEF.js.map
549
+ //# sourceMappingURL=chunk-OTUFRUV3.js.map
@@ -1,6 +1,3 @@
1
- import {
2
- ChatTransport
3
- } from "./chunk-JUXOTY6J.js";
4
1
  import {
5
2
  SingleFlightProbe,
6
3
  extractNonRecoverableBackendReason,
@@ -11,6 +8,9 @@ import {
11
8
  resolveUnavailableVerdict,
12
9
  waitForRetryBackoff
13
10
  } from "./chunk-WKDFJXW5.js";
11
+ import {
12
+ ChatTransport
13
+ } from "./chunk-JUXOTY6J.js";
14
14
  import {
15
15
  resolveLocalLlmCapabilities,
16
16
  resolvePipelineProcessingCapabilities
@@ -1095,4 +1095,4 @@ var LocalLlmClient = class _LocalLlmClient {
1095
1095
  export {
1096
1096
  LocalLlmClient
1097
1097
  };
1098
- //# sourceMappingURL=chunk-KFBOPMF6.js.map
1098
+ //# sourceMappingURL=chunk-OWC42MDT.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  StorageManager
3
- } from "./chunk-M4YHAODQ.js";
3
+ } from "./chunk-XXRRHING.js";
4
4
  import {
5
5
  bumpMemoryCorpusVersionForDir
6
6
  } from "./chunk-KMAP7SNQ.js";
@@ -526,7 +526,8 @@ async function runMemoryGovernance(options) {
526
526
  const memoryWindow = boundedScan ? await storage.readMemoriesWindow({
527
527
  maxMemories: options.maxMemories,
528
528
  batchSize: options.batchSize,
529
- updatedAfter
529
+ updatedAfter,
530
+ includeMalformedPaths: true
530
531
  }) : void 0;
531
532
  const memories = excludeSupportPassportPrivateMemories(
532
533
  memoryWindow?.memories ?? await storage.readAllMemories()
@@ -764,4 +765,4 @@ export {
764
765
  listMemoryGovernanceRuns,
765
766
  readMemoryGovernanceRunArtifact
766
767
  };
767
- //# sourceMappingURL=chunk-GJ776BC2.js.map
768
+ //# sourceMappingURL=chunk-P2FA65P2.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/maintenance/memory-governance.ts"],"sourcesContent":["import path from \"node:path\";\nimport { lstat, mkdir, readFile, readdir, realpath, rm, writeFile } from \"node:fs/promises\";\nimport { StorageManager } from \"../storage.js\";\nimport { decideLifecycleTransition } from \"../lifecycle.js\";\nimport type { MemoryFile, MemoryStatus } from \"../types.js\";\nimport { RECALL_FALLBACK_DIRS } from \"../utils/category-dir.js\";\nimport { bumpMemoryCorpusVersionForDir } from \"../memory-corpus-version.js\";\nimport { assertPathInsideRoot } from \"../utils/path-containment.js\";\nimport { requestEntityCanonicalIdReconcile } from \"../storage/entity-canonical-id-references.js\";\nimport { excludeSupportPassportPrivateMemories } from \"../support-passport/card-projection.js\";\n\nexport type MemoryGovernanceMode = \"shadow\" | \"apply\";\nexport type MemoryGovernanceReasonCode =\n | \"exact_duplicate\"\n | \"semantic_duplicate_candidate\"\n | \"disputed_memory\"\n | \"speculative_low_confidence\"\n | \"archive_candidate\"\n | \"explicit_capture_review\"\n | \"malformed_import\";\n\nexport interface MemoryGovernanceReviewQueueEntry {\n entryId: string;\n memoryId: string;\n path: string;\n reasonCode: MemoryGovernanceReasonCode;\n severity: \"low\" | \"medium\" | \"high\";\n suggestedAction: \"set_status\" | \"archive\";\n suggestedStatus?: Extract<MemoryStatus, \"pending_review\" | \"quarantined\" | \"rejected\">;\n relatedMemoryIds: string[];\n}\n\nexport interface MemoryGovernanceAppliedAction {\n action: \"set_status\" | \"archive\";\n memoryId: string;\n reasonCode: MemoryGovernanceReviewQueueEntry[\"reasonCode\"];\n beforeStatus: MemoryStatus;\n afterStatus?: MemoryStatus;\n originalPath: string;\n currentPath: string;\n}\n\ninterface MemoryGovernanceRestoreEntry {\n action: MemoryGovernanceAppliedAction[\"action\"];\n memoryId: string;\n reasonCode: MemoryGovernanceReviewQueueEntry[\"reasonCode\"];\n originalPath: string;\n currentPath: string;\n beforeRaw: string;\n expectedCurrentRaw?: string;\n applied: boolean;\n}\n\nexport interface MemoryGovernanceRestoreManifest {\n runId: string;\n createdAt: string;\n entries: MemoryGovernanceRestoreEntry[];\n}\n\nexport interface MemoryGovernanceSummary {\n schemaVersion: 1;\n runId: string;\n traceId: string;\n mode: MemoryGovernanceMode;\n createdAt: string;\n scannedMemories: number;\n reviewQueueCount: number;\n proposedActionCount: number;\n appliedActionCount: number;\n ruleVersion: string;\n}\n\nexport interface MemoryGovernanceMetrics {\n reviewReasons: Record<MemoryGovernanceReasonCode, number>;\n proposedStatuses: Record<string, number>;\n keptMemoryCount: number;\n qualityScore: MemoryGovernanceQualityScore;\n}\n\nexport interface MemoryGovernanceQualityScore {\n score: number;\n maxScore: 100;\n grade: \"excellent\" | \"good\" | \"fair\" | \"poor\";\n deductions: Array<{\n reasonCode: MemoryGovernanceReasonCode;\n count: number;\n pointsLost: number;\n }>;\n}\n\nexport interface MemoryGovernanceTransitionReport {\n proposed: Record<string, MemoryGovernanceAppliedAction[]>;\n applied: Record<string, MemoryGovernanceAppliedAction[]>;\n}\n\nexport interface MemoryGovernanceManifest {\n schemaVersion: 1;\n runId: string;\n traceId: string;\n mode: MemoryGovernanceMode;\n createdAt: string;\n ruleVersion: string;\n artifacts: Record<string, string>;\n}\n\nexport interface MemoryGovernanceRunResult {\n runId: string;\n traceId: string;\n mode: MemoryGovernanceMode;\n summary: MemoryGovernanceSummary;\n summaryPath: string;\n reviewQueuePath: string;\n qualityScorePath: string;\n transitionReportPath: string;\n reportPath: string;\n keptMemoriesPath: string;\n appliedActionsPath: string;\n metricsPath: string;\n manifestPath: string;\n restorePath?: string;\n reviewQueue: MemoryGovernanceReviewQueueEntry[];\n proposedActions: MemoryGovernanceAppliedAction[];\n appliedActions: MemoryGovernanceAppliedAction[];\n}\n\nexport interface RestoreMemoryGovernanceRunResult {\n runId: string;\n restoredActions: number;\n restorePath: string;\n}\n\nexport interface RunMemoryGovernanceOptions {\n memoryDir: string;\n mode: MemoryGovernanceMode;\n now?: Date;\n maxMemories?: number;\n batchSize?: number;\n recentDays?: number;\n}\n\nexport interface RestoreMemoryGovernanceRunOptions {\n memoryDir: string;\n runId: string;\n now?: Date;\n}\n\nexport const RULE_VERSION = \"memory-governance.v2\";\nconst SEMANTIC_DUPLICATE_MIN_TOKENS = 6;\nconst SEMANTIC_DUPLICATE_MIN_JACCARD = 0.66;\nconst QUALITY_SCORE_WEIGHTS: Record<MemoryGovernanceReasonCode, number> = {\n exact_duplicate: 6,\n semantic_duplicate_candidate: 4,\n disputed_memory: 15,\n speculative_low_confidence: 8,\n archive_candidate: 2,\n explicit_capture_review: 5,\n malformed_import: 12,\n};\n\nfunction governanceRunsDir(memoryDir: string): string {\n return path.join(memoryDir, \"state\", \"memory-governance\", \"runs\");\n}\n\nfunction governanceRunDir(memoryDir: string, runId: string): string {\n return path.join(governanceRunsDir(memoryDir), runId);\n}\n\nfunction governanceRestorePath(memoryDir: string, runId: string): string {\n return path.join(governanceRunDir(memoryDir, runId), \"restore.json\");\n}\n\nfunction buildRunId(now: Date): string {\n return `gov-${now.toISOString().replace(/[:.]/g, \"-\")}`;\n}\n\nfunction plannedArchivePath(memoryDir: string, originalPath: string, now: Date): string {\n return path.join(\n memoryDir,\n \"archive\",\n now.toISOString().slice(0, 10),\n path.basename(originalPath),\n );\n}\n\nfunction normalizeContent(content: string): string {\n return content.trim().replace(/\\s+/g, \" \").toLowerCase();\n}\n\nfunction statusOf(memory: MemoryFile): MemoryStatus {\n return memory.frontmatter.status ?? \"active\";\n}\n\nfunction parseIsoMs(value?: string): number | null {\n if (!value) return null;\n const ms = Date.parse(value);\n return Number.isFinite(ms) ? ms : null;\n}\n\nfunction daysSince(value: string | undefined, now: Date): number {\n const ts = parseIsoMs(value);\n if (ts === null) return 365;\n return Math.max(0, (now.getTime() - ts) / 86_400_000);\n}\n\nfunction compareCanonicalPreference(left: MemoryFile, right: MemoryFile): number {\n if (left.frontmatter.confidence !== right.frontmatter.confidence) {\n return (right.frontmatter.confidence ?? 0) - (left.frontmatter.confidence ?? 0);\n }\n return left.frontmatter.created.localeCompare(right.frontmatter.created);\n}\n\nfunction proposedStatusPriority(status: MemoryStatus): number {\n switch (status) {\n case \"quarantined\":\n return 4;\n case \"rejected\":\n return 3;\n case \"archived\":\n return 2;\n case \"pending_review\":\n return 1;\n default:\n return 0;\n }\n}\n\nfunction proposedActionPriority(action: MemoryGovernanceAppliedAction): number {\n if (action.action === \"archive\") {\n return proposedStatusPriority(\"archived\");\n }\n return proposedStatusPriority(action.afterStatus ?? \"active\");\n}\n\nfunction tokenizeSemanticContent(content: string): string[] {\n return Array.from(\n new Set(\n normalizeContent(content)\n .replaceAll(/[^\\p{L}\\p{N}]+/gu, \" \")\n .split(\" \")\n .filter((token) => token.length >= 4),\n ),\n );\n}\n\nfunction jaccardSimilarity(left: string[], right: string[]): number {\n if (left.length === 0 || right.length === 0) return 0;\n const leftSet = new Set(left);\n const rightSet = new Set(right);\n let intersection = 0;\n for (const token of leftSet) {\n if (rightSet.has(token)) intersection += 1;\n }\n const union = new Set([...leftSet, ...rightSet]).size;\n return union > 0 ? intersection / union : 0;\n}\n\nfunction sameSemanticDuplicateScope(left: MemoryFile, right: MemoryFile): boolean {\n if (left.frontmatter.category !== right.frontmatter.category) return false;\n const leftEntityRef = left.frontmatter.entityRef?.trim();\n const rightEntityRef = right.frontmatter.entityRef?.trim();\n if (leftEntityRef && rightEntityRef && leftEntityRef !== rightEntityRef) return false;\n return true;\n}\n\nfunction buildSemanticDuplicateEntries(activeMemories: MemoryFile[]): MemoryGovernanceReviewQueueEntry[] {\n const reviewQueue: MemoryGovernanceReviewQueueEntry[] = [];\n const ordered = [...activeMemories].sort(compareCanonicalPreference);\n const tokensByMemoryId = new Map(\n ordered.map((memory) => [memory.frontmatter.id, tokenizeSemanticContent(memory.content)] as const),\n );\n const claimed = new Set<string>();\n\n for (let candidateIndex = 1; candidateIndex < ordered.length; candidateIndex += 1) {\n const candidate = ordered[candidateIndex];\n if (claimed.has(candidate.frontmatter.id)) continue;\n const candidateTokens = tokensByMemoryId.get(candidate.frontmatter.id) ?? [];\n if (candidateTokens.length < SEMANTIC_DUPLICATE_MIN_TOKENS) continue;\n const candidateNormalized = normalizeContent(candidate.content);\n\n for (let canonicalIndex = 0; canonicalIndex < candidateIndex; canonicalIndex += 1) {\n const canonical = ordered[canonicalIndex];\n if (!sameSemanticDuplicateScope(canonical, candidate)) continue;\n const canonicalNormalized = normalizeContent(canonical.content);\n if (canonicalNormalized === candidateNormalized) continue;\n const canonicalTokens = tokensByMemoryId.get(canonical.frontmatter.id) ?? [];\n if (canonicalTokens.length < SEMANTIC_DUPLICATE_MIN_TOKENS) continue;\n\n const shorter = Math.min(candidateTokens.length, canonicalTokens.length);\n const longer = Math.max(candidateTokens.length, canonicalTokens.length);\n if (shorter / longer < 0.6) continue;\n if (jaccardSimilarity(candidateTokens, canonicalTokens) < SEMANTIC_DUPLICATE_MIN_JACCARD) continue;\n\n reviewQueue.push({\n entryId: `review:${candidate.frontmatter.id}:semantic_duplicate_candidate`,\n memoryId: candidate.frontmatter.id,\n path: candidate.path,\n reasonCode: \"semantic_duplicate_candidate\",\n severity: \"medium\",\n suggestedAction: \"set_status\",\n suggestedStatus: \"pending_review\",\n relatedMemoryIds: [canonical.frontmatter.id],\n });\n claimed.add(candidate.frontmatter.id);\n break;\n }\n }\n\n return reviewQueue;\n}\n\nfunction buildExplicitCaptureReviewEntries(\n memories: MemoryFile[],\n lifecycleEvents: Array<{\n memoryId: string;\n eventType: string;\n reasonCode?: string;\n }>,\n): MemoryGovernanceReviewQueueEntry[] {\n const explicitQueuedIds = new Set(\n lifecycleEvents\n .filter((event) => event.eventType === \"explicit_capture_queued\")\n .map((event) => event.memoryId),\n );\n\n return memories\n .filter((memory) => {\n if (statusOf(memory) !== \"pending_review\") return false;\n const tags = memory.frontmatter.tags ?? [];\n if (tags.includes(\"queued-review\")) return true;\n if (explicitQueuedIds.has(memory.frontmatter.id)) return true;\n return memory.frontmatter.source === \"explicit-review\" || memory.frontmatter.source === \"explicit-inline-review\";\n })\n .map((memory) => ({\n entryId: `review:${memory.frontmatter.id}:explicit_capture_review`,\n memoryId: memory.frontmatter.id,\n path: memory.path,\n reasonCode: \"explicit_capture_review\" as const,\n severity: \"medium\" as const,\n suggestedAction: \"set_status\" as const,\n suggestedStatus: \"pending_review\" as const,\n relatedMemoryIds: [],\n }));\n}\n\n/**\n * List every `*.md` under `root`, refusing to follow symlinked directories or\n * entries that resolve outside `containmentRoot` (a realpath-resolved memory\n * store root). Mirrors the containment guard in consolidation-provenance's\n * walkMarkdownFiles / the CLI walker, reusing the shared assertPathInsideRoot\n * (rule 22). Without this, a symlinked category dir (e.g. decisions/ → outside\n * memoryDir) would be walked and its files surfaced by the malformed-import\n * governance sweep — an out-of-store info leak.\n */\nasync function listMarkdownFiles(root: string, containmentRoot: string): Promise<string[]> {\n const files: string[] = [];\n const walk = async (dir: string) => {\n try {\n const dirStat = await lstat(dir);\n if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) return;\n assertPathInsideRoot(containmentRoot, await realpath(dir), dir);\n const entries = await readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isSymbolicLink()) continue; // never follow symlinked entries\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n await walk(fullPath);\n continue;\n }\n if (entry.isFile() && entry.name.endsWith(\".md\")) {\n try {\n assertPathInsideRoot(containmentRoot, await realpath(fullPath), fullPath);\n } catch {\n continue; // poisoned entry escaping the root — skip it.\n }\n files.push(fullPath);\n }\n }\n } catch {\n // Absent dir (ENOENT), symlinked/out-of-root dir, or containment\n // violation — skip this subtree without aborting the sweep.\n }\n };\n\n await walk(root);\n return files;\n}\n\nfunction malformedMemoryId(memoryDir: string, filePath: string): string {\n return `malformed:${path.relative(memoryDir, filePath).replaceAll(path.sep, \"/\")}`;\n}\n\nasync function buildMalformedImportEntries(\n memoryDir: string,\n storage: StorageManager,\n parsedMemories: MemoryFile[],\n candidateFiles?: string[],\n): Promise<MemoryGovernanceReviewQueueEntry[]> {\n const parsedPaths = new Set(parsedMemories.map((memory) => memory.path));\n // Inspect every recall category directory (RECALL_FALLBACK_DIRS — the single\n // source of truth) so malformed files under newly-routed categories\n // (decisions/, preferences/, ...) are surfaced too, not just facts/ (#1546).\n // Resolve the containment root (realpath) once and thread it into the walker\n // so a symlinked category dir can't escape memoryDir. If memoryDir itself\n // can't be resolved, there is nothing valid to inspect.\n let containmentRoot: string | null = null;\n try {\n containmentRoot = await realpath(memoryDir);\n } catch {\n containmentRoot = null;\n }\n const filesToInspect =\n candidateFiles ??\n (containmentRoot === null\n ? []\n : (\n await Promise.all(\n RECALL_FALLBACK_DIRS.map((dir) =>\n listMarkdownFiles(path.join(memoryDir, dir), containmentRoot as string),\n ),\n )\n ).flat());\n const entries: MemoryGovernanceReviewQueueEntry[] = [];\n\n for (const filePath of filesToInspect) {\n if (parsedPaths.has(filePath)) continue;\n const parsed = await storage.readMemoryByPath(filePath);\n if (parsed) continue;\n entries.push({\n entryId: `review:${malformedMemoryId(memoryDir, filePath)}:malformed_import`,\n memoryId: malformedMemoryId(memoryDir, filePath),\n path: filePath,\n reasonCode: \"malformed_import\",\n severity: \"high\",\n suggestedAction: \"set_status\",\n suggestedStatus: \"quarantined\",\n relatedMemoryIds: [],\n });\n }\n\n return entries;\n}\n\nasync function buildReviewQueue(\n memoryDir: string,\n storage: StorageManager,\n memories: MemoryFile[],\n now: Date,\n options: {\n malformedCandidateFiles?: string[];\n } = {},\n): Promise<MemoryGovernanceReviewQueueEntry[]> {\n const reviewQueue: MemoryGovernanceReviewQueueEntry[] = [];\n const activeMemories = memories.filter((memory) => statusOf(memory) === \"active\");\n const duplicateBuckets = new Map<string, MemoryFile[]>();\n\n for (const memory of activeMemories) {\n const key = `${memory.frontmatter.category}:${normalizeContent(memory.content)}`;\n const bucket = duplicateBuckets.get(key) ?? [];\n bucket.push(memory);\n duplicateBuckets.set(key, bucket);\n }\n\n for (const bucket of duplicateBuckets.values()) {\n if (bucket.length < 2) continue;\n const ordered = [...bucket].sort(compareCanonicalPreference);\n const canonical = ordered[0];\n for (const duplicate of ordered.slice(1)) {\n reviewQueue.push({\n entryId: `review:${duplicate.frontmatter.id}:exact_duplicate`,\n memoryId: duplicate.frontmatter.id,\n path: duplicate.path,\n reasonCode: \"exact_duplicate\",\n severity: \"medium\",\n suggestedAction: \"set_status\",\n suggestedStatus: \"pending_review\",\n relatedMemoryIds: canonical ? [canonical.frontmatter.id] : [],\n });\n }\n }\n\n reviewQueue.push(...buildSemanticDuplicateEntries(activeMemories));\n\n for (const memory of activeMemories) {\n if (memory.frontmatter.verificationState === \"disputed\") {\n reviewQueue.push({\n entryId: `review:${memory.frontmatter.id}:disputed_memory`,\n memoryId: memory.frontmatter.id,\n path: memory.path,\n reasonCode: \"disputed_memory\",\n severity: \"high\",\n suggestedAction: \"set_status\",\n suggestedStatus: \"quarantined\",\n relatedMemoryIds: [],\n });\n }\n\n if (\n memory.frontmatter.confidenceTier === \"speculative\"\n && (memory.frontmatter.confidence ?? 0) <= 0.25\n ) {\n reviewQueue.push({\n entryId: `review:${memory.frontmatter.id}:speculative_low_confidence`,\n memoryId: memory.frontmatter.id,\n path: memory.path,\n reasonCode: \"speculative_low_confidence\",\n severity: \"medium\",\n suggestedAction: \"set_status\",\n suggestedStatus: \"pending_review\",\n relatedMemoryIds: [],\n });\n }\n\n const lifecycle = decideLifecycleTransition(memory, {}, now);\n const staleForArchive = memory.frontmatter.lifecycleState === \"stale\"\n && daysSince(memory.frontmatter.updated ?? memory.frontmatter.created, now) >= 180;\n if ((lifecycle.nextState === \"archived\" && lifecycle.changed) || staleForArchive) {\n reviewQueue.push({\n entryId: `review:${memory.frontmatter.id}:archive_candidate`,\n memoryId: memory.frontmatter.id,\n path: memory.path,\n reasonCode: \"archive_candidate\",\n severity: \"low\",\n suggestedAction: \"archive\",\n relatedMemoryIds: [],\n });\n }\n }\n\n const lifecycleEvents = await storage.readMemoryLifecycleEvents(Number.MAX_SAFE_INTEGER);\n reviewQueue.push(...buildExplicitCaptureReviewEntries(memories, lifecycleEvents));\n reviewQueue.push(...await buildMalformedImportEntries(\n memoryDir,\n storage,\n memories,\n options.malformedCandidateFiles,\n ));\n\n return reviewQueue;\n}\n\nexport function buildProposedActions(\n reviewQueue: MemoryGovernanceReviewQueueEntry[],\n memories: MemoryFile[],\n): MemoryGovernanceAppliedAction[] {\n const byMemory = new Map(memories.map((memory) => [memory.frontmatter.id, memory]));\n const selected = new Map<string, MemoryGovernanceAppliedAction>();\n\n for (const entry of reviewQueue) {\n const memory = byMemory.get(entry.memoryId);\n if (!memory) continue;\n const currentStatus = statusOf(memory);\n if (\n entry.suggestedAction === \"set_status\"\n && entry.suggestedStatus\n && entry.suggestedStatus === currentStatus\n ) {\n continue;\n }\n const candidate: MemoryGovernanceAppliedAction = {\n action: entry.suggestedAction,\n memoryId: entry.memoryId,\n reasonCode: entry.reasonCode,\n beforeStatus: currentStatus,\n afterStatus: entry.suggestedStatus,\n originalPath: memory.path,\n currentPath: memory.path,\n };\n\n const existing = selected.get(entry.memoryId);\n if (!existing) {\n selected.set(entry.memoryId, candidate);\n continue;\n }\n\n const existingPriority = proposedActionPriority(existing);\n const candidatePriority = proposedActionPriority(candidate);\n if (candidatePriority > existingPriority) {\n selected.set(entry.memoryId, candidate);\n }\n }\n\n return [...selected.values()];\n}\n\nfunction buildMetrics(\n reviewQueue: MemoryGovernanceReviewQueueEntry[],\n proposedActions: MemoryGovernanceAppliedAction[],\n scannedMemories: number,\n): MemoryGovernanceMetrics {\n const reviewReasons: MemoryGovernanceMetrics[\"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 proposedStatuses: Record<string, number> = {};\n\n for (const entry of reviewQueue) {\n reviewReasons[entry.reasonCode] += 1;\n }\n\n for (const action of proposedActions) {\n const effectiveStatus = action.afterStatus ?? (action.action === \"archive\" ? \"archived\" : undefined);\n if (!effectiveStatus) continue;\n proposedStatuses[effectiveStatus] = (proposedStatuses[effectiveStatus] ?? 0) + 1;\n }\n\n return {\n reviewReasons,\n proposedStatuses,\n keptMemoryCount: Math.max(0, scannedMemories - proposedActions.length),\n qualityScore: buildQualityScore(reviewReasons),\n };\n}\n\nexport function buildQualityScore(\n reviewReasons: Record<MemoryGovernanceReasonCode, number>,\n): MemoryGovernanceQualityScore {\n const deductions = Object.entries(reviewReasons)\n .map(([reasonCode, count]) => ({\n reasonCode: reasonCode as MemoryGovernanceReasonCode,\n count,\n pointsLost: count * QUALITY_SCORE_WEIGHTS[reasonCode as MemoryGovernanceReasonCode],\n }))\n .filter((entry) => entry.count > 0)\n .sort((left, right) => right.pointsLost - left.pointsLost);\n const totalPointsLost = deductions.reduce((sum, entry) => sum + entry.pointsLost, 0);\n const score = Math.max(0, 100 - totalPointsLost);\n const grade = score >= 90 ? \"excellent\"\n : score >= 75 ? \"good\"\n : score >= 50 ? \"fair\"\n : \"poor\";\n return {\n score,\n maxScore: 100,\n grade,\n deductions,\n };\n}\n\nexport function groupActionsByStatus(\n actions: MemoryGovernanceAppliedAction[],\n): Record<string, MemoryGovernanceAppliedAction[]> {\n const grouped: Record<string, MemoryGovernanceAppliedAction[]> = {};\n for (const action of actions) {\n const status = action.afterStatus ?? (action.action === \"archive\" ? \"archived\" : \"unchanged\");\n const bucket = grouped[status] ?? [];\n bucket.push(action);\n grouped[status] = bucket;\n }\n return grouped;\n}\n\nasync function safeRead(filePath: string): Promise<string | null> {\n try {\n return await readFile(filePath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nasync function persistRestoreManifest(\n memoryDir: string,\n manifest: MemoryGovernanceRestoreManifest,\n): Promise<string> {\n const restorePath = governanceRestorePath(memoryDir, manifest.runId);\n await mkdir(path.dirname(restorePath), { recursive: true });\n await writeFile(restorePath, JSON.stringify(manifest, null, 2), \"utf-8\");\n return restorePath;\n}\n\nasync function writeGovernanceArtifacts(options: {\n memoryDir: string;\n runId: string;\n traceId: string;\n summary: MemoryGovernanceSummary;\n metrics: MemoryGovernanceMetrics;\n qualityScore: MemoryGovernanceQualityScore;\n transitionReport: MemoryGovernanceTransitionReport;\n keptMemoryIds: string[];\n reviewQueue: MemoryGovernanceReviewQueueEntry[];\n proposedActions: MemoryGovernanceAppliedAction[];\n appliedActions: MemoryGovernanceAppliedAction[];\n restoreManifest?: MemoryGovernanceRestoreManifest;\n}): Promise<\n Pick<\n MemoryGovernanceRunResult,\n | \"summaryPath\"\n | \"reviewQueuePath\"\n | \"qualityScorePath\"\n | \"transitionReportPath\"\n | \"reportPath\"\n | \"keptMemoriesPath\"\n | \"appliedActionsPath\"\n | \"metricsPath\"\n | \"manifestPath\"\n | \"restorePath\"\n >\n> {\n const runDir = governanceRunDir(options.memoryDir, options.runId);\n await mkdir(runDir, { recursive: true });\n\n const summaryPath = path.join(runDir, \"summary.json\");\n const reviewQueuePath = path.join(runDir, \"review-queue.json\");\n const qualityScorePath = path.join(runDir, \"quality-score.json\");\n const transitionReportPath = path.join(runDir, \"status-transitions.json\");\n const reportPath = path.join(runDir, \"report.md\");\n const keptMemoriesPath = path.join(runDir, \"kept-memories.json\");\n const appliedActionsPath = path.join(runDir, \"applied-actions.json\");\n const metricsPath = path.join(runDir, \"metrics.json\");\n const manifestPath = path.join(runDir, \"manifest.json\");\n const restorePath = options.restoreManifest ? governanceRestorePath(options.memoryDir, options.runId) : undefined;\n\n await writeFile(summaryPath, JSON.stringify(options.summary, null, 2), \"utf-8\");\n await writeFile(reviewQueuePath, JSON.stringify(options.reviewQueue, null, 2), \"utf-8\");\n await writeFile(qualityScorePath, JSON.stringify(options.qualityScore, null, 2), \"utf-8\");\n await writeFile(transitionReportPath, JSON.stringify(options.transitionReport, null, 2), \"utf-8\");\n await writeFile(keptMemoriesPath, JSON.stringify(options.keptMemoryIds, null, 2), \"utf-8\");\n await writeFile(appliedActionsPath, JSON.stringify(options.appliedActions, null, 2), \"utf-8\");\n await writeFile(metricsPath, JSON.stringify(options.metrics, null, 2), \"utf-8\");\n await writeFile(\n reportPath,\n [\n `# Memory Governance Run ${options.runId}`,\n \"\",\n `- Trace ID: ${options.traceId}`,\n `- Mode: ${options.summary.mode}`,\n `- Scanned memories: ${options.summary.scannedMemories}`,\n `- Kept memories: ${options.metrics.keptMemoryCount}`,\n `- Review queue entries: ${options.summary.reviewQueueCount}`,\n `- Proposed actions: ${options.summary.proposedActionCount}`,\n `- Applied actions: ${options.summary.appliedActionCount}`,\n `- Quality score: ${options.qualityScore.score}/${options.qualityScore.maxScore} (${options.qualityScore.grade})`,\n \"\",\n \"## Metrics\",\n ...Object.entries(options.metrics.reviewReasons).map(([reason, count]) => `- ${reason}: ${count}`),\n ...(Object.entries(options.metrics.proposedStatuses).length > 0\n ? Object.entries(options.metrics.proposedStatuses).map(([status, count]) => `- proposed ${status}: ${count}`)\n : [\"- proposed statuses: (none)\"]),\n \"\",\n \"## Quality Score\",\n ...(options.qualityScore.deductions.length > 0\n ? options.qualityScore.deductions.map((entry) => `- ${entry.reasonCode}: ${entry.count} -> -${entry.pointsLost}`)\n : [\"- no deductions\"]),\n \"\",\n \"## Proposed Actions\",\n ...(options.proposedActions.length > 0\n ? options.proposedActions.map((action) =>\n `- ${action.memoryId}: ${action.action}${action.afterStatus ? ` -> ${action.afterStatus}` : \"\"} [${action.reasonCode}]`,\n )\n : [\"- (empty)\"]),\n \"\",\n \"## Applied Actions\",\n ...(options.appliedActions.length > 0\n ? options.appliedActions.map((action) =>\n `- ${action.memoryId}: ${action.action}${action.afterStatus ? ` -> ${action.afterStatus}` : \"\"} [${action.reasonCode}]`,\n )\n : [\"- (empty)\"]),\n \"\",\n \"## Review Queue\",\n ...(options.reviewQueue.length > 0\n ? options.reviewQueue.map((entry) =>\n `- ${entry.memoryId}: ${entry.reasonCode} -> ${entry.suggestedAction}${entry.suggestedStatus ? ` (${entry.suggestedStatus})` : \"\"}`,\n )\n : [\"- (empty)\"]),\n ].join(\"\\n\"),\n \"utf-8\",\n );\n const manifest: MemoryGovernanceManifest = {\n schemaVersion: 1,\n runId: options.runId,\n traceId: options.traceId,\n mode: options.summary.mode,\n createdAt: options.summary.createdAt,\n ruleVersion: options.summary.ruleVersion,\n artifacts: {\n summary: summaryPath,\n reviewQueue: reviewQueuePath,\n qualityScore: qualityScorePath,\n transitionReport: transitionReportPath,\n report: reportPath,\n keptMemories: keptMemoriesPath,\n appliedActions: appliedActionsPath,\n metrics: metricsPath,\n ...(restorePath ? { restore: restorePath } : {}),\n },\n };\n await writeFile(manifestPath, JSON.stringify(manifest, null, 2), \"utf-8\");\n if (restorePath && options.restoreManifest && await safeRead(restorePath) === null) {\n await writeFile(restorePath, JSON.stringify(options.restoreManifest, null, 2), \"utf-8\");\n }\n\n return {\n summaryPath,\n reviewQueuePath,\n qualityScorePath,\n transitionReportPath,\n reportPath,\n keptMemoriesPath,\n appliedActionsPath,\n metricsPath,\n manifestPath,\n restorePath,\n };\n}\n\nexport async function runMemoryGovernance(\n options: RunMemoryGovernanceOptions,\n): Promise<MemoryGovernanceRunResult> {\n const now = options.now ?? new Date();\n const runId = buildRunId(now);\n const traceId = runId;\n const storage = new StorageManager(options.memoryDir);\n const boundedScan =\n options.maxMemories !== undefined ||\n options.recentDays !== undefined ||\n options.batchSize !== undefined;\n const normalizedRecentDays = typeof options.recentDays === \"number\" && Number.isFinite(options.recentDays)\n ? Math.max(1, Math.floor(options.recentDays))\n : undefined;\n const updatedAfter = normalizedRecentDays !== undefined\n ? new Date(now.getTime() - normalizedRecentDays * 86_400_000)\n : undefined;\n const memoryWindow = boundedScan\n ? await storage.readMemoriesWindow({\n maxMemories: options.maxMemories,\n batchSize: options.batchSize,\n updatedAfter,\n })\n : undefined;\n const memories = excludeSupportPassportPrivateMemories(\n memoryWindow?.memories ?? await storage.readAllMemories(),\n );\n const reviewQueue = await buildReviewQueue(options.memoryDir, storage, memories, now, {\n malformedCandidateFiles: memoryWindow?.filePaths,\n });\n const proposedActions = buildProposedActions(reviewQueue, memories);\n const reviewEntryByActionKey = new Map(\n reviewQueue.map((entry) => [`${entry.memoryId}:${entry.reasonCode}`, entry] as const),\n );\n const metrics = buildMetrics(reviewQueue, proposedActions, memories.length);\n const transitionReport: MemoryGovernanceTransitionReport = {\n proposed: groupActionsByStatus(proposedActions),\n applied: {},\n };\n const memoryPathById = new Map(memories.map((memory) => [memory.frontmatter.id, memory.path] as const));\n const targetedMemoryIds = new Set(proposedActions.map((action) => action.memoryId));\n const keptMemoryIds = memories\n .map((memory) => memory.frontmatter.id)\n .filter((memoryId) => !targetedMemoryIds.has(memoryId));\n const appliedActions: MemoryGovernanceAppliedAction[] = [];\n const restoreEntries: MemoryGovernanceRestoreEntry[] = [];\n const restoreEntryByMemoryId = new Map<string, MemoryGovernanceRestoreEntry>();\n\n if (options.mode === \"apply\") {\n for (const action of proposedActions) {\n const memoryPath = memoryPathById.get(action.memoryId) ?? null;\n if (!memoryPath) continue;\n const memory = await storage.readMemoryByPath(memoryPath);\n if (!memory) continue;\n if (memory.frontmatter.id !== action.memoryId) continue;\n const beforeRaw = await safeRead(memory.path);\n if (!beforeRaw) continue;\n const entry: MemoryGovernanceRestoreEntry = {\n action: action.action,\n memoryId: action.memoryId,\n reasonCode: action.reasonCode,\n originalPath: memory.path,\n currentPath: action.action === \"archive\"\n ? plannedArchivePath(options.memoryDir, memory.path, now)\n : memory.path,\n beforeRaw,\n applied: false,\n };\n restoreEntries.push(entry);\n restoreEntryByMemoryId.set(action.memoryId, entry);\n }\n\n const restoreManifest: MemoryGovernanceRestoreManifest = {\n runId,\n createdAt: now.toISOString(),\n entries: restoreEntries,\n };\n await persistRestoreManifest(options.memoryDir, restoreManifest);\n\n for (const action of proposedActions) {\n const memoryPath = memoryPathById.get(action.memoryId) ?? null;\n if (!memoryPath) continue;\n const memory = await storage.readMemoryByPath(memoryPath);\n if (!memory) continue;\n if (memory.frontmatter.id !== action.memoryId) continue;\n const restoreEntry = restoreEntryByMemoryId.get(action.memoryId);\n if (!restoreEntry) continue;\n\n if (action.action === \"archive\") {\n const reviewEntry = reviewEntryByActionKey.get(`${action.memoryId}:${action.reasonCode}`);\n restoreEntry.applied = true;\n await persistRestoreManifest(options.memoryDir, restoreManifest);\n const archivedPath = await storage.archiveMemory(memory, {\n at: now,\n actor: \"memory-governance.apply\",\n reasonCode: action.reasonCode,\n ruleVersion: RULE_VERSION,\n relatedMemoryIds: reviewEntry?.relatedMemoryIds ?? [],\n correlationId: traceId,\n });\n if (!archivedPath) {\n restoreEntry.applied = false;\n await persistRestoreManifest(options.memoryDir, restoreManifest);\n continue;\n }\n restoreEntry.currentPath = archivedPath;\n restoreEntry.expectedCurrentRaw = await safeRead(archivedPath) ?? undefined;\n await persistRestoreManifest(options.memoryDir, restoreManifest);\n appliedActions.push({\n ...action,\n currentPath: archivedPath,\n afterStatus: \"archived\",\n });\n continue;\n }\n\n if (!action.afterStatus || action.beforeStatus === action.afterStatus) continue;\n const reviewEntry = reviewEntryByActionKey.get(`${action.memoryId}:${action.reasonCode}`);\n restoreEntry.applied = true;\n await persistRestoreManifest(options.memoryDir, restoreManifest);\n const updated = await storage.writeMemoryFrontmatter(memory, {\n status: action.afterStatus,\n updated: now.toISOString(),\n }, {\n actor: \"memory-governance.apply\",\n reasonCode: action.reasonCode,\n ruleVersion: RULE_VERSION,\n relatedMemoryIds: reviewEntry?.relatedMemoryIds ?? [],\n correlationId: traceId,\n });\n if (!updated) {\n restoreEntry.applied = false;\n await persistRestoreManifest(options.memoryDir, restoreManifest);\n continue;\n }\n restoreEntry.expectedCurrentRaw = await safeRead(memory.path) ?? undefined;\n await persistRestoreManifest(options.memoryDir, restoreManifest);\n appliedActions.push({\n ...action,\n currentPath: memory.path,\n });\n }\n }\n\n const summary: MemoryGovernanceSummary = {\n schemaVersion: 1,\n runId,\n traceId,\n mode: options.mode,\n createdAt: now.toISOString(),\n scannedMemories: memories.length,\n reviewQueueCount: reviewQueue.length,\n proposedActionCount: proposedActions.length,\n appliedActionCount: appliedActions.length,\n ruleVersion: RULE_VERSION,\n };\n const restoreManifest = options.mode === \"apply\"\n ? {\n runId,\n createdAt: now.toISOString(),\n entries: restoreEntries,\n }\n : undefined;\n transitionReport.applied = groupActionsByStatus(appliedActions);\n const paths = await writeGovernanceArtifacts({\n memoryDir: options.memoryDir,\n runId,\n traceId,\n summary,\n metrics,\n qualityScore: metrics.qualityScore,\n transitionReport,\n keptMemoryIds,\n reviewQueue,\n proposedActions,\n appliedActions,\n restoreManifest,\n });\n\n return {\n runId,\n traceId,\n mode: options.mode,\n summary,\n ...paths,\n reviewQueue,\n proposedActions,\n appliedActions,\n };\n}\n\nexport async function restoreMemoryGovernanceRun(\n options: RestoreMemoryGovernanceRunOptions,\n): Promise<RestoreMemoryGovernanceRunResult> {\n void options.now;\n const restorePath = governanceRestorePath(options.memoryDir, options.runId);\n const raw = JSON.parse(await readFile(restorePath, \"utf-8\")) as MemoryGovernanceRestoreManifest;\n let restoredActions = 0;\n\n for (const entry of [...raw.entries].reverse()) {\n if (!entry.applied) {\n continue;\n }\n const currentRaw = await safeRead(entry.currentPath);\n if (entry.expectedCurrentRaw && currentRaw !== entry.expectedCurrentRaw) {\n throw new Error(`restore conflict for ${entry.memoryId}: current contents diverged from governance run`);\n }\n if (entry.action === \"archive\") {\n await rm(entry.currentPath, { force: true });\n }\n await mkdir(path.dirname(entry.originalPath), { recursive: true });\n await writeFile(entry.originalPath, entry.beforeRaw, \"utf-8\");\n restoredActions += 1;\n // Restore writes/removes memory files directly (out-of-band — not through a\n // StorageManager mutation). Bump the corpus sentinel PER entry so a\n // same-process or peer readAllMemories rescans mid-batch and never serves a\n // partially-restored corpus (Cursor Medium, #1902).\n bumpMemoryCorpusVersionForDir(options.memoryDir);\n // Restored bytes predate the current migration journal and can carry\n // legacy entity references (issue #2213) — request one reconcile pass.\n await requestEntityCanonicalIdReconcile(path.join(options.memoryDir, \"state\"));\n }\n\n return {\n runId: raw.runId,\n restoredActions,\n restorePath,\n };\n}\n\nexport async function listMemoryGovernanceRuns(memoryDir: string): Promise<string[]> {\n try {\n return (await readdir(governanceRunsDir(memoryDir))).sort().reverse();\n } catch {\n return [];\n }\n}\n\nexport async function readMemoryGovernanceRunArtifact(\n memoryDir: string,\n runId: string,\n): Promise<{\n summary: MemoryGovernanceSummary;\n metrics: MemoryGovernanceMetrics;\n qualityScore: MemoryGovernanceQualityScore;\n keptMemoryIds: string[];\n reviewQueue: MemoryGovernanceReviewQueueEntry[];\n appliedActions: MemoryGovernanceAppliedAction[];\n transitionReport: MemoryGovernanceTransitionReport;\n report: string;\n manifest: MemoryGovernanceManifest;\n restore?: MemoryGovernanceRestoreManifest;\n}> {\n const runDir = governanceRunDir(memoryDir, runId);\n const summary = JSON.parse(await readFile(path.join(runDir, \"summary.json\"), \"utf-8\")) as MemoryGovernanceSummary;\n const metrics = JSON.parse(await readFile(path.join(runDir, \"metrics.json\"), \"utf-8\")) as MemoryGovernanceMetrics;\n metrics.qualityScore ??= buildQualityScore(metrics.reviewReasons);\n const keptMemoryIds = JSON.parse(await readFile(path.join(runDir, \"kept-memories.json\"), \"utf-8\")) as string[];\n const reviewQueue = JSON.parse(\n await readFile(path.join(runDir, \"review-queue.json\"), \"utf-8\"),\n ) as MemoryGovernanceReviewQueueEntry[];\n const appliedActions = JSON.parse(\n await readFile(path.join(runDir, \"applied-actions.json\"), \"utf-8\"),\n ) as MemoryGovernanceAppliedAction[];\n const qualityScoreRaw = await safeRead(path.join(runDir, \"quality-score.json\"));\n const transitionReportRaw = await safeRead(path.join(runDir, \"status-transitions.json\"));\n const manifest = JSON.parse(\n await readFile(path.join(runDir, \"manifest.json\"), \"utf-8\"),\n ) as MemoryGovernanceManifest;\n const report = await readFile(path.join(runDir, \"report.md\"), \"utf-8\");\n const restoreRaw = await safeRead(path.join(runDir, \"restore.json\"));\n const qualityScore = qualityScoreRaw\n ? JSON.parse(qualityScoreRaw) as MemoryGovernanceQualityScore\n : metrics.qualityScore ?? buildQualityScore(metrics.reviewReasons);\n const transitionReport = transitionReportRaw\n ? JSON.parse(transitionReportRaw) as MemoryGovernanceTransitionReport\n : {\n proposed: {},\n applied: groupActionsByStatus(appliedActions),\n };\n return {\n summary,\n metrics,\n qualityScore,\n keptMemoryIds,\n reviewQueue,\n appliedActions,\n transitionReport,\n report,\n manifest,\n restore: restoreRaw ? JSON.parse(restoreRaw) as MemoryGovernanceRestoreManifest : undefined,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,UAAU;AACjB,SAAS,OAAO,OAAO,UAAU,SAAS,UAAU,IAAI,iBAAiB;AAiJlE,IAAM,eAAe;AAC5B,IAAM,gCAAgC;AACtC,IAAM,iCAAiC;AACvC,IAAM,wBAAoE;AAAA,EACxE,iBAAiB;AAAA,EACjB,8BAA8B;AAAA,EAC9B,iBAAiB;AAAA,EACjB,4BAA4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QAAQ,aAAa;AAChE,QAAM,gBAAgB,KAAK,MAAM,MAAM,SAAS,KAAK,KAAK,QAAQ,oBAAoB,GAAG,OAAO,CAAC;AACjG,QAAM,cAAc,KAAK;AAAA,IACvB,MAAM,SAAS,KAAK,KAAK,QAAQ,mBAAmB,GAAG,OAAO;AAAA,EAChE;AACA,QAAM,iBAAiB,KAAK;AAAA,IAC1B,MAAM,SAAS,KAAK,KAAK,QAAQ,sBAAsB,GAAG,OAAO;AAAA,EACnE;AACA,QAAM,kBAAkB,MAAM,SAAS,KAAK,KAAK,QAAQ,oBAAoB,CAAC;AAC9E,QAAM,sBAAsB,MAAM,SAAS,KAAK,KAAK,QAAQ,yBAAyB,CAAC;AACvF,QAAM,WAAW,KAAK;AAAA,IACpB,MAAM,SAAS,KAAK,KAAK,QAAQ,eAAe,GAAG,OAAO;AAAA,EAC5D;AACA,QAAM,SAAS,MAAM,SAAS,KAAK,KAAK,QAAQ,WAAW,GAAG,OAAO;AACrE,QAAM,aAAa,MAAM,SAAS,KAAK,KAAK,QAAQ,cAAc,CAAC;AACnE,QAAM,eAAe,kBACjB,KAAK,MAAM,eAAe,IAC1B,QAAQ,gBAAgB,kBAAkB,QAAQ,aAAa;AACnE,QAAM,mBAAmB,sBACrB,KAAK,MAAM,mBAAmB,IAC9B;AAAA,IACE,UAAU,CAAC;AAAA,IACX,SAAS,qBAAqB,cAAc;AAAA,EAC9C;AACJ,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS,aAAa,KAAK,MAAM,UAAU,IAAuC;AAAA,EACpF;AACF;","names":["restoreManifest","reviewEntry"]}
1
+ {"version":3,"sources":["../src/maintenance/memory-governance.ts"],"sourcesContent":["import path from \"node:path\";\nimport { lstat, mkdir, readFile, readdir, realpath, rm, writeFile } from \"node:fs/promises\";\nimport { StorageManager } from \"../storage.js\";\nimport { decideLifecycleTransition } from \"../lifecycle.js\";\nimport type { MemoryFile, MemoryStatus } from \"../types.js\";\nimport { RECALL_FALLBACK_DIRS } from \"../utils/category-dir.js\";\nimport { bumpMemoryCorpusVersionForDir } from \"../memory-corpus-version.js\";\nimport { assertPathInsideRoot } from \"../utils/path-containment.js\";\nimport { requestEntityCanonicalIdReconcile } from \"../storage/entity-canonical-id-references.js\";\nimport { excludeSupportPassportPrivateMemories } from \"../support-passport/card-projection.js\";\n\nexport type MemoryGovernanceMode = \"shadow\" | \"apply\";\nexport type MemoryGovernanceReasonCode =\n | \"exact_duplicate\"\n | \"semantic_duplicate_candidate\"\n | \"disputed_memory\"\n | \"speculative_low_confidence\"\n | \"archive_candidate\"\n | \"explicit_capture_review\"\n | \"malformed_import\";\n\nexport interface MemoryGovernanceReviewQueueEntry {\n entryId: string;\n memoryId: string;\n path: string;\n reasonCode: MemoryGovernanceReasonCode;\n severity: \"low\" | \"medium\" | \"high\";\n suggestedAction: \"set_status\" | \"archive\";\n suggestedStatus?: Extract<MemoryStatus, \"pending_review\" | \"quarantined\" | \"rejected\">;\n relatedMemoryIds: string[];\n}\n\nexport interface MemoryGovernanceAppliedAction {\n action: \"set_status\" | \"archive\";\n memoryId: string;\n reasonCode: MemoryGovernanceReviewQueueEntry[\"reasonCode\"];\n beforeStatus: MemoryStatus;\n afterStatus?: MemoryStatus;\n originalPath: string;\n currentPath: string;\n}\n\ninterface MemoryGovernanceRestoreEntry {\n action: MemoryGovernanceAppliedAction[\"action\"];\n memoryId: string;\n reasonCode: MemoryGovernanceReviewQueueEntry[\"reasonCode\"];\n originalPath: string;\n currentPath: string;\n beforeRaw: string;\n expectedCurrentRaw?: string;\n applied: boolean;\n}\n\nexport interface MemoryGovernanceRestoreManifest {\n runId: string;\n createdAt: string;\n entries: MemoryGovernanceRestoreEntry[];\n}\n\nexport interface MemoryGovernanceSummary {\n schemaVersion: 1;\n runId: string;\n traceId: string;\n mode: MemoryGovernanceMode;\n createdAt: string;\n scannedMemories: number;\n reviewQueueCount: number;\n proposedActionCount: number;\n appliedActionCount: number;\n ruleVersion: string;\n}\n\nexport interface MemoryGovernanceMetrics {\n reviewReasons: Record<MemoryGovernanceReasonCode, number>;\n proposedStatuses: Record<string, number>;\n keptMemoryCount: number;\n qualityScore: MemoryGovernanceQualityScore;\n}\n\nexport interface MemoryGovernanceQualityScore {\n score: number;\n maxScore: 100;\n grade: \"excellent\" | \"good\" | \"fair\" | \"poor\";\n deductions: Array<{\n reasonCode: MemoryGovernanceReasonCode;\n count: number;\n pointsLost: number;\n }>;\n}\n\nexport interface MemoryGovernanceTransitionReport {\n proposed: Record<string, MemoryGovernanceAppliedAction[]>;\n applied: Record<string, MemoryGovernanceAppliedAction[]>;\n}\n\nexport interface MemoryGovernanceManifest {\n schemaVersion: 1;\n runId: string;\n traceId: string;\n mode: MemoryGovernanceMode;\n createdAt: string;\n ruleVersion: string;\n artifacts: Record<string, string>;\n}\n\nexport interface MemoryGovernanceRunResult {\n runId: string;\n traceId: string;\n mode: MemoryGovernanceMode;\n summary: MemoryGovernanceSummary;\n summaryPath: string;\n reviewQueuePath: string;\n qualityScorePath: string;\n transitionReportPath: string;\n reportPath: string;\n keptMemoriesPath: string;\n appliedActionsPath: string;\n metricsPath: string;\n manifestPath: string;\n restorePath?: string;\n reviewQueue: MemoryGovernanceReviewQueueEntry[];\n proposedActions: MemoryGovernanceAppliedAction[];\n appliedActions: MemoryGovernanceAppliedAction[];\n}\n\nexport interface RestoreMemoryGovernanceRunResult {\n runId: string;\n restoredActions: number;\n restorePath: string;\n}\n\nexport interface RunMemoryGovernanceOptions {\n memoryDir: string;\n mode: MemoryGovernanceMode;\n now?: Date;\n maxMemories?: number;\n batchSize?: number;\n recentDays?: number;\n}\n\nexport interface RestoreMemoryGovernanceRunOptions {\n memoryDir: string;\n runId: string;\n now?: Date;\n}\n\nexport const RULE_VERSION = \"memory-governance.v2\";\nconst SEMANTIC_DUPLICATE_MIN_TOKENS = 6;\nconst SEMANTIC_DUPLICATE_MIN_JACCARD = 0.66;\nconst QUALITY_SCORE_WEIGHTS: Record<MemoryGovernanceReasonCode, number> = {\n exact_duplicate: 6,\n semantic_duplicate_candidate: 4,\n disputed_memory: 15,\n speculative_low_confidence: 8,\n archive_candidate: 2,\n explicit_capture_review: 5,\n malformed_import: 12,\n};\n\nfunction governanceRunsDir(memoryDir: string): string {\n return path.join(memoryDir, \"state\", \"memory-governance\", \"runs\");\n}\n\nfunction governanceRunDir(memoryDir: string, runId: string): string {\n return path.join(governanceRunsDir(memoryDir), runId);\n}\n\nfunction governanceRestorePath(memoryDir: string, runId: string): string {\n return path.join(governanceRunDir(memoryDir, runId), \"restore.json\");\n}\n\nfunction buildRunId(now: Date): string {\n return `gov-${now.toISOString().replace(/[:.]/g, \"-\")}`;\n}\n\nfunction plannedArchivePath(memoryDir: string, originalPath: string, now: Date): string {\n return path.join(\n memoryDir,\n \"archive\",\n now.toISOString().slice(0, 10),\n path.basename(originalPath),\n );\n}\n\nfunction normalizeContent(content: string): string {\n return content.trim().replace(/\\s+/g, \" \").toLowerCase();\n}\n\nfunction statusOf(memory: MemoryFile): MemoryStatus {\n return memory.frontmatter.status ?? \"active\";\n}\n\nfunction parseIsoMs(value?: string): number | null {\n if (!value) return null;\n const ms = Date.parse(value);\n return Number.isFinite(ms) ? ms : null;\n}\n\nfunction daysSince(value: string | undefined, now: Date): number {\n const ts = parseIsoMs(value);\n if (ts === null) return 365;\n return Math.max(0, (now.getTime() - ts) / 86_400_000);\n}\n\nfunction compareCanonicalPreference(left: MemoryFile, right: MemoryFile): number {\n if (left.frontmatter.confidence !== right.frontmatter.confidence) {\n return (right.frontmatter.confidence ?? 0) - (left.frontmatter.confidence ?? 0);\n }\n return left.frontmatter.created.localeCompare(right.frontmatter.created);\n}\n\nfunction proposedStatusPriority(status: MemoryStatus): number {\n switch (status) {\n case \"quarantined\":\n return 4;\n case \"rejected\":\n return 3;\n case \"archived\":\n return 2;\n case \"pending_review\":\n return 1;\n default:\n return 0;\n }\n}\n\nfunction proposedActionPriority(action: MemoryGovernanceAppliedAction): number {\n if (action.action === \"archive\") {\n return proposedStatusPriority(\"archived\");\n }\n return proposedStatusPriority(action.afterStatus ?? \"active\");\n}\n\nfunction tokenizeSemanticContent(content: string): string[] {\n return Array.from(\n new Set(\n normalizeContent(content)\n .replaceAll(/[^\\p{L}\\p{N}]+/gu, \" \")\n .split(\" \")\n .filter((token) => token.length >= 4),\n ),\n );\n}\n\nfunction jaccardSimilarity(left: string[], right: string[]): number {\n if (left.length === 0 || right.length === 0) return 0;\n const leftSet = new Set(left);\n const rightSet = new Set(right);\n let intersection = 0;\n for (const token of leftSet) {\n if (rightSet.has(token)) intersection += 1;\n }\n const union = new Set([...leftSet, ...rightSet]).size;\n return union > 0 ? intersection / union : 0;\n}\n\nfunction sameSemanticDuplicateScope(left: MemoryFile, right: MemoryFile): boolean {\n if (left.frontmatter.category !== right.frontmatter.category) return false;\n const leftEntityRef = left.frontmatter.entityRef?.trim();\n const rightEntityRef = right.frontmatter.entityRef?.trim();\n if (leftEntityRef && rightEntityRef && leftEntityRef !== rightEntityRef) return false;\n return true;\n}\n\nfunction buildSemanticDuplicateEntries(activeMemories: MemoryFile[]): MemoryGovernanceReviewQueueEntry[] {\n const reviewQueue: MemoryGovernanceReviewQueueEntry[] = [];\n const ordered = [...activeMemories].sort(compareCanonicalPreference);\n const tokensByMemoryId = new Map(\n ordered.map((memory) => [memory.frontmatter.id, tokenizeSemanticContent(memory.content)] as const),\n );\n const claimed = new Set<string>();\n\n for (let candidateIndex = 1; candidateIndex < ordered.length; candidateIndex += 1) {\n const candidate = ordered[candidateIndex];\n if (claimed.has(candidate.frontmatter.id)) continue;\n const candidateTokens = tokensByMemoryId.get(candidate.frontmatter.id) ?? [];\n if (candidateTokens.length < SEMANTIC_DUPLICATE_MIN_TOKENS) continue;\n const candidateNormalized = normalizeContent(candidate.content);\n\n for (let canonicalIndex = 0; canonicalIndex < candidateIndex; canonicalIndex += 1) {\n const canonical = ordered[canonicalIndex];\n if (!sameSemanticDuplicateScope(canonical, candidate)) continue;\n const canonicalNormalized = normalizeContent(canonical.content);\n if (canonicalNormalized === candidateNormalized) continue;\n const canonicalTokens = tokensByMemoryId.get(canonical.frontmatter.id) ?? [];\n if (canonicalTokens.length < SEMANTIC_DUPLICATE_MIN_TOKENS) continue;\n\n const shorter = Math.min(candidateTokens.length, canonicalTokens.length);\n const longer = Math.max(candidateTokens.length, canonicalTokens.length);\n if (shorter / longer < 0.6) continue;\n if (jaccardSimilarity(candidateTokens, canonicalTokens) < SEMANTIC_DUPLICATE_MIN_JACCARD) continue;\n\n reviewQueue.push({\n entryId: `review:${candidate.frontmatter.id}:semantic_duplicate_candidate`,\n memoryId: candidate.frontmatter.id,\n path: candidate.path,\n reasonCode: \"semantic_duplicate_candidate\",\n severity: \"medium\",\n suggestedAction: \"set_status\",\n suggestedStatus: \"pending_review\",\n relatedMemoryIds: [canonical.frontmatter.id],\n });\n claimed.add(candidate.frontmatter.id);\n break;\n }\n }\n\n return reviewQueue;\n}\n\nfunction buildExplicitCaptureReviewEntries(\n memories: MemoryFile[],\n lifecycleEvents: Array<{\n memoryId: string;\n eventType: string;\n reasonCode?: string;\n }>,\n): MemoryGovernanceReviewQueueEntry[] {\n const explicitQueuedIds = new Set(\n lifecycleEvents\n .filter((event) => event.eventType === \"explicit_capture_queued\")\n .map((event) => event.memoryId),\n );\n\n return memories\n .filter((memory) => {\n if (statusOf(memory) !== \"pending_review\") return false;\n const tags = memory.frontmatter.tags ?? [];\n if (tags.includes(\"queued-review\")) return true;\n if (explicitQueuedIds.has(memory.frontmatter.id)) return true;\n return memory.frontmatter.source === \"explicit-review\" || memory.frontmatter.source === \"explicit-inline-review\";\n })\n .map((memory) => ({\n entryId: `review:${memory.frontmatter.id}:explicit_capture_review`,\n memoryId: memory.frontmatter.id,\n path: memory.path,\n reasonCode: \"explicit_capture_review\" as const,\n severity: \"medium\" as const,\n suggestedAction: \"set_status\" as const,\n suggestedStatus: \"pending_review\" as const,\n relatedMemoryIds: [],\n }));\n}\n\n/**\n * List every `*.md` under `root`, refusing to follow symlinked directories or\n * entries that resolve outside `containmentRoot` (a realpath-resolved memory\n * store root). Mirrors the containment guard in consolidation-provenance's\n * walkMarkdownFiles / the CLI walker, reusing the shared assertPathInsideRoot\n * (rule 22). Without this, a symlinked category dir (e.g. decisions/ → outside\n * memoryDir) would be walked and its files surfaced by the malformed-import\n * governance sweep — an out-of-store info leak.\n */\nasync function listMarkdownFiles(root: string, containmentRoot: string): Promise<string[]> {\n const files: string[] = [];\n const walk = async (dir: string) => {\n try {\n const dirStat = await lstat(dir);\n if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) return;\n assertPathInsideRoot(containmentRoot, await realpath(dir), dir);\n const entries = await readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isSymbolicLink()) continue; // never follow symlinked entries\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n await walk(fullPath);\n continue;\n }\n if (entry.isFile() && entry.name.endsWith(\".md\")) {\n try {\n assertPathInsideRoot(containmentRoot, await realpath(fullPath), fullPath);\n } catch {\n continue; // poisoned entry escaping the root — skip it.\n }\n files.push(fullPath);\n }\n }\n } catch {\n // Absent dir (ENOENT), symlinked/out-of-root dir, or containment\n // violation — skip this subtree without aborting the sweep.\n }\n };\n\n await walk(root);\n return files;\n}\n\nfunction malformedMemoryId(memoryDir: string, filePath: string): string {\n return `malformed:${path.relative(memoryDir, filePath).replaceAll(path.sep, \"/\")}`;\n}\n\nasync function buildMalformedImportEntries(\n memoryDir: string,\n storage: StorageManager,\n parsedMemories: MemoryFile[],\n candidateFiles?: string[],\n): Promise<MemoryGovernanceReviewQueueEntry[]> {\n const parsedPaths = new Set(parsedMemories.map((memory) => memory.path));\n // Inspect every recall category directory (RECALL_FALLBACK_DIRS — the single\n // source of truth) so malformed files under newly-routed categories\n // (decisions/, preferences/, ...) are surfaced too, not just facts/ (#1546).\n // Resolve the containment root (realpath) once and thread it into the walker\n // so a symlinked category dir can't escape memoryDir. If memoryDir itself\n // can't be resolved, there is nothing valid to inspect.\n let containmentRoot: string | null = null;\n try {\n containmentRoot = await realpath(memoryDir);\n } catch {\n containmentRoot = null;\n }\n const filesToInspect =\n candidateFiles ??\n (containmentRoot === null\n ? []\n : (\n await Promise.all(\n RECALL_FALLBACK_DIRS.map((dir) =>\n listMarkdownFiles(path.join(memoryDir, dir), containmentRoot as string),\n ),\n )\n ).flat());\n const entries: MemoryGovernanceReviewQueueEntry[] = [];\n\n for (const filePath of filesToInspect) {\n if (parsedPaths.has(filePath)) continue;\n const parsed = await storage.readMemoryByPath(filePath);\n if (parsed) continue;\n entries.push({\n entryId: `review:${malformedMemoryId(memoryDir, filePath)}:malformed_import`,\n memoryId: malformedMemoryId(memoryDir, filePath),\n path: filePath,\n reasonCode: \"malformed_import\",\n severity: \"high\",\n suggestedAction: \"set_status\",\n suggestedStatus: \"quarantined\",\n relatedMemoryIds: [],\n });\n }\n\n return entries;\n}\n\nasync function buildReviewQueue(\n memoryDir: string,\n storage: StorageManager,\n memories: MemoryFile[],\n now: Date,\n options: {\n malformedCandidateFiles?: string[];\n } = {},\n): Promise<MemoryGovernanceReviewQueueEntry[]> {\n const reviewQueue: MemoryGovernanceReviewQueueEntry[] = [];\n const activeMemories = memories.filter((memory) => statusOf(memory) === \"active\");\n const duplicateBuckets = new Map<string, MemoryFile[]>();\n\n for (const memory of activeMemories) {\n const key = `${memory.frontmatter.category}:${normalizeContent(memory.content)}`;\n const bucket = duplicateBuckets.get(key) ?? [];\n bucket.push(memory);\n duplicateBuckets.set(key, bucket);\n }\n\n for (const bucket of duplicateBuckets.values()) {\n if (bucket.length < 2) continue;\n const ordered = [...bucket].sort(compareCanonicalPreference);\n const canonical = ordered[0];\n for (const duplicate of ordered.slice(1)) {\n reviewQueue.push({\n entryId: `review:${duplicate.frontmatter.id}:exact_duplicate`,\n memoryId: duplicate.frontmatter.id,\n path: duplicate.path,\n reasonCode: \"exact_duplicate\",\n severity: \"medium\",\n suggestedAction: \"set_status\",\n suggestedStatus: \"pending_review\",\n relatedMemoryIds: canonical ? [canonical.frontmatter.id] : [],\n });\n }\n }\n\n reviewQueue.push(...buildSemanticDuplicateEntries(activeMemories));\n\n for (const memory of activeMemories) {\n if (memory.frontmatter.verificationState === \"disputed\") {\n reviewQueue.push({\n entryId: `review:${memory.frontmatter.id}:disputed_memory`,\n memoryId: memory.frontmatter.id,\n path: memory.path,\n reasonCode: \"disputed_memory\",\n severity: \"high\",\n suggestedAction: \"set_status\",\n suggestedStatus: \"quarantined\",\n relatedMemoryIds: [],\n });\n }\n\n if (\n memory.frontmatter.confidenceTier === \"speculative\"\n && (memory.frontmatter.confidence ?? 0) <= 0.25\n ) {\n reviewQueue.push({\n entryId: `review:${memory.frontmatter.id}:speculative_low_confidence`,\n memoryId: memory.frontmatter.id,\n path: memory.path,\n reasonCode: \"speculative_low_confidence\",\n severity: \"medium\",\n suggestedAction: \"set_status\",\n suggestedStatus: \"pending_review\",\n relatedMemoryIds: [],\n });\n }\n\n const lifecycle = decideLifecycleTransition(memory, {}, now);\n const staleForArchive = memory.frontmatter.lifecycleState === \"stale\"\n && daysSince(memory.frontmatter.updated ?? memory.frontmatter.created, now) >= 180;\n if ((lifecycle.nextState === \"archived\" && lifecycle.changed) || staleForArchive) {\n reviewQueue.push({\n entryId: `review:${memory.frontmatter.id}:archive_candidate`,\n memoryId: memory.frontmatter.id,\n path: memory.path,\n reasonCode: \"archive_candidate\",\n severity: \"low\",\n suggestedAction: \"archive\",\n relatedMemoryIds: [],\n });\n }\n }\n\n const lifecycleEvents = await storage.readMemoryLifecycleEvents(Number.MAX_SAFE_INTEGER);\n reviewQueue.push(...buildExplicitCaptureReviewEntries(memories, lifecycleEvents));\n reviewQueue.push(...await buildMalformedImportEntries(\n memoryDir,\n storage,\n memories,\n options.malformedCandidateFiles,\n ));\n\n return reviewQueue;\n}\n\nexport function buildProposedActions(\n reviewQueue: MemoryGovernanceReviewQueueEntry[],\n memories: MemoryFile[],\n): MemoryGovernanceAppliedAction[] {\n const byMemory = new Map(memories.map((memory) => [memory.frontmatter.id, memory]));\n const selected = new Map<string, MemoryGovernanceAppliedAction>();\n\n for (const entry of reviewQueue) {\n const memory = byMemory.get(entry.memoryId);\n if (!memory) continue;\n const currentStatus = statusOf(memory);\n if (\n entry.suggestedAction === \"set_status\"\n && entry.suggestedStatus\n && entry.suggestedStatus === currentStatus\n ) {\n continue;\n }\n const candidate: MemoryGovernanceAppliedAction = {\n action: entry.suggestedAction,\n memoryId: entry.memoryId,\n reasonCode: entry.reasonCode,\n beforeStatus: currentStatus,\n afterStatus: entry.suggestedStatus,\n originalPath: memory.path,\n currentPath: memory.path,\n };\n\n const existing = selected.get(entry.memoryId);\n if (!existing) {\n selected.set(entry.memoryId, candidate);\n continue;\n }\n\n const existingPriority = proposedActionPriority(existing);\n const candidatePriority = proposedActionPriority(candidate);\n if (candidatePriority > existingPriority) {\n selected.set(entry.memoryId, candidate);\n }\n }\n\n return [...selected.values()];\n}\n\nfunction buildMetrics(\n reviewQueue: MemoryGovernanceReviewQueueEntry[],\n proposedActions: MemoryGovernanceAppliedAction[],\n scannedMemories: number,\n): MemoryGovernanceMetrics {\n const reviewReasons: MemoryGovernanceMetrics[\"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 proposedStatuses: Record<string, number> = {};\n\n for (const entry of reviewQueue) {\n reviewReasons[entry.reasonCode] += 1;\n }\n\n for (const action of proposedActions) {\n const effectiveStatus = action.afterStatus ?? (action.action === \"archive\" ? \"archived\" : undefined);\n if (!effectiveStatus) continue;\n proposedStatuses[effectiveStatus] = (proposedStatuses[effectiveStatus] ?? 0) + 1;\n }\n\n return {\n reviewReasons,\n proposedStatuses,\n keptMemoryCount: Math.max(0, scannedMemories - proposedActions.length),\n qualityScore: buildQualityScore(reviewReasons),\n };\n}\n\nexport function buildQualityScore(\n reviewReasons: Record<MemoryGovernanceReasonCode, number>,\n): MemoryGovernanceQualityScore {\n const deductions = Object.entries(reviewReasons)\n .map(([reasonCode, count]) => ({\n reasonCode: reasonCode as MemoryGovernanceReasonCode,\n count,\n pointsLost: count * QUALITY_SCORE_WEIGHTS[reasonCode as MemoryGovernanceReasonCode],\n }))\n .filter((entry) => entry.count > 0)\n .sort((left, right) => right.pointsLost - left.pointsLost);\n const totalPointsLost = deductions.reduce((sum, entry) => sum + entry.pointsLost, 0);\n const score = Math.max(0, 100 - totalPointsLost);\n const grade = score >= 90 ? \"excellent\"\n : score >= 75 ? \"good\"\n : score >= 50 ? \"fair\"\n : \"poor\";\n return {\n score,\n maxScore: 100,\n grade,\n deductions,\n };\n}\n\nexport function groupActionsByStatus(\n actions: MemoryGovernanceAppliedAction[],\n): Record<string, MemoryGovernanceAppliedAction[]> {\n const grouped: Record<string, MemoryGovernanceAppliedAction[]> = {};\n for (const action of actions) {\n const status = action.afterStatus ?? (action.action === \"archive\" ? \"archived\" : \"unchanged\");\n const bucket = grouped[status] ?? [];\n bucket.push(action);\n grouped[status] = bucket;\n }\n return grouped;\n}\n\nasync function safeRead(filePath: string): Promise<string | null> {\n try {\n return await readFile(filePath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nasync function persistRestoreManifest(\n memoryDir: string,\n manifest: MemoryGovernanceRestoreManifest,\n): Promise<string> {\n const restorePath = governanceRestorePath(memoryDir, manifest.runId);\n await mkdir(path.dirname(restorePath), { recursive: true });\n await writeFile(restorePath, JSON.stringify(manifest, null, 2), \"utf-8\");\n return restorePath;\n}\n\nasync function writeGovernanceArtifacts(options: {\n memoryDir: string;\n runId: string;\n traceId: string;\n summary: MemoryGovernanceSummary;\n metrics: MemoryGovernanceMetrics;\n qualityScore: MemoryGovernanceQualityScore;\n transitionReport: MemoryGovernanceTransitionReport;\n keptMemoryIds: string[];\n reviewQueue: MemoryGovernanceReviewQueueEntry[];\n proposedActions: MemoryGovernanceAppliedAction[];\n appliedActions: MemoryGovernanceAppliedAction[];\n restoreManifest?: MemoryGovernanceRestoreManifest;\n}): Promise<\n Pick<\n MemoryGovernanceRunResult,\n | \"summaryPath\"\n | \"reviewQueuePath\"\n | \"qualityScorePath\"\n | \"transitionReportPath\"\n | \"reportPath\"\n | \"keptMemoriesPath\"\n | \"appliedActionsPath\"\n | \"metricsPath\"\n | \"manifestPath\"\n | \"restorePath\"\n >\n> {\n const runDir = governanceRunDir(options.memoryDir, options.runId);\n await mkdir(runDir, { recursive: true });\n\n const summaryPath = path.join(runDir, \"summary.json\");\n const reviewQueuePath = path.join(runDir, \"review-queue.json\");\n const qualityScorePath = path.join(runDir, \"quality-score.json\");\n const transitionReportPath = path.join(runDir, \"status-transitions.json\");\n const reportPath = path.join(runDir, \"report.md\");\n const keptMemoriesPath = path.join(runDir, \"kept-memories.json\");\n const appliedActionsPath = path.join(runDir, \"applied-actions.json\");\n const metricsPath = path.join(runDir, \"metrics.json\");\n const manifestPath = path.join(runDir, \"manifest.json\");\n const restorePath = options.restoreManifest ? governanceRestorePath(options.memoryDir, options.runId) : undefined;\n\n await writeFile(summaryPath, JSON.stringify(options.summary, null, 2), \"utf-8\");\n await writeFile(reviewQueuePath, JSON.stringify(options.reviewQueue, null, 2), \"utf-8\");\n await writeFile(qualityScorePath, JSON.stringify(options.qualityScore, null, 2), \"utf-8\");\n await writeFile(transitionReportPath, JSON.stringify(options.transitionReport, null, 2), \"utf-8\");\n await writeFile(keptMemoriesPath, JSON.stringify(options.keptMemoryIds, null, 2), \"utf-8\");\n await writeFile(appliedActionsPath, JSON.stringify(options.appliedActions, null, 2), \"utf-8\");\n await writeFile(metricsPath, JSON.stringify(options.metrics, null, 2), \"utf-8\");\n await writeFile(\n reportPath,\n [\n `# Memory Governance Run ${options.runId}`,\n \"\",\n `- Trace ID: ${options.traceId}`,\n `- Mode: ${options.summary.mode}`,\n `- Scanned memories: ${options.summary.scannedMemories}`,\n `- Kept memories: ${options.metrics.keptMemoryCount}`,\n `- Review queue entries: ${options.summary.reviewQueueCount}`,\n `- Proposed actions: ${options.summary.proposedActionCount}`,\n `- Applied actions: ${options.summary.appliedActionCount}`,\n `- Quality score: ${options.qualityScore.score}/${options.qualityScore.maxScore} (${options.qualityScore.grade})`,\n \"\",\n \"## Metrics\",\n ...Object.entries(options.metrics.reviewReasons).map(([reason, count]) => `- ${reason}: ${count}`),\n ...(Object.entries(options.metrics.proposedStatuses).length > 0\n ? Object.entries(options.metrics.proposedStatuses).map(([status, count]) => `- proposed ${status}: ${count}`)\n : [\"- proposed statuses: (none)\"]),\n \"\",\n \"## Quality Score\",\n ...(options.qualityScore.deductions.length > 0\n ? options.qualityScore.deductions.map((entry) => `- ${entry.reasonCode}: ${entry.count} -> -${entry.pointsLost}`)\n : [\"- no deductions\"]),\n \"\",\n \"## Proposed Actions\",\n ...(options.proposedActions.length > 0\n ? options.proposedActions.map((action) =>\n `- ${action.memoryId}: ${action.action}${action.afterStatus ? ` -> ${action.afterStatus}` : \"\"} [${action.reasonCode}]`,\n )\n : [\"- (empty)\"]),\n \"\",\n \"## Applied Actions\",\n ...(options.appliedActions.length > 0\n ? options.appliedActions.map((action) =>\n `- ${action.memoryId}: ${action.action}${action.afterStatus ? ` -> ${action.afterStatus}` : \"\"} [${action.reasonCode}]`,\n )\n : [\"- (empty)\"]),\n \"\",\n \"## Review Queue\",\n ...(options.reviewQueue.length > 0\n ? options.reviewQueue.map((entry) =>\n `- ${entry.memoryId}: ${entry.reasonCode} -> ${entry.suggestedAction}${entry.suggestedStatus ? ` (${entry.suggestedStatus})` : \"\"}`,\n )\n : [\"- (empty)\"]),\n ].join(\"\\n\"),\n \"utf-8\",\n );\n const manifest: MemoryGovernanceManifest = {\n schemaVersion: 1,\n runId: options.runId,\n traceId: options.traceId,\n mode: options.summary.mode,\n createdAt: options.summary.createdAt,\n ruleVersion: options.summary.ruleVersion,\n artifacts: {\n summary: summaryPath,\n reviewQueue: reviewQueuePath,\n qualityScore: qualityScorePath,\n transitionReport: transitionReportPath,\n report: reportPath,\n keptMemories: keptMemoriesPath,\n appliedActions: appliedActionsPath,\n metrics: metricsPath,\n ...(restorePath ? { restore: restorePath } : {}),\n },\n };\n await writeFile(manifestPath, JSON.stringify(manifest, null, 2), \"utf-8\");\n if (restorePath && options.restoreManifest && await safeRead(restorePath) === null) {\n await writeFile(restorePath, JSON.stringify(options.restoreManifest, null, 2), \"utf-8\");\n }\n\n return {\n summaryPath,\n reviewQueuePath,\n qualityScorePath,\n transitionReportPath,\n reportPath,\n keptMemoriesPath,\n appliedActionsPath,\n metricsPath,\n manifestPath,\n restorePath,\n };\n}\n\nexport async function runMemoryGovernance(\n options: RunMemoryGovernanceOptions,\n): Promise<MemoryGovernanceRunResult> {\n const now = options.now ?? new Date();\n const runId = buildRunId(now);\n const traceId = runId;\n const storage = new StorageManager(options.memoryDir);\n const boundedScan =\n options.maxMemories !== undefined ||\n options.recentDays !== undefined ||\n options.batchSize !== undefined;\n const normalizedRecentDays = typeof options.recentDays === \"number\" && Number.isFinite(options.recentDays)\n ? Math.max(1, Math.floor(options.recentDays))\n : undefined;\n const updatedAfter = normalizedRecentDays !== undefined\n ? new Date(now.getTime() - normalizedRecentDays * 86_400_000)\n : undefined;\n const memoryWindow = boundedScan\n ? await storage.readMemoriesWindow({\n maxMemories: options.maxMemories,\n batchSize: options.batchSize,\n updatedAfter,\n includeMalformedPaths: true,\n })\n : undefined;\n const memories = excludeSupportPassportPrivateMemories(\n memoryWindow?.memories ?? await storage.readAllMemories(),\n );\n const reviewQueue = await buildReviewQueue(options.memoryDir, storage, memories, now, {\n malformedCandidateFiles: memoryWindow?.filePaths,\n });\n const proposedActions = buildProposedActions(reviewQueue, memories);\n const reviewEntryByActionKey = new Map(\n reviewQueue.map((entry) => [`${entry.memoryId}:${entry.reasonCode}`, entry] as const),\n );\n const metrics = buildMetrics(reviewQueue, proposedActions, memories.length);\n const transitionReport: MemoryGovernanceTransitionReport = {\n proposed: groupActionsByStatus(proposedActions),\n applied: {},\n };\n const memoryPathById = new Map(memories.map((memory) => [memory.frontmatter.id, memory.path] as const));\n const targetedMemoryIds = new Set(proposedActions.map((action) => action.memoryId));\n const keptMemoryIds = memories\n .map((memory) => memory.frontmatter.id)\n .filter((memoryId) => !targetedMemoryIds.has(memoryId));\n const appliedActions: MemoryGovernanceAppliedAction[] = [];\n const restoreEntries: MemoryGovernanceRestoreEntry[] = [];\n const restoreEntryByMemoryId = new Map<string, MemoryGovernanceRestoreEntry>();\n\n if (options.mode === \"apply\") {\n for (const action of proposedActions) {\n const memoryPath = memoryPathById.get(action.memoryId) ?? null;\n if (!memoryPath) continue;\n const memory = await storage.readMemoryByPath(memoryPath);\n if (!memory) continue;\n if (memory.frontmatter.id !== action.memoryId) continue;\n const beforeRaw = await safeRead(memory.path);\n if (!beforeRaw) continue;\n const entry: MemoryGovernanceRestoreEntry = {\n action: action.action,\n memoryId: action.memoryId,\n reasonCode: action.reasonCode,\n originalPath: memory.path,\n currentPath: action.action === \"archive\"\n ? plannedArchivePath(options.memoryDir, memory.path, now)\n : memory.path,\n beforeRaw,\n applied: false,\n };\n restoreEntries.push(entry);\n restoreEntryByMemoryId.set(action.memoryId, entry);\n }\n\n const restoreManifest: MemoryGovernanceRestoreManifest = {\n runId,\n createdAt: now.toISOString(),\n entries: restoreEntries,\n };\n await persistRestoreManifest(options.memoryDir, restoreManifest);\n\n for (const action of proposedActions) {\n const memoryPath = memoryPathById.get(action.memoryId) ?? null;\n if (!memoryPath) continue;\n const memory = await storage.readMemoryByPath(memoryPath);\n if (!memory) continue;\n if (memory.frontmatter.id !== action.memoryId) continue;\n const restoreEntry = restoreEntryByMemoryId.get(action.memoryId);\n if (!restoreEntry) continue;\n\n if (action.action === \"archive\") {\n const reviewEntry = reviewEntryByActionKey.get(`${action.memoryId}:${action.reasonCode}`);\n restoreEntry.applied = true;\n await persistRestoreManifest(options.memoryDir, restoreManifest);\n const archivedPath = await storage.archiveMemory(memory, {\n at: now,\n actor: \"memory-governance.apply\",\n reasonCode: action.reasonCode,\n ruleVersion: RULE_VERSION,\n relatedMemoryIds: reviewEntry?.relatedMemoryIds ?? [],\n correlationId: traceId,\n });\n if (!archivedPath) {\n restoreEntry.applied = false;\n await persistRestoreManifest(options.memoryDir, restoreManifest);\n continue;\n }\n restoreEntry.currentPath = archivedPath;\n restoreEntry.expectedCurrentRaw = await safeRead(archivedPath) ?? undefined;\n await persistRestoreManifest(options.memoryDir, restoreManifest);\n appliedActions.push({\n ...action,\n currentPath: archivedPath,\n afterStatus: \"archived\",\n });\n continue;\n }\n\n if (!action.afterStatus || action.beforeStatus === action.afterStatus) continue;\n const reviewEntry = reviewEntryByActionKey.get(`${action.memoryId}:${action.reasonCode}`);\n restoreEntry.applied = true;\n await persistRestoreManifest(options.memoryDir, restoreManifest);\n const updated = await storage.writeMemoryFrontmatter(memory, {\n status: action.afterStatus,\n updated: now.toISOString(),\n }, {\n actor: \"memory-governance.apply\",\n reasonCode: action.reasonCode,\n ruleVersion: RULE_VERSION,\n relatedMemoryIds: reviewEntry?.relatedMemoryIds ?? [],\n correlationId: traceId,\n });\n if (!updated) {\n restoreEntry.applied = false;\n await persistRestoreManifest(options.memoryDir, restoreManifest);\n continue;\n }\n restoreEntry.expectedCurrentRaw = await safeRead(memory.path) ?? undefined;\n await persistRestoreManifest(options.memoryDir, restoreManifest);\n appliedActions.push({\n ...action,\n currentPath: memory.path,\n });\n }\n }\n\n const summary: MemoryGovernanceSummary = {\n schemaVersion: 1,\n runId,\n traceId,\n mode: options.mode,\n createdAt: now.toISOString(),\n scannedMemories: memories.length,\n reviewQueueCount: reviewQueue.length,\n proposedActionCount: proposedActions.length,\n appliedActionCount: appliedActions.length,\n ruleVersion: RULE_VERSION,\n };\n const restoreManifest = options.mode === \"apply\"\n ? {\n runId,\n createdAt: now.toISOString(),\n entries: restoreEntries,\n }\n : undefined;\n transitionReport.applied = groupActionsByStatus(appliedActions);\n const paths = await writeGovernanceArtifacts({\n memoryDir: options.memoryDir,\n runId,\n traceId,\n summary,\n metrics,\n qualityScore: metrics.qualityScore,\n transitionReport,\n keptMemoryIds,\n reviewQueue,\n proposedActions,\n appliedActions,\n restoreManifest,\n });\n\n return {\n runId,\n traceId,\n mode: options.mode,\n summary,\n ...paths,\n reviewQueue,\n proposedActions,\n appliedActions,\n };\n}\n\nexport async function restoreMemoryGovernanceRun(\n options: RestoreMemoryGovernanceRunOptions,\n): Promise<RestoreMemoryGovernanceRunResult> {\n void options.now;\n const restorePath = governanceRestorePath(options.memoryDir, options.runId);\n const raw = JSON.parse(await readFile(restorePath, \"utf-8\")) as MemoryGovernanceRestoreManifest;\n let restoredActions = 0;\n\n for (const entry of [...raw.entries].reverse()) {\n if (!entry.applied) {\n continue;\n }\n const currentRaw = await safeRead(entry.currentPath);\n if (entry.expectedCurrentRaw && currentRaw !== entry.expectedCurrentRaw) {\n throw new Error(`restore conflict for ${entry.memoryId}: current contents diverged from governance run`);\n }\n if (entry.action === \"archive\") {\n await rm(entry.currentPath, { force: true });\n }\n await mkdir(path.dirname(entry.originalPath), { recursive: true });\n await writeFile(entry.originalPath, entry.beforeRaw, \"utf-8\");\n restoredActions += 1;\n // Restore writes/removes memory files directly (out-of-band — not through a\n // StorageManager mutation). Bump the corpus sentinel PER entry so a\n // same-process or peer readAllMemories rescans mid-batch and never serves a\n // partially-restored corpus (Cursor Medium, #1902).\n bumpMemoryCorpusVersionForDir(options.memoryDir);\n // Restored bytes predate the current migration journal and can carry\n // legacy entity references (issue #2213) — request one reconcile pass.\n await requestEntityCanonicalIdReconcile(path.join(options.memoryDir, \"state\"));\n }\n\n return {\n runId: raw.runId,\n restoredActions,\n restorePath,\n };\n}\n\nexport async function listMemoryGovernanceRuns(memoryDir: string): Promise<string[]> {\n try {\n return (await readdir(governanceRunsDir(memoryDir))).sort().reverse();\n } catch {\n return [];\n }\n}\n\nexport async function readMemoryGovernanceRunArtifact(\n memoryDir: string,\n runId: string,\n): Promise<{\n summary: MemoryGovernanceSummary;\n metrics: MemoryGovernanceMetrics;\n qualityScore: MemoryGovernanceQualityScore;\n keptMemoryIds: string[];\n reviewQueue: MemoryGovernanceReviewQueueEntry[];\n appliedActions: MemoryGovernanceAppliedAction[];\n transitionReport: MemoryGovernanceTransitionReport;\n report: string;\n manifest: MemoryGovernanceManifest;\n restore?: MemoryGovernanceRestoreManifest;\n}> {\n const runDir = governanceRunDir(memoryDir, runId);\n const summary = JSON.parse(await readFile(path.join(runDir, \"summary.json\"), \"utf-8\")) as MemoryGovernanceSummary;\n const metrics = JSON.parse(await readFile(path.join(runDir, \"metrics.json\"), \"utf-8\")) as MemoryGovernanceMetrics;\n metrics.qualityScore ??= buildQualityScore(metrics.reviewReasons);\n const keptMemoryIds = JSON.parse(await readFile(path.join(runDir, \"kept-memories.json\"), \"utf-8\")) as string[];\n const reviewQueue = JSON.parse(\n await readFile(path.join(runDir, \"review-queue.json\"), \"utf-8\"),\n ) as MemoryGovernanceReviewQueueEntry[];\n const appliedActions = JSON.parse(\n await readFile(path.join(runDir, \"applied-actions.json\"), \"utf-8\"),\n ) as MemoryGovernanceAppliedAction[];\n const qualityScoreRaw = await safeRead(path.join(runDir, \"quality-score.json\"));\n const transitionReportRaw = await safeRead(path.join(runDir, \"status-transitions.json\"));\n const manifest = JSON.parse(\n await readFile(path.join(runDir, \"manifest.json\"), \"utf-8\"),\n ) as MemoryGovernanceManifest;\n const report = await readFile(path.join(runDir, \"report.md\"), \"utf-8\");\n const restoreRaw = await safeRead(path.join(runDir, \"restore.json\"));\n const qualityScore = qualityScoreRaw\n ? JSON.parse(qualityScoreRaw) as MemoryGovernanceQualityScore\n : metrics.qualityScore ?? buildQualityScore(metrics.reviewReasons);\n const transitionReport = transitionReportRaw\n ? JSON.parse(transitionReportRaw) as MemoryGovernanceTransitionReport\n : {\n proposed: {},\n applied: groupActionsByStatus(appliedActions),\n };\n return {\n summary,\n metrics,\n qualityScore,\n keptMemoryIds,\n reviewQueue,\n appliedActions,\n transitionReport,\n report,\n manifest,\n restore: restoreRaw ? JSON.parse(restoreRaw) as MemoryGovernanceRestoreManifest : undefined,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,UAAU;AACjB,SAAS,OAAO,OAAO,UAAU,SAAS,UAAU,IAAI,iBAAiB;AAiJlE,IAAM,eAAe;AAC5B,IAAM,gCAAgC;AACtC,IAAM,iCAAiC;AACvC,IAAM,wBAAoE;AAAA,EACxE,iBAAiB;AAAA,EACjB,8BAA8B;AAAA,EAC9B,iBAAiB;AAAA,EACjB,4BAA4B;AAAA,EAC5B,mBAAmB;AAAA,EACnB,yBAAyB;AAAA,EACzB,kBAAkB;AACpB;AAEA,SAAS,kBAAkB,WAA2B;AACpD,SAAO,KAAK,KAAK,WAAW,SAAS,qBAAqB,MAAM;AAClE;AAEA,SAAS,iBAAiB,WAAmB,OAAuB;AAClE,SAAO,KAAK,KAAK,kBAAkB,SAAS,GAAG,KAAK;AACtD;AAEA,SAAS,sBAAsB,WAAmB,OAAuB;AACvE,SAAO,KAAK,KAAK,iBAAiB,WAAW,KAAK,GAAG,cAAc;AACrE;AAEA,SAAS,WAAW,KAAmB;AACrC,SAAO,OAAO,IAAI,YAAY,EAAE,QAAQ,SAAS,GAAG,CAAC;AACvD;AAEA,SAAS,mBAAmB,WAAmB,cAAsB,KAAmB;AACtF,SAAO,KAAK;AAAA,IACV;AAAA,IACA;AAAA,IACA,IAAI,YAAY,EAAE,MAAM,GAAG,EAAE;AAAA,IAC7B,KAAK,SAAS,YAAY;AAAA,EAC5B;AACF;AAEA,SAAS,iBAAiB,SAAyB;AACjD,SAAO,QAAQ,KAAK,EAAE,QAAQ,QAAQ,GAAG,EAAE,YAAY;AACzD;AAEA,SAAS,SAAS,QAAkC;AAClD,SAAO,OAAO,YAAY,UAAU;AACtC;AAEA,SAAS,WAAW,OAA+B;AACjD,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,KAAK,KAAK,MAAM,KAAK;A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,qBAAqB,cAAc;AAAA,EAC9C;AACJ,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS,aAAa,KAAK,MAAM,UAAU,IAAuC;AAAA,EACpF;AACF;","names":["restoreManifest","reviewEntry"]}
@@ -279,4 +279,4 @@ async function searchHarmonicRetrieval(options) {
279
279
  export {
280
280
  searchHarmonicRetrieval
281
281
  };
282
- //# sourceMappingURL=chunk-43SEBY2M.js.map
282
+ //# sourceMappingURL=chunk-PCRHFB75.js.map
@@ -6,7 +6,7 @@ import {
6
6
  headerConnector,
7
7
  renderExtractionConversation,
8
8
  resolveSourceConnector
9
- } from "./chunk-6CYHUWCO.js";
9
+ } from "./chunk-QGKCM7C4.js";
10
10
  import {
11
11
  ConsolidationResultSchema,
12
12
  DaySummaryResultSchema,
@@ -45,14 +45,14 @@ import {
45
45
  classifyExtractionThrownError,
46
46
  classifyFallbackParseFailure
47
47
  } from "./chunk-BLDBT6HZ.js";
48
- import {
49
- delinearize
50
- } from "./chunk-VEWZZM3H.js";
51
48
  import {
52
49
  buildExtensionsFooterForSummary,
53
50
  formatDaySummaryMemories,
54
51
  loadDaySummaryPrompt
55
52
  } from "./chunk-RPSYDM6C.js";
53
+ import {
54
+ delinearize
55
+ } from "./chunk-VEWZZM3H.js";
56
56
  import {
57
57
  AMBIENT_CAPTURE_PROMPT_SECTION_COMPACT,
58
58
  clampAmbientCaptureConfidence
@@ -65,7 +65,7 @@ import {
65
65
  } from "./chunk-NLE6TSLG.js";
66
66
  import {
67
67
  LocalLlmClient
68
- } from "./chunk-KFBOPMF6.js";
68
+ } from "./chunk-OWC42MDT.js";
69
69
  import {
70
70
  normalizeProcedureSteps
71
71
  } from "./chunk-QDW3E4RD.js";
@@ -2442,4 +2442,4 @@ export {
2442
2442
  shouldEnableLocalExtractionThinking,
2443
2443
  ExtractionEngine
2444
2444
  };
2445
- //# sourceMappingURL=chunk-GN3WRFJY.js.map
2445
+ //# sourceMappingURL=chunk-QC6BILS7.js.map
@@ -2,7 +2,7 @@ import {
2
2
  SupportPassportError,
3
3
  SupportPassportOwnerCreateGrantRequestSchema,
4
4
  getOperation
5
- } from "./chunk-D3LBIUWV.js";
5
+ } from "./chunk-MTF5EFFF.js";
6
6
 
7
7
  // src/support-passport/access-http.ts
8
8
  var OWNER_ROOT = "/engram/v1/support-passport";
@@ -137,4 +137,4 @@ export {
137
137
  SUPPORT_PASSPORT_OWNER_HTTP_ROUTES,
138
138
  handleSupportPassportOwnerHttp
139
139
  };
140
- //# sourceMappingURL=chunk-NISZQW72.js.map
140
+ //# sourceMappingURL=chunk-QDWDVNWU.js.map
@@ -10,7 +10,7 @@ import {
10
10
  } from "./chunk-RZRUV6N2.js";
11
11
  import {
12
12
  deriveSourceConnector
13
- } from "./chunk-XZHE2DEN.js";
13
+ } from "./chunk-BXIMH7MC.js";
14
14
  import {
15
15
  resolvePipelineProcessingCapabilities
16
16
  } from "./chunk-2XRE6FLM.js";
@@ -108,4 +108,4 @@ export {
108
108
  renderExtractionConversation,
109
109
  applyGroundingWithConnector
110
110
  };
111
- //# sourceMappingURL=chunk-6CYHUWCO.js.map
111
+ //# sourceMappingURL=chunk-QGKCM7C4.js.map
@@ -1,3 +1,6 @@
1
+ import {
2
+ ClaudeCodeAdapter
3
+ } from "./chunk-J64TK33U.js";
1
4
  import {
2
5
  CodexAdapter
3
6
  } from "./chunk-RSUYKGGZ.js";
@@ -7,9 +10,6 @@ import {
7
10
  import {
8
11
  ReplitAdapter
9
12
  } from "./chunk-TMSXWOBZ.js";
10
- import {
11
- ClaudeCodeAdapter
12
- } from "./chunk-J64TK33U.js";
13
13
 
14
14
  // src/adapters/registry.ts
15
15
  var AdapterRegistry = class {
@@ -53,4 +53,4 @@ var AdapterRegistry = class {
53
53
  export {
54
54
  AdapterRegistry
55
55
  };
56
- //# sourceMappingURL=chunk-2QSZNTDO.js.map
56
+ //# sourceMappingURL=chunk-RKNJBZ55.js.map
@@ -1,6 +1,11 @@
1
1
  import {
2
2
  resolveEnsureCollectionArgs
3
3
  } from "./chunk-URS5GSM7.js";
4
+ import {
5
+ EMPTY_QMD_STATUS,
6
+ embedQmdFiles,
7
+ fetchQmdStatus
8
+ } from "./chunk-IUM3VSHI.js";
4
9
  import {
5
10
  QMD_PROBE_RETRY_BACKOFF_MS,
6
11
  QMD_PROBE_TIMEOUT_MS,
@@ -13,11 +18,6 @@ import {
13
18
  qmdVersionToString,
14
19
  resolveQmdCapabilities
15
20
  } from "./chunk-ZLQ37WJX.js";
16
- import {
17
- EMPTY_QMD_STATUS,
18
- embedQmdFiles,
19
- fetchQmdStatus
20
- } from "./chunk-IUM3VSHI.js";
21
21
  import {
22
22
  clearQmdResultCaches,
23
23
  getCachedQmdSearch,
@@ -2225,4 +2225,4 @@ export {
2225
2225
  sharedDaemonSessionCountForTest,
2226
2226
  QmdClient
2227
2227
  };
2228
- //# sourceMappingURL=chunk-QCECHYZL.js.map
2228
+ //# sourceMappingURL=chunk-RVO6TCTU.js.map