@remnic/core 9.65.1 → 9.65.3

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 (576) hide show
  1. package/dist/access-admin-ops-surface.d.ts +44 -44
  2. package/dist/access-admin-ops-surface.js +36 -35
  3. package/dist/access-authorization-probe.d.ts +39 -40
  4. package/dist/access-authorization-probe.js +37 -36
  5. package/dist/access-boundary.d.ts +41 -185
  6. package/dist/access-boundary.js +36 -35
  7. package/dist/access-cli.js +110 -107
  8. package/dist/access-cli.js.map +1 -1
  9. package/dist/access-coding-context-resolution.d.ts +3 -1
  10. package/dist/access-extraction-force-flush.d.ts +25 -25
  11. package/dist/access-extraction-force-flush.js +36 -35
  12. package/dist/access-health-types.d.ts +3 -1
  13. package/dist/access-http-lcm-compaction.d.ts +39 -39
  14. package/dist/access-http-lifecycle-flush.d.ts +40 -41
  15. package/dist/access-http-offline-stream.d.ts +25 -25
  16. package/dist/access-http-query.d.ts +4 -2
  17. package/dist/access-http-query.js +38 -37
  18. package/dist/access-http.d.ts +51 -44
  19. package/dist/access-http.js +57 -56
  20. package/dist/access-identity-continuity-surface.d.ts +12 -12
  21. package/dist/access-identity-continuity-surface.js +36 -35
  22. package/dist/access-lcm-surface.d.ts +27 -27
  23. package/dist/access-lcm-surface.js +36 -35
  24. package/dist/access-mcp-admin-tools.d.ts +9 -1
  25. package/dist/access-mcp-admin-tools.js +3 -1
  26. package/dist/access-mcp-output-schemas.js +1 -1
  27. package/dist/access-mcp.d.ts +39 -39
  28. package/dist/access-mcp.js +50 -47
  29. package/dist/access-memory-search-fanout.d.ts +4 -2
  30. package/dist/{access-namespace-preflight-BKUnKsBv.d.ts → access-namespace-preflight-B7Usyz-K.d.ts} +1 -1
  31. package/dist/access-namespace-preflight.d.ts +5 -3
  32. package/dist/access-namespace-preflight.js +36 -35
  33. package/dist/access-observe-write-surface.d.ts +39 -39
  34. package/dist/access-observe-write-surface.js +36 -35
  35. package/dist/access-offline-manifest.d.ts +12 -12
  36. package/dist/access-offline-manifest.js +5 -5
  37. package/dist/access-operations-batch.js +41 -40
  38. package/dist/access-operations.d.ts +46 -47
  39. package/dist/access-operations.js +44 -43
  40. package/dist/access-recall-concurrency.d.ts +40 -40
  41. package/dist/access-recall-concurrency.js +36 -35
  42. package/dist/access-recall-response.d.ts +24 -24
  43. package/dist/access-recall-response.js +36 -35
  44. package/dist/access-recall-surface.d.ts +24 -24
  45. package/dist/access-recall-surface.js +36 -35
  46. package/dist/access-schema.d.ts +139 -139
  47. package/dist/access-schema.js +3 -3
  48. package/dist/{access-service-B1Lbb-nQ.d.ts → access-service-DkaIG3n8.d.ts} +688 -140
  49. package/dist/access-service-helpers.d.ts +40 -40
  50. package/dist/access-service.d.ts +47 -47
  51. package/dist/access-service.js +36 -35
  52. package/dist/access-surface-catalog.d.ts +41 -42
  53. package/dist/access-surface-catalog.js +44 -37
  54. package/dist/access-surface-catalog.js.map +1 -1
  55. package/dist/access-wearables-meetings-surface.d.ts +5 -3
  56. package/dist/action-confidence.d.ts +3 -1
  57. package/dist/active-memory-bridge.d.ts +3 -1
  58. package/dist/active-recall.d.ts +3 -1
  59. package/dist/active-recall.js +11 -1
  60. package/dist/active-recall.js.map +1 -1
  61. package/dist/adapters/index.js +4 -4
  62. package/dist/adapters/registry.js +2 -2
  63. package/dist/ambient-provenance.d.ts +3 -1
  64. package/dist/artifact-search.d.ts +3 -1
  65. package/dist/{auto-sync-5L7EUZ27.js → auto-sync-H64ZCNIR.js} +13 -5
  66. package/dist/{auto-sync-5L7EUZ27.js.map → auto-sync-H64ZCNIR.js.map} +1 -1
  67. package/dist/behavior-learner.d.ts +3 -1
  68. package/dist/behavior-signals.d.ts +3 -1
  69. package/dist/bootstrap.d.ts +12 -12
  70. package/dist/briefing-window.d.ts +4 -2
  71. package/dist/briefing.d.ts +4 -2
  72. package/dist/briefing.js +16 -15
  73. package/dist/buffer-surprise-report.d.ts +3 -1
  74. package/dist/buffer-turn-helpers.d.ts +3 -1
  75. package/dist/buffer.d.ts +4 -2
  76. package/dist/buffer.js +4 -4
  77. package/dist/bulk-import/index.d.ts +5 -3
  78. package/dist/calibration.d.ts +3 -1
  79. package/dist/calibration.js +1 -1
  80. package/dist/capabilities.d.ts +3 -1
  81. package/dist/{capsule-crypto-7FJQINUR.js → capsule-crypto-YO5QJ6L3.js} +2 -2
  82. package/dist/{catalog-DjVhJoRM.d.ts → catalog-CX2BZEJh.d.ts} +1 -1
  83. package/dist/causal-behavior.d.ts +1 -1
  84. package/dist/causal-consolidation.d.ts +3 -1
  85. package/dist/causal-consolidation.js +20 -19
  86. package/dist/causal-consolidation.js.map +1 -1
  87. package/dist/causal-trajectory-graph.d.ts +1 -1
  88. package/dist/{chunk-MIBKEW7A.js → chunk-2VXWFYJE.js} +3 -3
  89. package/dist/{chunk-3YTTAGPB.js → chunk-3DVBKTSO.js} +2 -2
  90. package/dist/{chunk-EIR5VLIH.js → chunk-4K7IW3F7.js} +2 -2
  91. package/dist/chunk-4K7IW3F7.js.map +1 -0
  92. package/dist/{chunk-JTSVMJHV.js → chunk-4XDGYCZI.js} +3 -3
  93. package/dist/chunk-573TEZCD.js +88 -0
  94. package/dist/chunk-573TEZCD.js.map +1 -0
  95. package/dist/{chunk-HQSBYI5X.js → chunk-57HVIG5U.js} +2 -2
  96. package/dist/{chunk-PMVPCZJZ.js → chunk-6433HV72.js} +2 -2
  97. package/dist/{chunk-N6TRHP72.js → chunk-6TAX66IA.js} +2 -2
  98. package/dist/{chunk-AGKIG3YA.js → chunk-6VALIZKG.js} +2 -2
  99. package/dist/{chunk-YQ3CBLL4.js → chunk-76PL4XLG.js} +512 -8
  100. package/dist/chunk-76PL4XLG.js.map +1 -0
  101. package/dist/{chunk-4NZHHGVL.js → chunk-7BDZTALN.js} +4 -1
  102. package/dist/chunk-7BDZTALN.js.map +1 -0
  103. package/dist/{chunk-NS5ETDYD.js → chunk-7BEPVIH3.js} +3 -3
  104. package/dist/{chunk-JG22O53B.js → chunk-7CBKAQIG.js} +2 -1
  105. package/dist/chunk-7CBKAQIG.js.map +1 -0
  106. package/dist/{chunk-LYIZXQYY.js → chunk-7KFIMGMP.js} +2 -2
  107. package/dist/{chunk-LWVO2QZV.js → chunk-7QOO4LGC.js} +56 -56
  108. package/dist/chunk-AAXJNINV.js +55 -0
  109. package/dist/chunk-AAXJNINV.js.map +1 -0
  110. package/dist/{chunk-56BSXSHC.js → chunk-AB3A7EFH.js} +31 -2
  111. package/dist/{chunk-56BSXSHC.js.map → chunk-AB3A7EFH.js.map} +1 -1
  112. package/dist/{chunk-CCTVAVTT.js → chunk-AUO2LJ3K.js} +2 -2
  113. package/dist/{chunk-ALCJRQ72.js → chunk-AYDDB3XI.js} +2 -2
  114. package/dist/{chunk-3TMYV3LP.js → chunk-AYYGRVRP.js} +5 -5
  115. package/dist/{chunk-W6TSGWYS.js → chunk-AZAA5DNP.js} +2 -2
  116. package/dist/{chunk-WTOE7CW4.js → chunk-BKYPJUQL.js} +122 -16
  117. package/dist/chunk-BKYPJUQL.js.map +1 -0
  118. package/dist/{chunk-6JJT5AKI.js → chunk-BQUEAVNW.js} +2 -2
  119. package/dist/{chunk-2NLLXCJG.js → chunk-BXLOS5AJ.js} +2 -2
  120. package/dist/{chunk-CEH2AFXG.js → chunk-C24UZSFW.js} +6 -6
  121. package/dist/{chunk-ZPN7W3OP.js → chunk-CDUUDBWJ.js} +3 -3
  122. package/dist/{chunk-35NN3ZFA.js → chunk-CTVWELNK.js} +21 -3
  123. package/dist/chunk-CTVWELNK.js.map +1 -0
  124. package/dist/{chunk-Y23B2QXP.js → chunk-D27J626P.js} +2 -2
  125. package/dist/{chunk-2572MRP2.js → chunk-DHTQP334.js} +2 -2
  126. package/dist/{chunk-HJQZQUPC.js → chunk-DJZWNKFO.js} +5 -5
  127. package/dist/{chunk-X7Y7WX73.js → chunk-DQEMWVMT.js} +1 -1
  128. package/dist/{chunk-VJ6ECBIP.js → chunk-E4MVQQVX.js} +2 -2
  129. package/dist/{chunk-SYJ6EKKE.js → chunk-EIVIB73I.js} +2 -2
  130. package/dist/{chunk-HUNSEO5U.js → chunk-EV3YFLCB.js} +2 -2
  131. package/dist/{chunk-GEULB2VI.js → chunk-FC7TIRFS.js} +21 -1
  132. package/dist/chunk-FC7TIRFS.js.map +1 -0
  133. package/dist/{chunk-VPGRXEAB.js → chunk-G57LQRP6.js} +2 -2
  134. package/dist/{chunk-BC4QD3FM.js → chunk-GN55KU2P.js} +2 -2
  135. package/dist/{chunk-4W6INNXO.js → chunk-GUXS322H.js} +2 -2
  136. package/dist/{chunk-DBXZZIDU.js → chunk-H5FW4S5Q.js} +434 -693
  137. package/dist/chunk-H5FW4S5Q.js.map +1 -0
  138. package/dist/chunk-I32NKXE2.js +879 -0
  139. package/dist/chunk-I32NKXE2.js.map +1 -0
  140. package/dist/{chunk-3MADV4YC.js → chunk-IQSC3V2E.js} +2 -2
  141. package/dist/{chunk-UYCIS6V5.js → chunk-JCWY73FK.js} +2 -2
  142. package/dist/{chunk-T42L3S6A.js → chunk-LBWQ65SX.js} +4 -4
  143. package/dist/{chunk-MSTNSVXI.js → chunk-LDBFXD4F.js} +2 -1
  144. package/dist/chunk-LDBFXD4F.js.map +1 -0
  145. package/dist/{chunk-CEQF6L5K.js → chunk-LUNJ3WFO.js} +9 -7
  146. package/dist/chunk-LUNJ3WFO.js.map +1 -0
  147. package/dist/{chunk-256FBCVX.js → chunk-M4AHBM72.js} +7 -7
  148. package/dist/{chunk-YEQEGSJA.js → chunk-MBDJJTAT.js} +3 -3
  149. package/dist/{chunk-IAY7YBXS.js → chunk-MRTUN665.js} +2 -2
  150. package/dist/{chunk-JFJ3MHGV.js → chunk-NXKJHSDN.js} +1 -1
  151. package/dist/chunk-NXKJHSDN.js.map +1 -0
  152. package/dist/{chunk-R3AAOKR2.js → chunk-NZWEEALH.js} +2 -2
  153. package/dist/{chunk-I2HTKOOP.js → chunk-ODZG724P.js} +2 -2
  154. package/dist/{chunk-7QFBLYFP.js → chunk-OJD4WS2E.js} +3 -3
  155. package/dist/{chunk-CUS6S7PN.js → chunk-OLWTCWQ2.js} +9 -9
  156. package/dist/chunk-OLWTCWQ2.js.map +1 -0
  157. package/dist/{chunk-53ENM6F6.js → chunk-P4DHENRE.js} +2 -2
  158. package/dist/{chunk-DEFI2QBT.js → chunk-PAYGC3BD.js} +52 -22
  159. package/dist/chunk-PAYGC3BD.js.map +1 -0
  160. package/dist/{chunk-KPBLJCCV.js → chunk-PDVQ5JU3.js} +2 -2
  161. package/dist/{chunk-7BY7V4YX.js → chunk-Q4WONDMJ.js} +4 -3
  162. package/dist/{chunk-7BY7V4YX.js.map → chunk-Q4WONDMJ.js.map} +1 -1
  163. package/dist/{chunk-ESCQ6LY7.js → chunk-QFMO32TO.js} +3 -3
  164. package/dist/{chunk-HQSPXTQO.js → chunk-QXIQPCCN.js} +1 -1
  165. package/dist/{chunk-CFRBTATE.js → chunk-R47WINCY.js} +3 -3
  166. package/dist/{chunk-G72IPMR7.js → chunk-R4OCGPSH.js} +2 -2
  167. package/dist/{chunk-LCU5R6TQ.js → chunk-RAIUTAZZ.js} +22 -3
  168. package/dist/chunk-RAIUTAZZ.js.map +1 -0
  169. package/dist/chunk-RIAM7DND.js +167 -0
  170. package/dist/chunk-RIAM7DND.js.map +1 -0
  171. package/dist/{chunk-VZVP2W4O.js → chunk-RK4WXUI2.js} +2 -2
  172. package/dist/{chunk-JBPKEARU.js → chunk-RKNJBZ55.js} +4 -4
  173. package/dist/{chunk-6L27N6YI.js → chunk-S7Q5CM7E.js} +2 -2
  174. package/dist/{chunk-CTQRPANJ.js → chunk-SVSRPG6M.js} +2 -2
  175. package/dist/{chunk-GXWDWOWP.js → chunk-TDKSCV62.js} +2 -2
  176. package/dist/{chunk-S2VBSTTA.js → chunk-THG4GYIE.js} +2 -2
  177. package/dist/{chunk-IXRC7EQG.js → chunk-TR7DGXGI.js} +2 -2
  178. package/dist/{chunk-63FHSH7E.js → chunk-TYUS5TLG.js} +4 -4
  179. package/dist/{chunk-7PWWGYGO.js → chunk-URHCUXKI.js} +2 -2
  180. package/dist/{chunk-Z54TXZ2F.js → chunk-VA5KMSAE.js} +16 -7
  181. package/dist/chunk-VA5KMSAE.js.map +1 -0
  182. package/dist/{chunk-KQAFEZQX.js → chunk-VDX2J7OX.js} +2 -2
  183. package/dist/{chunk-MUJ4QFUQ.js → chunk-W4BMEGQA.js} +4 -4
  184. package/dist/{chunk-5HK3CJAR.js → chunk-W675UJCZ.js} +2 -2
  185. package/dist/{chunk-3PXVYJMC.js → chunk-WN5FSGLE.js} +2077 -215
  186. package/dist/chunk-WN5FSGLE.js.map +1 -0
  187. package/dist/{chunk-3RHFGGI5.js → chunk-YF6UHWOV.js} +30 -10
  188. package/dist/chunk-YF6UHWOV.js.map +1 -0
  189. package/dist/{chunk-X5SDZMO7.js → chunk-YHCBJULX.js} +2 -2
  190. package/dist/{chunk-5UYSCYR7.js → chunk-Z4RPXHJH.js} +4 -4
  191. package/dist/{cli-Pulnz-qm.d.ts → cli-ChKeYMZv.d.ts} +5 -5
  192. package/dist/cli.d.ts +25 -25
  193. package/dist/cli.js +81 -78
  194. package/dist/coding/pre-action-gate.d.ts +2 -60
  195. package/dist/compounding/engine.d.ts +4 -2
  196. package/dist/compounding/engine.js +17 -16
  197. package/dist/compounding/preference-consolidator.d.ts +3 -1
  198. package/dist/compression-optimizer.d.ts +3 -1
  199. package/dist/config.d.ts +3 -1
  200. package/dist/config.js +11 -1
  201. package/dist/connectors/codex-materialize-runner.d.ts +3 -1
  202. package/dist/connectors/codex-materialize-runner.js +16 -15
  203. package/dist/connectors/codex-materialize.d.ts +3 -1
  204. package/dist/connectors/index.d.ts +3 -1
  205. package/dist/connectors/index.js +16 -15
  206. package/dist/consolidation-provenance-check.d.ts +4 -2
  207. package/dist/consolidation-undo.d.ts +4 -2
  208. package/dist/contradiction/index.d.ts +10 -270
  209. package/dist/contradiction/index.js +20 -7
  210. package/dist/{contradiction-review-QKJH5DKD.js → contradiction-review-WRVLRWHS.js} +6 -2
  211. package/dist/{contradiction-scan-VOTQRRSX.js → contradiction-scan-AKUWPX5N.js} +5 -3
  212. package/dist/converge-config.d.ts +3 -1
  213. package/dist/convergence-refresh.d.ts +4 -2
  214. package/dist/convergence-refresh.js +18 -17
  215. package/dist/conversation-index/backend.d.ts +3 -1
  216. package/dist/conversation-index/chunker.d.ts +3 -1
  217. package/dist/conversation-index/faiss-adapter.d.ts +3 -1
  218. package/dist/conversation-index/indexer.d.ts +3 -1
  219. package/dist/conversation-index/search.d.ts +3 -1
  220. package/dist/corpus-watermark.d.ts +3 -1
  221. package/dist/corpus-watermark.js +18 -17
  222. package/dist/cross-lingual-recall.d.ts +3 -1
  223. package/dist/day-summary.d.ts +3 -1
  224. package/dist/delinearize.d.ts +3 -1
  225. package/dist/dependency-propagation-config.d.ts +3 -1
  226. package/dist/{dependency-propagation-delivery-Co17gxYb.d.ts → dependency-propagation-delivery-B8ZMBBCY.d.ts} +1 -1
  227. package/dist/direct-answer-wiring.d.ts +3 -1
  228. package/dist/direct-answer.d.ts +3 -1
  229. package/dist/embedding-fallback.d.ts +3 -1
  230. package/dist/enrichment/index.d.ts +3 -1
  231. package/dist/entity-origin-fields.d.ts +3 -1
  232. package/dist/entity-retrieval.d.ts +4 -2
  233. package/dist/entity-retrieval.js +16 -15
  234. package/dist/entity-schema.d.ts +3 -1
  235. package/dist/episodic-context.d.ts +3 -1
  236. package/dist/explicit-capture.d.ts +12 -12
  237. package/dist/explicit-capture.js +7 -6
  238. package/dist/external-wiki-access.d.ts +41 -42
  239. package/dist/external-wiki-access.js +37 -36
  240. package/dist/external-wiki-collection-registration.d.ts +3 -1
  241. package/dist/external-wiki-collection.d.ts +3 -1
  242. package/dist/external-wiki-mcp-tools.d.ts +40 -40
  243. package/dist/extraction-error-classification.d.ts +3 -1
  244. package/dist/extraction-faithfulness.d.ts +3 -1
  245. package/dist/extraction-judge-telemetry.d.ts +3 -1
  246. package/dist/extraction-judge-training.d.ts +3 -1
  247. package/dist/extraction-judge.d.ts +3 -1
  248. package/dist/extraction-judge.js +2 -2
  249. package/dist/extraction-liveness.d.ts +3 -1
  250. package/dist/extraction-normalization.d.ts +3 -1
  251. package/dist/extraction-normalization.js +2 -2
  252. package/dist/extraction-prompt.d.ts +4 -2
  253. package/dist/extraction-prompt.js +1 -1
  254. package/dist/extraction-source-grounding-rules.d.ts +3 -1
  255. package/dist/extraction-source-grounding.d.ts +3 -1
  256. package/dist/extraction.d.ts +3 -1
  257. package/dist/extraction.js +22 -21
  258. package/dist/fallback-llm.d.ts +3 -1
  259. package/dist/graph-dashboard-diff.d.ts +3 -1
  260. package/dist/graph-dashboard-key.d.ts +3 -1
  261. package/dist/graph-dashboard-parser.d.ts +3 -1
  262. package/dist/graph-edge-reinforcement.d.ts +3 -1
  263. package/dist/graph-path-reconstruction.d.ts +3 -1
  264. package/dist/graph-path-scoring.d.ts +3 -1
  265. package/dist/graph-snapshot.d.ts +3 -1
  266. package/dist/graph.d.ts +3 -1
  267. package/dist/harmonic-retrieval.js +1 -1
  268. package/dist/importance.d.ts +3 -1
  269. package/dist/importers/index.d.ts +3 -1
  270. package/dist/in-flight-reads.d.ts +3 -1
  271. package/dist/index-CexDrJzC.d.ts +284 -0
  272. package/dist/index.d.ts +946 -707
  273. package/dist/index.js +253 -151
  274. package/dist/intent.d.ts +3 -1
  275. package/dist/lcm/engine.d.ts +3 -1
  276. package/dist/lcm/engine.js +3 -3
  277. package/dist/lcm/index.d.ts +3 -1
  278. package/dist/lcm/index.js +6 -6
  279. package/dist/lcm/tools.d.ts +3 -1
  280. package/dist/lifecycle.d.ts +3 -1
  281. package/dist/live-connectors-runner.d.ts +3 -1
  282. package/dist/local-llm.d.ts +3 -1
  283. package/dist/local-model-endpoint.d.ts +3 -1
  284. package/dist/maintenance/memory-governance.d.ts +3 -1
  285. package/dist/maintenance/memory-governance.js +16 -15
  286. package/dist/maintenance/rebuild-memory-lifecycle-ledger.d.ts +4 -2
  287. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +16 -15
  288. package/dist/maintenance/rebuild-memory-projection.d.ts +4 -2
  289. package/dist/maintenance/rebuild-memory-projection.js +17 -16
  290. package/dist/{maintenance-DiSLtVN7.d.ts → maintenance-nkdtSrVr.d.ts} +3 -3
  291. package/dist/mcp-memory-inspector-app.d.ts +37 -37
  292. package/dist/mcp-read-only-tools.js +1 -1
  293. package/dist/memory-action-policy.d.ts +3 -1
  294. package/dist/memory-cache.d.ts +3 -1
  295. package/dist/memory-lifecycle-ledger-utils.d.ts +3 -1
  296. package/dist/memory-projection-store.d.ts +3 -1
  297. package/dist/memory-provenance.d.ts +3 -1
  298. package/dist/memory-snapshot.d.ts +3 -1
  299. package/dist/memory-subject-cli.d.ts +177 -0
  300. package/dist/memory-subject-cli.js +16 -0
  301. package/dist/memory-subject.d.ts +128 -0
  302. package/dist/memory-subject.js +44 -0
  303. package/dist/memory-subject.js.map +1 -0
  304. package/dist/memory-worth-outcomes.d.ts +7 -4
  305. package/dist/memory-worth-outcomes.js +1 -1
  306. package/dist/models-json.d.ts +3 -1
  307. package/dist/namespaces/migrate.d.ts +5 -3
  308. package/dist/namespaces/migrate.js +17 -16
  309. package/dist/namespaces/principal.d.ts +3 -1
  310. package/dist/namespaces/search.d.ts +3 -1
  311. package/dist/namespaces/search.js +6 -6
  312. package/dist/namespaces/storage.d.ts +5 -3
  313. package/dist/namespaces/storage.js +16 -15
  314. package/dist/native-knowledge.d.ts +3 -1
  315. package/dist/offline-sync-impression-drain.d.ts +3 -1
  316. package/dist/operator-doctor-corpus.d.ts +3 -1
  317. package/dist/operator-doctor-corpus.js +19 -18
  318. package/dist/operator-doctor-replica.d.ts +3 -1
  319. package/dist/operator-toolkit.d.ts +5 -3
  320. package/dist/operator-toolkit.js +29 -24
  321. package/dist/orchestration/compression-guideline-coordinator.d.ts +4 -2
  322. package/dist/orchestration/maintenance.d.ts +6 -4
  323. package/dist/orchestration/maintenance.js +22 -21
  324. package/dist/{orchestrator-DzCaxNS4.d.ts → orchestrator-Bvq1-RQs.d.ts} +23 -9
  325. package/dist/orchestrator.d.ts +12 -12
  326. package/dist/orchestrator.js +111 -108
  327. package/dist/patterns-cli.d.ts +3 -1
  328. package/dist/{pipeline-HJ8DKbFl.d.ts → pipeline-C8vfIiTX.d.ts} +1 -1
  329. package/dist/policy-runtime.d.ts +3 -1
  330. package/dist/proactive-contention.d.ts +3 -1
  331. package/dist/provenance.d.ts +3 -1
  332. package/dist/{public-http-DwXauTX3.d.ts → public-http-Cy0aYbys.d.ts} +1 -1
  333. package/dist/{qmd-BzxluoLt.d.ts → qmd-B9p1SZTZ.d.ts} +1 -1
  334. package/dist/qmd-preflight.d.ts +4 -2
  335. package/dist/qmd-recall-cache.d.ts +3 -1
  336. package/dist/qmd.d.ts +4 -2
  337. package/dist/qmd.js +4 -4
  338. package/dist/recall-concurrency-config.d.ts +3 -1
  339. package/dist/recall-disclosure-escalation.d.ts +3 -1
  340. package/dist/recall-explain-renderer.d.ts +3 -1
  341. package/dist/recall-explain-renderer.js +3 -3
  342. package/dist/recall-memory-map.d.ts +3 -1
  343. package/dist/recall-planner-llm.d.ts +3 -1
  344. package/dist/recall-state.d.ts +3 -1
  345. package/dist/recall-tag-filter.d.ts +3 -1
  346. package/dist/recall-timings.d.ts +3 -1
  347. package/dist/recall-xray-cli.d.ts +3 -1
  348. package/dist/recall-xray-cli.js +4 -4
  349. package/dist/recall-xray-renderer.d.ts +3 -1
  350. package/dist/recall-xray-renderer.js +3 -3
  351. package/dist/recall-xray.d.ts +3 -1
  352. package/dist/recall-xray.js +2 -2
  353. package/dist/reconcile/cursor.d.ts +3 -1
  354. package/dist/reconcile/manifest.d.ts +3 -1
  355. package/dist/reconcile/manifest.js +3 -3
  356. package/dist/reconcile/plan.d.ts +3 -1
  357. package/dist/replay/normalizers/chatgpt.d.ts +3 -1
  358. package/dist/replay/normalizers/claude.d.ts +3 -1
  359. package/dist/replay/normalizers/openclaw.d.ts +3 -1
  360. package/dist/replay/normalizers/shared.d.ts +3 -1
  361. package/dist/replay/runner.d.ts +3 -1
  362. package/dist/replay/types.d.ts +3 -1
  363. package/dist/replica-divergence.d.ts +3 -1
  364. package/dist/replica-peers-config.d.ts +3 -1
  365. package/dist/resolution-4552BNRV.js +36 -0
  366. package/dist/resolution-4552BNRV.js.map +1 -0
  367. package/dist/resolve-auth-token.d.ts +3 -1
  368. package/dist/resume-bundles.js +9 -2
  369. package/dist/retrieval-agents.d.ts +4 -2
  370. package/dist/retrieval-tiers.d.ts +3 -1
  371. package/dist/routing/engine.d.ts +3 -1
  372. package/dist/routing/store.d.ts +3 -1
  373. package/dist/salvage-envelope.d.ts +3 -1
  374. package/dist/salvage-envelope.js +10 -2
  375. package/dist/schemas.d.ts +130 -116
  376. package/dist/schemas.js +1 -1
  377. package/dist/{scope-profiles-CEMZz0t5.d.ts → scope-profiles-DLrRxFWR.d.ts} +1 -1
  378. package/dist/search/embed-helper.d.ts +3 -1
  379. package/dist/search/factory.d.ts +3 -1
  380. package/dist/search/factory.js +5 -5
  381. package/dist/search/index.d.ts +3 -1
  382. package/dist/search/index.js +9 -9
  383. package/dist/search/lancedb-backend.d.ts +3 -1
  384. package/dist/search/meilisearch-backend.d.ts +3 -1
  385. package/dist/search/noop-backend.d.ts +3 -1
  386. package/dist/search/orama-backend.d.ts +3 -1
  387. package/dist/search/port.d.ts +3 -1
  388. package/dist/search/remote-backend.d.ts +3 -1
  389. package/dist/{semantic-TddhF0y7.d.ts → semantic-BalR6EXU.d.ts} +1 -1
  390. package/dist/{semantic-consolidation-D9dYj6vu.d.ts → semantic-consolidation-DlN6xe20.d.ts} +1 -1
  391. package/dist/semantic-consolidation.d.ts +4 -2
  392. package/dist/semantic-consolidation.js +17 -16
  393. package/dist/semantic-rule-promotion.js +16 -15
  394. package/dist/semantic-rule-verifier.d.ts +3 -1
  395. package/dist/semantic-rule-verifier.js +16 -15
  396. package/dist/{service-_qgST_0y.d.ts → service-GkYyVfm9.d.ts} +2 -2
  397. package/dist/session-observer-bands.d.ts +3 -1
  398. package/dist/session-observer-state.d.ts +3 -1
  399. package/dist/shared-context/manager.d.ts +13 -11
  400. package/dist/signal.d.ts +3 -1
  401. package/dist/source-agent-qualifier.d.ts +3 -1
  402. package/dist/source-agent-qualifier.js +18 -17
  403. package/dist/{storage-B9lbNTYE.d.ts → storage-BIDzuKIn.d.ts} +3 -2
  404. package/dist/storage.d.ts +4 -2
  405. package/dist/storage.js +18 -17
  406. package/dist/subject-config.d.ts +40 -0
  407. package/dist/subject-config.js +20 -0
  408. package/dist/subject-config.js.map +1 -0
  409. package/dist/summarizer.d.ts +3 -1
  410. package/dist/summary-snapshot.d.ts +3 -1
  411. package/dist/support-passport/index.d.ts +43 -43
  412. package/dist/support-passport/index.js +39 -38
  413. package/dist/temporal-supersession.d.ts +4 -2
  414. package/dist/temporal-timeline-recall.d.ts +3 -1
  415. package/dist/temporal-validity.d.ts +3 -1
  416. package/dist/threading.d.ts +3 -1
  417. package/dist/tier-migration.d.ts +4 -2
  418. package/dist/tier-routing.d.ts +3 -1
  419. package/dist/topics.d.ts +3 -1
  420. package/dist/transcript.d.ts +3 -1
  421. package/dist/transfer/backup.js +2 -2
  422. package/dist/transfer/capsule-export.js +2 -2
  423. package/dist/transfer/capsule-import.js +2 -2
  424. package/dist/transfer/types.d.ts +86 -86
  425. package/dist/trust-score-stage.d.ts +3 -1
  426. package/dist/trust-score.d.ts +3 -1
  427. package/dist/{types-BrEzuxPA.d.ts → types-BxAcOl5Q.d.ts} +360 -32
  428. package/dist/types.d.ts +3 -1
  429. package/dist/types.js +1 -1
  430. package/dist/utility-runtime.d.ts +3 -1
  431. package/dist/verified-recall.js +16 -15
  432. package/dist/who-knows-cli.d.ts +40 -40
  433. package/dist/who-knows-cli.js +17 -16
  434. package/dist/who-knows.d.ts +42 -42
  435. package/dist/who-knows.js +16 -15
  436. package/dist/write-envelope.d.ts +7 -2
  437. package/dist/write-envelope.js +10 -1
  438. package/package.json +2 -2
  439. package/scripts/build-with-heap.mjs +1 -1
  440. package/src/access-boundary.ts +6 -0
  441. package/src/access-http.ts +6 -5
  442. package/src/access-mcp-admin-tools.ts +38 -0
  443. package/src/access-mcp-output-schemas.ts +20 -0
  444. package/src/access-mcp.ts +8 -8
  445. package/src/access-operations-batch.ts +13 -0
  446. package/src/access-service.ts +112 -0
  447. package/src/access-surface-catalog.test.ts +24 -0
  448. package/src/access-surface-catalog.ts +6 -0
  449. package/src/coding/action-gate.test.ts +341 -0
  450. package/src/coding/action-gate.ts +556 -0
  451. package/src/config.ts +15 -17
  452. package/src/contradiction/contradiction-review.ts +50 -4
  453. package/src/contradiction/contradiction-scan.ts +14 -3
  454. package/src/contradiction/resolution.ts +50 -2
  455. package/src/extraction-prompt.ts +1 -0
  456. package/src/extraction.ts +4 -1
  457. package/src/index.ts +9 -9
  458. package/src/mcp-read-only-tools.ts +1 -0
  459. package/src/memory-subject-cli.ts +135 -0
  460. package/src/memory-subject.test.ts +48 -0
  461. package/src/memory-subject.ts +314 -0
  462. package/src/memory-worth-outcomes.test.ts +6 -2
  463. package/src/memory-worth-outcomes.ts +11 -7
  464. package/src/operator-toolkit.ts +1 -1
  465. package/src/orchestration/extraction-persist.ts +48 -48
  466. package/src/orchestration/recall-internal.ts +6 -5
  467. package/src/orchestration/recall-rerank-coordinator.ts +123 -4
  468. package/src/orchestration/recall-result-formatter.ts +6 -2
  469. package/src/orchestration/recall-search-pipeline.ts +14 -1
  470. package/src/preferences/drift-config.ts +118 -0
  471. package/src/preferences/drift-recall.ts +133 -0
  472. package/src/preferences/drift-types.ts +87 -0
  473. package/src/preferences/index.ts +12 -0
  474. package/src/preferences/preference-drift.test.ts +690 -0
  475. package/src/preferences/preference-drift.ts +724 -0
  476. package/src/procedural/library-maintenance.test.ts +582 -0
  477. package/src/procedural/library-maintenance.ts +546 -0
  478. package/src/procedural/maintenance-config.ts +78 -0
  479. package/src/procedural/procedure-recall.ts +29 -1
  480. package/src/procedural/procedure-stats.ts +20 -0
  481. package/src/review/review-deck-access.test.ts +325 -0
  482. package/src/review/review-deck-http-base.ts +133 -0
  483. package/src/review/review-deck-mutation.test.ts +417 -0
  484. package/src/review/review-deck-mutation.ts +677 -0
  485. package/src/review/review-deck-snapshot.ts +196 -0
  486. package/src/review/review-deck-surface.ts +117 -0
  487. package/src/review/review-deck.test.ts +347 -0
  488. package/src/review/review-deck.ts +311 -0
  489. package/src/schemas.ts +7 -0
  490. package/src/spaces/index.ts +38 -2
  491. package/src/storage.ts +10 -8
  492. package/src/subject-config.ts +80 -0
  493. package/src/types.ts +33 -32
  494. package/src/write-envelope.test.ts +14 -0
  495. package/src/write-envelope.ts +24 -3
  496. package/dist/chunk-35NN3ZFA.js.map +0 -1
  497. package/dist/chunk-3PXVYJMC.js.map +0 -1
  498. package/dist/chunk-3RHFGGI5.js.map +0 -1
  499. package/dist/chunk-4NZHHGVL.js.map +0 -1
  500. package/dist/chunk-CEQF6L5K.js.map +0 -1
  501. package/dist/chunk-CUS6S7PN.js.map +0 -1
  502. package/dist/chunk-DBXZZIDU.js.map +0 -1
  503. package/dist/chunk-DEFI2QBT.js.map +0 -1
  504. package/dist/chunk-EIR5VLIH.js.map +0 -1
  505. package/dist/chunk-GEULB2VI.js.map +0 -1
  506. package/dist/chunk-JFJ3MHGV.js.map +0 -1
  507. package/dist/chunk-JG22O53B.js.map +0 -1
  508. package/dist/chunk-LCU5R6TQ.js.map +0 -1
  509. package/dist/chunk-MDVBCPOS.js +0 -402
  510. package/dist/chunk-MDVBCPOS.js.map +0 -1
  511. package/dist/chunk-MSTNSVXI.js.map +0 -1
  512. package/dist/chunk-WTOE7CW4.js.map +0 -1
  513. package/dist/chunk-YQ3CBLL4.js.map +0 -1
  514. package/dist/chunk-Z54TXZ2F.js.map +0 -1
  515. package/dist/resolution-DKMBPXHI.js +0 -18
  516. /package/dist/{capsule-crypto-7FJQINUR.js.map → capsule-crypto-YO5QJ6L3.js.map} +0 -0
  517. /package/dist/{chunk-MIBKEW7A.js.map → chunk-2VXWFYJE.js.map} +0 -0
  518. /package/dist/{chunk-3YTTAGPB.js.map → chunk-3DVBKTSO.js.map} +0 -0
  519. /package/dist/{chunk-JTSVMJHV.js.map → chunk-4XDGYCZI.js.map} +0 -0
  520. /package/dist/{chunk-HQSBYI5X.js.map → chunk-57HVIG5U.js.map} +0 -0
  521. /package/dist/{chunk-PMVPCZJZ.js.map → chunk-6433HV72.js.map} +0 -0
  522. /package/dist/{chunk-N6TRHP72.js.map → chunk-6TAX66IA.js.map} +0 -0
  523. /package/dist/{chunk-AGKIG3YA.js.map → chunk-6VALIZKG.js.map} +0 -0
  524. /package/dist/{chunk-NS5ETDYD.js.map → chunk-7BEPVIH3.js.map} +0 -0
  525. /package/dist/{chunk-LYIZXQYY.js.map → chunk-7KFIMGMP.js.map} +0 -0
  526. /package/dist/{chunk-LWVO2QZV.js.map → chunk-7QOO4LGC.js.map} +0 -0
  527. /package/dist/{chunk-CCTVAVTT.js.map → chunk-AUO2LJ3K.js.map} +0 -0
  528. /package/dist/{chunk-ALCJRQ72.js.map → chunk-AYDDB3XI.js.map} +0 -0
  529. /package/dist/{chunk-3TMYV3LP.js.map → chunk-AYYGRVRP.js.map} +0 -0
  530. /package/dist/{chunk-W6TSGWYS.js.map → chunk-AZAA5DNP.js.map} +0 -0
  531. /package/dist/{chunk-6JJT5AKI.js.map → chunk-BQUEAVNW.js.map} +0 -0
  532. /package/dist/{chunk-2NLLXCJG.js.map → chunk-BXLOS5AJ.js.map} +0 -0
  533. /package/dist/{chunk-CEH2AFXG.js.map → chunk-C24UZSFW.js.map} +0 -0
  534. /package/dist/{chunk-ZPN7W3OP.js.map → chunk-CDUUDBWJ.js.map} +0 -0
  535. /package/dist/{chunk-Y23B2QXP.js.map → chunk-D27J626P.js.map} +0 -0
  536. /package/dist/{chunk-2572MRP2.js.map → chunk-DHTQP334.js.map} +0 -0
  537. /package/dist/{chunk-HJQZQUPC.js.map → chunk-DJZWNKFO.js.map} +0 -0
  538. /package/dist/{chunk-X7Y7WX73.js.map → chunk-DQEMWVMT.js.map} +0 -0
  539. /package/dist/{chunk-VJ6ECBIP.js.map → chunk-E4MVQQVX.js.map} +0 -0
  540. /package/dist/{chunk-SYJ6EKKE.js.map → chunk-EIVIB73I.js.map} +0 -0
  541. /package/dist/{chunk-HUNSEO5U.js.map → chunk-EV3YFLCB.js.map} +0 -0
  542. /package/dist/{chunk-VPGRXEAB.js.map → chunk-G57LQRP6.js.map} +0 -0
  543. /package/dist/{chunk-BC4QD3FM.js.map → chunk-GN55KU2P.js.map} +0 -0
  544. /package/dist/{chunk-4W6INNXO.js.map → chunk-GUXS322H.js.map} +0 -0
  545. /package/dist/{chunk-3MADV4YC.js.map → chunk-IQSC3V2E.js.map} +0 -0
  546. /package/dist/{chunk-UYCIS6V5.js.map → chunk-JCWY73FK.js.map} +0 -0
  547. /package/dist/{chunk-T42L3S6A.js.map → chunk-LBWQ65SX.js.map} +0 -0
  548. /package/dist/{chunk-256FBCVX.js.map → chunk-M4AHBM72.js.map} +0 -0
  549. /package/dist/{chunk-YEQEGSJA.js.map → chunk-MBDJJTAT.js.map} +0 -0
  550. /package/dist/{chunk-IAY7YBXS.js.map → chunk-MRTUN665.js.map} +0 -0
  551. /package/dist/{chunk-R3AAOKR2.js.map → chunk-NZWEEALH.js.map} +0 -0
  552. /package/dist/{chunk-I2HTKOOP.js.map → chunk-ODZG724P.js.map} +0 -0
  553. /package/dist/{chunk-7QFBLYFP.js.map → chunk-OJD4WS2E.js.map} +0 -0
  554. /package/dist/{chunk-53ENM6F6.js.map → chunk-P4DHENRE.js.map} +0 -0
  555. /package/dist/{chunk-KPBLJCCV.js.map → chunk-PDVQ5JU3.js.map} +0 -0
  556. /package/dist/{chunk-ESCQ6LY7.js.map → chunk-QFMO32TO.js.map} +0 -0
  557. /package/dist/{chunk-HQSPXTQO.js.map → chunk-QXIQPCCN.js.map} +0 -0
  558. /package/dist/{chunk-CFRBTATE.js.map → chunk-R47WINCY.js.map} +0 -0
  559. /package/dist/{chunk-G72IPMR7.js.map → chunk-R4OCGPSH.js.map} +0 -0
  560. /package/dist/{chunk-VZVP2W4O.js.map → chunk-RK4WXUI2.js.map} +0 -0
  561. /package/dist/{chunk-JBPKEARU.js.map → chunk-RKNJBZ55.js.map} +0 -0
  562. /package/dist/{chunk-6L27N6YI.js.map → chunk-S7Q5CM7E.js.map} +0 -0
  563. /package/dist/{chunk-CTQRPANJ.js.map → chunk-SVSRPG6M.js.map} +0 -0
  564. /package/dist/{chunk-GXWDWOWP.js.map → chunk-TDKSCV62.js.map} +0 -0
  565. /package/dist/{chunk-S2VBSTTA.js.map → chunk-THG4GYIE.js.map} +0 -0
  566. /package/dist/{chunk-IXRC7EQG.js.map → chunk-TR7DGXGI.js.map} +0 -0
  567. /package/dist/{chunk-63FHSH7E.js.map → chunk-TYUS5TLG.js.map} +0 -0
  568. /package/dist/{chunk-7PWWGYGO.js.map → chunk-URHCUXKI.js.map} +0 -0
  569. /package/dist/{chunk-KQAFEZQX.js.map → chunk-VDX2J7OX.js.map} +0 -0
  570. /package/dist/{chunk-MUJ4QFUQ.js.map → chunk-W4BMEGQA.js.map} +0 -0
  571. /package/dist/{chunk-5HK3CJAR.js.map → chunk-W675UJCZ.js.map} +0 -0
  572. /package/dist/{chunk-X5SDZMO7.js.map → chunk-YHCBJULX.js.map} +0 -0
  573. /package/dist/{chunk-5UYSCYR7.js.map → chunk-Z4RPXHJH.js.map} +0 -0
  574. /package/dist/{contradiction-review-QKJH5DKD.js.map → contradiction-review-WRVLRWHS.js.map} +0 -0
  575. /package/dist/{contradiction-scan-VOTQRRSX.js.map → contradiction-scan-AKUWPX5N.js.map} +0 -0
  576. /package/dist/{resolution-DKMBPXHI.js.map → memory-subject-cli.js.map} +0 -0
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-7T4TOGMS.js";
4
4
  import {
5
5
  defineOperation
6
- } from "./chunk-3PXVYJMC.js";
6
+ } from "./chunk-WN5FSGLE.js";
7
7
 
