@remnic/core 9.63.6 → 9.63.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (304) hide show
  1. package/dist/access-admin-ops-surface.d.ts +3 -2
  2. package/dist/access-admin-ops-surface.js +31 -27
  3. package/dist/access-authorization-probe.d.ts +3 -2
  4. package/dist/access-authorization-probe.js +32 -28
  5. package/dist/access-boundary.d.ts +3 -2
  6. package/dist/access-boundary.js +31 -27
  7. package/dist/access-cli.js +98 -95
  8. package/dist/access-cli.js.map +1 -1
  9. package/dist/access-extraction-force-flush.d.ts +3 -2
  10. package/dist/access-extraction-force-flush.js +31 -27
  11. package/dist/access-http-lcm-compaction.d.ts +3 -2
  12. package/dist/access-http-lifecycle-flush.d.ts +3 -2
  13. package/dist/access-http-offline-stream.d.ts +3 -2
  14. package/dist/access-http-query.js +33 -29
  15. package/dist/access-http.d.ts +4 -3
  16. package/dist/access-http.js +47 -43
  17. package/dist/access-identity-continuity-surface.d.ts +2 -1
  18. package/dist/access-identity-continuity-surface.js +31 -27
  19. package/dist/access-lcm-surface.d.ts +3 -2
  20. package/dist/access-lcm-surface.js +31 -27
  21. package/dist/access-mcp-output-schemas.js +1 -1
  22. package/dist/access-mcp.d.ts +3 -2
  23. package/dist/access-mcp.js +38 -34
  24. package/dist/access-namespace-preflight.js +31 -27
  25. package/dist/access-observe-write-surface.d.ts +3 -2
  26. package/dist/access-observe-write-surface.js +31 -27
  27. package/dist/access-offline-manifest.d.ts +2 -1
  28. package/dist/access-offline-manifest.js +5 -4
  29. package/dist/access-operations-batch.js +32 -28
  30. package/dist/access-operations.d.ts +3 -2
  31. package/dist/access-operations.js +36 -32
  32. package/dist/access-recall-concurrency.d.ts +3 -2
  33. package/dist/access-recall-concurrency.js +31 -27
  34. package/dist/access-recall-response.d.ts +3 -2
  35. package/dist/access-recall-response.js +31 -27
  36. package/dist/access-recall-surface.d.ts +3 -2
  37. package/dist/access-recall-surface.js +31 -27
  38. package/dist/access-schema.js +6 -5
  39. package/dist/{access-service-cKQrte9Z.d.ts → access-service-BaPa_km6.d.ts} +1 -1
  40. package/dist/access-service-helpers.d.ts +3 -2
  41. package/dist/access-service.d.ts +3 -2
  42. package/dist/access-service.js +31 -27
  43. package/dist/access-surface-catalog.d.ts +3 -2
  44. package/dist/access-surface-catalog.js +33 -29
  45. package/dist/access-surface-catalog.js.map +1 -1
  46. package/dist/active-recall.js +4 -2
  47. package/dist/active-recall.js.map +1 -1
  48. package/dist/adapters/index.js +4 -4
  49. package/dist/adapters/registry.js +2 -2
  50. package/dist/{auto-sync-BKRJDMKX.js → auto-sync-3SHMZVQS.js} +5 -3
  51. package/dist/{auto-sync-BKRJDMKX.js.map → auto-sync-3SHMZVQS.js.map} +1 -1
  52. package/dist/bootstrap.d.ts +2 -1
  53. package/dist/briefing.js +10 -10
  54. package/dist/calibration.d.ts +2 -1
  55. package/dist/calibration.js +7 -0
  56. package/dist/calibration.js.map +1 -1
  57. package/dist/{capsule-crypto-7FJQINUR.js → capsule-crypto-YO5QJ6L3.js} +2 -2
  58. package/dist/causal-consolidation.js +11 -11
  59. package/dist/census-validation.d.ts +19 -0
  60. package/dist/census-validation.js +14 -0
  61. package/dist/census-validation.js.map +1 -0
  62. package/dist/{chunk-LEPOP46W.js → chunk-227UFSEQ.js} +4 -4
  63. package/dist/chunk-2YA5N2BY.js +65 -0
  64. package/dist/chunk-2YA5N2BY.js.map +1 -0
  65. package/dist/{chunk-PB4WVYGC.js → chunk-3IMYRX3W.js} +2 -2
  66. package/dist/{chunk-R6UMNP5C.js → chunk-3T6HIIKA.js} +2 -2
  67. package/dist/{chunk-77QZW2D6.js → chunk-3TDAA7VA.js} +2 -2
  68. package/dist/{chunk-TWTUGCTY.js → chunk-3YTTAGPB.js} +6 -1
  69. package/dist/chunk-3YTTAGPB.js.map +1 -0
  70. package/dist/{chunk-DXDAQZ2K.js → chunk-42TIIO2M.js} +2 -2
  71. package/dist/{chunk-Y7COCXY2.js → chunk-4F67JJPG.js} +2 -2
  72. package/dist/{chunk-OW7NVMGQ.js → chunk-5OOTHWGJ.js} +2 -2
  73. package/dist/{chunk-KYTRF64R.js → chunk-5SCFDQEJ.js} +2 -2
  74. package/dist/{chunk-DYZR3Z6D.js → chunk-5TF5STAV.js} +4 -4
  75. package/dist/{chunk-GG4DN63W.js → chunk-62Y5AGCM.js} +2 -2
  76. package/dist/{chunk-PMVPCZJZ.js → chunk-6433HV72.js} +2 -2
  77. package/dist/{chunk-KHCUVYCY.js → chunk-6UKSOXAO.js} +3 -3
  78. package/dist/{chunk-GF7RQWXC.js → chunk-AJRJDXYR.js} +2 -2
  79. package/dist/{chunk-YEQCMA5L.js → chunk-BOSIHHOH.js} +2 -2
  80. package/dist/{chunk-IVXVLDNT.js → chunk-BPQ7L27U.js} +77 -92
  81. package/dist/chunk-BPQ7L27U.js.map +1 -0
  82. package/dist/{chunk-7LF2OHIJ.js → chunk-BRHKW7GY.js} +2 -2
  83. package/dist/{chunk-2NLLXCJG.js → chunk-BXLOS5AJ.js} +2 -2
  84. package/dist/{chunk-LX4TNSAE.js → chunk-CBY54QYW.js} +4 -4
  85. package/dist/{chunk-CIAI24TQ.js → chunk-DGUVXXAU.js} +3 -3
  86. package/dist/{chunk-X7Y7WX73.js → chunk-DQEMWVMT.js} +1 -1
  87. package/dist/{chunk-QI5RDDEL.js → chunk-EDZNW3HE.js} +3 -3
  88. package/dist/chunk-FEHIOYML.js +168 -0
  89. package/dist/chunk-FEHIOYML.js.map +1 -0
  90. package/dist/{chunk-Z4N7SVVF.js → chunk-FZEEWOI2.js} +9 -4
  91. package/dist/chunk-FZEEWOI2.js.map +1 -0
  92. package/dist/{chunk-6YMEU6OQ.js → chunk-G72IPMR7.js} +2 -2
  93. package/dist/{chunk-7AF243WZ.js → chunk-GBVRVYF4.js} +1 -1
  94. package/dist/{chunk-FPEZ74F7.js → chunk-I2HTKOOP.js} +3 -3
  95. package/dist/{chunk-R7TZ2HCS.js → chunk-JG22O53B.js} +58 -3
  96. package/dist/chunk-JG22O53B.js.map +1 -0
  97. package/dist/{chunk-VPHSMJ2E.js → chunk-JPWSYHLB.js} +2 -2
  98. package/dist/{chunk-X7LEDA74.js → chunk-KFB4YNXM.js} +2 -2
  99. package/dist/{chunk-I5FLIB2J.js → chunk-KXWE62IH.js} +2 -2
  100. package/dist/chunk-LQWOFU6L.js +17 -0
  101. package/dist/chunk-LQWOFU6L.js.map +1 -0
  102. package/dist/{chunk-TSTI6A3A.js → chunk-LTYH2L6E.js} +13 -13
  103. package/dist/{chunk-ZUPKNWRZ.js → chunk-MIUL6AUZ.js} +3 -3
  104. package/dist/{chunk-EJY3HJMT.js → chunk-MYI3RKI6.js} +2 -2
  105. package/dist/{chunk-UCLMKNHA.js → chunk-N7V3P4V5.js} +2 -2
  106. package/dist/{chunk-NA56NSKL.js → chunk-O52TB5SL.js} +2 -2
  107. package/dist/{chunk-7KQB4EBS.js → chunk-OPPBTPUU.js} +4 -4
  108. package/dist/{chunk-ERPBRXVZ.js → chunk-PHKU6BZ2.js} +2 -2
  109. package/dist/{chunk-GTD4Q62X.js → chunk-PQHNZ63P.js} +4 -4
  110. package/dist/{chunk-FHKXVTM5.js → chunk-Q5XKKDFQ.js} +16 -16
  111. package/dist/{chunk-QRWMS6SI.js → chunk-Q6OL23WM.js} +2 -2
  112. package/dist/{chunk-V3KIRICY.js → chunk-QQYHYW2N.js} +3 -3
  113. package/dist/{chunk-YFCEBB5P.js → chunk-QTXNS3HB.js} +2 -2
  114. package/dist/{chunk-2QSZNTDO.js → chunk-RKNJBZ55.js} +4 -4
  115. package/dist/{chunk-E4KMY4KR.js → chunk-SNEUAZ6B.js} +2 -2
  116. package/dist/{chunk-F6JYBVL6.js → chunk-SY5JUJ2X.js} +52 -52
  117. package/dist/{chunk-EFKZT6AY.js → chunk-T42L3S6A.js} +6 -11
  118. package/dist/chunk-T42L3S6A.js.map +1 -0
  119. package/dist/{chunk-YXMHUBN2.js → chunk-TOP3FSDW.js} +25 -102
  120. package/dist/chunk-TOP3FSDW.js.map +1 -0
  121. package/dist/{chunk-PBRCYYO7.js → chunk-ULZFZL7K.js} +2 -2
  122. package/dist/{chunk-YYQAKIDJ.js → chunk-VD2OT77P.js} +2 -2
  123. package/dist/chunk-VD2OT77P.js.map +1 -0
  124. package/dist/{chunk-IPLYGWQF.js → chunk-VDX2J7OX.js} +6 -6
  125. package/dist/{chunk-UGHCZS6K.js → chunk-VFZQXYN5.js} +2 -2
  126. package/dist/{chunk-NKB43PGI.js → chunk-VYMICVRA.js} +2 -2
  127. package/dist/{chunk-OETHJBAL.js → chunk-WBPD6SBZ.js} +109 -116
  128. package/dist/chunk-WBPD6SBZ.js.map +1 -0
  129. package/dist/{chunk-2UM6WHME.js → chunk-XE2QCCT2.js} +2 -2
  130. package/dist/{chunk-SYVGVK4S.js → chunk-XTMYB2HY.js} +2 -2
  131. package/dist/{chunk-AYVCKGA6.js → chunk-YTXNDEUS.js} +2 -2
  132. package/dist/{chunk-3Z5TGRFA.js → chunk-ZOAAY2OE.js} +9 -9
  133. package/dist/{chunk-L3CHRBHE.js → chunk-ZRUEP4IK.js} +17 -11
  134. package/dist/chunk-ZRUEP4IK.js.map +1 -0
  135. package/dist/{chunk-PRDJMOST.js → chunk-ZVZHG7AI.js} +65 -15
  136. package/dist/chunk-ZVZHG7AI.js.map +1 -0
  137. package/dist/{chunk-RYST72N5.js → chunk-ZWYXSF2T.js} +4 -154
  138. package/dist/chunk-ZWYXSF2T.js.map +1 -0
  139. package/dist/{cli-BFBDYV0D.d.ts → cli-D0tV7eeU.d.ts} +2 -2
  140. package/dist/cli.d.ts +4 -3
  141. package/dist/cli.js +69 -65
  142. package/dist/compounding/engine.js +10 -10
  143. package/dist/config.js +4 -2
  144. package/dist/connectors/codex-materialize-runner.js +10 -10
  145. package/dist/connectors/index.js +10 -10
  146. package/dist/consolidation-provenance-check.js +2 -2
  147. package/dist/convergence-refresh.js +12 -12
  148. package/dist/conversation-index/backend.js +2 -2
  149. package/dist/corpus-watermark.js +12 -12
  150. package/dist/entity-retrieval.js +10 -10
  151. package/dist/explicit-capture.d.ts +2 -1
  152. package/dist/external-wiki-access.d.ts +3 -2
  153. package/dist/external-wiki-access.js +32 -28
  154. package/dist/external-wiki-mcp-tools.d.ts +3 -2
  155. package/dist/extraction-judge.d.ts +2 -1
  156. package/dist/extraction-judge.js +6 -1
  157. package/dist/extraction-normalization.js +2 -2
  158. package/dist/extraction-prompt.d.ts +20 -1
  159. package/dist/extraction-prompt.js +11 -1
  160. package/dist/extraction.js +13 -13
  161. package/dist/harmonic-retrieval.js +1 -1
  162. package/dist/included-memories.d.ts +11 -0
  163. package/dist/included-memories.js +14 -0
  164. package/dist/included-memories.js.map +1 -0
  165. package/dist/index.d.ts +6 -5
  166. package/dist/index.js +117 -114
  167. package/dist/lcm/index.js +3 -3
  168. package/dist/maintenance/memory-governance.js +10 -10
  169. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +10 -10
  170. package/dist/maintenance/rebuild-memory-projection.js +11 -11
  171. package/dist/mcp-memory-inspector-app.d.ts +3 -2
  172. package/dist/namespaces/migrate.js +11 -11
  173. package/dist/namespaces/search.js +4 -4
  174. package/dist/namespaces/storage.js +10 -10
  175. package/dist/offline-sync.js +2 -1
  176. package/dist/operator-doctor-corpus.js +13 -13
  177. package/dist/operator-toolkit.js +23 -21
  178. package/dist/orchestration/maintenance.js +16 -16
  179. package/dist/{orchestrator-CSc9GfQv.d.ts → orchestrator-Bay_AofR.d.ts} +2 -3
  180. package/dist/orchestrator.d.ts +2 -1
  181. package/dist/orchestrator.js +100 -97
  182. package/dist/{public-http-8PcrDIYi.d.ts → public-http-BtjiyKah.d.ts} +1 -1
  183. package/dist/recall-explain-renderer.d.ts +1 -0
  184. package/dist/recall-state.d.ts +6 -2
  185. package/dist/recall-state.js +6 -2
  186. package/dist/reconcile/cursor.js +7 -3
  187. package/dist/reconcile/cursor.js.map +1 -1
  188. package/dist/reconcile/manifest.js +3 -7
  189. package/dist/reconcile/plan.d.ts +15 -1
  190. package/dist/reconcile/plan.js +6 -10
  191. package/dist/resume-bundles.js +5 -3
  192. package/dist/search/factory.js +3 -3
  193. package/dist/search/index.js +3 -3
  194. package/dist/semantic-consolidation.js +16 -16
  195. package/dist/semantic-rule-promotion.js +10 -10
  196. package/dist/semantic-rule-verifier.js +10 -10
  197. package/dist/source-agent-qualifier.js +10 -10
  198. package/dist/storage.js +9 -9
  199. package/dist/support-passport/index.d.ts +6 -5
  200. package/dist/support-passport/index.js +34 -30
  201. package/dist/transfer/autodetect.js +1 -1
  202. package/dist/transfer/backup.js +2 -2
  203. package/dist/transfer/capsule-export.js +3 -3
  204. package/dist/transfer/capsule-import.js +2 -2
  205. package/dist/verified-recall.js +10 -10
  206. package/package.json +2 -2
  207. package/src/access-mcp-output-schemas.ts +1 -1
  208. package/src/access-recall-response.ts +4 -2
  209. package/src/access-recall-surface.ts +9 -9
  210. package/src/access-service-namespace.test.ts +9 -9
  211. package/src/access-service-raw-excerpt-read-gate.test.ts +1 -1
  212. package/src/calibration.ts +3 -1
  213. package/src/census-validation.ts +25 -0
  214. package/src/coding/architecture-surfaces.test.ts +9 -10
  215. package/src/coding/architecture-surfaces.ts +2 -35
  216. package/src/coding/codegraph-runtime-loader.test.ts +228 -0
  217. package/src/coding/codegraph-runtime.ts +30 -50
  218. package/src/coding/codegraph-surfaces.ts +2 -2
  219. package/src/coding/coding-knowledge-config.ts +35 -1
  220. package/src/coding/decision-surfaces.test.ts +9 -10
  221. package/src/coding/decision-surfaces.ts +2 -40
  222. package/src/coding/session-delta-surfaces.test.ts +9 -10
  223. package/src/coding/session-delta-surfaces.ts +2 -33
  224. package/src/extraction-judge.ts +3 -1
  225. package/src/extraction-output-language.test.ts +116 -0
  226. package/src/extraction-prompt.ts +70 -1
  227. package/src/extraction.ts +23 -95
  228. package/src/included-memories.ts +88 -0
  229. package/src/offline-sync.ts +4 -4
  230. package/src/orchestration/recall-internal-deps.ts +2 -4
  231. package/src/orchestration/recall-internal.ts +9 -13
  232. package/src/orchestration/recall-result-formatter-display-safe.test.ts +13 -16
  233. package/src/orchestration/recall-result-formatter.ts +32 -45
  234. package/src/orchestration/recall-section-coordinator.ts +20 -26
  235. package/src/orchestrator.ts +2 -4
  236. package/src/recall-explain-renderer.test.ts +4 -0
  237. package/src/recall-state.test.ts +108 -5
  238. package/src/recall-state.ts +85 -23
  239. package/src/recall-token-budget.test.ts +1 -1
  240. package/src/reconcile/census-parity.test.ts +152 -0
  241. package/src/reconcile/cursor.ts +5 -5
  242. package/src/reconcile/manifest.ts +4 -11
  243. package/src/reconcile/plan.ts +18 -15
  244. package/dist/chunk-EFKZT6AY.js.map +0 -1
  245. package/dist/chunk-IVXVLDNT.js.map +0 -1
  246. package/dist/chunk-L3CHRBHE.js.map +0 -1
  247. package/dist/chunk-OETHJBAL.js.map +0 -1
  248. package/dist/chunk-PRDJMOST.js.map +0 -1
  249. package/dist/chunk-R7TZ2HCS.js.map +0 -1
  250. package/dist/chunk-RYST72N5.js.map +0 -1
  251. package/dist/chunk-TWTUGCTY.js.map +0 -1
  252. package/dist/chunk-YXMHUBN2.js.map +0 -1
  253. package/dist/chunk-YYQAKIDJ.js.map +0 -1
  254. package/dist/chunk-Z4N7SVVF.js.map +0 -1
  255. /package/dist/{capsule-crypto-7FJQINUR.js.map → capsule-crypto-YO5QJ6L3.js.map} +0 -0
  256. /package/dist/{chunk-LEPOP46W.js.map → chunk-227UFSEQ.js.map} +0 -0
  257. /package/dist/{chunk-PB4WVYGC.js.map → chunk-3IMYRX3W.js.map} +0 -0
  258. /package/dist/{chunk-R6UMNP5C.js.map → chunk-3T6HIIKA.js.map} +0 -0
  259. /package/dist/{chunk-77QZW2D6.js.map → chunk-3TDAA7VA.js.map} +0 -0
  260. /package/dist/{chunk-DXDAQZ2K.js.map → chunk-42TIIO2M.js.map} +0 -0
  261. /package/dist/{chunk-Y7COCXY2.js.map → chunk-4F67JJPG.js.map} +0 -0
  262. /package/dist/{chunk-OW7NVMGQ.js.map → chunk-5OOTHWGJ.js.map} +0 -0
  263. /package/dist/{chunk-KYTRF64R.js.map → chunk-5SCFDQEJ.js.map} +0 -0
  264. /package/dist/{chunk-DYZR3Z6D.js.map → chunk-5TF5STAV.js.map} +0 -0
  265. /package/dist/{chunk-GG4DN63W.js.map → chunk-62Y5AGCM.js.map} +0 -0
  266. /package/dist/{chunk-PMVPCZJZ.js.map → chunk-6433HV72.js.map} +0 -0
  267. /package/dist/{chunk-KHCUVYCY.js.map → chunk-6UKSOXAO.js.map} +0 -0
  268. /package/dist/{chunk-GF7RQWXC.js.map → chunk-AJRJDXYR.js.map} +0 -0
  269. /package/dist/{chunk-YEQCMA5L.js.map → chunk-BOSIHHOH.js.map} +0 -0
  270. /package/dist/{chunk-7LF2OHIJ.js.map → chunk-BRHKW7GY.js.map} +0 -0
  271. /package/dist/{chunk-2NLLXCJG.js.map → chunk-BXLOS5AJ.js.map} +0 -0
  272. /package/dist/{chunk-LX4TNSAE.js.map → chunk-CBY54QYW.js.map} +0 -0
  273. /package/dist/{chunk-CIAI24TQ.js.map → chunk-DGUVXXAU.js.map} +0 -0
  274. /package/dist/{chunk-X7Y7WX73.js.map → chunk-DQEMWVMT.js.map} +0 -0
  275. /package/dist/{chunk-QI5RDDEL.js.map → chunk-EDZNW3HE.js.map} +0 -0
  276. /package/dist/{chunk-6YMEU6OQ.js.map → chunk-G72IPMR7.js.map} +0 -0
  277. /package/dist/{chunk-7AF243WZ.js.map → chunk-GBVRVYF4.js.map} +0 -0
  278. /package/dist/{chunk-FPEZ74F7.js.map → chunk-I2HTKOOP.js.map} +0 -0
  279. /package/dist/{chunk-VPHSMJ2E.js.map → chunk-JPWSYHLB.js.map} +0 -0
  280. /package/dist/{chunk-X7LEDA74.js.map → chunk-KFB4YNXM.js.map} +0 -0
  281. /package/dist/{chunk-I5FLIB2J.js.map → chunk-KXWE62IH.js.map} +0 -0
  282. /package/dist/{chunk-TSTI6A3A.js.map → chunk-LTYH2L6E.js.map} +0 -0
  283. /package/dist/{chunk-ZUPKNWRZ.js.map → chunk-MIUL6AUZ.js.map} +0 -0
  284. /package/dist/{chunk-EJY3HJMT.js.map → chunk-MYI3RKI6.js.map} +0 -0
  285. /package/dist/{chunk-UCLMKNHA.js.map → chunk-N7V3P4V5.js.map} +0 -0
  286. /package/dist/{chunk-NA56NSKL.js.map → chunk-O52TB5SL.js.map} +0 -0
  287. /package/dist/{chunk-7KQB4EBS.js.map → chunk-OPPBTPUU.js.map} +0 -0
  288. /package/dist/{chunk-ERPBRXVZ.js.map → chunk-PHKU6BZ2.js.map} +0 -0
  289. /package/dist/{chunk-GTD4Q62X.js.map → chunk-PQHNZ63P.js.map} +0 -0
  290. /package/dist/{chunk-FHKXVTM5.js.map → chunk-Q5XKKDFQ.js.map} +0 -0
  291. /package/dist/{chunk-QRWMS6SI.js.map → chunk-Q6OL23WM.js.map} +0 -0
  292. /package/dist/{chunk-V3KIRICY.js.map → chunk-QQYHYW2N.js.map} +0 -0
  293. /package/dist/{chunk-YFCEBB5P.js.map → chunk-QTXNS3HB.js.map} +0 -0
  294. /package/dist/{chunk-2QSZNTDO.js.map → chunk-RKNJBZ55.js.map} +0 -0
  295. /package/dist/{chunk-E4KMY4KR.js.map → chunk-SNEUAZ6B.js.map} +0 -0
  296. /package/dist/{chunk-F6JYBVL6.js.map → chunk-SY5JUJ2X.js.map} +0 -0
  297. /package/dist/{chunk-PBRCYYO7.js.map → chunk-ULZFZL7K.js.map} +0 -0
  298. /package/dist/{chunk-IPLYGWQF.js.map → chunk-VDX2J7OX.js.map} +0 -0
  299. /package/dist/{chunk-UGHCZS6K.js.map → chunk-VFZQXYN5.js.map} +0 -0
  300. /package/dist/{chunk-NKB43PGI.js.map → chunk-VYMICVRA.js.map} +0 -0
  301. /package/dist/{chunk-2UM6WHME.js.map → chunk-XE2QCCT2.js.map} +0 -0
  302. /package/dist/{chunk-SYVGVK4S.js.map → chunk-XTMYB2HY.js.map} +0 -0
  303. /package/dist/{chunk-AYVCKGA6.js.map → chunk-YTXNDEUS.js.map} +0 -0
  304. /package/dist/{chunk-3Z5TGRFA.js.map → chunk-ZOAAY2OE.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/recall-state.ts"],"sourcesContent":["import { appendFile, mkdir, readFile, rename, rm, stat, unlink, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { log } from \"./logger.js\";\nimport { writeFileAtomically } from \"./maintenance/atomic-file.js\";\nimport { isErrnoCode } from \"./utils/errno.js\";\nimport { withHeldFileLock, type HeldFileLockOptions } from \"./utils/serialize-mutations.js\";\nimport { ensureContainedSpillDir, listContainedSpillFiles } from \"./utils/path-containment.js\";\nimport type { SearchDegradation } from \"./search/port.js\";\nimport type {\n IdentityInjectionMode,\n RecallPlanMode,\n RecallTierExplain,\n} from \"./types.js\";\n\nexport interface LastRecallBudgetSummary {\n requestedTopK?: number;\n appliedTopK: number;\n recallBudgetChars: number;\n maxMemoryTokens: number;\n qmdFetchLimit?: number;\n qmdHybridFetchLimit?: number;\n finalContextChars?: number;\n truncated?: boolean;\n includedSections?: string[];\n omittedSections?: string[];\n includedMemoryIds?: string[];\n includedMemoryPaths?: string[];\n includedMemoryNamespaces?: Array<string | undefined>;\n omittedMemoryIds?: string[];\n}\n\nexport interface LastRecallSnapshot {\n sessionKey: string;\n recordedAt: string;\n queryHash: string;\n queryLen: number;\n memoryIds: string[];\n namespace?: string;\n recallNamespaces?: string[];\n traceId?: string;\n plannerMode?: RecallPlanMode;\n requestedMode?: RecallPlanMode;\n source?: string;\n fallbackUsed?: boolean;\n sourcesUsed?: string[];\n budgetsApplied?: LastRecallBudgetSummary;\n latencyMs?: number;\n resultPaths?: string[];\n resultNamespaces?: Array<string | undefined>;\n policyVersion?: string;\n identityInjectionMode?: IdentityInjectionMode | \"none\";\n identityInjectedChars?: number;\n identityInjectionTruncated?: boolean;\n /**\n * Collision-safe write nonce. Random UUID set on every `record()`\n * call so the observation-mode direct-answer hook can detect stale\n * snapshots and avoid annotating a snapshot that a subsequent recall\n * already replaced (issue #518).\n */\n writeNonce?: string;\n /**\n * Optional tier-level explanation of how recall was served\n * (issue #518). Populated by orchestrator call sites that can\n * identify a concrete tier; surfaces expose the block via\n * `engram query --explain`, the `?explain=1` HTTP flag, and the\n * `remnic_recall_explain` MCP tool. Orthogonal to the existing\n * graph-path `recallExplain` operation.\n */\n tierExplain?: RecallTierExplain;\n /**\n * Backend degradations observed while serving this recall (issue #1536).\n * Present only when a search backend reported unavailable/loading/timeout\n * during the recall — distinguishing \"no matches\" from \"backend could not\n * answer\" (CLAUDE.md rule 34). Deliberately independent of `tierExplain`,\n * which is gated behind `recallDirectAnswerEnabled`.\n */\n backendDegradations?: SearchDegradation[];\n}\n\nexport interface GraphRecallExpandedEntry {\n path: string;\n score: number;\n namespace: string;\n seed: string;\n hopDepth: number;\n decayedWeight: number;\n graphType: \"entity\" | \"time\" | \"causal\";\n /**\n * Issue #681 PR 3/3 — confidence of the edge that produced this entry's\n * recorded provenance (strongest edge along the chosen entry path).\n * Range `[0, 1]`. Optional so persisted snapshots from older builds\n * round-trip through `clampGraphRecallExpandedEntries` without dropping.\n */\n edgeConfidence?: number;\n /** Graph-relative activation path node ids when provenance is enabled. */\n pathNodeIds?: string[];\n /** True when a graph path penalty was applied. */\n pathPenaltyApplied?: boolean;\n}\n\nexport function clampGraphRecallExpandedEntries(\n entries: unknown,\n maxEntries: number = 64,\n): GraphRecallExpandedEntry[] {\n const limit = Math.max(1, Math.floor(maxEntries));\n if (!Array.isArray(entries)) return [];\n return entries\n .filter((item): item is Record<string, unknown> => !!item && typeof item === \"object\")\n .map((item) => {\n const graphType: \"entity\" | \"time\" | \"causal\" =\n item.graphType === \"entity\" || item.graphType === \"time\" || item.graphType === \"causal\"\n ? item.graphType\n : \"entity\";\n const out: GraphRecallExpandedEntry = {\n path: typeof item.path === \"string\" ? item.path : \"\",\n score: typeof item.score === \"number\" && Number.isFinite(item.score) ? item.score : 0,\n namespace: typeof item.namespace === \"string\" ? item.namespace : \"\",\n seed: typeof item.seed === \"string\" ? item.seed : \"\",\n hopDepth:\n typeof item.hopDepth === \"number\" && Number.isFinite(item.hopDepth)\n ? Math.max(0, Math.floor(item.hopDepth))\n : 0,\n decayedWeight:\n typeof item.decayedWeight === \"number\" && Number.isFinite(item.decayedWeight)\n ? Math.max(0, item.decayedWeight)\n : 0,\n graphType,\n };\n // Issue #681 PR 3/3: clamp `edgeConfidence` into [0, 1] when present.\n // Older snapshots without the field round-trip cleanly via the\n // optional shape; legacy callers always rendered as 1.0.\n if (\n typeof item.edgeConfidence === \"number\" &&\n Number.isFinite(item.edgeConfidence)\n ) {\n out.edgeConfidence = Math.min(1, Math.max(0, item.edgeConfidence));\n }\n if (\n Array.isArray(item.pathNodeIds) &&\n item.pathNodeIds.every((value): value is string => typeof value === \"string\")\n ) {\n out.pathNodeIds = item.pathNodeIds.slice(0, 64);\n }\n if (typeof item.pathPenaltyApplied === \"boolean\") {\n out.pathPenaltyApplied = item.pathPenaltyApplied;\n }\n return out;\n })\n .filter((item) => item.path.length > 0 && item.namespace.length > 0)\n .slice(0, limit);\n}\n\ntype LastRecallState = Record<string, LastRecallSnapshot>;\ntype StateFileWriter = (filePath: string, content: string) => Promise<void>;\n\n/**\n * Deep-copy a RecallTierExplain block. Used by both the write path\n * (so caller mutation after `record()` cannot tear the persisted\n * snapshot) and the read path (so caller mutation after `get()` /\n * `getMostRecent()` cannot tear the in-memory store).\n *\n * Uses structuredClone so future additions to RecallTierExplain do\n * not silently share references through hand-enumerated fields —\n * matching the pattern used elsewhere in the codebase (e.g.,\n * qmd-recall-cache.ts). The payload is pure JSON-shaped data, so\n * structuredClone is both safe and complete here.\n */\n/**\n * Stale-snapshot identity guard shared by the annotate methods (issue #518):\n * a writeNonce match wins outright; otherwise traceId (when expected) and\n * recordedAt are compared. Extracted so every annotation surface applies\n * identical guards (CLAUDE.md rule 22).\n */\nfunction snapshotMatchesExpectedIdentity(\n current: LastRecallSnapshot,\n expected?: { writeNonce?: string; traceId?: string; recordedAt?: string },\n): boolean {\n if (!expected) return true;\n if (typeof expected.writeNonce === \"string\" && expected.writeNonce.length > 0) {\n return current.writeNonce === expected.writeNonce;\n }\n const hasExpectedTraceId =\n typeof expected.traceId === \"string\" && expected.traceId.length > 0;\n if (hasExpectedTraceId) {\n return current.traceId === expected.traceId;\n }\n if (expected.recordedAt !== undefined) {\n return current.recordedAt === expected.recordedAt;\n }\n return true;\n}\n\nfunction cloneTierExplain(\n tierExplain: RecallTierExplain | undefined,\n): RecallTierExplain | undefined {\n if (!tierExplain) return undefined;\n return structuredClone(tierExplain);\n}\n\n/**\n * Deep-copy a LastRecallSnapshot so callers that receive it cannot\n * mutate the store's internal state through mutable array/object\n * fields. Same structuredClone rationale as cloneTierExplain above.\n */\nfunction cloneLastRecallSnapshot(\n snapshot: LastRecallSnapshot | null,\n): LastRecallSnapshot | null {\n if (!snapshot) return null;\n return structuredClone(snapshot);\n}\n\nexport interface TierMigrationCycleSummary {\n trigger: \"extraction\" | \"maintenance\" | \"manual\";\n scanned: number;\n migrated: number;\n promoted: number;\n demoted: number;\n limit: number;\n dryRun: boolean;\n skipped?: string;\n errorCount?: number;\n}\n\nexport interface TierMigrationStatusSnapshot {\n updatedAt: string;\n lastCycle: TierMigrationCycleSummary | null;\n totals: {\n cycles: number;\n scanned: number;\n migrated: number;\n promoted: number;\n demoted: number;\n errors: number;\n };\n}\n\nconst DEFAULT_TIER_MIGRATION_STATUS: TierMigrationStatusSnapshot = {\n updatedAt: new Date(0).toISOString(),\n lastCycle: null,\n totals: {\n cycles: 0,\n scanned: 0,\n migrated: 0,\n promoted: 0,\n demoted: 0,\n errors: 0,\n },\n};\n\n/**\n * Suffix marking an impression spill CLAIMED for commit but not yet deleted.\n * The crash-safe drain renames `<uuid>.jsonl` -> `<uuid>.jsonl.claimed` before\n * committing its rows, mirroring the lifecycle ledger's claim/commit protocol\n * (#2033).\n */\nconst CLAIMED_IMPRESSION_SPILL_SUFFIX = \".claimed\";\n\n/**\n * Outcome of {@link LastRecallStore.drainPendingImpressions}. Distinguishes a\n * completed drain (or nothing pending) from a DEFERRED drain that left durable\n * spills in the offline-sync-EXCLUDED queue, so the caller can tell the\n * data-safe cases apart from the one where an offline-sync snapshot would\n * silently omit recorded impressions (#2033).\n */\nexport interface DrainPendingImpressionsResult {\n /** Pending spill rows were folded into the synced active file this call. */\n folded: boolean;\n /**\n * Durable spill rows remain in the offline-sync-EXCLUDED pending queue after\n * this drain: the rotation lock could not be acquired, a spill could not be\n * claimed, or the drain-only fold left rows that would only fit by rotating\n * into a sync-excluded archive. A snapshot taken now would silently omit them\n * (#2033): the caller MUST treat the active file as INCOMPLETE and retry or\n * abort the snapshot rather than report success. `false` means the active file\n * is complete — every pending row was folded or nothing was pending.\n */\n pendingDeferred: boolean;\n}\n\nexport class LastRecallStore {\n private readonly statePath: string;\n private readonly impressionsPath: string;\n private readonly writeStateFile: StateFileWriter;\n private readonly impressionsRotateBytes: number;\n private readonly impressionsRotateKeep: number;\n // Lock-acquisition timing for the cross-process impression rotation lock.\n // Only tests set this (small maxWaitMs) to force the acquisition-timeout\n // (`acquired=false`) branch deterministically; production uses the defaults.\n private readonly impressionsLockOptions?: Pick<HeldFileLockOptions, \"maxWaitMs\" | \"pollMs\">;\n private state: LastRecallState = {};\n private stateWriteChain: Promise<void> = Promise.resolve();\n // Serializes the rotate-then-append critical section so concurrent record()\n // calls never interleave rotation renames with each other's appends (#1910).\n private impressionsWriteChain: Promise<void> = Promise.resolve();\n\n constructor(\n memoryDir: string,\n options: {\n writeStateFile?: StateFileWriter;\n impressionsRotateBytes?: number;\n impressionsRotateKeep?: number;\n impressionsLockOptions?: Pick<HeldFileLockOptions, \"maxWaitMs\" | \"pollMs\">;\n } = {},\n ) {\n this.statePath = path.join(memoryDir, \"state\", \"last_recall.json\");\n this.impressionsPath = path.join(memoryDir, \"state\", \"recall_impressions.jsonl\");\n // 0 disables rotation (never coerced to a default); keep floors at 1.\n this.impressionsRotateBytes = Math.max(0, Math.floor(options.impressionsRotateBytes ?? 0));\n this.impressionsRotateKeep = Math.max(1, Math.floor(options.impressionsRotateKeep ?? 5));\n this.impressionsLockOptions = options.impressionsLockOptions;\n this.writeStateFile =\n options.writeStateFile ??\n (async (filePath, content) => {\n await writeFileAtomically(filePath, content);\n });\n }\n\n async load(): Promise<void> {\n try {\n const raw = await readFile(this.statePath, \"utf-8\");\n const parsed = JSON.parse(raw) as LastRecallState;\n if (parsed && typeof parsed === \"object\") this.state = parsed;\n } catch {\n this.state = {};\n }\n }\n\n get(sessionKey: string): LastRecallSnapshot | null {\n // Defensive copy: callers must not be able to mutate internal state\n // by reaching into array/object fields on the returned snapshot.\n return cloneLastRecallSnapshot(this.state[sessionKey] ?? null);\n }\n\n getMostRecent(): LastRecallSnapshot | null {\n const snapshots = Object.values(this.state);\n if (snapshots.length === 0) return null;\n // Secondary key on sessionKey keeps the sort stable when two\n // snapshots share a recordedAt timestamp (CLAUDE.md rule 19).\n snapshots.sort((a, b) => {\n const byTime = b.recordedAt.localeCompare(a.recordedAt);\n if (byTime !== 0) return byTime;\n return a.sessionKey.localeCompare(b.sessionKey);\n });\n return cloneLastRecallSnapshot(snapshots[0] ?? null);\n }\n\n /**\n * Persist last-recall snapshot and append an impression log entry.\n * Does not store raw query text; uses a stable hash for correlation.\n */\n async record(opts: {\n sessionKey: string;\n query: string;\n memoryIds: string[];\n namespace?: string;\n recallNamespaces?: string[];\n traceId?: string;\n plannerMode?: RecallPlanMode;\n requestedMode?: RecallPlanMode;\n source?: string;\n fallbackUsed?: boolean;\n sourcesUsed?: string[];\n budgetsApplied?: LastRecallBudgetSummary;\n latencyMs?: number;\n resultPaths?: string[];\n resultNamespaces?: Array<string | undefined>;\n policyVersion?: string;\n appendImpression?: boolean;\n identityInjection?: {\n mode: IdentityInjectionMode | \"none\";\n injectedChars: number;\n truncated: boolean;\n };\n /**\n * Per-tier explain annotation (issue #518). When supplied, the\n * snapshot carries it so downstream surfaces (CLI / HTTP / MCP)\n * can render which retrieval tier served the query.\n */\n tierExplain?: RecallTierExplain;\n /**\n * Backend degradations observed while serving this recall (issue #1536).\n * Passed at record time so the published snapshot is born annotated —\n * a post-record annotation would leave a window where readers see the\n * snapshot without them (codex review on #1544).\n */\n backendDegradations?: SearchDegradation[];\n }): Promise<void> {\n const now = new Date().toISOString();\n const queryHash = createHash(\"sha256\").update(opts.query).digest(\"hex\");\n\n // Build the snapshot from opts, then deep-copy it via\n // cloneLastRecallSnapshot so caller arrays/objects passed in\n // `opts` cannot retain a live reference to the persisted state and\n // tear it after `record()` returns.\n const liveSnapshot: LastRecallSnapshot = {\n sessionKey: opts.sessionKey,\n recordedAt: now,\n queryHash,\n writeNonce: randomUUID(),\n queryLen: opts.query.length,\n memoryIds: opts.memoryIds,\n namespace: opts.namespace,\n recallNamespaces: opts.recallNamespaces,\n traceId: opts.traceId,\n plannerMode: opts.plannerMode,\n requestedMode: opts.requestedMode,\n source: opts.source,\n fallbackUsed: opts.fallbackUsed,\n sourcesUsed: opts.sourcesUsed,\n budgetsApplied: opts.budgetsApplied,\n latencyMs: opts.latencyMs,\n resultPaths: opts.resultPaths,\n resultNamespaces: opts.resultNamespaces,\n policyVersion: opts.policyVersion,\n identityInjectionMode: opts.identityInjection?.mode,\n identityInjectedChars: opts.identityInjection?.injectedChars,\n identityInjectionTruncated: opts.identityInjection?.truncated,\n tierExplain: opts.tierExplain,\n backendDegradations:\n opts.backendDegradations && opts.backendDegradations.length > 0\n ? opts.backendDegradations\n : undefined,\n };\n // `cloneLastRecallSnapshot` handles `null` but that never applies\n // at this call site — the non-null assertion keeps the type\n // checker honest.\n const snapshot = cloneLastRecallSnapshot(liveSnapshot)!;\n\n this.state[opts.sessionKey] = snapshot;\n\n // Keep the state bounded; the impression log is append-only.\n const keys = Object.keys(this.state);\n if (keys.length > 50) {\n const ordered = keys\n .map((k) => ({ k, at: this.state[k]?.recordedAt ?? \"\" }))\n .sort((a, b) => b.at.localeCompare(a.at));\n for (const doomed of ordered.slice(50)) {\n delete this.state[doomed.k];\n }\n }\n\n try {\n await this.flushState();\n } catch (err) {\n log.debug(`last recall store write failed: ${err}`);\n }\n\n if (opts.appendImpression !== false) {\n const line = JSON.stringify(snapshot) + \"\\n\";\n // Chain onto the previous impression write so rotation + append run as one\n // serialized critical section — concurrent record() calls can never\n // interleave a rename with another call's append (#1910). `.catch` before\n // the link keeps a prior failure from poisoning the chain.\n const chained = this.impressionsWriteChain\n .catch(() => {})\n .then(() => this.appendImpressionSerialized(line));\n this.impressionsWriteChain = chained;\n try {\n await chained;\n } catch (err) {\n log.debug(`recall impressions append failed: ${err}`);\n }\n }\n }\n\n /**\n * Drain pending spills, rotate (best-effort, sized to the projected payload),\n * then append one impression line under ONE shared cross-process lock (#1910,\n * #2033). Both the archive-shift renames AND the append run inside the same\n * held lock so a peer process holding the lock can never rename the active\n * inode to `.1` between our open and write — which would land the impression in\n * a rotated archive that offline-sync excludes, silently dropping it from\n * active-state/sync consumers.\n *\n * On lock-acquisition timeout the impression is NEVER written to the active\n * file unlocked (#2033): a peer holding the lock is likely mid-rotation, so an\n * unlocked append can land in the inode it is about to rename to `.1` — the\n * exact silent-drop this lock prevents. Instead the row is spilled to a\n * durable node-local per-event file under `<impressions>.pending.d/` and\n * folded back into the active file by the next append that DOES hold the lock,\n * preserving durability without racing rotation. Rotation failure under the\n * held lock is logged and the append still runs. Callers invoke this only\n * through `impressionsWriteChain` so the sequence is serialized in-process.\n */\n private get impressionsPendingDir(): string {\n return `${this.impressionsPath}.pending.d`;\n }\n\n private async spillImpression(line: string): Promise<void> {\n await ensureContainedSpillDir(this.impressionsPendingDir);\n // Write to a temp name the drain's `.jsonl` lister ignores, then atomically\n // rename to the final `<uuid>.jsonl` (#2033). writeFile creates the path\n // before its bytes are durable, so writing straight to the final name lets a\n // concurrent lock holder's drain read/rename/delete a partial spill and\n // append malformed JSON — permanently losing that impression. The temp lives\n // in the SAME contained dir, so the rename is atomic and stays symlink-safe.\n const id = randomUUID();\n const tempPath = path.join(this.impressionsPendingDir, `${id}.jsonl.tmp`);\n const finalPath = path.join(this.impressionsPendingDir, `${id}.jsonl`);\n await writeFile(tempPath, line, \"utf-8\");\n await rename(tempPath, finalPath);\n }\n\n /**\n * Recover a claim a crashed drain left mid-flight (#2033): the crash-safe\n * drain renames `<uuid>.jsonl` -> `<uuid>.jsonl.claimed` BEFORE committing, so\n * a `.claimed` file with no matching commit is the ONLY durable copy of those\n * rows. Rename each orphan back to `<uuid>.jsonl` so it re-enters the normal\n * collect+claim+commit flow. MUST run under the held rotation lock, before\n * collecting. listContainedSpillFiles skips symlinked/escaping entries.\n */\n private async recoverOrphanedImpressionClaims(): Promise<void> {\n const orphans = await listContainedSpillFiles(\n this.impressionsPendingDir,\n `.jsonl${CLAIMED_IMPRESSION_SPILL_SUFFIX}`,\n );\n for (const claimedPath of orphans) {\n const original = claimedPath.slice(0, -CLAIMED_IMPRESSION_SPILL_SUFFIX.length);\n await rename(claimedPath, original).catch(() => undefined);\n }\n }\n\n /**\n * Recover a crash-orphaned spill temp after its write completed but before\n * the atomic `.tmp` → `.jsonl` rename. Valid JSONL temps are promoted back\n * into the normal queue; incomplete temps remain pending and keep offline sync\n * deferred rather than being discarded.\n */\n private async recoverOrphanedImpressionTemps(): Promise<void> {\n const temps = await listContainedSpillFiles(this.impressionsPendingDir, \".jsonl.tmp\");\n for (const tempPath of temps) {\n let content: string;\n try {\n content = await readFile(tempPath, \"utf-8\");\n for (const line of content.split(\"\\n\")) {\n if (line.trim().length > 0) JSON.parse(line);\n }\n } catch {\n continue;\n }\n const finalPath = tempPath.slice(0, -\".tmp\".length);\n await rename(tempPath, finalPath).catch(() => undefined);\n }\n }\n\n private async appendImpressionSerialized(line: string): Promise<void> {\n await mkdir(path.dirname(this.impressionsPath), { recursive: true });\n // Every active-file write goes under the shared cross-process rotation lock,\n // even when THIS writer's local rotation is disabled (`impressionsRotateBytes\n // <= 0`). A peer process with rotation enabled shares this lock and may\n // rename the active inode to `.1` at any moment, so an unlocked append could\n // land in an offline-sync-excluded archive and be silently dropped (#2033).\n // Only the local rotate DECISION is disabled — the bounded fold skips\n // rotation when this writer's limit is 0 — the lock itself is not.\n const lockPath = `${this.impressionsPath}.lock`;\n await withHeldFileLock(\n lockPath,\n { staleMs: 30_000, ...this.impressionsLockOptions },\n async (acquired) => {\n // withHeldFileLock falls back to task(false) when it cannot acquire the\n // lock within the budget. Do NOT append to the active file unlocked: a\n // peer holding the lock may be mid-rotation, so an unlocked append could\n // land in the inode it renames to `.1` (an offline-sync-excluded\n // archive), silently dropping the impression. Spill it to the durable\n // pending queue instead — the next lock holder folds it back in (#2033).\n if (!acquired) {\n log.debug(\"recall impressions rotation lock not acquired; spilling impression to the durable pending queue\");\n await this.spillImpression(line);\n return;\n }\n await this.foldPendingImpressionsAndAppend(line);\n },\n );\n }\n\n /**\n * Fold any durable pending recall-impression spills into the synced active\n * `recall_impressions.jsonl` WITHOUT recording a new impression (#2033).\n *\n * The pending spill dir is offline-sync-excluded, so an impression that a\n * lock-timed-out `record()` spilled there is absent from an offline-sync\n * snapshot and lost if this node is discarded before the next `record()`\n * folds it back. Offline sync calls this before building a snapshot so a\n * recorded impression always reaches the remote. Fast no-op — no lock and no\n * dir/lock-file creation — when nothing is pending.\n *\n * Returns a {@link DrainPendingImpressionsResult}: `folded` is true when rows\n * were folded into the active file; `pendingDeferred` is true when durable\n * spills still remain in the offline-sync-EXCLUDED queue after this call —\n * because the rotation lock could not be acquired, a spill could not be\n * claimed, or the drain-only fold deferred rows that would only fit by\n * rotating into a sync-excluded archive (#2033). A snapshot taken while\n * `pendingDeferred` is true would silently drop those rows, so the caller MUST\n * NOT report a clean snapshot — it either retries or aborts.\n */\n async drainPendingImpressions(): Promise<DrainPendingImpressionsResult> {\n if (!(await this.pendingSpillsRemain())) {\n return { folded: false, pendingDeferred: false };\n }\n const lockPath = `${this.impressionsPath}.lock`;\n let folded = false;\n let acquiredLock = false;\n let spillsRemain = false;\n await withHeldFileLock(\n lockPath,\n { staleMs: 30_000, ...this.impressionsLockOptions },\n async (acquired) => {\n // A peer holds the lock (mid-rotation or mid-append). We MUST NOT touch\n // the active file unlocked (#2033), so the spills stay in the\n // offline-sync-EXCLUDED pending queue. Report the drain as DEFERRED\n // (pendingDeferred=true) so the caller does not build a snapshot that\n // silently omits them; the next lock holder — or a caller retry — folds\n // them in.\n if (!acquired) return;\n acquiredLock = true;\n folded = await this.foldPendingImpressionsAndAppend(null);\n // Even WITH the lock, a spill the fold could not claim or a `.claimed`\n // orphan a failed commit left behind keeps durable rows in the excluded\n // queue. Treat that as an incomplete drain so the caller retries/aborts\n // rather than snapshotting an active file that omits them (#2033).\n spillsRemain = await this.pendingSpillsRemain();\n },\n );\n return { folded, pendingDeferred: !acquiredLock || spillsRemain };\n }\n\n /**\n * Claim/commit fold of durable pending impression spills into the active file\n * under the held rotation lock (#2033). `line` is a new impression to append\n * after the drained rows, or null for a drain-only pre-sync fold.\n *\n * Each spill is folded as an INDEPENDENT claim -> append -> finalize unit\n * rather than materializing the whole queue as one joined payload and\n * splitting it in a single synchronous pass (#2033). A multi-hundred-MB drain\n * done as one join/split blocks the event loop long enough for\n * `withHeldFileLock`'s ownership-refresh timer to miss its window, so a peer\n * stale-breaks the 30s lock and rotates/appends concurrently — defeating the\n * rotation lock this drain relies on. The per-file `await`s keep the payload\n * bounded to one spill at a time and let the refresh timer fire between files.\n *\n * The DRAIN-ONLY path (`line === null`, run before an offline-sync snapshot)\n * NEVER rotates a drained row into an archive. `recall_impressions.jsonl.*`\n * is offline-sync-EXCLUDED, so rotating a just-drained row into `.1`/`.2` and\n * then deleting its spill would leave that row only in a path sync omits —\n * silently lost when the node is discarded after a \"successful\" sync (#2033).\n * It folds only the rows that fit the synced active file under the cap and\n * leaves the rest durable in the pending queue; {@link drainPendingImpressions}\n * then reports the drain DEFERRED so the caller retries or aborts. The\n * record() path (`line !== null`) keeps rotating normally — its archives stay\n * on a live node that is not being discarded.\n *\n * Recovers any crash-orphaned claim first. Each impression carries a unique\n * writeNonce, so a crash-recovered re-commit is a collapsible duplicate, never\n * a lost row. listContainedSpillFiles rejects symlinked/escaping entries; a\n * spill that cannot be claimed is skipped this pass. An append failure rolls\n * that spill's claim back so the row retries on the next lock holder's drain.\n * Returns true when the active file was written. MUST run under the held\n * rotation lock.\n */\n private async foldPendingImpressionsAndAppend(line: string | null): Promise<boolean> {\n await this.recoverOrphanedImpressionTemps();\n await this.recoverOrphanedImpressionClaims();\n const spillFiles = await listContainedSpillFiles(this.impressionsPendingDir);\n const drainOnly = line === null;\n const cap = this.impressionsRotateBytes;\n let activeSize = 0;\n if (cap > 0) {\n try {\n activeSize = (await stat(this.impressionsPath)).size;\n } catch (err) {\n if (!isErrnoCode(err, \"ENOENT\")) throw err;\n }\n }\n let wrote = false;\n for (const filePath of spillFiles) {\n const content = await readFile(filePath, \"utf-8\");\n const unit = content.length === 0 || content.endsWith(\"\\n\") ? content : `${content}\\n`;\n const unitBytes = Buffer.byteLength(unit, \"utf-8\");\n // Drain-only fold must never push a drained row into a sync-excluded\n // archive (#2033). Once the active file cannot take this spill under the\n // cap without rotating, stop: the remaining spills stay durable in the\n // pending queue and the drain reports itself deferred. A lone spill larger\n // than the cap on an empty active file is still folded whole (it cannot be\n // split without corrupting JSONL) so it reaches sync rather than stranding.\n if (drainOnly && cap > 0 && activeSize > 0 && activeSize + unitBytes >= cap) break;\n const claimedPath = `${filePath}${CLAIMED_IMPRESSION_SPILL_SUFFIX}`;\n try {\n await rename(filePath, claimedPath);\n } catch {\n continue; // could not claim → do not commit; a later drain retries it.\n }\n try {\n activeSize = await this.appendImpressionUnit(unit, activeSize, drainOnly);\n } catch (err) {\n // Commit failed: roll this spill's claim back so it retries on the next\n // lock holder's drain instead of being lost.\n await rename(claimedPath, filePath).catch(() => undefined);\n throw err;\n }\n // Commit is durable: delete the claimed file. A delete that fails leaves a\n // `.claimed` orphan the next drain recovers and re-commits — a\n // writeNonce-collapsible duplicate, never a lost row (#2033).\n await unlink(claimedPath).catch(() => undefined);\n wrote = true;\n }\n if (line !== null) {\n activeSize = await this.appendImpressionUnit(line, activeSize, false);\n wrote = true;\n }\n return wrote;\n }\n\n /**\n * Append one whole JSONL unit (a claimed spill's rows or a fresh impression\n * line) to the active impressions file, returning the resulting active-file\n * byte size. On the rotating (record) path, when the unit would push the\n * current active generation to/over `impressionsRotateBytes`, the full active\n * file is rotated aside FIRST so no generation exceeds the cap (#2033); a lone\n * unit larger than the cap on an empty active file is written whole because\n * splitting a JSONL row would corrupt it. `drainOnly` and disabled rotation\n * (`impressionsRotateBytes <= 0`) both skip rotation — drain-only defers its\n * overflow in {@link foldPendingImpressionsAndAppend} rather than rotating into\n * a sync-excluded archive. A rotation error is logged and the append still\n * runs so a row is never lost; an append failure propagates so the caller\n * rolls its claim back. MUST run under the held rotation lock.\n */\n private async appendImpressionUnit(\n unit: string,\n activeSize: number,\n drainOnly: boolean,\n ): Promise<number> {\n const cap = this.impressionsRotateBytes;\n const unitBytes = Buffer.byteLength(unit, \"utf-8\");\n if (cap > 0 && !drainOnly && activeSize > 0 && activeSize + unitBytes >= cap) {\n try {\n await this.shiftImpressionArchives();\n activeSize = 0;\n } catch (err) {\n log.debug(`recall impressions rotation failed (append preserved): ${err}`);\n }\n }\n await appendFile(this.impressionsPath, unit, \"utf-8\");\n return activeSize + unitBytes;\n }\n\n /**\n * True when any live `<uuid>.jsonl` spill, crash-orphaned `.claimed` file,\n * or crash-orphaned `.jsonl.tmp` spill remains in the offline-sync-EXCLUDED\n * pending queue (#2033). After a drain acquires the rotation lock, a spill\n * the fold could not claim (rename race / read-only dir) or a `.claimed`\n * orphan a failed commit left behind means durable rows are STILL excluded\n * from a snapshot — the drain must report itself INCOMPLETE so the caller\n * retries or aborts rather than snapshotting an active file that omits them.\n */\n private async pendingSpillsRemain(): Promise<boolean> {\n if ((await listContainedSpillFiles(this.impressionsPendingDir, \".jsonl.tmp\")).length > 0) {\n return true;\n }\n const liveSpills = await listContainedSpillFiles(this.impressionsPendingDir);\n if (liveSpills.length > 0) return true;\n const claimed = await listContainedSpillFiles(\n this.impressionsPendingDir,\n `.jsonl${CLAIMED_IMPRESSION_SPILL_SUFFIX}`,\n );\n return claimed.length > 0;\n }\n\n /**\n * Shift `.1..N` archives down one slot and move the active file to `.1`,\n * dropping anything beyond `keep`. Callers invoke this only while holding the\n * cross-process rotation lock (issue #1910).\n */\n private async shiftImpressionArchives(): Promise<void> {\n const keep = this.impressionsRotateKeep;\n // Drop the archive that would fall off the end, then shift down: .(keep-1)\n // -> .keep, ..., .1 -> .2, active -> .1.\n try {\n await rm(`${this.impressionsPath}.${keep}`, { force: true });\n } catch {\n // best-effort cleanup of the oldest archive\n }\n for (let i = keep - 1; i >= 1; i -= 1) {\n try {\n await rename(`${this.impressionsPath}.${i}`, `${this.impressionsPath}.${i + 1}`);\n } catch (err) {\n if (!isErrnoCode(err, \"ENOENT\")) throw err;\n }\n }\n try {\n await rename(this.impressionsPath, `${this.impressionsPath}.1`);\n } catch (err) {\n if (!isErrnoCode(err, \"ENOENT\")) throw err;\n }\n }\n\n /**\n * Attach a RecallTierExplain block to the existing snapshot for a\n * session without rewriting the entire snapshot. Used by the\n * post-recall direct-answer annotation path (issue #518 slice 3c):\n * recallInternal records the snapshot first, then the orchestrator\n * fires the direct-answer tier in observation mode and annotates\n * the stored snapshot with whichever tier served the query.\n *\n * No-op when no snapshot exists for the given session; callers do\n * not need to guard on existence.\n */\n async annotateTierExplain(\n sessionKey: string,\n tierExplain: RecallTierExplain,\n expected?: { writeNonce?: string; traceId?: string; recordedAt?: string },\n ): Promise<void> {\n const current = this.state[sessionKey];\n if (!current) return;\n if (!snapshotMatchesExpectedIdentity(current, expected)) return;\n this.state[sessionKey] = {\n ...current,\n tierExplain: cloneTierExplain(tierExplain),\n };\n try {\n await this.flushState();\n } catch (err) {\n log.debug(`last recall tier-explain annotate failed: ${err}`);\n }\n }\n\n\n private flushState(): Promise<void> {\n const run = this.stateWriteChain.catch(() => undefined).then(async () => {\n await mkdir(path.dirname(this.statePath), { recursive: true });\n await this.writeStateFile(this.statePath, JSON.stringify(this.state, null, 2));\n });\n this.stateWriteChain = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n }\n}\n\nexport class TierMigrationStatusStore {\n private readonly statePath: string;\n private state: TierMigrationStatusSnapshot = structuredClone(DEFAULT_TIER_MIGRATION_STATUS);\n\n constructor(memoryDir: string) {\n this.statePath = path.join(memoryDir, \"state\", \"tier-migration-status.json\");\n }\n\n async load(): Promise<void> {\n try {\n const raw = await readFile(this.statePath, \"utf-8\");\n const parsed = JSON.parse(raw) as Partial<TierMigrationStatusSnapshot> | null;\n if (!parsed || typeof parsed !== \"object\") {\n this.state = structuredClone(DEFAULT_TIER_MIGRATION_STATUS);\n return;\n }\n const totals = parsed.totals && typeof parsed.totals === \"object\"\n ? parsed.totals\n : DEFAULT_TIER_MIGRATION_STATUS.totals;\n this.state = {\n updatedAt:\n typeof parsed.updatedAt === \"string\" && parsed.updatedAt.length > 0\n ? parsed.updatedAt\n : DEFAULT_TIER_MIGRATION_STATUS.updatedAt,\n lastCycle:\n parsed.lastCycle && typeof parsed.lastCycle === \"object\"\n ? (parsed.lastCycle as TierMigrationCycleSummary)\n : null,\n totals: {\n cycles: typeof totals.cycles === \"number\" && Number.isFinite(totals.cycles) ? totals.cycles : 0,\n scanned: typeof totals.scanned === \"number\" && Number.isFinite(totals.scanned) ? totals.scanned : 0,\n migrated: typeof totals.migrated === \"number\" && Number.isFinite(totals.migrated) ? totals.migrated : 0,\n promoted: typeof totals.promoted === \"number\" && Number.isFinite(totals.promoted) ? totals.promoted : 0,\n demoted: typeof totals.demoted === \"number\" && Number.isFinite(totals.demoted) ? totals.demoted : 0,\n errors: typeof totals.errors === \"number\" && Number.isFinite(totals.errors) ? totals.errors : 0,\n },\n };\n } catch {\n this.state = structuredClone(DEFAULT_TIER_MIGRATION_STATUS);\n }\n }\n\n get(): TierMigrationStatusSnapshot {\n return {\n updatedAt: this.state.updatedAt,\n lastCycle: this.state.lastCycle ? { ...this.state.lastCycle } : null,\n totals: { ...this.state.totals },\n };\n }\n\n async recordCycle(summary: TierMigrationCycleSummary): Promise<void> {\n const now = new Date().toISOString();\n const migratedDelta = summary.dryRun ? 0 : Math.max(0, summary.migrated);\n const promotedDelta = summary.dryRun ? 0 : Math.max(0, summary.promoted);\n const demotedDelta = summary.dryRun ? 0 : Math.max(0, summary.demoted);\n const next: TierMigrationStatusSnapshot = {\n updatedAt: now,\n lastCycle: { ...summary },\n totals: {\n cycles: this.state.totals.cycles + 1,\n scanned: this.state.totals.scanned + Math.max(0, summary.scanned),\n migrated: this.state.totals.migrated + migratedDelta,\n promoted: this.state.totals.promoted + promotedDelta,\n demoted: this.state.totals.demoted + demotedDelta,\n errors: this.state.totals.errors + Math.max(0, summary.errorCount ?? 0),\n },\n };\n this.state = next;\n try {\n await mkdir(path.dirname(this.statePath), { recursive: true });\n await writeFile(this.statePath, JSON.stringify(next, null, 2), \"utf-8\");\n } catch (err) {\n log.debug(`tier migration status write failed: ${err}`);\n }\n }\n}\n\n\n/**\n * Per-session bounded history of recent recall memory-id sets, used ONLY by\n * handle resolution (issue #1582). Distinct from {@link LastRecallStore} —\n * that keeps ONE last snapshot per session; this keeps a small ring (depth N)\n * of the memory-id arrays a session has recalled, newest first, so a handle\n * cited in a later turn still resolves even after a newer recall displaced the\n * \"last\" snapshot.\n *\n * Deliberately lightweight: stores only `string[]` per entry (no full\n * snapshot), capped at `depth` per session and 50 sessions total (rule 27\n * slice/cap guards). Misses are acceptable and tagged at resolution time.\n */\nexport class RecallHandleHistoryStore {\n private readonly statePath: string;\n private readonly writeStateFile: StateFileWriter;\n private state: Record<string, Array<{ at: string; ids: string[] }>> = {};\n private writeChain: Promise<void> = Promise.resolve();\n private readonly maxDepth: number;\n\n constructor(memoryDir: string, options: { writeStateFile?: StateFileWriter; maxDepth?: number } = {}) {\n this.statePath = path.join(memoryDir, \"state\", \"handle_history.json\");\n this.writeStateFile =\n options.writeStateFile ??\n (async (filePath, content) => {\n await writeFileAtomically(filePath, content);\n });\n this.maxDepth =\n typeof options.maxDepth === \"number\" && Number.isFinite(options.maxDepth)\n ? Math.max(1, Math.min(50, Math.floor(options.maxDepth)))\n : 5;\n }\n\n async load(): Promise<void> {\n try {\n const raw = await readFile(this.statePath, \"utf-8\");\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\") this.state = parsed as typeof this.state;\n } catch {\n this.state = {};\n }\n }\n\n /**\n * Record one recall's admitted memory ids for a session, newest first.\n * The ring is capped at {@link maxDepth}; older entries drop off the tail.\n */\n async record(sessionKey: string, memoryIds: readonly string[]): Promise<void> {\n if (!sessionKey) return;\n const ids = memoryIds.filter((id): id is string => typeof id === \"string\" && id.length > 0);\n const entry = { at: new Date().toISOString(), ids };\n const prior = this.state[sessionKey] ?? [];\n const next = [entry, ...prior].slice(0, this.maxDepth);\n this.state[sessionKey] = next;\n this.capSessions();\n try {\n await this.flush();\n } catch (err) {\n log.debug(`recall handle history write failed: ${err}`);\n }\n }\n\n /**\n * Return the memory-id arrays for a session, newest first, capped at `depth`.\n * Empty array when the session has no recorded history.\n */\n recent(sessionKey: string, depth: number = this.maxDepth): Array<readonly string[]> {\n const entries = this.state[sessionKey];\n if (!entries || entries.length === 0) return [];\n const limit = Math.max(0, Math.min(depth, entries.length));\n return entries.slice(0, limit).map((e) => e.ids);\n }\n\n /** Test seam: drop all history (used by the corpus-scan hygiene test). */\n clearForTest(): void {\n this.state = {};\n }\n\n private capSessions(): void {\n const keys = Object.keys(this.state);\n if (keys.length <= 50) return;\n const ordered = keys\n .map((k) => ({ k, at: this.state[k]?.[0]?.at ?? \"\" }))\n .sort((a, b) => b.at.localeCompare(a.at));\n for (const doomed of ordered.slice(50)) {\n delete this.state[doomed.k];\n }\n }\n\n private flush(): Promise<void> {\n const run = this.writeChain.catch(() => undefined).then(async () => {\n await mkdir(path.dirname(this.statePath), { recursive: true });\n await this.writeStateFile(this.statePath, JSON.stringify(this.state, null, 2));\n });\n this.writeChain = run.then(() => undefined, () => undefined);\n return run;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,OAAO,UAAU,QAAQ,IAAI,MAAM,QAAQ,iBAAiB;AACjF,OAAO,UAAU;AACjB,SAAS,YAAY,kBAAkB;AAmGhC,SAAS,gCACd,SACA,aAAqB,IACO;AAC5B,QAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,MAAM,UAAU,CAAC;AAChD,MAAI,CAAC,MAAM,QAAQ,OAAO,EAAG,QAAO,CAAC;AACrC,SAAO,QACJ,OAAO,CAAC,SAA0C,CAAC,CAAC,QAAQ,OAAO,SAAS,QAAQ,EACpF,IAAI,CAAC,SAAS;AACb,UAAM,YACJ,KAAK,cAAc,YAAY,KAAK,cAAc,UAAU,KAAK,cAAc,WAC3E,KAAK,YACL;AACN,UAAM,MAAgC;AAAA,MACpC,MAAM,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO;AAAA,MAClD,OAAO,OAAO,KAAK,UAAU,YAAY,OAAO,SAAS,KAAK,KAAK,IAAI,KAAK,QAAQ;AAAA,MACpF,WAAW,OAAO,KAAK,cAAc,WAAW,KAAK,YAAY;AAAA,MACjE,MAAM,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO;AAAA,MAClD,UACE,OAAO,KAAK,aAAa,YAAY,OAAO,SAAS,KAAK,QAAQ,IAC9D,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,QAAQ,CAAC,IACrC;AAAA,MACN,eACE,OAAO,KAAK,kBAAkB,YAAY,OAAO,SAAS,KAAK,aAAa,IACxE,KAAK,IAAI,GAAG,KAAK,aAAa,IAC9B;AAAA,MACN;AAAA,IACF;AAIA,QACE,OAAO,KAAK,mBAAmB,YAC/B,OAAO,SAAS,KAAK,cAAc,GACnC;AACA,UAAI,iBAAiB,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,KAAK,cAAc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AO,MAAM,CAAC,CAAC;AAAA,IAC/E,CAAC;AACD,SAAK,aAAa,IAAI,KAAK,MAAM,QAAW,MAAM,MAAS;AAC3D,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/extraction-prompt.ts"],"sourcesContent":["/**\n * Extraction prompt construction (issue #1995 sibling extraction).\n *\n * The system prompt, its JSON response shape, and the placeholder table\n * derived from that shape are prompt DATA, not engine behavior. They live here\n * so `extraction.ts` holds the pipeline and one module owns the text every\n * extraction path — local LLM, direct client, gateway fallback — sends.\n */\n\nimport { AMBIENT_CAPTURE_PROMPT_SECTION, AMBIENT_SPECULATIVE_TIER_CLAUSE } from \"./ambient-provenance.js\";\nimport { resolveMemoryLifecycleCapabilities, resolveRecallAuxiliaryCapabilities } from \"./capabilities.js\";\nimport type { PluginConfig } from \"./types.js\";\n\nexport const EXTRACTION_RESPONSE_SHAPE = `{\n \"facts\": [{\n \"category\": \"<category>\",\n \"content\": \"<source-grounded statement>\",\n \"confidence\": 0.0,\n \"tags\": [\"<tag>\"],\n \"entityRef\": \"<optional normalized-name>\",\n \"cueAnchors\": [{\"type\": \"<anchor-type>\", \"value\": \"<entity-or-topic plus key aspect>\"}],\n \"promptedByQuestion\": \"<optional source-grounded question>\",\n \"quote\": \"<optional exact contiguous source span>\",\n \"scope\": \"<optional project-or-global>\",\n \"structuredAttributes\": {\"<key>\": \"<value>\"},\n \"procedureSteps\": [{\"order\": 1, \"intent\": \"<step>\"}, {\"order\": 2, \"intent\": \"<step>\"}],\n \"reasoningTrace\": {\n \"steps\": [{\"order\": 1, \"description\": \"<step>\"}, {\"order\": 2, \"description\": \"<step>\"}],\n \"finalAnswer\": \"<answer>\",\n \"observedOutcome\": \"<optional outcome>\"\n },\n \"eventTime\": \"<optional source temporal expression>\"\n }],\n \"entities\": [{\n \"name\": \"<normalized-name>\",\n \"type\": \"<entity-type>\",\n \"facts\": [\"<source-grounded statement>\"],\n \"promptedByQuestion\": \"<optional source-grounded question>\",\n \"structuredSections\": [{\"key\": \"<section-key>\", \"title\": \"<section-title>\", \"facts\": [\"<source-grounded statement>\"]}]\n }],\n \"profileUpdates\": [\"<source-grounded profile update>\"],\n \"questions\": [{\"question\": \"<source-grounded unresolved question>\", \"context\": \"<source-grounded context>\", \"priority\": 0.0}],\n \"identityReflection\": \"<conversation-grounded agent reflection>\",\n \"episodeTitle\": \"<six-to-eight word conversation segment title>\",\n \"relationships\": [{\"source\": \"<normalized-name>\", \"target\": \"<normalized-name>\", \"label\": \"<source-grounded relationship>\"}]\n}`;\nexport const EXTRACTION_RESPONSE_PLACEHOLDERS: Record<string, true> = {};\nfor (const placeholder of EXTRACTION_RESPONSE_SHAPE.match(/<[^<>\\r\\n]+>/g) ?? []) {\n EXTRACTION_RESPONSE_PLACEHOLDERS[placeholder] = true;\n}\nexport const CUE_ANCHOR_PROMPT_INSTRUCTION = `- For each fact, emit at most 3 \"cueAnchors\".\n- Each cue anchor value must be a source-grounded search hook of at most 120 characters, in the form \"<main entity or topic> <key aspect>\".\n- Set each cue anchor type to entity, file, tool, outcome, constraint, or date.\n- Omit cue anchors when the conversation does not support a useful search hook.\n- Example: \"Alice booked Bistro Max for Mike's surprise party\" can use {\"type\":\"entity\",\"value\":\"Mike surprise party\"} and {\"type\":\"entity\",\"value\":\"Alice restaurant booking\"}.`;\n\n/**\n * Bi-temporal event-time extraction instruction (#1578 PR2). Emitted on\n * every extraction entry path when `temporal.biTemporal` is on so the LLM\n * emits an optional per-fact `eventTime` expression. The expression is\n * resolved against the source turn timestamp at write time — never\n * wall-clock — so replay/import of old transcripts anchors correctly.\n * Returns an empty string when the gate is off (byte-identical prompt).\n */\nexport function eventTimePromptInstruction(config: PluginConfig): string {\n if (!config.temporalBiTemporal) return \"\";\n return `\nWhen a fact states when it became or stopped being true, copy that explicit temporal expression verbatim into \"eventTime\". Omit \"eventTime\" when no such expression appears; never infer dates.`;\n}\n\n/**\n * Build extraction instructions shared between local and cloud LLM.\n *\n * `ambientCapture` marks input from an always-on recorder, which may carry\n * speech the user never authored (issue #2294).\n */\nexport function buildExtractionInstructions(\n config: PluginConfig,\n existingEntities?: string[],\n ambientCapture = false\n): string {\n const lifecycleCaps = resolveMemoryLifecycleCapabilities(config);\n return `You are a memory extraction system. Analyze the following conversation and extract durable, reusable memories.\n\nMemory categories:\n- fact: Objective information about the world\n- preference: User likes, dislikes, or stylistic choices\n- correction: User correcting a mistake or misconception (highest priority)\n- entity: Information about a specific person, project, tool, or company\n- decision: A choice that was made with rationale\n- relationship: How two entities relate to each other (e.g., \"Alice is Bob's manager\", \"Acme Corp uses Shopify\")\n- principle: Durable rules, values, or operating beliefs (e.g., \"never use Chat Completions API\")\n- commitment: Promises, obligations, or deadlines (e.g., \"deploy by Friday\", \"call accountant Monday\")\n- moment: Emotionally significant events or milestones (e.g., \"first successful deployment of engram\")\n- skill: Capabilities the user or agent has demonstrated (e.g., \"user is proficient with Kubernetes\")${\n resolveRecallAuxiliaryCapabilities(config).causalRuleExtraction\n ? `\n- rule: Causal rules discovered through experience (format: \"IF <condition> THEN <action/outcome>\", e.g., \"IF Shopify API returns 401 THEN the admin token is missing read_products scope\")`\n : \"\"\n }\n- procedure: A reusable workflow the user wants remembered the same way across sessions. Set category to \"procedure\". Use \"content\" for a short title that includes explicit trigger phrasing (e.g. \"When you deploy to production…\", \"Whenever you ship a release…\"). Add \"procedureSteps\": an array of at least two objects {\"order\": number, \"intent\": \"concrete step description\"} in execution order. Optional per-step \"toolCall\": {\"kind\": \"…\", \"signature\": \"…\"}, \"expectedOutcome\", \"optional\": true.\n- reasoning_trace: A stored solution chain / chain-of-thought the user walked through to solve a problem (e.g. \"Here's how I debugged the latency spike: first I checked…, then I…, finally I…\"). Set category to \"reasoning_trace\". Use \"content\" for a short title summarising the problem (e.g. \"How I debugged the staging latency spike\"). Add \"reasoningTrace\": {\"steps\": [{\"order\": number, \"description\": \"what happened at this step\"}, …], \"finalAnswer\": \"the conclusion or answer\", \"observedOutcome\": \"optional confirmation of how it played out\"}. Require at least two ordered steps AND a finalAnswer. Use this category only when the user explicitly narrates their reasoning — not for ordinary decisions (use \"decision\") or reusable workflows (use \"procedure\").\n\nRules:\n- Only extract genuinely new information worth remembering across sessions.\n- Statements must be grounded in the conversation.\n- Do not treat instruction text, schema placeholders, or examples as conversation evidence.\n- Lines labelled [context user] or [context assistant] are reference context only. They may resolve references or complete a question-and-answer pair in a normal turn, but never alone establish durable information.\n- Skip transient task details and operational noise, including routine scheduler, monitoring, or automation status.\n- Priority: corrections > principles${resolveRecallAuxiliaryCapabilities(config).causalRuleExtraction ? \" > rules\" : \"\"} > preferences > commitments > decisions > relationships > entities > moments > skills > facts\n- Corrections get highest confidence.\n- Each fact should be a standalone, self-contained statement.\n- Entity references should use normalized names (lowercase, hyphenated: \"jane-doe\", \"acme-corp\")\n- CRITICAL: Entity names must be CANONICAL. Always use the hyphenated multi-word form: \"acme-corp\" NOT \"acmecorp\" or \"acme\". \"jane-doe\" NOT \"janedoe\" or \"jane\". If unsure, prefer the most specific full name.\n- Avoid creating entities typed as \"other\" when a more specific type fits (company, project, tool, person, place)\n${CUE_ANCHOR_PROMPT_INSTRUCTION}\n- When entity facts clearly belong under a durable named heading, add them to entity.structuredSections as {key, title, facts}. Example person headings: \"Beliefs\", \"Communication Style\", \"Building / Working On\". Leave structuredSections empty when no stable heading fits.\n- Tags should be concise and reusable (e.g., \"coding-style\", \"personal\", \"tools\")\n- When a fact contains measurable, categorical, or precisely valued data, include a \"structuredAttributes\" field with key-value string pairs (e.g., {\"price\": \"29.99\", \"brand\": \"Sony\"}, {\"date\": \"2024-03-15\", \"location\": \"SF\"}, {\"chosen\": \"PostgreSQL\", \"rejected\": \"MongoDB\"}). Only for concrete values, not narrative content.\n- Set confidence using these tiers:\n * Explicit (0.95-1.0): Direct user statements — \"I prefer X\", \"my name is Y\"\n * Implied (0.70-0.94): Strong contextual inference — user consistently does X, clear from conversation flow\n * Inferred (0.40-0.69): Pattern recognition — reasonable guess from limited evidence\n * Speculative (0.00-0.39): Tentative hypothesis — weak signal, needs future confirmation. Speculative memories auto-expire after 30 days if not confirmed.${ambientCapture ? AMBIENT_SPECULATIVE_TIER_CLAUSE : \"\"}${\n config.provenance?.enabled\n ? `\n- Source quotes: For each fact, include a \"quote\" field containing the EXACT verbatim words from the conversation that support the fact. Copy a contiguous span from a single speaker turn (not a paraphrase, not a summary). Cap at ~300 characters. This grounds every memory in the literal utterance that created it.`\n : \"\"\n }\n- For commitments: include any deadline or timeframe mentioned${\n lifecycleCaps.extractionScopeClassification\n ? `\n\nScope classification:\nFor each fact, set \"scope\" to one of:\n- \"global\" — knowledge that applies across projects: core framework/library bugs, API behavior patterns, user preferences (editor, language, style), general coding patterns, infrastructure knowledge, technology facts not tied to one codebase\n- \"project\" — knowledge specific to one codebase: file paths, environment configs, deployment details, project-specific workarounds, team/stakeholder info tied to one project, repo-specific conventions. Tool, command, or CLI-flag instructions TIED TO ONE AGENT are also \"project\", because the same tool name means different things in different agent integrations (a \"search\" tool may search repository code in one agent and the web in another); when keeping such an agent-tied instruction, the fact text MUST name the originating agent as a leading \"In <agent>,\" clause (e.g. \"In Pi, use the search tool with a repository path.\"). A tool/command fact that holds in every agent and every repo is NOT agent-tied — leave it \"global\" and do not add a qualifier (e.g. \"\\`git status --short\\` emits compact output\"). Examples: \"In Pi, the search tool takes a repository path\" -> \"project\"; \"\\`git status --short\\` emits compact output\" -> \"global\".\nWhen in doubt, prefer \"project\" — it is safer to keep knowledge scoped narrowly.`\n : \"\"\n }\n${\n ambientCapture\n ? `${AMBIENT_CAPTURE_PROMPT_SECTION}\n`\n : \"\"\n}\nEntity creation rules (STRICT):\n- Only create entities for DURABLE things: real people, companies, products, tools, ongoing projects\n- NEVER create entities for transient items: individual PRs, branches, Jira tickets, meetings, agent task IDs, log files, database tables, cron job runs, sessions\n- When you learn something about a transient item (e.g., PR #58 fixed a bug), store it as a FACT with an entityRef to the parent project — do NOT create an entity for the PR itself\n- Prefer attaching facts to broad parent entities rather than creating sub-entities. E.g., \"acme-store uses Algolia for search\" is a fact on entity \"acme-store\", NOT a new entity \"acme-store-algolia-connector\"\n- The entity list should be SHORT — think \"things that would have their own Wikipedia page\" not \"things mentioned in passing\"\n\n${\n existingEntities && existingEntities.length > 0\n ? `\nKNOWN ENTITIES (use these exact names when referencing existing things):\n${existingEntities.join(\", \")}\n\nWhen you see something that matches a known entity, use THAT name exactly. Only create a NEW entity if nothing in this list represents it.\n`\n : \"\"\n}\n${eventTimePromptInstruction(config)}\nAlso extract relationships between entities mentioned in the conversation.\n- Format: {source: \"entity-name\", target: \"entity-name\", label: \"relationship description\"}\n- Max 5 relationships per extraction\n- Only include clear, durable relationships (e.g., \"works at\", \"created\", \"manages\", \"uses\")\n- Use normalized entity names (e.g., \"person-jane-doe\", \"company-acme-corp\")\n\n\nAlso emit \"episodeTitle\" as a six-to-eight word title for this conversation segment.\nQuestions are optional. Include only source-grounded unresolved questions that would be useful in future sessions; otherwise return an empty array.\n\nFinally, write a brief identity reflection about the agent who had this conversation, based only on the conversation. Do not write about the extraction process.`;\n}\n"],"mappings":";;;;;;;;;;AAaO,IAAM,4BAA4B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiClC,IAAM,mCAAyD,CAAC;AACvE,WAAW,eAAe,0BAA0B,MAAM,eAAe,KAAK,CAAC,GAAG;AAChF,mCAAiC,WAAW,IAAI;AAClD;AACO,IAAM,gCAAgC;AAAA;AAAA;AAAA;AAAA;AActC,SAAS,2BAA2B,QAA8B;AACvE,MAAI,CAAC,OAAO,mBAAoB,QAAO;AACvC,SAAO;AAAA;AAET;AAQO,SAAS,4BACd,QACA,kBACA,iBAAiB,OACT;AACR,QAAM,gBAAgB,mCAAmC,MAA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