@remnic/core 9.69.43 → 9.69.45

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 (508) hide show
  1. package/dist/access-admin-ops-surface.d.ts +14 -14
  2. package/dist/access-admin-ops-surface.js +24 -24
  3. package/dist/access-authorization-probe.d.ts +14 -14
  4. package/dist/access-authorization-probe.js +25 -25
  5. package/dist/access-boundary.d.ts +14 -14
  6. package/dist/access-boundary.js +24 -24
  7. package/dist/access-cli.js +71 -69
  8. package/dist/access-cli.js.map +1 -1
  9. package/dist/access-coding-context-resolution.d.ts +1 -1
  10. package/dist/access-extraction-force-flush.d.ts +14 -14
  11. package/dist/access-extraction-force-flush.js +24 -24
  12. package/dist/access-health-types.d.ts +1 -1
  13. package/dist/access-http-briefing.d.ts +14 -14
  14. package/dist/access-http-briefing.js +25 -25
  15. package/dist/access-http-lcm-compaction.d.ts +14 -14
  16. package/dist/access-http-lifecycle-flush.d.ts +14 -14
  17. package/dist/access-http-offline-stream.d.ts +14 -14
  18. package/dist/access-http-query.d.ts +2 -2
  19. package/dist/access-http-query.js +26 -26
  20. package/dist/access-http.d.ts +15 -15
  21. package/dist/access-http.js +40 -40
  22. package/dist/access-identity-continuity-surface.d.ts +11 -11
  23. package/dist/access-identity-continuity-surface.js +24 -24
  24. package/dist/access-lcm-surface.d.ts +14 -14
  25. package/dist/access-lcm-surface.js +24 -24
  26. package/dist/access-mcp-shared-context-tools.d.ts +14 -14
  27. package/dist/access-mcp.d.ts +14 -14
  28. package/dist/access-mcp.js +32 -32
  29. package/dist/access-memory-search-fanout.d.ts +2 -2
  30. package/dist/{access-namespace-preflight-CE-RrXKu.d.ts → access-namespace-preflight-DDnsN22V.d.ts} +1 -1
  31. package/dist/access-namespace-preflight.d.ts +3 -3
  32. package/dist/access-namespace-preflight.js +24 -24
  33. package/dist/access-observe-transcript.d.ts +11 -11
  34. package/dist/access-observe-write-category.d.ts +4 -3
  35. package/dist/access-observe-write-category.js +2 -2
  36. package/dist/access-observe-write-surface.d.ts +14 -14
  37. package/dist/access-observe-write-surface.js +24 -24
  38. package/dist/access-offline-manifest.d.ts +11 -11
  39. package/dist/access-offline-manifest.js +3 -3
  40. package/dist/access-operations-batch.js +25 -25
  41. package/dist/access-operations.d.ts +14 -14
  42. package/dist/access-operations.js +31 -31
  43. package/dist/access-recall-concurrency.d.ts +14 -14
  44. package/dist/access-recall-concurrency.js +24 -24
  45. package/dist/access-recall-response.d.ts +14 -14
  46. package/dist/access-recall-response.js +24 -24
  47. package/dist/access-recall-surface.d.ts +14 -14
  48. package/dist/access-recall-surface.js +24 -24
  49. package/dist/access-schema.d.ts +9 -2
  50. package/dist/access-schema.js +3 -1
  51. package/dist/{access-service-DxTTTg9O.d.ts → access-service-CDteK_Gt.d.ts} +9 -9
  52. package/dist/access-service-helpers.d.ts +14 -14
  53. package/dist/access-service.d.ts +14 -14
  54. package/dist/access-service.js +24 -24
  55. package/dist/access-surface-catalog.d.ts +14 -14
  56. package/dist/access-surface-catalog.js +26 -26
  57. package/dist/access-wearables-meetings-surface.d.ts +4 -4
  58. package/dist/action-confidence.d.ts +1 -1
  59. package/dist/active-memory-bridge.d.ts +1 -1
  60. package/dist/active-recall.d.ts +1 -1
  61. package/dist/active-recall.js +2 -2
  62. package/dist/activity/digest.d.ts +1 -1
  63. package/dist/ambient-provenance.d.ts +1 -1
  64. package/dist/artifact-search.d.ts +1 -1
  65. package/dist/{auto-sync-QZD4RD6H.js → auto-sync-DG5KEOF5.js} +5 -5
  66. package/dist/background-generation.d.ts +1 -1
  67. package/dist/behavior-learner.d.ts +1 -1
  68. package/dist/behavior-signals.d.ts +1 -1
  69. package/dist/bootstrap.d.ts +11 -11
  70. package/dist/briefing-window.d.ts +2 -2
  71. package/dist/briefing.d.ts +2 -2
  72. package/dist/briefing.js +6 -6
  73. package/dist/buffer-surprise-report.d.ts +1 -1
  74. package/dist/buffer-turn-helpers.d.ts +1 -1
  75. package/dist/buffer.d.ts +2 -2
  76. package/dist/buffer.js +3 -3
  77. package/dist/bulk-import/index.d.ts +3 -3
  78. package/dist/calibration.d.ts +1 -1
  79. package/dist/calibration.js +2 -2
  80. package/dist/capabilities.d.ts +1 -1
  81. package/dist/{catalog-Ya3DDn_T.d.ts → catalog-Dl2hYqpS.d.ts} +1 -1
  82. package/dist/causal-behavior.d.ts +1 -1
  83. package/dist/causal-consolidation.d.ts +1 -1
  84. package/dist/causal-consolidation.js +7 -7
  85. package/dist/causal-trajectory-graph.d.ts +1 -1
  86. package/dist/{chunk-BZDK5EOD.js → chunk-2LRO73MN.js} +2 -2
  87. package/dist/chunk-2WMXZYMS.js +25 -0
  88. package/dist/chunk-2WMXZYMS.js.map +1 -0
  89. package/dist/{chunk-JDL5BYYF.js → chunk-46A4RGBC.js} +2 -2
  90. package/dist/{chunk-6EGIQEKC.js → chunk-4HTQ76O4.js} +2 -2
  91. package/dist/{chunk-7L54ARML.js → chunk-4XTSKGLX.js} +2 -2
  92. package/dist/{chunk-KOM36ILJ.js → chunk-5TKHJ5RW.js} +13 -13
  93. package/dist/{chunk-IB7FDRRC.js → chunk-5XTILJRI.js} +2 -2
  94. package/dist/{chunk-J2MGTGKC.js → chunk-5ZXGH2ZL.js} +20 -3
  95. package/dist/chunk-5ZXGH2ZL.js.map +1 -0
  96. package/dist/{chunk-VJXMFBVR.js → chunk-6II55MXS.js} +2 -2
  97. package/dist/{chunk-LT4H7SL5.js → chunk-7LKXP4QG.js} +19 -19
  98. package/dist/{chunk-PF7LQ22G.js → chunk-A2YN3FR4.js} +3 -3
  99. package/dist/chunk-AAQA6ZUP.js +41 -0
  100. package/dist/chunk-AAQA6ZUP.js.map +1 -0
  101. package/dist/{chunk-RJ7Z7YXK.js → chunk-AG6PANBG.js} +14 -20
  102. package/dist/chunk-AG6PANBG.js.map +1 -0
  103. package/dist/{chunk-KDLOKVX7.js → chunk-AOMUIF3R.js} +2 -2
  104. package/dist/{chunk-2YIUUXNK.js → chunk-B55FYF6F.js} +2 -2
  105. package/dist/{chunk-2HDLDBJW.js → chunk-BOWAP64Q.js} +2 -2
  106. package/dist/{chunk-PPDZSJXB.js → chunk-C3MCMFNV.js} +2 -2
  107. package/dist/{chunk-DABSYX7V.js → chunk-D3DJYGU2.js} +3 -3
  108. package/dist/{chunk-F2FJTOV6.js → chunk-DO6R3LIE.js} +2 -2
  109. package/dist/{chunk-LD22AAJI.js → chunk-DSHSQGSN.js} +2 -2
  110. package/dist/{chunk-3254BYQV.js → chunk-E5VOKZQV.js} +1 -1
  111. package/dist/{chunk-46FVFU7S.js → chunk-EC5SVM6H.js} +2 -2
  112. package/dist/{chunk-UHSOPTNB.js → chunk-EP6BA7VV.js} +50 -15
  113. package/dist/chunk-EP6BA7VV.js.map +1 -0
  114. package/dist/{chunk-BPXJINHW.js → chunk-EUP4AXIW.js} +2 -2
  115. package/dist/{chunk-KY75VZKG.js → chunk-F6AYWLRN.js} +2 -2
  116. package/dist/{chunk-4AX5OYKC.js → chunk-FDDCZDBI.js} +2 -2
  117. package/dist/{chunk-VHANUT45.js → chunk-HBGSZ62Z.js} +7 -7
  118. package/dist/{chunk-M7H56FOQ.js → chunk-HVGCQMTQ.js} +2 -2
  119. package/dist/{chunk-GMU7MAHS.js → chunk-IAT5WFEU.js} +3 -3
  120. package/dist/{chunk-R3H2AXO2.js → chunk-IFULZYYQ.js} +2 -2
  121. package/dist/{chunk-ZYSOT6HD.js → chunk-J3IWHCMF.js} +2 -2
  122. package/dist/{chunk-QCTXQ2HW.js → chunk-J6NEOCQC.js} +2 -2
  123. package/dist/{chunk-H2N6SLTR.js → chunk-JIWZVOQM.js} +2 -2
  124. package/dist/{chunk-LUAQHDUI.js → chunk-JMBTNVMW.js} +2 -2
  125. package/dist/{chunk-HKQAI6XI.js → chunk-JPNUKKSL.js} +2 -2
  126. package/dist/{chunk-CRK6F6N3.js → chunk-JUOJGZPV.js} +5 -1
  127. package/dist/chunk-JUOJGZPV.js.map +1 -0
  128. package/dist/{chunk-F6PTJLEM.js → chunk-K4KE5MYE.js} +1 -1
  129. package/dist/{chunk-5AJZ7EUW.js → chunk-K75H7FSO.js} +2 -2
  130. package/dist/{chunk-JL4TQYM5.js → chunk-L272A5QW.js} +33 -2
  131. package/dist/{chunk-JL4TQYM5.js.map → chunk-L272A5QW.js.map} +1 -1
  132. package/dist/{chunk-7F47R4H4.js → chunk-LZAJONO5.js} +2 -2
  133. package/dist/{chunk-2WFOVXVJ.js → chunk-M7ECD3KN.js} +2 -2
  134. package/dist/{chunk-KORQWGUA.js → chunk-MDYZCPNQ.js} +2 -2
  135. package/dist/{chunk-IWHNT35B.js → chunk-N6I257OM.js} +3 -3
  136. package/dist/{chunk-YR5QT4SR.js → chunk-NAFPHFDM.js} +2 -2
  137. package/dist/{chunk-D7UUB33A.js → chunk-NGAFYIHQ.js} +2 -2
  138. package/dist/{chunk-LXMZM7LM.js → chunk-NKDQXDFL.js} +16 -16
  139. package/dist/{chunk-ZBSP4BSN.js → chunk-NRFUYVW7.js} +2 -2
  140. package/dist/{chunk-VNQRRUNS.js → chunk-O6ZSWHVR.js} +2 -3
  141. package/dist/chunk-O6ZSWHVR.js.map +1 -0
  142. package/dist/{chunk-XOCGC3FJ.js → chunk-OFBJD3V5.js} +2 -2
  143. package/dist/{chunk-YPB3Y57U.js → chunk-OOBUWMPY.js} +4 -4
  144. package/dist/{chunk-324HBGS4.js → chunk-OREGA7GY.js} +6 -6
  145. package/dist/{chunk-4WMGRLTV.js → chunk-Q4MI2KCG.js} +2 -2
  146. package/dist/{chunk-MOL7JK4F.js → chunk-R4HFCATE.js} +2 -2
  147. package/dist/{chunk-AKB44K3D.js → chunk-SPN5YFXN.js} +8 -8
  148. package/dist/{chunk-2PIC6CEN.js → chunk-T2ZNUWUY.js} +2 -2
  149. package/dist/{chunk-NHFXGNGC.js → chunk-TFS5FAAC.js} +36 -36
  150. package/dist/{chunk-JDOBQPJY.js → chunk-TNQR7N52.js} +2 -2
  151. package/dist/{chunk-JWBDHA4F.js → chunk-UJXNBZYJ.js} +4 -4
  152. package/dist/{chunk-DDGQDNQW.js → chunk-VA5QRTZX.js} +2 -2
  153. package/dist/{chunk-XIJHRQ4A.js → chunk-W6YDAIVB.js} +2 -2
  154. package/dist/{chunk-GKKLI23D.js → chunk-WCQ7L54B.js} +2 -2
  155. package/dist/{chunk-3YQ7VLP3.js → chunk-WMTYEQO5.js} +2 -2
  156. package/dist/{chunk-VKDXYEA6.js → chunk-WNMVUWI7.js} +2 -2
  157. package/dist/{chunk-OGAKUA7I.js → chunk-YHSEUZV5.js} +2 -2
  158. package/dist/{chunk-GR76OKET.js → chunk-YSBYNCCN.js} +2 -2
  159. package/dist/{chunk-QUBPZQED.js → chunk-Z5YNVWRD.js} +2 -2
  160. package/dist/{chunk-UCLWIMVW.js → chunk-ZLVURGAJ.js} +2 -2
  161. package/dist/{chunk-M6FKXOYV.js → chunk-ZQ533JDE.js} +2 -2
  162. package/dist/{chunk-TRTLWUDD.js → chunk-ZTHGFTMW.js} +2 -2
  163. package/dist/{cli-BfCl5kWD.d.ts → cli-CZDhIcxu.d.ts} +5 -5
  164. package/dist/cli.d.ts +16 -16
  165. package/dist/cli.js +53 -53
  166. package/dist/coding/export-okf-codegraph.d.ts +1 -1
  167. package/dist/coding/export-okf-codegraph.js +5 -5
  168. package/dist/coding/pre-action-gate.d.ts +1 -1
  169. package/dist/compounding/engine.d.ts +2 -2
  170. package/dist/compounding/engine.js +6 -6
  171. package/dist/compounding/preference-consolidator.d.ts +1 -1
  172. package/dist/compression-optimizer.d.ts +1 -1
  173. package/dist/config.d.ts +1 -1
  174. package/dist/config.js +2 -2
  175. package/dist/connectors/codex-materialize-runner.d.ts +1 -1
  176. package/dist/connectors/codex-materialize-runner.js +6 -6
  177. package/dist/connectors/codex-materialize.d.ts +1 -1
  178. package/dist/connectors/index.d.ts +1 -1
  179. package/dist/connectors/index.js +6 -6
  180. package/dist/consolidation-provenance-check.d.ts +2 -2
  181. package/dist/consolidation-undo.d.ts +2 -2
  182. package/dist/contradiction/index.d.ts +4 -4
  183. package/dist/converge-config.d.ts +1 -1
  184. package/dist/convergence-refresh.d.ts +2 -2
  185. package/dist/convergence-refresh.js +8 -8
  186. package/dist/conversation-index/backend.d.ts +1 -1
  187. package/dist/conversation-index/chunker.d.ts +1 -1
  188. package/dist/conversation-index/faiss-adapter.d.ts +1 -1
  189. package/dist/conversation-index/indexer.d.ts +1 -1
  190. package/dist/conversation-index/search.d.ts +1 -1
  191. package/dist/corpus-watermark.d.ts +1 -1
  192. package/dist/corpus-watermark.js +8 -8
  193. package/dist/cross-lingual-recall.d.ts +1 -1
  194. package/dist/day-summary.d.ts +1 -1
  195. package/dist/deep-recall-http-glue.d.ts +14 -14
  196. package/dist/deep-recall-http-glue.js +2 -2
  197. package/dist/deep-recall-mcp-tools.d.ts +14 -14
  198. package/dist/deep-recall-policy-llm.d.ts +2 -2
  199. package/dist/deep-recall-policy-llm.js +3 -3
  200. package/dist/deep-recall-seeds.d.ts +1 -1
  201. package/dist/delinearize.d.ts +1 -1
  202. package/dist/dependency-propagation-config.d.ts +1 -1
  203. package/dist/{dependency-propagation-delivery-CggS9BFT.d.ts → dependency-propagation-delivery-BXaUoVUf.d.ts} +1 -1
  204. package/dist/direct-answer-wiring.d.ts +1 -1
  205. package/dist/direct-answer.d.ts +1 -1
  206. package/dist/embedding-fallback.d.ts +1 -1
  207. package/dist/enrichment/index.d.ts +1 -1
  208. package/dist/entity-origin-fields.d.ts +1 -1
  209. package/dist/entity-retrieval.d.ts +2 -2
  210. package/dist/entity-retrieval.js +6 -6
  211. package/dist/entity-schema.d.ts +1 -1
  212. package/dist/episodic-context.d.ts +1 -1
  213. package/dist/eval-trajectory-contracts.d.ts +1 -1
  214. package/dist/eval-trajectory-store.d.ts +1 -1
  215. package/dist/eval-trajectory.d.ts +1 -1
  216. package/dist/explicit-capture.d.ts +11 -11
  217. package/dist/external-wiki-access.d.ts +14 -14
  218. package/dist/external-wiki-access.js +25 -25
  219. package/dist/external-wiki-collection-registration.d.ts +1 -1
  220. package/dist/external-wiki-collection.d.ts +1 -1
  221. package/dist/external-wiki-mcp-tools.d.ts +14 -14
  222. package/dist/extraction-error-classification.d.ts +1 -1
  223. package/dist/extraction-faithfulness.d.ts +2 -2
  224. package/dist/extraction-faithfulness.js +3 -3
  225. package/dist/extraction-judge-telemetry.d.ts +2 -2
  226. package/dist/extraction-judge-training.d.ts +2 -2
  227. package/dist/extraction-judge.d.ts +2 -2
  228. package/dist/extraction-judge.js +3 -3
  229. package/dist/extraction-liveness.d.ts +1 -1
  230. package/dist/extraction-normalization.d.ts +1 -1
  231. package/dist/extraction-prompt.d.ts +1 -1
  232. package/dist/extraction-source-grounding-rules.d.ts +1 -1
  233. package/dist/extraction-source-grounding.d.ts +1 -1
  234. package/dist/extraction-span-config.d.ts +1 -1
  235. package/dist/extraction-span-materialize.d.ts +1 -1
  236. package/dist/extraction-span-wire.d.ts +23 -4
  237. package/dist/extraction-span-wire.js +7 -8
  238. package/dist/extraction-span-wire.js.map +1 -1
  239. package/dist/extraction.d.ts +2 -2
  240. package/dist/extraction.js +13 -11
  241. package/dist/fallback-llm-codex-subscription.d.ts +1 -1
  242. package/dist/fallback-llm-codex-subscription.js +1 -1
  243. package/dist/fallback-llm.d.ts +1 -1
  244. package/dist/fallback-llm.js +2 -2
  245. package/dist/{generic-recall-paths-CoXPSnCw.d.ts → generic-recall-paths-BkVVEoeO.d.ts} +1 -1
  246. package/dist/graph-append-error.d.ts +1 -1
  247. package/dist/graph-dashboard-diff.d.ts +1 -1
  248. package/dist/graph-dashboard-key.d.ts +1 -1
  249. package/dist/graph-dashboard-parser.d.ts +1 -1
  250. package/dist/graph-edge-reinforcement.d.ts +1 -1
  251. package/dist/graph-jsonl.d.ts +1 -1
  252. package/dist/graph-path-reconstruction.d.ts +1 -1
  253. package/dist/graph-path-scoring.d.ts +1 -1
  254. package/dist/graph-snapshot.d.ts +1 -1
  255. package/dist/graph.d.ts +1 -1
  256. package/dist/harmonic-retrieval.js +1 -1
  257. package/dist/importance.d.ts +1 -1
  258. package/dist/importers/index.d.ts +1 -1
  259. package/dist/importers/test-utils.d.ts +1 -1
  260. package/dist/in-flight-reads.d.ts +1 -1
  261. package/dist/{index-fdw_oK5a.d.ts → index-TBPe6NvB.d.ts} +3 -3
  262. package/dist/index.d.ts +28 -28
  263. package/dist/index.js +73 -69
  264. package/dist/intent.d.ts +1 -1
  265. package/dist/lcm/engine.d.ts +1 -1
  266. package/dist/lcm/index.d.ts +1 -1
  267. package/dist/lcm/tools.d.ts +1 -1
  268. package/dist/lifecycle.d.ts +1 -1
  269. package/dist/live-connectors-runner.d.ts +1 -1
  270. package/dist/{local-llm-3-jtw52a.d.ts → local-llm-DdrhmecM.d.ts} +1 -1
  271. package/dist/local-llm-config.js +1 -1
  272. package/dist/local-llm-helpers.d.ts +2 -2
  273. package/dist/local-llm.d.ts +2 -2
  274. package/dist/local-model-endpoint.d.ts +1 -1
  275. package/dist/location/index.d.ts +5 -5
  276. package/dist/location/index.js +8 -8
  277. package/dist/maintenance/memory-governance.d.ts +1 -1
  278. package/dist/maintenance/memory-governance.js +6 -6
  279. package/dist/maintenance/rebuild-memory-lifecycle-ledger.d.ts +2 -2
  280. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +6 -6
  281. package/dist/maintenance/rebuild-memory-projection.d.ts +2 -2
  282. package/dist/maintenance/rebuild-memory-projection.js +7 -7
  283. package/dist/{maintenance-DgeeH0a1.d.ts → maintenance-B813YFWJ.d.ts} +3 -3
  284. package/dist/mcp-memory-inspector-app.d.ts +14 -14
  285. package/dist/memory-action-policy.d.ts +1 -1
  286. package/dist/memory-cache.d.ts +1 -1
  287. package/dist/memory-controller.d.ts +1 -1
  288. package/dist/memory-lifecycle-ledger-utils.d.ts +1 -1
  289. package/dist/memory-projection-store.d.ts +1 -1
  290. package/dist/memory-provenance.d.ts +1 -1
  291. package/dist/memory-snapshot.d.ts +1 -1
  292. package/dist/memory-subject-cli.d.ts +14 -14
  293. package/dist/memory-subject.d.ts +14 -14
  294. package/dist/memory-worth-outcomes.d.ts +2 -2
  295. package/dist/models-json.d.ts +1 -1
  296. package/dist/namespaces/migrate.d.ts +3 -3
  297. package/dist/namespaces/migrate.js +7 -7
  298. package/dist/namespaces/principal.d.ts +1 -1
  299. package/dist/namespaces/search.d.ts +1 -1
  300. package/dist/namespaces/storage.d.ts +3 -3
  301. package/dist/namespaces/storage.js +6 -6
  302. package/dist/native-knowledge.d.ts +1 -1
  303. package/dist/offline-sync-impression-drain.d.ts +1 -1
  304. package/dist/operator-doctor-corpus.d.ts +1 -1
  305. package/dist/operator-doctor-corpus.js +9 -9
  306. package/dist/operator-doctor-replica.d.ts +1 -1
  307. package/dist/operator-toolkit.d.ts +3 -3
  308. package/dist/operator-toolkit.js +16 -16
  309. package/dist/orchestration/compression-guideline-coordinator.d.ts +2 -2
  310. package/dist/orchestration/maintenance.d.ts +4 -4
  311. package/dist/orchestration/maintenance.js +14 -14
  312. package/dist/{orchestrator-VXWKdatm.d.ts → orchestrator-BCvQavIS.d.ts} +10 -10
  313. package/dist/orchestrator.d.ts +11 -11
  314. package/dist/orchestrator.js +71 -69
  315. package/dist/patterns-cli.d.ts +1 -1
  316. package/dist/{pipeline-CwXZBKR5.d.ts → pipeline-4lqKJZ_0.d.ts} +1 -1
  317. package/dist/policy-runtime.d.ts +1 -1
  318. package/dist/proactive-contention.d.ts +2 -2
  319. package/dist/provenance.d.ts +1 -1
  320. package/dist/{public-http-B55s59aR.d.ts → public-http-NH72a6aa.d.ts} +1 -1
  321. package/dist/{qmd-DOLTPIQg.d.ts → qmd-DnoWaXKb.d.ts} +1 -1
  322. package/dist/qmd-preflight.d.ts +2 -2
  323. package/dist/qmd-recall-cache.d.ts +1 -1
  324. package/dist/qmd.d.ts +2 -2
  325. package/dist/recall-concurrency-config.d.ts +1 -1
  326. package/dist/recall-disclosure-escalation.d.ts +1 -1
  327. package/dist/recall-explain-renderer.d.ts +1 -1
  328. package/dist/recall-memory-map.d.ts +1 -1
  329. package/dist/recall-navigate-access.d.ts +1 -1
  330. package/dist/recall-navigate-disclosure.d.ts +1 -1
  331. package/dist/recall-navigate.d.ts +1 -1
  332. package/dist/recall-navigation-http-glue.d.ts +14 -14
  333. package/dist/recall-navigation-mcp-tools.d.ts +14 -14
  334. package/dist/recall-navigation-operations.js +25 -25
  335. package/dist/recall-navigation-renderer.d.ts +1 -1
  336. package/dist/recall-navigation.d.ts +1 -1
  337. package/dist/recall-navigation.js +24 -24
  338. package/dist/recall-planner-llm.d.ts +1 -1
  339. package/dist/recall-planner-llm.js +2 -2
  340. package/dist/recall-state-view-admission.d.ts +2 -2
  341. package/dist/recall-state-view-admission.js +3 -3
  342. package/dist/recall-state-view-anchors.d.ts +1 -1
  343. package/dist/recall-state.d.ts +1 -1
  344. package/dist/recall-tag-filter.d.ts +1 -1
  345. package/dist/recall-timings.d.ts +1 -1
  346. package/dist/recall-xray-cli.d.ts +1 -1
  347. package/dist/recall-xray-renderer.d.ts +1 -1
  348. package/dist/recall-xray.d.ts +1 -1
  349. package/dist/reconcile/cursor.d.ts +1 -1
  350. package/dist/reconcile/manifest.d.ts +1 -1
  351. package/dist/reconcile/manifest.js +2 -2
  352. package/dist/reconcile/plan.d.ts +1 -1
  353. package/dist/replay/normalizers/chatgpt.d.ts +1 -1
  354. package/dist/replay/normalizers/claude.d.ts +1 -1
  355. package/dist/replay/normalizers/openclaw.d.ts +1 -1
  356. package/dist/replay/normalizers/shared.d.ts +1 -1
  357. package/dist/replay/runner.d.ts +1 -1
  358. package/dist/replay/types.d.ts +1 -1
  359. package/dist/replica-divergence.d.ts +1 -1
  360. package/dist/replica-peers-config.d.ts +1 -1
  361. package/dist/resolve-auth-token.d.ts +1 -1
  362. package/dist/resume-bundles.js +3 -3
  363. package/dist/retrieval-agents.d.ts +2 -2
  364. package/dist/retrieval-tiers.d.ts +1 -1
  365. package/dist/routing/engine.d.ts +1 -1
  366. package/dist/routing/store.d.ts +1 -1
  367. package/dist/salvage-envelope.d.ts +1 -1
  368. package/dist/{scope-profiles-C564-hrv.d.ts → scope-profiles-crazXegZ.d.ts} +1 -1
  369. package/dist/search/embed-helper.d.ts +1 -1
  370. package/dist/search/factory.d.ts +1 -1
  371. package/dist/search/index.d.ts +1 -1
  372. package/dist/search/lancedb-backend.d.ts +1 -1
  373. package/dist/search/meilisearch-backend.d.ts +1 -1
  374. package/dist/search/noop-backend.d.ts +1 -1
  375. package/dist/search/orama-backend.d.ts +1 -1
  376. package/dist/search/port.d.ts +1 -1
  377. package/dist/search/remote-backend.d.ts +1 -1
  378. package/dist/{semantic-consolidation-g6x-ShY8.d.ts → semantic-consolidation-B09JI9WM.d.ts} +1 -1
  379. package/dist/semantic-consolidation.d.ts +2 -2
  380. package/dist/semantic-consolidation.js +7 -7
  381. package/dist/semantic-rule-promotion.js +6 -6
  382. package/dist/semantic-rule-verifier.d.ts +1 -1
  383. package/dist/semantic-rule-verifier.js +6 -6
  384. package/dist/{service-CaCOk0rd.d.ts → service-Echc5Xso.d.ts} +2 -2
  385. package/dist/session-observer-bands.d.ts +1 -1
  386. package/dist/session-observer-state.d.ts +1 -1
  387. package/dist/shared-context/manager.d.ts +1 -1
  388. package/dist/signal.d.ts +1 -1
  389. package/dist/source-agent-qualifier.d.ts +1 -1
  390. package/dist/source-agent-qualifier.js +9 -9
  391. package/dist/source-attribution.d.ts +7 -4
  392. package/dist/source-attribution.js +1 -1
  393. package/dist/standup/build.js +6 -6
  394. package/dist/{storage-C9nsZX5Q.d.ts → storage-ClkHCQSE.d.ts} +1 -1
  395. package/dist/storage.d.ts +2 -2
  396. package/dist/storage.js +5 -5
  397. package/dist/subject-config.d.ts +1 -1
  398. package/dist/summarizer.d.ts +1 -1
  399. package/dist/summarizer.js +3 -3
  400. package/dist/summary-snapshot.d.ts +1 -1
  401. package/dist/support-passport/index.d.ts +17 -17
  402. package/dist/support-passport/index.js +27 -27
  403. package/dist/{tagging-BA4RFdH3.d.ts → tagging-ksktJ60G.d.ts} +2 -2
  404. package/dist/temporal-supersession.d.ts +2 -2
  405. package/dist/temporal-timeline-recall.d.ts +1 -1
  406. package/dist/temporal-validity.d.ts +1 -1
  407. package/dist/threading.d.ts +1 -1
  408. package/dist/tier-migration.d.ts +2 -2
  409. package/dist/tier-routing.d.ts +1 -1
  410. package/dist/topics.d.ts +1 -1
  411. package/dist/transcript.d.ts +1 -1
  412. package/dist/transfer/export-okf.d.ts +1 -1
  413. package/dist/transfer/export-okf.js +6 -6
  414. package/dist/trust-score-stage.d.ts +1 -1
  415. package/dist/trust-score.d.ts +1 -1
  416. package/dist/{types-Sps-lg5I.d.ts → types-nmhnJpxx.d.ts} +1 -1
  417. package/dist/types.d.ts +1 -1
  418. package/dist/utility-runtime.d.ts +1 -1
  419. package/dist/verified-recall.js +6 -6
  420. package/dist/who-knows-cli.d.ts +14 -14
  421. package/dist/who-knows-cli.js +7 -7
  422. package/dist/who-knows.d.ts +14 -14
  423. package/dist/who-knows.js +6 -6
  424. package/dist/write-envelope.d.ts +1 -1
  425. package/package.json +2 -2
  426. package/src/access-category-alias.test.ts +57 -0
  427. package/src/access-observe-write-category.ts +20 -1
  428. package/src/access-schema.ts +10 -0
  429. package/src/background-generation.test.ts +77 -0
  430. package/src/extraction-span-wire.test.ts +17 -1
  431. package/src/extraction-span-wire.ts +46 -3
  432. package/src/extraction.ts +2 -11
  433. package/src/local-llm-config.test.ts +21 -0
  434. package/src/local-llm-config.ts +1 -2
  435. package/src/providers/codex-subscription.test.ts +109 -3
  436. package/src/providers/codex-subscription.ts +57 -17
  437. package/src/source-attribution.test.ts +27 -0
  438. package/src/source-attribution.ts +41 -5
  439. package/src/summarizer.ts +18 -0
  440. package/dist/chunk-CRK6F6N3.js.map +0 -1
  441. package/dist/chunk-J2MGTGKC.js.map +0 -1
  442. package/dist/chunk-RJ7Z7YXK.js.map +0 -1
  443. package/dist/chunk-UHSOPTNB.js.map +0 -1
  444. package/dist/chunk-VNQRRUNS.js.map +0 -1
  445. package/dist/chunk-YTV6J4T6.js +0 -14
  446. package/dist/chunk-YTV6J4T6.js.map +0 -1
  447. /package/dist/{auto-sync-QZD4RD6H.js.map → auto-sync-DG5KEOF5.js.map} +0 -0
  448. /package/dist/{chunk-BZDK5EOD.js.map → chunk-2LRO73MN.js.map} +0 -0
  449. /package/dist/{chunk-JDL5BYYF.js.map → chunk-46A4RGBC.js.map} +0 -0
  450. /package/dist/{chunk-6EGIQEKC.js.map → chunk-4HTQ76O4.js.map} +0 -0
  451. /package/dist/{chunk-7L54ARML.js.map → chunk-4XTSKGLX.js.map} +0 -0
  452. /package/dist/{chunk-KOM36ILJ.js.map → chunk-5TKHJ5RW.js.map} +0 -0
  453. /package/dist/{chunk-IB7FDRRC.js.map → chunk-5XTILJRI.js.map} +0 -0
  454. /package/dist/{chunk-VJXMFBVR.js.map → chunk-6II55MXS.js.map} +0 -0
  455. /package/dist/{chunk-LT4H7SL5.js.map → chunk-7LKXP4QG.js.map} +0 -0
  456. /package/dist/{chunk-PF7LQ22G.js.map → chunk-A2YN3FR4.js.map} +0 -0
  457. /package/dist/{chunk-KDLOKVX7.js.map → chunk-AOMUIF3R.js.map} +0 -0
  458. /package/dist/{chunk-2YIUUXNK.js.map → chunk-B55FYF6F.js.map} +0 -0
  459. /package/dist/{chunk-2HDLDBJW.js.map → chunk-BOWAP64Q.js.map} +0 -0
  460. /package/dist/{chunk-PPDZSJXB.js.map → chunk-C3MCMFNV.js.map} +0 -0
  461. /package/dist/{chunk-DABSYX7V.js.map → chunk-D3DJYGU2.js.map} +0 -0
  462. /package/dist/{chunk-F2FJTOV6.js.map → chunk-DO6R3LIE.js.map} +0 -0
  463. /package/dist/{chunk-LD22AAJI.js.map → chunk-DSHSQGSN.js.map} +0 -0
  464. /package/dist/{chunk-3254BYQV.js.map → chunk-E5VOKZQV.js.map} +0 -0
  465. /package/dist/{chunk-46FVFU7S.js.map → chunk-EC5SVM6H.js.map} +0 -0
  466. /package/dist/{chunk-BPXJINHW.js.map → chunk-EUP4AXIW.js.map} +0 -0
  467. /package/dist/{chunk-KY75VZKG.js.map → chunk-F6AYWLRN.js.map} +0 -0
  468. /package/dist/{chunk-4AX5OYKC.js.map → chunk-FDDCZDBI.js.map} +0 -0
  469. /package/dist/{chunk-VHANUT45.js.map → chunk-HBGSZ62Z.js.map} +0 -0
  470. /package/dist/{chunk-M7H56FOQ.js.map → chunk-HVGCQMTQ.js.map} +0 -0
  471. /package/dist/{chunk-GMU7MAHS.js.map → chunk-IAT5WFEU.js.map} +0 -0
  472. /package/dist/{chunk-R3H2AXO2.js.map → chunk-IFULZYYQ.js.map} +0 -0
  473. /package/dist/{chunk-ZYSOT6HD.js.map → chunk-J3IWHCMF.js.map} +0 -0
  474. /package/dist/{chunk-QCTXQ2HW.js.map → chunk-J6NEOCQC.js.map} +0 -0
  475. /package/dist/{chunk-H2N6SLTR.js.map → chunk-JIWZVOQM.js.map} +0 -0
  476. /package/dist/{chunk-LUAQHDUI.js.map → chunk-JMBTNVMW.js.map} +0 -0
  477. /package/dist/{chunk-HKQAI6XI.js.map → chunk-JPNUKKSL.js.map} +0 -0
  478. /package/dist/{chunk-F6PTJLEM.js.map → chunk-K4KE5MYE.js.map} +0 -0
  479. /package/dist/{chunk-5AJZ7EUW.js.map → chunk-K75H7FSO.js.map} +0 -0
  480. /package/dist/{chunk-7F47R4H4.js.map → chunk-LZAJONO5.js.map} +0 -0
  481. /package/dist/{chunk-2WFOVXVJ.js.map → chunk-M7ECD3KN.js.map} +0 -0
  482. /package/dist/{chunk-KORQWGUA.js.map → chunk-MDYZCPNQ.js.map} +0 -0
  483. /package/dist/{chunk-IWHNT35B.js.map → chunk-N6I257OM.js.map} +0 -0
  484. /package/dist/{chunk-YR5QT4SR.js.map → chunk-NAFPHFDM.js.map} +0 -0
  485. /package/dist/{chunk-D7UUB33A.js.map → chunk-NGAFYIHQ.js.map} +0 -0
  486. /package/dist/{chunk-LXMZM7LM.js.map → chunk-NKDQXDFL.js.map} +0 -0
  487. /package/dist/{chunk-ZBSP4BSN.js.map → chunk-NRFUYVW7.js.map} +0 -0
  488. /package/dist/{chunk-XOCGC3FJ.js.map → chunk-OFBJD3V5.js.map} +0 -0
  489. /package/dist/{chunk-YPB3Y57U.js.map → chunk-OOBUWMPY.js.map} +0 -0
  490. /package/dist/{chunk-324HBGS4.js.map → chunk-OREGA7GY.js.map} +0 -0
  491. /package/dist/{chunk-4WMGRLTV.js.map → chunk-Q4MI2KCG.js.map} +0 -0
  492. /package/dist/{chunk-MOL7JK4F.js.map → chunk-R4HFCATE.js.map} +0 -0
  493. /package/dist/{chunk-AKB44K3D.js.map → chunk-SPN5YFXN.js.map} +0 -0
  494. /package/dist/{chunk-2PIC6CEN.js.map → chunk-T2ZNUWUY.js.map} +0 -0
  495. /package/dist/{chunk-NHFXGNGC.js.map → chunk-TFS5FAAC.js.map} +0 -0
  496. /package/dist/{chunk-JDOBQPJY.js.map → chunk-TNQR7N52.js.map} +0 -0
  497. /package/dist/{chunk-JWBDHA4F.js.map → chunk-UJXNBZYJ.js.map} +0 -0
  498. /package/dist/{chunk-DDGQDNQW.js.map → chunk-VA5QRTZX.js.map} +0 -0
  499. /package/dist/{chunk-XIJHRQ4A.js.map → chunk-W6YDAIVB.js.map} +0 -0
  500. /package/dist/{chunk-GKKLI23D.js.map → chunk-WCQ7L54B.js.map} +0 -0
  501. /package/dist/{chunk-3YQ7VLP3.js.map → chunk-WMTYEQO5.js.map} +0 -0
  502. /package/dist/{chunk-VKDXYEA6.js.map → chunk-WNMVUWI7.js.map} +0 -0
  503. /package/dist/{chunk-OGAKUA7I.js.map → chunk-YHSEUZV5.js.map} +0 -0
  504. /package/dist/{chunk-GR76OKET.js.map → chunk-YSBYNCCN.js.map} +0 -0
  505. /package/dist/{chunk-QUBPZQED.js.map → chunk-Z5YNVWRD.js.map} +0 -0
  506. /package/dist/{chunk-UCLWIMVW.js.map → chunk-ZLVURGAJ.js.map} +0 -0
  507. /package/dist/{chunk-M6FKXOYV.js.map → chunk-ZQ533JDE.js.map} +0 -0
  508. /package/dist/{chunk-TRTLWUDD.js.map → chunk-ZTHGFTMW.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/access-schema.ts"],"sourcesContent":["// Request/response schema validation for the Remnic HTTP API.\n// Uses zod for runtime validation — returns structured 400 errors with\n// field-level detail so consumers get clear feedback on malformed requests.\n\nimport { z } from \"zod\";\n\nimport type { MemoryCategory } from \"./types.js\";\nimport {\n ACTION_CONFIDENCE_CONTEXT_READINESS,\n ACTION_CONFIDENCE_RISK_CATEGORIES,\n ACTION_CONFIDENCE_RULE_KINDS,\n} from \"./action-confidence.js\";\nimport { isValidCapsuleSince } from \"./transfer/capsule-export.js\";\nimport { validateArchiveRelativePath } from \"./transfer/fs-utils.js\";\nimport { CAPSULE_ID_PATTERN } from \"./transfer/types.js\";\nimport {\n OFFLINE_SYNC_FILE_CONTENT_MAX_CHUNK_BYTES,\n OFFLINE_SYNC_MAX_MTIME_MS,\n} from \"./offline-sync.js\";\n\n// ---------------------------------------------------------------------------\n// Error formatting\n// ---------------------------------------------------------------------------\n\nexport interface SchemaValidationError {\n error: string;\n code: \"validation_error\";\n details: Array<{ field: string; message: string }>;\n}\n\nexport function formatZodError(error: z.ZodError): SchemaValidationError {\n return {\n error: \"request validation failed\",\n code: \"validation_error\",\n details: error.issues.map((issue) => ({\n field: issue.path.join(\".\") || \"(root)\",\n message: issue.message,\n })),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Shared fields\n// ---------------------------------------------------------------------------\n\nconst namespaceSchema = z.string().trim().max(256).optional();\nconst sessionKeySchema = z.string().trim().min(1).max(512).optional();\nconst idempotencyKeySchema = z.string().trim().min(1).max(256).optional();\nconst cwdSchema = z.string().trim().min(1, \"cwd must be non-empty when provided\").max(2048).optional();\nconst projectTagSchema = z\n .string()\n .trim()\n .min(1, \"projectTag must be non-empty when provided\")\n .max(256)\n .optional();\nconst deadlineMsSchema = z.number().finite().min(0).max(Number.MAX_SAFE_INTEGER).optional();\nconst dryRunSchema = z.boolean().optional();\nconst schemaVersionSchema = z.number().int().optional();\nconst timeZoneSchema = z\n .string()\n .trim()\n .min(1)\n .max(128)\n .refine((value) => {\n try {\n Intl.DateTimeFormat(undefined, { timeZone: value });\n return true;\n } catch {\n return false;\n }\n }, \"must be a valid IANA timezone\");\n\n// ---------------------------------------------------------------------------\n// Recall\n// ---------------------------------------------------------------------------\n\n/**\n * Coding-agent context (issue #569). Optional payload that connectors may\n * ship with a recall request so the project/branch namespace overlay\n * applies to that recall. All fields are validated per CLAUDE.md #51 —\n * empty-string projectId / rootPath is rejected, not silently accepted.\n */\nexport const codingContextSchema = z\n .object({\n projectId: z.string().trim().min(1, \"codingContext.projectId is required\").max(128),\n branch: z.string().trim().max(256).nullable(),\n rootPath: z.string().trim().min(1, \"codingContext.rootPath is required\").max(1024),\n defaultBranch: z.string().trim().max(256).nullable(),\n })\n .nullable();\n\n/**\n * Recall disclosure depth (issue #677). Mirrors the `RecallDisclosure`\n * type in `types.ts` — keep these in sync. Default-application happens\n * inside `EngramAccessService.recall()`; the schema only accepts/rejects.\n * Invalid values throw a structured 400 instead of silently defaulting,\n * per CLAUDE.md rule 51.\n */\nexport const recallDisclosureSchema = z.enum([\"chunk\", \"section\", \"raw\"]);\n\n/**\n * Tag-match semantics (issue #689). `any` (default when `tags` is provided\n * and `tagMatch` is omitted) admits a result when it carries at least one\n * of the filter tags. `all` requires every filter tag to be present.\n * Schema rejects unknown values up front — never silently defaults\n * (CLAUDE.md rule 51).\n */\nexport const tagMatchSchema = z.enum([\"any\", \"all\"]);\n\nexport const recallRequestSchema = z.object({\n query: z.string().min(1, \"query is required\"),\n sessionKey: sessionKeySchema,\n namespace: namespaceSchema,\n topK: z.number().int().min(0).max(200).optional(),\n mode: z.enum([\"auto\", \"no_recall\", \"minimal\", \"full\", \"graph_mode\"]).optional(),\n includeDebug: z.boolean().optional(),\n idempotencyKey: idempotencyKeySchema,\n disclosure: recallDisclosureSchema.optional(),\n codingContext: codingContextSchema.optional(),\n /** Working directory for auto git-context resolution (issue #569). */\n cwd: cwdSchema,\n /**\n * Arbitrary project tag for non-git-based project scoping (issue #569).\n * Creates a coding context with `projectId: \"tag:<projectTag>\"`.\n */\n projectTag: projectTagSchema,\n /**\n * Historical recall pin (issue #680). ISO 8601 timestamp. The\n * schema only enforces the basic shape; the access service runs\n * `Date.parse` and emits a structured 400 on malformed input\n * (CLAUDE.md rule 51).\n */\n asOf: z.string().trim().min(1, \"asOf must be a non-empty ISO 8601 timestamp\").max(64).optional(),\n /**\n * Free-form recall tag filter (issue #689). When provided, recall results\n * whose frontmatter `tags` do not match the filter are removed before the\n * response is returned. Comparison is case-sensitive exact match.\n */\n tags: z.array(z.string().trim().min(1).max(256)).max(50).optional(),\n /**\n * Match mode for `tags` (issue #689). Defaults to `\"any\"` when `tags` is\n * provided and `tagMatch` is omitted. Ignored when `tags` is absent.\n */\n tagMatch: tagMatchSchema.optional(),\n /**\n * Include graph edges below `graphTraversalConfidenceFloor` for diagnostic\n * recall traversal (issue #681). Defaults to false.\n */\n includeLowConfidence: z.boolean().optional(),\n /**\n * #1952 — per-call opt-in to state-aware recall views for this recall.\n * ORs with the `recallStateViews` config flag; a change-intent query\n * (e.g. \"when did\", \"used to\", \"switched\") is still required for any\n * effect, so this can never perturb ordinary recalls.\n */\n stateView: z.boolean().optional(),\n});\n\nexport const recallExplainRequestSchema = z.object({\n sessionKey: sessionKeySchema,\n namespace: namespaceSchema,\n});\n\n/**\n * Standalone \"set coding context\" request. Used by the HTTP endpoint\n * `POST /engram/v1/coding-context` and the MCP `remnic.set_coding_context`\n * tool (PR 7). `codingContext: null` clears the attached context.\n */\nexport const setCodingContextRequestSchema = z\n .object({\n sessionKey: z.string().trim().min(1, \"sessionKey is required\").max(512),\n codingContext: codingContextSchema.optional(),\n /**\n * Project tag shorthand for non-git-based project scoping. When\n * `codingContext` is omitted, this becomes\n * `{ projectId: \"tag:<projectTag>\", branch: null, rootPath: \"tag:<projectTag>\", defaultBranch: null }`.\n */\n projectTag: z.string().trim().min(1, \"projectTag must be non-empty when provided\").max(256).optional(),\n })\n .superRefine((value, ctx) => {\n if (value.codingContext === undefined && value.projectTag === undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"codingContext or projectTag is required\",\n path: [\"codingContext\"],\n });\n }\n });\n\n// ---------------------------------------------------------------------------\n// Observe\n// ---------------------------------------------------------------------------\n\nconst messageSchema = z.object({\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string().min(1, \"message content must be non-empty\"),\n sourceFormat: z\n .enum([\"openai\", \"anthropic\", \"openclaw\", \"pi\", \"lossless-claw\", \"remnic\"])\n .nullable()\n .optional(),\n rawContent: z.unknown().nullable().optional(),\n parts: z\n .array(\n z.object({\n ordinal: z.number().int().min(0).nullable().optional(),\n kind: z.enum([\n \"text\",\n \"tool_call\",\n \"tool_result\",\n \"patch\",\n \"file_read\",\n \"file_write\",\n \"step_start\",\n \"step_finish\",\n \"snapshot\",\n \"retry\",\n ]),\n payload: z.record(z.string(), z.unknown()),\n toolName: z.string().nullable().optional(),\n tool_name: z.string().nullable().optional(),\n filePath: z.string().nullable().optional(),\n file_path: z.string().nullable().optional(),\n createdAt: z.string().nullable().optional(),\n created_at: z.string().nullable().optional(),\n }),\n )\n .nullable()\n .optional(),\n});\n\nexport const observeRequestSchema = z.object({\n sessionKey: z.string().trim().min(1, \"sessionKey is required\").max(512),\n messages: z.array(messageSchema).min(1, \"messages must be a non-empty array\"),\n namespace: namespaceSchema,\n skipExtraction: z.boolean().optional(),\n /**\n * Optional idempotency key for server-side dedup of retried observe POSTs\n * (issue #1649). A retry that reaches the daemon after the first attempt\n * already processed is replayed from cache instead of re-ingested. When the\n * key is reused with a DIFFERENT payload the request is rejected as a\n * conflict (same contract as memory_store/suggestion_submit).\n */\n idempotencyKey: idempotencyKeySchema,\n /** Working directory for auto git-context resolution (issue #569). */\n cwd: cwdSchema,\n /**\n * Arbitrary project tag for non-git-based project scoping (issue #569).\n * Creates a coding context with `projectId: \"tag:<projectTag>\"`.\n */\n projectTag: projectTagSchema,\n});\n\n// ---------------------------------------------------------------------------\n// Deep recall (issue #2332)\n// ---------------------------------------------------------------------------\n\nexport const deepRecallRequestSchema = z.object({\n query: z.string().trim().min(1, \"query is required\").max(2000),\n /** Optional policy-step ceiling; validated against the configured maximum in the service. */\n maxSteps: z.union([z.number().int().min(0), z.string()]).optional(),\n namespace: namespaceSchema,\n sessionKey: z.string().optional(),\n});\n\n// ---------------------------------------------------------------------------\n// Memory store / suggestion submit\n// ---------------------------------------------------------------------------\n\nconst writeContentSchema = z.string().min(1, \"content is required\").max(50000);\n// ---------------------------------------------------------------------------\n// Category wire contract (issue #2829): truthful input/output modeling.\n// ---------------------------------------------------------------------------\n\n/** Canonical input spellings — exactly the `MemoryCategory` union. */\nconst MEMORY_CATEGORY_CANONICAL_INPUT = [\n \"fact\", \"preference\", \"correction\", \"entity\", \"decision\",\n \"relationship\", \"principle\", \"commitment\", \"moment\", \"skill\", \"rule\", \"procedure\",\n \"reasoning_trace\",\n] as const satisfies readonly MemoryCategory[];\n\n/**\n * Compatibility alias spellings admitted on input. The four project-shaped\n * categories fleet telemetry actually shows do not exist in the taxonomy;\n * they parse to the canonical \"fact\". Exact match only — no trimming, no\n * case folding, so near-misses like `projection` or `Project_State` reject\n * like any other invalid category, with the full valid list in the error.\n */\nconst MEMORY_CATEGORY_ALIAS_INPUT = [\n \"project\",\n \"project_state\",\n \"project-state\",\n \"project_update\",\n] as const;\n\nexport type MemoryCategoryAlias = (typeof MEMORY_CATEGORY_ALIAS_INPUT)[number];\n\nconst MEMORY_CATEGORY_ALIAS_TO_CANONICAL: Readonly<\n Record<MemoryCategoryAlias, Extract<MemoryCategory, \"fact\">>\n> = {\n project: \"fact\",\n project_state: \"fact\",\n \"project-state\": \"fact\",\n project_update: \"fact\",\n};\n\nexport function isMemoryCategoryAlias(value: string): value is MemoryCategoryAlias {\n return Object.prototype.hasOwnProperty.call(MEMORY_CATEGORY_ALIAS_TO_CANONICAL, value);\n}\n\n/**\n * Canonical category for an accepted alias spelling; undefined for anything\n * else (canonical spellings and near-misses map to nothing). Service-boundary\n * consumers that receive `category` without a prior wire parse use this to\n * match the transport contract (#2962).\n */\nexport function canonicalCategoryForAlias(value: string): \"fact\" | undefined {\n return isMemoryCategoryAlias(value) ? MEMORY_CATEGORY_ALIAS_TO_CANONICAL[value] : undefined;\n}\n\n/** Coercion diagnostic for a write whose input category was a compat alias. */\nexport interface CategoryAliasCoercion {\n from: MemoryCategoryAlias;\n to: \"fact\";\n}\n\n/** Boundary-derived coercion note for a retained raw spelling. */\nexport function categoryAliasCoercion(rawCategory: string | undefined): CategoryAliasCoercion | undefined {\n return rawCategory !== undefined && isMemoryCategoryAlias(rawCategory)\n ? { from: rawCategory, to: \"fact\" }\n : undefined;\n}\n\n/**\n * Recover the retained alias spelling from a pre-parse raw envelope: the\n * `rawCategory` minted by a previous parse of the same schema (the HTTP/MCP\n * validate-then-dispatch double pass), or — for single-parse callers like the\n * CLI store command — the as-yet-untransformed alias still sitting on\n * `category` (issue #2889). A minted `rawCategory` always wins: it names the\n * spelling the transform actually canonicalized.\n */\nexport function retainedCategoryAlias(rawInput: unknown): MemoryCategoryAlias | undefined {\n if (!rawInput || typeof rawInput !== \"object\") return undefined;\n const envelope = rawInput as Record<string, unknown>;\n const minted = envelope.rawCategory;\n if (typeof minted === \"string\" && isMemoryCategoryAlias(minted)) return minted;\n const category = envelope.category;\n return typeof category === \"string\" && isMemoryCategoryAlias(category) ? category : undefined;\n}\n\n/**\n * An idempotent replay returns the FIRST request's stored response, whose\n * coercion note names that request's spelling. Rewrite the note from the\n * CURRENT request's retained spelling so every response identifies what its\n * caller actually sent; the stored idempotent result is reused untouched.\n */\nexport function reapplyCategoryCoercion<T extends object>(\n response: T,\n categoryCoercion: CategoryAliasCoercion | undefined,\n): T & { categoryCoercion?: CategoryAliasCoercion } {\n const restamped: T & { categoryCoercion?: CategoryAliasCoercion } = { ...response };\n if (categoryCoercion !== undefined) {\n restamped.categoryCoercion = categoryCoercion;\n } else {\n delete restamped.categoryCoercion;\n }\n return restamped;\n}\n\nconst categoryWireSchema = z.enum(\n [...MEMORY_CATEGORY_CANONICAL_INPUT, ...MEMORY_CATEGORY_ALIAS_INPUT],\n {\n errorMap: () => ({\n message:\n `category must be one of: ${[...MEMORY_CATEGORY_CANONICAL_INPUT, ...MEMORY_CATEGORY_ALIAS_INPUT].join(\", \")}; ` +\n 'for project state/facts use \"fact\"',\n }),\n },\n);\n\nconst confidenceSchema = z.number().min(0).max(1).optional();\nconst tagsSchema = z.array(z.string().max(256)).max(50).optional();\nconst entityRefSchema = z.string().trim().max(512).optional();\nconst ttlSchema = z.string().trim().max(128).optional();\nconst sourceReasonSchema = z.string().trim().max(2000).optional();\n\nconst memoryStoreRequestShape = z.object({\n schemaVersion: schemaVersionSchema,\n idempotencyKey: idempotencyKeySchema,\n dryRun: dryRunSchema,\n sessionKey: sessionKeySchema,\n content: writeContentSchema,\n category: categoryWireSchema.optional(),\n confidence: confidenceSchema,\n namespace: namespaceSchema,\n tags: tagsSchema,\n entityRef: entityRefSchema,\n ttl: ttlSchema,\n sourceReason: sourceReasonSchema,\n // Git/project context for project-scoped writes (#1434). When no explicit\n // `namespace` is given, these route the write to the same project namespace\n // recall/observe resolve from `cwd`/`projectTag` (issue #569, rule 42). Also\n // lets MCP clients that auto-inject `cwd` (e.g. Pi MCPorter) call write tools.\n cwd: cwdSchema,\n projectTag: projectTagSchema,\n});\n\n/**\n * Parsed memory-store request (issue #2829): the category transform maps\n * compat aliases to the canonical \"fact\" DURING parsing, so the output type\n * stays the finite `MemoryCategory` union — never an alias spelling. The raw\n * spelling travels separately on `rawCategory`, minted only by the transform\n * (zod strips it from client bodies), for the write surface's coercion note\n * and idempotent-replay rebuild.\n */\nexport type MemoryStoreParsedRequest = Omit<z.infer<typeof memoryStoreRequestShape>, \"category\"> & {\n category?: MemoryCategory;\n rawCategory?: MemoryCategoryAlias;\n};\n\nexport const memoryStoreRequestSchema = memoryStoreRequestShape.transform(\n (request): MemoryStoreParsedRequest => {\n if (request.category === undefined || !isMemoryCategoryAlias(request.category)) {\n // Spread so the narrowed canonical category, not the wide wire union,\n // becomes the output type.\n return { ...request, category: request.category };\n }\n return {\n ...request,\n category: MEMORY_CATEGORY_ALIAS_TO_CANONICAL[request.category],\n rawCategory: request.category,\n };\n },\n);\n\nexport const suggestionSubmitRequestSchema = memoryStoreRequestSchema;\n\n// ---------------------------------------------------------------------------\n// Review disposition\n// ---------------------------------------------------------------------------\n\nexport const reviewDispositionRequestSchema = z.object({\n memoryId: z.string().trim().min(1, \"memoryId is required\"),\n status: z.enum([\n \"active\", \"pending_review\", \"quarantined\", \"rejected\", \"superseded\", \"archived\",\n ]),\n reasonCode: z.string().trim().min(1, \"reasonCode is required\"),\n namespace: namespaceSchema,\n});\n\n// ---------------------------------------------------------------------------\n// Trust-zone promote\n// ---------------------------------------------------------------------------\n\nexport const trustZonePromoteRequestSchema = z.object({\n recordId: z.string().trim().min(1, \"recordId is required\"),\n targetZone: z.enum([\"working\", \"trusted\"], {\n errorMap: () => ({ message: \"targetZone must be 'working' or 'trusted'\" }),\n }),\n promotionReason: z.string().trim().min(1, \"promotionReason is required\"),\n recordedAt: z.string().trim().optional(),\n summary: z.string().trim().max(5000).optional(),\n dryRun: dryRunSchema,\n namespace: namespaceSchema,\n});\n\n// ---------------------------------------------------------------------------\n// Trust-zone demo-seed\n// ---------------------------------------------------------------------------\n\nexport const trustZoneDemoSeedRequestSchema = z.object({\n scenario: z.string().trim().max(256).optional(),\n recordedAt: z.string().trim().optional(),\n dryRun: dryRunSchema,\n namespace: namespaceSchema,\n});\n\n// ---------------------------------------------------------------------------\n// LCM search\n// ---------------------------------------------------------------------------\n\nexport const lcmSearchRequestSchema = z.object({\n query: z.string().min(1, \"query is required\"),\n sessionKey: sessionKeySchema,\n sessionPrefix: z.string().trim().min(1).max(512).optional(),\n namespace: namespaceSchema,\n limit: z.number().int().min(1).max(100).optional(),\n});\n\nexport const lcmCompactionFlushRequestSchema = z\n .object({\n sessionKey: z.string().trim().min(1, \"sessionKey is required\").max(512),\n namespace: namespaceSchema,\n cwd: cwdSchema,\n projectTag: projectTagSchema,\n /**\n * Optional multi-namespace flush used by delegate lifecycle replay. The\n * server handles the whole list as one quota-counted write.\n */\n namespaces: z.array(z.string().trim().max(256)).min(1).max(64).optional(),\n })\n .superRefine((value, ctx) => {\n if (value.namespace !== undefined && value.namespaces !== undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"namespace and namespaces are mutually exclusive\",\n path: [\"namespaces\"],\n });\n }\n if (\n value.namespaces !== undefined &&\n new Set(value.namespaces).size !== value.namespaces.length\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"namespaces must not contain duplicates\",\n path: [\"namespaces\"],\n });\n }\n });\n\nexport const extractionForceFlushRequestSchema = z.object({\n sessionKey: z.string().trim().min(1, \"sessionKey is required\").max(512),\n namespace: namespaceSchema,\n cwd: cwdSchema,\n projectTag: projectTagSchema,\n deadlineMs: deadlineMsSchema,\n});\n\nexport const lcmCompactionRecordRequestSchema = z.object({\n sessionKey: z.string().trim().min(1, \"sessionKey is required\").max(512),\n namespace: namespaceSchema,\n tokensBefore: z.number().int().min(0, \"tokensBefore must be a non-negative integer\"),\n tokensAfter: z.number().int().min(0, \"tokensAfter must be a non-negative integer\"),\n});\n\n// ---------------------------------------------------------------------------\n// Day summary\n// ---------------------------------------------------------------------------\n\nexport const daySummaryRequestSchema = z.object({\n memories: z.string().max(100000).optional(),\n includeLocation: z.boolean().optional(),\n sessionKey: sessionKeySchema,\n namespace: namespaceSchema,\n timeZone: timeZoneSchema.optional(),\n});\n\n// ---------------------------------------------------------------------------\n// Capsule export\n// ---------------------------------------------------------------------------\n\nconst capsuleTopLevelSegmentSchema = z\n .string()\n .trim()\n .min(1)\n .max(128)\n .refine(\n (value) => !value.includes(\"/\") && !value.includes(\"\\\\\"),\n \"must be a top-level directory name without path separators\",\n );\n\nconst capsulePeerIdSchema = z\n .string()\n .trim()\n .min(1)\n .max(256)\n .refine(\n (value) => value !== \".\" && value !== \"..\" && !value.includes(\"/\") && !value.includes(\"\\\\\"),\n \"must be a plain peer id without path separators\",\n );\n\nconst capsuleIsoSinceSchema = z\n .string()\n .trim()\n .min(1, \"since must be a non-empty ISO 8601 timestamp\")\n .max(128)\n .refine(\n isValidCapsuleSince,\n \"since must be a valid ISO 8601 timestamp with no calendar overflow\",\n );\n\nexport const capsuleExportRequestSchema = z\n .object({\n name: z\n .string()\n .trim()\n .min(1, \"name is required\")\n .max(64, \"name must be 64 characters or fewer\")\n .regex(\n CAPSULE_ID_PATTERN,\n \"name must be alphanumeric with single dashes (no spaces, no leading/trailing dashes)\",\n ),\n namespace: namespaceSchema,\n since: capsuleIsoSinceSchema.optional(),\n includeKinds: z.array(capsuleTopLevelSegmentSchema).max(50).optional(),\n peerIds: z.array(capsulePeerIdSchema).max(100).optional(),\n includeTranscripts: z.boolean().optional(),\n encrypt: z.boolean().optional(),\n });\n\nexport const capsuleImportRequestSchema = z\n .object({\n archivePath: z.string().trim().min(1, \"archivePath is required\").max(4096),\n namespace: namespaceSchema,\n mode: z.enum([\"skip\", \"overwrite\", \"fork\"]).optional(),\n passphrase: z.string().min(1, \"passphrase must not be empty\").max(4096).optional(),\n });\n\nexport const capsuleListRequestSchema = z\n .object({\n namespace: namespaceSchema,\n sessionKey: sessionKeySchema,\n });\n\n// ---------------------------------------------------------------------------\n// Offline sync\n// ---------------------------------------------------------------------------\n\nfunction isValidOfflineSyncPath(value: string): boolean {\n try {\n validateArchiveRelativePath(value, \"path\");\n return true;\n } catch {\n return false;\n }\n}\n\nconst offlineSyncPathSchema = z\n .string()\n .trim()\n .min(1, \"path must be non-empty\")\n .max(4096)\n .refine(\n isValidOfflineSyncPath,\n \"path must be a POSIX relative path without unsafe segments\",\n );\n\nconst offlineSyncFileStateSchema = z.object({\n path: offlineSyncPathSchema,\n sha256: z.string().regex(/^[a-f0-9]{64}$/i, \"sha256 must be a 64-character hex digest\"),\n bytes: z.number().int().min(0),\n mtimeMs: z.number().finite().min(0).max(OFFLINE_SYNC_MAX_MTIME_MS),\n});\n\nconst offlineSyncBaseCapturedAtSchema = z\n .string()\n .trim()\n .min(1, \"baseCapturedAt must be non-empty when provided\")\n .max(64)\n .refine((value) => Number.isFinite(Date.parse(value)), {\n message: \"baseCapturedAt must be a valid ISO 8601 timestamp\",\n });\n\nexport const offlineSyncSnapshotRequestSchema = z.object({\n namespace: namespaceSchema,\n includeTranscripts: z.boolean().optional(),\n includeContent: z.boolean().optional(),\n baseCapturedAt: offlineSyncBaseCapturedAtSchema.optional(),\n baseFiles: z\n .array(offlineSyncFileStateSchema)\n .max(300_000, \"baseFiles must contain 300000 or fewer entries\")\n .optional(),\n});\n\nexport const offlineSyncApplyRequestSchema = z\n .object({\n namespace: namespaceSchema,\n changeset: z.unknown(),\n returnCurrentFiles: z.boolean().optional(),\n })\n .refine((value) => value.changeset !== undefined && value.changeset !== null, {\n message: \"changeset is required\",\n path: [\"changeset\"],\n });\n\nexport const offlineSyncFilesRequestSchema = z.object({\n namespace: namespaceSchema,\n includeTranscripts: z.boolean().optional(),\n paths: z\n .array(offlineSyncPathSchema)\n .max(5000, \"paths must contain 5000 or fewer entries\"),\n});\n\nexport const offlineSyncFileContentRequestSchema = z.object({\n namespace: namespaceSchema,\n includeTranscripts: z.boolean().optional(),\n path: offlineSyncPathSchema,\n offset: z.number().int().min(0).optional(),\n length: z.number().int().min(1).max(OFFLINE_SYNC_FILE_CONTENT_MAX_CHUNK_BYTES).optional(),\n});\n\n// ---------------------------------------------------------------------------\n// Action confidence\n// ---------------------------------------------------------------------------\n\nconst nullableOptional = <T extends z.ZodTypeAny>(schema: T) =>\n schema.optional().nullable().transform((value) => value ?? undefined);\n\nconst actionConfidenceRuleSchema = z\n .object({\n kind: z.enum(ACTION_CONFIDENCE_RULE_KINDS),\n description: nullableOptional(z.string().trim().min(1).max(2000)),\n matched: nullableOptional(z.boolean()),\n })\n .strict();\n\nconst actionConfidenceMemorySchema = z\n .object({\n source: nullableOptional(z.string().trim().min(1).max(256)),\n created: nullableOptional(z.string().trim().min(1).max(128)),\n updated: nullableOptional(z.string().trim().min(1).max(128)),\n scope: nullableOptional(z.string().trim().min(1).max(512)),\n userContextScopes: nullableOptional(z.array(z.string().trim().min(1).max(128)).max(50)),\n retrievalReason: nullableOptional(z.string().trim().min(1).max(2000)),\n confidence: nullableOptional(z.number().min(0).max(1)),\n stale: nullableOptional(z.boolean()),\n corrected: nullableOptional(z.boolean()),\n correctionState: nullableOptional(z.enum([\"none\", \"correction\", \"superseded\", \"disputed\", \"forgotten\"])),\n safeToUse: nullableOptional(z.boolean()),\n safety: nullableOptional(z.enum([\"safe\", \"requires-review\", \"blocked\"])),\n safetyReasons: nullableOptional(z.array(z.string().trim().min(1).max(1000)).max(50)),\n })\n .strict();\n\nexport const actionConfidenceRequestSchema = z\n .object({\n intendedAction: nullableOptional(z.string().trim().min(1).max(1000)),\n confidence: nullableOptional(z.number().min(0).max(1)),\n risk: nullableOptional(z.enum(ACTION_CONFIDENCE_RISK_CATEGORIES)),\n contextReadiness: nullableOptional(z.enum(ACTION_CONFIDENCE_CONTEXT_READINESS)),\n currentContextScopes: nullableOptional(z.array(z.string().trim().min(1).max(128)).max(50)),\n userRules: nullableOptional(z.array(actionConfidenceRuleSchema).max(100)),\n retrievedMemories: nullableOptional(z.array(actionConfidenceMemorySchema).max(200)),\n })\n .strict();\n\n// ---------------------------------------------------------------------------\n// Inferred types\n// ---------------------------------------------------------------------------\n\nexport type RecallRequest = z.infer<typeof recallRequestSchema>;\nexport type RecallExplainRequest = z.infer<typeof recallExplainRequestSchema>;\nexport type SetCodingContextRequest = z.infer<typeof setCodingContextRequestSchema>;\nexport type ObserveRequest = z.infer<typeof observeRequestSchema>;\nexport type MemoryStoreRequest = z.infer<typeof memoryStoreRequestSchema>;\nexport type SuggestionSubmitRequest = z.infer<typeof suggestionSubmitRequestSchema>;\nexport type ReviewDispositionRequest = z.infer<typeof reviewDispositionRequestSchema>;\nexport type TrustZonePromoteRequest = z.infer<typeof trustZonePromoteRequestSchema>;\nexport type TrustZoneDemoSeedRequest = z.infer<typeof trustZoneDemoSeedRequestSchema>;\nexport type LcmSearchRequest = z.infer<typeof lcmSearchRequestSchema>;\nexport type LcmCompactionFlushRequest = z.infer<typeof lcmCompactionFlushRequestSchema>;\nexport type ExtractionForceFlushRequest = z.infer<typeof extractionForceFlushRequestSchema>;\nexport type LcmCompactionRecordRequest = z.infer<typeof lcmCompactionRecordRequestSchema>;\nexport type DaySummaryRequest = z.infer<typeof daySummaryRequestSchema>;\nexport type CapsuleExportRequest = z.infer<typeof capsuleExportRequestSchema>;\nexport type CapsuleImportRequest = z.infer<typeof capsuleImportRequestSchema>;\nexport type CapsuleListRequest = z.infer<typeof capsuleListRequestSchema>;\nexport type OfflineSyncApplyRequest = z.infer<typeof offlineSyncApplyRequestSchema>;\nexport type OfflineSyncSnapshotRequest = z.infer<typeof offlineSyncSnapshotRequestSchema>;\nexport type OfflineSyncFilesRequest = z.infer<typeof offlineSyncFilesRequestSchema>;\nexport type OfflineSyncFileContentRequest = z.infer<typeof offlineSyncFileContentRequestSchema>;\nexport type ActionConfidenceRequest = z.infer<typeof actionConfidenceRequestSchema>;\n\n// ---------------------------------------------------------------------------\n// Validation helper\n// ---------------------------------------------------------------------------\n\nexport type SchemaName =\n | \"recall\"\n | \"recallExplain\"\n | \"setCodingContext\"\n | \"observe\"\n | \"memoryStore\"\n | \"suggestionSubmit\"\n | \"reviewDisposition\"\n | \"trustZonePromote\"\n | \"trustZoneDemoSeed\"\n | \"lcmSearch\"\n | \"lcmCompactionFlush\"\n | \"extractionForceFlush\"\n | \"lcmCompactionRecord\"\n | \"daySummary\"\n | \"capsuleExport\"\n | \"capsuleImport\"\n | \"capsuleList\"\n | \"offlineSyncSnapshot\"\n | \"offlineSyncFiles\"\n | \"offlineSyncFileContent\"\n | \"offlineSyncApply\"\n | \"actionConfidence\";\n\nexport type SchemaTypeFor<N extends SchemaName> =\n N extends \"recall\" ? RecallRequest\n : N extends \"recallExplain\" ? RecallExplainRequest\n : N extends \"setCodingContext\" ? SetCodingContextRequest\n : N extends \"observe\" ? ObserveRequest\n : N extends \"memoryStore\" ? MemoryStoreRequest\n : N extends \"suggestionSubmit\" ? SuggestionSubmitRequest\n : N extends \"reviewDisposition\" ? ReviewDispositionRequest\n : N extends \"trustZonePromote\" ? TrustZonePromoteRequest\n : N extends \"trustZoneDemoSeed\" ? TrustZoneDemoSeedRequest\n : N extends \"lcmSearch\" ? LcmSearchRequest\n : N extends \"lcmCompactionFlush\" ? LcmCompactionFlushRequest\n : N extends \"extractionForceFlush\" ? ExtractionForceFlushRequest\n : N extends \"lcmCompactionRecord\" ? LcmCompactionRecordRequest\n : N extends \"daySummary\" ? DaySummaryRequest\n : N extends \"capsuleExport\" ? CapsuleExportRequest\n : N extends \"capsuleImport\" ? CapsuleImportRequest\n : N extends \"capsuleList\" ? CapsuleListRequest\n : N extends \"offlineSyncSnapshot\" ? OfflineSyncSnapshotRequest\n : N extends \"offlineSyncFiles\" ? OfflineSyncFilesRequest\n : N extends \"offlineSyncFileContent\" ? OfflineSyncFileContentRequest\n : N extends \"offlineSyncApply\" ? OfflineSyncApplyRequest\n : N extends \"actionConfidence\" ? ActionConfidenceRequest\n : never;\n\nconst schemas: Record<SchemaName, z.ZodTypeAny> = {\n recall: recallRequestSchema,\n recallExplain: recallExplainRequestSchema,\n setCodingContext: setCodingContextRequestSchema,\n observe: observeRequestSchema,\n memoryStore: memoryStoreRequestSchema,\n suggestionSubmit: suggestionSubmitRequestSchema,\n reviewDisposition: reviewDispositionRequestSchema,\n trustZonePromote: trustZonePromoteRequestSchema,\n trustZoneDemoSeed: trustZoneDemoSeedRequestSchema,\n lcmSearch: lcmSearchRequestSchema,\n lcmCompactionFlush: lcmCompactionFlushRequestSchema,\n extractionForceFlush: extractionForceFlushRequestSchema,\n lcmCompactionRecord: lcmCompactionRecordRequestSchema,\n daySummary: daySummaryRequestSchema,\n capsuleExport: capsuleExportRequestSchema,\n capsuleImport: capsuleImportRequestSchema,\n capsuleList: capsuleListRequestSchema,\n offlineSyncSnapshot: offlineSyncSnapshotRequestSchema,\n offlineSyncFiles: offlineSyncFilesRequestSchema,\n offlineSyncFileContent: offlineSyncFileContentRequestSchema,\n offlineSyncApply: offlineSyncApplyRequestSchema,\n actionConfidence: actionConfidenceRequestSchema,\n};\n\n/**\n * Validate a request body against the named schema.\n * Returns `{ success: true, data }` on pass or\n * `{ success: false, error }` on failure with field-level detail.\n */\nexport function validateRequest<T = unknown>(\n schemaName: SchemaName,\n body: unknown,\n): { success: true; data: T } | { success: false; error: SchemaValidationError } {\n const schema = schemas[schemaName];\n if (!schema) {\n return {\n success: false,\n error: {\n error: `unknown schema: ${schemaName}`,\n code: \"validation_error\",\n details: [],\n },\n };\n }\n const result = schema.safeParse(stripNullsExceptCodingContext(body));\n if (result.success) {\n return { success: true, data: result.data as T };\n }\n return { success: false, error: formatZodError(result.error) };\n}\n\nfunction stripNullsExceptCodingContext(data: unknown): unknown {\n if (!data || typeof data !== \"object\" || Array.isArray(data)) return data;\n const cleaned: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(data as Record<string, unknown>)) {\n if (value === null && key !== \"codingContext\") continue;\n cleaned[key] = value;\n }\n return cleaned;\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAIA,SAAS,SAAS;AA0BX,SAAS,eAAe,OAA0C;AACvE,SAAO;AAAA,IACL,OAAO;AAAA,IACP,MAAM;AAAA,IACN,SAAS,MAAM,OAAO,IAAI,CAAC,WAAW;AAAA,MACpC,OAAO,MAAM,KAAK,KAAK,GAAG,KAAK;AAAA,MAC/B,SAAS,MAAM;AAAA,IACjB,EAAE;AAAA,EACJ;AACF;AAMA,IAAM,kBAAkB,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,GAAG,EAAE,SAAS;AAC5D,IAA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K,KAAK,KAAK,OAAO,QAAQ,IAA+B,GAAG;AAC1E,QAAI,UAAU,QAAQ,QAAQ,gBAAiB;AAC/C,YAAQ,GAAG,IAAI;AAAA,EACjB;AACA,SAAO;AACT;","names":[]}
@@ -645,4 +645,4 @@ export {
645
645
  appendMemoryToGraphContext,
646
646
  resolvePersistedMemoryRelativePath
647
647
  };
648
- //# sourceMappingURL=chunk-F6PTJLEM.js.map
648
+ //# sourceMappingURL=chunk-K4KE5MYE.js.map
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-TBBDFYXW.js";
4
4
  import {
5
5
  StorageManager
6
- } from "./chunk-GMU7MAHS.js";
6
+ } from "./chunk-IAT5WFEU.js";
7
7
  import {
8
8
  bumpMemoryCorpusVersionForDir
9
9
  } from "./chunk-XCB6QDL6.js";