8
8
  // src/external-wiki-access.ts
9
9
  import { z } from "zod";
@@ -26,4 +26,4 @@ var externalWikiSearchOperation = defineOperation({
26
26
  export {
27
27
  externalWikiSearchOperation
28
28
  };
29
- //# sourceMappingURL=chunk-KPBLJCCV.js.map
29
+ //# sourceMappingURL=chunk-PDVQ5JU3.js.map
@@ -6,7 +6,7 @@ import {
6
6
  migrateUnscopedPairsToNamespace,
7
7
  readPair,
8
8
  writePairs
9
- } from "./chunk-35NN3ZFA.js";
9
+ } from "./chunk-CTVWELNK.js";
10
10
  import {
11
11
  extractJsonCandidates
12
12
  } from "./chunk-RGMVMVMF.js";
@@ -548,6 +548,7 @@ export {
548
548
  verdictCacheSize,
549
549
  judgeContradictionPairs,
550
550
  ACTIVE_STATUSES,
551
- runContradictionScan
551
+ runContradictionScan,
552
+ resolveScanStorage
552
553
  };
553
- //# sourceMappingURL=chunk-7BY7V4YX.js.map
554
+ //# sourceMappingURL=chunk-Q4WONDMJ.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/contradiction/contradiction-judge.ts","../src/contradiction/contradiction-scan.ts"],"sourcesContent":["/**\n * Contradiction Judge — LLM-as-judge for semantic contradiction detection (issue #520).\n *\n * Pairs semantically-similar memories and classifies their relationship.\n * Reuses the extraction-judge adapter pattern but with a contradiction-specific\n * prompt and verdict taxonomy.\n *\n * Design constraints:\n * - Default verdict on any failure is \"needs-user\" (rule 48: least-privileged default).\n * - Never auto-resolve; all verdicts enter the review queue.\n * - Content-hash caching avoids redundant LLM calls across runs.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { log } from \"../logger.js\";\nimport type { PluginConfig } from \"../types.js\";\nimport type { LocalLlmClient } from \"../local-llm.js\";\nimport type { FallbackLlmClient } from \"../fallback-llm.js\";\nimport { extractJsonCandidates } from \"../json-extract.js\";\n\n// ── Types ──────────────────────────────────────────────────────────────────────\n\nexport type ContradictionVerdict =\n | \"contradicts\"\n | \"independent\"\n | \"duplicates\"\n | \"needs-user\";\n\nexport interface ContradictionJudgeInput {\n /** Memory ID of the first fact. */\n memoryIdA: string;\n /** Memory ID of the second fact. */\n memoryIdB: string;\n /** Content text of the first fact. */\n textA: string;\n /** Content text of the second fact. */\n textB: string;\n /** Category of the first fact (optional context). */\n categoryA?: string;\n /** Category of the second fact (optional context). */\n categoryB?: string;\n}\n\nexport interface ContradictionJudgeResult {\n /** Memory IDs of the pair. */\n memoryIdA: string;\n memoryIdB: string;\n /** Verdict from the judge. */\n verdict: ContradictionVerdict;\n /** Human-readable rationale. */\n rationale: string;\n /** Confidence in [0, 1]. */\n confidence: number;\n}\n\nexport interface ContradictionJudgeBatchResult {\n /** Results keyed by pair key (\"idA:idB\"). */\n results: Map<string, ContradictionJudgeResult>;\n /** Number served from cache. */\n cached: number;\n /** Number produced by LLM call. */\n judged: number;\n /** Total wall-clock time in ms. */\n elapsed: number;\n}\n\n// ── Prompt ─────────────────────────────────────────────────────────────────────\n\nconst CONTRADICTION_JUDGE_PROMPT = `You are a memory contradiction classifier. You will receive pairs of stored memories and must classify their semantic relationship.\n\nFor each pair, respond with a JSON array where each element has:\n- \"pairKey\": the pairKey provided in the input\n- \"verdict\": one of \"contradicts\", \"independent\", \"duplicates\", \"needs-user\"\n- \"rationale\": one sentence explaining why\n- \"confidence\": number between 0 and 1\n\nVERDICT DEFINITIONS:\n- \"contradicts\": The two memories make claims that cannot both be true. One must be wrong or outdated.\n- \"duplicates\": The two memories convey essentially the same information (near-paraphrase).\n- \"independent\": The memories are topically similar but do not conflict or duplicate.\n- \"needs-user\": Cannot determine with sufficient confidence; requires human review.\n\nIMPORTANT:\n- Be conservative. When in doubt, prefer \"needs-user\" over a wrong classification.\n- Two memories about the same entity/topic are NOT necessarily contradictory.\n- Temporal changes (\"Joshua uses pnpm\" vs \"Joshua switched to npm\") ARE contradictions.\n- Different aspects of the same entity (\"Joshua uses pnpm\" vs \"Joshua works on Remnic\") are \"independent\".`;\n\n// ── Cache ──────────────────────────────────────────────────────────────────────\n\n/** Module-level fallback cache — only used when caller does not supply one. */\nlet defaultVerdictCache: Map<string, ContradictionJudgeResult> = new Map();\nconst CACHE_MAX = 10_000;\n\nfunction pairKey(idA: string, idB: string): string {\n const sorted = [idA, idB].sort();\n return `${sorted[0]}:${sorted[1]}`;\n}\n\nfunction contentHash(a: ContradictionJudgeInput): string {\n // Sort each side pair to be order-independent (matching pairKey behavior)\n const sides = [\n { text: a.textA.trim(), category: (a.categoryA ?? \"\").trim() },\n { text: a.textB.trim(), category: (a.categoryB ?? \"\").trim() },\n ].sort((left, right) => {\n const leftKey = JSON.stringify(left);\n const rightKey = JSON.stringify(right);\n return leftKey.localeCompare(rightKey);\n });\n const normalized = JSON.stringify(sides);\n return createHash(\"sha256\").update(normalized).digest(\"hex\").slice(0, 16);\n}\n\nexport function createVerdictCache(): Map<string, ContradictionJudgeResult> {\n return new Map();\n}\n\nexport function clearVerdictCache(): void {\n defaultVerdictCache.clear();\n}\n\nexport function verdictCacheSize(): number {\n return defaultVerdictCache.size;\n}\n\n// ── Public API ──────────────────────────────────────────────────────────────────\n\n/**\n * Judge a batch of memory pairs for contradiction.\n *\n * Uses content-hash caching to skip pairs already judged in a prior run.\n * On any LLM failure, all unresolved pairs default to \"needs-user\".\n */\nexport async function judgeContradictionPairs(\n pairs: ContradictionJudgeInput[],\n config: PluginConfig,\n localLlm: LocalLlmClient | null,\n fallbackLlm: FallbackLlmClient | null,\n cache?: Map<string, ContradictionJudgeResult>,\n): Promise<ContradictionJudgeBatchResult> {\n const startTime = Date.now();\n const results = new Map<string, ContradictionJudgeResult>();\n const activeCache = cache ?? defaultVerdictCache;\n let cached = 0;\n let judged = 0;\n\n // Partition into cached vs needs-judging\n const toJudge: ContradictionJudgeInput[] = [];\n for (const pair of pairs) {\n const key = pairKey(pair.memoryIdA, pair.memoryIdB);\n const hash = contentHash(pair);\n const cachedResult = activeCache.get(hash);\n if (cachedResult) {\n results.set(key, { ...cachedResult, memoryIdA: pair.memoryIdA, memoryIdB: pair.memoryIdB });\n cached++;\n } else {\n toJudge.push(pair);\n }\n }\n\n if (toJudge.length === 0) {\n return { results, cached, judged, elapsed: Date.now() - startTime };\n }\n\n // Build the prompt with all pairs\n const pairDescriptions = toJudge.map((p, i) => {\n const pk = pairKey(p.memoryIdA, p.memoryIdB);\n const catA = p.categoryA ? ` [${p.categoryA}]` : \"\";\n const catB = p.categoryB ? ` [${p.categoryB}]` : \"\";\n return `Pair ${i + 1} (pairKey: \"${pk}\"):${catA} \"${p.textA}\"${catB} \"${p.textB}\"`;\n });\n\n const userMessage = `Classify these ${toJudge.length} memory pair(s):\\n\\n${pairDescriptions.join(\"\\n\\n\")}`;\n\n // Try LLM call\n let llmResponse: string | null = null;\n\n if (localLlm) {\n try {\n llmResponse = await callLlm(localLlm, config, userMessage);\n } catch (err) {\n log.warn(\"[contradiction-judge] local LLM call failed: %s\", err instanceof Error ? err.message : err);\n }\n }\n\n if (!llmResponse && fallbackLlm) {\n try {\n llmResponse = await callLlm(fallbackLlm, config, userMessage);\n } catch (err) {\n log.warn(\"[contradiction-judge] fallback LLM call failed: %s\", err instanceof Error ? err.message : err);\n }\n }\n\n // Parse response or default to needs-user\n if (llmResponse) {\n const candidates = extractJsonCandidates(llmResponse);\n const parsed = parseJudgeResponse(candidates, toJudge);\n\n for (const result of parsed) {\n const key = pairKey(result.memoryIdA, result.memoryIdB);\n results.set(key, result);\n\n // Update cache\n const input = toJudge.find(\n (p) => pairKey(p.memoryIdA, p.memoryIdB) === key,\n );\n if (input) {\n const hash = contentHash(input);\n if (activeCache.size >= CACHE_MAX) {\n const firstKey = activeCache.keys().next().value;\n if (firstKey !== undefined) activeCache.delete(firstKey);\n }\n activeCache.set(hash, result);\n }\n judged++;\n }\n } else {\n // All unresolved → needs-user (rule 48)\n for (const pair of toJudge) {\n const key = pairKey(pair.memoryIdA, pair.memoryIdB);\n const result: ContradictionJudgeResult = {\n memoryIdA: pair.memoryIdA,\n memoryIdB: pair.memoryIdB,\n verdict: \"needs-user\",\n rationale: \"LLM call failed; requires manual review\",\n confidence: 0,\n };\n results.set(key, result);\n judged++;\n }\n }\n\n return { results, cached, judged, elapsed: Date.now() - startTime };\n}\n\n// ── Internals ──────────────────────────────────────────────────────────────────\n\nasync function callLlm(\n client: LocalLlmClient | FallbackLlmClient,\n config: PluginConfig,\n userMessage: string,\n): Promise<string> {\n const messages: Array<{ role: \"user\" | \"assistant\" | \"system\"; content: string }> = [\n { role: \"system\", content: CONTRADICTION_JUDGE_PROMPT },\n { role: \"user\", content: userMessage },\n ];\n if (\"chatCompletion\" in client && typeof client.chatCompletion === \"function\") {\n const result = await client.chatCompletion(messages, {\n temperature: 0.1,\n maxTokens: 4096,\n operation: \"contradiction-judge\",\n });\n return result?.content ?? \"\";\n }\n // FallbackLlmClient — try OpenAI-compatible chat completions\n if (\"complete\" in client && typeof (client as Record<string, unknown>).complete === \"function\") {\n const result = await (client as { complete: (msg: Array<{ role: string; content: string }>) => Promise<{ content: string }> }).complete(messages);\n return result.content ?? \"\";\n }\n return \"\";\n}\n\nfunction parseJudgeResponse(\n candidates: string[],\n inputs: ContradictionJudgeInput[],\n): ContradictionJudgeResult[] {\n const VALID_VERDICTS: ContradictionVerdict[] = [\"contradicts\", \"independent\", \"duplicates\", \"needs-user\"];\n let conservativeFallback: ContradictionJudgeResult[] | null = null;\n\n for (const candidate of candidates) {\n try {\n const parsed = JSON.parse(candidate);\n const items = Array.isArray(parsed) ? parsed : [parsed];\n const results: ContradictionJudgeResult[] = [];\n const matchedKeys = new Set<string>();\n\n for (const item of items) {\n if (!item || typeof item !== \"object\") continue;\n\n const verdict = typeof item.verdict === \"string\" && VALID_VERDICTS.includes(item.verdict as ContradictionVerdict)\n ? (item.verdict as ContradictionVerdict)\n : \"needs-user\";\n\n const pairKeyVal = typeof item.pairKey === \"string\" && item.pairKey.length > 0\n ? item.pairKey\n : null;\n const input = pairKeyVal\n ? inputs.find((p) => pairKey(p.memoryIdA, p.memoryIdB) === pairKeyVal)\n : null;\n\n if (!input) continue;\n\n matchedKeys.add(pairKey(input.memoryIdA, input.memoryIdB));\n\n const confidence = typeof item.confidence === \"number\"\n ? Math.min(1, Math.max(0, item.confidence))\n : 0.5;\n\n results.push({\n memoryIdA: input.memoryIdA,\n memoryIdB: input.memoryIdB,\n verdict,\n rationale: typeof item.rationale === \"string\" ? item.rationale : \"No rationale provided\",\n confidence,\n });\n }\n\n // Backfill any inputs the LLM omitted with needs-user\n for (const inp of inputs) {\n const key = pairKey(inp.memoryIdA, inp.memoryIdB);\n if (!matchedKeys.has(key)) {\n results.push({\n memoryIdA: inp.memoryIdA,\n memoryIdB: inp.memoryIdB,\n verdict: \"needs-user\",\n rationale: \"LLM response omitted this pair\",\n confidence: 0,\n });\n }\n }\n\n if (matchedKeys.size > 0) return results;\n if (results.length > 0 && conservativeFallback === null) {\n conservativeFallback = results;\n }\n } catch {\n continue;\n }\n }\n\n if (conservativeFallback !== null) return conservativeFallback;\n\n // All parse attempts failed → needs-user for every input\n return inputs.map((p) => ({\n memoryIdA: p.memoryIdA,\n memoryIdB: p.memoryIdB,\n verdict: \"needs-user\" as ContradictionVerdict,\n rationale: \"Failed to parse judge response\",\n confidence: 0,\n }));\n}\n\nexport { pairKey as _pairKey, contentHash as _contentHash };\n","/**\n * Contradiction Scan — pair generator + scan driver (issue #520).\n *\n * Nightly cron that pairs semantically-similar active memories within\n * the same namespace, sends candidate pairs to the LLM-as-judge\n * contradiction classifier, and drops contradicting pairs into a\n * review queue for user resolution.\n *\n * Pair generation (cheap pre-filter):\n * 1. Find candidate peers via embedding cosine >= similarityFloor.\n * 2. Restrict to pairs sharing at least one entityRef OR overlapping\n * topic tokens >= topicOverlapFloor.\n * 3. Skip pairs already judged independent/both-valid within cooldown.\n * 4. Cap per-run work at maxPairsPerRun.\n */\n\nimport { resolveNamespaceCapabilities } from \"../capabilities.js\";\nimport type { StorageManager } from \"../storage.js\";\nimport type { PluginConfig, MemoryFile, MemoryStatus } from \"../types.js\";\nimport type { SemanticDedupLookup } from \"../dedup/semantic.js\";\nimport { log } from \"../logger.js\";\nimport { judgeContradictionPairs, type ContradictionJudgeInput } from \"./contradiction-judge.js\";\nimport {\n writePairs,\n readPair,\n isCoolingDown,\n memoryHashesChanged,\n computeMemoryContentHash,\n computePairId,\n migrateUnscopedPairsToNamespace,\n type ContradictionPair,\n} from \"./contradiction-review.js\";\nimport type { LocalLlmClient } from \"../local-llm.js\";\nimport type { FallbackLlmClient } from \"../fallback-llm.js\";\nimport { isSupportPassportPrivateMemory } from \"../support-passport/card-projection.js\";\n\n// ── Types ──────────────────────────────────────────────────────────────────────\n\n/** The set of statuses that represent \"live\" memories eligible for scanning. */\nexport const ACTIVE_STATUSES: Set<MemoryStatus> = new Set([\"active\"]);\n\n/** High-value taxonomy buckets to scan. */\nconst SCAN_CATEGORIES = new Set([\n \"decision\",\n \"principle\",\n \"rule\",\n \"entity\",\n \"fact\",\n \"preference\",\n]);\n\nexport interface ScanResult {\n /** Total active memories scanned. */\n scanned: number;\n /** Candidate pairs generated by the pre-filter. */\n candidates: number;\n /** Pairs sent to judge. */\n judged: number;\n /** Pairs written to review queue. */\n queued: number;\n /** Pairs skipped due to cooldown. */\n cooledDown: number;\n /** Total wall-clock time in ms. */\n elapsedMs: number;\n}\n\nexport interface ScanStorageResolution {\n storage: StorageManager;\n namespace?: string;\n}\n\nexport interface ScanDependencies {\n storage: StorageManager;\n config: PluginConfig;\n memoryDir: string;\n /** Pre-built embedding lookup. When provided, used as-is for Strategy 3. */\n embeddingLookup?: SemanticDedupLookup;\n /**\n * Factory to build a namespace-scoped embedding lookup.\n * When provided, takes precedence over `embeddingLookup`.\n * The scan driver passes its own `storage` so the lookup queries the correct index.\n */\n embeddingLookupFactory?: (storage: StorageManager) => SemanticDedupLookup | undefined;\n /** Resolver for namespace-scoped storage. Required for scans when namespaces are enabled. */\n storageForNamespace?: (\n namespace: string | undefined,\n ) => StorageManager | ScanStorageResolution | Promise<StorageManager | ScanStorageResolution>;\n localLlm: LocalLlmClient | null;\n fallbackLlm: FallbackLlmClient | null;\n namespace?: string;\n}\n\n// ── Main scan driver ───────────────────────────────────────────────────────────\n\n/**\n * Run a contradiction scan over the memory corpus.\n *\n * This is the entry point called by the nightly cron and by the CLI.\n */\nexport async function runContradictionScan(deps: ScanDependencies): Promise<ScanResult> {\n const startTime = Date.now();\n const { config, memoryDir, embeddingLookup, embeddingLookupFactory, localLlm, fallbackLlm } = deps;\n const requestedNamespace = normalizeScanNamespace(deps.namespace);\n const scanConfig = config.contradictionScan;\n\n if (!scanConfig.enabled) {\n log.info(\"[contradiction-scan] disabled by config\");\n return { scanned: 0, candidates: 0, judged: 0, queued: 0, cooledDown: 0, elapsedMs: 0 };\n }\n\n const { storage: scanStorage, namespace } = await resolveScanStorage(deps, requestedNamespace);\n if (resolveNamespaceCapabilities(config).namespaces && namespace !== undefined && isDefaultNamespaceScan(config, requestedNamespace, namespace)) {\n const migrated = migrateUnscopedPairsToNamespace(memoryDir, namespace, { cooldownDays: scanConfig.cooldownDays });\n if (migrated > 0) {\n log.info(\"[contradiction-scan] migrated %d legacy unscoped review pairs to namespace %s\", migrated, namespace);\n }\n }\n\n // Prefer the factory (which uses the scan's own storage for correct namespace scoping)\n // over a pre-built lookup (which may use default-namespace storage).\n const scopedEmbeddingLookup = embeddingLookupFactory\n ? embeddingLookupFactory(scanStorage)\n : embeddingLookup;\n\n // 1. Load active memories in scan categories\n const memories = await loadEligibleMemories(scanStorage);\n log.info(\"[contradiction-scan] loaded %d eligible memories\", memories.length);\n\n if (memories.length < 2) {\n return { scanned: memories.length, candidates: 0, judged: 0, queued: 0, cooledDown: 0, elapsedMs: Date.now() - startTime };\n }\n\n // 2. Prepare exact existing-pair lookup for cooldown checking.\n // Pair IDs are deterministic, so lookup the candidate's file directly instead\n // of paging through the review queue and risking a bounded-list miss.\n const existingPairCache = new Map<string, ContradictionPair | undefined>();\n const getExistingPair = (pairId: string): ContradictionPair | undefined => {\n if (!existingPairCache.has(pairId)) {\n existingPairCache.set(pairId, readPair(memoryDir, pairId) ?? undefined);\n }\n return existingPairCache.get(pairId);\n };\n\n // 3. Generate candidate pairs\n const candidates = await generatePairs(memories, getExistingPair, scanConfig, namespace, scopedEmbeddingLookup);\n const cooledDown = candidates.skipped;\n log.info(\"[contradiction-scan] generated %d candidates (%d cooled down)\", candidates.pairs.length, cooledDown);\n\n if (candidates.pairs.length === 0) {\n return {\n scanned: memories.length,\n candidates: 0,\n judged: 0,\n queued: 0,\n cooledDown,\n elapsedMs: Date.now() - startTime,\n };\n }\n\n // 4. Build judge inputs. Candidate generation already preserves strategy\n // priority and caps work at maxPairsPerRun.\n const judgeInputs: ContradictionJudgeInput[] = candidates.pairs.map((pair) => ({\n memoryIdA: pair.idA,\n memoryIdB: pair.idB,\n textA: pair.textA,\n textB: pair.textB,\n categoryA: pair.categoryA,\n categoryB: pair.categoryB,\n }));\n\n // 6. Send to judge (per-scan cache avoids module-level singleton leak)\n const scanCache = new Map<string, import(\"./contradiction-judge.js\").ContradictionJudgeResult>();\n const judgeResult = await judgeContradictionPairs(judgeInputs, config, localLlm, fallbackLlm, scanCache);\n log.info(\"[contradiction-scan] judge completed: %d judged, %d cached in %dms\", judgeResult.judged, judgeResult.cached, judgeResult.elapsed);\n\n // 7. Write to review queue\n const queueEntries: Array<Omit<ContradictionPair, \"pairId\"> & { memoryIds: [string, string] }> = [];\n const currentMemoryHashes = memoryContentHashMap(memories);\n for (const [key, result] of judgeResult.results) {\n queueEntries.push({\n memoryIds: [result.memoryIdA, result.memoryIdB],\n verdict: result.verdict,\n rationale: result.rationale,\n confidence: result.confidence,\n detectedAt: new Date().toISOString(),\n // Set lastReviewedAt for non-actionable verdicts so cooldown prevents re-judging\n lastReviewedAt: result.verdict === \"independent\" ? new Date().toISOString() : undefined,\n memoryContentHashes: pairMemoryContentHashes(result.memoryIdA, result.memoryIdB, currentMemoryHashes),\n namespace,\n });\n }\n\n const written = writePairs(memoryDir, queueEntries, { cooldownDays: scanConfig.cooldownDays });\n const elapsed = Date.now() - startTime;\n log.info(\"[contradiction-scan] complete: %d queued in %dms\", written.length, elapsed);\n\n return {\n scanned: memories.length,\n candidates: candidates.pairs.length,\n judged: judgeResult.judged,\n queued: written.length,\n cooledDown,\n elapsedMs: elapsed,\n };\n}\n\n// ── Pair generation ────────────────────────────────────────────────────────────\n\ninterface CandidatePair {\n idA: string;\n idB: string;\n textA: string;\n textB: string;\n categoryA?: string;\n categoryB?: string;\n}\n\ninterface PairGenResult {\n pairs: CandidatePair[];\n skipped: number;\n}\n\nasync function generatePairs(\n memories: MemoryFile[],\n getExistingPair: (pairId: string) => ContradictionPair | undefined,\n scanConfig: PluginConfig[\"contradictionScan\"],\n namespace: string | undefined,\n embeddingLookup?: SemanticDedupLookup,\n): Promise<PairGenResult> {\n const pairs: CandidatePair[] = [];\n let skipped = 0;\n const seen = new Set<string>();\n const maxPairs = Math.max(0, Math.floor(scanConfig.maxPairsPerRun));\n if (maxPairs === 0) return { pairs, skipped };\n\n const orderedMemories = [...memories].sort(compareMemoryId);\n const currentMemoryHashes = memoryContentHashMap(orderedMemories);\n\n const pushCandidate = (pair: CandidatePair): void => {\n if (pairs.length < maxPairs) pairs.push(pair);\n };\n\n const hasCapacity = (): boolean => pairs.length < maxPairs;\n const isSkippedByCooldown = (existing: ContradictionPair | undefined): boolean => {\n if (!existing || !isCoolingDown(existing, scanConfig.cooldownDays)) return false;\n return !memoryHashesChanged(\"\", existing, (memoryId) => currentMemoryHashes.get(memoryId) ?? null);\n };\n\n // Build index by entityRef for fast lookup\n const byEntity = new Map<string, MemoryFile[]>();\n for (const mem of orderedMemories) {\n const entity = mem.frontmatter.entityRef;\n if (entity) {\n const existing = byEntity.get(entity) ?? [];\n existing.push(mem);\n byEntity.set(entity, existing);\n }\n }\n\n // Strategy 1: Entity-ref based pairing (high precision)\n entityPairs:\n for (const entity of [...byEntity.keys()].sort()) {\n const group = byEntity.get(entity) ?? [];\n if (group.length < 2) continue;\n for (let i = 0; i < group.length; i++) {\n for (let j = i + 1; j < group.length; j++) {\n if (!hasCapacity()) break entityPairs;\n const a = group[i];\n const b = group[j];\n const pairId = computePairId(a.frontmatter.id!, b.frontmatter.id!, namespace);\n\n if (seen.has(pairId)) continue;\n seen.add(pairId);\n\n // Check cooldown\n const existing = getExistingPair(pairId);\n if (isSkippedByCooldown(existing)) {\n skipped++;\n continue;\n }\n\n pushCandidate({\n idA: a.frontmatter.id!,\n idB: b.frontmatter.id!,\n textA: a.content,\n textB: b.content,\n categoryA: a.frontmatter.category as string | undefined,\n categoryB: b.frontmatter.category as string | undefined,\n });\n }\n }\n }\n\n // Strategy 2: Tag/topic overlap for memories without a shared entityRef\n topicPairs:\n for (let i = 0; i < orderedMemories.length; i++) {\n for (let j = i + 1; j < orderedMemories.length; j++) {\n if (!hasCapacity()) break topicPairs;\n const a = orderedMemories[i];\n const b = orderedMemories[j];\n if (shareEntityRef(a, b)) continue;\n const overlap = jaccardOverlap(\n (a.frontmatter.tags as string[]) ?? [],\n (b.frontmatter.tags as string[]) ?? [],\n );\n\n if (overlap < scanConfig.topicOverlapFloor) continue;\n\n const pairId = computePairId(a.frontmatter.id!, b.frontmatter.id!, namespace);\n if (seen.has(pairId)) continue;\n seen.add(pairId);\n\n const existing = getExistingPair(pairId);\n if (isSkippedByCooldown(existing)) {\n skipped++;\n continue;\n }\n\n pushCandidate({\n idA: a.frontmatter.id!,\n idB: b.frontmatter.id!,\n textA: a.content,\n textB: b.content,\n categoryA: a.frontmatter.category as string | undefined,\n categoryB: b.frontmatter.category as string | undefined,\n });\n }\n }\n\n // Strategy 3: Embedding cosine similarity (enforces similarityFloor config)\n if (embeddingLookup && hasCapacity()) {\n const memoryById = new Map(orderedMemories.map((m) => [m.frontmatter.id!, m]));\n embeddingPairs:\n for (const mem of orderedMemories) {\n if (!hasCapacity()) break;\n const id = mem.frontmatter.id!;\n try {\n const hits = (await embeddingLookup(mem.content, 20)).sort((a, b) =>\n b.score - a.score || a.id.localeCompare(b.id),\n );\n for (const hit of hits) {\n if (!hasCapacity()) break embeddingPairs;\n if (hit.score < scanConfig.similarityFloor) continue;\n if (hit.id === id) continue;\n const peer = memoryById.get(hit.id);\n if (!peer) continue;\n\n const pairId = computePairId(id, hit.id, namespace);\n if (seen.has(pairId)) continue;\n seen.add(pairId);\n\n const existing = getExistingPair(pairId);\n if (isSkippedByCooldown(existing)) {\n skipped++;\n continue;\n }\n\n pushCandidate({\n idA: id,\n idB: hit.id,\n textA: mem.content,\n textB: peer.content,\n categoryA: mem.frontmatter.category as string | undefined,\n categoryB: peer.frontmatter.category as string | undefined,\n });\n }\n } catch {\n // Embedding backend unavailable — skip, entity-ref/tag strategies already covered\n }\n }\n }\n\n return { pairs, skipped };\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────────────\n\nfunction normalizeScanNamespace(namespace: string | undefined): string | undefined {\n const trimmed = namespace?.trim();\n return trimmed ? trimmed : undefined;\n}\n\nasync function resolveScanStorage(\n deps: ScanDependencies,\n namespace: string | undefined,\n): Promise<ScanStorageResolution> {\n if (!resolveNamespaceCapabilities(deps.config).namespaces) {\n const defaultNamespace = normalizeScanNamespace(deps.config.defaultNamespace);\n if (namespace && namespace !== defaultNamespace) {\n throw new Error(`unsupported namespace: ${namespace}`);\n }\n return { storage: deps.storage, namespace: undefined };\n }\n\n if (deps.storageForNamespace) {\n const resolved = await deps.storageForNamespace(namespace);\n if (isScanStorageResolution(resolved)) {\n return {\n storage: resolved.storage,\n namespace: normalizeScanNamespace(resolved.namespace) ?? fallbackResolvedNamespace(deps, namespace),\n };\n }\n if (!isStorageManagerLike(resolved)) {\n throw new Error(\"storageForNamespace must return a StorageManager or { storage: StorageManager, namespace?: string }\");\n }\n return {\n storage: resolved,\n namespace: fallbackResolvedNamespace(deps, namespace),\n };\n }\n\n throw new Error(\n \"contradiction scans require storageForNamespace when namespaces are enabled so callers can enforce namespace access\",\n );\n}\n\nfunction isScanStorageResolution(value: StorageManager | ScanStorageResolution): value is ScanStorageResolution {\n if (isStorageManagerLike(value)) return false;\n if (typeof value !== \"object\" || value === null) return false;\n const candidate = value as { storage?: unknown };\n return isStorageManagerLike(candidate.storage);\n}\n\nfunction isStorageManagerLike(value: unknown): value is StorageManager {\n if (typeof value !== \"object\" || value === null) return false;\n const candidate = value as { readAllMemories?: unknown };\n return typeof candidate.readAllMemories === \"function\";\n}\n\nfunction fallbackResolvedNamespace(deps: ScanDependencies, namespace: string | undefined): string | undefined {\n if (namespace) return namespace;\n return resolveNamespaceCapabilities(deps.config).namespaces ? deps.config.defaultNamespace : undefined;\n}\n\nfunction isDefaultNamespaceScan(\n config: PluginConfig,\n requestedNamespace: string | undefined,\n resolvedNamespace: string,\n): boolean {\n if (requestedNamespace === undefined) return true;\n return requestedNamespace === config.defaultNamespace || resolvedNamespace === config.defaultNamespace;\n}\n\nasync function loadEligibleMemories(storage: StorageManager): Promise<MemoryFile[]> {\n let all: MemoryFile[];\n try {\n all = await storage.readAllMemories();\n } catch {\n return [];\n }\n\n return all.filter((mem) => {\n const fm = mem.frontmatter;\n if (isSupportPassportPrivateMemory(mem)) return false;\n // Only active memories (rule 53: explicit ACTIVE_STATUSES set)\n const status = (fm.status as MemoryStatus) ?? \"active\";\n if (!ACTIVE_STATUSES.has(status)) return false;\n\n // Only scan high-value categories\n const category = fm.category as string | undefined;\n if (category && !SCAN_CATEGORIES.has(category)) return false;\n\n // Must have content\n if (!mem.content || mem.content.trim().length === 0) return false;\n\n // Must have an ID\n if (!fm.id) return false;\n\n return true;\n });\n}\n\nfunction jaccardOverlap(a: string[], b: string[]): number {\n if (a.length === 0 && b.length === 0) return 0;\n const setA = new Set(a.map((t) => t.toLowerCase()));\n const setB = new Set(b.map((t) => t.toLowerCase()));\n let intersection = 0;\n for (const item of setA) {\n if (setB.has(item)) intersection++;\n }\n const union = setA.size + setB.size - intersection;\n return union === 0 ? 0 : intersection / union;\n}\n\nfunction shareEntityRef(a: MemoryFile, b: MemoryFile): boolean {\n const entityA = a.frontmatter.entityRef?.trim();\n const entityB = b.frontmatter.entityRef?.trim();\n return Boolean(entityA && entityB && entityA === entityB);\n}\n\nfunction compareMemoryId(a: MemoryFile, b: MemoryFile): number {\n return (a.frontmatter.id ?? \"\").localeCompare(b.frontmatter.id ?? \"\");\n}\n\nfunction memoryContentHashMap(memories: MemoryFile[]): Map<string, string> {\n const hashes = new Map<string, string>();\n for (const memory of memories) {\n const id = memory.frontmatter.id;\n if (!id) continue;\n hashes.set(id, computeMemoryContentHash(memory.content, memory.frontmatter.category as string | undefined));\n }\n return hashes;\n}\n\nfunction pairMemoryContentHashes(\n memoryIdA: string,\n memoryIdB: string,\n currentMemoryHashes: Map<string, string>,\n): Record<string, string> | undefined {\n const hashA = currentMemoryHashes.get(memoryIdA);\n const hashB = currentMemoryHashes.get(memoryIdB);\n if (!hashA || !hashB) return undefined;\n return {\n [memoryIdA]: hashA,\n [memoryIdB]: hashB,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAaA,SAAS,kBAAkB;AAuD3B,IAAM,6BAA6B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAuBnC,IAAI,sBAA6D,oBAAI,IAAI;AACzE,IAAM,YAAY;AAElB,SAAS,QAAQ,KAAa,KAAqB;AACjD,QAAM,SAAS,CAAC,KAAK,GAAG,EAAE,KAAK;AAC/B,SAAO,GAAG,OAAO,CAAC,CAAC,IAAI,OAAO,CAAC,CAAC;AAClC;AAEA,SAAS,YAAY,GAAoC;AAEvD,QAAM,QAAQ;AAAA,IACZ,EAAE,MAAM,EAAE,MAAM,KAAK,GAAG,WAAW,EAAE,aAAa,IAAI,KAAK,EAAE;AAAA,IAC7D,EAAE,MAAM,EAAE,MAAM,KAAK,GAAG,WAAW,EAAE,aAAa,IAAI,KAAK,EAAE;AAAA,EAC/D,EAAE,KAAK,CAAC,MAAM,UAAU;AACtB,UAAM,UAAU,KAAK,UAAU,IAAI;AACnC,UAAM,WAAW,KAAK,UA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OAAO;AACtC,SAAO,UAAU,IAAI,IAAI,eAAe;AAC1C;AAEA,SAAS,eAAe,GAAe,GAAwB;AAC7D,QAAM,UAAU,EAAE,YAAY,WAAW,KAAK;AAC9C,QAAM,UAAU,EAAE,YAAY,WAAW,KAAK;AAC9C,SAAO,QAAQ,WAAW,WAAW,YAAY,OAAO;AAC1D;AAEA,SAAS,gBAAgB,GAAe,GAAuB;AAC7D,UAAQ,EAAE,YAAY,MAAM,IAAI,cAAc,EAAE,YAAY,MAAM,EAAE;AACtE;AAEA,SAAS,qBAAqB,UAA6C;AACzE,QAAM,SAAS,oBAAI,IAAoB;AACvC,aAAW,UAAU,UAAU;AAC7B,UAAM,KAAK,OAAO,YAAY;AAC9B,QAAI,CAAC,GAAI;AACT,WAAO,IAAI,IAAI,yBAAyB,OAAO,SAAS,OAAO,YAAY,QAA8B,CAAC;AAAA,EAC5G;AACA,SAAO;AACT;AAEA,SAAS,wBACP,WACA,WACA,qBACoC;AACpC,QAAM,QAAQ,oBAAoB,IAAI,SAAS;AAC/C,QAAM,QAAQ,oBAAoB,IAAI,SAAS;AAC/C,MAAI,CAAC,SAAS,CAAC,MAAO,QAAO;AAC7B,SAAO;AAAA,IACL,CAAC,SAAS,GAAG;AAAA,IACb,CAAC,SAAS,GAAG;AAAA,EACf;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/contradiction/contradiction-judge.ts","../src/contradiction/contradiction-scan.ts"],"sourcesContent":["/**\n * Contradiction Judge — LLM-as-judge for semantic contradiction detection (issue #520).\n *\n * Pairs semantically-similar memories and classifies their relationship.\n * Reuses the extraction-judge adapter pattern but with a contradiction-specific\n * prompt and verdict taxonomy.\n *\n * Design constraints:\n * - Default verdict on any failure is \"needs-user\" (rule 48: least-privileged default).\n * - Never auto-resolve; all verdicts enter the review queue.\n * - Content-hash caching avoids redundant LLM calls across runs.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { log } from \"../logger.js\";\nimport type { PluginConfig } from \"../types.js\";\nimport type { LocalLlmClient } from \"../local-llm.js\";\nimport type { FallbackLlmClient } from \"../fallback-llm.js\";\nimport { extractJsonCandidates } from \"../json-extract.js\";\n\n// ── Types ──────────────────────────────────────────────────────────────────────\n\nexport type ContradictionVerdict =\n | \"contradicts\"\n | \"independent\"\n | \"duplicates\"\n | \"needs-user\";\n\nexport interface ContradictionJudgeInput {\n /** Memory ID of the first fact. */\n memoryIdA: string;\n /** Memory ID of the second fact. */\n memoryIdB: string;\n /** Content text of the first fact. */\n textA: string;\n /** Content text of the second fact. */\n textB: string;\n /** Category of the first fact (optional context). */\n categoryA?: string;\n /** Category of the second fact (optional context). */\n categoryB?: string;\n}\n\nexport interface ContradictionJudgeResult {\n /** Memory IDs of the pair. */\n memoryIdA: string;\n memoryIdB: string;\n /** Verdict from the judge. */\n verdict: ContradictionVerdict;\n /** Human-readable rationale. */\n rationale: string;\n /** Confidence in [0, 1]. */\n confidence: number;\n}\n\nexport interface ContradictionJudgeBatchResult {\n /** Results keyed by pair key (\"idA:idB\"). */\n results: Map<string, ContradictionJudgeResult>;\n /** Number served from cache. */\n cached: number;\n /** Number produced by LLM call. */\n judged: number;\n /** Total wall-clock time in ms. */\n elapsed: number;\n}\n\n// ── Prompt ─────────────────────────────────────────────────────────────────────\n\nconst CONTRADICTION_JUDGE_PROMPT = `You are a memory contradiction classifier. You will receive pairs of stored memories and must classify their semantic relationship.\n\nFor each pair, respond with a JSON array where each element has:\n- \"pairKey\": the pairKey provided in the input\n- \"verdict\": one of \"contradicts\", \"independent\", \"duplicates\", \"needs-user\"\n- \"rationale\": one sentence explaining why\n- \"confidence\": number between 0 and 1\n\nVERDICT DEFINITIONS:\n- \"contradicts\": The two memories make claims that cannot both be true. One must be wrong or outdated.\n- \"duplicates\": The two memories convey essentially the same information (near-paraphrase).\n- \"independent\": The memories are topically similar but do not conflict or duplicate.\n- \"needs-user\": Cannot determine with sufficient confidence; requires human review.\n\nIMPORTANT:\n- Be conservative. When in doubt, prefer \"needs-user\" over a wrong classification.\n- Two memories about the same entity/topic are NOT necessarily contradictory.\n- Temporal changes (\"Joshua uses pnpm\" vs \"Joshua switched to npm\") ARE contradictions.\n- Different aspects of the same entity (\"Joshua uses pnpm\" vs \"Joshua works on Remnic\") are \"independent\".`;\n\n// ── Cache ──────────────────────────────────────────────────────────────────────\n\n/** Module-level fallback cache — only used when caller does not supply one. */\nlet defaultVerdictCache: Map<string, ContradictionJudgeResult> = new Map();\nconst CACHE_MAX = 10_000;\n\nfunction pairKey(idA: string, idB: string): string {\n const sorted = [idA, idB].sort();\n return `${sorted[0]}:${sorted[1]}`;\n}\n\nfunction contentHash(a: ContradictionJudgeInput): string {\n // Sort each side pair to be order-independent (matching pairKey behavior)\n const sides = [\n { text: a.textA.trim(), category: (a.categoryA ?? \"\").trim() },\n { text: a.textB.trim(), category: (a.categoryB ?? \"\").trim() },\n ].sort((left, right) => {\n const leftKey = JSON.stringify(left);\n const rightKey = JSON.stringify(right);\n return leftKey.localeCompare(rightKey);\n });\n const normalized = JSON.stringify(sides);\n return createHash(\"sha256\").update(normalized).digest(\"hex\").slice(0, 16);\n}\n\nexport function createVerdictCache(): Map<string, ContradictionJudgeResult> {\n return new Map();\n}\n\nexport function clearVerdictCache(): void {\n defaultVerdictCache.clear();\n}\n\nexport function verdictCacheSize(): number {\n return defaultVerdictCache.size;\n}\n\n// ── Public API ──────────────────────────────────────────────────────────────────\n\n/**\n * Judge a batch of memory pairs for contradiction.\n *\n * Uses content-hash caching to skip pairs already judged in a prior run.\n * On any LLM failure, all unresolved pairs default to \"needs-user\".\n */\nexport async function judgeContradictionPairs(\n pairs: ContradictionJudgeInput[],\n config: PluginConfig,\n localLlm: LocalLlmClient | null,\n fallbackLlm: FallbackLlmClient | null,\n cache?: Map<string, ContradictionJudgeResult>,\n): Promise<ContradictionJudgeBatchResult> {\n const startTime = Date.now();\n const results = new Map<string, ContradictionJudgeResult>();\n const activeCache = cache ?? defaultVerdictCache;\n let cached = 0;\n let judged = 0;\n\n // Partition into cached vs needs-judging\n const toJudge: ContradictionJudgeInput[] = [];\n for (const pair of pairs) {\n const key = pairKey(pair.memoryIdA, pair.memoryIdB);\n const hash = contentHash(pair);\n const cachedResult = activeCache.get(hash);\n if (cachedResult) {\n results.set(key, { ...cachedResult, memoryIdA: pair.memoryIdA, memoryIdB: pair.memoryIdB });\n cached++;\n } else {\n toJudge.push(pair);\n }\n }\n\n if (toJudge.length === 0) {\n return { results, cached, judged, elapsed: Date.now() - startTime };\n }\n\n // Build the prompt with all pairs\n const pairDescriptions = toJudge.map((p, i) => {\n const pk = pairKey(p.memoryIdA, p.memoryIdB);\n const catA = p.categoryA ? ` [${p.categoryA}]` : \"\";\n const catB = p.categoryB ? ` [${p.categoryB}]` : \"\";\n return `Pair ${i + 1} (pairKey: \"${pk}\"):${catA} \"${p.textA}\"${catB} \"${p.textB}\"`;\n });\n\n const userMessage = `Classify these ${toJudge.length} memory pair(s):\\n\\n${pairDescriptions.join(\"\\n\\n\")}`;\n\n // Try LLM call\n let llmResponse: string | null = null;\n\n if (localLlm) {\n try {\n llmResponse = await callLlm(localLlm, config, userMessage);\n } catch (err) {\n log.warn(\"[contradiction-judge] local LLM call failed: %s\", err instanceof Error ? err.message : err);\n }\n }\n\n if (!llmResponse && fallbackLlm) {\n try {\n llmResponse = await callLlm(fallbackLlm, config, userMessage);\n } catch (err) {\n log.warn(\"[contradiction-judge] fallback LLM call failed: %s\", err instanceof Error ? err.message : err);\n }\n }\n\n // Parse response or default to needs-user\n if (llmResponse) {\n const candidates = extractJsonCandidates(llmResponse);\n const parsed = parseJudgeResponse(candidates, toJudge);\n\n for (const result of parsed) {\n const key = pairKey(result.memoryIdA, result.memoryIdB);\n results.set(key, result);\n\n // Update cache\n const input = toJudge.find(\n (p) => pairKey(p.memoryIdA, p.memoryIdB) === key,\n );\n if (input) {\n const hash = contentHash(input);\n if (activeCache.size >= CACHE_MAX) {\n const firstKey = activeCache.keys().next().value;\n if (firstKey !== undefined) activeCache.delete(firstKey);\n }\n activeCache.set(hash, result);\n }\n judged++;\n }\n } else {\n // All unresolved → needs-user (rule 48)\n for (const pair of toJudge) {\n const key = pairKey(pair.memoryIdA, pair.memoryIdB);\n const result: ContradictionJudgeResult = {\n memoryIdA: pair.memoryIdA,\n memoryIdB: pair.memoryIdB,\n verdict: \"needs-user\",\n rationale: \"LLM call failed; requires manual review\",\n confidence: 0,\n };\n results.set(key, result);\n judged++;\n }\n }\n\n return { results, cached, judged, elapsed: Date.now() - startTime };\n}\n\n// ── Internals ──────────────────────────────────────────────────────────────────\n\nasync function callLlm(\n client: LocalLlmClient | FallbackLlmClient,\n config: PluginConfig,\n userMessage: string,\n): Promise<string> {\n const messages: Array<{ role: \"user\" | \"assistant\" | \"system\"; content: string }> = [\n { role: \"system\", content: CONTRADICTION_JUDGE_PROMPT },\n { role: \"user\", content: userMessage },\n ];\n if (\"chatCompletion\" in client && typeof client.chatCompletion === \"function\") {\n const result = await client.chatCompletion(messages, {\n temperature: 0.1,\n maxTokens: 4096,\n operation: \"contradiction-judge\",\n });\n return result?.content ?? \"\";\n }\n // FallbackLlmClient — try OpenAI-compatible chat completions\n if (\"complete\" in client && typeof (client as Record<string, unknown>).complete === \"function\") {\n const result = await (client as { complete: (msg: Array<{ role: string; content: string }>) => Promise<{ content: string }> }).complete(messages);\n return result.content ?? \"\";\n }\n return \"\";\n}\n\nfunction parseJudgeResponse(\n candidates: string[],\n inputs: ContradictionJudgeInput[],\n): ContradictionJudgeResult[] {\n const VALID_VERDICTS: ContradictionVerdict[] = [\"contradicts\", \"independent\", \"duplicates\", \"needs-user\"];\n let conservativeFallback: ContradictionJudgeResult[] | null = null;\n\n for (const candidate of candidates) {\n try {\n const parsed = JSON.parse(candidate);\n const items = Array.isArray(parsed) ? parsed : [parsed];\n const results: ContradictionJudgeResult[] = [];\n const matchedKeys = new Set<string>();\n\n for (const item of items) {\n if (!item || typeof item !== \"object\") continue;\n\n const verdict = typeof item.verdict === \"string\" && VALID_VERDICTS.includes(item.verdict as ContradictionVerdict)\n ? (item.verdict as ContradictionVerdict)\n : \"needs-user\";\n\n const pairKeyVal = typeof item.pairKey === \"string\" && item.pairKey.length > 0\n ? item.pairKey\n : null;\n const input = pairKeyVal\n ? inputs.find((p) => pairKey(p.memoryIdA, p.memoryIdB) === pairKeyVal)\n : null;\n\n if (!input) continue;\n\n matchedKeys.add(pairKey(input.memoryIdA, input.memoryIdB));\n\n const confidence = typeof item.confidence === \"number\"\n ? Math.min(1, Math.max(0, item.confidence))\n : 0.5;\n\n results.push({\n memoryIdA: input.memoryIdA,\n memoryIdB: input.memoryIdB,\n verdict,\n rationale: typeof item.rationale === \"string\" ? item.rationale : \"No rationale provided\",\n confidence,\n });\n }\n\n // Backfill any inputs the LLM omitted with needs-user\n for (const inp of inputs) {\n const key = pairKey(inp.memoryIdA, inp.memoryIdB);\n if (!matchedKeys.has(key)) {\n results.push({\n memoryIdA: inp.memoryIdA,\n memoryIdB: inp.memoryIdB,\n verdict: \"needs-user\",\n rationale: \"LLM response omitted this pair\",\n confidence: 0,\n });\n }\n }\n\n if (matchedKeys.size > 0) return results;\n if (results.length > 0 && conservativeFallback === null) {\n conservativeFallback = results;\n }\n } catch {\n continue;\n }\n }\n\n if (conservativeFallback !== null) return conservativeFallback;\n\n // All parse attempts failed → needs-user for every input\n return inputs.map((p) => ({\n memoryIdA: p.memoryIdA,\n memoryIdB: p.memoryIdB,\n verdict: \"needs-user\" as ContradictionVerdict,\n rationale: \"Failed to parse judge response\",\n confidence: 0,\n }));\n}\n\nexport { pairKey as _pairKey, contentHash as _contentHash };\n","/**\n * Contradiction Scan — pair generator + scan driver (issue #520).\n *\n * Nightly cron that pairs semantically-similar active memories within\n * the same namespace, sends candidate pairs to the LLM-as-judge\n * contradiction classifier, and drops contradicting pairs into a\n * review queue for user resolution.\n *\n * Pair generation (cheap pre-filter):\n * 1. Find candidate peers via embedding cosine >= similarityFloor.\n * 2. Restrict to pairs sharing at least one entityRef OR overlapping\n * topic tokens >= topicOverlapFloor.\n * 3. Skip pairs already judged independent/both-valid within cooldown.\n * 4. Cap per-run work at maxPairsPerRun.\n */\n\nimport { resolveNamespaceCapabilities } from \"../capabilities.js\";\nimport type { StorageManager } from \"../storage.js\";\nimport type { PluginConfig, MemoryFile, MemoryStatus } from \"../types.js\";\nimport type { SemanticDedupLookup } from \"../dedup/semantic.js\";\nimport { log } from \"../logger.js\";\nimport { judgeContradictionPairs, type ContradictionJudgeInput } from \"./contradiction-judge.js\";\nimport {\n writePairs,\n readPair,\n isCoolingDown,\n memoryHashesChanged,\n computeMemoryContentHash,\n computePairId,\n migrateUnscopedPairsToNamespace,\n type ContradictionPair,\n} from \"./contradiction-review.js\";\nimport type { LocalLlmClient } from \"../local-llm.js\";\nimport type { FallbackLlmClient } from \"../fallback-llm.js\";\nimport { isSupportPassportPrivateMemory } from \"../support-passport/card-projection.js\";\n\n// ── Types ──────────────────────────────────────────────────────────────────────\n\n/** The set of statuses that represent \"live\" memories eligible for scanning. */\nexport const ACTIVE_STATUSES: Set<MemoryStatus> = new Set([\"active\"]);\n\n/** High-value taxonomy buckets to scan. */\nconst SCAN_CATEGORIES = new Set([\n \"decision\",\n \"principle\",\n \"rule\",\n \"entity\",\n \"fact\",\n \"preference\",\n]);\n\nexport interface ScanResult {\n /** Total active memories scanned. */\n scanned: number;\n /** Candidate pairs generated by the pre-filter. */\n candidates: number;\n /** Pairs sent to judge. */\n judged: number;\n /** Pairs written to review queue. */\n queued: number;\n /** Pairs skipped due to cooldown. */\n cooledDown: number;\n /** Total wall-clock time in ms. */\n elapsedMs: number;\n}\n\nexport interface ScanStorageResolution {\n storage: StorageManager;\n namespace?: string;\n}\n\nexport interface ScanDependencies {\n storage: StorageManager;\n config: PluginConfig;\n memoryDir: string;\n /** Pre-built embedding lookup. When provided, used as-is for Strategy 3. */\n embeddingLookup?: SemanticDedupLookup;\n /**\n * Factory to build a namespace-scoped embedding lookup.\n * When provided, takes precedence over `embeddingLookup`.\n * The scan driver passes its own `storage` so the lookup queries the correct index.\n */\n embeddingLookupFactory?: (storage: StorageManager) => SemanticDedupLookup | undefined;\n /** Resolver for namespace-scoped storage. Required for scans when namespaces are enabled. */\n storageForNamespace?: (\n namespace: string | undefined,\n ) => StorageManager | ScanStorageResolution | Promise<StorageManager | ScanStorageResolution>;\n localLlm: LocalLlmClient | null;\n fallbackLlm: FallbackLlmClient | null;\n namespace?: string;\n}\n\n// ── Main scan driver ───────────────────────────────────────────────────────────\n\n/**\n * Run a contradiction scan over the memory corpus.\n *\n * This is the entry point called by the nightly cron and by the CLI.\n */\nexport async function runContradictionScan(deps: ScanDependencies): Promise<ScanResult> {\n const startTime = Date.now();\n const { config, memoryDir, embeddingLookup, embeddingLookupFactory, localLlm, fallbackLlm } = deps;\n const requestedNamespace = normalizeScanNamespace(deps.namespace);\n const scanConfig = config.contradictionScan;\n\n if (!scanConfig.enabled) {\n log.info(\"[contradiction-scan] disabled by config\");\n return { scanned: 0, candidates: 0, judged: 0, queued: 0, cooledDown: 0, elapsedMs: 0 };\n }\n\n const { storage: scanStorage, namespace } = await resolveScanStorage(deps, requestedNamespace);\n if (resolveNamespaceCapabilities(config).namespaces && namespace !== undefined && isDefaultNamespaceScan(config, requestedNamespace, namespace)) {\n const migrated = migrateUnscopedPairsToNamespace(memoryDir, namespace, { cooldownDays: scanConfig.cooldownDays });\n if (migrated > 0) {\n log.info(\"[contradiction-scan] migrated %d legacy unscoped review pairs to namespace %s\", migrated, namespace);\n }\n }\n\n // Prefer the factory (which uses the scan's own storage for correct namespace scoping)\n // over a pre-built lookup (which may use default-namespace storage).\n const scopedEmbeddingLookup = embeddingLookupFactory\n ? embeddingLookupFactory(scanStorage)\n : embeddingLookup;\n\n // 1. Load active memories in scan categories\n const memories = await loadEligibleMemories(scanStorage);\n log.info(\"[contradiction-scan] loaded %d eligible memories\", memories.length);\n\n if (memories.length < 2) {\n return { scanned: memories.length, candidates: 0, judged: 0, queued: 0, cooledDown: 0, elapsedMs: Date.now() - startTime };\n }\n\n // 2. Prepare exact existing-pair lookup for cooldown checking.\n // Pair IDs are deterministic, so lookup the candidate's file directly instead\n // of paging through the review queue and risking a bounded-list miss.\n const existingPairCache = new Map<string, ContradictionPair | undefined>();\n const getExistingPair = (pairId: string): ContradictionPair | undefined => {\n if (!existingPairCache.has(pairId)) {\n existingPairCache.set(pairId, readPair(memoryDir, pairId) ?? undefined);\n }\n return existingPairCache.get(pairId);\n };\n\n // 3. Generate candidate pairs\n const candidates = await generatePairs(memories, getExistingPair, scanConfig, namespace, scopedEmbeddingLookup);\n const cooledDown = candidates.skipped;\n log.info(\"[contradiction-scan] generated %d candidates (%d cooled down)\", candidates.pairs.length, cooledDown);\n\n if (candidates.pairs.length === 0) {\n return {\n scanned: memories.length,\n candidates: 0,\n judged: 0,\n queued: 0,\n cooledDown,\n elapsedMs: Date.now() - startTime,\n };\n }\n\n // 4. Build judge inputs. Candidate generation already preserves strategy\n // priority and caps work at maxPairsPerRun.\n const judgeInputs: ContradictionJudgeInput[] = candidates.pairs.map((pair) => ({\n memoryIdA: pair.idA,\n memoryIdB: pair.idB,\n textA: pair.textA,\n textB: pair.textB,\n categoryA: pair.categoryA,\n categoryB: pair.categoryB,\n }));\n\n // 6. Send to judge (per-scan cache avoids module-level singleton leak)\n const scanCache = new Map<string, import(\"./contradiction-judge.js\").ContradictionJudgeResult>();\n const judgeResult = await judgeContradictionPairs(judgeInputs, config, localLlm, fallbackLlm, scanCache);\n log.info(\"[contradiction-scan] judge completed: %d judged, %d cached in %dms\", judgeResult.judged, judgeResult.cached, judgeResult.elapsed);\n\n // 7. Write to review queue\n const queueEntries: Array<Omit<ContradictionPair, \"pairId\"> & { memoryIds: [string, string] }> = [];\n const currentMemoryHashes = memoryContentHashMap(memories);\n for (const [key, result] of judgeResult.results) {\n queueEntries.push({\n memoryIds: [result.memoryIdA, result.memoryIdB],\n verdict: result.verdict,\n rationale: result.rationale,\n confidence: result.confidence,\n detectedAt: new Date().toISOString(),\n // Set lastReviewedAt for non-actionable verdicts so cooldown prevents re-judging\n lastReviewedAt: result.verdict === \"independent\" ? new Date().toISOString() : undefined,\n memoryContentHashes: pairMemoryContentHashes(result.memoryIdA, result.memoryIdB, currentMemoryHashes),\n namespace,\n });\n }\n\n const written = writePairs(memoryDir, queueEntries, { cooldownDays: scanConfig.cooldownDays });\n const elapsed = Date.now() - startTime;\n log.info(\"[contradiction-scan] complete: %d queued in %dms\", written.length, elapsed);\n\n return {\n scanned: memories.length,\n candidates: candidates.pairs.length,\n judged: judgeResult.judged,\n queued: written.length,\n cooledDown,\n elapsedMs: elapsed,\n };\n}\n\n// ── Pair generation ────────────────────────────────────────────────────────────\n\ninterface CandidatePair {\n idA: string;\n idB: string;\n textA: string;\n textB: string;\n categoryA?: string;\n categoryB?: string;\n}\n\ninterface PairGenResult {\n pairs: CandidatePair[];\n skipped: number;\n}\n\nasync function generatePairs(\n memories: MemoryFile[],\n getExistingPair: (pairId: string) => ContradictionPair | undefined,\n scanConfig: PluginConfig[\"contradictionScan\"],\n namespace: string | undefined,\n embeddingLookup?: SemanticDedupLookup,\n): Promise<PairGenResult> {\n const pairs: CandidatePair[] = [];\n let skipped = 0;\n const seen = new Set<string>();\n const maxPairs = Math.max(0, Math.floor(scanConfig.maxPairsPerRun));\n if (maxPairs === 0) return { pairs, skipped };\n\n const orderedMemories = [...memories].sort(compareMemoryId);\n const currentMemoryHashes = memoryContentHashMap(orderedMemories);\n\n const pushCandidate = (pair: CandidatePair): void => {\n if (pairs.length < maxPairs) pairs.push(pair);\n };\n\n const hasCapacity = (): boolean => pairs.length < maxPairs;\n const isSkippedByCooldown = (existing: ContradictionPair | undefined): boolean => {\n if (!existing || !isCoolingDown(existing, scanConfig.cooldownDays)) return false;\n return !memoryHashesChanged(\"\", existing, (memoryId) => currentMemoryHashes.get(memoryId) ?? null);\n };\n\n // Build index by entityRef for fast lookup\n const byEntity = new Map<string, MemoryFile[]>();\n for (const mem of orderedMemories) {\n const entity = mem.frontmatter.entityRef;\n if (entity) {\n const existing = byEntity.get(entity) ?? [];\n existing.push(mem);\n byEntity.set(entity, existing);\n }\n }\n\n // Strategy 1: Entity-ref based pairing (high precision)\n entityPairs:\n for (const entity of [...byEntity.keys()].sort()) {\n const group = byEntity.get(entity) ?? [];\n if (group.length < 2) continue;\n for (let i = 0; i < group.length; i++) {\n for (let j = i + 1; j < group.length; j++) {\n if (!hasCapacity()) break entityPairs;\n const a = group[i];\n const b = group[j];\n const pairId = computePairId(a.frontmatter.id!, b.frontmatter.id!, namespace);\n\n if (seen.has(pairId)) continue;\n seen.add(pairId);\n\n // Check cooldown\n const existing = getExistingPair(pairId);\n if (isSkippedByCooldown(existing)) {\n skipped++;\n continue;\n }\n\n pushCandidate({\n idA: a.frontmatter.id!,\n idB: b.frontmatter.id!,\n textA: a.content,\n textB: b.content,\n categoryA: a.frontmatter.category as string | undefined,\n categoryB: b.frontmatter.category as string | undefined,\n });\n }\n }\n }\n\n // Strategy 2: Tag/topic overlap for memories without a shared entityRef\n topicPairs:\n for (let i = 0; i < orderedMemories.length; i++) {\n for (let j = i + 1; j < orderedMemories.length; j++) {\n if (!hasCapacity()) break topicPairs;\n const a = orderedMemories[i];\n const b = orderedMemories[j];\n if (shareEntityRef(a, b)) continue;\n const overlap = jaccardOverlap(\n (a.frontmatter.tags as string[]) ?? [],\n (b.frontmatter.tags as string[]) ?? [],\n );\n\n if (overlap < scanConfig.topicOverlapFloor) continue;\n\n const pairId = computePairId(a.frontmatter.id!, b.frontmatter.id!, namespace);\n if (seen.has(pairId)) continue;\n seen.add(pairId);\n\n const existing = getExistingPair(pairId);\n if (isSkippedByCooldown(existing)) {\n skipped++;\n continue;\n }\n\n pushCandidate({\n idA: a.frontmatter.id!,\n idB: b.frontmatter.id!,\n textA: a.content,\n textB: b.content,\n categoryA: a.frontmatter.category as string | undefined,\n categoryB: b.frontmatter.category as string | undefined,\n });\n }\n }\n\n // Strategy 3: Embedding cosine similarity (enforces similarityFloor config)\n if (embeddingLookup && hasCapacity()) {\n const memoryById = new Map(orderedMemories.map((m) => [m.frontmatter.id!, m]));\n embeddingPairs:\n for (const mem of orderedMemories) {\n if (!hasCapacity()) break;\n const id = mem.frontmatter.id!;\n try {\n const hits = (await embeddingLookup(mem.content, 20)).sort((a, b) =>\n b.score - a.score || a.id.localeCompare(b.id),\n );\n for (const hit of hits) {\n if (!hasCapacity()) break embeddingPairs;\n if (hit.score < scanConfig.similarityFloor) continue;\n if (hit.id === id) continue;\n const peer = memoryById.get(hit.id);\n if (!peer) continue;\n\n const pairId = computePairId(id, hit.id, namespace);\n if (seen.has(pairId)) continue;\n seen.add(pairId);\n\n const existing = getExistingPair(pairId);\n if (isSkippedByCooldown(existing)) {\n skipped++;\n continue;\n }\n\n pushCandidate({\n idA: id,\n idB: hit.id,\n textA: mem.content,\n textB: peer.content,\n categoryA: mem.frontmatter.category as string | undefined,\n categoryB: peer.frontmatter.category as string | undefined,\n });\n }\n } catch {\n // Embedding backend unavailable — skip, entity-ref/tag strategies already covered\n }\n }\n }\n\n return { pairs, skipped };\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────────────\n\nfunction normalizeScanNamespace(namespace: string | undefined): string | undefined {\n const trimmed = namespace?.trim();\n return trimmed ? trimmed : undefined;\n}\n\n/**\n * Resolve the namespace-scoped storage a scan must read and write through.\n *\n * Exported and narrowed to the fields it actually reads so sibling scans\n * (preference drift, issue #2371) share ONE namespace resolver rather than\n * re-deriving the read/write namespace independently — the divergence the\n * namespace/ACL scenario matrix in AGENTS.md exists to prevent.\n */\nexport async function resolveScanStorage(\n deps: Pick<ScanDependencies, \"config\" | \"storage\" | \"storageForNamespace\">,\n namespace: string | undefined,\n): Promise<ScanStorageResolution> {\n if (!resolveNamespaceCapabilities(deps.config).namespaces) {\n const defaultNamespace = normalizeScanNamespace(deps.config.defaultNamespace);\n if (namespace && namespace !== defaultNamespace) {\n throw new Error(`unsupported namespace: ${namespace}`);\n }\n return { storage: deps.storage, namespace: undefined };\n }\n\n if (deps.storageForNamespace) {\n const resolved = await deps.storageForNamespace(namespace);\n if (isScanStorageResolution(resolved)) {\n return {\n storage: resolved.storage,\n namespace: normalizeScanNamespace(resolved.namespace) ?? fallbackResolvedNamespace(deps, namespace),\n };\n }\n if (!isStorageManagerLike(resolved)) {\n throw new Error(\"storageForNamespace must return a StorageManager or { storage: StorageManager, namespace?: string }\");\n }\n return {\n storage: resolved,\n namespace: fallbackResolvedNamespace(deps, namespace),\n };\n }\n\n throw new Error(\n \"contradiction scans require storageForNamespace when namespaces are enabled so callers can enforce namespace access\",\n );\n}\n\nfunction isScanStorageResolution(value: StorageManager | ScanStorageResolution): value is ScanStorageResolution {\n if (isStorageManagerLike(value)) return false;\n if (typeof value !== \"object\" || value === null) return false;\n const candidate = value as { storage?: unknown };\n return isStorageManagerLike(candidate.storage);\n}\n\nfunction isStorageManagerLike(value: unknown): value is StorageManager {\n if (typeof value !== \"object\" || value === null) return false;\n const candidate = value as { readAllMemories?: unknown };\n return typeof candidate.readAllMemories === \"function\";\n}\n\nfunction fallbackResolvedNamespace(\n deps: Pick<ScanDependencies, \"config\">,\n namespace: string | undefined,\n): string | undefined {\n if (namespace) return namespace;\n return resolveNamespaceCapabilities(deps.config).namespaces ? deps.config.defaultNamespace : undefined;\n}\n\nfunction isDefaultNamespaceScan(\n config: PluginConfig,\n requestedNamespace: string | undefined,\n resolvedNamespace: string,\n): boolean {\n if (requestedNamespace === undefined) return true;\n return requestedNamespace === config.defaultNamespace || resolvedNamespace === config.defaultNamespace;\n}\n\nasync function loadEligibleMemories(storage: StorageManager): Promise<MemoryFile[]> {\n let all: MemoryFile[];\n try {\n all = await storage.readAllMemories();\n } catch {\n return [];\n }\n\n return all.filter((mem) => {\n const fm = mem.frontmatter;\n if (isSupportPassportPrivateMemory(mem)) return false;\n // Only active memories (rule 53: explicit ACTIVE_STATUSES set)\n const status = (fm.status as MemoryStatus) ?? \"active\";\n if (!ACTIVE_STATUSES.has(status)) return false;\n\n // Only scan high-value categories\n const category = fm.category as string | undefined;\n if (category && !SCAN_CATEGORIES.has(category)) return false;\n\n // Must have content\n if (!mem.content || mem.content.trim().length === 0) return false;\n\n // Must have an ID\n if (!fm.id) return false;\n\n return true;\n });\n}\n\nfunction jaccardOverlap(a: string[], b: string[]): number {\n if (a.length === 0 && b.length === 0) return 0;\n const setA = new Set(a.map((t) => t.toLowerCase()));\n const setB = new Set(b.map((t) => t.toLowerCase()));\n let intersection = 0;\n for (const item of setA) {\n if (setB.has(item)) intersection++;\n }\n const union = setA.size + setB.size - intersection;\n return union === 0 ? 0 : intersection / union;\n}\n\nfunction shareEntityRef(a: MemoryFile, b: MemoryFile): boolean {\n const entityA = a.frontmatter.entityRef?.trim();\n const entityB = b.frontmatter.entityRef?.trim();\n return Boolean(entityA && entityB && entityA === entityB);\n}\n\nfunction compareMemoryId(a: MemoryFile, b: MemoryFile): number {\n return (a.frontmatter.id ?? \"\").localeCompare(b.frontmatter.id ?? \"\");\n}\n\nfunction memoryContentHashMap(memories: MemoryFile[]): Map<string, string> {\n const hashes = new Map<string, string>();\n for (const memory of memories) {\n const id = memory.frontmatter.id;\n if (!id) continue;\n hashes.set(id, computeMemoryContentHash(memory.content, memory.frontmatter.category as string | undefined));\n }\n return hashes;\n}\n\nfunction pairMemoryContentHashes(\n memoryIdA: string,\n memoryIdB: string,\n currentMemoryHashes: Map<string, string>,\n): Record<string, string> | undefined {\n const hashA = currentMemoryHashes.get(memoryIdA);\n const hashB = currentMemoryHashes.get(memoryIdB);\n if (!hashA || !hashB) return undefined;\n return {\n [memoryIdA]: hashA,\n [memoryIdB]: hashB,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAaA,SAAS,kBAAkB;AAuD3B,IAAM,6BAA6B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAuBnC,IAAI,sBAA6D,oBAAI,IAAI;AACzE,IAAM,YAAY;AAElB,SAAS,QAAQ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AS,GAAG;AAAA,EACf;AACF;","names":[]}
@@ -7,10 +7,10 @@ import {
7
7
  import {
8
8
  listMemoryGovernanceRuns,
9
9
  readMemoryGovernanceRunArtifact
10
- } from "./chunk-SYJ6EKKE.js";
10
+ } from "./chunk-EIVIB73I.js";
11
11
  import {
12
12
  StorageManager
13
- } from "./chunk-DEFI2QBT.js";
13
+ } from "./chunk-PAYGC3BD.js";
14
14
  import {
15
15
  normalizeProjectionPreview,
16
16
  normalizeProjectionTags
@@ -1005,4 +1005,4 @@ export {
1005
1005
  verifyMemoryProjection,
1006
1006
  repairMemoryProjection
1007
1007
  };
1008
- //# sourceMappingURL=chunk-ESCQ6LY7.js.map
1008
+ //# sourceMappingURL=chunk-QFMO32TO.js.map
@@ -296,4 +296,4 @@ async function searchHarmonicRetrieval(options) {
296
296
  export {
297
297
  searchHarmonicRetrieval
298
298
  };
299
- //# sourceMappingURL=chunk-HQSPXTQO.js.map
299
+ //# sourceMappingURL=chunk-QXIQPCCN.js.map
@@ -4,10 +4,10 @@ import {
4
4
  } from "./chunk-VI637ILW.js";
5
5
  import {
6
6
  composeSalvagedEnvelope
7
- } from "./chunk-UYCIS6V5.js";
7
+ } from "./chunk-JCWY73FK.js";
8
8
  import {
9
9
  StorageManager
10
- } from "./chunk-DEFI2QBT.js";
10
+ } from "./chunk-PAYGC3BD.js";
11
11
  import {
12
12
  parseContinuityImprovementLoops
13
13
  } from "./chunk-LDXUBPMO.js";
@@ -1283,4 +1283,4 @@ export {
1283
1283
  defaultTierMigrationCycleBudget,
1284
1284
  CompoundingEngine
1285
1285
  };
1286
- //# sourceMappingURL=chunk-CFRBTATE.js.map
1286
+ //# sourceMappingURL=chunk-R47WINCY.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  EXTRACTION_RESPONSE_PLACEHOLDERS
3
- } from "./chunk-JG22O53B.js";
3
+ } from "./chunk-7CBKAQIG.js";
4
4
  import {
5
5
  normalizeRecallTokens
6
6
  } from "./chunk-YCVB7X56.js";
@@ -69,4 +69,4 @@ export {
69
69
  extractionAttributes,
70
70
  extractionCueAnchors
71
71
  };
72
- //# sourceMappingURL=chunk-G72IPMR7.js.map
72
+ //# sourceMappingURL=chunk-R4OCGPSH.js.map
@@ -1,6 +1,9 @@
1
1
  import {
2
2
  normalizeTags
3
3
  } from "./chunk-BT7NVCML.js";
4
+ import {
5
+ isMemorySubject
6
+ } from "./chunk-RIAM7DND.js";
4
7
  import {
5
8
  assemblePersistedBody
6
9
  } from "./chunk-JDSVLVCG.js";