@@ -765,4 +765,4 @@ export {
765
765
  listMemoryGovernanceRuns,
766
766
  readMemoryGovernanceRunArtifact
767
767
  };
768
- //# sourceMappingURL=chunk-5AJZ7EUW.js.map
768
+ //# sourceMappingURL=chunk-K75H7FSO.js.map
@@ -155,9 +155,15 @@ function citationTemplatesToRecognize(primary, extra = []) {
155
155
  if (!citationTemplateIsDetectable(template)) return;
156
156
  if (!out.includes(template)) out.push(template);
157
157
  };
158
- add(DEFAULT_CITATION_FORMAT);
159
158
  add(primary);
160
159
  for (const template of extra) add(template);
160
+ add(DEFAULT_CITATION_FORMAT);
161
+ out.sort((a, b) => {
162
+ if (b.length !== a.length) return b.length - a.length;
163
+ if (a === primary && b !== primary) return -1;
164
+ if (b === primary && a !== primary) return 1;
165
+ return 0;
166
+ });
161
167
  return out;
162
168
  }
163
169
  function citationTemplatesForMerge(config) {
@@ -255,6 +261,12 @@ function stripCitationForTemplate(text, template) {
255
261
  if (typeof text !== "string" || text.length === 0) return text;
256
262
  const afterDefault = hasCitation(text) ? stripCitation(text) : text;
257
263
  if (!hasCitationForTemplate(afterDefault, template)) return afterDefault;
264
+ PLACEHOLDER_REGEX.lastIndex = 0;
265
+ if (!PLACEHOLDER_REGEX.test(template)) {
266
+ PLACEHOLDER_REGEX.lastIndex = 0;
267
+ return stripExactLiteralCitation(afterDefault, template);
268
+ }
269
+ PLACEHOLDER_REGEX.lastIndex = 0;
258
270
  const matcher = templateMatcher(template);
259
271
  if (!matcher) return afterDefault;
260
272
  const globalMatcher = new RegExp(
@@ -283,6 +295,25 @@ function stripCitationForTemplate(text, template) {
283
295
  }
284
296
  return result.trimEnd();
285
297
  }
298
+ function stripExactLiteralCitation(text, marker) {
299
+ if (marker.length === 0) return text;
300
+ let result = "";
301
+ let lastIndex = 0;
302
+ let idx = text.indexOf(marker);
303
+ if (idx === -1) return text;
304
+ while (idx !== -1) {
305
+ const before = text.slice(lastIndex, idx).replace(/[ \t]+$/, "");
306
+ result += before;
307
+ lastIndex = idx + marker.length;
308
+ idx = text.indexOf(marker, lastIndex);
309
+ }
310
+ const after = text.slice(lastIndex).replace(/^[ \t]+/, "");
311
+ if (after.length > 0) {
312
+ if (result.length > 0) result += " ";
313
+ result += after;
314
+ }
315
+ return result.trimEnd();
316
+ }
286
317
  function enclosingDelimiterRange(text, start, end) {
287
318
  if (start <= 0 || end >= text.length) return void 0;
288
319
  const opener = text[start - 1];
@@ -312,4 +343,4 @@ export {
312
343
  stripCitation,
313
344
  stripCitationForTemplate
314
345
  };
315
- //# sourceMappingURL=chunk-JL4TQYM5.js.map
346
+ //# sourceMappingURL=chunk-L272A5QW.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/source-attribution.ts"],"sourcesContent":["/**\n * Inline Source Attribution Protocol (issue #369)\n *\n * Extracted facts carry provenance inline inside the fact body, so the\n * citation survives hostile memory text, copy/paste, and LLM quoting. This\n * complements — never replaces — the YAML frontmatter provenance stored on\n * disk.\n *\n * Default format (matches issue #369 proposal):\n *\n * The foo service uses Redis for rate limiting. [Source: agent=planner, session=abc123, ts=2026-04-10T14:25:07Z]\n *\n * Key properties:\n * - Inline (part of the body, not metadata).\n * - Compact (typically <80 chars of overhead per fact).\n * - Machine-parseable by a single regex.\n * - Opt-in via `inlineSourceAttributionEnabled` config flag (default off\n * for backwards compatibility with existing downstream consumers).\n * - Legacy facts without a citation remain fully readable.\n *\n * The format template is configurable via `inlineSourceAttributionFormat`\n * with supported placeholders:\n *\n * {agent} — principal / agent identifier\n * {session} — full session key (colon-delimited)\n * {sessionId} — short stable session id (trailing component)\n * {ts} — extraction timestamp (ISO 8601)\n * {date} — extraction date (YYYY-MM-DD)\n *\n * Any privacy-sensitive identifiers should be normalized before being passed\n * to `formatCitation` — the helper treats them as opaque strings.\n */\n\n/** Default citation format template (matches issue #369). */\nexport const DEFAULT_CITATION_FORMAT =\n \"[Source: agent={agent}, session={sessionId}, ts={ts}]\";\n\n/** Sentinel value used when a provenance field is missing. */\nexport const CITATION_UNKNOWN = \"unknown\";\n\nexport interface CitationContext {\n /** Principal / agent identifier (e.g. resolved via resolvePrincipal). */\n agent?: string;\n /** Full session key (e.g. \"agent:planner:main\"). */\n session?: string;\n /**\n * Opaque short session id. Derived from the trailing component of the\n * session key when not provided explicitly. Use this for compact formats\n * that do not need the full colon-delimited session key.\n */\n sessionId?: string;\n /** Extraction timestamp as an ISO 8601 string. */\n ts?: string;\n}\n\nexport interface ParsedCitation {\n /** Agent identifier parsed from the citation (never crashes on malformed input). */\n agent?: string;\n /** Session identifier parsed from the citation. */\n session?: string;\n /** Extraction timestamp parsed from the citation. */\n ts?: string;\n /** The full matched citation substring. */\n raw: string;\n}\n\n/**\n * Regex that matches the default `[Source: agent=X, session=Y, ts=Z]` shape\n * as well as human-edited variants (extra whitespace, reordered fields,\n * subset of fields). Matches non-greedily so it can be anchored anywhere in\n * the text. Kept as a getter factory so callers do not share regex state.\n */\nfunction defaultCitationMatcher(): RegExp {\n // Bounded repetition {1,1024} instead of + so the match cannot backtrack\n // polynomially over hostile memory text (CodeQL js/polynomial-redos). A real\n // citation is far shorter than 1024 chars, so this is behavior-preserving for\n // any genuine [Source: …] block; only pathological/oversized input is excluded.\n return /\\[Source:([^\\]\\n]{1,1024})\\]/gi;\n}\n\n// Linear trailing-whitespace trim. Replaces text.replace(/\\s+$/u, \"\"), whose\n// anchored quantifier backtracks polynomially on long inputs (CodeQL\n// js/polynomial-redos). Matches the exact \\s (with u flag) semantics one char\n// at a time, so the trailing-content preservation logic in attachCitation is\n// unaffected.\nfunction trimTrailingWhitespace(text: string): string {\n let end = text.length;\n while (end > 0 && /\\s/u.test(text[end - 1]!)) end--;\n return text.slice(0, end);\n}\n\n/**\n * Derive a short session id from a full session key.\n * Falls back to the raw session string if no colon is present.\n */\nexport function deriveSessionId(session: string | undefined): string | undefined {\n if (!session) return undefined;\n const trimmed = session.trim();\n if (trimmed.length === 0) return undefined;\n const parts = trimmed.split(\":\").filter((p) => p.length > 0);\n if (parts.length === 0) return trimmed;\n return parts[parts.length - 1];\n}\n\n/**\n * Format an inline citation tag using the provided template.\n *\n * Missing context fields fall back to {@link CITATION_UNKNOWN} — the caller\n * should always get a non-empty, parseable tag.\n *\n * Uses a single-pass substitution so that values which themselves contain\n * placeholder syntax (e.g. an agent literally named `\"{ts}\"`) cannot be\n * re-interpreted by subsequent replacement steps. Each placeholder slot\n * receives exactly one lookup and the substituted value is treated as\n * terminal text, not template source.\n */\nexport function formatCitation(\n ctx: CitationContext,\n template: string = DEFAULT_CITATION_FORMAT,\n): string {\n const session = ctx.session ?? \"\";\n const sessionId = ctx.sessionId ?? deriveSessionId(session) ?? CITATION_UNKNOWN;\n const ts = ctx.ts ?? CITATION_UNKNOWN;\n const agent = ctx.agent && ctx.agent.trim().length > 0 ? ctx.agent : CITATION_UNKNOWN;\n const date = ts && ts !== CITATION_UNKNOWN ? ts.slice(0, 10) : CITATION_UNKNOWN;\n const sessionForTemplate = session.trim().length > 0 ? session : CITATION_UNKNOWN;\n\n // Map from recognised placeholder names to their resolved value. Unknown\n // placeholder names are left intact (returning the original `{name}`).\n const values: Record<string, string> = {\n agent,\n session: sessionForTemplate,\n sessionId,\n ts,\n date,\n };\n\n // Single-pass scan: replace every recognised `{name}` in one sweep so that\n // substituted values cannot themselves be treated as template source on a\n // subsequent pass. The replacer-function form also guarantees that `$` /\n // `$&` / `$1` sequences inside values are emitted literally.\n return template.replace(/\\{([a-zA-Z_][\\w]*)\\}/g, (match, name: string) => {\n return Object.prototype.hasOwnProperty.call(values, name)\n ? values[name]!\n : match;\n });\n}\n\n/**\n * Returns true if the text already carries at least one citation marker.\n * Safe to call on any string — never throws.\n */\nexport function hasCitation(text: string): boolean {\n if (typeof text !== \"string\" || text.length === 0) return false;\n return defaultCitationMatcher().test(text);\n}\n\n/**\n * Escape a string for use as a regex literal.\n */\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Escape a single character for use INSIDE a character class `[...]`.\n * Special chars inside character classes: `]`, `\\`, `^`, `-`.\n */\nfunction escapeRegExpCharClass(ch: string): string {\n if (ch === \"]\") return \"\\\\]\";\n if (ch === \"\\\\\") return \"\\\\\\\\\";\n if (ch === \"^\") return \"\\\\^\";\n if (ch === \"-\") return \"\\\\-\";\n // Other regex meta chars are NOT special inside [...] but escaping them is safe.\n return escapeRegExp(ch);\n}\n\n/**\n * Build a per-placeholder token pattern that excludes newlines, whitespace,\n * and any punctuation characters used as inner separators in the template.\n *\n * This prevents a placeholder span from consuming separator bytes and\n * matching strings that cross separator boundaries in user-supplied content.\n *\n * @param nonWordSepChars - Set of non-word (non-alphanumeric, non-`_`) chars\n * extracted from the inner separator literals of the template.\n */\nfunction buildTokenPattern(nonWordSepChars: Set<string>): string {\n // Always exclude newlines and whitespace.\n const base = \"\\\\n\\\\s\";\n if (nonWordSepChars.size === 0) {\n // No inner separator punctuation — the placeholder spans the full space\n // between prefix and suffix. Fall back to a generous no-newline match.\n return `[^\\\\n]+?`;\n }\n const escaped = [...nonWordSepChars].map(escapeRegExpCharClass).join(\"\");\n return `[^${base}${escaped}]+?`;\n}\n\n/** Regex that matches a `{placeholder}` token inside a template string. */\nconst PLACEHOLDER_REGEX = /\\{[a-zA-Z_][\\w]*\\}/g;\n\n/**\n * Build a regex that matches a citation produced by the given template.\n *\n * The approach depends on the shape of the template:\n *\n * - **Normal case (non-empty literal prefix or suffix).** Anchor the match\n * on the outer literal frame and reconstruct the interior as\n * `interToken + sep + interToken + sep + ... + sep + lastToken`.\n * All **intermediate** per-placeholder tokens exclude the combined set of\n * non-word separator characters used between any two adjacent placeholders,\n * preventing a value from consuming a separator and crossing placeholder\n * boundaries. The **last** token is only required to avoid newlines because\n * it is terminated by the literal suffix anchor — this lets placeholder\n * values that legitimately contain a separator character be recognised (e.g.\n * an ISO-8601 timestamp `2026-04-10T14:25:07Z` in `[src:{agent}:{ts}]`\n * where `:` is the inter-placeholder separator). A template like\n * `[src:{agent}/{sessionId}@{date}]` emits\n * `\\[src:[^\\n\\s/@]+?\\/[^\\n\\s/@]+?@[^\\n]+?\\]` so that `[src:foo/bar]`\n * is NOT matched (wrong separator count), `[src:foo/bar/extra@2026]`\n * is NOT matched (intermediate token crosses a `/` boundary), and\n * `[src:planner/main@2026-04-10]` IS matched correctly.\n *\n * - **Placeholder-bounded with whitespace separator.** Both prefix and\n * suffix are empty and the separator literal(s) between placeholders\n * contain at least one whitespace character (e.g. `{source}: {content}`,\n * `{agent} {sessionId}`). A whitespace-containing separator produces\n * output that is visually indistinguishable from ordinary prose, so the\n * safe strategy is to require a **hard bracket/paren/angle delimiter** on\n * both sides of the reconstructed match. Prose almost never places\n * `[...]` / `(...)` / `<...>` around a phrase, so this yields clean\n * false-positive rejection.\n *\n * - **Placeholder-bounded with compact (non-whitespace) separator.** Both\n * prefix and suffix are empty and the separator literal(s) contain NO\n * whitespace (e.g. `{agent}:{sessionId}`, `{agent}/{sessionId}`).\n * `formatCitation` emits a compact token like `planner:main` with no\n * surrounding delimiters, so the bracket strategy cannot detect it.\n * Instead, the pattern requires that the entire token is bordered by\n * whitespace or a bracket/paren/angle on each side:\n *\n * `(?:(?<=[\\[\\(\\<])|(?<!\\S))[\\w.-]+<sep>[\\w.-]+(?:(?=[\\]\\)\\>])|(?!\\S))`\n *\n * This accepts `planner:main` when it appears standalone or inside a\n * bracket-wrapped token, and rejects `host:80` embedded inside a URL like\n * `http://host:80` because `host` is immediately preceded by `/`\n * (non-whitespace, non-bracket).\n *\n * - **All-placeholder case (no literals between placeholders either).** No\n * reliable regex can be built — a template like `{agent}{sessionId}`\n * contains no anchor characters. Returns `null`; {@link\n * hasCitationForTemplate} treats this as \"cannot detect\" and returns\n * false, falling back on explicit sentinel/format detection only for the\n * default `[Source: ...]` shape.\n *\n * Returns `null` when the template has no placeholders (fully-literal\n * citation, handled by the string-equality fast path in {@link\n * hasCitationForTemplate}) **or** when the template is entirely placeholder-\n * only with no literal content whatsoever.\n */\nfunction templateMatcher(template: string): RegExp | null {\n // Split around all {placeholder} tokens.\n const parts = template.split(PLACEHOLDER_REGEX);\n if (parts.length <= 1) return null;\n\n const prefix = parts[0] ?? \"\";\n const suffix = parts[parts.length - 1] ?? \"\";\n\n // Normal case: at least one literal frame on the outside.\n // Tighten the per-placeholder token so it cannot consume separator\n // characters and match strings that cross separator boundaries\n // (Finding 3 — Uru3).\n if (prefix.length > 0 || suffix.length > 0) {\n const escapedPrefix = escapeRegExp(prefix);\n const escapedSuffix = escapeRegExp(suffix);\n\n // Inner parts: literal separators that sit between adjacent placeholders.\n // For `[src:{agent}/{sessionId}@{date}]`, parts = [\"[src:\", \"/\", \"@\", \"]\"]\n // so innerParts = [\"/\", \"@\"].\n const innerParts = parts.slice(1, -1);\n\n // Collect only the non-word (punctuation/symbol) characters from each\n // inner separator so alphabetic separator text (unlikely but valid) does\n // not exclude letters from the per-placeholder token pattern.\n const nonWordSepChars = new Set<string>();\n for (const sep of innerParts) {\n for (const ch of sep) {\n if (!/\\w/.test(ch)) {\n nonWordSepChars.add(ch);\n }\n }\n }\n\n // All intermediate tokens (every placeholder except the last) use the\n // combined exclusion so they cannot cross placeholder boundaries.\n //\n // The LAST token is different: it is terminated by the literal suffix anchor\n // (e.g. `\\]`), so it does not need to exclude inner-separator characters.\n // Dropping that restriction lets placeholder values that legitimately contain\n // a separator character (e.g. an ISO-8601 timestamp `2026-04-10T14:25:07Z`\n // in template `[src:{agent}:{ts}]`) be recognised correctly instead of\n // producing false-negative misses that trigger duplicate citation injection.\n //\n // Only the LAST token is relaxed. Intermediate tokens keep the combined\n // exclusion so that cross-boundary false positives are still rejected\n // (e.g. `[src:foo/bar/extra@2026-04-11]` for `[src:{a}/{b}@{c}]`).\n const interToken = buildTokenPattern(nonWordSepChars);\n // Last token: terminated by suffix anchor — exclude only newlines.\n const lastToken = buildTokenPattern(new Set<string>());\n\n // Reconstruct the interior: interToken sep interToken sep ... sep lastToken\n // (or just lastToken when there are no inner separators at all).\n const middle =\n innerParts.length === 0\n ? lastToken\n : interToken +\n innerParts\n .slice(0, -1)\n .map((sep) => escapeRegExp(sep) + interToken)\n .join(\"\") +\n escapeRegExp(innerParts[innerParts.length - 1]!) +\n lastToken;\n\n const pattern = escapedPrefix + middle + escapedSuffix;\n return new RegExp(pattern, \"i\");\n }\n\n // Placeholder-bounded case: prefix and suffix are both empty.\n const middleLiterals = parts.slice(1, -1);\n const hasNonEmptyMiddle = middleLiterals.some((p) => p.length > 0);\n if (!hasNonEmptyMiddle) {\n // All-placeholder template with no literal content. Impossible to anchor\n // reliably without sentinel markers; signal the caller.\n return null;\n }\n\n // Identifier token: one or more word chars, dots, dashes, or colons.\n // Colons are included to allow timestamp values like \"10:30\" or session\n // keys like \"agent:planner:main\" inside compact placeholder-bounded\n // templates. URL-like fragments (`http://host:80`) are still rejected\n // because the lead anchor requires whitespace or a bracket immediately\n // before the first id-token group (`http` is preceded by `/`).\n const idToken = \"[\\\\w.:-]+\";\n const body =\n idToken +\n middleLiterals.map((lit) => escapeRegExp(lit) + idToken).join(\"\");\n\n const separatorText = middleLiterals.join(\"\");\n if (/\\s/.test(separatorText)) {\n // Separator contains whitespace: the emitted citation looks like ordinary\n // prose (e.g. `planner main`). Require a hard bracket/paren/angle\n // delimiter on both sides to prevent false matches on English text.\n const opener = \"[\\\\[\\\\(\\\\<]\";\n const closer = \"[\\\\]\\\\)\\\\>]\";\n return new RegExp(opener + body + closer, \"i\");\n }\n\n // Separator is compact (no whitespace): `formatCitation` emits a token like\n // `planner:main` without surrounding delimiters. The challenge is that the\n // same token shape also matches ordinary hyphenated or slashed prose words\n // (e.g. `long-term`, `docs/setup`), causing `hasCitationForTemplate` to\n // return true on uncited fact bodies and silently suppress citation injection\n // from `attachCitation`.\n //\n // Fix (Finding 1): tighten the trail anchor so a bare compact token is only\n // accepted when it sits at the very end of the string (possibly followed by\n // optional trailing whitespace or a newline). Since `attachCitation` always\n // appends the citation at the trimmed end of the fact body, a real citation\n // token will always appear at the tail. Prose like `\"long-term solution\"`\n // has `long-term` in the middle of the string (followed by ` solution`), so\n // the end-of-string anchor rejects it — no false positive, no silent drop.\n //\n // The lead anchor still accepts either a bracket opener or a whitespace\n // boundary (or start of string), so `\"Fact. planner:main\"` and standalone\n // `\"planner:main\"` are both detected after the first attachment pass.\n //\n // Bracket-wrapped form (e.g. `[planner:main]`) is also accepted via the\n // opener/closer pair — bracket still takes precedence over end-of-string.\n //\n // Example — why `http://host:80` does NOT match:\n // Trying to match `host:80`: the char before `h` is `/` (non-whitespace,\n // non-bracket), so `(?<=[\\[\\(\\<])` and `(?<!\\S)` both fail ⟹ no match.\n // Trying to match `http:...`: after `http:` the next chars are `//` which\n // are not `[\\w.-]+`, so the second id-token group fails ⟹ no match.\n const leadAnchor = \"(?:(?<=[\\\\[\\\\(\\\\<])|(?<!\\\\S))\";\n // Trail: either a bracket closer (for `[token]` shape) or end-of-string\n // optionally preceded by whitespace. The `(?!\\S)` is deliberately removed\n // so that a compact token in the MIDDLE of a sentence does not match.\n const trailAnchor = \"(?:(?=[\\\\]\\\\)\\\\>])|(?=\\\\s*$))\";\n return new RegExp(leadAnchor + body + trailAnchor, \"i\");\n}\n\n/**\n * Returns true if `text` already carries a citation produced by `template`\n * **or** by the default `[Source: ...]` format (for facts that were tagged\n * before a config change).\n *\n * Use this instead of {@link hasCitation} whenever the caller has access to\n * the configured `inlineSourceAttributionFormat`.\n *\n * All-placeholder templates such as `{agent}{sessionId}` have no literal\n * content to anchor on and therefore cannot be reliably detected without\n * dedicated sentinel markers. In that case the function returns `false` —\n * callers that need idempotent dedup for such templates should either adopt\n * a template with literal delimiters (recommended) or rely on the default\n * `[Source: ...]` marker detection which is always available via\n * {@link hasCitation}.\n */\nexport function hasCitationForTemplate(text: string, template: string): boolean {\n if (typeof text !== \"string\" || text.length === 0) return false;\n // Always accept the default format as a fallback so facts tagged before a\n // configuration change are not double-tagged on reprocessing.\n if (hasCitation(text)) return true;\n // If the configured template matches the default, we're done.\n //\n // Known limitation (Thread 2 — Codex P2): this fast path exits without\n // checking whether the content carries a citation from a DIFFERENT custom\n // template that was active before the config was changed back to the default.\n // Such a fact would be detected by `hasCitation` above only if the prior\n // custom template happened to match the default `[Source: ...]` pattern.\n // In practice, template changes mid-stream are rare, and the false-negative\n // (missing an old custom citation) produces a benign duplicate citation rather\n // than data loss. A full fix would require storing the citation template used\n // at write time in the frontmatter and checking that here.\n if (template === DEFAULT_CITATION_FORMAT) return false;\n\n // Fully-literal template (no placeholders): exact inclusion check.\n if (!PLACEHOLDER_REGEX.test(template)) {\n // Reset lastIndex because PLACEHOLDER_REGEX is declared with /g.\n PLACEHOLDER_REGEX.lastIndex = 0;\n return text.includes(template);\n }\n // Reset lastIndex after the .test() probe above.\n PLACEHOLDER_REGEX.lastIndex = 0;\n\n const matcher = templateMatcher(template);\n if (!matcher) {\n // All-placeholder template: cannot build a reliable matcher. See the\n // docstring — callers should not rely on dedup for this shape.\n return false;\n }\n return matcher.test(text);\n}\n\n/**\n * Return the LAST citation marker in `text` for the given template (or the\n * default `[Source: ...]` shape). `attachCitation` always appends at the\n * trimmed end, so the last occurrence is the most recently attached marker —\n * callers use this to lift a just-attached citation off a cited body and\n * re-attach it to a derived body (the merged-target commit path). Returns\n * null when the text carries no marker of this template (including\n * all-placeholder templates that cannot be matched reliably).\n */\nexport function lastCitationMarkerForTemplate(\n text: string,\n template: string = DEFAULT_CITATION_FORMAT,\n): string | null {\n if (typeof text !== \"string\" || text.length === 0) return null;\n let matcher: RegExp | null;\n if (template === DEFAULT_CITATION_FORMAT) {\n matcher = defaultCitationMatcher();\n } else if (!PLACEHOLDER_REGEX.test(template)) {\n // Fully-literal template: presence is exact inclusion (no placeholders\n // to widen the match).\n PLACEHOLDER_REGEX.lastIndex = 0;\n return text.includes(template) ? template : null;\n } else {\n PLACEHOLDER_REGEX.lastIndex = 0;\n matcher = templateMatcher(template);\n }\n if (!matcher) return null;\n const global = new RegExp(\n matcher.source,\n matcher.flags.includes(\"g\") ? matcher.flags : matcher.flags + \"g\",\n );\n let last: string | null = null;\n for (let match = global.exec(text); match !== null; match = global.exec(text)) {\n last = match[0];\n if (match[0].length === 0) global.lastIndex++;\n }\n return last;\n}\n\n/**\n * True when a template can be matched and stripped later. All-placeholder\n * templates such as `{agent}{sessionId}` have no literal anchors.\n */\nexport function citationTemplateIsDetectable(template: string): boolean {\n if (typeof template !== \"string\" || template.length === 0) return false;\n if (template === DEFAULT_CITATION_FORMAT) return true;\n PLACEHOLDER_REGEX.lastIndex = 0;\n if (!PLACEHOLDER_REGEX.test(template)) {\n PLACEHOLDER_REGEX.lastIndex = 0;\n return true;\n }\n PLACEHOLDER_REGEX.lastIndex = 0;\n return templateMatcher(template) !== null;\n}\n\n/**\n * Templates the merge path may lift, preserve, or strip: the default\n * format, the current format when it is detectable, then any prior\n * configured formats the caller still holds. Undetectable shapes are\n * dropped so we never hash or attach a marker we cannot re-match.\n */\nexport function citationTemplatesToRecognize(\n primary: string | undefined,\n extra: readonly string[] = [],\n): string[] {\n const out: string[] = [];\n const add = (template: string | undefined): void => {\n if (typeof template !== \"string\" || template.length === 0) return;\n if (!citationTemplateIsDetectable(template)) return;\n if (!out.includes(template)) out.push(template);\n };\n add(DEFAULT_CITATION_FORMAT);\n add(primary);\n for (const template of extra) add(template);\n return out;\n}\n\n/**\n * Prior formats the caller still holds, if any. Absent or malformed\n * history is ignored — fail safe, do not invent templates.\n */\nexport function citationTemplatesForMerge(config: {\n inlineSourceAttributionFormat?: string;\n inlineSourceAttributionFormatHistory?: unknown;\n}): string[] {\n const raw = config.inlineSourceAttributionFormatHistory;\n const extra = Array.isArray(raw)\n ? raw.filter((value): value is string => typeof value === \"string\" && value.length > 0)\n : [];\n return citationTemplatesToRecognize(config.inlineSourceAttributionFormat, extra);\n}\n\nexport function lastRecognizedCitationMarker(\n text: string,\n templates: readonly string[],\n): string | null {\n for (const template of templates) {\n const marker = lastCitationMarkerForTemplate(text, template);\n if (marker) return marker;\n }\n return null;\n}\n\nexport function stripRecognizedCitations(text: string, templates: readonly string[]): string {\n let out = text;\n for (const template of templates) {\n out = stripCitationForTemplate(out, template);\n }\n return out;\n}\n\n/**\n * Attach an inline citation to fact text.\n *\n * If the text already has a citation — either the default `[Source: ...]`\n * marker or one produced by the configured template — it is returned unchanged.\n * Existing provenance is respected and never overwritten. Otherwise the\n * citation is appended to the trimmed text with a single space separator,\n * which keeps the marker visually adjacent to the fact body.\n */\nexport function attachCitation(\n text: string,\n ctx: CitationContext,\n template: string = DEFAULT_CITATION_FORMAT,\n): string {\n if (typeof text !== \"string\") return text as unknown as string;\n if (hasCitationForTemplate(text, template)) return text;\n const trimmedEnd = trimTrailingWhitespace(text);\n if (trimmedEnd.length === 0) return text;\n const citation = formatCitation(ctx, template);\n // Preserve any trailing newline that callers rely on for markdown rendering.\n const trailing = text.slice(trimmedEnd.length);\n return `${trimmedEnd} ${citation}${trailing}`;\n}\n\n/**\n * Parse a single inline citation from a piece of text. Returns the first\n * citation encountered or `null` when none is present. Malformed citations\n * do not throw — fields that cannot be parsed simply remain `undefined`.\n */\nexport function parseCitation(text: string): ParsedCitation | null {\n if (typeof text !== \"string\" || text.length === 0) return null;\n const matcher = defaultCitationMatcher();\n const match = matcher.exec(text);\n if (!match) return null;\n\n const body = match[1] ?? \"\";\n const raw = match[0] ?? \"\";\n const parsed: ParsedCitation = { raw };\n\n const fields = body\n .split(\",\")\n .map((segment) => segment.trim())\n .filter((segment) => segment.length > 0);\n\n for (const field of fields) {\n const eqIdx = field.indexOf(\"=\");\n if (eqIdx <= 0) continue;\n const key = field.slice(0, eqIdx).trim().toLowerCase();\n const value = field.slice(eqIdx + 1).trim();\n if (value.length === 0) continue;\n switch (key) {\n case \"agent\":\n parsed.agent = value;\n break;\n case \"session\":\n case \"sessionid\":\n parsed.session = value;\n break;\n case \"ts\":\n case \"timestamp\":\n parsed.ts = value;\n break;\n default:\n // Unknown fields are ignored defensively so human edits never crash.\n break;\n }\n }\n\n return parsed;\n}\n\n/**\n * Parse every citation embedded in the text. Always returns an array; empty\n * when none are present.\n */\nexport function parseAllCitations(text: string): ParsedCitation[] {\n if (typeof text !== \"string\" || text.length === 0) return [];\n const matcher = defaultCitationMatcher();\n const results: ParsedCitation[] = [];\n let match: RegExpExecArray | null;\n while ((match = matcher.exec(text)) !== null) {\n const parsed = parseCitation(match[0]);\n if (parsed) results.push(parsed);\n }\n return results;\n}\n\n/**\n * Remove all inline citations from a piece of text.\n *\n * Callers that want the raw fact body (for dedup hashing, display, or\n * comparison) should use this helper instead of hand-rolled regexes so the\n * whole codebase agrees on the citation syntax.\n *\n * Finding 2 fix: when the input contains no citation marker, the input is\n * returned byte-for-byte unchanged. When a citation IS removed, whitespace\n * normalization is applied only at each join seam (the single space between\n * the preceding text and where the citation was), rather than across the\n * entire string. This preserves markdown hard-break spacing, aligned text,\n * and code-like snippets in fact bodies that happen to carry a citation.\n *\n * Implementation: each citation match is replaced by its \"seam fix\" — the\n * content before the match has its trailing whitespace trimmed and then a\n * single space is appended if any text remains, collapsing only the gap\n * left by the removed marker. Whitespace elsewhere in the body is untouched.\n */\nexport function stripCitation(text: string): string {\n if (typeof text !== \"string\" || text.length === 0) return text;\n // Early exit: no citation marker present — return the input unchanged so\n // that callers never lose formatting fidelity on uncited strings.\n if (!hasCitation(text)) return text;\n\n // Walk through all citations and slice them out one by one so that we can\n // normalise ONLY the whitespace at each seam rather than the entire string.\n const matcher = defaultCitationMatcher();\n let result = \"\";\n let lastIndex = 0;\n\n let match: RegExpExecArray | null;\n while ((match = matcher.exec(text)) !== null) {\n // Text before this citation. Trim trailing spaces/tabs at the seam only.\n const before = text.slice(lastIndex, match.index).replace(/[ \\t]+$/, \"\");\n result += before;\n lastIndex = match.index + match[0].length;\n }\n\n // Append any trailing text after the last citation. Trim leading\n // spaces/tabs and trailing whitespace at the join seam.\n const after = text.slice(lastIndex).replace(/^[ \\t]+/, \"\");\n if (after.length > 0) {\n if (result.length > 0) result += \" \";\n result += after;\n }\n\n return result.trimEnd();\n}\n\n/**\n * Strip an inline citation from text using a specific template regex.\n *\n * This is the template-aware counterpart to {@link stripCitation}. When the\n * caller holds the configured `inlineSourceAttributionFormat`, use this\n * function to strip citations produced by that template — including custom\n * templates that differ from the default `[Source: ...]` pattern.\n *\n * Behaviour:\n * - If the text has a **default-format** citation, strips it first\n * (always safe).\n * - Then, if the result has a **custom-template** citation detected by\n * `hasCitationForTemplate`, builds the template regex and removes every\n * occurrence. BOTH passes run when a body carries both forms — a target\n * written under the default format can carry the default marker plus a\n * custom marker appended after a config change; returning after the\n * default pass alone left the custom marker inside hash inputs (#2330).\n * - All-placeholder templates (no literal prefix/suffix/separator) cannot\n * produce a reliable matcher. `hasCitationForTemplate` already returns\n * `false` for such templates, so this function never attempts to strip an\n * undetectable citation. The text is returned unchanged when no citation\n * is detected.\n * - If no citation is detected for the given template, returns the text\n * unchanged.\n *\n * @returns The stripped text (or the original text when no citation is found).\n */\nexport function stripCitationForTemplate(\n text: string,\n template: string,\n): string {\n if (typeof text !== \"string\" || text.length === 0) return text;\n\n // First pass: the default-format marker, if any. A second pass below still\n // runs — a body can carry the default marker AND the custom template's\n // marker, and canonicalization must remove every recognized form.\n const afterDefault = hasCitation(text) ? stripCitation(text) : text;\n\n if (!hasCitationForTemplate(afterDefault, template)) return afterDefault;\n\n // Build the template matcher. hasCitationForTemplate already returned true,\n // which means templateMatcher produced a non-null result. The null branch\n // here is a defensive fallback only — the default pass already ran.\n const matcher = templateMatcher(template);\n if (!matcher) return afterDefault;\n\n // The matcher regex was built without the global flag; add it for exec loop.\n const globalMatcher = new RegExp(\n matcher.source,\n matcher.flags.includes(\"g\") ? matcher.flags : matcher.flags + \"g\",\n );\n let result = \"\";\n let lastIndex = 0;\n let match: RegExpExecArray | null;\n\n while ((match = globalMatcher.exec(afterDefault)) !== null) {\n const matchEnd = match.index + match[0].length;\n const enclosure = enclosingDelimiterRange(afterDefault, match.index, matchEnd);\n const removalStart = enclosure?.start ?? match.index;\n const removalEnd = enclosure?.end ?? matchEnd;\n const before = afterDefault.slice(lastIndex, removalStart).replace(/[ \\t]+$/, \"\");\n result += before;\n lastIndex = removalEnd;\n // Guard against zero-width matches causing an infinite loop.\n if (match[0].length === 0) {\n globalMatcher.lastIndex++;\n }\n }\n\n const after = afterDefault.slice(lastIndex).replace(/^[ \\t]+/, \"\");\n if (after.length > 0) {\n if (result.length > 0) result += \" \";\n result += after;\n }\n\n return result.trimEnd();\n}\n\nfunction enclosingDelimiterRange(\n text: string,\n start: number,\n end: number,\n): { start: number; end: number } | undefined {\n if (start <= 0 || end >= text.length) return undefined;\n const opener = text[start - 1];\n const closer = text[end];\n if (\n (opener === \"[\" && closer === \"]\") ||\n (opener === \"(\" && closer === \")\") ||\n (opener === \"<\" && closer === \">\")\n ) {\n return { start: start - 1, end: end + 1 };\n }\n return undefined;\n}\n"],"mappings":";AAkCO,IAAM,0BACX;AAGK,IAAM,mBAAmB;AAkChC,SAAS,yBAAiC;AAKxC,SAAO;AACT;AAOA,SAAS,uBAAuB,MAAsB;AACpD,MAAI,MAAM,KAAK;AACf,SAAO,MAAM,KAAK,MAAM,KAAK,KAAK,MAAM,CAAC,CAAE,EAAG;AAC9C,SAAO,KAAK,MAAM,GAAG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;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/source-attribution.ts"],"sourcesContent":["/**\n * Inline Source Attribution Protocol (issue #369)\n *\n * Extracted facts carry provenance inline inside the fact body, so the\n * citation survives hostile memory text, copy/paste, and LLM quoting. This\n * complements — never replaces — the YAML frontmatter provenance stored on\n * disk.\n *\n * Default format (matches issue #369 proposal):\n *\n * The foo service uses Redis for rate limiting. [Source: agent=planner, session=abc123, ts=2026-04-10T14:25:07Z]\n *\n * Key properties:\n * - Inline (part of the body, not metadata).\n * - Compact (typically <80 chars of overhead per fact).\n * - Machine-parseable by a single regex.\n * - Opt-in via `inlineSourceAttributionEnabled` config flag (default off\n * for backwards compatibility with existing downstream consumers).\n * - Legacy facts without a citation remain fully readable.\n *\n * The format template is configurable via `inlineSourceAttributionFormat`\n * with supported placeholders:\n *\n * {agent} — principal / agent identifier\n * {session} — full session key (colon-delimited)\n * {sessionId} — short stable session id (trailing component)\n * {ts} — extraction timestamp (ISO 8601)\n * {date} — extraction date (YYYY-MM-DD)\n *\n * Any privacy-sensitive identifiers should be normalized before being passed\n * to `formatCitation` — the helper treats them as opaque strings.\n */\n\n/** Default citation format template (matches issue #369). */\nexport const DEFAULT_CITATION_FORMAT =\n \"[Source: agent={agent}, session={sessionId}, ts={ts}]\";\n\n/** Sentinel value used when a provenance field is missing. */\nexport const CITATION_UNKNOWN = \"unknown\";\n\nexport interface CitationContext {\n /** Principal / agent identifier (e.g. resolved via resolvePrincipal). */\n agent?: string;\n /** Full session key (e.g. \"agent:planner:main\"). */\n session?: string;\n /**\n * Opaque short session id. Derived from the trailing component of the\n * session key when not provided explicitly. Use this for compact formats\n * that do not need the full colon-delimited session key.\n */\n sessionId?: string;\n /** Extraction timestamp as an ISO 8601 string. */\n ts?: string;\n}\n\nexport interface ParsedCitation {\n /** Agent identifier parsed from the citation (never crashes on malformed input). */\n agent?: string;\n /** Session identifier parsed from the citation. */\n session?: string;\n /** Extraction timestamp parsed from the citation. */\n ts?: string;\n /** The full matched citation substring. */\n raw: string;\n}\n\n/**\n * Regex that matches the default `[Source: agent=X, session=Y, ts=Z]` shape\n * as well as human-edited variants (extra whitespace, reordered fields,\n * subset of fields). Matches non-greedily so it can be anchored anywhere in\n * the text. Kept as a getter factory so callers do not share regex state.\n */\nfunction defaultCitationMatcher(): RegExp {\n // Bounded repetition {1,1024} instead of + so the match cannot backtrack\n // polynomially over hostile memory text (CodeQL js/polynomial-redos). A real\n // citation is far shorter than 1024 chars, so this is behavior-preserving for\n // any genuine [Source: …] block; only pathological/oversized input is excluded.\n return /\\[Source:([^\\]\\n]{1,1024})\\]/gi;\n}\n\n// Linear trailing-whitespace trim. Replaces text.replace(/\\s+$/u, \"\"), whose\n// anchored quantifier backtracks polynomially on long inputs (CodeQL\n// js/polynomial-redos). Matches the exact \\s (with u flag) semantics one char\n// at a time, so the trailing-content preservation logic in attachCitation is\n// unaffected.\nfunction trimTrailingWhitespace(text: string): string {\n let end = text.length;\n while (end > 0 && /\\s/u.test(text[end - 1]!)) end--;\n return text.slice(0, end);\n}\n\n/**\n * Derive a short session id from a full session key.\n * Falls back to the raw session string if no colon is present.\n */\nexport function deriveSessionId(session: string | undefined): string | undefined {\n if (!session) return undefined;\n const trimmed = session.trim();\n if (trimmed.length === 0) return undefined;\n const parts = trimmed.split(\":\").filter((p) => p.length > 0);\n if (parts.length === 0) return trimmed;\n return parts[parts.length - 1];\n}\n\n/**\n * Format an inline citation tag using the provided template.\n *\n * Missing context fields fall back to {@link CITATION_UNKNOWN} — the caller\n * should always get a non-empty, parseable tag.\n *\n * Uses a single-pass substitution so that values which themselves contain\n * placeholder syntax (e.g. an agent literally named `\"{ts}\"`) cannot be\n * re-interpreted by subsequent replacement steps. Each placeholder slot\n * receives exactly one lookup and the substituted value is treated as\n * terminal text, not template source.\n */\nexport function formatCitation(\n ctx: CitationContext,\n template: string = DEFAULT_CITATION_FORMAT,\n): string {\n const session = ctx.session ?? \"\";\n const sessionId = ctx.sessionId ?? deriveSessionId(session) ?? CITATION_UNKNOWN;\n const ts = ctx.ts ?? CITATION_UNKNOWN;\n const agent = ctx.agent && ctx.agent.trim().length > 0 ? ctx.agent : CITATION_UNKNOWN;\n const date = ts && ts !== CITATION_UNKNOWN ? ts.slice(0, 10) : CITATION_UNKNOWN;\n const sessionForTemplate = session.trim().length > 0 ? session : CITATION_UNKNOWN;\n\n // Map from recognised placeholder names to their resolved value. Unknown\n // placeholder names are left intact (returning the original `{name}`).\n const values: Record<string, string> = {\n agent,\n session: sessionForTemplate,\n sessionId,\n ts,\n date,\n };\n\n // Single-pass scan: replace every recognised `{name}` in one sweep so that\n // substituted values cannot themselves be treated as template source on a\n // subsequent pass. The replacer-function form also guarantees that `$` /\n // `$&` / `$1` sequences inside values are emitted literally.\n return template.replace(/\\{([a-zA-Z_][\\w]*)\\}/g, (match, name: string) => {\n return Object.prototype.hasOwnProperty.call(values, name)\n ? values[name]!\n : match;\n });\n}\n\n/**\n * Returns true if the text already carries at least one citation marker.\n * Safe to call on any string — never throws.\n */\nexport function hasCitation(text: string): boolean {\n if (typeof text !== \"string\" || text.length === 0) return false;\n return defaultCitationMatcher().test(text);\n}\n\n/**\n * Escape a string for use as a regex literal.\n */\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Escape a single character for use INSIDE a character class `[...]`.\n * Special chars inside character classes: `]`, `\\`, `^`, `-`.\n */\nfunction escapeRegExpCharClass(ch: string): string {\n if (ch === \"]\") return \"\\\\]\";\n if (ch === \"\\\\\") return \"\\\\\\\\\";\n if (ch === \"^\") return \"\\\\^\";\n if (ch === \"-\") return \"\\\\-\";\n // Other regex meta chars are NOT special inside [...] but escaping them is safe.\n return escapeRegExp(ch);\n}\n\n/**\n * Build a per-placeholder token pattern that excludes newlines, whitespace,\n * and any punctuation characters used as inner separators in the template.\n *\n * This prevents a placeholder span from consuming separator bytes and\n * matching strings that cross separator boundaries in user-supplied content.\n *\n * @param nonWordSepChars - Set of non-word (non-alphanumeric, non-`_`) chars\n * extracted from the inner separator literals of the template.\n */\nfunction buildTokenPattern(nonWordSepChars: Set<string>): string {\n // Always exclude newlines and whitespace.\n const base = \"\\\\n\\\\s\";\n if (nonWordSepChars.size === 0) {\n // No inner separator punctuation — the placeholder spans the full space\n // between prefix and suffix. Fall back to a generous no-newline match.\n return `[^\\\\n]+?`;\n }\n const escaped = [...nonWordSepChars].map(escapeRegExpCharClass).join(\"\");\n return `[^${base}${escaped}]+?`;\n}\n\n/** Regex that matches a `{placeholder}` token inside a template string. */\nconst PLACEHOLDER_REGEX = /\\{[a-zA-Z_][\\w]*\\}/g;\n\n/**\n * Build a regex that matches a citation produced by the given template.\n *\n * The approach depends on the shape of the template:\n *\n * - **Normal case (non-empty literal prefix or suffix).** Anchor the match\n * on the outer literal frame and reconstruct the interior as\n * `interToken + sep + interToken + sep + ... + sep + lastToken`.\n * All **intermediate** per-placeholder tokens exclude the combined set of\n * non-word separator characters used between any two adjacent placeholders,\n * preventing a value from consuming a separator and crossing placeholder\n * boundaries. The **last** token is only required to avoid newlines because\n * it is terminated by the literal suffix anchor — this lets placeholder\n * values that legitimately contain a separator character be recognised (e.g.\n * an ISO-8601 timestamp `2026-04-10T14:25:07Z` in `[src:{agent}:{ts}]`\n * where `:` is the inter-placeholder separator). A template like\n * `[src:{agent}/{sessionId}@{date}]` emits\n * `\\[src:[^\\n\\s/@]+?\\/[^\\n\\s/@]+?@[^\\n]+?\\]` so that `[src:foo/bar]`\n * is NOT matched (wrong separator count), `[src:foo/bar/extra@2026]`\n * is NOT matched (intermediate token crosses a `/` boundary), and\n * `[src:planner/main@2026-04-10]` IS matched correctly.\n *\n * - **Placeholder-bounded with whitespace separator.** Both prefix and\n * suffix are empty and the separator literal(s) between placeholders\n * contain at least one whitespace character (e.g. `{source}: {content}`,\n * `{agent} {sessionId}`). A whitespace-containing separator produces\n * output that is visually indistinguishable from ordinary prose, so the\n * safe strategy is to require a **hard bracket/paren/angle delimiter** on\n * both sides of the reconstructed match. Prose almost never places\n * `[...]` / `(...)` / `<...>` around a phrase, so this yields clean\n * false-positive rejection.\n *\n * - **Placeholder-bounded with compact (non-whitespace) separator.** Both\n * prefix and suffix are empty and the separator literal(s) contain NO\n * whitespace (e.g. `{agent}:{sessionId}`, `{agent}/{sessionId}`).\n * `formatCitation` emits a compact token like `planner:main` with no\n * surrounding delimiters, so the bracket strategy cannot detect it.\n * Instead, the pattern requires that the entire token is bordered by\n * whitespace or a bracket/paren/angle on each side:\n *\n * `(?:(?<=[\\[\\(\\<])|(?<!\\S))[\\w.-]+<sep>[\\w.-]+(?:(?=[\\]\\)\\>])|(?!\\S))`\n *\n * This accepts `planner:main` when it appears standalone or inside a\n * bracket-wrapped token, and rejects `host:80` embedded inside a URL like\n * `http://host:80` because `host` is immediately preceded by `/`\n * (non-whitespace, non-bracket).\n *\n * - **All-placeholder case (no literals between placeholders either).** No\n * reliable regex can be built — a template like `{agent}{sessionId}`\n * contains no anchor characters. Returns `null`; {@link\n * hasCitationForTemplate} treats this as \"cannot detect\" and returns\n * false, falling back on explicit sentinel/format detection only for the\n * default `[Source: ...]` shape.\n *\n * Returns `null` when the template has no placeholders (fully-literal\n * citation, handled by the string-equality fast path in {@link\n * hasCitationForTemplate}) **or** when the template is entirely placeholder-\n * only with no literal content whatsoever.\n */\nfunction templateMatcher(template: string): RegExp | null {\n // Split around all {placeholder} tokens.\n const parts = template.split(PLACEHOLDER_REGEX);\n if (parts.length <= 1) return null;\n\n const prefix = parts[0] ?? \"\";\n const suffix = parts[parts.length - 1] ?? \"\";\n\n // Normal case: at least one literal frame on the outside.\n // Tighten the per-placeholder token so it cannot consume separator\n // characters and match strings that cross separator boundaries\n // (Finding 3 — Uru3).\n if (prefix.length > 0 || suffix.length > 0) {\n const escapedPrefix = escapeRegExp(prefix);\n const escapedSuffix = escapeRegExp(suffix);\n\n // Inner parts: literal separators that sit between adjacent placeholders.\n // For `[src:{agent}/{sessionId}@{date}]`, parts = [\"[src:\", \"/\", \"@\", \"]\"]\n // so innerParts = [\"/\", \"@\"].\n const innerParts = parts.slice(1, -1);\n\n // Collect only the non-word (punctuation/symbol) characters from each\n // inner separator so alphabetic separator text (unlikely but valid) does\n // not exclude letters from the per-placeholder token pattern.\n const nonWordSepChars = new Set<string>();\n for (const sep of innerParts) {\n for (const ch of sep) {\n if (!/\\w/.test(ch)) {\n nonWordSepChars.add(ch);\n }\n }\n }\n\n // All intermediate tokens (every placeholder except the last) use the\n // combined exclusion so they cannot cross placeholder boundaries.\n //\n // The LAST token is different: it is terminated by the literal suffix anchor\n // (e.g. `\\]`), so it does not need to exclude inner-separator characters.\n // Dropping that restriction lets placeholder values that legitimately contain\n // a separator character (e.g. an ISO-8601 timestamp `2026-04-10T14:25:07Z`\n // in template `[src:{agent}:{ts}]`) be recognised correctly instead of\n // producing false-negative misses that trigger duplicate citation injection.\n //\n // Only the LAST token is relaxed. Intermediate tokens keep the combined\n // exclusion so that cross-boundary false positives are still rejected\n // (e.g. `[src:foo/bar/extra@2026-04-11]` for `[src:{a}/{b}@{c}]`).\n const interToken = buildTokenPattern(nonWordSepChars);\n // Last token: terminated by suffix anchor — exclude only newlines.\n const lastToken = buildTokenPattern(new Set<string>());\n\n // Reconstruct the interior: interToken sep interToken sep ... sep lastToken\n // (or just lastToken when there are no inner separators at all).\n const middle =\n innerParts.length === 0\n ? lastToken\n : interToken +\n innerParts\n .slice(0, -1)\n .map((sep) => escapeRegExp(sep) + interToken)\n .join(\"\") +\n escapeRegExp(innerParts[innerParts.length - 1]!) +\n lastToken;\n\n const pattern = escapedPrefix + middle + escapedSuffix;\n return new RegExp(pattern, \"i\");\n }\n\n // Placeholder-bounded case: prefix and suffix are both empty.\n const middleLiterals = parts.slice(1, -1);\n const hasNonEmptyMiddle = middleLiterals.some((p) => p.length > 0);\n if (!hasNonEmptyMiddle) {\n // All-placeholder template with no literal content. Impossible to anchor\n // reliably without sentinel markers; signal the caller.\n return null;\n }\n\n // Identifier token: one or more word chars, dots, dashes, or colons.\n // Colons are included to allow timestamp values like \"10:30\" or session\n // keys like \"agent:planner:main\" inside compact placeholder-bounded\n // templates. URL-like fragments (`http://host:80`) are still rejected\n // because the lead anchor requires whitespace or a bracket immediately\n // before the first id-token group (`http` is preceded by `/`).\n const idToken = \"[\\\\w.:-]+\";\n const body =\n idToken +\n middleLiterals.map((lit) => escapeRegExp(lit) + idToken).join(\"\");\n\n const separatorText = middleLiterals.join(\"\");\n if (/\\s/.test(separatorText)) {\n // Separator contains whitespace: the emitted citation looks like ordinary\n // prose (e.g. `planner main`). Require a hard bracket/paren/angle\n // delimiter on both sides to prevent false matches on English text.\n const opener = \"[\\\\[\\\\(\\\\<]\";\n const closer = \"[\\\\]\\\\)\\\\>]\";\n return new RegExp(opener + body + closer, \"i\");\n }\n\n // Separator is compact (no whitespace): `formatCitation` emits a token like\n // `planner:main` without surrounding delimiters. The challenge is that the\n // same token shape also matches ordinary hyphenated or slashed prose words\n // (e.g. `long-term`, `docs/setup`), causing `hasCitationForTemplate` to\n // return true on uncited fact bodies and silently suppress citation injection\n // from `attachCitation`.\n //\n // Fix (Finding 1): tighten the trail anchor so a bare compact token is only\n // accepted when it sits at the very end of the string (possibly followed by\n // optional trailing whitespace or a newline). Since `attachCitation` always\n // appends the citation at the trimmed end of the fact body, a real citation\n // token will always appear at the tail. Prose like `\"long-term solution\"`\n // has `long-term` in the middle of the string (followed by ` solution`), so\n // the end-of-string anchor rejects it — no false positive, no silent drop.\n //\n // The lead anchor still accepts either a bracket opener or a whitespace\n // boundary (or start of string), so `\"Fact. planner:main\"` and standalone\n // `\"planner:main\"` are both detected after the first attachment pass.\n //\n // Bracket-wrapped form (e.g. `[planner:main]`) is also accepted via the\n // opener/closer pair — bracket still takes precedence over end-of-string.\n //\n // Example — why `http://host:80` does NOT match:\n // Trying to match `host:80`: the char before `h` is `/` (non-whitespace,\n // non-bracket), so `(?<=[\\[\\(\\<])` and `(?<!\\S)` both fail ⟹ no match.\n // Trying to match `http:...`: after `http:` the next chars are `//` which\n // are not `[\\w.-]+`, so the second id-token group fails ⟹ no match.\n const leadAnchor = \"(?:(?<=[\\\\[\\\\(\\\\<])|(?<!\\\\S))\";\n // Trail: either a bracket closer (for `[token]` shape) or end-of-string\n // optionally preceded by whitespace. The `(?!\\S)` is deliberately removed\n // so that a compact token in the MIDDLE of a sentence does not match.\n const trailAnchor = \"(?:(?=[\\\\]\\\\)\\\\>])|(?=\\\\s*$))\";\n return new RegExp(leadAnchor + body + trailAnchor, \"i\");\n}\n\n/**\n * Returns true if `text` already carries a citation produced by `template`\n * **or** by the default `[Source: ...]` format (for facts that were tagged\n * before a config change).\n *\n * Use this instead of {@link hasCitation} whenever the caller has access to\n * the configured `inlineSourceAttributionFormat`.\n *\n * All-placeholder templates such as `{agent}{sessionId}` have no literal\n * content to anchor on and therefore cannot be reliably detected without\n * dedicated sentinel markers. In that case the function returns `false` —\n * callers that need idempotent dedup for such templates should either adopt\n * a template with literal delimiters (recommended) or rely on the default\n * `[Source: ...]` marker detection which is always available via\n * {@link hasCitation}.\n */\nexport function hasCitationForTemplate(text: string, template: string): boolean {\n if (typeof text !== \"string\" || text.length === 0) return false;\n // Always accept the default format as a fallback so facts tagged before a\n // configuration change are not double-tagged on reprocessing.\n if (hasCitation(text)) return true;\n // If the configured template matches the default, we're done.\n //\n // Known limitation (Thread 2 — Codex P2): this fast path exits without\n // checking whether the content carries a citation from a DIFFERENT custom\n // template that was active before the config was changed back to the default.\n // Such a fact would be detected by `hasCitation` above only if the prior\n // custom template happened to match the default `[Source: ...]` pattern.\n // In practice, template changes mid-stream are rare, and the false-negative\n // (missing an old custom citation) produces a benign duplicate citation rather\n // than data loss. A full fix would require storing the citation template used\n // at write time in the frontmatter and checking that here.\n if (template === DEFAULT_CITATION_FORMAT) return false;\n\n // Fully-literal template (no placeholders): exact inclusion check.\n if (!PLACEHOLDER_REGEX.test(template)) {\n // Reset lastIndex because PLACEHOLDER_REGEX is declared with /g.\n PLACEHOLDER_REGEX.lastIndex = 0;\n return text.includes(template);\n }\n // Reset lastIndex after the .test() probe above.\n PLACEHOLDER_REGEX.lastIndex = 0;\n\n const matcher = templateMatcher(template);\n if (!matcher) {\n // All-placeholder template: cannot build a reliable matcher. See the\n // docstring — callers should not rely on dedup for this shape.\n return false;\n }\n return matcher.test(text);\n}\n\n/**\n * Return the LAST citation marker in `text` for the given template (or the\n * default `[Source: ...]` shape). `attachCitation` always appends at the\n * trimmed end, so the last occurrence is the most recently attached marker —\n * callers use this to lift a just-attached citation off a cited body and\n * re-attach it to a derived body (the merged-target commit path). Returns\n * null when the text carries no marker of this template (including\n * all-placeholder templates that cannot be matched reliably).\n */\nexport function lastCitationMarkerForTemplate(\n text: string,\n template: string = DEFAULT_CITATION_FORMAT,\n): string | null {\n if (typeof text !== \"string\" || text.length === 0) return null;\n let matcher: RegExp | null;\n if (template === DEFAULT_CITATION_FORMAT) {\n matcher = defaultCitationMatcher();\n } else if (!PLACEHOLDER_REGEX.test(template)) {\n // Fully-literal template: presence is exact inclusion (no placeholders\n // to widen the match).\n PLACEHOLDER_REGEX.lastIndex = 0;\n return text.includes(template) ? template : null;\n } else {\n PLACEHOLDER_REGEX.lastIndex = 0;\n matcher = templateMatcher(template);\n }\n if (!matcher) return null;\n const global = new RegExp(\n matcher.source,\n matcher.flags.includes(\"g\") ? matcher.flags : matcher.flags + \"g\",\n );\n let last: string | null = null;\n for (let match = global.exec(text); match !== null; match = global.exec(text)) {\n last = match[0];\n if (match[0].length === 0) global.lastIndex++;\n }\n return last;\n}\n\n/**\n * True when a template can be matched and stripped later. All-placeholder\n * templates such as `{agent}{sessionId}` have no literal anchors.\n */\nexport function citationTemplateIsDetectable(template: string): boolean {\n if (typeof template !== \"string\" || template.length === 0) return false;\n if (template === DEFAULT_CITATION_FORMAT) return true;\n PLACEHOLDER_REGEX.lastIndex = 0;\n if (!PLACEHOLDER_REGEX.test(template)) {\n PLACEHOLDER_REGEX.lastIndex = 0;\n return true;\n }\n PLACEHOLDER_REGEX.lastIndex = 0;\n return templateMatcher(template) !== null;\n}\n\n/**\n * Templates the merge path may lift, preserve, or strip. Longest\n * templates first so an overlapping custom marker beats an inner default\n * match; the current template wins equal-length ties. Undetectable\n * shapes are dropped so we never hash or attach a marker we cannot re-match.\n */\nexport function citationTemplatesToRecognize(\n primary: string | undefined,\n extra: readonly string[] = [],\n): string[] {\n const out: string[] = [];\n const add = (template: string | undefined): void => {\n if (typeof template !== \"string\" || template.length === 0) return;\n if (!citationTemplateIsDetectable(template)) return;\n if (!out.includes(template)) out.push(template);\n };\n add(primary);\n for (const template of extra) add(template);\n add(DEFAULT_CITATION_FORMAT);\n out.sort((a, b) => {\n if (b.length !== a.length) return b.length - a.length;\n if (a === primary && b !== primary) return -1;\n if (b === primary && a !== primary) return 1;\n return 0;\n });\n return out;\n}\n\n/**\n * Prior formats the caller still holds, if any. Absent or malformed\n * history is ignored — fail safe, do not invent templates.\n */\nexport function citationTemplatesForMerge(config: {\n inlineSourceAttributionFormat?: string;\n inlineSourceAttributionFormatHistory?: unknown;\n}): string[] {\n const raw = config.inlineSourceAttributionFormatHistory;\n const extra = Array.isArray(raw)\n ? raw.filter((value): value is string => typeof value === \"string\" && value.length > 0)\n : [];\n return citationTemplatesToRecognize(config.inlineSourceAttributionFormat, extra);\n}\n\nexport function lastRecognizedCitationMarker(\n text: string,\n templates: readonly string[],\n): string | null {\n for (const template of templates) {\n const marker = lastCitationMarkerForTemplate(text, template);\n if (marker) return marker;\n }\n return null;\n}\n\nexport function stripRecognizedCitations(text: string, templates: readonly string[]): string {\n let out = text;\n for (const template of templates) {\n out = stripCitationForTemplate(out, template);\n }\n return out;\n}\n\n/**\n * Attach an inline citation to fact text.\n *\n * If the text already has a citation — either the default `[Source: ...]`\n * marker or one produced by the configured template — it is returned unchanged.\n * Existing provenance is respected and never overwritten. Otherwise the\n * citation is appended to the trimmed text with a single space separator,\n * which keeps the marker visually adjacent to the fact body.\n */\nexport function attachCitation(\n text: string,\n ctx: CitationContext,\n template: string = DEFAULT_CITATION_FORMAT,\n): string {\n if (typeof text !== \"string\") return text as unknown as string;\n if (hasCitationForTemplate(text, template)) return text;\n const trimmedEnd = trimTrailingWhitespace(text);\n if (trimmedEnd.length === 0) return text;\n const citation = formatCitation(ctx, template);\n // Preserve any trailing newline that callers rely on for markdown rendering.\n const trailing = text.slice(trimmedEnd.length);\n return `${trimmedEnd} ${citation}${trailing}`;\n}\n\n/**\n * Parse a single inline citation from a piece of text. Returns the first\n * citation encountered or `null` when none is present. Malformed citations\n * do not throw — fields that cannot be parsed simply remain `undefined`.\n */\nexport function parseCitation(text: string): ParsedCitation | null {\n if (typeof text !== \"string\" || text.length === 0) return null;\n const matcher = defaultCitationMatcher();\n const match = matcher.exec(text);\n if (!match) return null;\n\n const body = match[1] ?? \"\";\n const raw = match[0] ?? \"\";\n const parsed: ParsedCitation = { raw };\n\n const fields = body\n .split(\",\")\n .map((segment) => segment.trim())\n .filter((segment) => segment.length > 0);\n\n for (const field of fields) {\n const eqIdx = field.indexOf(\"=\");\n if (eqIdx <= 0) continue;\n const key = field.slice(0, eqIdx).trim().toLowerCase();\n const value = field.slice(eqIdx + 1).trim();\n if (value.length === 0) continue;\n switch (key) {\n case \"agent\":\n parsed.agent = value;\n break;\n case \"session\":\n case \"sessionid\":\n parsed.session = value;\n break;\n case \"ts\":\n case \"timestamp\":\n parsed.ts = value;\n break;\n default:\n // Unknown fields are ignored defensively so human edits never crash.\n break;\n }\n }\n\n return parsed;\n}\n\n/**\n * Parse every citation embedded in the text. Always returns an array; empty\n * when none are present.\n */\nexport function parseAllCitations(text: string): ParsedCitation[] {\n if (typeof text !== \"string\" || text.length === 0) return [];\n const matcher = defaultCitationMatcher();\n const results: ParsedCitation[] = [];\n let match: RegExpExecArray | null;\n while ((match = matcher.exec(text)) !== null) {\n const parsed = parseCitation(match[0]);\n if (parsed) results.push(parsed);\n }\n return results;\n}\n\n/**\n * Remove all inline citations from a piece of text.\n *\n * Callers that want the raw fact body (for dedup hashing, display, or\n * comparison) should use this helper instead of hand-rolled regexes so the\n * whole codebase agrees on the citation syntax.\n *\n * Finding 2 fix: when the input contains no citation marker, the input is\n * returned byte-for-byte unchanged. When a citation IS removed, whitespace\n * normalization is applied only at each join seam (the single space between\n * the preceding text and where the citation was), rather than across the\n * entire string. This preserves markdown hard-break spacing, aligned text,\n * and code-like snippets in fact bodies that happen to carry a citation.\n *\n * Implementation: each citation match is replaced by its \"seam fix\" — the\n * content before the match has its trailing whitespace trimmed and then a\n * single space is appended if any text remains, collapsing only the gap\n * left by the removed marker. Whitespace elsewhere in the body is untouched.\n */\nexport function stripCitation(text: string): string {\n if (typeof text !== \"string\" || text.length === 0) return text;\n // Early exit: no citation marker present — return the input unchanged so\n // that callers never lose formatting fidelity on uncited strings.\n if (!hasCitation(text)) return text;\n\n // Walk through all citations and slice them out one by one so that we can\n // normalise ONLY the whitespace at each seam rather than the entire string.\n const matcher = defaultCitationMatcher();\n let result = \"\";\n let lastIndex = 0;\n\n let match: RegExpExecArray | null;\n while ((match = matcher.exec(text)) !== null) {\n // Text before this citation. Trim trailing spaces/tabs at the seam only.\n const before = text.slice(lastIndex, match.index).replace(/[ \\t]+$/, \"\");\n result += before;\n lastIndex = match.index + match[0].length;\n }\n\n // Append any trailing text after the last citation. Trim leading\n // spaces/tabs and trailing whitespace at the join seam.\n const after = text.slice(lastIndex).replace(/^[ \\t]+/, \"\");\n if (after.length > 0) {\n if (result.length > 0) result += \" \";\n result += after;\n }\n\n return result.trimEnd();\n}\n\n/**\n * Strip an inline citation from text using a specific template regex.\n *\n * This is the template-aware counterpart to {@link stripCitation}. When the\n * caller holds the configured `inlineSourceAttributionFormat`, use this\n * function to strip citations produced by that template — including custom\n * templates that differ from the default `[Source: ...]` pattern.\n *\n * Behaviour:\n * - If the text has a **default-format** citation, strips it first\n * (always safe).\n * - Then, if the result has a **custom-template** citation detected by\n * `hasCitationForTemplate`, builds the template regex and removes every\n * occurrence. BOTH passes run when a body carries both forms — a target\n * written under the default format can carry the default marker plus a\n * custom marker appended after a config change; returning after the\n * default pass alone left the custom marker inside hash inputs (#2330).\n * - Fully-literal templates (no placeholders) are stripped by exact match\n * of the template text, the same inclusion check `hasCitationForTemplate`\n * uses.\n * - All-placeholder templates (no literal prefix/suffix/separator) cannot\n * produce a reliable matcher. `hasCitationForTemplate` already returns\n * `false` for such templates, so this function never attempts to strip an\n * undetectable citation. The text is returned unchanged when no citation\n * is detected.\n * - If no citation is detected for the given template, returns the text\n * unchanged.\n *\n * @returns The stripped text (or the original text when no citation is found).\n */\nexport function stripCitationForTemplate(\n text: string,\n template: string,\n): string {\n if (typeof text !== \"string\" || text.length === 0) return text;\n\n // First pass: the default-format marker, if any. A second pass below still\n // runs — a body can carry the default marker AND the custom template's\n // marker, and canonicalization must remove every recognized form.\n const afterDefault = hasCitation(text) ? stripCitation(text) : text;\n\n if (!hasCitationForTemplate(afterDefault, template)) return afterDefault;\n\n PLACEHOLDER_REGEX.lastIndex = 0;\n if (!PLACEHOLDER_REGEX.test(template)) {\n PLACEHOLDER_REGEX.lastIndex = 0;\n return stripExactLiteralCitation(afterDefault, template);\n }\n PLACEHOLDER_REGEX.lastIndex = 0;\n\n // Build the template matcher. hasCitationForTemplate already returned true,\n // which means templateMatcher produced a non-null result. The null branch\n // here is a defensive fallback only — the default pass already ran.\n const matcher = templateMatcher(template);\n if (!matcher) return afterDefault;\n\n // The matcher regex was built without the global flag; add it for exec loop.\n const globalMatcher = new RegExp(\n matcher.source,\n matcher.flags.includes(\"g\") ? matcher.flags : matcher.flags + \"g\",\n );\n let result = \"\";\n let lastIndex = 0;\n let match: RegExpExecArray | null;\n\n while ((match = globalMatcher.exec(afterDefault)) !== null) {\n const matchEnd = match.index + match[0].length;\n const enclosure = enclosingDelimiterRange(afterDefault, match.index, matchEnd);\n const removalStart = enclosure?.start ?? match.index;\n const removalEnd = enclosure?.end ?? matchEnd;\n const before = afterDefault.slice(lastIndex, removalStart).replace(/[ \\t]+$/, \"\");\n result += before;\n lastIndex = removalEnd;\n // Guard against zero-width matches causing an infinite loop.\n if (match[0].length === 0) {\n globalMatcher.lastIndex++;\n }\n }\n\n const after = afterDefault.slice(lastIndex).replace(/^[ \\t]+/, \"\");\n if (after.length > 0) {\n if (result.length > 0) result += \" \";\n result += after;\n }\n\n return result.trimEnd();\n}\n\nfunction stripExactLiteralCitation(text: string, marker: string): string {\n if (marker.length === 0) return text;\n let result = \"\";\n let lastIndex = 0;\n let idx = text.indexOf(marker);\n if (idx === -1) return text;\n while (idx !== -1) {\n const before = text.slice(lastIndex, idx).replace(/[ \\t]+$/, \"\");\n result += before;\n lastIndex = idx + marker.length;\n idx = text.indexOf(marker, lastIndex);\n }\n const after = text.slice(lastIndex).replace(/^[ \\t]+/, \"\");\n if (after.length > 0) {\n if (result.length > 0) result += \" \";\n result += after;\n }\n return result.trimEnd();\n}\n\nfunction enclosingDelimiterRange(\n text: string,\n start: number,\n end: number,\n): { start: number; end: number } | undefined {\n if (start <= 0 || end >= text.length) return undefined;\n const opener = text[start - 1];\n const closer = text[end];\n if (\n (opener === \"[\" && closer === \"]\") ||\n (opener === \"(\" && closer === \")\") ||\n (opener === \"<\" && closer === \">\")\n ) {\n return { start: start - 1, end: end + 1 };\n }\n return undefined;\n}\n"],"mappings":";AAkCO,IAAM,0BACX;AAGK,IAAM,mBAAmB;AAkChC,SAAS,yBAAiC;AAKxC,SAAO;AACT;AAOA,SAAS,uBAAuB,MAAsB;AACpD,MAAI,MAAM,KAAK;AACf,SAAO,MAAM,KAAK,MAAM,KAAK,KAAK,MAAM,CAAC,CAAE,EAAG;AAC9C,SAAO,KAAK,MAAM,GAAG,GAAG;AAC1B;AAMO,SAAS,gBAAgB,SAAiD;AAC/E,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,UAAU,QAAQ,KAAK;AAC7B,MAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,QAAM,QAAQ,QAAQ,MAAM,GAAG,EAAE,OAAO,CAAC,MAAM,EAAE,SAAS,C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AAO;AACvB,SAAO,QAAQ,IAAI;AACjB,UAAM,SAAS,KAAK,MAAM,WAAW,GAAG,EAAE,QAAQ,WAAW,EAAE;AAC/D,cAAU;AACV,gBAAY,MAAM,OAAO;AACzB,UAAM,KAAK,QAAQ,QAAQ,SAAS;AAAA,EACtC;AACA,QAAM,QAAQ,KAAK,MAAM,SAAS,EAAE,QAAQ,WAAW,EAAE;AACzD,MAAI,MAAM,SAAS,GAAG;AACpB,QAAI,OAAO,SAAS,EAAG,WAAU;AACjC,cAAU;AAAA,EACZ;AACA,SAAO,OAAO,QAAQ;AACxB;AAEA,SAAS,wBACP,MACA,OACA,KAC4C;AAC5C,MAAI,SAAS,KAAK,OAAO,KAAK,OAAQ,QAAO;AAC7C,QAAM,SAAS,KAAK,QAAQ,CAAC;AAC7B,QAAM,SAAS,KAAK,GAAG;AACvB,MACG,WAAW,OAAO,WAAW,OAC7B,WAAW,OAAO,WAAW,OAC7B,WAAW,OAAO,WAAW,KAC9B;AACA,WAAO,EAAE,OAAO,QAAQ,GAAG,KAAK,MAAM,EAAE;AAAA,EAC1C;AACA,SAAO;AACT;","names":[]}
@@ -4,7 +4,7 @@ import {
4
4
  import {
5
5
  computeCorpusWatermarks,
6
6
  resolveCorpusNamespaceRoots
7
- } from "./chunk-KDLOKVX7.js";
7
+ } from "./chunk-AOMUIF3R.js";
8
8
 
9
9
  // src/operator-doctor-corpus.ts
10
10
  var DIGEST_PREFIX_LENGTH = 12;
@@ -78,4 +78,4 @@ export {
78
78
  corpusWatermarksFromCheck,
79
79
  summarizeCorpusAndReplica
80
80
  };
81
- //# sourceMappingURL=chunk-7F47R4H4.js.map
81
+ //# sourceMappingURL=chunk-LZAJONO5.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  defineOperation
3
- } from "./chunk-LXMZM7LM.js";
3
+ } from "./chunk-NKDQXDFL.js";
4
4
  import {
5
5
  EngramAccessInputError
6
6
  } from "./chunk-2Z24E5W2.js";
@@ -92,4 +92,4 @@ defineOperation({
92
92
  };
93
93
  }
94
94
  });