@@ -190,6 +193,17 @@ function composeMemoryEnvelope(input, ctx, opts = {}) {
190
193
  confidence = input.confidence;
191
194
  }
192
195
  }
196
+ let subject;
197
+ if (input.subject !== void 0) {
198
+ if (!isMemorySubject(input.subject)) {
199
+ hygiene.flag(
200
+ "subject",
201
+ `must be "user" or "agent" (got ${JSON.stringify(input.subject)}) \u2014 dropped`
202
+ );
203
+ } else {
204
+ subject = input.subject;
205
+ }
206
+ }
193
207
  const validAt = input.validAt === void 0 ? void 0 : validateIsoTimestamp("validAt", input.validAt);
194
208
  const now = ctx.now ? ctx.now() : /* @__PURE__ */ new Date();
195
209
  if (!(now instanceof Date) || Number.isNaN(now.getTime())) {
@@ -212,11 +226,12 @@ function composeMemoryEnvelope(input, ctx, opts = {}) {
212
226
  structuredAttributes: attributes?.canonical,
213
227
  rawStructuredAttributes: attributes?.raw,
214
228
  entityRef: normalizeOptionalString("entityRef", input.entityRef, hygiene),
229
+ origin: normalizeOptionalString("origin", input.origin, hygiene),
230
+ subject,
215
231
  confidence,
216
232
  ttl: normalizeOptionalString("ttl", input.ttl, hygiene),
217
233
  validAt,
218
234
  sourceConnector: normalizeOptionalString("sourceConnector", input.sourceConnector, hygiene),
219
- origin: normalizeOptionalString("origin", input.origin, hygiene),
220
235
  sourceReason: normalizeOptionalString("sourceReason", input.sourceReason, hygiene),
221
236
  source: ctx.source.trim(),
222
237
  composedAt: now.toISOString(),
@@ -308,8 +323,9 @@ function sealedWriteToLegacyArgs(envelope, extras = {}) {
308
323
  // extras — a conditional spread let extras.sourceConnector smuggle
309
324
  // unvalidated connector provenance past the sealed envelope when the
310
325
  // envelope had none.
326
+ origin: envelope.origin,
311
327
  sourceConnector: envelope.sourceConnector,
312
- origin: envelope.origin
328
+ subject: envelope.subject
313
329
  }
314
330
  };
315
331
  }
@@ -330,6 +346,9 @@ var FINGERPRINT_EXEMPT_FIELDS = [
330
346
  // Free-text provenance note; carries no identity.
331
347
  // Origin is provenance metadata, not write identity (#1955).
332
348
  "origin",
349
+ // Subject is derived classification metadata (#2372): two writes identical
350
+ // except subject are the same memory for dedup purposes.
351
+ "subject",
333
352
  "sourceReason"
334
353
  ];
335
354
  var FINGERPRINT_SCOPE_FIELDS = [
@@ -423,4 +442,4 @@ export {
423
442
  buildAccessWriteRequestFingerprint,
424
443
  buildObserveRequestFingerprint
425
444
  };
426
- //# sourceMappingURL=chunk-LCU5R6TQ.js.map
445
+ //# sourceMappingURL=chunk-RAIUTAZZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/write-envelope.ts"],"sourcesContent":["/**\n * Sealed memory-write envelope (issue #1989, umbrella #1988).\n *\n * THE single stamping point for cross-cutting memory-creation fields.\n *\n * Why this exists: PR #1852 needed 27 rework commits because adding one\n * cross-cutting field (`sourceConnector`) required hand-editing every\n * write call site and every idempotency payload, and reviewers discovered\n * missed sites one round at a time. This module removes the fan-out:\n *\n * 1. `composeMemoryEnvelope()` is the only way to mint a\n * `SealedMemoryEnvelope` — the brand is a non-exported `unique symbol`,\n * so a hand-built object literal fails `tsc` (`npm run check-types`\n * is already a required repo-wide gate; the type system IS the fence).\n * 2. `buildWriteIdempotencyPayload()` derives every access-surface\n * idempotency payload from ONE ordered field registry\n * (`WRITE_FINGERPRINT_FIELDS`). Adding a fingerprint-relevant field is\n * a one-line registry change picked up by every surface; forgetting to\n * classify a new `MemoryWriteInput` field is a compile error (see the\n * exhaustiveness guards at the bottom of this file).\n *\n * PR1 scope (no call-site changes): the composer, the registry, and the\n * payload builder, fully tested. PR2–PR4 migrate storage entry points and\n * the write call sites onto this module (see #1989 for the slicing).\n */\n\nimport { isMemorySubject } from \"./memory-subject.js\";\nimport type { MemoryCategory, MemorySubject } from \"./types.js\";\nimport { normalizeTags } from \"./recall-tag-filter.js\";\nimport { parseFlexibleIsoTimestamp } from \"./utils/iso-timestamp.js\";\nimport { assemblePersistedBody } from \"./structured-attributes.js\";\n\n// ---------------------------------------------------------------------------\n// Input surface\n// ---------------------------------------------------------------------------\n\n/**\n * Every cross-cutting memory-creation field lives HERE and only here.\n *\n * When you add a field you MUST also add it to either\n * `WRITE_FINGERPRINT_FIELDS` or `FINGERPRINT_EXEMPT_FIELDS` — the\n * exhaustiveness guard below makes forgetting a compile error.\n */\nexport interface MemoryWriteInput {\n /** Raw memory content. Must be non-empty after trimming. */\n content: string;\n /** Memory category — validated against the canonical category set. */\n category: MemoryCategory;\n /** Free-form labels; normalized (trim/dedupe) and capped, see TAG_LIMITS. */\n tags?: string[];\n /** String→string structured attributes; non-string values are rejected. */\n structuredAttributes?: Record<string, string>;\n /** Entity file reference (e.g. `person-jane-doe`). */\n entityRef?: string;\n /** Extraction confidence in [0, 1]. */\n confidence?: number;\n /** Opaque TTL expression (e.g. `90d` or an ISO date) — validated non-empty. */\n ttl?: string;\n /** Event-time validity start (ISO 8601). */\n validAt?: string;\n /** Connector identity that produced this write (issue #1852). */\n sourceConnector?: string;\n /** Origin class stamped at creation time (issue #1955). */\n origin?: string;\n /** Whom the memory models (issue #2372): \"user\" or \"agent\". */\n subject?: MemorySubject;\n /** Human-readable provenance note. */\n sourceReason?: string;\n}\n\n/** Context supplied by the write path, not by the payload author. */\nexport interface WriteContext {\n /** Frontmatter `source` string (e.g. `extraction`, `wearable:bee`). */\n source: string;\n /** Clock override for tests. */\n now?: () => Date;\n}\n\n/** Scope facts that participate in idempotency but never in frontmatter. */\nexport interface FingerprintScope {\n /** Access surface performing the write (e.g. `memory_store`, `observe`). */\n surface: string;\n namespace?: string;\n principal?: string;\n codingContext?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Normalization limits (single source of truth — docs/tags.md contract)\n// ---------------------------------------------------------------------------\n\nexport const TAG_LIMITS = Object.freeze({\n /** Maximum number of tags persisted per memory. */\n maxTags: 50,\n /** Maximum length of a single tag. */\n maxTagLength: 256,\n});\n\nexport const STRUCTURED_ATTRIBUTE_LIMITS = Object.freeze({\n /** Maximum number of structured attributes per memory. */\n maxEntries: 64,\n /** Maximum length of one attribute key. */\n maxKeyLength: 128,\n /** Maximum length of one attribute value. */\n maxValueLength: 1024,\n});\n\nconst MEMORY_CATEGORY_TABLE: Record<MemoryCategory, true> = {\n fact: true,\n preference: true,\n correction: true,\n entity: true,\n decision: true,\n relationship: true,\n principle: true,\n commitment: true,\n moment: true,\n skill: true,\n rule: true,\n procedure: true,\n reasoning_trace: true,\n};\n\nconst MEMORY_CATEGORY_NAMES = Object.keys(MEMORY_CATEGORY_TABLE).sort();\n\nexport function isMemoryCategory(value: string): value is MemoryCategory {\n return Object.prototype.hasOwnProperty.call(MEMORY_CATEGORY_TABLE, value);\n}\n\n// ---------------------------------------------------------------------------\n// Sealed envelope\n// ---------------------------------------------------------------------------\n\ndeclare const sealed: unique symbol;\n\n/**\n * A normalized, validated memory-write envelope.\n *\n * Opaque: only `composeMemoryEnvelope()` can mint one. Storage creation\n * entry points accept this type (PR2), so every write path is forced\n * through the composer at compile time.\n */\nexport interface SealedMemoryEnvelope {\n readonly [sealed]: true;\n /**\n * Caller-supplied content VERBATIM (validated non-empty-after-trim).\n * `StorageManager.writeMemory` persists content byte-for-byte (callers\n * that trim, e.g. explicit capture, do so before composing), so the\n * envelope must not transform it — the earlier compose-time trim/sanitize\n * broke byte-parity with extraction writes and was removed in PR2.\n */\n readonly content: string;\n /**\n * The exact body persistence will write: attribute-suffix enrichment then\n * combined sanitization, produced by the SAME `assemblePersistedBody`\n * helper `writeMemory` uses (issue #1989 PR2; AGENTS.md §13). This is the\n * form write-idempotency fingerprints hash.\n */\n readonly persistedBody: string;\n /** Injection patterns matched during body assembly (empty = clean). */\n readonly sanitizeViolations: readonly string[];\n /**\n * Salvage-mode hygiene notes (empty in strict mode): each dropped/clamped\n * invalid optional field is recorded here — visible, never silent\n * (repo rule 34). Callers persisting machine-generated input log these.\n */\n readonly salvageNotes: readonly string[];\n readonly category: MemoryCategory;\n readonly tags: readonly string[];\n /**\n * CANONICAL attributes (keys trim+lowercase, values trim) — the form\n * fingerprints and downstream consumers use; stable across caller casing.\n */\n readonly structuredAttributes: Readonly<Record<string, string>> | undefined;\n /**\n * The validated ORIGINAL attribute map, byte-preserved. `writeMemory`\n * persists frontmatter attributes raw (canonicalizing only the body\n * suffix via normalizeAttributePairs) — a pre-existing raw/canonical\n * inconsistency (supersession keys read the raw form). The sealed path\n * preserves those bytes; canonicalizing the frontmatter at the storage\n * boundary is a follow-up once the legacy path retires (#1989 PR4).\n */\n readonly rawStructuredAttributes: Readonly<Record<string, string>> | undefined;\n readonly entityRef: string | undefined;\n readonly confidence: number | undefined;\n readonly ttl: string | undefined;\n readonly validAt: string | undefined;\n readonly sourceConnector: string | undefined;\n readonly origin: string | undefined;\n readonly subject: MemorySubject | undefined;\n readonly sourceReason: string | undefined;\n readonly source: string;\n /** ISO timestamp the envelope was composed (from ctx.now). */\n readonly composedAt: string;\n}\n\nfunction fail(field: string, message: string): never {\n throw new Error(`composeMemoryEnvelope: ${field} ${message}`);\n}\n\n/**\n * Compose-time input hygiene mode (issue #1989 PR2, review round on #2014).\n *\n * - `strict` (default): every invalid field throws — correct for OPERATOR\n * and API input (explicit capture, memory_store), where a bad value is a\n * caller bug that must surface.\n * - `salvage`: for MACHINE-GENERATED input (LLM extraction, wearable\n * ingestion). One malformed fact from an extractor must not abort a whole\n * persistence batch that legacy `writeMemory` would have accepted.\n * Invalid tags/attributes/optional fields are DROPPED with a note pushed\n * to `envelope.salvageNotes` — visible, never silent (repo rule 34);\n * callers log the notes. Content, category, ctx.source, and validAt stay\n * FATAL in both modes (legacy writeMemory also throws on bad validAt, and\n * a write without valid content/category cannot proceed).\n */\nexport interface ComposeEnvelopeOptions {\n salvage?: boolean;\n}\n\n/** Internal reporter: throws in strict mode, records a note in salvage. */\ninterface Hygiene {\n salvage: boolean;\n notes: string[];\n flag(field: string, message: string): void;\n}\n\nfunction makeHygiene(salvage: boolean): Hygiene {\n const notes: string[] = [];\n return {\n salvage,\n notes,\n flag(field: string, message: string): void {\n if (!salvage) fail(field, message);\n notes.push(`${field} ${message}`);\n },\n };\n}\n\n/**\n * Validate and CANONICALIZE `validAt` via the repo's shared flexible ISO\n * parser (`utils/iso-timestamp.ts`) — the same family durable writes use, so\n * the envelope can never accept a value storage would reject or reinterpret\n * (review findings on #1998: no second validation convention; reduced\n * precision like `2026-07-17T09:30Z` is valid; offsets are bounded ±14:00;\n * `Date.parse` alone is not an ISO validator).\n *\n * Canonical form is the epoch round-trip (`Date.toISOString()`), so\n * fingerprints are identical for `...T09:30Z`, `...T09:30:00.000Z`, and the\n * same instant expressed with an offset (§13 hash-consistency).\n */\nfunction validateIsoTimestamp(field: string, value: string): string {\n const trimmed = value.trim();\n if (trimmed.length === 0) fail(field, \"must be a non-empty ISO 8601 timestamp\");\n const epochMs = parseFlexibleIsoTimestamp(trimmed);\n if (epochMs === null) {\n fail(\n field,\n `is not a valid ISO 8601 date/timestamp: ${JSON.stringify(value)} (date-only, reduced precision, Z, and ±HH:MM offsets up to ±14:00 are accepted; calendar overflow is not)`,\n );\n }\n return new Date(epochMs).toISOString();\n}\n\nfunction normalizeEnvelopeTags(raw: string[] | undefined, hygiene: Hygiene): readonly string[] {\n if (raw === undefined) return Object.freeze([]);\n if (!Array.isArray(raw)) {\n hygiene.flag(\"tags\", \"must be an array of strings — dropped\");\n return Object.freeze([]);\n }\n const usable: string[] = [];\n for (const tag of raw) {\n if (typeof tag !== \"string\") {\n hygiene.flag(\"tags\", `entries must be strings (got ${typeof tag})`);\n continue;\n }\n if (tag.trim().length > TAG_LIMITS.maxTagLength) {\n hygiene.flag(\"tags\", `entry exceeds ${TAG_LIMITS.maxTagLength} characters: ${JSON.stringify(tag.slice(0, 40))}…`);\n continue;\n }\n usable.push(tag);\n }\n let normalized = normalizeTags(usable) ?? [];\n if (normalized.length > TAG_LIMITS.maxTags) {\n hygiene.flag(\"tags\", `exceed the ${TAG_LIMITS.maxTags}-tag limit (got ${normalized.length}) — keeping the first ${TAG_LIMITS.maxTags}`);\n normalized = normalized.slice(0, TAG_LIMITS.maxTags);\n }\n return Object.freeze(normalized);\n}\n\nfunction normalizeStructuredAttributes(\n raw: Record<string, string> | undefined,\n hygiene: Hygiene,\n): { canonical: Readonly<Record<string, string>>; raw: Readonly<Record<string, string>> } | undefined {\n if (raw === undefined) return undefined;\n if (\n raw === null ||\n typeof raw !== \"object\" ||\n Array.isArray(raw) ||\n (Object.getPrototypeOf(raw) !== Object.prototype && Object.getPrototypeOf(raw) !== null)\n ) {\n // Map/Date/class instances have empty Object.entries() and would\n // silently normalize to \"no attributes\" (review finding on #1998\n // round 5) — never a plain pass-through.\n hygiene.flag(\"structuredAttributes\", \"must be a plain object of string values (Map, Date, and class instances are rejected) — dropped\");\n return undefined;\n }\n let entries = Object.entries(raw);\n if (entries.length === 0) return undefined;\n if (entries.length > STRUCTURED_ATTRIBUTE_LIMITS.maxEntries) {\n hygiene.flag(\n \"structuredAttributes\",\n `exceed the ${STRUCTURED_ATTRIBUTE_LIMITS.maxEntries}-entry limit (got ${entries.length}) — keeping the first ${STRUCTURED_ATTRIBUTE_LIMITS.maxEntries} in insertion order`,\n );\n entries = entries.slice(0, STRUCTURED_ATTRIBUTE_LIMITS.maxEntries);\n }\n // Keys that collide with Object.prototype machinery are REJECTED outright:\n // `hashAccessIdempotencyPayload`'s stableStringify rebuilds objects with\n // plain assignment, where a \"__proto__\" own property silently vanishes —\n // so such a key can never round-trip through the fingerprint faithfully\n // (review finding on #1998 round 3). Rejection beats smuggling (§1/§39).\n const FORBIDDEN_ATTRIBUTE_KEYS = [\"__proto__\", \"constructor\", \"prototype\"];\n const out: Record<string, string> = Object.create(null);\n const survivingOriginal: Array<[string, string]> = [];\n for (const [key, value] of entries) {\n // Canonicalize exactly like storage's normalizeAttributePairs\n // (storage.ts:1277): keys trim+lowercase, values trim — so the\n // fingerprint and the persisted searchable form can never diverge\n // (review finding on #1998; AGENTS.md §13 hash-consistency).\n const cleanKey = key.trim().toLowerCase();\n if (cleanKey.length === 0) {\n hygiene.flag(\"structuredAttributes\", \"contain an empty key\");\n continue;\n }\n if (cleanKey.length > STRUCTURED_ATTRIBUTE_LIMITS.maxKeyLength) {\n hygiene.flag(\"structuredAttributes\", `key exceeds ${STRUCTURED_ATTRIBUTE_LIMITS.maxKeyLength} characters: ${JSON.stringify(cleanKey.slice(0, 40))}…`);\n continue;\n }\n if (typeof value !== \"string\") {\n hygiene.flag(\"structuredAttributes\", `value for ${JSON.stringify(cleanKey)} must be a string (got ${typeof value}) — stringify numbers/booleans at the call site`);\n continue;\n }\n const cleanValue = value.trim();\n if (FORBIDDEN_ATTRIBUTE_KEYS.includes(cleanKey)) {\n hygiene.flag(\n \"structuredAttributes\",\n `contain the reserved key ${JSON.stringify(cleanKey)} — prototype-machinery names cannot round-trip through fingerprint serialization`,\n );\n continue;\n }\n if (cleanValue.length > STRUCTURED_ATTRIBUTE_LIMITS.maxValueLength) {\n hygiene.flag(\"structuredAttributes\", `value for ${JSON.stringify(cleanKey)} exceeds ${STRUCTURED_ATTRIBUTE_LIMITS.maxValueLength} characters`);\n continue;\n }\n if (Object.hasOwn(out, cleanKey)) {\n hygiene.flag(\"structuredAttributes\", `contain duplicate key after canonicalization (trim + lowercase): ${JSON.stringify(cleanKey)}`);\n continue;\n }\n out[cleanKey] = cleanValue;\n survivingOriginal.push([key, value]);\n }\n if (Object.keys(out).length === 0) return undefined;\n // Copy onto a normal object so downstream JSON/stableStringify behavior is\n // unchanged; keys are already validated. The RAW map carries only the\n // SURVIVING original pairs — dropped entries must not reach frontmatter.\n return {\n canonical: Object.freeze({ ...out }),\n raw: Object.freeze(Object.fromEntries(survivingOriginal)),\n };\n}\n\nfunction normalizeOptionalString(\n field: string,\n value: string | undefined,\n hygiene: Hygiene,\n): string | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== \"string\") {\n hygiene.flag(field, `must be a string (got ${typeof value}) — dropped`);\n return undefined;\n }\n const trimmed = value.trim();\n if (trimmed.length === 0) {\n hygiene.flag(field, \"must be non-empty when provided — dropped\");\n return undefined;\n }\n return trimmed;\n}\n\n/**\n * Compose (normalize + validate + seal) a memory-write envelope.\n *\n * Strict mode (default) throws on any invalid input — never silently\n * defaults (AGENTS.md §1/§39). Salvage mode (`{ salvage: true }`, for\n * machine-generated input like LLM extraction) drops invalid OPTIONAL\n * fields with notes on `envelope.salvageNotes` instead of aborting the\n * batch; content/category/source/validAt stay fatal in both modes.\n */\nexport function composeMemoryEnvelope(\n input: MemoryWriteInput,\n ctx: WriteContext,\n opts: ComposeEnvelopeOptions = {},\n): SealedMemoryEnvelope {\n if (input === null || typeof input !== \"object\") fail(\"input\", \"must be an object\");\n if (ctx === null || typeof ctx !== \"object\") fail(\"ctx\", \"must be an object\");\n const hygiene = makeHygiene(opts.salvage === true);\n\n if (typeof input.content !== \"string\" || input.content.trim().length === 0) {\n fail(\"content\", \"must be a non-empty string\");\n }\n if (typeof input.category !== \"string\" || !isMemoryCategory(input.category)) {\n fail(\n \"category\",\n `must be one of: ${MEMORY_CATEGORY_NAMES.join(\", \")} (got ${JSON.stringify(input.category)})`,\n );\n }\n if (typeof ctx.source !== \"string\" || ctx.source.trim().length === 0) {\n fail(\"ctx.source\", \"must be a non-empty string\");\n }\n\n let confidence: number | undefined;\n if (input.confidence !== undefined) {\n if (\n typeof input.confidence !== \"number\" ||\n !Number.isFinite(input.confidence) ||\n input.confidence < 0 ||\n input.confidence > 1\n ) {\n hygiene.flag(\n \"confidence\",\n `must be a finite number within [0, 1] (got ${String(input.confidence)}) — dropped (storage defaults apply)`,\n );\n } else {\n confidence = input.confidence;\n }\n }\n\n let subject: MemorySubject | undefined;\n if (input.subject !== undefined) {\n if (!isMemorySubject(input.subject)) {\n hygiene.flag(\n \"subject\",\n `must be \"user\" or \"agent\" (got ${JSON.stringify(input.subject)}) — dropped`,\n );\n } else {\n subject = input.subject;\n }\n }\n\n // validAt stays FATAL in salvage too: legacy writeMemory throws on an\n // invalid validAt (normalizeMemoryWriteTimestamp), so salvage-dropping it\n // would CHANGE behavior rather than preserve it.\n const validAt =\n input.validAt === undefined ? undefined : validateIsoTimestamp(\"validAt\", input.validAt);\n\n const now = ctx.now ? ctx.now() : new Date();\n if (!(now instanceof Date) || Number.isNaN(now.getTime())) {\n fail(\"ctx.now\", \"must return a valid Date\");\n }\n\n const attributes = normalizeStructuredAttributes(input.structuredAttributes, hygiene);\n // Assemble the EXACT persisted form (attribute suffix + combined sanitize)\n // with the same helper writeMemory uses — fingerprints hash this form, so\n // envelope and storage cannot diverge (§13; #1998 round-8 thread resolved\n // here in PR2 as promised). writeMemory assembles from the RAW map;\n // normalizeAttributePairs canonicalizes internally, so raw and canonical\n // maps yield the same suffix — asserted by the parity suite.\n const assembled = assemblePersistedBody(\n input.content,\n attributes ? { ...attributes.raw } : undefined,\n );\n if (assembled.text.trim().length === 0) {\n fail(\"content\", \"is empty after sanitization\");\n }\n\n const body = {\n content: input.content,\n persistedBody: assembled.text,\n sanitizeViolations: Object.freeze([...assembled.violations]),\n category: input.category,\n tags: normalizeEnvelopeTags(input.tags, hygiene),\n structuredAttributes: attributes?.canonical,\n rawStructuredAttributes: attributes?.raw,\n entityRef: normalizeOptionalString(\"entityRef\", input.entityRef, hygiene),\n origin: normalizeOptionalString(\"origin\", input.origin, hygiene),\n subject,\n confidence,\n ttl: normalizeOptionalString(\"ttl\", input.ttl, hygiene),\n validAt,\n sourceConnector: normalizeOptionalString(\"sourceConnector\", input.sourceConnector, hygiene),\n sourceReason: normalizeOptionalString(\"sourceReason\", input.sourceReason, hygiene),\n source: ctx.source.trim(),\n composedAt: now.toISOString(),\n salvageNotes: Object.freeze([...hygiene.notes]),\n };\n const envelope = Object.freeze(body) as unknown as SealedMemoryEnvelope;\n SEALED_ENVELOPES.add(envelope);\n return envelope;\n}\n\n// The runtime seal registry. The declared `sealed` unique symbol exists only\n// at the type level (compile-time fence); this WeakSet is the runtime fence.\nconst SEALED_ENVELOPES = new WeakSet<object>();\n\n/**\n * TOCTOU guard for the structural arm (#2014 round 4): a frozen object may\n * still carry ACCESSOR properties whose getters return different values on\n * each read — valid data during re-composition, forged data when the write\n * path reads the field again. Frozen DATA properties are immutable, so\n * requiring data-only descriptors (on the envelope and its array/map\n * fields) makes every later read provably identical to the validated one.\n */\nfunction hasOnlyFrozenDataProperties(value: object): boolean {\n if (!Object.isFrozen(value)) return false;\n // Inherited accessors are as dangerous as own ones (round 5): a frozen\n // object can inherit a `tags` getter from a custom prototype. Composer\n // envelopes are plain object literals and plain arrays — require exactly\n // those prototypes so prototype-supplied getters cannot serve fields.\n const proto = Object.getPrototypeOf(value);\n if (Array.isArray(value)) {\n if (proto !== Array.prototype) return false;\n } else if (proto !== Object.prototype && proto !== null) {\n return false;\n }\n for (const key of Reflect.ownKeys(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (!descriptor || descriptor.get !== undefined || descriptor.set !== undefined) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Runtime check (belt) — the compile-time brand is the real fence.\n *\n * Fast path: WeakSet membership (same module graph). Fallback: RE-COMPOSITION\n * EQUIVALENCE — Node resolves `@remnic/core` through `dist/` for built\n * consumers and `src/` for tsx-loaded tests, and each graph gets its OWN\n * WeakSet, so identity alone would reject genuinely-sealed envelopes that\n * crossed a build boundary. The structural arm requires frozen DATA-only\n * properties (no accessors — TOCTOU guard, round 4), then re-runs the\n * STRICT composer on the candidate's own inputs and demands every envelope\n * field reproduce exactly (#2014 round 2: shape-only validation admitted\n * lookalikes with 51 tags or out-of-range confidence). A value that\n * survives has, by construction, passed every composer invariant, and its\n * fields cannot change between validation and the write that follows.\n *\n * `salvageNotes` is deliberately NOT compared: a legitimately salvage-minted\n * envelope carries notes while the strict re-composition of its (already\n * clean) surviving fields yields none. Notes are advisory provenance, not\n * identity — every load-bearing field is still verified.\n */\n\nexport function isSealedMemoryEnvelope(value: unknown): value is SealedMemoryEnvelope {\n if (typeof value !== \"object\" || value === null) return false;\n if (SEALED_ENVELOPES.has(value)) return true;\n if (!hasOnlyFrozenDataProperties(value)) return false;\n const v = value as Partial<SealedMemoryEnvelope>;\n if (\n typeof v.content !== \"string\" ||\n typeof v.persistedBody !== \"string\" ||\n typeof v.source !== \"string\" ||\n typeof v.composedAt !== \"string\" ||\n typeof v.category !== \"string\" ||\n !isMemoryCategory(v.category) ||\n !Array.isArray(v.tags) ||\n !hasOnlyFrozenDataProperties(v.tags) ||\n !Array.isArray(v.sanitizeViolations) ||\n !hasOnlyFrozenDataProperties(v.sanitizeViolations) ||\n !Array.isArray(v.salvageNotes) ||\n !hasOnlyFrozenDataProperties(v.salvageNotes)\n ) {\n return false;\n }\n const attrs = v.rawStructuredAttributes;\n if (\n attrs !== undefined &&\n (attrs === null || typeof attrs !== \"object\" || Array.isArray(attrs) || !hasOnlyFrozenDataProperties(attrs))\n ) {\n return false;\n }\n const canonicalAttrs = v.structuredAttributes;\n if (\n canonicalAttrs !== undefined &&\n (canonicalAttrs === null ||\n typeof canonicalAttrs !== \"object\" ||\n Array.isArray(canonicalAttrs) ||\n !hasOnlyFrozenDataProperties(canonicalAttrs))\n ) {\n return false;\n }\n let rebuilt: SealedMemoryEnvelope;\n try {\n rebuilt = composeMemoryEnvelope(\n {\n content: v.content,\n category: v.category,\n ...(v.tags.length > 0 ? { tags: [...(v.tags as string[])] } : {}),\n ...(attrs !== undefined ? { structuredAttributes: { ...attrs } } : {}),\n ...(v.entityRef !== undefined ? { entityRef: v.entityRef } : {}),\n ...(v.confidence !== undefined ? { confidence: v.confidence } : {}),\n ...(v.ttl !== undefined ? { ttl: v.ttl } : {}),\n ...(v.validAt !== undefined ? { validAt: v.validAt } : {}),\n ...(v.sourceConnector !== undefined ? { sourceConnector: v.sourceConnector } : {}),\n ...(v.origin !== undefined ? { origin: v.origin } : {}),\n ...(v.sourceReason !== undefined ? { sourceReason: v.sourceReason } : {}),\n },\n { source: v.source, now: () => new Date(v.composedAt as string) },\n );\n } catch {\n // Strict re-composition rejected an input — the candidate carries a\n // value the composer would never have minted.\n return false;\n }\n const sameArray = (a: readonly string[], b: readonly string[]): boolean =>\n a.length === b.length && a.every((entry, i) => entry === b[i]);\n const sameMap = (\n a: Readonly<Record<string, string>> | undefined,\n b: Readonly<Record<string, string>> | undefined,\n ): boolean => {\n if (a === undefined || b === undefined) return a === b;\n const ak = Object.keys(a);\n const bk = Object.keys(b);\n return ak.length === bk.length && ak.every((k) => Object.hasOwn(b, k) && a[k] === b[k]);\n };\n return (\n rebuilt.content === v.content &&\n rebuilt.persistedBody === v.persistedBody &&\n rebuilt.category === v.category &&\n rebuilt.source === v.source &&\n rebuilt.composedAt === v.composedAt &&\n rebuilt.confidence === v.confidence &&\n rebuilt.entityRef === v.entityRef &&\n rebuilt.ttl === v.ttl &&\n rebuilt.validAt === v.validAt &&\n rebuilt.sourceConnector === v.sourceConnector &&\n rebuilt.origin === v.origin &&\n rebuilt.sourceReason === v.sourceReason &&\n sameArray(rebuilt.tags, v.tags as string[]) &&\n sameArray(rebuilt.sanitizeViolations, v.sanitizeViolations as string[]) &&\n sameMap(rebuilt.structuredAttributes, v.structuredAttributes) &&\n sameMap(rebuilt.rawStructuredAttributes, attrs)\n );\n}\n\n/**\n * The ONE mapping from a sealed envelope (+ extras) to the legacy\n * `writeMemory(category, content, options)` argument shape. Used by\n * `StorageManager.writeSealedMemory` AND by test doubles that stub storage —\n * so mock fidelity (AGENTS.md §21) cannot drift from production.\n */\nexport function sealedWriteToLegacyArgs(\n envelope: SealedMemoryEnvelope,\n extras: Record<string, unknown> = {},\n): { category: MemoryCategory; content: string; options: Record<string, unknown> } {\n return {\n category: envelope.category,\n content: envelope.content,\n options: {\n ...extras,\n confidence: envelope.confidence,\n tags: envelope.tags.length > 0 ? [...envelope.tags] : undefined,\n entityRef: envelope.entityRef,\n source: envelope.source,\n expiresAt: envelope.ttl,\n validAt: envelope.validAt,\n // RAW map for frontmatter byte-parity with the legacy path; the body\n // suffix canonicalizes identically from either form.\n structuredAttributes: envelope.rawStructuredAttributes\n ? { ...envelope.rawStructuredAttributes }\n : undefined,\n // Unconditional (round 3): envelope-owned fields must ALWAYS overwrite\n // extras — a conditional spread let extras.sourceConnector smuggle\n // unvalidated connector provenance past the sealed envelope when the\n // envelope had none.\n origin: envelope.origin,\n sourceConnector: envelope.sourceConnector,\n subject: envelope.subject,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Idempotency field registry\n// ---------------------------------------------------------------------------\n\n/**\n * Ordered registry of envelope fields that participate in write-idempotency\n * fingerprints. Adding a fingerprint-relevant field = one entry here; every\n * surface that builds its payload via `buildWriteIdempotencyPayload()` picks\n * it up automatically.\n */\nexport const WRITE_FINGERPRINT_FIELDS = [\n \"content\",\n \"category\",\n \"tags\",\n \"structuredAttributes\",\n \"entityRef\",\n \"ttl\",\n \"validAt\",\n \"sourceConnector\",\n] as const satisfies readonly (keyof MemoryWriteInput)[];\n\n/**\n * Envelope fields deliberately EXCLUDED from fingerprints. Exempting a field\n * is a visible, reviewable decision — this list exists so the exhaustiveness\n * guard can force every new `MemoryWriteInput` field to be classified.\n */\nexport const FINGERPRINT_EXEMPT_FIELDS = [\n // Confidence is a scoring detail: two extractions of the same fact with\n // slightly different confidence are the same write for dedup purposes.\n \"confidence\",\n // Free-text provenance note; carries no identity.\n // Origin is provenance metadata, not write identity (#1955).\n \"origin\",\n // Subject is derived classification metadata (#2372): two writes identical\n // except subject are the same memory for dedup purposes.\n \"subject\",\n \"sourceReason\",\n] as const satisfies readonly (keyof MemoryWriteInput)[];\n\n/** Scope keys always folded into the fingerprint payload. */\nexport const FINGERPRINT_SCOPE_FIELDS = [\n \"surface\",\n \"namespace\",\n \"principal\",\n \"codingContext\",\n] as const satisfies readonly (keyof FingerprintScope)[];\n\n// --- compile-time exhaustiveness guards ------------------------------------\n// A new MemoryWriteInput field that is in NEITHER list is a compile error;\n// a registry entry that names a non-existent field is a compile error; a\n// field in BOTH lists is a compile error.\n\ntype RegistryField = (typeof WRITE_FINGERPRINT_FIELDS)[number];\ntype ExemptField = (typeof FINGERPRINT_EXEMPT_FIELDS)[number];\ntype UnclassifiedField = Exclude<keyof MemoryWriteInput, RegistryField | ExemptField>;\ntype DoublyClassifiedField = RegistryField & ExemptField;\n\nconst assertEveryFieldClassified: UnclassifiedField extends never ? true : never = true;\nconst assertNoDoubleClassification: DoublyClassifiedField extends never ? true : never = true;\nvoid assertEveryFieldClassified;\nvoid assertNoDoubleClassification;\n\n// ---------------------------------------------------------------------------\n// Payload builder\n// ---------------------------------------------------------------------------\n\n/**\n * Build the canonical write-idempotency payload for a sealed envelope.\n *\n * Determinism guarantees (AGENTS.md §26):\n * - tags are SORTED in the payload (tag order never changes identity);\n * - structured attributes are serialized key-sorted by the existing\n * `stableStringify` inside `hashAccessIdempotencyPayload`;\n * - the payload shape is versioned (`v: 1`) so a future field-semantics\n * change can migrate stored idempotency state explicitly instead of\n * silently colliding.\n *\n * Feed the result to `hashAccessIdempotencyPayload()` — this module does\n * not hash so surfaces keep a single hashing implementation.\n */\nexport function buildWriteIdempotencyPayload(\n envelope: SealedMemoryEnvelope,\n scope: FingerprintScope,\n): Record<string, unknown> {\n if (!isSealedMemoryEnvelope(envelope)) {\n throw new Error(\n \"buildWriteIdempotencyPayload: envelope must be minted by composeMemoryEnvelope\",\n );\n }\n if (scope === null || typeof scope !== \"object\") {\n throw new Error(\"buildWriteIdempotencyPayload: scope must be an object\");\n }\n if (typeof scope.surface !== \"string\" || scope.surface.trim().length === 0) {\n throw new Error(\"buildWriteIdempotencyPayload: scope.surface must be a non-empty string\");\n }\n\n const fields: Record<string, unknown> = {};\n for (const field of WRITE_FINGERPRINT_FIELDS) {\n const value = envelope[field];\n if (value === undefined) continue;\n if (field === \"tags\") {\n const tags = value as readonly string[];\n if (tags.length === 0) continue;\n fields.tags = [...tags].sort();\n continue;\n }\n if (field === \"content\") {\n // Fingerprints hash the PERSISTED form (attribute suffix + combined\n // sanitize), not the raw input — one instant of stored state, one\n // fingerprint (§13; issue #1989 PR2).\n fields.content = envelope.persistedBody;\n continue;\n }\n fields[field] = value;\n }\n // The write source (extraction vs wearable:bee vs observe replay, ...) is\n // identity: the same content arriving from two different sources must not\n // dedupe into one write (review finding on #1998). Not a MemoryWriteInput\n // key, so it rides beside the registry fields explicitly.\n fields.source = envelope.source;\n\n const scopeOut: Record<string, string> = {};\n for (const key of FINGERPRINT_SCOPE_FIELDS) {\n const value = scope[key];\n if (value === undefined) continue;\n if (typeof value !== \"string\") {\n throw new Error(`buildWriteIdempotencyPayload: scope.${key} must be a string`);\n }\n // Trimmed: \"ns\" and \"ns \" must not mint distinct fingerprints (review\n // finding on #1998). Empty-after-trim optional scope values are dropped.\n const cleanValue = value.trim();\n if (key === \"surface\" || cleanValue.length > 0) {\n scopeOut[key] = cleanValue;\n }\n }\n\n return { v: 1, kind: \"memory-write\", fields, scope: scopeOut };\n}\n\n// ---------------------------------------------------------------------------\n// Access-surface request fingerprints (issue #1989 PR3)\n// ---------------------------------------------------------------------------\n//\n// The access surfaces (memory_store / suggestion_submit writes, their peek\n// twins, and observe) key their idempotency dedup on a hash of the RAW\n// request — computed BEFORE validation, and persisted indefinitely in\n// `AccessIdempotencyStore` (last-512 LRU, no time TTL). Those stored hashes\n// are load-bearing state: changing the payload shape would silently break\n// replay/conflict detection for every in-flight key. So these builders\n// REPRODUCE each surface's historical shape byte-for-byte (asserted by the\n// parity suite) instead of adopting the versioned envelope payload above —\n// a versioned migration of stored state is the explicit prerequisite for\n// unifying them (#1989 PR3 scope note).\n//\n// What centralizing buys even under byte-parity: one module now owns every\n// fingerprint shape, and the compile-time assertion below ties the write\n// shape to WRITE_FINGERPRINT_FIELDS — adding a fingerprint-relevant field\n// to MemoryWriteInput fails compilation here until the author decides how\n// the access surfaces represent it.\n\n/** The raw request fields the write surfaces fingerprint (legacy shape). */\nexport interface AccessWriteFingerprintParts {\n schemaVersion: number;\n namespace: string;\n content: string;\n category?: string;\n confidence?: number;\n tags?: string[];\n entityRef?: string;\n ttl?: string;\n sourceReason?: string;\n sourceConnector?: string;\n}\n\n// Registry coupling: every fingerprint-relevant MemoryWriteInput field must\n// either appear in AccessWriteFingerprintParts or be named in this explicit\n// exemption list. `structuredAttributes` and `validAt` are exempt because\n// the access write requests cannot express them today (ExplicitCaptureInput\n// has no such fields) — the moment they become representable, this type\n// stops compiling and forces a fingerprint decision (+ versioned state\n// migration) instead of a silent dedup gap.\ntype AccessSurfaceUnrepresentable = \"structuredAttributes\" | \"validAt\";\ntype UncoveredAccessFingerprintField = Exclude<\n Extract<RegistryField, keyof MemoryWriteInput>,\n keyof AccessWriteFingerprintParts | AccessSurfaceUnrepresentable\n>;\nconst assertAccessFingerprintCoversRegistry: UncoveredAccessFingerprintField extends never\n ? true\n : never = true;\nvoid assertAccessFingerprintCoversRegistry;\n\n/**\n * Fingerprint payload for `memory_store` / `suggestion_submit` (write AND\n * peek paths — both MUST call this so peek can never diverge from the\n * write it predicts). Key set and values reproduce the historical inline\n * literals exactly; `hashAccessIdempotencyPayload`'s stableStringify sorts\n * keys and drops `undefined`, so optional absent fields hash identically\n * to the old shape.\n */\nexport function buildAccessWriteRequestFingerprint(\n parts: AccessWriteFingerprintParts,\n): Record<string, unknown> {\n return {\n schemaVersion: parts.schemaVersion,\n content: parts.content,\n category: parts.category,\n confidence: parts.confidence,\n namespace: parts.namespace,\n tags: parts.tags,\n entityRef: parts.entityRef,\n ttl: parts.ttl,\n sourceReason: parts.sourceReason,\n sourceConnector: parts.sourceConnector,\n };\n}\n\n/** The raw request fields the observe surface fingerprints (legacy shape). */\nexport interface ObserveFingerprintParts {\n sessionKey: string;\n messages: unknown;\n namespace?: string;\n skipExtraction?: boolean;\n authenticatedPrincipal?: string;\n cwd?: string;\n projectTag?: string;\n /** Resolved coding context — `null` (not undefined) when absent, matching the historical literal. */\n effectiveCodingContext: unknown;\n sourceConnector?: string;\n}\n\n/**\n * Fingerprint payload for `observe` — turn ingestion, not a memory write,\n * so it fingerprints session/message identity rather than MemoryWriteInput\n * fields. Shape reproduces the historical inline literal exactly.\n */\nexport function buildObserveRequestFingerprint(\n parts: ObserveFingerprintParts,\n): Record<string, unknown> {\n return {\n sessionKey: parts.sessionKey,\n messages: parts.messages,\n namespace: parts.namespace,\n skipExtraction: parts.skipExtraction,\n authenticatedPrincipal: parts.authenticatedPrincipal,\n cwd: parts.cwd,\n projectTag: parts.projectTag,\n effectiveCodingContext: parts.effectiveCodingContext,\n sourceConnector: parts.sourceConnector,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AA2FO,IAAM,aAAa,OAAO,OAAO;AAAA;AAAA,EAEtC,SAAS;AAAA;AAAA,EAET,cAAc;AAChB,CAAC;AAEM,IAAM,8BAA8B,OAAO,OAAO;AAAA;AAAA,EAEvD,YAAY;AAAA;AAAA,EAEZ,cAAc;AAAA;AAAA,EAEd,gBAAgB;AAClB,CAAC;AAED,IAAM,wBAAsD;AAAA,EAC1D,MAAM;AAAA,EACN,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,cAAc;AAAA,EACd,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,MAAM;AAAA,EACN,WAAW;AAAA,EACX,iBAAiB;AACnB;AAEA,IAAM,wBAAwB,OAAO,KAAK,qBAAqB,EAAE,KAAK;AAE/D,SAAS,iBAAiB,OAAwC;AACvE,SAAO,OAAO,UAAU,eAAe,KAAK,uBAAuB,KAAK;AAC1E;AAqEA,SAAS,KAAK,OAAe,SAAwB;AACnD,QAAM,IAAI,MAAM,0BAA0B,KAAK,IAAI,OAAO,E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