95
- //# sourceMappingURL=chunk-2WFOVXVJ.js.map
95
+ //# sourceMappingURL=chunk-M7ECD3KN.js.map
@@ -7,7 +7,7 @@ import {
7
7
  } from "./chunk-PIWFNPQT.js";
8
8
  import {
9
9
  StorageManager
10
- } from "./chunk-GMU7MAHS.js";
10
+ } from "./chunk-IAT5WFEU.js";
11
11
  import {
12
12
  projectProceduresToSkills
13
13
  } from "./chunk-236PXYG7.js";
@@ -134,4 +134,4 @@ export {
134
134
  runCodexMaterialize,
135
135
  runPostConsolidationMaterialize
136
136
  };
137
- //# sourceMappingURL=chunk-KORQWGUA.js.map
137
+ //# sourceMappingURL=chunk-MDYZCPNQ.js.map
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  hasMemoryData
3
- } from "./chunk-GKKLI23D.js";
3
+ } from "./chunk-WCQ7L54B.js";
4
4
  import {
5
5
  resolveNamespaceStorageRoot
6
- } from "./chunk-3YQ7VLP3.js";
6
+ } from "./chunk-WMTYEQO5.js";
7
7
  import {
8
8
  getConfiguredNamespaces
9
9
  } from "./chunk-OQQXGYMX.js";
@@ -724,4 +724,4 @@ export {
724
724
  runNamespaceMaintenancePlan,
725
725
  runNamespaceMaintenanceBatchPlan
726
726
  };
727
- //# sourceMappingURL=chunk-IWHNT35B.js.map
727
+ //# sourceMappingURL=chunk-N6I257OM.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  gatewayTaskChainOptions
3
- } from "./chunk-TRTLWUDD.js";
3
+ } from "./chunk-ZTHGFTMW.js";
4
4
  import {
5
5
  isAbortError,
6
6
  throwIfAborted
@@ -70,4 +70,4 @@ export {
70
70
  DEEP_RECALL_POLICY_SYSTEM_PROMPT,
71
71
  callDeepRecallPolicyLlm
72
72
  };
73
- //# sourceMappingURL=chunk-YR5QT4SR.js.map
73
+ //# sourceMappingURL=chunk-NAFPHFDM.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  parseEntityFile
3
- } from "./chunk-GMU7MAHS.js";
3
+ } from "./chunk-IAT5WFEU.js";
4
4
  import {
5
5
  inferMemoryStatus
6
6
  } from "./chunk-7RJUVTVF.js";
@@ -253,4 +253,4 @@ export {
253
253
  WHO_KNOWS_MCP_TOOLS,
254
254
  handleWhoKnowsHttpQuery
255
255
  };
256
- //# sourceMappingURL=chunk-D7UUB33A.js.map
256
+ //# sourceMappingURL=chunk-NGAFYIHQ.js.map